harperdb 4.3.21 → 4.4.0-alpha.1

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.
Files changed (32) hide show
  1. package/README.md +1 -1
  2. package/bin/harperdb.js +85 -72
  3. package/bin/lite.js +32 -22
  4. package/config/yaml/defaultConfig.yaml +9 -41
  5. package/config/yaml/defaultNatsConfig.yaml +36 -0
  6. package/json/systemSchema.json +32 -79
  7. package/launchServiceScripts/launchInstallNATSServer.js +4 -4
  8. package/launchServiceScripts/launchNatsIngestService.js +32 -22
  9. package/launchServiceScripts/launchNatsReplyService.js +32 -22
  10. package/launchServiceScripts/launchUpdateNodes4-0-0.js +32 -22
  11. package/npm-shrinkwrap.json +634 -312
  12. package/package.json +17 -15
  13. package/resources/DatabaseTransaction.d.ts +1 -0
  14. package/resources/RecordEncoder.d.ts +3 -1
  15. package/resources/Resource.d.ts +8 -1
  16. package/resources/ResourceInterface.d.ts +7 -3
  17. package/resources/Resources.d.ts +5 -4
  18. package/resources/Table.d.ts +47 -16
  19. package/resources/auditStore.d.ts +45 -1
  20. package/resources/databases.d.ts +54 -17
  21. package/resources/search.d.ts +6 -0
  22. package/resources/transactionBroadcast.d.ts +2 -1
  23. package/server/Server.d.ts +1 -1
  24. package/server/jobs/jobProcess.js +32 -22
  25. package/server/serverHelpers/Headers.d.ts +8 -0
  26. package/server/threads/threadServer.js +32 -22
  27. package/studio/build-local/asset-manifest.json +2 -2
  28. package/studio/build-local/index.html +1 -1
  29. package/studio/build-local/static/js/main.4fd117ad.js +2 -0
  30. package/utility/scripts/restartHdb.js +32 -22
  31. package/studio/build-local/static/js/main.a22f6951.js +0 -2
  32. /package/studio/build-local/static/js/{main.a22f6951.js.LICENSE.txt → main.4fd117ad.js.LICENSE.txt} +0 -0
@@ -1,32 +1,42 @@
1
- "use strict";var GG=Object.create;var ac=Object.defineProperty;var FG=Object.getOwnPropertyDescriptor;var qG=Object.getOwnPropertyNames;var kG=Object.getPrototypeOf,VG=Object.prototype.hasOwnProperty;var a=(e,t)=>ac(e,"name",{value:t,configurable:!0});var Re=(e,t)=>()=>(e&&(t=e(e=0)),t);var g=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),qe=(e,t)=>{for(var r in t)ac(e,r,{get:t[r],enumerable:!0})},WA=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of qG(t))!VG.call(e,s)&&s!==r&&ac(e,s,{get:()=>t[s],enumerable:!(n=FG(t,s))||n.enumerable});return e};var B=(e,t,r)=>(r=e!=null?GG(kG(e)):{},WA(t||!e||!e.__esModule?ac(r,"default",{value:e,enumerable:!0}):r,e)),ie=e=>WA(ac({},"__esModule",{value:!0}),e);var JA=g((Ooe,zA)=>{var $G=require("fast-glob"),{statSync:Th,existsSync:gh,readFileSync:YG,writeFileSync:KG}=require("fs"),{spawnSync:WG,spawn:QG,execFileSync:Aoe}=require("child_process"),{isMainThread:zG}=require("worker_threads"),{join:Js,relative:QA}=require("path"),{PACKAGE_ROOT:On}=U(),{tmpdir:JG,platform:XG}=require("os");require("source-map-support").install();var jG=["resources","server","dataLayer","components"],cc="ts-build",Rh,ZG=__filename.endsWith("tsBuild.js");if(ZG){if(zG){let r;try{Th(Js(On,cc)),r=!0}catch{}if(r)for(let n of $G.sync(jG.map(s=>s+"/**/*.ts"),{cwd:On})){let s=0,i=0;try{s=Th(Js(On,n)).mtimeMs-5e3,i=Th(Js(On,cc,n.replace(/.ts$/,".js"))).mtimeMs}catch{}if(s>i){console.warn(`TypeScript ${n} is not compiled`+(i?` (TS source file was modified at ${new Date(s)} and compiled file at ${new Date(i)})`:"")+", consider enabling auto-compilation of TypeScript in your IDE), compiling now."),Rh=!0;break}}else console.log("TypeScript modules are not compiled, compiling now"),Rh=!0;if(Rh){let n=Js(On,"node_modules/.bin/tsc");XG()==="win32"&&(n+=".cmd");let s=WG(n,{cwd:On});if(s.stdout?.length&&console.log(s.stdout.toString()),s.stderr?.length&&console.log(s.stderr.toString()),r){let i=Js(JG(),"harperdb-tsc.pid"),o;if(gh(i))try{process.kill(+YG(i,{encoding:"utf8"}),0),o=!0}catch{}if(!o){console.log("starting tsc background process");let c=QG(n,["--watch"],{cwd:On,detached:!0,stdio:"ignore"});KG(i,c.pid.toString()),c.unref()}}}}let e=zA.constructor,t=e._findPath;e._findPath=function(r,n,s){if(r.startsWith(".")&&!s&&n.length===1&&n[0].startsWith(On)&&!n[0].includes("node_modules")){let i=QA(On,n[0]),o;i.startsWith(cc)?o=Js(On,QA(cc,i)):o=Js(On,cc,i);let c=Js(o,r),l=c+".js";if(gh(l))return l;if(c.includes(".")&&gh(c))return c}return t(r,n,s)}}});var U=g((Noe,uO)=>{"use strict";var on=require("path"),eF=require("fs"),{relative:boe,join:yoe}=on,{existsSync:tF}=eF;function rF(){let e=__dirname;for(;!tF(on.join(e,"package.json"));){let t=on.dirname(e);if(t===e)throw new Error("Could not find package root");e=t}return e}a(rF,"getHDBPackageRoot");var Xs=rF(),XA="js",Xu=XA,nF="harperdb-config.yaml",sF="defaultConfig.yaml",iF="hdb",jA=`harperdb.${Xu}`,ZA=`customFunctionsServer.${Xu}`,oF=`restartHdb.${Xu}`,Oh="HarperDB",Ju="Custom Functions",ju="Clustering Hub",Zu="Clustering Leaf",aF="Clustering Ingest Service",cF="Clustering Reply Service",lF="foreground.pid",uF="hdb.pid",_F="data",dF={HDB:Oh,CLUSTERING_HUB:ju,CLUSTERING_LEAF:Zu,CLUSTERING_INGEST_SERVICE:aF,CLUSTERING_REPLY_SERVICE:cF,CUSTOM_FUNCTIONS:Ju,RESTART_HDB:"Restart HDB",INSTALL:"Install",RUN:"Run",STOP:"Stop",UPGRADE:"Upgrade",REGISTER:"Register",JOB:"Job",CLUSTERING_UPGRADE_4_0_0:"Upgrade-4-0-0"},fF={HDB:"hdb.log",INSTALL:"install.log",CLUSTERING_HUB:"clustering_hub.log",CLUSTERING_LEAF:"clustering_leaf.log"},EF={NOTIFY:"notify",FATAL:"fatal",ERROR:"error",WARN:"warn",INFO:"info",DEBUG:"debug",TRACE:"trace"},hF={harperdb:Oh,"clustering hub":ju,"clustering leaf":Zu,"custom functions":Ju,custom_functions:Ju,clustering:"clustering","clustering config":"clustering config",clustering_config:"clustering_config",http_workers:"http_workers"},mF={CLUSTERING_HUB_PROC_DESCRIPTOR:ju,CLUSTERING_LEAF_PROC_DESCRIPTOR:Zu},Ah={HDB:on.join(Xs,"server/harperdb"),CUSTOM_FUNCTIONS:on.join(Xs,"server/customFunctions"),CLUSTERING_HUB:on.join(Xs,"server/nats"),CLUSTERING_LEAF:on.join(Xs,"server/nats")},pF={HDB:on.join(Ah.HDB,jA),CUSTOM_FUNCTIONS:on.join(Ah.CUSTOM_FUNCTIONS,ZA)},SF={MAIN:"bin/harperdb.js",NATS_INGEST_SERVICE:on.join(Xs,"launchServiceScripts/launchNatsIngestService.js"),NATS_REPLY_SERVICE:on.join(Xs,"launchServiceScripts/launchNatsReplyService.js"),NODES_UPGRADE_4_0_0:on.join(Xs,"launchServiceScripts/launchUpdateNodes4-0-0.js")},TF={SUPER_USER:"super_user",CLUSTER_USER:"cluster_user"},eO="support@harperdb.io",gF="customer-success@harperdb.io",tO=1,RF=4141,rO="https://harperdbhelp.zendesk.com/hc/en-us/requests/new",AF="https://www.harperdb.io/product",OF=`For support, please submit a request at ${rO} or contact ${eO}`,nO=`For license support, please contact ${gF}`,bF="None of the specified records were found.",yF="hash attribute not found",NF=`Your current license only supports ${tO} role. ${nO}`,IF="Your current license only supports 3 connections to a node.",wF="127.0.0.1",CF=1,DF=/^\.$/,LF=/^\.\.$/,MF="U+002E",PF=/\//g,UF="U+002F",vF=/U\+002F/g,BF=/^U\+002E$/,HF=/^U\+002EU\+002E$/,xF="d",GF=999999,FF="*",qF="--max-old-space-size=",kF="system",VF="__hdb_hash",$F=".harperdb",YF=".hdb",KF="keys",WF="hdb_boot_properties.file",QF=".updateConfig.json",zF="SIGTSTP",JF=24,XF=6e4,jF=448,ZF="blob",eq="trash",tq="database",rq="schema",nq="transactions",sq=".count",iq="id",oq="PROCESS_NAME",sO={SETTINGS_PATH_KEY:"settings_path"},iO=require("lodash"),aq={TC_AGREEMENT:"TC_AGREEMENT",CLUSTERING_USER:"CLUSTERING_USER",CLUSTERING_PASSWORD:"CLUSTERING_PASSWORD",HDB_ADMIN_USERNAME:"HDB_ADMIN_USERNAME",HDB_ADMIN_PASSWORD:"HDB_ADMIN_PASSWORD",OPERATIONSAPI_ROOT:"OPERATIONSAPI_ROOT",ROOTPATH:"ROOTPATH",OPERATIONSAPI_NETWORK_PORT:"OPERATIONSAPI_NETWORK_PORT",CLUSTERING_NODENAME:"CLUSTERING_NODENAME",CLUSTERING_ENABLED:"CLUSTERING_ENABLED",HDB_CONFIG:"HDB_CONFIG",OPERATIONSAPI_NETWORK_SECUREPORT:"OPERATIONSAPI_NETWORK_SECUREPORT",CLUSTERING_PORT:"CLUSTERING_PORT",HDB_ROOT:"HDB_ROOT",SERVER_PORT:"SERVER_PORT",NODE_NAME:"NODE_NAME",CLUSTERING:"CLUSTERING"},cq={HDB_PATH_KEY:"HDB_INTERNAL_PATH",HDB_AUTH_HEADER:"hdb_auth_header",HDB_USER_DATA_KEY:"hdb_user",CHUNK_SIZE:1e3,MAX_CHARACTER_SIZE:250},lq={DATA_VERSION:"data_version",UPGRADE_VERSION:"upgrade_version"},uq={JOB_TABLE_NAME:"hdb_job",NODE_TABLE_NAME:"hdb_nodes",ATTRIBUTE_TABLE_NAME:"hdb_attribute",LICENSE_TABLE_NAME:"hdb_license",ROLE_TABLE_NAME:"hdb_role",SCHEMA_TABLE_NAME:"hdb_schema",TABLE_TABLE_NAME:"hdb_table",USER_TABLE_NAME:"hdb_user",INFO_TABLE_NAME:"hdb_info"},_q={JOB_TABLE_HASH_ATTRIBUTE:"id",NODE_TABLE_HASH_ATTRIBUTE:"name",ATTRIBUTE_TABLE_HASH_ATTRIBUTE:"id",LICENSE_TABLE_HASH_ATTRIBUTE:"license_key",ROLE_TABLE_HASH_ATTRIBUTE:"id",SCHEMA_TABLE_HASH_ATTRIBUTE:"name",TABLE_TABLE_HASH_ATTRIBUTE:"id",USER_TABLE_HASH_ATTRIBUTE:"username",INFO_TABLE_ATTRIBUTE:"info_id"},Pr="hdb_internal:",dq={CREATE_SCHEMA:Pr+"create_schema",CREATE_TABLE:Pr+"create_table",CREATE_ATTRIBUTE:Pr+"create_attribute",ADD_USER:Pr+"add_user",ALTER_USER:Pr+"alter_user",DROP_USER:Pr+"drop_user",HDB_NODES:Pr+"hdb_nodes",HDB_USERS:Pr+"hdb_users",HDB_WORKERS:Pr+"hdb_workers",CATCHUP:Pr+"catchup",SCHEMA_CATCHUP:Pr+"schema_catchup",WORKER_ROOM:Pr+"cluster_workers"},fq={ATTR_ATTRIBUTE_KEY:"attribute",ATTR_CREATEDDATE_KEY:"createddate",ATTR_HASH_ATTRIBUTE_KEY:"hash_attribute",ATTR_ID_KEY:"id",ATTR_NAME_KEY:"name",ATTR_PASSWORD_KEY:"password",ATTR_RESIDENCE_KEY:"residence",ATTR_ROLE_KEY:"role",ATTR_SCHEMA_KEY:"schema",ATTR_SCHEMA_TABLE_KEY:"schema_table",ATTR_TABLE_KEY:"table",ATTR_USERNAME_KEY:"username"},Eq="060493.ks",hq=".license",mq={CREATED:"CREATED",IN_PROGRESS:"IN_PROGRESS",COMPLETE:"COMPLETE",ERROR:"ERROR"},Z={INSERT:"insert",UPDATE:"update",UPSERT:"upsert",SEARCH_BY_CONDITIONS:"search_by_conditions",SEARCH_BY_HASH:"search_by_hash",SEARCH_BY_ID:"search_by_id",SEARCH_BY_VALUE:"search_by_value",SEARCH:"search",SQL:"sql",CSV_DATA_LOAD:"csv_data_load",CSV_FILE_LOAD:"csv_file_load",CSV_URL_LOAD:"csv_url_load",CREATE_SCHEMA:"create_schema",CREATE_DATABASE:"create_database",CREATE_TABLE:"create_table",CREATE_ATTRIBUTE:"create_attribute",DROP_SCHEMA:"drop_schema",DROP_DATABASE:"drop_database",DROP_TABLE:"drop_table",DESCRIBE_SCHEMA:"describe_schema",DESCRIBE_DATABASE:"describe_database",DESCRIBE_TABLE:"describe_table",DESCRIBE_ALL:"describe_all",DELETE:"delete",ADD_USER:"add_user",ALTER_USER:"alter_user",DROP_USER:"drop_user",LIST_USERS:"list_users",LIST_ROLES:"list_roles",ADD_ROLE:"add_role",ALTER_ROLE:"alter_role",DROP_ROLE:"drop_role",USER_INFO:"user_info",READ_LOG:"read_log",ADD_NODE:"add_node",UPDATE_NODE:"update_node",SET_NODE_REPLICATION:"set_node_replication",EXPORT_TO_S3:"export_to_s3",IMPORT_FROM_S3:"import_from_s3",DELETE_FILES_BEFORE:"delete_files_before",DELETE_RECORDS_BEFORE:"delete_records_before",EXPORT_LOCAL:"export_local",SEARCH_JOBS_BY_START_DATE:"search_jobs_by_start_date",GET_JOB:"get_job",DELETE_JOB:"delete_job",UPDATE_JOB:"update_job",GET_FINGERPRINT:"get_fingerprint",SET_LICENSE:"set_license",GET_REGISTRATION_INFO:"registration_info",CONFIGURE_CLUSTER:"configure_cluster",SET_CONFIGURATION:"set_configuration",CLUSTER_STATUS:"cluster_status",CLUSTER_NETWORK:"cluster_network",DROP_ATTRIBUTE:"drop_attribute",REMOVE_NODE:"remove_node",RESTART:"restart",RESTART_SERVICE:"restart_service",CATCHUP:"catchup",SYSTEM_INFORMATION:"system_information",DELETE_AUDIT_LOGS_BEFORE:"delete_audit_logs_before",READ_AUDIT_LOG:"read_audit_log",CREATE_AUTHENTICATION_TOKENS:"create_authentication_tokens",LOGIN:"login",LOGOUT:"logout",REFRESH_OPERATION_TOKEN:"refresh_operation_token",GET_CONFIGURATION:"get_configuration",CUSTOM_FUNCTIONS_STATUS:"custom_functions_status",GET_CUSTOM_FUNCTIONS:"get_custom_functions",GET_CUSTOM_FUNCTION:"get_custom_function",SET_CUSTOM_FUNCTION:"set_custom_function",GET_COMPONENTS:"get_components",GET_COMPONENT_FILE:"get_component_file",SET_COMPONENT_FILE:"set_component_file",DROP_COMPONENT:"drop_component",DROP_CUSTOM_FUNCTION:"drop_custom_function",ADD_CUSTOM_FUNCTION_PROJECT:"add_custom_function_project",ADD_COMPONENT:"add_component",DROP_CUSTOM_FUNCTION_PROJECT:"drop_custom_function_project",PACKAGE_CUSTOM_FUNCTION_PROJECT:"package_custom_function_project",DEPLOY_CUSTOM_FUNCTION_PROJECT:"deploy_custom_function_project",PACKAGE_COMPONENT:"package_component",DEPLOY_COMPONENT:"deploy_component",CLUSTER_SET_ROUTES:"cluster_set_routes",CLUSTER_DELETE_ROUTES:"cluster_delete_routes",CLUSTER_GET_ROUTES:"cluster_get_routes",READ_TRANSACTION_LOG:"read_transaction_log",DELETE_TRANSACTION_LOGS_BEFORE:"delete_transaction_logs_before",INSTALL_NODE_MODULES:"install_node_modules",AUDIT_NODE_MODULES:"audit_node_modules",PURGE_STREAM:"purge_stream",GET_BACKUP:"get_backup"},pq={CSV:".csv",JSON:".json"},Sq={AWS_ACCESS_KEY:"aws_access_key_id",AWS_SECRET:"aws_secret_access_key",AWS_BUCKET:"bucket",AWS_FILE_KEY:"key",REGION:"region"},Tq={SELECT:"select",INSERT:"insert",UPDATE:"update",DELETE:"delete"},lc={};lc[Z.INSERT]=Z.INSERT;lc[Z.UPDATE]=Z.UPDATE;lc[Z.UPSERT]=Z.UPSERT;lc[Z.DELETE]=Z.DELETE;var He=Object.create(null);He[Z.DESCRIBE_ALL]=Z.DESCRIBE_ALL;He[Z.DESCRIBE_TABLE]=Z.DESCRIBE_TABLE;He[Z.DESCRIBE_SCHEMA]=Z.DESCRIBE_SCHEMA;He[Z.READ_LOG]=Z.READ_LOG;He[Z.ADD_NODE]=Z.ADD_NODE;He[Z.LIST_USERS]=Z.LIST_USERS;He[Z.LIST_ROLES]=Z.LIST_ROLES;He[Z.USER_INFO]=Z.USER_INFO;He[Z.SQL]=Z.SQL;He[Z.GET_JOB]=Z.GET_JOB;He[Z.SEARCH_JOBS_BY_START_DATE]=Z.SEARCH_JOBS_BY_START_DATE;He[Z.DELETE_FILES_BEFORE]=Z.DELETE_FILES_BEFORE;He[Z.EXPORT_LOCAL]=Z.EXPORT_LOCAL;He[Z.EXPORT_TO_S3]=Z.EXPORT_TO_S3;He[Z.CLUSTER_STATUS]=Z.CLUSTER_STATUS;He[Z.REMOVE_NODE]=Z.REMOVE_NODE;He[Z.RESTART]=Z.RESTART;He[Z.CUSTOM_FUNCTIONS_STATUS]=Z.CUSTOM_FUNCTIONS_STATUS;He[Z.GET_CUSTOM_FUNCTIONS]=Z.GET_CUSTOM_FUNCTIONS;He[Z.GET_CUSTOM_FUNCTION]=Z.GET_CUSTOM_FUNCTION;He[Z.SET_CUSTOM_FUNCTION]=Z.SET_CUSTOM_FUNCTION;He[Z.DROP_CUSTOM_FUNCTION]=Z.DROP_CUSTOM_FUNCTION;He[Z.ADD_CUSTOM_FUNCTION_PROJECT]=Z.ADD_CUSTOM_FUNCTION_PROJECT;He[Z.DROP_CUSTOM_FUNCTION_PROJECT]=Z.DROP_CUSTOM_FUNCTION_PROJECT;He[Z.PACKAGE_CUSTOM_FUNCTION_PROJECT]=Z.PACKAGE_CUSTOM_FUNCTION_PROJECT;He[Z.DEPLOY_CUSTOM_FUNCTION_PROJECT]=Z.DEPLOY_CUSTOM_FUNCTION_PROJECT;var gq={DEV:"dev",RUN:"run",START:"start",INSTALL:"install",REGISTER:"register",STOP:"stop",RESTART:"restart",VERSION:"version",UPGRADE:"upgrade",HELP:"help",STATUS:"status",OPERATION:"operation",RENEWCERTS:"renew-certs",COPYDB:"copy-db"},Rq={point:"point",lineString:"lineString",multiLineString:"multiLineString",multiPoint:"multiPoint",multiPolygon:"multiPolygon",polygon:"polygon"},oO={HDB_ROOT_KEY:"HDB_ROOT",SERVER_PORT_KEY:"SERVER_PORT",CERT_KEY:"CERTIFICATE",PRIVATE_KEY_KEY:"PRIVATE_KEY",HTTP_SECURE_ENABLED_KEY:"HTTPS_ON",CORS_ENABLED_KEY:"CORS_ON",CORS_WHITELIST_KEY:"CORS_WHITELIST",LOG_LEVEL_KEY:"LOG_LEVEL",LOGGER_KEY:"LOGGER",LOG_PATH_KEY:"LOG_PATH",LOG_ROTATE:"LOG_ROTATE",LOG_ROTATE_MAX_SIZE:"LOG_ROTATE_MAX_SIZE",LOG_ROTATE_RETAIN:"LOG_ROTATE_RETAIN",LOG_ROTATE_COMPRESS:"LOG_ROTATE_COMPRESS",LOG_ROTATE_DATE_FORMAT:"LOG_ROTATE_DATE_FORMAT",LOG_ROTATE_ROTATE_MODULE:"LOG_ROTATE_ROTATE_MODULE",LOG_ROTATE_WORKER_INTERVAL:"LOG_ROTATE_WORKER_INTERVAL",LOG_ROTATE_ROTATE_INTERVAL:"LOG_ROTATE_ROTATE_INTERVAL",LOG_ROTATE_TIMEZONE:"LOG_ROTATE_TIMEZONE",LOG_DAILY_ROTATE_KEY:"LOG_DAILY_ROTATE",LOG_MAX_DAILY_FILES_KEY:"LOG_MAX_DAILY_FILES",PROPS_ENV_KEY:"NODE_ENV",SETTINGS_PATH_KEY:"settings_path",CLUSTERING_PORT_KEY:"CLUSTERING_PORT",CLUSTERING_NODE_NAME_KEY:"NODE_NAME",CLUSTERING_ENABLED_KEY:"CLUSTERING",ALLOW_SELF_SIGNED_SSL_CERTS:"ALLOW_SELF_SIGNED_SSL_CERTS",MAX_HDB_PROCESSES:"MAX_HDB_PROCESSES",INSTALL_USER:"install_user",CLUSTERING_USER_KEY:"CLUSTERING_USER",MAX_CLUSTERING_PROCESSES:"MAX_CLUSTERING_PROCESSES",SERVER_TIMEOUT_KEY:"SERVER_TIMEOUT_MS",SERVER_KEEP_ALIVE_TIMEOUT_KEY:"SERVER_KEEP_ALIVE_TIMEOUT",SERVER_HEADERS_TIMEOUT_KEY:"SERVER_HEADERS_TIMEOUT",DISABLE_TRANSACTION_LOG_KEY:"DISABLE_TRANSACTION_LOG",OPERATION_TOKEN_TIMEOUT_KEY:"OPERATION_TOKEN_TIMEOUT",REFRESH_TOKEN_TIMEOUT_KEY:"REFRESH_TOKEN_TIMEOUT",CUSTOM_FUNCTIONS_ENABLED_KEY:"CUSTOM_FUNCTIONS",CUSTOM_FUNCTIONS_PORT_KEY:"CUSTOM_FUNCTIONS_PORT",CUSTOM_FUNCTIONS_DIRECTORY_KEY:"CUSTOM_FUNCTIONS_DIRECTORY",MAX_CUSTOM_FUNCTION_PROCESSES:"MAX_CUSTOM_FUNCTION_PROCESSES",LOG_TO_FILE:"LOG_TO_FILE",LOG_TO_STDSTREAMS:"LOG_TO_STDSTREAMS",RUN_IN_FOREGROUND:"RUN_IN_FOREGROUND",LOCAL_STUDIO_ON:"LOCAL_STUDIO_ON",STORAGE_WRITE_ASYNC:"STORAGE_WRITE_ASYNC"},Aq=iO.invert(oO),Oq={CUSTOMFUNCTIONS_ENABLED:"customFunctions_enabled",CUSTOMFUNCTIONS_NETWORK_PORT:"customFunctions_network_port",CUSTOMFUNCTIONS_TLS_CERTIFICATE:"customFunctions_tls_certificate",CUSTOMFUNCTIONS_NETWORK_CORS:"customFunctions_network_cors",CUSTOMFUNCTIONS_NETWORK_CORSACCESSLIST:"customFunctions_network_corsAccessList",CUSTOMFUNCTIONS_NETWORK_HEADERSTIMEOUT:"customFunctions_network_headersTimeout",CUSTOMFUNCTIONS_NETWORK_HTTPS:"customFunctions_network_https",CUSTOMFUNCTIONS_NETWORK_KEEPALIVETIMEOUT:"customFunctions_network_keepAliveTimeout",CUSTOMFUNCTIONS_TLS_PRIVATEKEY:"customFunctions_tls_privateKey",CUSTOMFUNCTIONS_TLS_CERT_AUTH:"customFunctions_tls_certificateAuthority",CUSTOMFUNCTIONS_NETWORK_TIMEOUT:"customFunctions_network_timeout",CUSTOMFUNCTIONS_NODEENV:"customFunctions_nodeEnv",CUSTOMFUNCTIONS_ROOT:"customFunctions_root"},I={ANALYTICS_AGGREGATEPERIOD:"analytics_aggregatePeriod",AUTHENTICATION_AUTHORIZELOCAL:"authentication_authorizeLocal",AUTHENTICATION_CACHETTL:"authentication_cacheTTL",AUTHENTICATION_ENABLESESSIONS:"authentication_enableSessions",AUTHENTICATION_OPERATIONTOKENTIMEOUT:"authentication_operationTokenTimeout",AUTHENTICATION_REFRESHTOKENTIMEOUT:"authentication_refreshTokenTimeout",CLUSTERING_USER:"clustering_user",CLUSTERING_ENABLED:"clustering_enabled",CLUSTERING_HUBSERVER_CLUSTER_NAME:"clustering_hubServer_cluster_name",CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT:"clustering_hubServer_cluster_network_port",CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES:"clustering_hubServer_cluster_network_routes",CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT:"clustering_hubServer_leafNodes_network_port",CLUSTERING_HUBSERVER_NETWORK_PORT:"clustering_hubServer_network_port",CLUSTERING_LEAFSERVER_NETWORK_PORT:"clustering_leafServer_network_port",CLUSTERING_LEAFSERVER_NETWORK_ROUTES:"clustering_leafServer_network_routes",CLUSTERING_LEAFSERVER_STREAMS_MAXAGE:"clustering_leafServer_streams_maxAge",CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES:"clustering_leafServer_streams_maxBytes",CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS:"clustering_leafServer_streams_maxMsgs",CLUSTERING_LEAFSERVER_STREAMS_MAXCONSUMEMSGS:"clustering_leafServer_streams_maxConsumeMsgs",CLUSTERING_LEAFSERVER_STREAMS_MAXINGESTTHREADS:"clustering_leafServer_streams_maxIngestThreads",CLUSTERING_LEAFSERVER_STREAMS_PATH:"clustering_leafServer_streams_path",CLUSTERING_NODENAME:"clustering_nodeName",CLUSTERING_TLS_CERTIFICATE:"clustering_tls_certificate",CLUSTERING_TLS_PRIVATEKEY:"clustering_tls_privateKey",CLUSTERING_TLS_CERT_AUTH:"clustering_tls_certificateAuthority",CLUSTERING_TLS_INSECURE:"clustering_tls_insecure",CLUSTERING_TLS_VERIFY:"clustering_tls_verify",CLUSTERING_LOGLEVEL:"clustering_logLevel",CLUSTERING_REPUBLISHMESSAGES:"clustering_republishMessages",CLUSTERING_DATABASELEVEL:"clustering_databaseLevel",CUSTOMFUNCTIONS_NETWORK_HTTPS:"customFunctions_network_https",THREADS:"threads",THREADS_COUNT:"threads_count",THREADS_DEBUG:"threads_debug",THREADS_DEBUG_STARTINGPORT:"threads_debug_startingPort",THREADS_DEBUG_PORT:"threads_debug_port",THREADS_DEBUG_HOST:"threads_debug_host",THREADS_DEBUG_WAITFORDEBUGGER:"threads_debug_waitForDebugger",THREADS_MAXHEAPMEMORY:"threads_maxHeapMemory",HTTP_SESSIONAFFINITY:"http_sessionAffinity",HTTP_COMPRESSIONTHRESHOLD:"http_compressionThreshold",HTTP_CORS:"http_cors",HTTP_CORSACCESSLIST:"http_corsAccessList",HTTP_HEADERSTIMEOUT:"http_headersTimeout",HTTP_KEEPALIVETIMEOUT:"http_keepAliveTimeout",HTTP_TIMEOUT:"http_timeout",HTTP_PORT:"http_port",HTTP_SECUREPORT:"http_securePort",HTTP_MTLS:"http_mtls",HTTP_MTLS_REQUIRED:"http_mtls_required",HTTP_MTLS_USER:"http_mtls_user",HTTP_MAXHEADERSIZE:"http_maxHeaderSize",HTTP_THREADRANGE:"http_threadRange",LOCALSTUDIO_ENABLED:"localStudio_enabled",LOGGING_FILE:"logging_file",LOGGING_LEVEL:"logging_level",LOGGING_ROOT:"logging_root",LOGGING_ROTATION_ENABLED:"logging_rotation_enabled",LOGGING_ROTATION_COMPRESS:"logging_rotation_compress",LOGGING_ROTATION_INTERVAL:"logging_rotation_interval",LOGGING_ROTATION_MAXSIZE:"logging_rotation_maxSize",LOGGING_ROTATION_PATH:"logging_rotation_path",LOGGING_STDSTREAMS:"logging_stdStreams",LOGGING_AUDITLOG:"logging_auditLog",LOGGING_AUDITRETENTION:"logging_auditRetention",LOGGING_AUDITAUTHEVENTS_LOGFAILED:"logging_auditAuthEvents_logFailed",LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL:"logging_auditAuthEvents_logSuccessful",OPERATIONSAPI_NETWORK_CORS:"operationsApi_network_cors",OPERATIONSAPI_NETWORK_CORSACCESSLIST:"operationsApi_network_corsAccessList",OPERATIONSAPI_NETWORK_HEADERSTIMEOUT:"operationsApi_network_headersTimeout",OPERATIONSAPI_NETWORK_HTTPS:"operationsApi_network_https",OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT:"operationsApi_network_keepAliveTimeout",OPERATIONSAPI_NETWORK_PORT:"operationsApi_network_port",OPERATIONSAPI_NETWORK_DOMAINSOCKET:"operationsApi_network_domainSocket",OPERATIONSAPI_NETWORK_SECUREPORT:"operationsApi_network_securePort",OPERATIONSAPI_TLS:"operationsApi_tls",OPERATIONSAPI_TLS_CERTIFICATE:"operationsApi_tls_certificate",OPERATIONSAPI_TLS_PRIVATEKEY:"operationsApi_tls_privateKey",OPERATIONSAPI_TLS_CERTIFICATEAUTHORITY:"operationsApi_tls_certificateAuthority",OPERATIONSAPI_NETWORK_TIMEOUT:"operationsApi_network_timeout",ROOTPATH:"rootPath",SERIALIZATION_BIGINT:"serialization_bigInt",STORAGE_WRITEASYNC:"storage_writeAsync",STORAGE_OVERLAPPINGSYNC:"storage_overlappingSync",STORAGE_CACHING:"storage_caching",STORAGE_COMPRESSION:"storage_compression",STORAGE_NOREADAHEAD:"storage_noReadAhead",STORAGE_PREFETCHWRITES:"storage_prefetchWrites",STORAGE_ENCRYPTION:"storage_encryption",STORAGE_MAXTRANSACTIONQUEUETIME:"storage_maxTransactionQueueTime",STORAGE_PATH:"storage_path",STORAGE_AUDIT_PATH:"storage_audit_path",STORAGE_MAXFREESPACETOLOAD:"storage_maxFreeSpaceToLoad",STORAGE_MAXFREESPACETORETAIN:"storage_maxFreeSpaceToRetain",STORAGE_PAGESIZE:"storage_pageSize",STORAGE_COMPRESSION_DICTIONARY:"storage_compression_dictionary",STORAGE_COMPRESSION_THRESHOLD:"storage_compression_threshold",STORAGE_COMPACTONSTART:"storage_compactOnStart",STORAGE_COMPACTONSTARTKEEPBACKUP:"storage_compactOnStartKeepBackup",DATABASES:"databases",IGNORE_SCRIPTS:"ignoreScripts",MQTT_NETWORK_PORT:"mqtt_network_port",MQTT_WEBSOCKET:"mqtt_webSocket",MQTT_NETWORK_SECUREPORT:"mqtt_network_securePort",MQTT_NETWORK_MTLS:"mqtt_network_mtls",MQTT_NETWORK_MTLS_REQUIRED:"mqtt_network_mtls_required",MQTT_NETWORK_MTLS_CERTIFICATEAUTHORITY:"mqtt_network_mtls_certificateAuthority",MQTT_NETWORK_MTLS_USER:"mqtt_network_mtls_user",MQTT_REQUIREAUTHENTICATION:"mqtt_requireAuthentication",COMPONENTSROOT:"componentsRoot",TLS_CERTIFICATE:"tls_certificate",TLS_PRIVATEKEY:"tls_privateKey",TLS_CERTIFICATEAUTHORITY:"tls_certificateAuthority",TLS_CIPHERS:"tls_ciphers",TLS:"tls",CLONED:"cloned"},aO={settings_path:sO.SETTINGS_PATH_KEY,hdb_root_key:I.ROOTPATH,hdb_root:I.ROOTPATH,rootpath:I.ROOTPATH,server_port_key:I.OPERATIONSAPI_NETWORK_PORT,server_port:I.OPERATIONSAPI_NETWORK_PORT,cert_key:I.TLS_CERTIFICATE,certificate:I.TLS_CERTIFICATE,private_key_key:I.TLS_PRIVATEKEY,private_key:I.TLS_PRIVATEKEY,http_secure_enabled_key:I.OPERATIONSAPI_NETWORK_HTTPS,https_on:I.OPERATIONSAPI_NETWORK_HTTPS,cors_enabled_key:I.OPERATIONSAPI_NETWORK_CORS,cors_on:I.OPERATIONSAPI_NETWORK_CORS,cors_whitelist_key:I.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_whitelist:I.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_accesslist_key:I.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_accesslist:I.OPERATIONSAPI_NETWORK_CORSACCESSLIST,log_level_key:I.LOGGING_LEVEL,log_level:I.LOGGING_LEVEL,log_path_key:I.LOGGING_ROOT,log_path:I.LOGGING_ROOT,clustering_node_name_key:I.CLUSTERING_NODENAME,node_name:I.CLUSTERING_NODENAME,clustering_enabled_key:I.CLUSTERING_ENABLED,clustering:I.CLUSTERING_ENABLED,max_http_threads:I.THREADS_COUNT,max_hdb_processes:I.THREADS_COUNT,server_timeout_key:I.OPERATIONSAPI_NETWORK_TIMEOUT,server_timeout_ms:I.OPERATIONSAPI_NETWORK_TIMEOUT,server_keep_alive_timeout_key:I.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT,server_keep_alive_timeout:I.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT,server_headers_timeout_key:I.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT,server_headers_timeout:I.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT,disable_transaction_log_key:I.LOGGING_AUDITLOG,disable_transaction_log:I.LOGGING_AUDITLOG,operation_token_timeout_key:I.AUTHENTICATION_OPERATIONTOKENTIMEOUT,operation_token_timeout:I.AUTHENTICATION_OPERATIONTOKENTIMEOUT,refresh_token_timeout_key:I.AUTHENTICATION_REFRESHTOKENTIMEOUT,refresh_token_timeout:I.AUTHENTICATION_REFRESHTOKENTIMEOUT,custom_functions_port_key:I.HTTP_PORT,custom_functions_port:I.HTTP_PORT,custom_functions_directory_key:I.COMPONENTSROOT,custom_functions_directory:I.COMPONENTSROOT,max_custom_function_processes:I.THREADS_COUNT,log_to_file:I.LOGGING_FILE,log_to_stdstreams:I.LOGGING_STDSTREAMS,local_studio_on:I.LOCALSTUDIO_ENABLED,clustering_port:I.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT,clustering_user:I.CLUSTERING_USER,clustering_enabled:I.CLUSTERING_ENABLED,clustering_hubserver_cluster_name:I.CLUSTERING_HUBSERVER_CLUSTER_NAME,clustering_hubserver_cluster_network_port:I.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT,clustering_hubserver_cluster_network_routes:I.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,clustering_hubserver_leafnodes_network_port:I.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT,clustering_hubserver_network_port:I.CLUSTERING_HUBSERVER_NETWORK_PORT,clustering_leafserver_network_port:I.CLUSTERING_LEAFSERVER_NETWORK_PORT,clustering_leafserver_network_routes:I.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,clustering_leafserver_streams_maxage:I.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE,clustering_leafserver_streams_maxbytes:I.CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES,clustering_leafserver_streams_maxconsumemsgs:I.CLUSTERING_LEAFSERVER_STREAMS_MAXCONSUMEMSGS,clustering_leafserver_streams_maxingestthreads:I.CLUSTERING_LEAFSERVER_STREAMS_MAXINGESTTHREADS,clustering_leafserver_streams_maxmsgs:I.CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS,clustering_leafserver_streams_path:I.CLUSTERING_LEAFSERVER_STREAMS_PATH,clustering_nodename:I.CLUSTERING_NODENAME,clustering_tls_certificate:I.CLUSTERING_TLS_CERTIFICATE,clustering_tls_privatekey:I.CLUSTERING_TLS_PRIVATEKEY,clustering_tls_certificateauthority:I.CLUSTERING_TLS_CERT_AUTH,clustering_tls_insecure:I.CLUSTERING_TLS_INSECURE,clustering_tls_verify:I.CLUSTERING_TLS_VERIFY,clustering_loglevel:I.CLUSTERING_LOGLEVEL,clustering_republishmessages:I.CLUSTERING_REPUBLISHMESSAGES,clustering_databaselevel:I.CLUSTERING_DATABASELEVEL,customfunctions_network_port:I.HTTP_PORT,customfunctions_tls_certificate:I.TLS_CERTIFICATE,customfunctions_network_cors:I.HTTP_CORS,customfunctions_network_corsaccesslist:I.HTTP_CORSACCESSLIST,customfunctions_network_headerstimeout:I.HTTP_HEADERSTIMEOUT,customfunctions_network_https:I.CUSTOMFUNCTIONS_NETWORK_HTTPS,customfunctions_network_keepalivetimeout:I.HTTP_KEEPALIVETIMEOUT,customfunctions_tls_privatekey:I.TLS_PRIVATEKEY,customfunctions_tls_certificateauthority:I.TLS_CERTIFICATEAUTHORITY,customfunctions_network_timeout:I.HTTP_TIMEOUT,customfunctions_tls:I.TLS,http_threads:I.THREADS_COUNT,threads:I.THREADS_COUNT,threads_count:I.THREADS_COUNT,threads_debug:I.THREADS_DEBUG,threads_debug_startingport:I.THREADS_DEBUG_STARTINGPORT,threads_debug_port:I.THREADS_DEBUG_PORT,threads_debug_host:I.THREADS_DEBUG_HOST,threads_debug_waitfordebugger:I.THREADS_DEBUG_WAITFORDEBUGGER,threads_maxheapmemory:I.THREADS_MAXHEAPMEMORY,http_session_affinity:I.HTTP_SESSIONAFFINITY,http_compressionthreshold:I.HTTP_COMPRESSIONTHRESHOLD,http_cors:I.HTTP_CORS,http_corsaccesslist:I.HTTP_CORSACCESSLIST,http_headerstimeout:I.HTTP_HEADERSTIMEOUT,http_keepalivetimeout:I.HTTP_KEEPALIVETIMEOUT,http_timeout:I.HTTP_TIMEOUT,http_port:I.HTTP_PORT,http_secureport:I.HTTP_SECUREPORT,http_mtls:I.HTTP_MTLS,http_mtls_user:I.HTTP_MTLS_USER,http_mtls_required:I.HTTP_MTLS_REQUIRED,http_maxheadersize:I.HTTP_MAXHEADERSIZE,http_threadrange:I.HTTP_THREADRANGE,customfunctions_processes:I.THREADS_COUNT,customfunctions_root:I.COMPONENTSROOT,localstudio_enabled:I.LOCALSTUDIO_ENABLED,logging_file:I.LOGGING_FILE,logging_level:I.LOGGING_LEVEL,logging_root:I.LOGGING_ROOT,logging_rotation_enabled:I.LOGGING_ROTATION_ENABLED,logging_rotation_compress:I.LOGGING_ROTATION_COMPRESS,logging_rotation_interval:I.LOGGING_ROTATION_INTERVAL,logging_rotation_maxsize:I.LOGGING_ROTATION_MAXSIZE,logging_rotation_path:I.LOGGING_ROTATION_PATH,logging_stdstreams:I.LOGGING_STDSTREAMS,logging_auditlog:I.LOGGING_AUDITLOG,logging_auditretention:I.LOGGING_AUDITRETENTION,logging_auditauthevents_logfailed:I.LOGGING_AUDITAUTHEVENTS_LOGFAILED,logging_auditauthevents_logsuccessful:I.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL,operationsapi_authentication_operationtokentimeout:I.AUTHENTICATION_OPERATIONTOKENTIMEOUT,operationsapi_authentication_refreshtokentimeout:I.AUTHENTICATION_REFRESHTOKENTIMEOUT,operationsapi_network_cors:I.OPERATIONSAPI_NETWORK_CORS,operationsapi_network_corsaccesslist:I.OPERATIONSAPI_NETWORK_CORSACCESSLIST,operationsapi_network_headerstimeout:I.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT,operationsapi_network_https:I.OPERATIONSAPI_NETWORK_HTTPS,operationsapi_network_keepalivetimeout:I.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT,operationsapi_network_port:I.OPERATIONSAPI_NETWORK_PORT,operationsapi_network_domainsocket:I.OPERATIONSAPI_NETWORK_DOMAINSOCKET,operationsapi_network_secureport:I.OPERATIONSAPI_NETWORK_SECUREPORT,operationsapi_tls:I.OPERATIONSAPI_TLS,operationsapi_tls_certificate:I.OPERATIONSAPI_TLS_CERTIFICATE,operationsapi_tls_privatekey:I.OPERATIONSAPI_TLS_PRIVATEKEY,operationsapi_tls_certificateauthority:I.OPERATIONSAPI_TLS_CERTIFICATEAUTHORITY,operationsapi_network_timeout:I.OPERATIONSAPI_NETWORK_TIMEOUT,operationsapi_root:I.ROOTPATH,databases:I.DATABASES,storage_path:I.STORAGE_PATH,storage_maxtransactionqueuetime:I.STORAGE_MAXTRANSACTIONQUEUETIME,ignorescripts:I.IGNORE_SCRIPTS,mqtt_network_port:I.MQTT_NETWORK_PORT,mqtt_websocket:I.MQTT_WEBSOCKET,mqtt_network_secureport:I.MQTT_NETWORK_SECUREPORT,mqtt_network_mtls:I.MQTT_NETWORK_MTLS,mqtt_network_mtls_certificateAuthority:I.MQTT_NETWORK_MTLS_CERTIFICATEAUTHORITY,mqtt_network_mtls_user:I.MQTT_NETWORK_MTLS_USER,mqtt_network_mtls_required:I.MQTT_NETWORK_MTLS_REQUIRED,mqtt_requireauthentication:I.MQTT_REQUIREAUTHENTICATION,analytics_aggregatePeriod:I.ANALYTICS_AGGREGATEPERIOD,authentication_authorizelocal:I.AUTHENTICATION_AUTHORIZELOCAL,authentication_cachettl:I.AUTHENTICATION_CACHETTL,authentication_enablesessions:I.AUTHENTICATION_ENABLESESSIONS,authentication_operationtokentimeout:I.AUTHENTICATION_OPERATIONTOKENTIMEOUT,authentication_refreshtokentimeout:I.AUTHENTICATION_REFRESHTOKENTIMEOUT,componentsroot:I.COMPONENTSROOT,tls:I.TLS,tls_certificate:I.TLS_CERTIFICATE,tls_privatekey:I.TLS_PRIVATEKEY,tls_certificateauthority:I.TLS_CERTIFICATEAUTHORITY,tls_ciphers:I.TLS_CIPHERS};for(let e in I){let t=I[e];aO[t.toLowerCase()]=t}var bq={TABLES:"tables",PATH:"path",AUDIT_PATH:"auditPath"},yq={csv_file_load:"csv_file_load",csv_data_load:Z.CSV_DATA_LOAD,csv_url_load:Z.CSV_URL_LOAD,delete_files_before:"delete_files_before",delete_records_before:"delete_records_before",delete_audit_logs_before:"delete_audit_logs_before",delete_transaction_logs_before:"delete_transaction_logs_before",empty_trash:"empty_trash",export_local:"export_local",export_to_s3:"export_to_s3",import_from_s3:"import_from_s3",restart_service:"restart_service"},Nq={CLUSTERING_PAYLOAD:"clustering_payload",DELEGATE_THREAD_RESPONSE:"delegate_thread_response",CLUSTERING:"clustering",SCHEMA:"schema",CLUSTER_STATUS:"cluster_status",JOB:"job",CHILD_STARTED:"child_started",CHILD_STOPPED:"child_stopped",USER:"user",RESTART:"restart"},Iq={BIDIRECTIONAL:"BIDIRECTIONAL",OUTBOUND:"OUTBOUND",INBOUND:"INBOUND"},wq={VERSION_DEFAULT:"2.2.0"},Cq={DEVELOPMENT:8192,DEFAULT:512},Dq={IDENTIFY:"identify",AUTHENTICATE:"authenticate",AUTHENTICATE_OK:"authenticated",AUTHENTICATE_FAIL:"authenticate_fail",CONNECTION:"connection",CONNECT:"connect",CATCHUP_REQUEST:"catchup_request",CATCHUP_RESPONSE:"catchup",CONFIRM_MSG:"confirm_msg",ERROR:"error",DISCONNECT:"disconnect",SCHEMA_UPDATE_REQ:"schema_update_request",SCHEMA_UPDATE_RES:"schema_update_response",RECONNECT_ATTEMPT:"reconnect_attempt",CONNECT_ERROR:"connect_error",MESSAGE:"msg",VERSION_MISMATCH:"version_mismatch",DIRECTION_CHANGE:"direction_change"},Lq={1e3:"SUCCESSFUL_SHUTDOWN",1001:"CLOSE_GOING_AWAY",1002:"CLOSE_PROTOCOL_ERROR",1003:"CLOSE_UNSUPPORTED",1005:"CLOSE_NO_STATUS",1006:"CLOSE_ABNORMAL",1007:"UNSUPPORTED_PAYLOAD",1008:"POLICY_VIOLATION",1009:"CLOSE_TOO_LARGE",1010:"MANDATORY_EXTENSION",1011:"SERVER_ERROR",1012:"SERVICE_RESTART",1013:"SERVER_BUSY",1014:"BAD_GATEWAY",1015:"HANDSHAKE_FAIL",4141:"LICENSE_LIMIT_REACHED"},Mq={ENOENT:"ENOENT",EACCES:"EACCES",EEXIST:"EEXIST",ERR_INVALID_ARG_TYPE:"ERR_INVALID_ARG_TYPE"},cO={CREATED_TIME:"__createdtime__",UPDATED_TIME:"__updatedtime__"},Pq=Symbol("metadata"),Uq="__clustering__",vq=Object.values(cO),Bq=15984864e5,lO={LESS:"<",LESS_OR_EQ:"<=",GREATER:">",GREATER_OR_EQ:">=",BETWEEN:"..."},Hq=iO.invert(lO),xq={GET_CLUSTER_STATUS:"GET_CLUSTER_STATUS",CLUSTER_STATUS_RESPONSE:"CLUSTER_STATUS_RESPONSE",ERROR_RESPONSE:"ERROR",ADD_USER:"ADD_USER",ALTER_USER:"ALTER_USER",DROP_USER:"DROP_USER",HDB_OPERATION:"HDB_OPERATION",ADD_NODE:"ADD_NODE",UPDATE_NODE:"UPDATE_NODE",REMOVE_NODE:"REMOVE_NODE",HDB_USERS_MSG:"HDB_USERS_MSG",HDB_WORKERS:"HDB_WORKERS",HDB_TRANSACTION:"HDB_TRANSACTION"},Gq=111,Fq=`\r
2
- `,qq={READ:"read",INSERT:"insert",UPDATE:"update",DELETE:"delete"},kq=["*","%"],Vq="unauthorized_access",$q="func_val",Yq={HASH_VALUE:"hash_value",TIMESTAMP:"timestamp",USERNAME:"username"},Kq={JWT_PRIVATE_KEY_NAME:".jwtPrivate.key",JWT_PUBLIC_KEY_NAME:".jwtPublic.key",JWT_PASSPHRASE_NAME:".jwtPass"},Wq={SHUTDOWN:"shutdown",CHILD_STARTED:"child_started",CHILD_STOPPED:"child_stopped",SCHEMA:"schema",USER:"user",CLUSTER_STATUS_RESPONSE:"cluster_status_response",CLUSTER_STATUS_REQUEST:"cluster_status_request",METRICS:"metrics",GET_METRICS:"get_metrics",RESTART:"restart",START_JOB:"start_job",NATS_CONSUMER_UPDATE:"nats_consumer_update"},Qq={HDB_CORE:"hdb_core",CUSTOM_FUNCTIONS:"custom_functions"},zq={HTTP:"http"},Jq={STOPPED:"stopped",ONLINE:"online"},Xq="3.x.x",jq={SUCCESS:"success",FAILURE:"failure"},Zq={AUTHENTICATION:"authentication",AUTHORIZATION:"authorization"};uO.exports={LOCAL_HARPERDB_OPERATIONS:He,HDB_SUPPORT_ADDRESS:eO,HDB_SUPPORT_URL:rO,HDB_PRICING_URL:AF,SUPPORT_HELP_MSG:OF,LICENSE_HELP_MSG:nO,HDB_PROC_NAME:jA,HDB_PROC_DESCRIPTOR:Oh,CLUSTERING_LEAF_PROC_DESCRIPTOR:Zu,CLUSTERING_HUB_PROC_DESCRIPTOR:ju,SYSTEM_SCHEMA_NAME:kF,HASH_FOLDER_NAME:VF,HDB_HOME_DIR_NAME:$F,UPDATE_FILE_NAME:QF,LICENSE_KEY_DIR_NAME:KF,BOOT_PROPS_FILE_NAME:WF,JOB_TYPE_ENUM:yq,JOB_STATUS_ENUM:mq,SYSTEM_TABLE_NAMES:uq,SYSTEM_TABLE_HASH_ATTRIBUTES:_q,OPERATIONS_ENUM:Z,VALID_S3_FILE_TYPES:pq,S3_BUCKET_AUTH_KEYS:Sq,VALID_SQL_OPS_ENUM:Tq,GEO_CONVERSION_ENUM:Rq,HDB_SETTINGS_NAMES:oO,HDB_SETTINGS_NAMES_REVERSE_LOOKUP:Aq,SERVICE_ACTIONS_ENUM:gq,CLUSTER_MESSAGE_TYPE_ENUM:Nq,CLUSTER_CONNECTION_DIRECTION_ENUM:Iq,CLUSTER_EVENTS_DEFS_ENUM:Dq,PERIOD_REGEX:DF,DOUBLE_PERIOD_REGEX:LF,UNICODE_PERIOD:MF,FORWARD_SLASH_REGEX:PF,UNICODE_FORWARD_SLASH:UF,ESCAPED_FORWARD_SLASH_REGEX:vF,ESCAPED_PERIOD_REGEX:BF,ESCAPED_DOUBLE_PERIOD_REGEX:HF,REG_KEY_FILE_NAME:Eq,RESTART_TIMEOUT_MS:XF,HDB_FILE_PERMISSIONS:jF,DATABASES_DIR_NAME:tq,LEGACY_DATABASES_DIR_NAME:rq,TRANSACTIONS_DIR_NAME:nq,LIMIT_COUNT_NAME:sq,ID_ATTRIBUTE_STRING:iq,INSERT_MODULE_ENUM:cq,UPGRADE_JSON_FIELD_NAMES_ENUM:lq,RESTART_CODE:zF,RESTART_CODE_NUM:JF,CLUSTER_OPERATIONS:lc,SYSTEM_DEFAULT_ATTRIBUTE_NAMES:fq,HDB_INTERNAL_SC_CHANNEL_PREFIX:Pr,INTERNAL_SC_CHANNELS:dq,CLUSTERING_MESSAGE_TYPES:xq,HDB_FILE_SUFFIX:YF,BLOB_FOLDER_NAME:ZF,HDB_TRASH_DIR:eq,ORIGINATOR_SET_VALUE:Gq,LICENSE_VALUES:wq,RAM_ALLOCATION_ENUM:Cq,TIME_STAMP_NAMES_ENUM:cO,TIME_STAMP_NAMES:vq,PERMS_UPDATE_RELEASE_TIMESTAMP:Bq,SEARCH_NOT_FOUND_MESSAGE:bF,SEARCH_ATTRIBUTE_NOT_FOUND:yF,LICENSE_ROLE_DENIED_RESPONSE:NF,LICENSE_MAX_CONNS_REACHED:IF,BASIC_LICENSE_MAX_NON_CU_ROLES:tO,BASIC_LICENSE_CLUSTER_CONNECTION_LIMIT_WS_ERROR_CODE:RF,VALUE_SEARCH_COMPARATORS:lO,VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP:Hq,LICENSE_FILE_NAME:hq,WEBSOCKET_CLOSE_CODE_DESCRIPTION_LOOKUP:Lq,NEW_LINE:Fq,BASIC_LICENSE_MAX_CLUSTER_USER_ROLES:CF,MOMENT_DAYS_TAG:xF,API_TURNOVER_SEC:GF,LOOPBACK:wF,CODE_EXTENSION:Xu,WILDCARD_SEARCH_VALUE:FF,NODE_ERROR_CODES:Mq,JAVASCRIPT_EXTENSION:XA,PERMS_CRUD_ENUM:qq,UNAUTHORIZED_PERMISSION_NAME:Vq,SEARCH_WILDCARDS:kq,FUNC_VAL:$q,READ_AUDIT_LOG_SEARCH_TYPES_ENUM:Yq,JWT_ENUM:Kq,CLUSTERING_FLAG:Uq,ITC_EVENT_TYPES:Wq,CUSTOM_FUNCTION_PROC_NAME:ZA,CUSTOM_FUNCTION_PROC_DESCRIPTOR:Ju,SERVICES:Qq,THREAD_TYPES:zq,MEM_SETTING_KEY:qF,HDB_RESTART_SCRIPT:oF,PROCESS_DESCRIPTORS:dF,SERVICE_SERVERS:pF,SERVICE_SERVERS_CWD:Ah,PROCESS_DESCRIPTORS_VALIDATE:hF,LAUNCH_SERVICE_SCRIPTS:SF,LOG_LEVELS:EF,PROCESS_NAME_ENV_PROP:oq,LOG_NAMES:fF,PM2_PROCESS_STATUSES:Jq,CONFIG_PARAM_MAP:aO,CONFIG_PARAMS:I,HDB_CONFIG_FILE:nF,HDB_DEFAULT_CONFIG_FILE:sF,ROLE_TYPES_ENUM:TF,BOOT_PROP_PARAMS:sO,INSTALL_PROMPTS:aq,HDB_ROOT_DIR_NAME:iF,CLUSTERING_PROCESSES:mF,FOREGROUND_PID_FILE:lF,PACKAGE_ROOT:Xs,PRE_4_0_0_VERSION:Xq,DATABASES_PARAM_CONFIG:bq,METADATA_PROPERTY:Pq,AUTH_AUDIT_STATUS:jq,AUTH_AUDIT_TYPES:Zq,HDB_PID_FILE:uF,DEFAULT_DATABASE_NAME:_F,LEGACY_CONFIG_PARAMS:Oq};JA()});var bh=g((woe,fO)=>{"use strict";var _O=require("minimist");fO.exports=ek;function ek(e=[],t=!1){if(!Array.isArray(e))return{};let r,n;t?(r=dO(process.env),n=dO(_O(process.argv))):(r=process.env,n=_O(process.argv));let s={};for(let i=0,o=e.length;i<o;i++){let c=e[i];n[c]!==void 0?s[c]=n[c].toString().trim():r[c]!==void 0&&(s[c]=r[c].toString().trim())}return s}a(ek,"assignCMDENVVariables");function dO(e){let t,r=Object.keys(e),n=r.length,s={};for(;n--;)t=r[n],s[t.toLowerCase()]=e[t];return s}a(dO,"objKeysToLowerCase")});var K=g((Doe,Lh)=>{"use strict";var Ui=require("fs-extra"),{workerData:tk,threadId:rk}=require("worker_threads"),ps=require("path"),mO=require("yaml"),pO=require("properties-reader"),St=U(),EO=bh(),nk=require("os"),{PACKAGE_ROOT:Nh}=U(),{_assignPackageExport:sk}=require("../index"),_c={};for(let e in console)_c[e]||(_c[e]=console[e]);var cr={notify:7,fatal:6,error:5,warn:4,info:3,debug:2,trace:1},SO={STDOUT:"stdOut",STDERR:"stdErr"},ik=ps.join(Nh,"logs"),ok=ps.join(Nh,"config/yaml/",St.HDB_DEFAULT_CONFIG_FILE),ak=1e4,ms,Kn,ar,e_,t_,dc,Go,uc;uc===void 0&&TO();Lh.exports={notify:AO,fatal:OO,error:fc,warn:Dh,info:r_,debug:Ch,trace:wh,setLogLevel:Ek,log_level:ar,loggerWithTag:ck,suppressLogging:lk,initLogSettings:TO,setupConsoleLogging:gO,logCustomLevel:dk,closeLogFile:Ih,getLogFilePath:()=>dc,OUTPUTS:SO,AuthAuditLog:pk};sk("logger",Lh.exports);function TO(e=!1){try{if(uc===void 0||e){Ih();let t=fk(),r=EO(["ROOTPATH"]);try{uc=pO(t)}catch(n){if(!r.ROOTPATH||r.ROOTPATH&&!Ui.pathExistsSync(ps.join(r.ROOTPATH,St.HDB_CONFIG_FILE)))throw n}({level:ar,config_log_path:t_,to_file:ms,to_stream:Kn}=hk(r.ROOTPATH?ps.join(r.ROOTPATH,St.HDB_CONFIG_FILE):uc.get("settings_path"))),e_=St.LOG_NAMES.HDB,dc=ps.join(t_,e_)}}catch(t){if(uc=void 0,t.code===St.NODE_ERROR_CODES.ENOENT||t.code===St.NODE_ERROR_CODES.ERR_INVALID_ARG_TYPE){let r=EO(Object.keys(St.CONFIG_PARAM_MAP),!0);for(let o in r){let c=St.CONFIG_PARAM_MAP[o];c&&c.toLowerCase();let l=r[o];if(c===St.CONFIG_PARAMS.LOGGING_LEVEL){ar=l;continue}if(c===St.CONFIG_PARAMS.LOGGING_STDSTREAMS){Kn=l;continue}c===St.CONFIG_PARAMS.LOGGING_FILE&&(ms=c)}let{default_level:n,default_to_file:s,default_to_stream:i}=mk();ms=ms===void 0?s:ms,ms=hO(ms),Kn=Kn===void 0?i:Kn,Kn=hO(Kn),ar=ar===void 0?n:ar,t_=ik,e_=St.LOG_NAMES.INSTALL,dc=ps.join(t_,e_);return}throw fc("Error initializing log settings"),fc(t),t}process.env.DEV_MODE&&(Kn=!0),gO()}a(TO,"initLogSettings");var yh=!0;function gO(){xo("error",fc),xo("warn",Dh),xo("log",r_),xo("info",r_),xo("debug",Ch),xo("trace",wh)}a(gO,"setupConsoleLogging");function xo(e,t){console[e]=function(...r){if(yh&&t(...r),!/PM2 log:|App \[/.test(r[0]))return _c[e](...r)}}a(xo,"logConsole");function ck(e){let t={tagName:e.replace(/ /g,"-")};return{notify:r(AO),fatal:r(OO),error:r(fc),warn:r(Dh),info:r(r_),debug:r(Ch),trace:r(wh)};function r(n){return function(...s){return n(t,...s)}}}a(ck,"loggerWithTag");function lk(e){try{yh=!1,e()}finally{yh=!0}}a(lk,"suppressLogging");var uk=tk?.name?.replace(/ /g,"-")||"main";function Ss(e,t){let r=new Date(Date.now()).toISOString(),n="",s=t.length,i=s-1,o=[e],c=0,l;for(typeof t[0]=="object"&&(t[0]?.tagName?(o.push(t[0]?.tagName),c++):t[0]?.serviceName&&(l=t[0]?.serviceName,c++)),o.unshift(l||uk+"/"+rk);c<s;c++){let _=t[c];_ instanceof Error&&_.stack?n+=_.stack:typeof _=="object"?n+=JSON.stringify(_):n+=_,c<i&&(n+=" ")}return`${r} [${o.join("] [")}]: ${n}
3
- `}a(Ss,"createLogRecord");function Ec(e){ms&&RO(e),Kn&&process.stdout.write(e)}a(Ec,"logStdOut");function n_(e){ms&&RO(e),Kn&&process.stderr.write(e)}a(n_,"logStdErr");function RO(e){_k(),Go?Ui.appendFileSync(Go,e):_c.log(e)}a(RO,"logToFile");function Ih(){try{Ui.closeSync(Go)}catch{}Go=null}a(Ih,"closeLogFile");function _k(){if(!Go){try{if(!dc)debugger;Go=Ui.openSync(dc,"a")}catch(e){_c.error(e)}setTimeout(()=>{Ih()},ak).unref()}}a(_k,"openLogFile");function r_(...e){cr[ar]<=cr.info&&Ec(Ss("info",e))}a(r_,"info");function wh(...e){cr[ar]<=cr.trace&&Ec(Ss("trace",e))}a(wh,"trace");function fc(...e){cr[ar]<=cr.error&&n_(Ss("error",e))}a(fc,"error");function Ch(...e){cr[ar]<=cr.debug&&Ec(Ss("debug",e))}a(Ch,"debug");function AO(...e){cr[ar]<=cr.notify&&Ec(Ss("notify",e))}a(AO,"notify");function OO(...e){cr[ar]<=cr.fatal&&n_(Ss("fatal",e))}a(OO,"fatal");function Dh(...e){cr[ar]<=cr.warn&&n_(Ss("warn",e))}a(Dh,"warn");function dk(e,t,...r){t===SO.STDERR?n_(Ss(e,r)):Ec(Ss(e,r))}a(dk,"logCustomLevel");function fk(){let e;try{e=nk.homedir()}catch{e=process.env.HOME}e||(e="~/");let t=ps.join(e,St.HDB_HOME_DIR_NAME,St.BOOT_PROPS_FILE_NAME);return Ui.existsSync(t)||(t=ps.join(Nh,"utility/hdb_boot_properties.file")),t}a(fk,"getPropsFilePath");function Ek(e){ar=e}a(Ek,"setLogLevel");function hO(e){return e===!0||typeof e=="string"&&e.toLowerCase()==="true"}a(hO,"autoCastBoolean");function hk(e){try{if(e.includes("config/settings.js")){let o=pO(e);return{level:o.get(St.HDB_SETTINGS_NAMES.LOG_LEVEL_KEY),config_log_path:ps.dirname(o.get(St.HDB_SETTINGS_NAMES.LOG_PATH_KEY)),to_file:o.get(St.HDB_SETTINGS_NAMES.LOG_TO_FILE),to_stream:o.get(St.HDB_SETTINGS_NAMES.LOG_TO_STDSTREAMS)}}let t=mO.parseDocument(Ui.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===St.NODE_ERROR_CODES.ENOENT)throw t;console.error("Error accessing config file for logging"),console.error(t)}}a(hk,"getLogConfig");function mk(){try{let e=mO.parseDocument(Ui.readFileSync(ok,"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(mk,"getDefaultConfig");function pk(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(pk,"AuthAuditLog")});var yO=g((Moe,bO)=>{"use strict";var Sk=require("util"),Tk=require("path"),gk=require("child_process"),Rk=Sk.promisify(gk.execFile),Ak=1e3*1e3*10;bO.exports={findPs:Ok};async function Ok(e){let t={};try{await Promise.all(["comm","args","ppid","uid","%cpu","%mem"].map(async r=>{let{stdout:n}=await Rk("ps",["wwxo",`pid,${r}`],{maxBuffer:Ak});for(let s of n.trim().split(`
4
- `).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:Tk.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(Ok,"findPs")});var dt=g((Uoe,IO)=>{"use strict";var bk="__dbis__",yk="__txns__",Nk="__environment_name__",Ik="__dbi_defintion__",wk={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"},Ck=["__createdtime__","__updatedtime__"],Dk="\uFFFF",NO={TIMESTAMP:"timestamp",HASH_VALUE:"hash_value",USER_NAME:"user_name"},Lk=Object.values(NO);IO.exports={AUDIT_STORE_NAME:yk,INTERNAL_DBIS_NAME:bk,DBI_DEFINITION_NAME:Ik,SEARCH_TYPES:wk,TIMESTAMP_NAMES:Ck,MAX_SEARCH_KEY_LENGTH:256,ENVIRONMENT_NAME_KEY:Nk,TRANSACTIONS_DBI_NAMES_ENUM:NO,TRANSACTIONS_DBIS:Lk,OVERFLOW_MARKER:Dk}});var Ur=g((voe,BO)=>{"use strict";var wO=U(),CO=dt(),DO={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},LO=a(e=>`${e} Check logs and try again.`,"CHECK_LOGS_WRAPPER"),MO={500:LO("There was an error processing your request."),400:"Invalid request"},Mk=MO[DO.INTERNAL_SERVER_ERROR],Pk={OP_NOT_SUPPORTED_FOR_FS:e=>`${e} is not available for this instance because it uses the File System data store.`,MISSING_VALUE:e=>`${e} is missing.`,INVALID_VALUE:e=>`${e} is invalid.`,NOT_FOUND:e=>`${e} not found.`},Uk={CONFIG_VALIDATION:e=>`HarperDB config file validation error: ${e}`},vk={DEFAULT_BULK_LOAD_ERR:"There was an error during your bulk load into HarperDB.",DOWNLOAD_FILE_ERR:e=>`There was an error downloading '${e}'.`,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:e=>`Bulk load operation failed - ${e} is not a valid 'action' parameter`,INVALID_FILE_EXT_ERR:e=>`Error selecting correct parser - valid file type not found in json - ${e}`,MAX_FILE_SIZE_ERR:(e,t)=>`File size is ${e} bytes, which exceeded the maximum size allowed of: ${t} bytes`,PAPA_PARSE_ERR:"There was an error parsing the downloaded CSV data.",S3_DOWNLOAD_ERR:e=>`There was an error downloading '${e}' from AWS.`,WRITE_TEMP_FILE_ERR:"Error writing temporary file to storage"},Bk={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 ${CO.INTERNAL_DBIS_NAME}`,CANNOT_DROP_INTERNAL_DBIS_NAME:`cannot drop a dbi named ${CO.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"},Hk={ATTR_NAME_LENGTH_ERR:e=>`transaction aborted due to attribute name ${e} being too long. Attribute names cannot be longer than ${wO.INSERT_MODULE_ENUM.MAX_CHARACTER_SIZE} bytes.`,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 ${wO.INSERT_MODULE_ENUM.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"},PO={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"},xk={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:e=>`Operation '${e}' is restricted to 'super_user' roles`,OP_NOT_FOUND:e=>`Operation '${e}' 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:(e,t,r)=>`There was an error authorizing ${e} op on table '${t}.${r}'`,USER_HAS_NO_PERMS:e=>`User ${e} has no role or permissions. Please assign the user a valid role.`,DROP_SYSTEM:"The 'system' database, tables and records are used internally by HarperDB and cannot be updated or removed."},Gk={ATTR_PERM_MISSING:(e,t)=>`${e.toUpperCase()} attribute permission missing for '${t}'`,ATTR_PERM_MISSING_NAME:"Permission object in 'attribute_permission' missing an 'attribute_name'",ATTR_PERM_NOT_BOOLEAN:(e,t)=>`${e.toUpperCase()} attribute permission for '${t}' must be a 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:e=>`Invalid attribute '${e}' in 'attribute_permissions'`,INVALID_PERM_KEY:e=>`Invalid table permission key value '${e}'`,INVALID_ATTR_PERM_KEY:e=>`Invalid attribute permission key value '${e}'`,INVALID_ROLE_JSON_KEYS:e=>`Invalid ${e.length>1?"keys":"key"} in JSON body - '${e.join("', '")}'`,MISMATCHED_TABLE_ATTR_PERMS:e=>`You have a conflict with TABLE permissions for '${e}' being false and ATTRIBUTE permissions being true`,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:e=>`A role with name '${e}' already exists`,ROLE_NOT_FOUND:"Role not found",ROLE_PERMS_ERROR:"Errors in the role permissions JSON provided",SCHEMA_PERM_ERROR:e=>`Your role does not have permission to view database metadata for '${e}'`,SCHEMA_TABLE_PERM_ERROR:(e,t)=>`Your role does not have permission to view database.table metadata for '${e}.${t}'`,SU_ROLE_MISSING_ERROR:"Missing 'super_user' key/value in permission set",SU_CU_ROLE_BOOLEAN_ERROR:e=>`Value for '${e}' permission must be a boolean`,STRUCTURE_USER_ROLE_TYPE_ERROR:e=>`Value for '${e}' permission must be a boolean or Array`,SU_CU_ROLE_NO_PERMS_ALLOWED:e=>`Roles with '${e}' set to true cannot have other permissions set.`,SU_CU_ROLE_COMBINED_ERROR:"Roles cannot have both 'super_user' and 'cluster_user' values included in their permissions set.",TABLE_PERM_MISSING:e=>`Missing table ${e.toUpperCase()} permission`,TABLE_PERM_NOT_BOOLEAN:e=>`Table ${e.toUpperCase()} permission must be a boolean`},Fk={ATTR_NOT_FOUND:(e,t,r)=>`Attribute '${r}' does not exist on '${e}.${t}'`,ATTR_EXISTS_ERR:(e,t,r)=>`Attribute '${r}' already exists in ${e}.${t}'`,DESCRIBE_ALL_ERR:"There was an error during describeAll. Please check the logs and try again.",INVALID_TABLE_ERR:e=>`Invalid table ${JSON.stringify(e)}`,SCHEMA_NOT_FOUND:e=>`database '${e}' does not exist`,SCHEMA_EXISTS_ERR:e=>`database '${e}' already exists`,TABLE_EXISTS_ERR:(e,t)=>`Table '${t}' already exists in '${e}'`,SCHEMA_REQUIRED_ERR:"database is required",TABLE_NOT_FOUND:(e,t)=>`Table '${e}.${t}' does not exist`,TABLE_REQUIRED_ERR:"table is required"},qk={OUTER_JOIN_TRANSLATION_ERROR:"There was an error translating the final SQL outer join data."},kk={ALTER_USER_DUP_ROLES:e=>`Update failed. There are duplicates for the '${e}' role which is not allowed. Update your roles and try again.`,ALTER_USER_ROLE_NOT_FOUND:e=>`Update failed. Requested '${e}' role not found.`,DUP_ROLES_FOUND:e=>`Multiple ${e} roles found. Roles must have unique 'role' value. Please update and try again.`,ROLE_NAME_NOT_FOUND:e=>`${e} role not found`,USER_ALREADY_EXISTS:e=>`User ${e} already exists`,USER_NOT_EXIST:e=>`User ${e} does not exist`},UO={INVALID_DATE:"Invalid date, must be in ISO-8601 format (YYYY-MM-DD).",SEARCH_CONDITIONS_INVALID_SORT_ATTRIBUTE:e=>`invalid sort attribute '${e}', the attribute must either be the table's hash attribute or an attribute used in conditions.`},vO={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:e=>`ITC server received invalid event type: ${e}`},Vk={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."},$k={CLUSTERING_NOT_ENABLED:"Clustering must be enabled to perform this operation."},Yk={...PO,...vk,...Pk,...xk,...Gk,...Fk,...qk,...kk,...Hk,...UO,...vO,...Vk,...$k,...Uk};BO.exports={CHECK_LOGS_WRAPPER:LO,HDB_ERROR_MSGS:Yk,DEFAULT_ERROR_MSGS:MO,DEFAULT_ERROR_RESP:Mk,HTTP_STATUS_CODES:DO,LMDB_ERRORS_ENUM:Bk,AUTHENTICATION_ERROR_MSGS:PO,VALIDATION_ERROR_MSGS:UO,ITC_ERRORS:vO}});var ne=g((Hoe,GO)=>{"use strict";var Fo=Ur(),Kk=K(),Wk=U(),s_=class extends Error{static{a(this,"HdbError")}constructor(t,r,n,s,i){super(),Error.captureStackTrace(this,HO),this.statusCode=n||Fo.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR,this.http_resp_msg=r||(Fo.DEFAULT_ERROR_MSGS[n]?Fo.DEFAULT_ERROR_MSGS[n]:Fo.DEFAULT_ERROR_MSGS[Fo.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&&Kk[s](i)}},Mh=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}},Ph=class extends Error{static{a(this,"ServerError")}constructor(t,r){super(t),this.statusCode=r||500}};function HO(e,t,r,n=Wk.LOG_LEVELS.ERROR,s=null,i=!1){if(xO(e))return e;let o=new s_(e,t,r,n,s);return i&&delete o.stack,o}a(HO,"handleHDBError");function xO(e){return e.__proto__.constructor.name===s_.name}a(xO,"isHDBError");GO.exports={isHDBError:xO,handleHDBError:HO,ClientError:Mh,ServerError:Ph,hdb_errors:Fo}});var ze=g((Goe,KO)=>{"use strict";var Tc=U(),Qk=z(),lr=te(),gc=require("path"),zk=require("minimist"),FO=require("fs-extra"),qO=require("lodash");lr.initSync();var{CONFIG_PARAMS:js,DATABASES_PARAM_CONFIG:hc,SYSTEM_SCHEMA_NAME:i_}=Tc,mc,pc,Sc;function kO(){if(mc!==void 0)return mc;if(lr.getHdbBasePath()!==void 0)return mc=lr.get(js.STORAGE_PATH)||gc.join(lr.getHdbBasePath(),Tc.DATABASES_DIR_NAME),mc}a(kO,"getBaseSchemaPath");function VO(){if(pc!==void 0)return pc;if(lr.getHdbBasePath()!==void 0)return pc=YO(i_),pc}a(VO,"getSystemSchemaPath");function $O(){if(Sc!==void 0)return Sc;if(lr.getHdbBasePath()!==void 0)return Sc=lr.get(Tc.CONFIG_PARAMS.STORAGE_AUDIT_PATH)||gc.join(lr.getHdbBasePath(),Tc.TRANSACTIONS_DIR_NAME),Sc}a($O,"getTransactionAuditStoreBasePath");function Jk(e,t){let r=lr.get(js.DATABASES)?.[e];return t&&r?.tables?.[t]?.auditPath||r?.auditPath||gc.join($O(),e.toString())}a(Jk,"getTransactionAuditStorePath");function YO(e,t){e=e.toString(),t=t&&t.toString();let r=lr.get(Tc.CONFIG_PARAMS.DATABASES)?.[e];return t&&r?.tables?.[t]?.path||r?.path||gc.join(kO(),e)}a(YO,"getSchemaPath");function Xk(e,t){e=e.toString(),t=t.toString();let r=process.env;Object.assign(r,zk(process.argv));let n=r[js.DATABASES.toUpperCase()];if(n){let i;try{i=JSON.parse(n)}catch(o){if(!Qk.isObject(n))throw o;i=n}for(let o of i){let c=o[i_];if(!c)continue;let l=lr.get(js.DATABASES);l=l??{};let _=c?.tables?.[t]?.[hc.PATH];if(_)return qO.set(l,[i_,hc.TABLES,t,hc.PATH],_),lr.setProperty(js.DATABASES,l),_;let u=c?.[hc.PATH];if(u)return qO.set(l,[i_,hc.PATH],u),lr.setProperty(js.DATABASES,l),u}}let s=r[js.STORAGE_PATH.toUpperCase()];if(s){if(!FO.pathExistsSync(s))throw new Error(s+" does not exist");let i=gc.join(s,e);return FO.mkdirsSync(i),lr.setProperty(js.STORAGE_PATH,s),i}return VO()}a(Xk,"initSystemSchemaPaths");function jk(){mc=void 0,pc=void 0,Sc=void 0}a(jk,"resetPaths");KO.exports={getBaseSchemaPath:kO,getSystemSchemaPath:VO,getTransactionAuditStorePath:Jk,getTransactionAuditStoreBasePath:$O,getSchemaPath:YO,initSystemSchemaPaths:Xk,resetPaths:jk}});var vr=g((Voe,XO)=>{"use strict";var Zk=Ur().LMDB_ERRORS_ENUM,qoe=require("lmdb"),eV=dt(),koe=require("buffer").Buffer,{OVERFLOW_MARKER:WO,MAX_SEARCH_KEY_LENGTH:o_}=eV,QO=["number","string","symbol","boolean","bigint"];function tV(e){if(e=e?.primaryStore||e,!e)throw new Error(Zk.ENV_REQUIRED)}a(tV,"validateEnv");function rV(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(rV,"stringifyData");function nV(e){return e instanceof Date?e.valueOf():e}a(nV,"convertKeyValueToWrite");function sV(e,t){if(e===null)return t?[null]:void 0;if(e===void 0)return;if(QO.includes(typeof e))return e.length>o_?[e.slice(0,o_)+WO]:[e];let r;if(Array.isArray(e)){r=[];for(let n=0,s=e.length;n<s;n++){let i=e[n];if(QO.includes(typeof i))i.length>o_?r.push(i.slice(0,o_)+WO):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(sV,"getIndexedValues");var a_=0,zO=0;function JO(){zO=Date.now()-performance.now()}a(JO,"adjustStartTime");JO();var iV=6e4;setInterval(JO,iV).unref();function oV(){let e=performance.now()+zO;return e>a_?(a_=e,e):(a_+=488e-6,a_)}a(oV,"getNextMonotonicTime");XO.exports={validateEnv:tV,stringifyData:rV,convertKeyValueToWrite:nV,getNextMonotonicTime:oV,getIndexedValues:sV}});var jO,bn,Uh,Rc=Re(()=>{jO=require("events"),bn=class extends jO.EventEmitter{static{a(this,"IterableEventQueue")}resolveNext;queue;hasDataListeners;[Symbol.asyncIterator](){let t=new Uh;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(){return this.queue?.shift()}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)}},Uh=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}}}});var vi={};qe(vi,{server:()=>st});var ZO,st,ur=Re(()=>{ZO=require("../index"),st={};(0,ZO._assignPackageExport)("server",st)});var Hh={};qe(Hh,{loadGQLSchema:()=>lV,start:()=>Bh,startOnMainThread:()=>cV});function Bh({ensureTable:e}){return{handleFile:t,setupFile:t};async function t(r,n,s,i){let{parse:o,Source:c,Kind:l,NamedTypeNode:_,StringValueNode:u}=await import("graphql"),d=o(new c(r.toString(),s)),E=new Map,f=[],h;for(let S of d.definitions)switch(S.kind){case l.OBJECT_TYPE_DEFINITION:let H=function(v){if(v.kind==="NonNullType"){let Q=H(v.type);return Q.nullable=!1,Q}if(v.kind==="ListType")return{type:"array",elements:H(v.type)};let M={type:v.name?.value};return Object.defineProperty(M,"location",{value:v.loc.startToken}),M};a(H,"getProperty");let T=S.name.value,R=[],b={table:null,database:null,properties:R};E.set(T,b);for(let v of S.directives){if(v.name.value==="table"){for(let q of v.arguments)b[q.name.value]=q.value.value;b.schema&&(b.database=b.schema),b.table||(b.table=T),b.audit&&(b.audit=b.audit!=="false"),b.attributes=b.properties,f.push(b)}if(v.name.value==="sealed"&&(b.sealed=!0),v.name.value==="export"){b.export=!0;for(let q of v.arguments)q.name.value==="name"&&(b.export={name:q.value.value})}}let C=!1;for(let v of S.fields){let q=H(v.type);q.name=v.name.value,R.push(q);for(let M of v.directives)if(M.name.value==="primaryKey")C?console.warn("Can not define two attributes as a primary key"):(q.isPrimaryKey=!0,C=!0);else if(M.name.value==="indexed")q.indexed=!0;else if(M.name.value==="relationship"){let Q={};for(let J of M.arguments)Q[J.name.value]=J.value.value;q.relationship=Q}else if(M.name.value==="createdTime")q.assignCreatedTime=!0;else if(M.name.value==="updatedTime")q.assignUpdatedTime=!0;else if(M.name.value==="expiresAt")q.expiresAt=!0;else if(M.name.value==="allow"){let Q=q.authorizedRoles=[];for(let J of M.arguments)J.name.value==="role"&&Q.push(J.value.value)}}b.type=T,T==="Query"&&(h=b)}function p(S){let T=E.get(S.type);T?(Object.defineProperty(S,"properties",{value:T.properties}),Object.defineProperty(S,"definition",{value:T})):S.type==="array"?p(S.elements):aV.includes(S.type)||(0,eb.getWorkerIndex)()===0&&console.error(`The type ${S.type} is unknown at line ${S.location.line}, column ${S.location.column}, in ${s}`)}a(p,"connectPropertyType");for(let S of E.values())for(let T of S.properties)p(T);for(let S of f)S.tableClass=e(S),S.export&&(S.export.name===""?i.set((0,vh.dirname)(n),S.tableClass):i.set((0,vh.dirname)(n)+"/"+(S.export.name||S.type),S.tableClass))}}var vh,eb,aV,cV,lV,tb=Re(()=>{vh=require("path");Ae();eb=B(it()),aV=["ID","Int","Float","Long","String","Boolean","Date","Bytes","Any","BigInt"];a(Bh,"start");cV=Bh,lV=Bh({ensureTable:ft}).handleFile});async function c_(e){let t=(0,sb.pathToFileURL)(e).toString();return uV?(Ac||(Ac=_V(fV)),(await(await Ac).import(t)).namespace):import(t)}async function _V(e){let{StaticModuleRecord:t}=await import("@endo/static-module-record");return require("ses"),lockdown({domainTaming:"unsafe",consoleTaming:"unsafe",errorTaming:"unsafe",errorTrapping:"none",stackFiltering:"verbose"}),Ac=new Compartment({console,Math,Date,fetch:dV,...e()},{},{name:"h-dapp",resolveHook(r,n){return r==="harperdb"?"harperdb":(r=new URL(r,n).toString(),(0,nb.extname)(r)||(r+=".js"),r)},importHook:async r=>{if(r==="harperdb")return{imports:[],exports:["Resource","tables","databases"],execute(s){Object.assign(s,{Resource:$t,tables:Br,databases:ot})}};let n=await(0,rb.readFile)(new URL(r),{encoding:"utf-8"});return new t(n,r)}}),Ac}function dV(e,t){let r=typeof e=="string"||e.url;if(new URL(r).protocol!="https")throw new Error("Only https is allowed in fetch");return fetch(e,t)}function fV(){return{Resource:$t,tables:Br}}var rb,nb,sb,uV,Ac,xh=Re(()=>{yn();Ae();rb=require("fs/promises"),nb=require("path"),sb=require("url"),uV=!1;a(c_,"secureImport");a(_V,"getCompartment");a(dV,"secureOnlyFetch");a(fV,"getGlobalVars")});var Fh={};qe(Fh,{handleFile:()=>EV});async function EV(e,t,r,n){let s=new Map,i=await c_(r);c(i.default)&&n.set((0,Gh.dirname)(t),i.default),o(i,(0,Gh.dirname)(t));function o(l,_){for(let u in l){let d=l[u];c(d)?n.set(_+"/"+u,d):typeof d=="object"&&o(d,_+"/"+u)}}a(o,"recurseForResources");function c(l){return typeof l=="function"&&(l.get||l.put||l.post||l.delete)}return a(c,"isResource"),s}var Gh,ib=Re(()=>{xh();Gh=require("path");a(EV,"handleFile")});var kh={};qe(kh,{start:()=>hV});function hV({resources:e}){e.set("login",qh),e.loginPath=t=>"/login?redirect="+encodeURIComponent(t.url)}var qh,ob=Re(()=>{yn();a(hV,"start");qh=class extends $t{static{a(this,"Login")}static async get(t,r,n){}static async post(t,r,n){let{username:s,password:i,redirect:o}=r;return{data:await n.login(s,i)}}}});var fb={};qe(fb,{parse:()=>$h,streamAsJSON:()=>Oc,stringify:()=>Bi});function Oc(e){return new Vh({value:e})}function ab(e){return console.error(e),JSON.stringify(e.toString())}function cb(e,t,r){return e?.then?r?e.then(t,r):e.then(t):t(e)}function Bi(e){try{return JSON.stringify(e)??"null"}catch(t){if(t===_b)return db(e);if(t.resolution)return t.resolution.then(()=>Bi(e));throw t}}function db(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+=db(e[n]);return r+"]"}else{r="{";let n=!0;for(let s in e)n?n=!1:r+=",",r+=JSON.stringify(s)+":"+Bi(e[s]);return r+"}"}}else{if(t==="string")return JSON.stringify(e);if(t==="undefined")return"null"}return e.toString()}function $h(e){return SV.test(e)?mV.parse(e):JSON.parse(e)}var lb,ub,mV,pV,_b,Vh,SV,Yh=Re(()=>{lb=require("stream"),ub=B(require("json-bigint-fixes")),mV=(0,ub.default)({useNativeBigInt:!0}),pV=1e4,_b={};BigInt.prototype.toJSON=function(){throw _b};a(Oc,"streamAsJSON");Vh=class extends lb.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(;;)if(o=i.next(),o.then&&(yield o.then(c=>(o=c,""))),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),ab)}catch(s){yield ab(s)}else yield Bi(t)}else yield Bi(t)}_read(){if(!this._amReading){if(this._amReading=!0,this.done)return this.push(null);cb(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>pV?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 cb(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(ab,"handleError");a(cb,"when");a(Bi,"stringify");a(db,"jsStringify");SV=/[[,:]\s*-?\d{16,}/;a($h,"parse")});var Nb=g((iae,yb)=>{"use strict";var Kh=require("recursive-iterator"),TV=require("alasql"),Wh=require("clone"),Eb=z(),{handleHDBError:hb,hdb_errors:gV}=ne(),{HDB_ERROR_MSGS:mb,HTTP_STATUS_CODES:pb}=gV,{getDatabases:RV}=(Ae(),ie(ke)),AV=["DISTINCT_ARRAY"],Sb=Symbol("validateTables"),Qh=Symbol("validateTable"),sae=Symbol("getAllColumns"),Tb=Symbol("validateAllColumns"),l_=Symbol("findColumn"),gb=Symbol("validateOrderBy"),bc=Symbol("validateSegment"),zh=Symbol("validateColumn"),Rb=Symbol("setColumnsForTable"),Ab=Symbol("checkColumnsForAsterisk"),Ob=Symbol("validateGroupBy"),bb=Symbol("hasColumns"),Jh=class{static{a(this,"SelectValidator")}constructor(t){this.statement=t,this.attributes=[]}validate(){if(!this.statement)throw new Error("invalid sql statement");this[Sb](),this[Ab](),this[Tb]()}[Sb](){if(this[bb]()){if(!this.statement.from||this.statement.from.length===0)throw"no from clause";this.statement.from.forEach(t=>{this[Qh](t)}),this.statement.joins&&this.statement.joins.forEach(t=>{t.table.as=t.as,this[Qh](t.table)})}}[bb](){let t=!1,r=new Kh(this.statement);for(let{node:n,path:s}of r)if(n&&n.columnid){t=!0;break}return t}[Qh](t){if(!t.databaseid)throw`schema not defined for table ${t.tableid}`;let r=RV();if(!r[t.databaseid])throw hb(new Error,mb.SCHEMA_NOT_FOUND(t.databaseid),pb.NOT_FOUND);if(!r[t.databaseid][t.tableid])throw hb(new Error,mb.TABLE_NOT_FOUND(t.databaseid,t.tableid),pb.NOT_FOUND);r[t.databaseid][t.tableid].attributes.forEach(s=>{let i=Wh(s);i.table=Wh(t),this.attributes.push(i)})}[l_](t){return this.attributes.filter(r=>t.tableid?(r.table.as===t.tableid||r.table.tableid===t.tableid)&&r.attribute===t.columnid:r.attribute===t.columnid)}[Ab](){let t=new Kh(this.statement.columns);for(let{node:r,path:n}of t)r&&r.columnid==="*"&&n.indexOf("expression")<0&&this[Rb](r.tableid)}[Rb](t){this.attributes.forEach(r=>{(!t||t&&(r.table.tableid===t||r.table.as===t))&&!r.relation&&this.statement.columns.push(new TV.yy.Column({columnid:r.attribute,tableid:r.table.as?r.table.as:r.table.tableid}))})}[Tb](){this[bc](this.statement.columns,!1),this[bc](this.statement.joins,!1),this[bc](this.statement.where,!1),this[Ob](this.statement.group,!1),this[bc](this.statement.order,!0)}[bc](t,r){if(!t)return;let n=new Kh(t),s=[];for(let{node:i,path:o}of n)!Eb.isEmpty(i)&&!Eb.isEmpty(i.columnid)&&i.columnid!=="*"&&(r?this[gb](i):s.push(this[zh](i)));return s}[Ob](t){if(!t)return;let r=[];if(this.statement.columns.forEach(n=>{if(!(n.funcid&&AV.indexOf(n.funcid.toUpperCase())>=0)){if(!n.aggregatorid&&!n.columnid){let s=Wh(n);delete s.as,r.push(s)}else if(n.columnid){let s=this[l_](n)[0];s&&r.push(s)}}}),this.statement.group.forEach(n=>{let s=null;if(!n.columnid)r.forEach((i,o)=>{if(i.toString()===n.toString()){s=i,r.splice(o,1);return}});else{let i=this[l_](n);if(!i||i.length===0)throw`unknown column '${n.toString()}' in group by`;if(i.length>1)throw`ambiguously defined column '${n.toString()}' in group by`;r.forEach((o,c)=>{if(o.attribute===i[0].attribute&&o.table.tableid===i[0].table.tableid){s=o,r.splice(c,1);return}})}if(!s)throw`group by column '${n.toString()}' must be in select`}),r.length>0)throw`select column '${r[0].attribute?r[0].attribute:r[0].toString()}' must be in group by`}[gb](t){let r=this.statement.columns.filter(n=>n.as===t.columnid);if(r.length>1)throw`ambiguous column reference ${(t.tableid?t.tableid+".":"")+t.columnid} in order by`;r.length===0&&this[zh](t)}[zh](t){let r=this[l_](t),n=(t.tableid?t.tableid+".":"")+t.columnid;if(r.length===0)throw`unknown column ${n}`;if(r.length>1)throw`ambiguous column reference ${n}`;return r[0]}};yb.exports=Jh});var wb=g((aae,Ib)=>{"use strict";var Xh=class{static{a(this,"BridgeMethods")}createSchema(){throw new Error("createSchema bridge method is not defined")}dropSchema(){throw new Error("dropSchema bridge method is not defined")}createTable(){throw new Error("createTable bridge method is not defined")}dropTable(){throw new Error("dropTable bridge method is not defined")}createRecords(){throw new Error("createRecords bridge method is not defined")}updateRecords(){throw new Error("updateRecords bridge method is not defined")}async upsertRecords(){throw new Error("upsertRecords bridge method is not defined")}deleteRecords(){throw new Error("deleteRecords bridge method is not defined")}createAttribute(){throw new Error("createAttribute bridge method is not defined")}dropAttribute(){throw new Error("dropAttribute bridge method is not defined")}searchByConditions(){throw new Error("searchByConditions bridge method is not defined")}searchByHash(){throw new Error("searchByHash bridge method is not defined")}searchByValue(){throw new Error("searchByValue bridge method is not defined")}getDataByHash(){throw new Error("getDataByHash bridge method is not defined")}getDataByValue(){throw new Error("getDataByValue bridge method is not defined")}deleteRecordsBefore(){throw new Error("deleteRecordsBefore bridge method is not defined")}deleteAuditLogsBefore(){throw new Error("deleteAuditLogsBefore bridge method is not defined")}async readAuditLog(){throw new Error("readAuditLog bridge method is not defined")}};Ib.exports=Xh});var Db=g((lae,Cb)=>{"use strict";var jh=class{static{a(this,"DBIDefinition")}constructor(t=!1,r=!1){this.dup_sort=t,this.is_hash_attribute=r,this.useVersions=r}};Cb.exports=jh});var Ub={};qe(Ub,{HAS_EXPIRATION:()=>im,LAST_TIMESTAMP_PLACEHOLDER:()=>Ic,LOCAL_TIMESTAMP:()=>OV,METADATA:()=>yc,NO_TIMESTAMP:()=>em,PENDING_LOCAL_TIME:()=>om,PREVIOUS_TIMESTAMP_PLACEHOLDER:()=>sm,RecordEncoder:()=>nm,TIMESTAMP_ASSIGN_LAST:()=>yV,TIMESTAMP_ASSIGN_NEW:()=>Mb,TIMESTAMP_ASSIGN_PREVIOUS:()=>Pb,TIMESTAMP_PLACEHOLDER:()=>u_,TIMESTAMP_RECORD_PREVIOUS:()=>tm,getUpdateRecord:()=>am,handleLocalTimeForGets:()=>E_});function IV(){return Nc[0]=Nc[0]^64,bV.getFloat64(0)}function E_(e){let t=e.getEntry;e.readCount=0,e.cachePuts=!1,e.getEntry=function(i,o){e.readCount++;let c=t.call(this,i,o),l=c?.value,_=l?.[yc];return _>=0&&(c.metadataFlags=_,c.localTime=l.localTime,c.value=l.value,l.expiresAt>0&&(c.expiresAt=l.expiresAt)),c&&(c.key=i),c};let r=e.get;e.get=function(i,o){let c=r.call(this,i,o);return c?.[yc]>=0?c.value:c};let n=e.getRange;e.getRange=function(i){let o=n.call(this,i);return i.valuesForKey?o.map(c=>c?.value):i.values===!1||i.onlyCount?o:o.map(c=>{let l=c.value,_=l[yc];return _>=0&&(c.metadataFlags=_,c.localTime=l.localTime,c.value=l.value,l.expiresAt>0&&(c.expiresAt=l.expiresAt)),c})};let s=e.useReadTransaction();if(s.done(),!s.done.isTracked){let i=s.constructor,o=s.use,c=s.done;i.prototype.use=function(){this.timerTracked||(this.timerTracked=!0,Hi.push(new WeakRef(this))),o.call(this)},i.prototype.done=function(){if(c.call(this),this.isDone)for(let l=0;l<Hi.length;l++){let _=Hi[l].deref();(!_||_.isDone||_.isCommitted)&&Hi.splice(l--,1)}},i.prototype.done.isTracked=!0}return e}function am(e,t,r){return function(n,s,i,o,c=-1,l,_,u,d="put",E,f){if(E||l==null?qo=i?.localTime?tm|Pb:em:qo=l?i?.localTime?tm|16384:Mb|16384:em,u>0&&(c|=im),d_=c,rm=u,i?.version===o&&l===!1)throw new Error("Must retain local time if version is not changed");let h={version:o,instructedWrite:qo>0},p;try{E&&(h.ifVersion=p=i?.version??null);let S=e.put(n,s,h);if(l){let T=_?.user?.username;if(f&&(__=e.encoder.encode(f)),E&&i?.localTime){let R=i?.localTime,b=r.get(R);if(b){let C=vt(b).previousLocalTime;return r.put(R,f_(o,t,n,C,T,d,__),{ifVersion:p}),S}}r.put(Ic,f_(o,t,n,i?.localTime?1:0,T,d,__),{append:d!=="invalidate",instructedWrite:!0,ifVersion:p})}return S}catch(S){throw S.message+=" id: "+n+" options: "+h,S}}}var Lb,Zh,u_,Ic,sm,OV,yc,Nc,bV,em,Mb,yV,Pb,tm,im,om,NV,__,qo,d_,rm,nm,Hi,wc=Re(()=>{Lb=require("msgpackr");Zs();Zh=B(K()),u_=new Uint8Array([1,1,1,1,4,64,0,0]),Ic=new Uint8Array([1,1,1,1,1,0,0,0]),sm=new Uint8Array([1,1,1,1,3,64,0,0]),OV=Symbol("local-timestamp"),yc=Symbol("metadata"),Nc=new Uint8Array(8),bV=new DataView(Nc.buffer,0,8),em=0,Mb=0,yV=1,Pb=3,tm=4,im=16,om=1,qo=0,d_=-1,rm=0,nm=class extends Lb.Encoder{static{a(this,"RecordEncoder")}constructor(t){t.useBigIntExtension=!0,super(t);let r=this.encode;this.encode=function(n,s){if(qo||d_>=0){let i=0,o=qo;o&&(i+=8,qo=0);let c=d_,l=rm;c>=0&&(i+=2,d_=-1,l&&(i+=8,rm=0));let _=NV=r.call(this,n,s|2048|i);__=_.subarray((_.start||0)+i,_.end);let u=_.start||0;return o&&(u_[4]=o,u_[5]=o>>8,_.set(u_,u),u+=8),c>=0&&(_[u++]=c,_[u++]=0,l&&(_.dataView||(_.dataView=new DataView(_.buffer,_.byteOffset,_.byteLength))).setFloat64(u,l)),_}else return r.call(this,n,s)}}decode(t,r){let n=r?.start||0,s=r>-1?r:r?.end||t.length,i=t[n],o=0;try{if(i<32&&s>2){let c=n,l;if(i===2){if(t.copy)t.copy(Nc,0,c),c+=8;else for(let d=0;d<8;d++)Nc[d]=t[c++];l=IV(),i=t[c]}let _;i<32&&(o=i,c+=2,o&im&&(_=(t.dataView||(t.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength))).getFloat64(c),c+=8));let u=super.decode(t.subarray(c,s),s-c);return{localTime:l,value:u,[yc]:o,expiresAt:_}}return super.decode(t,r)}catch(c){throw c.message+=", data: "+t.slice(0,40).toString("hex"),c}}};a(IV,"getTimestamp");a(E_,"handleLocalTimeForGets");Hi=[];setInterval(()=>{for(let e=0;e<Hi.length;e++){let t=Hi[e].deref();!t||t.isDone||t.isCommitted?Hi.splice(e--,1):t.notCurrent&&(t.openTimer?(t.openTimer>3&&(t.openTimer>60?(Zh.error("Read transaction detected that has been open too long (over 15 minutes), ending transaction",t),t.done()):Zh.error("Read transaction detected that has been open too long (over one minute), make sure read transactions are quickly closed",t)),t.openTimer++):t.openTimer=1)}},15e3).unref();a(am,"getUpdateRecord")});var Cc=g((Eae,Bb)=>{"use strict";var vb=te(),wV=U(),{RecordEncoder:CV}=(wc(),ie(Ub)),fae=require("fs");vb.initSync();var DV=vb.get(wV.CONFIG_PARAMS.STORAGE_CACHING)!==!1,cm=class{static{a(this,"OpenDBIObject")}constructor(t,r=!1){this.dupSort=t===!0,this.encoding=t?"ordered-binary":"msgpack",this.useVersions=r,this.sharedStructuresKey=Symbol.for("structures"),r&&(this.cache=DV&&{validated:!0},this.randomAccessStructure=!0,this.freezeData=!0,this.encoder={Encoder:CV})}};Bb.exports=cm});var Dc=g((mae,Hb)=>{"use strict";var Hr=te(),an=U();Hr.initSync();var h_=class{static{a(this,"OpenEnvironmentObject")}constructor(t,r=!1){this.path=t,this.mapSize=1073741824,this.maxDbs=1e4,this.maxReaders=1e3,this.sharedStructuresKey=Symbol.for("structures"),this.readOnly=r,this.trackMetrics=!0,this.eventTurnBatching=!1,this.noSync=Hr.get(an.CONFIG_PARAMS.STORAGE_WRITEASYNC)===!0||Hr.get(an.CONFIG_PARAMS.STORAGE_WRITEASYNC)==="true"||Hr.get(an.CONFIG_PARAMS.STORAGE_WRITEASYNC)==="TRUE",Hr.get(an.CONFIG_PARAMS.STORAGE_OVERLAPPINGSYNC)!==void 0&&(this.overlappingSync=Hr.get(an.CONFIG_PARAMS.STORAGE_OVERLAPPINGSYNC)),Hr.get(an.CONFIG_PARAMS.STORAGE_MAXFREESPACETOLOAD)&&(this.maxFreeSpaceToLoad=Hr.get(an.CONFIG_PARAMS.STORAGE_MAXFREESPACETOLOAD)),Hr.get(an.CONFIG_PARAMS.STORAGE_MAXFREESPACETORETAIN)&&(this.maxFreeSpaceToRetain=Hr.get(an.CONFIG_PARAMS.STORAGE_MAXFREESPACETORETAIN)),Hr.get(an.CONFIG_PARAMS.STORAGE_PAGESIZE)&&(this.pageSize=Hr.get(an.CONFIG_PARAMS.STORAGE_PAGESIZE)),this.noReadAhead=Hr.get(an.CONFIG_PARAMS.STORAGE_NOREADAHEAD)}};Hb.exports=h_;h_.MAX_DBS=1e4});var Ke=g((Sae,Wb)=>{"use strict";var um=require("lmdb"),Nn=require("fs-extra"),xr=require("path"),m_=vr(),Fb=K(),_r=Ur().LMDB_ERRORS_ENUM,p_=Db(),_m=Cc(),qb=Dc(),ei=dt(),xb=U(),{table:LV,resetDatabases:MV}=(Ae(),ie(ke)),Gb=te(),In=ei.INTERNAL_DBIS_NAME,kb=ei.DBI_DEFINITION_NAME,PV="data.mdb",UV="lock.mdb",Lc=".mdb",vV="-lock",lm=class{static{a(this,"TransactionCursor")}constructor(t,r,n=!1){this.dbi=cn(t,r),this.key_type=this.dbi[ei.DBI_DEFINITION_NAME].key_type,this.is_hash_attribute=this.dbi[ei.DBI_DEFINITION_NAME].is_hash_attribute,this.txn=t.beginTxn({readOnly:n===!1}),this.cursor=new um.Cursor(this.txn,this.dbi)}close(){this.cursor.close(),this.txn.abort()}commit(){this.cursor.close(),this.txn.commit()}};function S_(e,t){if(e===void 0)throw new Error(_r.BASE_PATH_REQUIRED);if(t===void 0)throw new Error(_r.ENV_NAME_REQUIRED)}a(S_,"pathEnvNameValidation");async function dm(e,t,r=!0){try{await Nn.access(e)}catch(n){throw n.code==="ENOENT"?new Error(_r.INVALID_BASE_PATH):n}try{let n=xr.join(e,t+Lc);return await Nn.access(n,Nn.constants.R_OK|Nn.constants.F_OK),n}catch(n){if(n.code==="ENOENT")if(r)try{return await Nn.access(xr.join(e,t,PV),Nn.constants.R_OK|Nn.constants.F_OK),xr.join(e,t)}catch(s){if(s.code==="ENOENT")throw new Error(_r.INVALID_ENVIRONMENT)}else throw new Error(_r.INVALID_ENVIRONMENT);throw n}}a(dm,"validateEnvironmentPath");function T_(e,t){if(m_.validateEnv(e),t===void 0)throw new Error(_r.DBI_NAME_REQUIRED)}a(T_,"validateEnvDBIName");async function BV(e,t,r=!1,n=!1){S_(e,t);let s=xr.basename(e);t=t.toString();let i=Gb.get(xb.CONFIG_PARAMS.DATABASES);i||Gb.setProperty(xb.CONFIG_PARAMS.DATABASES,i={}),i[s]||(i[s]={}),i[s].path=e;try{return await dm(e,t,n),Vb(e,t,r)}catch(o){if(o.message===_r.INVALID_ENVIRONMENT){let c=xr.join(e,t);await Nn.mkdirp(n?c:e);let l=new qb(n?c:c+Lc,!1),_=um.open(l);_.dbis=Object.create(null);let u=new _m(!1);_.openDB(In,u),global.lmdb_map===void 0&&(global.lmdb_map=Object.create(null));let d=fm(e,t,r);return _[ei.ENVIRONMENT_NAME_KEY]=d,global.lmdb_map[d]=_,_}throw o}}a(BV,"createEnvironment");async function HV(e,t,r,n=!0){S_(e,t),t=t.toString();let s=xr.join(e,t);return LV({table:t,database:xr.parse(e).name,path:s,attributes:[{name:"id",isPrimaryKey:!0}]})}a(HV,"copyEnvironment");async function Vb(e,t,r=!1){S_(e,t),t=t.toString();let n=fm(e,t,r);if(global.lmdb_map===void 0&&(global.lmdb_map=Object.create(null)),global.lmdb_map[n]!==void 0)return global.lmdb_map[n];let s=await dm(e,t),i=xr.join(e,t+Lc),o=s!=i,c=new qb(s,o),l=um.open(c);l.dbis=Object.create(null);let _=Yb(l);for(let u=0;u<_.length;u++)cn(l,_[u]);return l[ei.ENVIRONMENT_NAME_KEY]=n,global.lmdb_map[n]=l,l}a(Vb,"openEnvironment");async function xV(e,t,r=!1){S_(e,t),t=t.toString();let n=xr.join(e,t+Lc),s=await dm(e,t);if(global.lmdb_map!==void 0){let i=fm(e,t,r);if(global.lmdb_map[i]){let o=global.lmdb_map[i];await $b(o),delete global.lmdb_map[i]}}await Nn.remove(s),await Nn.remove(s===n?s+vV:xr.join(xr.dirname(s),UV))}a(xV,"deleteEnvironment");async function $b(e){m_.validateEnv(e);let t=e[ei.ENVIRONMENT_NAME_KEY];await e.close(),t!==void 0&&global.lmdb_map!==void 0&&delete global.lmdb_map[t]}a($b,"closeEnvironment");function fm(e,t,r=!1){let s=`${xr.basename(e)}.${t}`;return r===!0&&(s=`txn.${s}`),s}a(fm,"getCachedEnvironmentName");function GV(e){m_.validateEnv(e);let t=Object.create(null),r=cn(e,In);for(let{key:n,value:s}of r.getRange({start:!1}))if(n!==In)try{t[n]=Object.assign(new p_,s)}catch{Fb.warn(`an internal error occurred: unable to parse DBI Definition for ${n}`)}return t}a(GV,"listDBIDefinitions");function Yb(e){m_.validateEnv(e);let t=[],r=cn(e,In);for(let{key:n}of r.getRange({start:!1}))n!==In&&t.push(n);return t}a(Yb,"listDBIs");function FV(e,t){let n=cn(e,In).getEntry(t),s=new p_;if(n!==void 0){try{s=Object.assign(s,n.value)}catch{Fb.warn(`an internal error occurred: unable to parse DBI Definition for ${n}`)}return s}}a(FV,"getDBIDefinition");function Kb(e,t,r,n=!r){if(T_(e,t),t=t.toString(),t===In)throw new Error(_r.CANNOT_CREATE_INTERNAL_DBIS_NAME);try{return cn(e,t)}catch(s){if(s.message===_r.DBI_DOES_NOT_EXIST){let i=new _m(r,n===!0),o=e.openDB(t,i),c=new p_(r===!0,n);return o[kb]=c,cn(e,In).putSync(t,c),e.dbis[t]=o,o}throw s}}a(Kb,"createDBI");function cn(e,t){if(T_(e,t),t=t.toString(),e.dbis[t]!==void 0)return e.dbis[t];let r;if(t!==In?r=FV(e,t):r=new p_,r===void 0)throw new Error(_r.DBI_DOES_NOT_EXIST);let n;try{let s=new _m(r.dup_sort,r.useVersions);if(n=e.openDB(t,s),n.db===void 0)throw new Error("MDB_NOTFOUND")}catch(s){throw s.message.includes("MDB_NOTFOUND")===!0?new Error(_r.DBI_DOES_NOT_EXIST):s}return n[kb]=r,e.dbis[t]=n,n}a(cn,"openDBI");function qV(e,t){T_(e,t),t=t.toString();let r=cn(e,t),n=r.getStats();return r[ei.DBI_DEFINITION_NAME].is_hash_attribute&&n.entryCount>0&&n.entryCount--,n}a(qV,"statDBI");async function kV(e,t){try{let r=xr.join(e,t+Lc);return(await Nn.stat(r)).size}catch{throw new Error(_r.INVALID_ENVIRONMENT)}}a(kV,"environmentDataSize");function VV(e,t){if(T_(e,t),t=t.toString(),t===In)throw new Error(_r.CANNOT_DROP_INTERNAL_DBIS_NAME);cn(e,t).dropSync(),e.dbis!==void 0&&delete e.dbis[t],cn(e,In).removeSync(t)}a(VV,"dropDBI");function $V(e,t,r){let n;for(let s=0;s<r.length;s++){let i=r[s];if(!e.dbis[i])try{cn(e,i)}catch(o){if(o.message===_r.DBI_DOES_NOT_EXIST)Kb(e,i,i!==t,i===t),n=!0;else throw o}}n&&MV()}a($V,"initializeDBIs");Wb.exports={openDBI:cn,openEnvironment:Vb,createEnvironment:BV,listDBIs:Yb,listDBIDefinitions:GV,createDBI:Kb,dropDBI:VV,statDBI:qV,deleteEnvironment:xV,initializeDBIs:$V,TransactionCursor:lm,environmentDataSize:kV,copyEnvironment:HV,closeEnvironment:$b}});var zb=g((gae,Qb)=>{"use strict";var Em=class{static{a(this,"InsertRecordsResponseObject")}constructor(t=[],r=[],n=void 0){this.written_hashes=t,this.skipped_hashes=r,this.txn_time=n}};Qb.exports=Em});var Xb=g((Aae,Jb)=>{"use strict";var hm=class{static{a(this,"UpdateRecordsResponseObject")}constructor(t=[],r=[],n=void 0,s=[]){this.written_hashes=t,this.skipped_hashes=r,this.txn_time=n,this.original_records=s}};Jb.exports=hm});var Zb=g((bae,jb)=>{"use strict";var mm=class{static{a(this,"UpsertRecordsResponseObject")}constructor(t=[],r=void 0,n=[]){this.written_hashes=t,this.txn_time=r,this.original_records=n}};jb.exports=mm});var ko=g((Cae,ry)=>{"use strict";var YV=Ke(),KV=zb(),WV=Xb(),QV=Zb(),Wn=vr(),Mc=Ur().LMDB_ERRORS_ENUM,zV=dt(),Ts=U(),JV=z(),XV=require("uuid"),Nae=require("lmdb"),{handleHDBError:jV,hdb_errors:ZV}=ne(),{OVERFLOW_MARKER:Iae,MAX_SEARCH_KEY_LENGTH:wae}=zV,ey=te();ey.initSync();var g_=ey.get(Ts.CONFIG_PARAMS.STORAGE_PREFETCHWRITES),pm=Ts.TIME_STAMP_NAMES_ENUM.CREATED_TIME,xi=Ts.TIME_STAMP_NAMES_ENUM.UPDATED_TIME;async function e$(e,t,r,n,s=Wn.getNextMonotonicTime()){Rm(e,t,r,n),Sm(e,t,r);let i=new KV,o=[],c=[];for(let l=0;l<n.length;l++){let _=n[l];ty(_,!0,s);let u=t$(e,t,r,_),d=_[t];o.push(u),c.push(d)}return Tm(o,c,n,i,s)}a(e$,"insertRecords");function t$(e,t,r,n){let s=n[t];return e.dbis[t].ifNoExists(s,()=>{for(let i=0;i<r.length;i++){let o=r[i];if(o===t||n.hasOwnProperty(o)===!1)continue;let c=n[o];if(typeof c=="function"){let u=c([[{}]]);Array.isArray(u)&&(c=u[0][Ts.FUNC_VAL],n[o]=c)}let l=Wn.getIndexedValues(c),_=e.dbis[o];if(l){g_&&_.prefetch(l.map(u=>({key:u,value:s})),R_);for(let u=0,d=l.length;u<d;u++)_.put(l[u],s)}}g_&&e.dbis[t].prefetch([s],R_),e.dbis[t].put(s,n,n[xi])})}a(t$,"insertRecord");function r$(e,t=[]){let r=0;for(let n=0;n<t.length;n++){let s=t[n];e.splice(s-r,1),r++}}a(r$,"removeSkippedRecords");function ty(e,t,r){let n=r>0;(n||!Number.isInteger(e[xi]))&&(e[xi]=r||(r=Wn.getNextMonotonicTime())),t===!0?(n||!Number.isInteger(e[pm]))&&(e[pm]=r||Wn.getNextMonotonicTime()):delete e[pm]}a(ty,"setTimestamps");function Sm(e,t,r){r.indexOf(Ts.TIME_STAMP_NAMES_ENUM.CREATED_TIME)<0&&r.push(Ts.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.indexOf(Ts.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)<0&&r.push(Ts.TIME_STAMP_NAMES_ENUM.UPDATED_TIME),YV.initializeDBIs(e,t,r)}a(Sm,"initializeTransaction");async function n$(e,t,r,n,s=Wn.getNextMonotonicTime()){Rm(e,t,r,n),Sm(e,t,r);let i=new WV,o=[],c=[],l=[];for(let _=0;_<n.length;_++){let u=n[_],d=u[t],E;try{E=gm(e,t,u,d,i,!0,s)}catch{i.skipped_hashes.push(d),o.push(_);continue}c.push(E),l.push(d)}return Tm(c,l,n,i,s,o)}a(n$,"updateRecords");async function s$(e,t,r,n,s=Wn.getNextMonotonicTime()){try{Rm(e,t,r,n)}catch(l){throw jV(l,l.message,ZV.HTTP_STATUS_CODES.BAD_REQUEST)}Sm(e,t,r);let i=new QV,o=[],c=[];for(let l=0;l<n.length;l++){let _=n[l],u;JV.isEmpty(_[t])?(u=XV.v4(),_[t]=u):u=_[t];let d=gm(e,t,_,u,i,!1,s);o.push(d),c.push(u)}return Tm(o,c,n,i,s)}a(s$,"upsertRecords");async function Tm(e,t,r,n,s,i=[]){let o=await Promise.all(e);for(let c=0,l=o.length;c<l;c++)o[c]===!0?n.written_hashes.push(t[c]):(n.skipped_hashes.push(t[c]),i.push(c));return n.txn_time=s||Wn.getNextMonotonicTime(),r$(r,i),n}a(Tm,"finalizeWrite");function gm(e,t,r,n,s,i=!1,o){let c=e.dbis[t],l=c.getEntry(n),_=l?.value,u=_;if(!_){if(i)return!1;_={}}if(ty(r,!u,o),Number.isInteger(r[xi])&&_[xi]>r[xi])return!1;u&&s.original_records.push(_);let d,E=a(()=>{for(let h in r){if(!r.hasOwnProperty(h)||h===t)continue;let p=r[h],S=e.dbis[h];if(S===void 0)continue;let T=_[h];if(typeof p=="function"){let b=p([[_]]);Array.isArray(b)&&(p=b[0][Ts.FUNC_VAL],r[h]=p)}if(p===T)continue;let R=Wn.getIndexedValues(T);if(R){g_&&S.prefetch(R.map(b=>({key:b,value:n})),R_);for(let b=0,C=R.length;b<C;b++)S.remove(R[b],n)}if(R=Wn.getIndexedValues(p),R){g_&&S.prefetch(R.map(b=>({key:b,value:n})),R_);for(let b=0,C=R.length;b<C;b++)S.put(R[b],n)}}let f=Object.assign({},_,r);c.put(n,f,f[xi])},"do_put");return l?d=c.ifVersion(n,l.version,E):d=c.ifNoExists(n,E),d.then(f=>f?!0:gm(e,t,r,n,s,i,o))}a(gm,"updateUpsertRecord");function i$(e,t,r){if(Wn.validateEnv(e),t===void 0)throw new Error(Mc.HASH_ATTRIBUTE_REQUIRED);if(!Array.isArray(r))throw r===void 0?new Error(Mc.WRITE_ATTRIBUTES_REQUIRED):new Error(Mc.WRITE_ATTRIBUTES_MUST_BE_ARRAY)}a(i$,"validateBasic");function Rm(e,t,r,n){if(i$(e,t,r),!Array.isArray(n))throw n===void 0?new Error(Mc.RECORDS_REQUIRED):new Error(Mc.RECORDS_MUST_BE_ARRAY)}a(Rm,"validateWrite");function R_(){}a(R_,"noop");ry.exports={insertRecords:e$,updateRecords:n$,upsertRecords:s$}});var Gi=g((Lae,o$)=>{o$.exports={hdb_table:{hash_attribute:"id",name:"hdb_table",schema:"system",residence:["*"],attributes:[{attribute:"id"},{attribute:"name"},{attribute:"hash_attribute"},{attribute:"schema"},{attribute:"residence"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_attribute:{hash_attribute:"id",name:"hdb_attribute",schema:"system",residence:["*"],attributes:[{attribute:"id"},{attribute:"schema"},{attribute:"table"},{attribute:"attribute"},{attribute:"schema_table"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_schema:{hash_attribute:"name",name:"hdb_schema",schema:"system",residence:["*"],attributes:[{attribute:"name"},{attribute:"createddate"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_user:{hash_attribute:"username",name:"hdb_user",schema:"system",residence:["*"],attributes:[{attribute:"username"},{attribute:"password"},{attribute:"role"},{attribute:"active"},{attribute:"hash"},{attribute:"refresh_token"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_role:{hash_attribute:"id",name:"hdb_role",schema:"system",attributes:[{attribute:"id"},{attribute:"role"},{attribute:"permission"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}],residence:["*"]},hdb_job:{hash_attribute:"id",name:"hdb_job",schema:"system",attributes:[{attribute:"id"},{attribute:"user"},{attribute:"type"},{attribute:"status"},{attribute:"start_datetime"},{attribute:"end_datetime"},{attribute:"message"},{attribute:"created_datetime"},{attribute:"request"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_license:{hash_attribute:"license_key",name:"hdb_license",schema:"system",attributes:[{attribute:"license_key"},{attribute:"company"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_info:{hash_attribute:"info_id",name:"hdb_info",schema:"system",attributes:[{attribute:"info_id"},{attribute:"data_version_num"},{attribute:"hdb_version_num"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_nodes:{hash_attribute:"name",name:"hdb_nodes",schema:"system",attributes:[{attribute:"name"},{attribute:"subscriptions"},{attribute:"system_info"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_analytics:{hash_attribute:"id",name:"hdb_analytics",schema:"system",audit:!1,attributes:[{attribute:"id"},{name:"metric"},{name:"path"},{name:"method"},{name:"type"}]},hdb_raw_analytics:{hash_attribute:"id",name:"hdb_raw_analytics",schema:"system",audit:!1,attributes:[{attribute:"id"},{attribute:"time"},{attribute:"metrics"}]},hdb_temp:{hash_attribute:"id",name:"hdb_temp",schema:"system",attributes:[{attribute:"id"}]},hdb_durable_session:{hash_attribute:"id",name:"hdb_durable_session",schema:"system",attributes:[{attribute:"id"}]},hdb_session_will:{hash_attribute:"id",name:"hdb_session_will",schema:"system",attributes:[{attribute:"id"}]}}});var zn=g((Mae,iy)=>{"use strict";var sy=z(),ny=U(),Vo=/^[\x20-\x2E|\x30-\x5F|\x61-\x7E]*$/,Qn=require("joi"),ti={schema_format:{pattern:Vo,message:"names cannot include backticks or forward slashes"},schema_length:{minimum:1,maximum:250,tooLong:"cannot exceed 250 characters"}},a$=Qn.alternatives(Qn.string().min(1).max(ti.schema_length.maximum).pattern(Vo).messages({"string.pattern.base":"{:#label} "+ti.schema_format.message}),Qn.number(),Qn.array()).required(),c$=Qn.alternatives(Qn.string().min(1).max(ti.schema_length.maximum).pattern(Vo).messages({"string.pattern.base":"{:#label} "+ti.schema_format.message}),Qn.number()),l$=Qn.alternatives(Qn.string().min(1).max(ti.schema_length.maximum).pattern(Vo).messages({"string.pattern.base":"{:#label} "+ti.schema_format.message}),Qn.number()).required();function u$(e,t){return t?typeof t!="string"?`'${e}' must be a string`:t.length?t.length>ti.schema_length.maximum?`'${e}' maximum of 250 characters`:Vo.test(t)?"":`'${e}' has illegal characters`:`'${e}' must be at least one character`:`'${e}' is required`}a(u$,"checkValidTable");function _$(e,t){return sy.doesSchemaExist(e)?e:t.message(`Database '${e}' does not exist`)}a(_$,"validateSchemaExists");function d$(e,t){let r=t.state.ancestors[0].schema;return sy.doesTableExist(r,e)?e:t.message(`Table '${e}' does not exist`)}a(d$,"validateTableExists");function f$(e,t){return e.toLowerCase()===ny.SYSTEM_SCHEMA_NAME?t.message(`'subscriptions[${t.state.path[1]}]' invalid database name, '${ny.SYSTEM_SCHEMA_NAME}' name is reserved`):e}a(f$,"validateSchemaName");iy.exports={common_validators:ti,schema_regex:Vo,hdb_schema_table:a$,validateSchemaExists:_$,validateTableExists:d$,validateSchemaName:f$,checkValidTable:u$,hdb_database:c$,hdb_table:l$}});var at=g((Uae,oy)=>{"use strict";var dr=require("validate.js");dr.validators.type=function(e,t,r,n){return e===null||typeof e>"u"||dr.validators.type.checks[t](e)?null:` must be a '${t}' value`};dr.validators.type.checks={Object:function(e){return dr.isObject(e)&&!dr.isArray(e)},Array:dr.isArray,Integer:dr.isInteger,Number:dr.isNumber,String:dr.isString,Date:dr.isDate,Boolean:function(e){return typeof e=="boolean"}};dr.validators.hasValidFileExt=function(e,t){return dr.isString(e)?e===""?"can't be blank":t.filter(r=>e.endsWith(r)).length>0?null:`must include one of the following valid file extensions - '${t.join("', '")}'`:null};oy.exports={validateObject:E$,validateObjectAsync:h$,validateBySchema:m$};function E$(e,t){if(!e||!t)return new Error("validateObject parameters were null");let r=dr(e,t,{format:"flat"});return r?new Error(r):null}a(E$,"validateObject");async function h$(e,t){if(!e||!t)return new Error("validateObject parameters were null");try{await dr.async(e,t,{format:"flat"})}catch(r){let n=r.join(",");return new Error(n)}return null}a(h$,"validateObjectAsync");function m$(e,t){let r=t.validate(e,{allowUnknown:!0,abortEarly:!1,errors:{wrap:{label:"'"}}});if(r.error)return new Error(r.error.message)}a(m$,"validateBySchema")});var A_=g((Bae,ay)=>{var{common_validators:Jn}=zn(),Uc=at(),Pc="is required",Tt={database:{presence:!1,format:Jn.schema_format,length:Jn.schema_length},schema:{presence:!1,format:Jn.schema_format,length:Jn.schema_length},table:{presence:!0,format:Jn.schema_format,length:Jn.schema_length},attribute:{presence:!0,format:Jn.schema_format,length:Jn.schema_length},hash_attribute:{presence:!0,format:Jn.schema_format,length:Jn.schema_length}};function vc(e){for(let t in e)e[t]=e[t]===null||e[t]===void 0||typeof e[t]=="object"?e[t]:e[t].toString();return e}a(vc,"makeAttributesStrings");function p$(e){return e=vc(e),Tt.table.presence=!1,Tt.attribute.presence=!1,Tt.hash_attribute.presence=!1,Uc.validateObject(e,Tt)}a(p$,"schema_object");function S$(e){return e=vc(e),Tt.table.presence={message:Pc},Tt.attribute.presence=!1,Tt.hash_attribute.presence=!1,Uc.validateObject(e,Tt)}a(S$,"table_object");function T$(e){return e=vc(e),Tt.table.presence={message:Pc},Tt.attribute.presence=!1,Uc.validateObject(e,Tt)}a(T$,"create_table_object");function g$(e){return e=vc(e),Tt.table.presence={message:Pc},Tt.attribute.presence={message:Pc},Tt.hash_attribute.presence=!1,Uc.validateObject(e,Tt)}a(g$,"attribute_object");function R$(e){return e=vc(e),Tt.table.presence={message:Pc},Tt.attribute.presence=!1,Tt.hash_attribute.presence=!1,Uc.validateObject(e,Tt)}a(R$,"describe_table");function A$(e){if(e){if(!Array.isArray(e))throw new Error("residence must be a string array");if(e.length===0)throw new Error("residence cannot be an empty array");for(let t=0;t<e.length;t++)if(typeof e[t]!="string")throw new Error(`residence must be a string array, item '${e[t]}' is not a string`)}}a(A$,"validateTableResidence");ay.exports={schema_object:p$,create_table_object:T$,table_object:S$,attribute_object:g$,describe_table:R$,validateTableResidence:A$}});var ly=g((xae,cy)=>{"use strict";var O$=require("uuid"),Am=class{static{a(this,"CreateAttributeObject")}constructor(t,r,n,s){this.schema=t,this.table=r,this.attribute=n,this.id=s||O$.v4(),this.schema_table=`${this.schema}.${this.table}`}};cy.exports=Am});var O_=g((Fae,uy)=>{"use strict";var b$=ly(),Om=class extends b${static{a(this,"LMDBCreateAttributeObject")}constructor(t,r,n,s,i=!0,o=!1){super(t,r,n,s),this.dup_sort=i,this.is_hash_attribute=o}};uy.exports=Om});var dy=g((kae,_y)=>{"use strict";_y.exports=N$;var y$="inserted";function N$(e,t,r,n){let s={message:`${e} ${t.length} of ${r.records.length} records`,skipped_hashes:n};return e===y$?(s.inserted_hashes=t,s):(s.update_hashes=t,s)}a(N$,"returnObject")});var b_=g(($ae,py)=>{"use strict";var I$=U(),bm=Ke(),w$=ko(),{getSystemSchemaPath:C$,getSchemaPath:D$}=ze(),L$=Gi(),M$=A_(),P$=O_(),U$=dy(),{handleHDBError:fy,hdb_errors:hy}=ne(),Ey=z(),{HTTP_STATUS_CODES:v$}=hy,ym=L$.hdb_attribute,my=[];for(let e=0;e<ym.attributes.length;e++)my.push(ym.attributes[e].attribute);var B$="inserted";py.exports=H$;async function H$(e){let t=M$.attribute_object(e);if(t)throw fy(new Error,t.message,hy.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0);let r=!e.skip_table_check&&Ey.checkGlobalSchemaTable(e.schema,e.table);if(r)throw fy(new Error,r,v$.NOT_FOUND);e.is_hash_attribute=e.is_hash_attribute=="true",e.dup_sort=Ey.isEmpty(e.dup_sort)||e.dup_sort=="true";let n=[];if(global.hdb_schema[e.schema]&&global.hdb_schema[e.schema][e.table]&&(n=global.hdb_schema[e.schema][e.table].attributes),Array.isArray(n)&&n.length>0){for(let i of n)if(i.attribute===e.attribute)throw new Error(`attribute '${i.attribute}' already exists in ${e.schema}.${e.table}`)}let s=new P$(e.schema,e.table,e.attribute,e.id);try{let i=await bm.openEnvironment(D$(e.schema,e.table),e.table);if(i.dbis[e.attribute]!==void 0)throw new Error(`attribute '${e.attribute}' already exists in ${e.schema}.${e.table}`);bm.createDBI(i,e.attribute,e.dup_sort,e.is_hash_attribute);let o=await bm.openEnvironment(C$(),I$.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME),{written_hashes:c,skipped_hashes:l}=await w$.insertRecords(o,ym.hash_attribute,my,[s]);return U$(B$,c,{records:[s]},l)}catch(i){throw i}}a(H$,"lmdbCreateAttribute")});var Im=g((Kae,Ty)=>{var{hdb_table:x$,hdb_database:Sy}=zn(),G$=at(),Nm=require("joi"),F$={undefined:"undefined",null:"null"},q$=a((e,t)=>{let r=Object.keys(e),n=r.length,s;for(let i=0;i<n;i++){let o=r[i];(!o||o.length===0||F$[o]!==void 0)&&(s===void 0?s=`Invalid attribute name: '${o}'`:s+=`. Invalid attribute name: '${o}'`)}return s?t.message(s):e},"custom_records_val"),k$=Nm.object({database:Sy,schema:Sy,table:x$,records:Nm.array().items(Nm.object().custom(q$)).required()});Ty.exports=function(e){return G$.validateBySchema(e,k$)}});var Bc=g((zae,Ry)=>{"use strict";var gs=z(),gy=K(),Qae=Im(),{getDatabases:V$}=(Ae(),ie(ke)),{ClientError:Fi}=ne();Ry.exports=$$;function $$(e){if(gs.isEmpty(e))throw new Fi("invalid update parameters defined.");if(gs.isEmptyOrZeroLength(e.schema))throw new Fi("invalid schema specified.");if(gs.isEmptyOrZeroLength(e.table))throw new Fi("invalid table specified.");if(!Array.isArray(e.records))throw new Fi("records must be an array");let t=V$()[e.schema]?.[e.table];if(gs.isEmpty(t))throw new Fi(`could not retrieve schema:${e.schema} and table ${e.table}`);let r=t.primaryKey,n=new Set,s={},i=!1;return e.operation==="update"&&(i=!0),e.records.forEach(o=>{if(i&&gs.isEmptyOrZeroLength(o[r]))throw gy.error("a valid hash attribute must be provided with update record:",o),new Fi("a valid hash attribute must be provided with update record, check log for more info");if(!gs.isEmptyOrZeroLength(o[r])&&(o[r]==="null"||o[r]==="undefined"))throw gy.error(`a valid hash value must be provided with ${e.operation} record:`,o),new Fi(`Invalid hash value: '${o[r]}' is not a valid hash attribute value, check log for more info`);!gs.isEmpty(o[r])&&o[r]!==""&&n.has(gs.autoCast(o[r]))&&(o.skip=!0),n.add(gs.autoCast(o[r]));for(let c in o)s[c]=1}),s[r]=1,{schema_table:t,hashes:Array.from(n),attributes:Object.keys(s)}}a($$,"insertUpdateValidate")});var Hc=g((Xae,Ay)=>{"use strict";var Y$=U().OPERATIONS_ENUM,wm=class{static{a(this,"InsertObject")}constructor(t,r,n,s,i=void 0){this.operation=Y$.INSERT,this.schema=t,this.table=r,this.hash_attribute=n,this.records=s,this.__origin=i}};Ay.exports=wm});var xc=g((ece,by)=>{"use strict";var Zae=Hc(),y_=U(),Cm=z(),Oy=K(),K$=require("uuid"),{handleHDBError:N_,hdb_errors:W$}=ne(),{HDB_ERROR_MSGS:I_,HTTP_STATUS_CODES:w_}=W$;by.exports=Q$;function Q$(e,t,r){for(let s=0;s<t.length;s++)z$(t[s]);let{records:n}=e;for(let s=0;s<n.length;s++){let i=n[s];J$(i,r,e.operation)}}a(Q$,"processRows");function z$(e){if(Buffer.byteLength(String(e))>y_.INSERT_MODULE_ENUM.MAX_CHARACTER_SIZE)throw N_(new Error,I_.ATTR_NAME_LENGTH_ERR(e),w_.BAD_REQUEST,void 0,void 0,!0);if(Cm.isEmptyOrZeroLength(e)||Cm.isEmpty(e.trim()))throw N_(new Error,I_.ATTR_NAME_NULLISH_ERR,w_.BAD_REQUEST,void 0,void 0,!0)}a(z$,"validateAttribute");function J$(e,t,r){if(!e.hasOwnProperty(t)||Cm.isEmptyOrZeroLength(e[t])){if(r===y_.OPERATIONS_ENUM.INSERT||r===y_.OPERATIONS_ENUM.UPSERT){e[t]=K$.v4();return}throw Oy.error("Update transaction aborted due to record with no hash value:",e),N_(new Error,I_.RECORD_MISSING_HASH_ERR,w_.BAD_REQUEST,void 0,void 0,!0)}if(Buffer.byteLength(String(e[t]))>y_.INSERT_MODULE_ENUM.MAX_CHARACTER_SIZE)throw Oy.error(e),N_(new Error,I_.HASH_VAL_LENGTH_ERR,w_.BAD_REQUEST,void 0,void 0,!0)}a(J$,"validateHash")});var Ny=g((rce,yy)=>{"use strict";var Dm=class{static{a(this,"ITCEventObject")}constructor(t,r){this.type=t,this.message=r}};yy.exports=Dm});var Cy=g((sce,wy)=>{"use strict";var Lm=Ke(),X$=K(),Iy=Ur().LMDB_ERRORS_ENUM;wy.exports=j$;async function j$(e){try{if(global.lmdb_map!==void 0&&e.operation!==void 0){let t=Object.keys(global.lmdb_map),r;switch(e.operation){case"drop_schema":for(let i=0;i<t.length;i++){let o=t[i];if(o.startsWith(`${e.schema}.`)||o.startsWith(`txn.${e.schema}.`))try{await Lm.closeEnvironment(global.lmdb_map[o])}catch(c){if(c.message!==Iy.ENV_REQUIRED)throw c}}break;case"drop_table":let n=`${e.schema}.${e.table}`,s=`txn.${n}`;try{await Lm.closeEnvironment(global.lmdb_map[n]),await Lm.closeEnvironment(global.lmdb_map[s])}catch(i){if(i.message!==Iy.ENV_REQUIRED)throw i}break;case"drop_attribute":r=global.lmdb_map[`${e.schema}.${e.table}`],r!==void 0&&typeof r.dbis=="object"&&r.dbis[`${e.attribute}`]!==void 0&&delete r.dbis[`${e.attribute}`];break;default:break}}}catch(t){X$.error(t)}}a(j$,"cleanLMDBMap")});var Rs=g((oce,Py)=>{"use strict";var Gc=require("crypto"),Z$=te(),{CONFIG_PARAMS:e1}=U(),Ly="aes-256-cbc",t1=32,r1=16,Mm=64,My=32,n1=Mm+My,Dy=new Map;Py.exports={encrypt:s1,decrypt:i1,createNatsTableStreamName:o1};function s1(e){let t=Gc.randomBytes(t1),r=Gc.randomBytes(r1),n=Gc.createCipheriv(Ly,Buffer.from(t),r),s=n.update(e);s=Buffer.concat([s,n.final()]);let i=t.toString("hex"),o=r.toString("hex"),c=s.toString("hex");return i+o+c}a(s1,"encrypt");function i1(e){let t=e.substr(0,Mm),r=e.substr(Mm,My),n=e.substr(n1,e.length),s=Buffer.from(r,"hex"),i=Buffer.from(n,"hex"),o=Gc.createDecipheriv(Ly,Buffer.from(t,"hex"),s),c=o.update(i);return c=Buffer.concat([c,o.final()]),c.toString()}a(i1,"decrypt");function o1(e,t){let r=Z$.get(e1.CLUSTERING_DATABASELEVEL)?e:`${e}.${t}`,n=Dy.get(r);return n||(n=Gc.createHash("md5").update(r).digest("hex"),Dy.set(r,n)),n}a(o1,"createNatsTableStreamName")});var ri=g((lce,vy)=>{"use strict";var cce=Gr(),Fc=K(),Uy=A_(),a1=Rs(),C_=z(),{handleHDBError:D_,hdb_errors:c1}=ne(),{HDB_ERROR_MSGS:L_,HTTP_STATUS_CODES:Pm}=c1,l1=te();l1.initSync();var{getDatabases:Um}=(Ae(),ie(ke)),u1=require("fs-extra");vy.exports={describeAll:_1,describeTable:M_,describeSchema:d1};async function _1(e){try{let t=C_.isEmptyOrZeroLength(e),r,n;t||(r=e.hdb_user.role.permission,n=r.super_user||r.cluster_user);let s=Um(),i={},o={},c=[],l=e?.exact_count;for(let u in s){i[u]=!0,!t&&!n&&(o[u]=e.hdb_user.role.permission[u].describe);let d=s[u];for(let E in d)try{let f;if(t||n)f=await M_({schema:u,table:E,exact_count:l});else if(r&&r[u].describe&&r[u].tables[E].describe){let h=r[u].tables[E].attribute_permissions;f=await M_({schema:u,table:E,exact_count:l},h)}f&&c.push(f)}catch(f){Fc.error(f)}}let _={};for(let u in c)t||n?(_[c[u].schema]==null&&(_[c[u].schema]={}),_[c[u].schema][c[u].name]=c[u],i[c[u].schema]&&delete i[c[u].schema]):o[c[u].schema]&&(_[c[u].schema]==null&&(_[c[u].schema]={}),_[c[u].schema][c[u].name]=c[u],i[c[u].schema]&&delete i[c[u].schema]);for(let u in i)t||n?_[u]={}:o[u]&&(_[u]={});return _}catch(t){return Fc.error("Got an error in describeAll"),Fc.error(t),D_(new Error,L_.DESCRIBE_ALL_ERR)}}a(_1,"describeAll");async function M_(e,t){C_.transformReq(e);let{schema:r,table:n}=e;r=r?.toString(),n=n?.toString();let s=t;e.hdb_user&&!e.hdb_user.role.permission.super_user&&(s=e.hdb_user.role.permission[r].tables[n].attribute_permissions);let i=Uy.describe_table(e);if(i)throw i;let c=Um()[r];if(!c)throw D_(new Error,L_.SCHEMA_NOT_FOUND(e.schema),Pm.NOT_FOUND);let l=c[n];if(!l)throw D_(new Error,L_.TABLE_NOT_FOUND(e.schema,e.table),Pm.NOT_FOUND);function _(f){u.push(Object.assign({},{attribute:f.attribute,type:f.type,elements:f.elements?.type,indexed:f.indexed,is_primary_key:f.isPrimaryKey,assigned_created_time:f.assignCreatedTime,assigned_updated_time:f.assignUpdatedTime,nullable:f.nullable,properties:f.properties?f.properties.map(h=>({type:h.type,name:h.name})):void 0}))}a(_,"pushAtt");let u=[];if(s){let f={};s.forEach(h=>{h.describe&&(f[h.attribute_name]=!0)}),l.attributes.forEach(h=>{f[h.name]&&_(h)})}else l.attributes?.forEach(f=>_(f));let d;try{d=(await u1.stat(l.primaryStore.env.path)).size}catch(f){Fc.warn("unable to get database size",f)}let E={schema:r,name:l.tableName,hash_attribute:l.attributes.find(f=>f.isPrimaryKey||f.is_hash_attribute)?.name,audit:l.audit,schema_defined:l.schemaDefined,attributes:u,db_size:d};E.clustering_stream_name=a1.createNatsTableStreamName(E.schema,E.name);try{let f=l.getRecordCount({exactCount:e.exact_count==="true"});E.record_count=f.recordCount,E.estimated_record_range=f.estimatedRange;let h=l.auditStore;if(h)for(let p of h.getKeys({reverse:!0,limit:1}))E.last_updated_record=p[0];if(!E.last_updated_record&&l.indices.__updatedtime__)for(let p of l.indices.__updatedtime__.getKeys({reverse:!0,limit:1}))E.last_updated_record=p}catch(f){Fc.warn(`unable to stat table dbi due to ${f}`)}return E}a(M_,"descTable");async function d1(e){C_.transformReq(e);let t=Uy.schema_object(e);if(t)throw t;let r;e.hdb_user&&!e.hdb_user.role.permission.super_user&&(r=e.hdb_user.role.permission[e.schema]);let n=e.schema.toString(),i=Um()[n];if(!i)throw D_(new Error,L_.SCHEMA_NOT_FOUND(e.schema),Pm.NOT_FOUND);let o={};for(let c in i){let l;if(r&&r.tables[c]&&(l=r.tables[c]),C_.isEmpty(l)||l.describe){let _=await M_({schema:e.schema,table:c,exact_count:e.exact_count},l?l.attribute_permissions:null);_&&(o[_.name]=_)}}return o}a(d1,"describeSchema")});var ni=g((fce,Fy)=>{var f1=Gi(),{callbackify:Hy,promisify:E1}=require("util"),{getDatabases:xy}=(Ae(),ie(ke));Fy.exports={setSchemaDataToGlobal:By,getTableSchema:h1,getSystemSchema:m1,setSchemaDataToGlobalAsync:E1(By)};var Gy=ri(),_ce=Hy(Gy.describeAll),dce=Hy(Gy.describeTable);function By(e){global.hdb_schema=xy(),e&&e()}a(By,"setSchemaDataToGlobal");function h1(e,t,r){let n=xy()[e];if(!n)return r(`schema ${e} does not exist`);let s=n[t];return s?r(null,{schema:e,name:t,hash_attribute:s.primaryKey}):r(`table ${e}.${t} does not exist`)}a(h1,"getTableSchema");function m1(){return f1}a(m1,"getSystemSchema")});var ln=g((hce,$y)=>{"use strict";var U_=Im(),Yt=z(),p1=require("util"),v_=wn(),S1=ni(),qy=K(),{handleHDBError:qi,hdb_errors:T1}=ne(),{HTTP_STATUS_CODES:ki}=T1,g1=p1.promisify(S1.getTableSchema),R1="updated",ky="inserted",Vy="upserted";$y.exports={insert:O1,update:b1,upsert:y1,validation:A1,flush:N1};async function A1(e){if(Yt.isEmpty(e))throw new Error("invalid update parameters defined.");if(Yt.isEmptyOrZeroLength(e.schema))throw new Error("invalid database specified.");if(Yt.isEmptyOrZeroLength(e.table))throw new Error("invalid table specified.");let t=await g1(e.schema,e.table),r=U_(e);if(r)throw r;if(!Array.isArray(e.records))throw new Error("records must be an array");let n=t.hash_attribute,s=new Set,i={},o=!1;return e.operation==="update"&&(o=!0),e.records.forEach(c=>{if(o&&Yt.isEmptyOrZeroLength(c[n]))throw qy.error("a valid hash attribute must be provided with update record:",c),new Error("a valid hash attribute must be provided with update record");if(!Yt.isEmptyOrZeroLength(c[n])&&(c[n]==="null"||c[n]==="undefined"))throw qy.error(`a valid hash value must be provided with ${e.operation} record:`,c),new Error(`"${c[n]}" is not a valid hash attribute value`);!Yt.isEmpty(c[n])&&c[n]!==""&&s.has(Yt.autoCast(c[n]))&&(c.skip=!0),s.add(Yt.autoCast(c[n]));for(let l in c)i[l]=1}),i[n]=1,{schema_table:t,hashes:Array.from(s),attributes:Object.keys(i)}}a(A1,"validation");async function O1(e){if(e.operation!=="insert")throw new Error("invalid operation, must be insert");let t=U_(e);if(t)throw qi(new Error,t.message,ki.BAD_REQUEST);Yt.transformReq(e);let r=Yt.checkSchemaTableExist(e.schema,e.table);if(r)throw qi(new Error,r,ki.BAD_REQUEST);let n=await v_.createRecords(e);return P_(ky,n.written_hashes,e,n.skipped_hashes,n.new_attributes,n.txn_time)}a(O1,"insertData");async function b1(e){if(e.operation!=="update")throw new Error("invalid operation, must be update");let t=U_(e);if(t)throw qi(new Error,t.message,ki.BAD_REQUEST);Yt.transformReq(e);let r=Yt.checkSchemaTableExist(e.schema,e.table);if(r)throw qi(new Error,r,ki.BAD_REQUEST);let n=await v_.updateRecords(e);return Yt.isEmpty(n.existing_rows)?P_(R1,n.written_hashes,e,n.skipped_hashes,n.new_attributes,n.txn_time):P_(n.update_action,[],e,n.hashes,void 0,n.txn_time)}a(b1,"updateData");async function y1(e){if(e.operation!=="upsert")throw qi(new Error,"invalid operation, must be upsert",ki.INTERNAL_SERVER_ERROR);let t=U_(e);if(t)throw qi(new Error,t.message,ki.BAD_REQUEST);Yt.transformReq(e);let r=Yt.checkSchemaTableExist(e.schema,e.table);if(r)throw qi(new Error,r,ki.BAD_REQUEST);let n=await v_.upsertRecords(e);return P_(Vy,n.written_hashes,e,[],n.new_attributes,n.txn_time)}a(y1,"upsertData");function P_(e,t,r,n,s,i){let o={message:`${e} ${t.length} of ${t.length+n.length} records`,new_attributes:s,txn_time:i};return e===ky?(o.inserted_hashes=t,o.skipped_hashes=n,o):e===Vy?(o.upserted_hashes=t,o):(o.update_hashes=t,o.skipped_hashes=n,o)}a(P_,"returnObject");function N1(e){return Yt.transformReq(e),v_.flush(e.schema,e.table)}a(N1,"flush")});var Bm=g((pce,Wy)=>{var I1=at(),vm=require("joi"),{hdb_table:w1,hdb_database:Yy}=zn(),Ky={schema:Yy,database:Yy,table:w1},C1={date:vm.date().iso().required()},D1={timestamp:vm.date().timestamp().required().messages({"date.format":"'timestamp' is invalid"})};Wy.exports=function(e,t){let r=t==="timestamp"?{...Ky,...D1}:{...Ky,...C1},n=vm.object(r);return I1.validateBySchema(e,n)}});var Jy=g((Sce,zy)=>{var L1=at(),Hm=require("joi"),{hdb_table:M1,hdb_database:Qy}=zn(),P1=Hm.object({schema:Qy,database:Qy,table:M1,hash_values:Hm.array().required(),ids:Hm.array()});zy.exports=function(e){return L1.validateBySchema(e,P1)}});var jy=g((Tce,Xy)=>{"use strict";var xm=class{static{a(this,"InsertObject")}constructor(t,r,n,s,i){this.operation=t,this.schema=r,this.table=n,this.hash_attribute=s,this.records=i}},Gm=class{static{a(this,"NoSQLSeachObject")}constructor(t,r,n,s,i,o){this.schema=t,this.table=r,this.search_attribute=n,this.hash_attribute=s,this.get_attributes=i,this.search_value=o}},Fm=class{static{a(this,"DeleteResponseObject")}constructor(){this.message=void 0,this.deleted_hashes=[],this.skipped_hashes=[]}};Xy.exports={InsertObject:xm,NoSQLSeachObject:Gm,DeleteResponseObject:Fm}});var Yi=g((Rce,nN)=>{"use strict";var eN=Bm(),U1=Jy(),Vi=z(),Zy=require("moment"),tN=K(),{promisify:v1,callbackify:B1}=require("util"),$i=U(),H1=ni(),qm=v1(H1.getTableSchema),km=wn(),{DeleteResponseObject:x1}=jy(),{handleHDBError:si,hdb_errors:G1}=ne(),{HDB_ERROR_MSGS:B_,HTTP_STATUS_CODES:ii}=G1,F1="records successfully deleted",q1=B1(rN);nN.exports={delete:q1,deleteRecord:rN,deleteFilesBefore:k1,deleteAuditLogsBefore:V1};async function k1(e){let t=eN(e,"date");if(t)throw si(t,t.message,ii.BAD_REQUEST,void 0,void 0,!0);if(Vi.transformReq(e),!Zy(e.date,Zy.ISO_8601).isValid())throw si(new Error,B_.INVALID_DATE,ii.BAD_REQUEST,$i.LOG_LEVELS.ERROR,B_.INVALID_DATE,!0);let n=Vi.checkSchemaTableExist(e.schema,e.table);if(n)throw si(new Error,n,ii.NOT_FOUND,$i.LOG_LEVELS.ERROR,n,!0);let s=await km.deleteRecordsBefore(e);if(await qm(e.schema,e.table),tN.info(`Finished deleting files before ${e.date}`),s&&s.message)return s.message}a(k1,"deleteFilesBefore");async function V1(e){let t=eN(e,"timestamp");if(t)throw si(t,t.message,ii.BAD_REQUEST,void 0,void 0,!0);if(Vi.transformReq(e),isNaN(e.timestamp))throw si(new Error,B_.INVALID_VALUE("Timestamp"),ii.BAD_REQUEST,$i.LOG_LEVELS.ERROR,B_.INVALID_VALUE("Timestamp"),!0);let r=Vi.checkSchemaTableExist(e.schema,e.table);if(r)throw si(new Error,r,ii.NOT_FOUND,$i.LOG_LEVELS.ERROR,r,!0);let n=await km.deleteAuditLogsBefore(e);return await qm(e.schema,e.table),tN.info(`Finished deleting audit logs before ${e.timestamp}`),n}a(V1,"deleteAuditLogsBefore");async function rN(e){e.ids&&(e.hash_values=e.ids);let t=U1(e);if(t)throw si(t,t.message,ii.BAD_REQUEST,void 0,void 0,!0);Vi.transformReq(e);let r=Vi.checkSchemaTableExist(e.schema,e.table);if(r)throw si(new Error,r,ii.NOT_FOUND,$i.LOG_LEVELS.ERROR,r,!0);try{await qm(e.schema,e.table);let n=await km.deleteRecords(e);return Vi.isEmptyOrZeroLength(n.message)&&(n.message=`${n.deleted_hashes.length} of ${e.hash_values.length} ${F1}`),n}catch(n){if(n.message===$i.SEARCH_NOT_FOUND_MESSAGE){let s=new x1;return s.message=$i.SEARCH_NOT_FOUND_MESSAGE,s.skipped_hashes=e.hash_values.length,s.deleted_hashes=0,s}throw n}}a(rN,"deleteRecord")});var H_=g((Oce,oN)=>{var $1=require("crypto"),sN=9;function Y1(e){let t=W1(sN),r=iN(e+t);return t+r}a(Y1,"createHash");function K1(e,t){let r=e?.substr(0,sN),n=r+iN(t+r);return e===n}a(K1,"validateHash");function W1(e){let t="0123456789abcdefghijklmnopqurstuvwxyzABCDEFGHIJKLMNOPQURSTUVWXYZ",r=t.length,n="";for(let s=0;s<e;s++){let i=Math.floor(Math.random()*r);n+=t[i]}return n}a(W1,"generateSalt");function iN(e){return $1.createHash("md5").update(e).digest("hex")}a(iN,"md5");oN.exports={hash:Y1,validate:K1}});var cN=g((yce,aN)=>{var Vm=at(),Zt={username:{presence:!0,format:"[\\w\\-\\_]+",exclusion:{within:["system"],message:"You cannot create tables within the system schema"}},password:{presence:!0},role:{presence:!0,format:"[\\w\\-\\_]+"},active:{presence:!0,inclusion:{within:[!0,!1],message:"must be a boolean"}}};function Q1(e){return Zt.password.presence=!0,Zt.username.presence=!0,Zt.role.presence=!0,Zt.active.presence=!0,Vm.validateObject(e,Zt)}a(Q1,"addUserValidation");function z1(e){return Zt.password.presence=!1,Zt.username.presence=!0,Zt.role.presence=!1,Zt.active.presence=!1,Vm.validateObject(e,Zt)}a(z1,"alterUserValidation");function J1(e){return Zt.password.presence=!1,Zt.username.presence=!0,Zt.role.presence=!1,Zt.active.presence=!1,Vm.validateObject(e,Zt)}a(J1,"dropUserValidation");aN.exports={addUserValidation:Q1,alterUserValidation:z1,dropUserValidation:J1}});var ct=g((wce,uN)=>{"use strict";var{platform:Ice}=require("os"),X1="nats-server.zip",$m="nats-server",j1=process.platform==="win32"?`${$m}.exe`:$m,Z1=/^[^\s.,*>]+$/,lN="__request__",eY=a(e=>`${e}.${lN}`,"REQUEST_SUBJECT"),tY={NATS_MSG_ID:"Nats-Msg-Id",ORIGIN:"origin",TRANSACTED_NODES:"transacted_nodes"},rY={HUB_SERVER:"hub.json",LEAF_SERVER:"leaf.json"},nY={HUB:"hub.pid",LEAF:"leaf.pid"},sY={HUB:"-hub",LEAF:"-leaf",ADMIN:"-admin"},iY={SUCCESS:"success",ERROR:"error"},oY={OPEN:"open",CLOSED:"closed",NO_RESPONDERS:"NoResponders",TIMEOUT:"Timeout"},aY={TXN:"txn",MSGID:"msgid"},$o={ERR:"error",WRN:"warn",INF:"info",DBG:"debug",TRC:"trace"},cY={[$o.ERR]:1,[$o.WRN]:2,[$o.INF]:3,[$o.DBG]:4,[$o.TRC]:5},lY={debug:"-D",trace:"-DVV"};uN.exports={NATS_SERVER_ZIP:X1,NATS_SERVER_NAME:$m,NATS_BINARY_NAME:j1,PID_FILES:nY,NATS_CONFIG_FILES:rY,SERVER_SUFFIX:sY,NATS_TERM_CONSTRAINTS_RX:Z1,REQUEST_SUFFIX:lN,UPDATE_REMOTE_RESPONSE_STATUSES:iY,CLUSTER_STATUS_STATUSES:oY,REQUEST_SUBJECT:eY,SUBJECT_PREFIXES:aY,MSG_HEADERS:tY,LOG_LEVELS:$o,LOG_LEVEL_FLAGS:lY,LOG_LEVEL_HIERARCHY:cY}});var dN=g((Dce,_N)=>{"use strict";var uY={key:"-----BEGIN RSA PRIVATE KEY-----\rMIIEowIBAAKCAQEArBFJQRfFiJku/KwhV1Ssp7cX61vvuKmd4Rp6A9jB2QLgx8nj\r/+Xhp2hPRkISnOA8BuAxr4dMD9syGJwX4kNy9mbZ5Q0fWZCiEGBpVcU1J+k+N5K4\rSuZ2SqgxeN2IN2RLzt3GyQY4imcdHgNv7aHoXUrEwBx0MeYEw3IIDXtrYKCR2D8I\rvWBfwMUgWa24G8lpWILWA5hd9srRz9NxlAiHSjhbgT7B0xruEpHRCHSyKjvaIJVt\rWBR+amejYsAKVrD/hgrqjsA1123Y6++YqvU6vwg64xhS2kz5r3dkNKhvwbWgpZdI\rIaRvsiB77f4kLGo0vi8RFgJ1ZRjGg3RRK2w1LQIDAQABAoIBAQCEOmh78EOpnGZC\rYBjjHrvrysVD5gvLcfVUtl8Ls7gMB60re1eOIF+PoZZCHKZnDd6zPfiQtj1adg0C\rYnnsM/8VoaZS4gm0b3RLd3ubIQifWhuo40RissY2yxfxlPSH9LhZCY8ojnJG0cTL\resK579E8WCfopjUY33XLqEbN7Ylv39J+DSqInjqV3efJZUa+HqUJ98VxxzodcKMD\rP3bwUU4gHoSSp4pAsOFH5sQhaIWH1IcNjrAwpee2cJQuh4G157RRIuuUpagtaEG/\rXJIiAyBguJyu3JQFnIBQF01N5+omJgXYJ1L0m54543/iIRThmF3zDCDgCyUzmOk+\rH6As9fv1AoGBANOpOtOZLSAScjGsgJamT3ceJ2wCa86g2j8Oxu8lJUmUp5s3tA0v\rBFW5O3S4KR1EXwkLMBUMrfFM8YvzHWxsXBI6XV8azGLvyqPHxr65OhmpGYkGZMXu\rn9okgjkqlewnY2I073gvyK7ppX51UL5y9fF1vlsk+UlW+Rgx/vMHbdcjAoGBANAc\rxRUsxs4QJpbS4zD3JOkHjr24a97TrS3kCybAHUMpR2NrEHPZw9zex0/aphOJUHfL\rIMkOZdpfDqMfxWy4FAEmqBEMkO2SB+h0Wp4P+qp81ax4vGFiB0cD3wtixr11U1tt\rlZ/ZTdv4VDpDFNK1KaplhTDeyuCjeYfS3/GJia9vAoGAcOsAgjBevZR5rXx84WH6\rVO8WUu37u7FenXNxt9VWTinrPMh72uixZFY8nOk+rely1e1NCn3IMko9Ns9NbDFm\r8SaH95vhXArXTYbfxZIlp9jp0YtCqcHDL+p4Oq04bFMbFyJseu7rHj1x18QYfnHw\rOY/6LL/N6k1m+Hx7qgXVmIcCgYB/w0nTCBw84XlvWqSTqQaF8VfWbWP79mP5KmkW\rLxdH5g2noVEGbohqDnK6OXd/wusdwByukiJBf94Skyy25AOT+VFwthA7aU1ljhkb\rtJ+lDuJ28eBkwLPLCzthWBC+u0qjdJFJAzVjd/7tjcU43nNn4s90AzL12iaAFhvZ\rwyA+DQKBgGc/4cdyGJ3YkcA8150gQBawgJZ7q8V1JND87ggWA8wnK3cHn7rMZQl2\r3emDp9HEFXFex5dbGDDqZFAoesZCDxjknIn9oNfW4PvaWS8q7b6ZKLZG1p03Pu7/\rtYaD0kPbo0kysfFT/co+NgHbdykvIyboomfGdNLTUjYuy6lpwpvs\r-----END RSA PRIVATE KEY-----\r".replace(/\r/g,`\r
5
- `),cert:"-----BEGIN CERTIFICATE-----\rMIIDXDCCAkSgAwIBAgIFNTE4MzQwDQYJKoZIhvcNAQELBQAwXTEXMBUGA1UEAxMO\rSGFycGVyREIsIEluYy4xCzAJBgNVBAYTAlVTMQswCQYDVQQIEwJDTzEPMA0GA1UE\rBxMGRGVudmVyMRcwFQYDVQQKEw5IYXJwZXJEQiwgSW5jLjAeFw0yMjAzMTEyMzAz\rNDlaFw0yNzAzMTAyMzAzNDlaMF0xFzAVBgNVBAMTDkhhcnBlckRCLCBJbmMuMQsw\rCQYDVQQGEwJVUzELMAkGA1UECBMCQ08xDzANBgNVBAcTBkRlbnZlcjEXMBUGA1UE\rChMOSGFycGVyREIsIEluYy4wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIB\rAQCsEUlBF8WImS78rCFXVKyntxfrW++4qZ3hGnoD2MHZAuDHyeP/5eGnaE9GQhKc\r4DwG4DGvh0wP2zIYnBfiQ3L2ZtnlDR9ZkKIQYGlVxTUn6T43krhK5nZKqDF43Yg3\rZEvO3cbJBjiKZx0eA2/toehdSsTAHHQx5gTDcggNe2tgoJHYPwi9YF/AxSBZrbgb\ryWlYgtYDmF32ytHP03GUCIdKOFuBPsHTGu4SkdEIdLIqO9oglW1YFH5qZ6NiwApW\rsP+GCuqOwDXXbdjr75iq9Tq/CDrjGFLaTPmvd2Q0qG/BtaCll0ghpG+yIHvt/iQs\rajS+LxEWAnVlGMaDdFErbDUtAgMBAAGjIzAhMA8GA1UdEwEB/wQFMAMBAf8wDgYD\rVR0PAQH/BAQDAgIEMA0GCSqGSIb3DQEBCwUAA4IBAQASR4YW/rPK7PNArHVe9zzM\rb0rKNX/2T9/0nybRhmE/+hdlSgliTAeebmwkUS2APckmekYt/q2ZY2NS65Fo/jjp\rG8TJrtcF4h+ylVqUp0ZXQLFtIsr7r2JZA7hJ6njW6G4DHSZ0gxtECLi4CBlTjzm5\rNmnmIDObvGRTuqmcdAZmXeObbta/He2XIzietukPAYX062pNM+G5XT5UM1eG/Vlp\rN86vjhpyI+ffKy+C60SJqxmKM3ydgN7oLscE7+2wLPN25XqN4W99OwGsp5dTdu/f\r5lPtFayXdJ55e/sNQKmGN+UGLrL05c2MWgjb8U/LFilnupUianceoeSERZmVjzKX\r-----END CERTIFICATE-----\r".replace(/\r/g,`\r
6
- `)},_Y="certificate.pem",dY="privateKey.pem",fY="ca.pem";_N.exports={CERTIFICATE_VALUES:uY,CERTIFICATE_PEM_NAME:_Y,PRIVATEKEY_PEM_NAME:dY,CA_PEM_NAME:fY}});var Ym=g((Mce,SN)=>{"use strict";var mN=require("fs-extra"),oe=require("joi"),EY=require("os"),{boolean:be,string:er,number:Ze,array:x_}=oe.types(),{totalmem:fN}=require("os"),Ki=require("path"),hY=K(),G_=z(),Lce=dN(),EN=U(),mY=at(),hN="log",pY="components",SY="Invalid logging.rotation.maxSize unit. Available units are G, M or K",TY="Invalid logging.rotation.interval unit. Available units are D, H or M (minutes)",gY="Invalid logging.rotation.maxSize value. Value should be a number followed by unit e.g. '10M'",RY="Invalid logging.rotation.interval value. Value should be a number followed by unit e.g. '10D'",AY="rootPath config parameter is undefined",OY="clustering.enabled config parameter is undefined",Wi=Ze.min(0).required(),F_=x_.items({host:er.required(),port:Wi}).empty(null),Xn,pN=!1;SN.exports={configValidator:bY,routesValidator:DY,route_constraints:F_};function bY(e,t=!1){if(pN=t,Xn=e.rootPath,G_.isEmpty(Xn))throw AY;let r=be.required(),n=Ze.min(0).max(1e3).empty(null).default(CY),s=er.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path").empty(null).default(qc),i=er.optional().empty(null),o=er.pattern(/^[^\s.,*>]+$/).messages({"string.pattern.base":"{:#label} invalid, must not contain ., * or >"}).empty(null).required(),c=oe.string().empty(null).default(qc),l=oe.custom(NY).empty(null).default(qc),_=e.clustering?.enabled;if(G_.isEmpty(_))throw OY;let u=oe.object({certificate:i,certificateAuthority:i,privateKey:i}),d;return _===!0?d=oe.object({enabled:r,hubServer:oe.object({cluster:oe.object({name:oe.required().empty(null),network:oe.object({port:Wi,routes:F_}).required()}).required(),leafNodes:oe.object({network:oe.object({port:Wi}).required()}).required(),network:oe.object({port:Wi}).required()}).required(),leafServer:oe.object({network:oe.object({port:Wi,routes:F_}).required(),streams:oe.object({maxAge:Ze.min(120).allow(null).optional(),maxBytes:Ze.min(1).allow(null).optional(),maxMsgs:Ze.min(1).allow(null).optional(),path:c}).required()}).required(),logLevel:oe.valid("error","warn","info","debug","trace"),nodeName:o,republishMessages:be.optional(),databaseLevel:be.optional(),tls:oe.object({certificate:i,certificateAuthority:i,privateKey:i,insecure:be.required(),verify:be.optional()}),user:er.optional().empty(null)}).required():d=oe.object({enabled:r,tls:oe.object({certificate:i,certificateAuthority:i,privateKey:i,insecure:be.required()})}).required(),oe.object({authentication:oe.object({authorizeLocal:be,cacheTTL:Ze.required(),enableSessions:be}),analytics:oe.object({aggregatePeriod:Ze}),componentsRoot:s.optional(),clustering:d,localStudio:oe.object({enabled:r}).required(),logging:oe.object({auditAuthEvents:oe.object({logFailed:be,logSuccessful:be}),file:be.required(),level:oe.valid("notify","fatal","error","warn","info","debug","trace"),rotation:oe.object({enabled:be.optional(),compress:be.optional(),interval:er.custom(wY).optional().empty(null),maxSize:er.custom(IY).optional().empty(null),path:er.optional().empty(null).default(qc)}).required(),root:s,stdStreams:be.required(),auditLog:be.required()}).required(),operationsApi:oe.object({network:oe.object({cors:be.optional(),corsAccessList:x_.optional(),headersTimeout:Ze.min(1).optional(),keepAliveTimeout:Ze.min(1).optional(),port:Ze.optional().empty(null),domainSocket:oe.optional().empty("hdb/operations-server").default(qc),securePort:Ze.optional().empty(null),timeout:Ze.min(1).optional()}).optional(),tls:oe.alternatives([oe.array().items(u),u])}).required(),rootPath:er.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path").required(),mqtt:oe.object({network:oe.object({port:Wi,securePort:Wi,mtls:oe.alternatives([be.optional(),oe.object({user:er.optional(),certificateAuthority:i,required:be.optional()})])}).required(),webSocket:be.optional(),requireAuthentication:be.optional()}),http:oe.object({compressionThreshold:Ze.optional(),cors:be.optional(),corsAccessList:x_.optional(),headersTimeout:Ze.min(1).optional(),port:Ze.min(0).optional().empty(null),securePort:Ze.min(0).optional().empty(null),maxHeaderSize:Ze.optional(),mtls:oe.alternatives([be.optional(),oe.object({user:er.optional(),certificateAuthority:i,required:be.optional()})]),threadRange:oe.alternatives([x_.optional(),er.optional()])}).required(),threads:oe.alternatives(n.optional(),oe.object({count:n.optional(),debug:oe.alternatives(be.optional(),oe.object({startingPort:Ze.min(1).optional(),host:er.optional(),waitForDebugger:be.optional()})),maxHeapMemory:Ze.min(0).optional()})),storage:oe.object({writeAsync:be.required(),overlappingSync:be.optional(),caching:be.optional(),compression:oe.alternatives([be.optional(),oe.object({dictionary:er.optional(),threshold:Ze.optional()})]),compactOnStart:be.optional(),compactOnStartKeepBackup:be.optional(),noReadAhead:be.optional(),path:l,prefetchWrites:be.optional(),maxFreeSpaceToLoad:Ze.optional(),maxFreeSpaceToRetain:Ze.optional()}).required(),ignoreScripts:be.optional(),tls:oe.alternatives([oe.array().items(u),u])}).validate(e,{allowUnknown:!0,abortEarly:!1,errors:{wrap:{label:"'"}}})}a(bY,"configValidator");function yY(e){return pN||mN.existsSync(e)?null:`Specified path ${e} does not exist.`}a(yY,"doesPathExist");function NY(e,t){oe.assert(e,er.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path"));let r=yY(e);if(r)return t.message(r)}a(NY,"validatePath");function IY(e,t){let r=e.slice(-1);if(r!=="G"&&r!=="M"&&r!=="K")return t.message(SY);let n=e.slice(0,-1);return isNaN(parseInt(n))?t.message(gY):e}a(IY,"validateRotationMaxSize");function wY(e,t){let r=e.slice(-1);if(r!=="D"&&r!=="H"&&r!=="M")return t.message(TY);let n=e.slice(0,-1);return isNaN(parseInt(n))?t.message(RY):e}a(wY,"validateRotationInterval");function CY(e,t){let r=t.state.path.join("."),n=EY.cpus().length,s=n-1;s<=2&&(s=2);let i=process.constrainedMemory?.()||fN();return i=Math.round(Math.min(i,fN())/1e6),s=Math.max(Math.min(s,Math.round((i-750)/300)),1),hY.info(`Detected ${n} cores and ${i}MB on this machine, defaulting ${r} to ${s}`),s}a(CY,"setDefaultThreads");function qc(e,t){let r=t.state.path.join(".");if(!G_.isEmpty(t.original)&&r!=="operationsApi.network.domainSocket")return t.original;if(G_.isEmpty(Xn))throw new Error(`Error setting default root for: ${r}. HDB root is not defined`);switch(r){case"componentsRoot":return Ki.join(Xn,pY);case"logging.root":return Ki.join(Xn,hN);case"clustering.leafServer.streams.path":return Ki.join(Xn,"clustering","leaf");case"storage.path":let n=Ki.join(Xn,EN.LEGACY_DATABASES_DIR_NAME);return mN.existsSync(n)?n:Ki.join(Xn,EN.DATABASES_DIR_NAME);case"logging.rotation.path":return Ki.join(Xn,hN);case"operationsApi.network.domainSocket":return r==null?null:Ki.join(Xn,"operations-server");default:throw new Error(`Error setting default root for config parameter: ${r}. Unrecognized config parameter`)}}a(qc,"setDefaultRoot");function DY(e){let t=oe.object({routes:F_});return mY.validateBySchema({routes:e},t)}a(DY,"routesValidator")});var Er=g((vce,IN)=>{"use strict";var qr=U(),Bt=z(),Nt=K(),{configValidator:LY,routesValidator:TN}=Ym(),fr=require("fs-extra"),MY=require("yaml"),Cn=require("path"),PY=require("is-number"),RN=require("properties-reader"),UY=require("lodash"),{handleHDBError:vY}=ne(),{HTTP_STATUS_CODES:BY,HDB_ERROR_MSGS:q_}=Ur(),Uce=require("minimist"),{server:HY}=(ur(),ie(vi)),{DATABASES_PARAM_CONFIG:kc,CONFIG_PARAMS:Fr,CONFIG_PARAM_MAP:Dn}=qr,xY="Unable to get config value because config is uninitialized",GY="Config successfully initialized",FY="Error backing up config file",qY="Empty parameter sent to getConfigValue",AN=Cn.join(qr.PACKAGE_ROOT,"config","yaml",qr.HDB_DEFAULT_CONFIG_FILE),kY="Configuration successfully set. You must restart HarperDB for new config settings to take effect.",gN={logging_rotation_retain:"logging.rotation.retain",logging_rotation_rotate:"logging.rotation.rotate",logging_rotation_rotateinterval:"logging.rotation.rotateInterval",logging_rotation_rotatemodule:"logging.rotation.rotateModule",logging_rotation_timezone:"logging.rotation.timezone",logging_rotation_workerinterval:"logging.rotation.workerInterval"},k_,It,V_;IN.exports={createConfigFile:VY,getDefaultConfig:$Y,getConfigValue:bN,initConfig:Wm,flattenConfig:Yo,updateConfigValue:yN,updateConfigObject:KY,getConfiguration:zY,setConfiguration:JY,readConfigFile:zm,getClusteringRoutes:XY,initOldConfig:NN,getConfigFromFile:jY,getConfigFilePath:Qi,addConfig:ZY,deleteConfigFromFile:eK,getConfigObj:tK};function VY(e,t=!1){let r=oi(AN);k_=Yo(r.toJSON());let n;for(let c in e){let l=Dn[c.toLowerCase()];if(l===Fr.DATABASES){Array.isArray(e[c])?n=e[c]:n=Object.keys(e[c]).map(_=>({[_]:e[c][_]}));continue}if(!l&&(c.endsWith("_package")||c.endsWith("_port"))&&(l=c),l!==void 0){let _=l.split("_"),u=Km(l,e[c]);l==="rootPath"&&u?.endsWith("/")&&(u=u.slice(0,-1));try{r.setIn([..._],u)}catch(d){Nt.error(d)}}}n&&ON(r,n),Qm(r,t);let s=r.toJSON();It=Yo(s);let i=r.getIn(["rootPath"]),o=Cn.join(i,qr.HDB_CONFIG_FILE);fr.createFileSync(o),fr.writeFileSync(o,String(r)),Nt.trace(`Config file written to ${o}`)}a(VY,"createConfigFile");function ON(e,t){let r;try{try{r=JSON.parse(t)}catch(n){if(!Bt.isObject(t))throw n;r=t}for(let n of r){let s=Object.keys(n)[0];if(n[s].hasOwnProperty(kc.TABLES))for(let i in n[s][kc.TABLES])for(let o in n[s][kc.TABLES][i]){let c=n[s][kc.TABLES][i][o],l=[Fr.DATABASES,s,kc.TABLES,i,o];e.hasIn(l)?e.setIn(l,c):e.addIn(l,c)}else for(let i in n[s]){let o=n[s][i],c=[Fr.DATABASES,s,i];e.hasIn(c)?e.setIn(c,o):e.addIn(c,o)}}}catch(n){Nt.error("Error parsing schemas CLI/env config arguments",n)}}a(ON,"setSchemasConfig");function $Y(e){if(k_===void 0){let r=oi(AN);k_=Yo(r.toJSON())}let t=Dn[e.toLowerCase()];if(t!==void 0)return k_[t.toLowerCase()]}a($Y,"getDefaultConfig");function bN(e){if(e==null){Nt.error(qY);return}if(It===void 0){Nt.trace(xY);return}let t=Dn[e.toLowerCase()];if(t!==void 0)return It[t.toLowerCase()]}a(bN,"getConfigValue");function Qi(e=Bt.getPropsFilePath()){let t=Bt.getEnvCliRootPath();return t?Cn.join(t,qr.HDB_CONFIG_FILE):RN(e).get(qr.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY)}a(Qi,"getConfigFilePath");function Wm(e=!1){if(It===void 0||e){let t;if(!Bt.noBootFile()){t=Bt.getPropsFilePath();try{fr.accessSync(t,fr.constants.F_OK|fr.constants.R_OK)}catch(i){throw Nt.error(i),new Error(`HarperDB properties file at path ${t} does not exist`)}}let r=Qi(t),n;if(r.includes("config/settings.js"))try{NN(r);return}catch(i){if(i.code!==qr.NODE_ERROR_CODES.ENOENT)throw i}try{n=oi(r)}catch(i){if(i.code===qr.NODE_ERROR_CODES.ENOENT){Nt.trace(`HarperDB config file not found at ${r}.
7
- This can occur during early stages of install where the config file has not yet been created`);return}else throw Nt.error(i),new Error(`Error reading HarperDB config file at ${r}`)}YY(n,r),Qm(n);let s=n.toJSON();if(HY.config=s,It=Yo(s),It.logging_rotation_rotate)for(let i in gN)It[i]&&Nt.error(`Config ${gN[i]} has been deprecated. Please check https://docs.harperdb.io/docs/ for further details.`);Nt.trace(GY)}}a(Wm,"initConfig");function YY(e,t){let r=e.getIn(["rootPath"]),n=!1;e.hasIn(["storage","path"])||(e.setIn(["storage","path"],Cn.join(r,"database")),n=!0),e.hasIn(["clustering","leafServer","streams","path"])||(e.setIn(["clustering","leafServer","streams","path"],Cn.join(r,"clustering","leaf")),n=!0),e.hasIn(["logging","rotation","path"])||(e.setIn(["logging","rotation","path"],Cn.join(r,"log")),n=!0),e.hasIn(["clustering","tls","verify"])||(e.setIn(["clustering","tls","verify"],!0),n=!0),e.hasIn(["authentication"])||(e.addIn(["authentication"],{cacheTTL:3e4,enableSessions:!0,operationTokenTimeout:e.getIn(["operationsApi","authentication","operationTokenTimeout"])??"1d",refreshTokenTimeout:e.getIn(["operationsApi","authentication","refreshTokenTimeout"])??"30d"}),n=!0),e.hasIn(["analytics"])||(e.addIn(["analytics"],{aggregatePeriod:60}),n=!0),n&&(Nt.trace("Updating config file with missing config params"),fr.writeFileSync(t,String(e)))}a(YY,"checkForUpdatedConfig");function Qm(e,t=!1){let r=e.toJSON();r.componentsRoot=r.componentsRoot??r?.customFunctions?.root,r?.http?.threads&&(r.threads=r?.http?.threads);let n=LY(r,t);if(n.error)throw q_.CONFIG_VALIDATION(n.error.message);typeof n.value.threads=="object"?e.setIn(["threads","count"],n.value.threads.count):e.setIn(["threads"],n.value.threads),e.setIn(["componentsRoot"],n.value.componentsRoot),e.setIn(["logging","root"],n.value.logging.root),e.setIn(["storage","path"],n.value.storage.path),e.setIn(["logging","rotation","path"],n.value.logging.rotation.path),e.setIn(["clustering","leafServer","streams","path"],n.value.clustering.leafServer.streams?.path),e.setIn(["operationsApi","network","domainSocket"],n.value?.operationsApi?.network?.domainSocket)}a(Qm,"validateConfig");function KY(e,t){It===void 0&&(It={});let r=Dn[e.toLowerCase()];if(r===void 0){Nt.trace(`Unable to update config object because config param '${e}' does not exist`);return}It[r.toLowerCase()]=t}a(KY,"updateConfigObject");function yN(e,t,r=void 0,n=!1,s=!1,i=!1){It===void 0&&Wm();let o=bN(Dn.hdb_root),c=Cn.join(o,qr.HDB_CONFIG_FILE),l=oi(c),_;if(r===void 0&&e.toLowerCase()===Fr.DATABASES)_=t;else if(r===void 0){let E;if(i)E=e;else if(E=Dn[e.toLowerCase()],E===void 0)throw new Error(`Unable to update config, unrecognized config parameter: ${e}`);let f=E.split("_"),h=Km(E,t);l.setIn([...f],h)}else for(let E in r){let f=Dn[E.toLowerCase()];if(f===Fr.HTTP_SECUREPORT&&r[E]===It[Fr.HTTP_PORT]?.toString()&&l.setIn(["http","port"],null),f===Fr.OPERATIONSAPI_NETWORK_SECUREPORT&&r[E]===It[Fr.OPERATIONSAPI_NETWORK_PORT.toLowerCase()]?.toString()&&l.setIn(["operationsApi","network","port"],null),f===Fr.DATABASES){_=r[E];continue}if(f?.startsWith("threads_")){let h=l.getIn(["threads"]);h>=0&&(l.deleteIn(["threads"]),l.setIn(["threads","count"],h))}if(!f&&(E.endsWith("_package")||E.endsWith("_port"))&&(f=E),f!==void 0){let h=f.split("_"),p=qr.LEGACY_CONFIG_PARAMS[E.toUpperCase()];p&&p.startsWith("customFunctions")&&l.hasIn(p.split("_"))&&(f=p,h=p.split("_"));let S=Km(f,r[E]);f==="rootPath"&&S?.endsWith("/")&&(S=S.slice(0,-1));try{h.length>1&&typeof l.getIn(h.slice(0,-1))=="boolean"&&l.deleteIn(h.slice(0,-1)),l.setIn([...h],S)}catch(T){Nt.error(T)}}}_&&ON(l,_),Qm(l);let u=l.getIn(["rootPath"]),d=Cn.join(u,qr.HDB_CONFIG_FILE);n===!0&&WY(c,u),fr.writeFileSync(d,String(l)),s&&(It=Yo(l.toJSON())),Nt.trace(`Config parameter: ${e} updated with value: ${t}`)}a(yN,"updateConfigValue");function WY(e,t){try{let r=Cn.join(t,"backup",`${qr.HDB_CONFIG_FILE}.bak`);fr.copySync(e,r),Nt.trace(`Config file: ${e} backed up to: ${r}`)}catch(r){Nt.error(FY),Nt.error(r)}}a(WY,"backupConfigFile");var QY=["databases"];function Yo(e){return e.http&&Object.assign(e.http,e?.customFunctions?.network),e?.operationsApi?.network&&(e.operationsApi.network=Object.assign({},e.http,e.operationsApi.network)),e?.operationsApi&&(e.operationsApi.tls=Object.assign({},e.tls,e.operationsApi.tls)),V_=e,r(e);function r(n){let s={};for(let i in n)if(n.hasOwnProperty(i)){if(typeof n[i]=="object"&&n[i]!==null&&!Array.isArray(n[i])&&!QY.includes(i)){let o=r(n[i]);for(let c in o){if(!o.hasOwnProperty(c))continue;c!=="package"&&(i=i.toLowerCase());let l=i+"_"+c;!Fr[l.toUpperCase()]&&Dn[l]&&(s[Dn[l].toLowerCase()]=o[c]),s[l]=o[c]}}n[i]!==void 0&&(s[i.toLowerCase()]=n[i])}return s}a(r,"squashObj")}a(Yo,"flattenConfig");function Km(e,t){if(e===Fr.CLUSTERING_NODENAME||e===Fr.CLUSTERING_USER){if(t==null)return t;if(!isNaN(t))return t.toString();if(typeof t=="string"&&t.toLowerCase()==="true"||typeof t=="string"&&t.toLowerCase()==="false")return t}else{if(PY(t))return parseFloat(t);if(t===!0||t===!1||Array.isArray(t)||Bt.isObject(t)||t===null)return t;if(typeof t=="string"&&t.toLowerCase()==="true")return!0;if(typeof t=="string"&&t.toLowerCase()==="false")return!1}if(t===void 0||t.toLowerCase()==="undefined")return null;if(typeof t=="string"&&(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]")))try{return JSON.parse(t)}catch{}return Bt.autoCast(t)}a(Km,"castConfigValue");function zY(){let e=Bt.getPropsFilePath(),t=Qi(e);return oi(t).toJSON()}a(zY,"getConfiguration");async function JY(e){let{operation:t,hdb_user:r,hdb_auth_header:n,...s}=e;try{return yN(void 0,void 0,s,!0),kY}catch(i){throw typeof i=="string"||i instanceof String?vY(i,i,BY.BAD_REQUEST,void 0,void 0,!0):i}}a(JY,"setConfiguration");function zm(){let e=Bt.getPropsFilePath();try{fr.accessSync(e,fr.constants.F_OK|fr.constants.R_OK)}catch(n){if(!Bt.noBootFile())throw Nt.error(n),new Error(`HarperDB properties file at path ${e} does not exist`)}let t=Qi(e);return oi(t).toJSON()}a(zm,"readConfigFile");function oi(e){return MY.parseDocument(fr.readFileSync(e,"utf8"),{simpleKeys:!0})}a(oi,"parseYamlDoc");function XY(){let e=zm(),t=e?.clustering?.hubServer?.cluster?.network?.routes;t=Bt.isEmptyOrZeroLength(t)?[]:t;let r=TN(t);if(r)throw q_.CONFIG_VALIDATION(r.message);let n=e?.clustering?.leafServer?.network?.routes;n=Bt.isEmptyOrZeroLength(n)?[]:n;let s=TN(n);if(s)throw q_.CONFIG_VALIDATION(s.message);if(!Bt.isEmptyOrZeroLength(n)&&!Bt.isEmptyOrZeroLength(t)){let i=t.filter(o=>n.some(c=>c.host===o.host&&c.port===o.port));if(!Bt.isEmptyOrZeroLength(i)){let o=`Duplicate hub and leaf routes found ${JSON.stringify(i)}`;throw q_.CONFIG_VALIDATION(o)}}return{hub_routes:t,leaf_routes:n}}a(XY,"getClusteringRoutes");function NN(e){let t=RN(e);It={};for(let r in Dn){let n=t.get(r.toUpperCase());if(Bt.isEmpty(n)||typeof n=="string"&&n.trim().length===0)continue;let s=Dn[r].toLowerCase();s===Fr.LOGGING_ROOT?It[s]=Cn.dirname(n):It[s]=n}return It}a(NN,"initOldConfig");function jY(e){let t=zm();return UY.get(t,e.replaceAll("_","."))}a(jY,"getConfigFromFile");async function ZY(e,t){let r=oi(Qi());r.hasIn([e])?r.setIn([e],t):r.addIn([e],t),await fr.writeFile(Qi(),String(r))}a(ZY,"addConfig");function eK(e){let t=Qi(Bt.getPropsFilePath()),r=oi(t);r.deleteIn(e);let n=r.getIn(["rootPath"]),s=Cn.join(n,qr.HDB_CONFIG_FILE);fr.writeFileSync(s,String(r))}a(eK,"deleteConfigFromFile");function tK(){return V_||(Wm(),V_)}a(tK,"getConfigObj")});var CN=g((Hce,wN)=>{"use strict";var $_=U(),Y_=class{static{a(this,"BaseLicense")}constructor(t=0,r=$_.RAM_ALLOCATION_ENUM.DEFAULT,n=$_.LICENSE_VALUES.VERSION_DEFAULT,s){this.exp_date=t,this.ram_allocation=r,this.version=n,this.fingerprint=s}},Jm=class extends Y_{static{a(this,"ExtendedLicense")}constructor(t=0,r=$_.RAM_ALLOCATION_ENUM.DEFAULT,n=$_.LICENSE_VALUES.VERSION_DEFAULT,s,i=!1){super(t,r,n,s),this.enterprise=i}};wN.exports={BaseLicense:Y_,ExtendedLicense:Jm}});var zi=g((Gce,vN)=>{"use strict";var Wo=require("fs-extra"),LN=H_(),MN=require("crypto"),rK=require("moment"),nK=require("uuid").v4,tr=K(),jm=require("path"),sK=z(),ai=U(),{totalmem:DN}=require("os"),iK=CN().ExtendedLicense,Ko="invalid license key format",oK="061183",aK="mofi25",cK="aes-256-cbc",lK=16,uK=32,PN=te();PN.initSync();var Xm;vN.exports={validateLicense:UN,generateFingerPrint:dK,licenseSearch:tp,getLicense:hK,checkMemoryLimit:mK};function Zm(){return jm.join(PN.getHdbBasePath(),ai.LICENSE_KEY_DIR_NAME,ai.LICENSE_FILE_NAME)}a(Zm,"getLicenseDirPath");function _K(){let e=Zm();return jm.join(e,ai.LICENSE_FILE_NAME)}a(_K,"getLicenseFilePath");function ep(){let e=Zm();return jm.join(e,ai.REG_KEY_FILE_NAME)}a(ep,"getFingerPrintFilePath");async function dK(){let e=ep();try{return await Wo.readFile(e,"utf8")}catch(t){if(t.code==="ENOENT")return await fK();throw tr.error(`Error writing fingerprint file to ${e}`),tr.error(t),new Error("There was an error generating the fingerprint")}}a(dK,"generateFingerPrint");async function fK(){let e=nK(),t=LN.hash(e),r=ep();try{await Wo.mkdirp(Zm()),await Wo.writeFile(r,t)}catch(n){if(n.code==="EEXIST")return t;throw tr.error(`Error writing fingerprint file to ${r}`),tr.error(n),new Error("There was an error generating the fingerprint")}return t}a(fK,"writeFingerprint");function UN(e,t){let r={valid_license:!1,valid_date:!1,valid_machine:!1,exp_date:null,ram_allocation:ai.RAM_ALLOCATION_ENUM.DEFAULT,version:ai.LICENSE_VALUES.VERSION_DEFAULT};if(!e)return tr.error("empty license key passed to validate."),r;let n=ep(),s=!1;try{s=Wo.statSync(n)}catch(i){tr.error(i)}if(s){let i;try{i=Wo.readFileSync(n,"utf8")}catch{tr.error("error validating this machine in the license"),r.valid_machine=!1;return}let o=e.split(aK),c=o[1];c=Buffer.concat([Buffer.from(c)],lK);let l=Buffer.concat([Buffer.from(i)],uK),_=MN.createDecipheriv(cK,l,c);r.valid_date=!0,r.valid_license=!0,r.valid_machine=!0;let u=null;try{u=_.update(o[0],"hex","utf8"),u.trim(),u+=_.final("utf8")}catch{let f=EK(o[0],i);if(f)u=f;else throw r.valid_license=!1,r.valid_machine=!1,console.error(Ko),tr.error(Ko),new Error(Ko)}let d;if(isNaN(u))try{d=JSON.parse(u),r.version=d.version,r.exp_date=d.exp_date,isNaN(r.exp_date)&&(r.exp_date=new Date(r.exp_date).getTime()),d.ram_allocation&&(r.ram_allocation=d.ram_allocation)}catch{throw console.error(Ko),tr.error(Ko),new Error(Ko)}else r.exp_date=u;r.exp_date<rK().valueOf()&&(r.valid_date=!1),LN.validate(o[1],`${oK}${i}${t}`)||(r.valid_license=!1)}else r.valid_license=!1,r.valid_machine=!1;return r.valid_license&&r.valid_machine&&r.valid_date||tr.error("Invalid licence"),r}a(UN,"validateLicense");function EK(e,t){try{let r=MN.createDecipher("aes192",t),n=r.update(e,"hex","utf8");return n.trim(),n+=r.final("utf8"),n}catch{tr.warn("Check old license failed")}}a(EK,"checkOldLicense");function tp(){let e=new iK,t=[];try{t=Wo.readFileSync(_K(),"utf-8").split(ai.NEW_LINE)}catch(r){r.code==="ENOENT"?tr.info("no license file found"):tr.error(`could not search for licenses due to: '${r.message}`)}for(let r=0;r<t.length;++r){let n=t[r];try{if(sK.isEmptyOrZeroLength(n))continue;let s=JSON.parse(n),i=UN(s.license_key,s.company);i.valid_machine===!0&&i.valid_date===!0&&i.valid_machine===!0&&(e.exp_date=i.exp_date>e.exp_date?i.exp_date:e.exp_date,e.ram_allocation=i.ram_allocation,e.enterprise=!0)}catch(s){tr.error("There was an error parsing the license string."),tr.error(s),e.ram_allocation=ai.RAM_ALLOCATION_ENUM.DEFAULT,e.enterprise=!1}}return Xm=e,e}a(tp,"licenseSearch");async function hK(){return Xm||await tp(),Xm}a(hK,"getLicense");function mK(){let e=tp().ram_allocation,t=process.constrainedMemory?.()||DN();if(t=Math.round(Math.min(t,DN())/2**20),t>e)return`This server has more memory (${t}MB) than HarperDB is licensed for (${e}MB), this should only be used for educational and development purposes.`}a(mK,"checkMemoryLimit")});var un=g(($ce,XN)=>{"use strict";var GN="username is required",FN="nothing to update, must supply active, role or password to update",qN="password cannot be an empty string",kN="If role is specified, it cannot be empty.",VN="active must be true or false";XN.exports={addUser:yK,alterUser:NK,dropUser:wK,getSuperUser:MK,userInfo:CK,listUsers:W_,listUsersExternal:DK,setUsersToGlobal:zo,findAndValidateUser:zN,getClusterUser:PK,USERNAME_REQUIRED:GN,ALTERUSER_NOTHING_TO_UPDATE:FN,EMPTY_PASSWORD:qN,EMPTY_ROLE:kN,ACTIVE_BOOLEAN:VN};var $N=ln(),pK=Yi(),sp=H_(),YN=cN(),KN=Gr(),ip=As(),kr=z(),WN=require("validate.js"),Oe=K(),{promisify:SK}=require("util"),op=Rs(),BN=U(),HN=ct(),TK=Er(),qce=te(),kce=zi(),gK=Gi(),{table:Vce}=(Ae(),ie(ke)),{handleHDBError:jn,hdb_errors:RK}=ne(),{HTTP_STATUS_CODES:Zn,AUTHENTICATION_ERROR_MSGS:rp,HDB_ERROR_MSGS:Qo}=RK,{UserEventMsg:ap}=Ln(),np=require("lodash"),{server:cp}=(ur(),ie(vi)),AK=K();cp.getUser=(e,t)=>zN(e,t,t!=null);var QN={username:!0,active:!0,role:!0,password:!0},xN=new Map,K_=KN.searchByValue,OK=KN.searchByHash,bK=SK(pK.delete);async function yK(e){let t=WN.cleanAttributes(e,QN),r=YN.addUserValidation(t);if(r)throw jn(new Error,r.message,Zn.BAD_REQUEST,void 0,void 0,!0);let n={schema:"system",table:"hdb_role",search_attribute:"role",search_value:t.role,get_attributes:["id","permission","role"]},s;try{s=await K_(n),s=s&&Array.from(s)}catch(l){throw Oe.error("There was an error searching for a role in add user"),Oe.error(l),l}if(!s||s.length<1)throw jn(new Error,Qo.ROLE_NAME_NOT_FOUND(t.role),Zn.NOT_FOUND,void 0,void 0,!0);if(s.length>1)throw jn(new Error,Qo.DUP_ROLES_FOUND(t.role),Zn.CONFLICT,void 0,void 0,!0);s[0].permission.cluster_user===!0&&(t.hash=op.encrypt(t.password)),t.password=sp.hash(t.password),t.role=s[0].id;let i={operation:"insert",schema:"system",table:"hdb_user",records:[t]},o;try{o=await $N.insert(i)}catch(l){throw Oe.error("There was an error searching for a user."),Oe.error(l),l}Oe.debug(o);try{await zo()}catch(l){throw Oe.error("Got an error setting users to global"),Oe.error(l),l}if(o.skipped_hashes.length===1)throw jn(new Error,Qo.USER_ALREADY_EXISTS(t.username),Zn.CONFLICT,void 0,void 0,!0);let c=Object.assign({},t);return c.role=s[0],ip.signalUserChange(new ap(process.pid)),`${c.username} successfully added`}a(yK,"addUser");async function NK(e){let t=WN.cleanAttributes(e,QN);if(kr.isEmptyOrZeroLength(t.username))throw new Error(GN);if(kr.isEmptyOrZeroLength(t.password)&&kr.isEmptyOrZeroLength(t.role)&&kr.isEmptyOrZeroLength(t.active))throw new Error(FN);if(!kr.isEmpty(t.password)&&kr.isEmptyOrZeroLength(t.password.trim()))throw new Error(qN);if(!kr.isEmpty(t.active)&&!kr.isBoolean(t.active))throw new Error(VN);let r=IK(t.username);if(!kr.isEmpty(t.password)&&!kr.isEmptyOrZeroLength(t.password.trim())&&(r&&(t.hash=op.encrypt(t.password)),t.password=sp.hash(t.password)),t.role==="")throw new Error(kN);if(t.role){let i={schema:"system",table:"hdb_role",search_attribute:"role",search_value:t.role,get_attributes:["*"]},o;try{o=Array.from(await K_(i)||[])}catch(c){throw Oe.error("Got an error searching for a role."),Oe.error(c),c}if(!o||o.length===0){let c=Qo.ALTER_USER_ROLE_NOT_FOUND(t.role);throw Oe.error(c),jn(new Error,c,Zn.NOT_FOUND,void 0,void 0,!0)}if(o.length>1){let c=Qo.ALTER_USER_DUP_ROLES(t.role);throw Oe.error(c),jn(new Error,c,Zn.CONFLICT,void 0,void 0,!0)}t.role=o[0].id}let n={operation:"update",schema:"system",table:"hdb_user",records:[t]},s;try{s=await $N.update(n)}catch(i){throw Oe.error("Error during update."),Oe.error(i),i}try{await zo()}catch(i){throw Oe.error("Got an error setting users to global"),Oe.error(i),i}return ip.signalUserChange(new ap(process.pid)),s}a(NK,"alterUser");function IK(e){let t=!1,r=global.hdb_users.get(e);return r&&r.role.permission.cluster_user===!0&&(t=!0),t}a(IK,"isClusterUser");async function wK(e){try{let t=YN.dropUserValidation(e);if(t)throw new Error(t);let r={table:"hdb_user",schema:"system",hash_values:[e.username]};if(kr.isEmpty(global.hdb_users.get(e.username)))throw jn(new Error,Qo.USER_NOT_EXIST(e.username),Zn.NOT_FOUND,void 0,void 0,!0);let n;try{n=await bK(r)}catch(s){throw Oe.error("Got an error deleting a user."),Oe.error(s),s}Oe.debug(n);try{await zo()}catch(s){throw Oe.error("Got an error setting users to global."),Oe.error(s),s}return ip.signalUserChange(new ap(process.pid)),`${e.username} successfully deleted`}catch(t){throw t}}a(wK,"dropUser");async function CK(e){let t={};try{if(!e||!e.hdb_user)return"There was no user info in the body";t=np.cloneDeep(e.hdb_user);let r={schema:"system",table:"hdb_role",hash_values:[t.role.id],get_attributes:["*"]},n;try{n=await OK(r)}catch(s){throw Oe.error("Got an error searching for a role."),Oe.error(s),s}t.role=n[0],delete t.password,delete t.refresh_token,delete t.hash}catch(r){throw Oe.error(r),r}return t}a(CK,"userInfo");async function DK(){let e;try{e=await W_()}catch(t){throw Oe.error("Got an error listing users."),Oe.error(t),t}try{e.forEach(t=>{delete t.password,delete t.hash,delete t.refresh_token})}catch{throw new Error("there was an error massaging the user data")}return[...e.values()]}a(DK,"listUsersExternal");async function W_(){try{let e={schema:"system",table:"hdb_role",search_value:"*",search_attribute:"role",get_attributes:["*"]},t;try{t=await K_(e)}catch(o){throw Oe.error("Got an error searching for roles."),Oe.error(o),o}let r={};for(let o of t)r[o.id]=np.cloneDeep(o);if(Object.keys(r).length===0)return null;let n={schema:"system",table:"hdb_user",search_value:"*",search_attribute:"username",get_attributes:["*"]},s;try{s=await K_(n)}catch(o){throw Oe.error("Got an error searching for users."),Oe.error(o),o}let i=new Map;for(let o of s)o=np.cloneDeep(o),o.role=r[o.role],LK(o.role),i.set(o.username,o);return i}catch(e){throw Oe.error("got an error listing users"),Oe.error(e),kr.errorizeMessage(e)}return null}a(W_,"listUsers");function LK(e){try{if(!e){Oe.error("invalid user role found.");return}e.permission.system||(e.permission.system={}),e.permission.system.tables||(e.permission.system.tables={});for(let t of Object.keys(gK)){let r={read:!!e.permission.super_user,insert:!1,update:!1,delete:!1,attribute_permissions:[]};e.permission.system.tables[t]=r}}catch(t){Oe.error("Got an error trying to set system permissions."),Oe.error(t)}}a(LK,"appendSystemTablesToRole");async function zo(){try{let e=await W_();global.hdb_users=e}catch(e){throw Oe.error(e),e}}a(zo,"setUsersToGlobal");async function zN(e,t,r=!0){global.hdb_users||await zo();let n=global.hdb_users.get(e);if(!n){if(!r)return{username:e};throw jn(new Error,rp.GENERIC_AUTH_FAIL,Zn.UNAUTHORIZED,void 0,void 0,!0)}if(n&&!n.active)throw jn(new Error,rp.USER_INACTIVE,Zn.UNAUTHORIZED,void 0,void 0,!0);let s={active:n.active,username:n.username};if(n.refresh_token&&(s.refresh_token=n.refresh_token),n.role&&(s.role=n.role),r===!0){if(xN.get(t)===n.password)return s;if(sp.validate(n.password,t))xN.set(t,n.password);else throw jn(new Error,rp.GENERIC_AUTH_FAIL,Zn.UNAUTHORIZED,void 0,void 0,!0)}return s}a(zN,"findAndValidateUser");async function MK(){global.hdb_users||await zo();for(let[,e]of global.hdb_users)if(e.role.role==="super_user")return e}a(MK,"getSuperUser");async function PK(){let e=await W_(),t=TK.getConfigFromFile(BN.CONFIG_PARAMS.CLUSTERING_USER),r=e.get(t);if(!kr.isEmpty(r)&&r?.role?.role===BN.ROLE_TYPES_ENUM.CLUSTER_USER)return r.decrypt_hash=op.decrypt(r.hash),r.uri_encoded_d_hash=encodeURIComponent(r.decrypt_hash),r.uri_encoded_name=encodeURIComponent(r.username),r.sys_name=r.username+HN.SERVER_SUFFIX.ADMIN,r.sys_name_encoded=r.uri_encoded_name+HN.SERVER_SUFFIX.ADMIN,r}a(PK,"getClusterUser");var JN=[];cp.invalidateUser=function(e){for(let t of JN)try{t(e)}catch(r){AK.error("Error invalidating user",r)}};cp.onInvalidatedUser=function(e){JN.push(e)}});var $c=g((Qce,tI)=>{"use strict";var Ji=K(),Vr=U(),UK=Cy(),Kce=ni(),Wce=ri(),vK=un(),{validateEvent:jN}=Ln(),Vc=wn(),BK=require("process"),{resetDatabases:HK}=(Ae(),ie(ke)),xK={[Vr.ITC_EVENT_TYPES.SCHEMA]:GK,[Vr.ITC_EVENT_TYPES.USER]:eI};async function GK(e){let t=jN(e);if(t){Ji.error(t);return}Ji.trace("ITC schemaHandler received schema event:",e),await UK(e.message),await FK(e.message)}a(GK,"schemaHandler");async function FK(e){try{Vc.resetReadTxn(Vr.SYSTEM_SCHEMA_NAME,Vr.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME),Vc.resetReadTxn(Vr.SYSTEM_SCHEMA_NAME,Vr.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME),Vc.resetReadTxn(Vr.SYSTEM_SCHEMA_NAME,Vr.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME);let t=HK();e.table&&e.database&&await t[e.database][e.table].put(Symbol.for("write-verify"),null)}catch(t){Ji.error(t)}}a(FK,"syncSchemaMetadata");var ZN=[];async function eI(e){try{try{Vc.resetReadTxn(Vr.SYSTEM_SCHEMA_NAME,Vr.SYSTEM_TABLE_NAMES.USER_TABLE_NAME),Vc.resetReadTxn(Vr.SYSTEM_SCHEMA_NAME,Vr.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME)}catch(r){Ji.warn(r)}let t=jN(e);if(t){Ji.error(t);return}Ji.trace(`ITC userHandler ${Vr.HDB_ITC_CLIENT_PREFIX}${BK.pid} received user event:`,e),await vK.setUsersToGlobal();for(let r of ZN)r()}catch(t){Ji.error(t)}}a(eI,"userHandler");eI.addListener=function(e){ZN.push(e)};tI.exports=xK});var Ln=g((ele,nI)=>{"use strict";var Jce=K(),lp=z(),qK=U(),{ITC_ERRORS:Yc}=Ur(),{parentPort:Xce,threadId:kK,isMainThread:VK,workerData:jce}=require("worker_threads"),{onMessageFromWorkers:$K,broadcast:Zce,broadcastWithAcknowledgement:YK}=it();nI.exports={sendItcEvent:KK,validateEvent:rI,SchemaEventMsg:WK,UserEventMsg:QK};var Q_;$K(async(e,t)=>{Q_=Q_||$c(),rI(e),Q_[e.type]&&await Q_[e.type](e),e.requestId&&t&&t.postMessage({type:"ack",id:e.requestId})});function KK(e){return!VK&&e.message&&(e.message.originator=kK),YK(e)}a(KK,"sendItcEvent");function rI(e){if(typeof e!="object")return Yc.INVALID_ITC_DATA_TYPE;if(!e.hasOwnProperty("type")||lp.isEmpty(e.type))return Yc.MISSING_TYPE;if(!e.hasOwnProperty("message")||lp.isEmpty(e.message))return Yc.MISSING_MSG;if(!e.message.hasOwnProperty("originator")||lp.isEmpty(e.message.originator))return Yc.MISSING_ORIGIN;if(qK.ITC_EVENT_TYPES[e.type.toUpperCase()]===void 0)return Yc.INVALID_EVENT(e.type)}a(rI,"validateEvent");function WK(e,t,r,n=void 0,s=void 0){this.originator=e,this.operation=t,this.schema=r,this.table=n,this.attribute=s}a(WK,"SchemaEventMsg");function QK(e){this.originator=e}a(QK,"UserEventMsg")});var As=g((nle,aI)=>{"use strict";var sI=U(),rle=z(),z_=K(),iI=Ny(),Jo,{sendItcEvent:oI}=Ln();function zK(e){try{z_.trace("signalSchemaChange called with message:",e),Jo=Jo||$c();let t=new iI(sI.ITC_EVENT_TYPES.SCHEMA,e);return Jo.schema(t),oI(t)}catch(t){z_.error(t)}}a(zK,"signalSchemaChange");function JK(e){try{z_.trace("signalUserChange called with message:",e),Jo=Jo||$c();let t=new iI(sI.ITC_EVENT_TYPES.USER,e);return Jo.user(t),oI(t)}catch(t){z_.error(t)}}a(JK,"signalUserChange");aI.exports={signalSchemaChange:zK,signalUserChange:JK}});var J_=g((ile,lI)=>{"use strict";var cI=z(),XK=U(),jK=K(),ZK=b_(),eW=O_(),tW=As(),{SchemaEventMsg:rW}=Ln(),nW="already exists in";lI.exports=sW;async function sW(e,t,r){if(cI.isEmptyOrZeroLength(r))return r;let n=[];cI.isEmptyOrZeroLength(t.attributes)||t.attributes.forEach(i=>{n.push(i.attribute)});let s=r.filter(i=>n.indexOf(i)<0);return s.length===0||await Promise.all(s.map(async i=>{await iW(e,t.schema,t.name,i)})),s}a(sW,"lmdbCheckForNewAttributes");async function iW(e,t,r,n){let s=new eW(t,r,n,void 0,!0);e&&(s.hdb_auth_header=e);try{await oW(s)}catch(i){if(typeof i=="object"&&i.message!==void 0&&i.message.includes(nW))jK.warn(`attribute ${t}.${r}.${n} already exists`);else throw i}}a(iW,"createNewAttribute");async function oW(e){let t;return t=await ZK(e),tW.signalSchemaChange(new rW(process.pid,XK.OPERATIONS_ENUM.CREATE_ATTRIBUTE,e.schema,e.table,e.attribute)),t}a(oW,"createAttribute")});var Xo=g((ale,uI)=>{"use strict";var up=class{static{a(this,"LMDBTransactionObject")}constructor(t,r,n,s,i=void 0){this.operation=t,this.user_name=r,this.timestamp=n,this.hash_values=s,this.origin=i}};uI.exports=up});var dI=g((lle,_I)=>{"use strict";var aW=Xo(),cW=U().OPERATIONS_ENUM,_p=class extends aW{static{a(this,"LMDBInsertTransactionObject")}constructor(t,r,n,s,i=void 0){super(cW.INSERT,r,n,s,i),this.records=t}};_I.exports=_p});var EI=g((_le,fI)=>{"use strict";var lW=Xo(),uW=U().OPERATIONS_ENUM,dp=class extends lW{static{a(this,"LMDBUpdateTransactionObject")}constructor(t,r,n,s,i,o=void 0){super(uW.UPDATE,n,s,i,o),this.records=t,this.original_records=r}};fI.exports=dp});var mI=g((fle,hI)=>{"use strict";var _W=Xo(),dW=U().OPERATIONS_ENUM,fp=class extends _W{static{a(this,"LMDBUpsertTransactionObject")}constructor(t,r,n,s,i,o=void 0){super(dW.UPSERT,n,s,i,o),this.records=t,this.original_records=r}};hI.exports=fp});var SI=g((hle,pI)=>{"use strict";var fW=Xo(),EW=U().OPERATIONS_ENUM,Ep=class extends fW{static{a(this,"LMDBDeleteTransactionObject")}constructor(t,r,n,s,i=void 0){super(EW.DELETE,n,s,t,i),this.original_records=r}};pI.exports=Ep});var Kc=g((Sle,AI)=>{"use strict";var ple=require("path"),TI=Ke(),hW=dI(),mW=EI(),pW=mI(),SW=SI(),jo=dt(),gI=z(),{CONFIG_PARAMS:TW}=U(),RI=te();RI.initSync();var X_=U().OPERATIONS_ENUM,{getTransactionAuditStorePath:gW}=ze();AI.exports=RW;async function RW(e,t){if(RI.get(TW.LOGGING_AUDITLOG)===!1)return;let r=gW(e.schema,e.table),n=await TI.openEnvironment(r,e.table,!0),s=AW(e,t);if(!(s===void 0||s.hash_values.length===0)&&n!==void 0){TI.initializeDBIs(n,jo.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,jo.TRANSACTIONS_DBIS);let i=s.timestamp;return await n.dbis[jo.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP].ifNoExists(i,()=>{n.dbis[jo.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP].put(i,s),gI.isEmpty(s.user_name)||n.dbis[jo.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].put(s.user_name,i);for(let o=0;o<s.hash_values.length;o++)n.dbis[jo.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE].put(s.hash_values[o],i)})}}a(RW,"writeTransaction");function AW(e,t){let r=gI.isEmpty(e.hdb_user)?void 0:e.hdb_user.username;if(e.operation===X_.INSERT)return new hW(e.records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===X_.UPDATE)return new mW(e.records,t.original_records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===X_.UPSERT)return new pW(e.records,t.original_records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===X_.DELETE)return new SW(t.deleted,t.original_records,r,t.txn_time,e.__origin)}a(AW,"createTransactionObject")});var hp=g((Rle,OI)=>{"use strict";var OW=Bc(),gle=Hc(),Wc=U(),bW=xc(),yW=ko().insertRecords,NW=Ke(),IW=K(),wW=J_(),{getSchemaPath:CW}=ze(),DW=Kc();OI.exports=LW;async function LW(e){try{let{schema_table:t,attributes:r}=OW(e);bW(e,r,t.hash_attribute),e.schema!==Wc.SYSTEM_SCHEMA_NAME&&(r.includes(Wc.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||r.push(Wc.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.includes(Wc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||r.push(Wc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let n=await wW(e.hdb_auth_header,t,r),s=CW(e.schema,e.table),i=await NW.openEnvironment(s,e.table),o=await yW(i,t.hash_attribute,r,e.records,e.__origin?.timestamp);try{await DW(e,o)}catch(c){IW.error(`unable to write transaction due to ${c.message}`)}return{written_hashes:o.written_hashes,skipped_hashes:o.skipped_hashes,schema_table:t,new_attributes:n,txn_time:o.txn_time}}catch(t){throw t}}a(LW,"lmdbCreateRecords")});var NI=g((Ole,yI)=>{"use strict";var bI=U(),MW=hp(),PW=Hc(),UW=require("fs-extra"),{getSchemaPath:vW}=ze();yI.exports=BW;async function BW(e){let t=[{name:e.schema,createddate:Date.now()}],r=new PW(bI.SYSTEM_SCHEMA_NAME,bI.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,void 0,t);await MW(r),await UW.mkdirp(vW(e.schema))}a(BW,"lmdbCreateSchema")});var wI=g((yle,II)=>{"use strict";var mp=class{static{a(this,"DeleteRecordsResponseObject")}constructor(t=[],r=[],n=void 0,s=[]){this.deleted=t,this.skipped=r,this.txn_time=n,this.original_records=s}};II.exports=mp});var MI=g((Dle,LI)=>{"use strict";var CI=Ke(),pp=vr(),Sp=Ur().LMDB_ERRORS_ENUM,HW=dt(),DI=K(),Ile=z(),xW=require("lmdb"),GW=wI(),FW=U(),{OVERFLOW_MARKER:wle,MAX_SEARCH_KEY_LENGTH:Cle}=HW,qW=FW.TIME_STAMP_NAMES_ENUM.UPDATED_TIME;async function kW(e,t,r,n){if(pp.validateEnv(e),t===void 0)throw new Error(Sp.HASH_ATTRIBUTE_REQUIRED);if(!Array.isArray(r))throw r===void 0?new Error(Sp.IDS_REQUIRED):new Error(Sp.IDS_MUST_BE_ITERABLE);try{let s=CI.listDBIs(e);CI.initializeDBIs(e,t,s);let i=new GW,o,c=[],l=[];for(let E=0,f=r.length;E<f;E++)try{o=r[E];let h=e.dbis[t].get(o);if(!h||n&&h[qW]>n){i.skipped.push(o);continue}let p=e.dbis[t].ifVersion(o,xW.IF_EXISTS,()=>{e.dbis[t].remove(o);for(let S=0;S<s.length;S++){let T=s[S];if(!h.hasOwnProperty(T)||T===t)continue;let R=e.dbis[T],b=h[T];if(b!=null)try{let C=pp.getIndexedValues(b);if(C)for(let H=0,v=C.length;H<v;H++)R.remove(C[H],o)}catch{DI.warn(`cannot delete from attribute: ${T}, ${b}:${o}`)}}});c.push(p),l.push(o),i.original_records.push(h)}catch(h){DI.warn(h),i.skipped.push(o)}let _=[],u=await Promise.all(c);for(let E=0,f=u.length;E<f;E++)u[E]===!0?i.deleted.push(l[E]):(i.skipped.push(l[E]),_.push(E));let d=0;for(let E=0;E<_.length;E++){let f=_[E];i.original_records.splice(f-d,1),d++}return i.txn_time=pp.getNextMonotonicTime(),i}catch(s){throw s}}a(kW,"deleteRecords");LI.exports={deleteRecords:kW}});var Qc=g((Mle,UI)=>{"use strict";var Zo=z(),VW=MI(),$W=Ke(),{getSchemaPath:YW}=ze(),KW=Kc(),WW=K();UI.exports=QW;async function QW(e,t=!0){let n=global.hdb_schema[e.schema][e.table].hash_attribute;if(Zo.isEmpty(n))throw new Error(`could not retrieve hash attribute for schema:${e.schema} and table ${e.table}`);try{if(Zo.isEmptyOrZeroLength(e.hash_values)&&!Zo.isEmptyOrZeroLength(e.records)){e.hash_values=[];for(let c=0;c<e.records.length;c++){let l=e.records[c][n];Zo.isEmpty(l)||e.hash_values.push(l)}}if(Zo.isEmptyOrZeroLength(e.hash_values))return PI([],[]);if(!Array.isArray(e.hash_values))throw new Error("hash_values must be an array");if(Zo.isEmptyOrZeroLength(e.records)){e.records=[];for(let c=0;c<e.hash_values.length;c++)e.records[c]={[n]:e.hash_values[c]}}let s=YW(e.schema,e.table),i=await $W.openEnvironment(s,e.table),o=await VW.deleteRecords(i,n,e.hash_values,e.__origin?.timestamp);try{t===!0&&await KW(e,o)}catch(c){WW.error(`unable to write transaction due to ${c.message}`)}return PI(o.deleted,o.skipped,o.txn_time)}catch(s){throw s}}a(QW,"lmdbDeleteRecords");function PI(e,t,r){let n=e.length+t.length,s=n===1?"record":"records";return{message:`${e.length} of ${n} ${s} successfully deleted`,deleted_hashes:e,skipped_hashes:t,txn_time:r}}a(PI,"createDeleteResponse")});var gp=g((vle,vI)=>{"use strict";var zW=U(),Ule=vr();function Tp(e,t){let r=Object.create(null);if(t.length===1&&zW.SEARCH_WILDCARDS.indexOf(t[0])>=0)Object.assign(r,e);else for(let n=0;n<t.length;n++){let s=t[n],i=e[s];r[s]=i===void 0?null:i}return r}a(Tp,"parseRow");function JW(e,t,r,n){let s=Tp(r,e);n.push(s)}a(JW,"searchAll");function XW(e,t,r,n){let s=Tp(r,e);n[t]=s}a(XW,"searchAllToMap");function jW(e,t,r){r[e]===void 0&&(r[e]=[]),r[e].push(t)}a(jW,"iterateDBI");function Xi(e,t,r,n,s){let i=Object.create(null);i[s]=e;let o;n===s?o=e:(o=t,n!==void 0&&(i[n]=o)),r[0].push(o),r[1].push(i)}a(Xi,"pushResults");function ZW(e,t,r,n,s,i){t.toString().endsWith(e)&&Xi(t,r,n,s,i)}a(ZW,"endsWith");function eQ(e,t,r,n,s,i){t.toString().includes(e)&&Xi(t,r,n,s,i)}a(eQ,"contains");function tQ(e,t,r,n,s,i){t>e&&Xi(t,r,n,s,i)}a(tQ,"greaterThanCompare");function rQ(e,t,r,n,s,i){t>=e&&Xi(t,r,n,s,i)}a(rQ,"greaterThanEqualCompare");function nQ(e,t,r,n,s,i){t<e&&Xi(t,r,n,s,i)}a(nQ,"lessThanCompare");function sQ(e,t,r,n,s,i){t<=e&&Xi(t,r,n,s,i)}a(sQ,"lessThanEqualCompare");vI.exports={parseRow:Tp,searchAll:JW,searchAllToMap:XW,iterateDBI:jW,endsWith:ZW,contains:eQ,greaterThanCompare:tQ,greaterThanEqualCompare:rQ,lessThanCompare:nQ,lessThanEqualCompare:sQ,pushResults:Xi}});var ea=g((Fle,kI)=>{"use strict";var ci=Ke(),Hle=K(),$r=vr(),j_=dt(),Et=Ur().LMDB_ERRORS_ENUM,xle=z(),iQ=U(),Z_=gp(),{parseRow:oQ}=Z_,Gle=require("lmdb"),{OVERFLOW_MARKER:BI,MAX_SEARCH_KEY_LENGTH:aQ}=j_;function HI(e,t,r,n=!1,s=void 0,i=void 0){return ji(e,t,r,(o,c)=>c.getRange({transaction:o,start:n?void 0:!1,end:n?!1:void 0,limit:s,offset:i,reverse:n}))}a(HI,"iterateFullIndex");function zc(e,t,r,n,s,i=!1,o=void 0,c=void 0,l=!1,_=!1){return ji(e,t,r,(u,d,E,f)=>{let R={transaction:u,start:i===!0?s:n,end:i===!0?n:s,reverse:i,limit:o,offset:c,inclusiveEnd:i===!0?!l:!_,exclusiveStart:i===!0?_:l};return f===r?(R.values=!1,d.getRange(R).map(b=>({value:b}))):d.getRange(R)})}a(zc,"iterateRangeBetween");function ji(e,t,r,n){let s=e.database||e,i=ci.openDBI(s,r);i[j_.DBI_DEFINITION_NAME].is_hash_attribute?t=r:t&&ci.openDBI(s,t);let o;e.database?o=e:(o=e.useReadTransaction(),o.database=e);let c=n(o,i,s,t);return c.transaction=o,e.database||(c.onDone=()=>{o.done()}),c}a(ji,"setupTransaction");function xI(e,t,r,n){let s;return function(i,o){if(typeof i=="string"&&i.endsWith(BI)){if(!s)if(r)s=ci.openDBI(e,r);else{let l=ci.listDBIs(e);for(let _=0,u=l.length;_<u&&(s=ci.openDBI(e,l[_]),!s[j_.DBI_DEFINITION_NAME].is_hash_attribute);_++);}i=s.get(o,{transaction:t,lazy:!0})[n]}return i}}a(xI,"getOverflowCheck");function cQ(e,t,r,n=!1,s=void 0,i=void 0){if($r.validateEnv(e),t===void 0)throw new Error(Et.HASH_ATTRIBUTE_REQUIRED);return ji(e,t,t,(o,c,l)=>(ed(r),r=Jc(l,r),c.getRange({transaction:o,start:n?void 0:!1,end:n?!1:void 0,limit:s,offset:i,reverse:n}).map(_=>oQ(_.value,r))))}a(cQ,"searchAll");function lQ(e,t,r,n=!1,s=void 0,i=void 0){if($r.validateEnv(e),t===void 0)throw new Error(Et.HASH_ATTRIBUTE_REQUIRED);ed(r),r=Jc(e.database||e,r);let o=new Map;for(let{key:c,value:l}of HI(e,t,t,n,s,i))o.set(c,Z_.parseRow(l,r));return o}a(lQ,"searchAllToMap");function uQ(e,t,r=!1,n=void 0,s=void 0){if($r.validateEnv(e),t===void 0)throw new Error(Et.ATTRIBUTE_REQUIRED);let i=Object.create(null),o=HI(e,void 0,t,r,n,s),c=o.transaction,l=xI(c.database,c,void 0,t);for(let{key:_,value:u}of o){let d=l(_,u);i[d]===void 0&&(i[d]=[]),i[d].push(u)}return i}a(uQ,"iterateDBI");function _Q(e,t){if($r.validateEnv(e),t===void 0)throw new Error(Et.HASH_ATTRIBUTE_REQUIRED);return ci.statDBI(e,t).entryCount}a(_Q,"countAll");function dQ(e,t,r,n,s=!1,i=void 0,o=void 0){return li(e,r,n),ji(e,t,r,(c,l,_,u)=>(n=$r.convertKeyValueToWrite(n),u===r?l.get(n,{transaction:c,lazy:!0})===void 0?[]:[{key:n,value:n}]:l.getValues(n,{transaction:c,reverse:s,limit:i,offset:o}).map(d=>({key:n,value:d}))))}a(dQ,"equals");function fQ(e,t,r){return li(e,t,r),ci.openDBI(e,t).getValuesCount(r)}a(fQ,"count");function EQ(e,t,r,n,s=!1,i=void 0,o=void 0){return li(e,r,n),ji(e,null,r,(c,l)=>{n=$r.convertKeyValueToWrite(n);let _=!0;typeof n=="number"&&(_=!1);let u;if(s===!0){let d;for(let E of l.getKeys({transaction:c,start:n}))if(!E.startsWith(n)){d=E;break}return d!==void 0&&(Number.isInteger(o)?o++:i++),u=l.getRange({transaction:c,start:d,end:void 0,reverse:s,limit:i,offset:o}).map(E=>{let{key:f}=E;if(f!==d){if(f.toString().startsWith(n))return E;if(_===!0)return u.DONE}}),u.filter(E=>E)}else return u=l.getRange({transaction:c,start:n,reverse:s,limit:i,offset:o}).map(d=>{if(d.key.toString().startsWith(n))return d;if(_===!0)return u.DONE}),_?u:u.filter(d=>d)})}a(EQ,"startsWith");function hQ(e,t,r,n,s=!1,i=void 0,o=void 0){return GI(e,t,r,n,s,i,o,!0)}a(hQ,"endsWith");function GI(e,t,r,n,s=!1,i=void 0,o=void 0,c=!1){return li(e,r,n),ji(e,null,r,(l,_,u,d)=>{let E=xI(u,l,d,r);return o=Number.isInteger(o)?o:0,_.getKeys({transaction:l,end:s?!1:void 0,reverse:s}).flatMap(f=>{let h=f.toString();return h.endsWith(BI)?_.getValues(f,{transaction:l}).map(p=>{let S=E(f,p);if(c?S.endsWith(n):S.includes(n))return{key:S,value:p}}).filter(p=>p):(c?h.endsWith(n):h.includes(n))?_[j_.DBI_DEFINITION_NAME].is_hash_attribute?{key:f,value:f}:_.getValues(f,{transaction:l}).map(p=>({key:f,value:p})):[]}).slice(o,i===void 0?void 0:i+(o||0))})}a(GI,"contains");function mQ(e,t,r,n,s=!1,i=void 0,o=void 0){li(e,r,n);let c=typeof n,l;return c==="string"?l="\uFFFF":c==="number"?l=1/0:c==="boolean"&&(l=!0),zc(e,t,r,n,l,s,i,o,!0,!1)}a(mQ,"greaterThan");function pQ(e,t,r,n,s=!1,i=void 0,o=void 0){li(e,r,n);let c=typeof n,l;return c==="string"?l="\uFFFF":c==="number"?l=1/0:c==="boolean"&&(l=!0),zc(e,t,r,n,l,s,i,o,!1,!1)}a(pQ,"greaterThanEqual");function SQ(e,t,r,n,s=!1,i=void 0,o=void 0){li(e,r,n);let c=typeof n,l;return c==="string"?l="\0":c==="number"?l=-1/0:c==="boolean"&&(l=!1),zc(e,t,r,l,n,s,i,o,!1,!0)}a(SQ,"lessThan");function TQ(e,t,r,n,s=!1,i=void 0,o=void 0){li(e,r,n);let c=typeof n,l;return c==="string"?l="\0":c==="number"?l=-1/0:c==="boolean"&&(l=!1),zc(e,t,r,l,n,s,i,o,!1,!1)}a(TQ,"lessThanEqual");function gQ(e,t,r,n,s,i=!1,o=void 0,c=void 0){if($r.validateEnv(e),r===void 0)throw new Error(Et.ATTRIBUTE_REQUIRED);if(n===void 0)throw new Error(Et.START_VALUE_REQUIRED);if(s===void 0)throw new Error(Et.END_VALUE_REQUIRED);if(n=$r.convertKeyValueToWrite(n),s=$r.convertKeyValueToWrite(s),n>s)throw new Error(Et.END_VALUE_MUST_BE_GREATER_THAN_START_VALUE);return zc(e,t,r,n,s,i,o,c)}a(gQ,"between");function RQ(e,t,r,n){$r.validateEnv(e);let s=e.database||e,i=e.database?e:null;if(t===void 0)throw new Error(Et.HASH_ATTRIBUTE_REQUIRED);if(ed(r),r=Jc(s,r),n===void 0)throw new Error(Et.ID_REQUIRED);let o=null,c=s.dbis[t].get(n,{transaction:i,lazy:r.length<3});return c&&(o=Z_.parseRow(c,r)),o}a(RQ,"searchByHash");function AQ(e,t,r){$r.validateEnv(e);let n=e.database||e,s=e.database?e:null;if(t===void 0)throw new Error(Et.HASH_ATTRIBUTE_REQUIRED);if(r===void 0)throw new Error(Et.ID_REQUIRED);let i=!0;return n.dbis[t].get(r,{transaction:s,lazy:!0})===void 0&&(i=!1),i}a(AQ,"checkHashExists");function OQ(e,t,r,n,s=[]){return qI(e,t,r,n,s),FI(e,t,r,n,s).map(i=>i[1])}a(OQ,"batchSearchByHash");function bQ(e,t,r,n,s=[]){qI(e,t,r,n,s);let i=new Map;for(let[o,c]of FI(e,t,r,n,s))i.set(o,c);return i}a(bQ,"batchSearchByHashToMap");function FI(e,t,r,n,s=[]){return ji(e,t,t,(i,o,c)=>{r=Jc(c,r);let l=r.length<3;return n.map(_=>{let u=c.dbis[t].get(_,{transaction:i,lazy:l});if(u)return[_,Z_.parseRow(u,r)];s.push(_)}).filter(_=>_)})}a(FI,"batchHashSearch");function qI(e,t,r,n,s){if($r.validateEnv(e),t===void 0)throw new Error(Et.HASH_ATTRIBUTE_REQUIRED);if(ed(r),n==null)throw new Error(Et.IDS_REQUIRED);if(!n[Symbol.iterator])throw new Error(Et.IDS_MUST_BE_ITERABLE)}a(qI,"initializeBatchSearchByHash");function ed(e){if(!Array.isArray(e))throw e===void 0?new Error(Et.FETCH_ATTRIBUTES_REQUIRED):new Error(Et.FETCH_ATTRIBUTES_MUST_BE_ARRAY)}a(ed,"validateFetchAttributes");function li(e,t,r){if($r.validateEnv(e),t===void 0)throw new Error(Et.ATTRIBUTE_REQUIRED);if(r===void 0)throw new Error(Et.SEARCH_VALUE_REQUIRED);if(r?.length>aQ)throw new Error(Et.SEARCH_VALUE_TOO_LARGE)}a(li,"validateComparisonFunctions");function Jc(e,t){return t.length===1&&iQ.SEARCH_WILDCARDS.indexOf(t[0])>=0&&(t=ci.listDBIs(e)),t}a(Jc,"setGetWholeRowAttributes");kI.exports={searchAll:cQ,searchAllToMap:lQ,count:fQ,countAll:_Q,equals:dQ,startsWith:EQ,endsWith:hQ,contains:GI,searchByHash:RQ,setGetWholeRowAttributes:Jc,batchSearchByHash:OQ,batchSearchByHashToMap:bQ,checkHashExists:AQ,iterateDBI:uQ,greaterThan:mQ,greaterThanEqual:pQ,lessThan:SQ,lessThanEqual:TQ,between:gQ}});var ta=g((kle,WI)=>{var VI=require("lodash"),$I=at(),fe=require("joi"),yQ=z(),{hdb_schema_table:Xc,checkValidTable:YI,hdb_table:KI,hdb_database:td}=zn(),{handleHDBError:NQ,hdb_errors:IQ}=ne(),{getDatabases:wQ}=(Ae(),ie(ke)),{HTTP_STATUS_CODES:CQ}=IQ,DQ=fe.object({database:td,schema:td,table:KI,search_attribute:Xc,search_value:fe.any().required(),get_attributes:fe.array().min(1).items(fe.alternatives(Xc,fe.object())).optional(),desc:fe.bool(),limit:fe.number().integer().min(1),offset:fe.number().integer().min(0)}),LQ=fe.object({database:td,schema:td,table:KI,operator:fe.string().valid("and","or").default("and").lowercase(),offset:fe.number().integer().min(0),limit:fe.number().integer().min(1),get_attributes:fe.array().min(1).items(fe.alternatives(Xc,fe.object())).optional(),sort:fe.object({attribute:fe.alternatives(Xc,fe.array().min(1)),descending:fe.bool().optional()}).optional(),conditions:fe.array().min(1).items(fe.alternatives(fe.object({operator:fe.string().valid("and","or").default("and").lowercase(),conditions:fe.array()}),fe.object({search_attribute:fe.alternatives(Xc,fe.array().min(1)),search_type:fe.string().valid("equals","contains","starts_with","ends_with","greater_than","greater_than_equal","less_than","less_than_equal","between","not_equal").optional(),search_value:fe.when("search_type",{switch:[{is:"equals",then:fe.any()},{is:"between",then:fe.array().items(fe.alternatives([fe.string(),fe.number()])).length(2)}],otherwise:fe.alternatives(fe.string(),fe.number())}).required()}))).required()});WI.exports=function(e,t){let r=null;switch(t){case"value":r=$I.validateBySchema(e,DQ);break;case"hashes":let i=function(o){s?s+=". "+o:s=o};var n=i;a(i,"addError");let s;i(YI("database",e.schema)),i(YI("table",e.table)),e.hash_values?Array.isArray(e.hash_values)?e.hash_values.every(o=>typeof o=="string"||typeof o=="number")||i("'hash_values' must be strings or numbers"):i("'hash_values' must be an array"):i("'hash_values' is required"),e.get_attributes?Array.isArray(e.get_attributes)?e.get_attributes.length===0?i("'get_attributes' must contain at least 1 item"):e.get_attributes.every(o=>typeof o=="string"||typeof o=="number")||i("'get_attributes' must be strings or numbers"):i("'get_attributes' must be an array"):i("'get_attributes' is required"),s&&(r=new Error(s.trim()));break;case"conditions":r=$I.validateBySchema(e,LQ);break;default:throw new Error(`Error validating search, unknown type: ${t}`)}if(!r&&e.schema!=="system"){let s=yQ.checkGlobalSchemaTable(e.schema,e.table);if(s)return NQ(new Error,s,CQ.NOT_FOUND);let o=wQ()[e.schema][e.table].attributes,c=e.get_attributes?[...e.get_attributes]:[];t==="value"&&c.push(e.search_attribute);let l=a(u=>{for(let d=0,E=u.conditions.length;d<E;d++){let f=u.conditions[d];f.conditions?l(f):c.push(f.search_attribute)}},"addConditions");t==="conditions"&&l(e);let _=VI.filter(c,u=>u!=="*"&&u.attribute!=="*"&&!Array.isArray(u)&&!u.name&&!VI.some(o,d=>d===u||d.attribute===u||d.attribute===u.attribute));if(_&&_.length>0){let u=_.join(", ");return u=u.replace(/,([^,]*)$/," and$1"),new Error(`unknown attribute '${u}'`)}}return r}});var Rp=g(($le,QI)=>{"use strict";var MQ=Ke(),PQ=ta(),{getSchemaPath:UQ}=ze();QI.exports=vQ;function vQ(e){let t=PQ(e,"hashes");if(t)throw t;let r=UQ(e.schema,e.table);return MQ.openEnvironment(r,e.table)}a(vQ,"initialize")});var Ap=g((Kle,zI)=>{"use strict";var BQ=ea(),HQ=Rp();zI.exports=xQ;async function xQ(e){let t=await HQ(e),r=t.useReadTransaction();r.database=t;let n=global.hdb_schema[e.schema][e.table];try{return BQ.batchSearchByHashToMap(r,n.hash_attribute,e.get_attributes,e.hash_values)}finally{r.done()}}a(xQ,"lmdbGetDataByHash")});var ra=g((Qle,JI)=>{"use strict";var Op=class{static{a(this,"SearchByHashObject")}constructor(t,r,n,s){this.schema=t,this.table=r,this.hash_values=n,this.get_attributes=s}};JI.exports=Op});var jI=g((Xle,XI)=>{"use strict";var Jle=ra(),GQ=ea(),FQ=Rp();XI.exports=qQ;async function qQ(e){let t=await FQ(e),r=global.hdb_schema[e.schema][e.table];return GQ.batchSearchByHash(t,r.hash_attribute,e.get_attributes,e.hash_values)}a(qQ,"lmdbSearchByHash")});var es=g((Zle,ZI)=>{"use strict";var bp=class{static{a(this,"SearchObject")}constructor(t,r,n,s,i,o,c,l=!1,_=void 0,u=void 0){this.schema=t,this.table=r,this.search_attribute=n,this.search_value=s,this.hash_attribute=i,this.get_attributes=o,this.end_value=c,this.reverse=l,this.limit=_,this.offset=u}};ZI.exports=bp});var rd=g((tue,iw)=>{"use strict";var rr=ea(),kQ=Ke(),VQ=z(),Ee=dt(),Zi=U(),$Q=Gi(),ew=Ur().LMDB_ERRORS_ENUM,{getSchemaPath:YQ}=ze(),Os=Zi.SEARCH_WILDCARDS;async function KQ(e,t,r){let n;e.schema===Zi.SYSTEM_SCHEMA_NAME?n=$Q[e.table]:n=global.hdb_schema[e.schema][e.table];let s=sw(e,n.hash_attribute,r,t);return rw(e,s,n.hash_attribute,r)}a(KQ,"prepSearch");async function rw(e,t,r,n){let s=YQ(e.schema,e.table),i=await kQ.openEnvironment(s,e.table),o=nw(i,e,t,r),c=o.transaction||i;if([Ee.SEARCH_TYPES.BATCH_SEARCH_BY_HASH,Ee.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP,Ee.SEARCH_TYPES.SEARCH_ALL,Ee.SEARCH_TYPES.SEARCH_ALL_TO_MAP].indexOf(t)>=0)return o;if(WQ(e,r)===!1){let u=e.search_attribute;if(u===r)return n?tw(o,()=>!0):o.map(E=>({[r]:E.key}));let d=a(E=>({[r]:E.value,[u]:E.key}),"toObject");return n?tw(o,d):o.map(d)}let _=e.search_attribute===r?o.map(u=>u.key):o.map(u=>u.value);return n===!0?rr.batchSearchByHashToMap(c,r,e.get_attributes,_):rr.batchSearchByHash(c,r,e.get_attributes,_)}a(rw,"executeSearch");function nw(e,t,r,n){let s,i=n;t.get_attributes.indexOf(n)<0&&(i=void 0);let{reverse:o,limit:c,offset:l}=t;switch(o=typeof o=="boolean"?o:!1,c=Number.isInteger(c)?c:void 0,l=Number.isInteger(l)?l:void 0,r){case Ee.SEARCH_TYPES.EQUALS:s=rr.equals(e,i,t.search_attribute,t.search_value,o,c,l);break;case Ee.SEARCH_TYPES.CONTAINS:s=rr.contains(e,i,t.search_attribute,t.search_value,o,c,l);break;case Ee.SEARCH_TYPES.ENDS_WITH:case Ee.SEARCH_TYPES._ENDS_WITH:s=rr.endsWith(e,i,t.search_attribute,t.search_value,o,c,l);break;case Ee.SEARCH_TYPES.STARTS_WITH:case Ee.SEARCH_TYPES._STARTS_WITH:s=rr.startsWith(e,i,t.search_attribute,t.search_value,o,c,l);break;case Ee.SEARCH_TYPES.BATCH_SEARCH_BY_HASH:return rr.batchSearchByHash(e,t.search_attribute,t.get_attributes,[t.search_value]);case Ee.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP:return rr.batchSearchByHashToMap(e,t.search_attribute,t.get_attributes,[t.search_value]);case Ee.SEARCH_TYPES.SEARCH_ALL:return rr.searchAll(e,n,t.get_attributes,o,c,l);case Ee.SEARCH_TYPES.SEARCH_ALL_TO_MAP:return rr.searchAllToMap(e,n,t.get_attributes,o,c,l);case Ee.SEARCH_TYPES.BETWEEN:s=rr.between(e,i,t.search_attribute,t.search_value,t.end_value,o,c,l);break;case Ee.SEARCH_TYPES.GREATER_THAN:case Ee.SEARCH_TYPES._GREATER_THAN:s=rr.greaterThan(e,i,t.search_attribute,t.search_value,o,c,l);break;case Ee.SEARCH_TYPES.GREATER_THAN_EQUAL:case Ee.SEARCH_TYPES._GREATER_THAN_EQUAL:s=rr.greaterThanEqual(e,i,t.search_attribute,t.search_value,o,c,l);break;case Ee.SEARCH_TYPES.LESS_THAN:case Ee.SEARCH_TYPES._LESS_THAN:s=rr.lessThan(e,i,t.search_attribute,t.search_value,o,c,l);break;case Ee.SEARCH_TYPES.LESS_THAN_EQUAL:case Ee.SEARCH_TYPES._LESS_THAN_EQUAL:s=rr.lessThanEqual(e,i,t.search_attribute,t.search_value,o,c,l);break;default:return Object.create(null)}return s}a(nw,"searchByType");function tw(e,t){let r=new Map;for(let n of e)r.set(n.value,t(n));return r}a(tw,"createMapFromIterable");function WQ(e,t){if(e.get_attributes.length===1&&e.get_attributes[0]==="*")return!0;let r=[e.search_attribute];e.get_attributes.indexOf(t)>=0&&r.push(t);let n=!1;for(let s=0;s<e.get_attributes.length;s++)if(r.indexOf(e.get_attributes[s])<0){n=!0;break}return n}a(WQ,"checkToFetchMore");function sw(e,t,r,n){if(VQ.isEmpty(n)){let s=e.search_value;typeof s=="object"?s=JSON.stringify(s):s=s.toString();let i=s.charAt(0),o=s.charAt(s.length-1),c=!1;if(e.search_attribute===t&&(c=!0),Os.indexOf(s)>-1)return r===!0?Ee.SEARCH_TYPES.SEARCH_ALL_TO_MAP:Ee.SEARCH_TYPES.SEARCH_ALL;if(s.indexOf(Os[0])<0&&s.indexOf(Os[1])<0)return c===!0?r===!0?Ee.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP:Ee.SEARCH_TYPES.BATCH_SEARCH_BY_HASH:Ee.SEARCH_TYPES.EQUALS;if(Os.indexOf(i)>=0&&Os.indexOf(o)>=0)return e.search_value=e.search_value.slice(1,-1),Ee.SEARCH_TYPES.CONTAINS;if(Os.indexOf(i)>=0)return e.search_value=e.search_value.substr(1),Ee.SEARCH_TYPES.ENDS_WITH;if(Os.indexOf(o)>=0)return e.search_value=e.search_value.slice(0,-1),Ee.SEARCH_TYPES.STARTS_WITH;if(s.includes(Os[0])||s.includes(Os[1]))return Ee.SEARCH_TYPES.EQUALS;throw new Error(ew.UNKNOWN_SEARCH_TYPE)}else switch(n){case Zi.VALUE_SEARCH_COMPARATORS.BETWEEN:return Ee.SEARCH_TYPES.BETWEEN;case Zi.VALUE_SEARCH_COMPARATORS.GREATER:return Ee.SEARCH_TYPES.GREATER_THAN;case Zi.VALUE_SEARCH_COMPARATORS.GREATER_OR_EQ:return Ee.SEARCH_TYPES.GREATER_THAN_EQUAL;case Zi.VALUE_SEARCH_COMPARATORS.LESS:return Ee.SEARCH_TYPES.LESS_THAN;case Zi.VALUE_SEARCH_COMPARATORS.LESS_OR_EQ:return Ee.SEARCH_TYPES.LESS_THAN_EQUAL;default:throw new Error(ew.UNKNOWN_SEARCH_TYPE)}}a(sw,"createSearchTypeFromSearchObject");iw.exports={executeSearch:rw,createSearchTypeFromSearchObject:sw,prepSearch:KQ,searchByType:nw}});var aw=g((sue,ow)=>{"use strict";var nue=es(),QQ=ta(),zQ=z(),JQ=U(),XQ=rd();ow.exports=jQ;function jQ(e,t){if(!zQ.isEmpty(t)&&JQ.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[t]===void 0)throw new Error(`Value search comparator - ${t} - is not valid`);let n=QQ(e,"value");if(n)throw n;return XQ.prepSearch(e,t,!0)}a(jQ,"lmdbGetDataByValue")});var jc=g((aue,cw)=>{"use strict";var oue=es(),ZQ=ta(),ez=z(),tz=U(),rz=rd();cw.exports=nz;async function nz(e,t){if(!ez.isEmpty(t)&&tz.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[t]===void 0)throw new Error(`Value search comparator - ${t} - is not valid`);let n=ZQ(e,"value");if(n)throw n;return rz.prepSearch(e,t,!1)}a(nz,"lmdbSearchByValue")});var uw=g((uue,lw)=>{"use strict";var lue=dt(),yp=class{static{a(this,"SearchByConditionsObject")}constructor(t,r,n,s,i=void 0,o=void 0,c="and"){this.schema=t,this.table=r,this.get_attributes=n,this.limit=i,this.offset=o,this.conditions=s,this.operator=c}},Np=class{static{a(this,"SearchCondition")}constructor(t,r,n){this.search_attribute=t,this.search_type=r,this.search_value=n}},Ip=class{static{a(this,"SortAttribute")}constructor(t,r){this.attribute=t,this.desc=r}};lw.exports={SearchByConditionsObject:yp,SearchCondition:Np,SortAttribute:Ip}});var hw=g((Eue,Ew)=>{"use strict";var due=uw().SearchByConditionsObject,sz=es(),iz=ta(),wp=ea(),nd=dt(),{Resource:fue}=(yn(),ie(Cp)),fw=rd(),oz=gp(),az=require("lodash"),{getSchemaPath:cz}=ze(),_w=Ke(),{handleHDBError:lz,hdb_errors:uz}=ne(),{HTTP_STATUS_CODES:_z}=uz,dz=1e8;Ew.exports=fz;async function fz(e){let t=iz(e,"conditions");if(t)throw lz(t,t.message,_z.BAD_REQUEST,void 0,void 0,!0);e.operator=e.operator?e.operator.toLowerCase():void 0,e.offset=Number.isInteger(e.offset)?e.offset:0;let r=cz(e.schema,e.table),n=await _w.openEnvironment(r,e.table),s=global.hdb_schema[e.schema][e.table];for(let _ of e.conditions)_w.openDBI(n,_.search_attribute);let i=az.sortBy(e.conditions,_=>{if(_.estimated_count===void 0){let u=_.search_type;u===nd.SEARCH_TYPES.EQUALS?_.estimated_count=wp.count(n,_.search_attribute,_.search_value):u===nd.SEARCH_TYPES.CONTAINS||u===nd.SEARCH_TYPES.ENDS_WITH?_.estimated_count=1/0:_.estimated_count=dz}return _.estimated_count}),o=n.useReadTransaction();o.database=n;let c=await dw(o,e,i[0],s.hash_attribute),l;if(!e.operator||e.operator.toLowerCase()==="and"){let _=n.dbis[s.hash_attribute],u=i.slice(1).map(fw.filterByType),d=u.length,E=wp.setGetWholeRowAttributes(n,e.get_attributes);l=c.map(f=>_.get(f,{transaction:o,lazy:!0})),d>0&&(l=l.filter(f=>{for(let h=0;h<d;h++)if(!u[h](f))return!1;return!0})),(e.offset||e.limit!==void 0)&&(l=l.slice(e.offset,e.limit!==void 0?(e.offset||0)+e.limit:void 0)),l=l.map(f=>oz.parseRow(f,E))}else{for(let d=1;d<i.length;d++){let E=i[d],f=await dw(o,e,E,s.hash_attribute);c=c.concat(f)}let _=new Set,u=e.offset||0;c=c.filter(d=>_.has(d)?!1:(_.add(d),!0)).slice(u,e.limit&&e.limit+u),l=wp.batchSearchByHash(o,s.hash_attribute,e.get_attributes,c)}return l.onDone=()=>{o.done()},l}a(fz,"lmdbSearchByConditions");async function dw(e,t,r,n){let s=new sz(t.schema,t.table,void 0,void 0,n,t.get_attributes),i=r.search_type;return s.search_attribute=r.search_attribute,i===nd.SEARCH_TYPES.BETWEEN?(s.search_value=r.search_value[0],s.end_value=r.search_value[1]):s.search_value=r.search_value,fw.searchByType(e,s,i,n).map(o=>o.value)}a(dw,"executeConditionSearch")});var Zc=g((mue,mw)=>{"use strict";var Ez=U().OPERATIONS_ENUM,Dp=class{static{a(this,"DeleteObject")}constructor(t,r,n,s=void 0){this.operation=Ez.DELETE,this.schema=t,this.table=r,this.hash_values=n,this.__origin=s}};mw.exports=Dp});var Lp=g((Sue,bw)=>{"use strict";var gw=es(),Rw=Zc(),Aw=jc(),Ow=Qc(),hr=U(),pw=z(),Sw=Ke(),{getTransactionAuditStorePath:hz,getSchemaPath:mz}=ze(),Tw=K();bw.exports=pz;async function pz(e){try{if(pw.isEmpty(global.hdb_schema[e.schema])||pw.isEmpty(global.hdb_schema[e.schema][e.table]))throw new Error(`unknown schema:${e.schema} and table ${e.table}`);await Sz(e),await Tz(e);let t=mz(e.schema,e.table);try{await Sw.deleteEnvironment(t,e.table)}catch(r){if(r.message==="invalid environment")Tw.warn(`cannot delete environment for ${e.schema}.${e.table}, environment not found`);else throw r}try{let r=hz(e.schema,e.table);await Sw.deleteEnvironment(r,e.table,!0)}catch(r){if(r.message==="invalid environment")Tw.warn(`cannot delete environment for ${e.schema}.${e.table}, environment not found`);else throw r}}catch(t){throw t}}a(pz,"lmdbDropTable");async function Sz(e){let t=new gw(hr.SYSTEM_SCHEMA_NAME,hr.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,hr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_TABLE_KEY,`${e.schema}.${e.table}`,void 0,[hr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),r=Array.from(await Aw(t)),n=[];for(let i=0;i<r.length;i++){let o=r[i];n.push(o.id)}if(n.length===0)return;let s=new Rw(hr.SYSTEM_SCHEMA_NAME,hr.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,n);await Ow(s)}a(Sz,"deleteAttributesFromSystem");async function Tz(e){let t=new gw(hr.SYSTEM_SCHEMA_NAME,hr.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,hr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY,e.table,void 0,[hr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY,hr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_KEY,hr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),r,n;try{r=Array.from(await Aw(t))}catch(i){throw i}for(let i=0;i<r.length;i++){let o=r[i];o.name===e.table&&o.schema===e.schema&&(n=o)}if(!n)throw new Error(`${e.schema}.${e.table} was not found`);let s=new Rw(hr.SYSTEM_SCHEMA_NAME,hr.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,[n.id]);try{await Ow(s)}catch(i){throw i}}a(Tz,"dropTableFromSystem")});var Nw=g((gue,yw)=>{"use strict";var gz=require("fs-extra"),Rz=es(),Az=ra(),Oz=Zc(),bz=Lp(),yz=Qc(),Nz=Ap(),Iz=jc(),bs=U(),{getSchemaPath:wz}=ze(),{handleHDBError:Cz,hdb_errors:Dz}=ne(),{HDB_ERROR_MSGS:Lz,HTTP_STATUS_CODES:Mz}=Dz;yw.exports=Pz;async function Pz(e){let t;try{t=await Uz(e.schema);let r=new Rz(bs.SYSTEM_SCHEMA_NAME,bs.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,bs.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_KEY,t,void 0,[bs.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY]),n=Array.from(await Iz(r));for(let o=0;o<n.length;o++){let c={schema:t,table:n[o].name};try{await bz(c)}catch(l){if(l.message!=="invalid environment")throw l}}let s=new Oz(bs.SYSTEM_SCHEMA_NAME,bs.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,[t]);await yz(s);let i=wz(t);await gz.remove(i)}catch(r){throw r}}a(Pz,"lmdbDropSchema");async function Uz(e){let t=new Az(bs.SYSTEM_SCHEMA_NAME,bs.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,[e],[bs.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY]),r,n;try{r=Array.from(await Nz(t))}catch(s){throw s}for(let[,s]of r)s.name===e&&(n=e);if(!n)throw Cz(new Error,Lz.SCHEMA_NOT_FOUND(e),Mz.NOT_FOUND,void 0,void 0,!0);return n}a(Uz,"validateDropSchema")});var Pp=g((Aue,Iw)=>{"use strict";var Mp=class{static{a(this,"CreateTableObject")}constructor(t,r,n){this.schema=t,this.table=r,this.hash_attribute=n}};Iw.exports=Mp});var Cw=g((yue,ww)=>{"use strict";var vz=require("fs-extra"),sd=Ke(),{getTransactionAuditStorePath:Bz}=ze(),Up=dt(),bue=Pp();ww.exports=Hz;async function Hz(e){let t;try{let r=Bz(e.schema,e.table);await vz.mkdirp(r),t=await sd.createEnvironment(r,e.table,!0)}catch(r){throw r.message=`unable to create transactions audit environment for ${e.schema}.${e.table} due to: ${r.message}`,r}try{sd.createDBI(t,Up.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,!1,!0),sd.createDBI(t,Up.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE,!0,!1),sd.createDBI(t,Up.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME,!0,!1)}catch(r){throw r.message=`unable to create dbi for ${e.schema}.${e.table} due to: ${r.message}`,r}return t}a(Hz,"createTransactionsAuditEnvironment")});var Pw=g((Iue,Mw)=>{"use strict";var vp=U(),Dw=Ke(),xz=ko(),{getSystemSchemaPath:Gz,getSchemaPath:Fz}=ze(),qz=Gi(),kz=b_(),Bp=O_(),Vz=K(),$z=Cw(),xp=qz.hdb_table,Lw=[];for(let e=0;e<xp.attributes.length;e++)Lw.push(xp.attributes[e].attribute);Mw.exports=Yz;async function Yz(e,t){let r=Fz(t.schema,t.table),n=new Bp(t.schema,t.table,vp.TIME_STAMP_NAMES_ENUM.CREATED_TIME,void 0,!0),s=new Bp(t.schema,t.table,vp.TIME_STAMP_NAMES_ENUM.UPDATED_TIME,void 0,!0),i=new Bp(t.schema,t.table,t.hash_attribute,void 0,!1,!0);try{if(await Dw.createEnvironment(r,t.table),e!==void 0){let o=await Dw.openEnvironment(Gz(),vp.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME);await xz.insertRecords(o,xp.hash_attribute,Lw,[e]),n.skip_table_check=!0,s.skip_table_check=!0,i.skip_table_check=!0,await Hp(n),await Hp(s),await Hp(i)}await $z(t)}catch(o){throw o}}a(Yz,"lmdbCreateTable");async function Hp(e){try{await kz(e)}catch(t){Vz.warn(`failed to create attribute ${e.attribute} due to ${t.message}`)}}a(Hp,"createAttribute")});var vw=g((Cue,Uw)=>{"use strict";var Kz=Bc(),Wz=xc(),Qz=J_(),el=U(),zz=ko().updateRecords,Jz=Ke(),{getSchemaPath:Xz}=ze(),jz=Kc(),Zz=K();Uw.exports=e2;async function e2(e){try{let{schema_table:t,attributes:r}=Kz(e);Wz(e,r,t.hash_attribute),e.schema!==el.SYSTEM_SCHEMA_NAME&&(r.includes(el.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||r.push(el.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.includes(el.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||r.push(el.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let n=await Qz(e.hdb_auth_header,t,r),s=Xz(e.schema,e.table),i=await Jz.openEnvironment(s,e.table),o=await zz(i,t.hash_attribute,r,e.records,e.__origin?.timestamp);try{await jz(e,o)}catch(c){Zz.error(`unable to write transaction due to ${c.message}`)}return{written_hashes:o.written_hashes,skipped_hashes:o.skipped_hashes,schema_table:t,new_attributes:n,txn_time:o.txn_time}}catch(t){throw t}}a(e2,"lmdbUpdateRecords")});var Hw=g((Lue,Bw)=>{"use strict";var t2=U().OPERATIONS_ENUM,Gp=class{static{a(this,"UpsertObject")}constructor(t,r,n,s=void 0){this.operation=t2.UPSERT,this.schema=t,this.table=r,this.records=n,this.__origin=s}};Bw.exports=Gp});var Gw=g((Uue,xw)=>{"use strict";var Pue=Hw(),r2=Bc(),n2=xc(),s2=J_(),tl=U(),i2=ko().upsertRecords,o2=Ke(),{getSchemaPath:a2}=ze(),c2=Kc(),l2=K(),{handleHDBError:u2,hdb_errors:_2}=ne();xw.exports=d2;async function d2(e){let t;try{t=r2(e)}catch(l){throw u2(l,l.message,_2.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0)}let{schema_table:r,attributes:n}=t;n2(e,n,r.hash_attribute),e.schema!==tl.SYSTEM_SCHEMA_NAME&&(n.includes(tl.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||n.push(tl.TIME_STAMP_NAMES_ENUM.CREATED_TIME),n.includes(tl.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||n.push(tl.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let s=await s2(e.hdb_auth_header,r,n),i=a2(e.schema,e.table),o=await o2.openEnvironment(i,e.table),c=await i2(o,r.hash_attribute,n,e.records,e.__origin?.timestamp);try{await c2(e,c)}catch(l){l2.error(`unable to write transaction due to ${l.message}`)}return{written_hashes:c.written_hashes,schema_table:r,new_attributes:s,txn_time:c.txn_time}}a(d2,"lmdbUpsertRecords")});var qw=g((Bue,Fw)=>{"use strict";var Fp=class{static{a(this,"DeleteBeforeObject")}constructor(t,r,n){this.schema=t,this.table=r,this.timestamp=n}};Fw.exports=Fp});var Vw=g((xue,kw)=>{"use strict";var qp=class{static{a(this,"DeleteAuditLogsBeforeResults")}constructor(t=void 0,r=void 0,n=0){this.start_timestamp=t,this.end_timestamp=r,this.transactions_deleted=n}};kw.exports=qp});var Kw=g((que,Yw)=>{"use strict";var kp=Ke(),{getTransactionAuditStorePath:f2}=ze(),Fue=qw(),rl=dt(),E2=z(),$w=Vw(),h2=require("util").promisify,m2=h2(setTimeout),p2=1e4,S2=100;Yw.exports=T2;async function T2(e){let t=f2(e.schema,e.table),r=await kp.openEnvironment(t,e.table,!0),n=kp.listDBIs(r);kp.initializeDBIs(r,rl.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,n);let s,i=new $w;do s=await g2(r,e.timestamp),i.start_timestamp===void 0&&(i.start_timestamp=s.start_timestamp),s.end_timestamp!==void 0&&(i.end_timestamp=s.end_timestamp),i.transactions_deleted+=s.transactions_deleted,await m2(S2);while(s.transactions_deleted>0);return i}a(T2,"deleteAuditLogsBefore");async function g2(e,t){let r=new $w;try{let n=e.dbis[rl.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP],s;for(let{key:i,value:o}of n.getRange({start:!1})){if(i>=t)break;r.start_timestamp===void 0&&(r.start_timestamp=i),s=n.remove(i);let c=o[rl.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME];E2.isEmpty(c)||(s=e.dbis[rl.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].remove(c,i));for(let l=0;l<o.hash_values.length;l++)s=e.dbis[rl.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE].remove(o.hash_values[l],i);if(r.transactions_deleted++,r.end_timestamp=i,r.transactions_deleted>p2)break}return await s,r}catch(n){throw n}}a(g2,"deleteTransactions")});var Qw=g((Vue,Ww)=>{"use strict";var Vp=class{static{a(this,"DropAttributeObject")}constructor(t,r,n){this.schema=t,this.table=r,this.attribute=n}};Ww.exports=Vp});var Jw=g((Kue,zw)=>{"use strict";var R2=es(),A2=Zc(),Yue=Qw(),ts=U(),O2=z(),$p=Ke(),b2=Gi(),y2=jc(),N2=Qc(),{getSchemaPath:I2}=ze();zw.exports=w2;async function w2(e,t=!0){let r;e.schema===ts.SYSTEM_SCHEMA_NAME?r=b2[e.table]:r=global.hdb_schema[e.schema][e.table];let n=await D2(e),s=I2(e.schema,e.table),i=await $p.openEnvironment(s,e.table);return t===!0&&await C2(e,i,r.hash_attribute),$p.dropDBI(i,e.attribute),n}a(w2,"lmdbDropAttribute");async function C2(e,t,r){let n=$p.openDBI(t,r),s,i=e.attribute;for(let{key:o,value:c,version:l}of n.getRange({start:!1,versions:!0})){let _={};for(let u in c)u!==i&&(_[u]=c[u]);s=t.dbis[r].put(o,_,l)}await s}a(C2,"removeAttributeFromAllObjects");async function D2(e){let t=new R2(ts.SYSTEM_SCHEMA_NAME,ts.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,ts.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_TABLE_KEY,`${e.schema}.${e.table}`,void 0,[ts.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY,ts.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ATTRIBUTE_KEY]),n=Array.from(await y2(t)).filter(o=>o[ts.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ATTRIBUTE_KEY]===e.attribute);if(O2.isEmptyOrZeroLength(n))throw new Error(`Attribute '${e.attribute}' was not found in '${e.schema}.${e.table}'`);let s=n.map(o=>o[ts.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),i=new A2(ts.SYSTEM_SCHEMA_NAME,ts.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,s);return N2(i)}a(D2,"dropAttributeFromSystem")});var rC=g((zue,tC)=>{"use strict";var Yp=Ke(),na=dt(),Que=vr(),Kp=U(),Xw=z(),{getTransactionAuditStorePath:L2}=ze(),M2=ea(),id=Xo(),P2=K();tC.exports=U2;async function U2(e){let t=L2(e.schema,e.table),r=await Yp.openEnvironment(t,e.table,!0),n=Yp.listDBIs(r);Yp.initializeDBIs(r,na.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,n);let s;switch(e.search_type){case Kp.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.TIMESTAMP:return jw(r,e.search_values);case Kp.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.HASH_VALUE:return s=global.hdb_schema[e.schema][e.table].hash_attribute,B2(r,e.search_values,s);case Kp.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.USERNAME:return v2(r,e.search_values);default:return jw(r)}}a(U2,"readAuditLog");function jw(e,t=[0,Date.now()]){Xw.isEmpty(t[0])&&(t[0]=0),Xw.isEmpty(t[1])&&(t[1]=Date.now());let r=e.dbis[na.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP],n;for(let s of r.getKeys({start:t[1]}))if(s!==t[1]){n=s;break}return r.getRange({start:t[0],end:n}).map(({value:s})=>Object.assign(new id,s))}a(jw,"searchTransactionsByTimestamp");function v2(e,t=[]){let r=new Map;for(let n=0;n<t.length;n++){let s=t[n],i=[];for(let o of e.dbis[na.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].getValues(s))i.push(o);r.set(s,eC(e,i))}return Object.fromEntries(r)}a(v2,"searchTransactionsByUsername");function B2(e,t,r){let n=new Map;for(let c=0,l=t.length;c<l;c++){let _=t[c],u=M2.equals(e,na.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,na.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE,_);for(let{value:d}of u){let E=Number(d);n.has(E)?n.get(E).push(_.toString()):n.set(E,[_.toString()])}}let s=Array.from(n.keys()),i=eC(e,s),o=new Map;for(let c=0;c<i.length;c++){let l=i[c],_=l.timestamp,u=n.get(_);Zw(l,"records",r,u,o),Zw(l,"original_records",r,u,o)}return Object.fromEntries(o)}a(B2,"searchTransactionsByHashValues");function Zw(e,t,r,n,s){let i=e.timestamp;if(e[t])for(let o=0;o<e[t].length;o++){let c=e[t][o],l=c[r].toString();if(n.indexOf(l)>=0)if(s.has(l)){let _=s.get(l),u=_[_.length-1];if(u.timestamp===i)u[t]=[c];else{let d=new id(e.operation,e.user_name,i,void 0);d[t]=[c],_.push(d)}}else{let _=new id(e.operation,e.user_name,i,void 0);_[t]=[c],s.set(l,[_])}}}a(Zw,"loopRecords");function eC(e,t){let r=[];try{let n=e.dbis[na.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP];for(let s=0;s<t.length;s++)try{let i=n.get(t[s]);if(i){let o=Object.assign(new id,i);r.push(o)}}catch(i){P2.warn(i)}return r}catch(n){throw n}}a(eC,"batchSearchTransactions")});var sC=g((Zue,nC)=>{"use strict";var{getSchemaPath:Xue}=ze(),jue=Ke(),{database:H2}=(Ae(),ie(ke));nC.exports={writeTransaction:x2};async function x2(e,t,r){return H2({database:e,table:t}).transaction(r)}a(x2,"writeTransaction")});var cC=g((t_e,aC)=>{"use strict";var{getSchemaPath:iC}=ze(),oC=Ke();aC.exports={flush:G2,resetReadTxn:F2};async function G2(e,t){return(await oC.openEnvironment(iC(e,t),t.toString())).flushed}a(G2,"flush");async function F2(e,t){try{(await oC.openEnvironment(iC(e,t),t.toString())).resetReadTxn()}catch{}}a(F2,"resetReadTxn")});var dC=g((n_e,_C)=>{"use strict";var{Readable:q2}=require("stream"),{getDatabases:k2}=(Ae(),ie(ke)),{readSync:V2,openSync:$2,createReadStream:lC}=require("fs"),{open:Y2}=require("lmdb"),uC=Cc(),K2=Dc(),{AUDIT_STORE_OPTIONS:W2}=(Zs(),ie(fC)),{INTERNAL_DBIS_NAME:Q2,AUDIT_STORE_NAME:z2}=dt();_C.exports=X2;var Wp=32768,J2=100;async function X2(e){let t=e.database||e.schema||"data",r=k2()[t],n=new Date().toISOString(),s=e.tables||e.table&&[e.table];if(s){let _=r[s[0]];if(!_)throw new Error(`Can not find table ${s[0]}`);let u=_.dbisDB,d=Y2({noSync:!0,maxDbs:K2.MAX_DBS}),E,f=d.openDB(Q2,new uC(!1)),h=u.useReadTransaction(),p=0,S=a(async function(R,b){b.encoding="binary",b.encoder=void 0;let C=d.openDB(R,b),H=u.openDB(R,b);for(let{key:v,version:q,value:M}of H.getRange({start:null,transaction:h,versions:H.useVersions}))E=C.put(v,M,q),p++%J2===0&&(await new Promise(Q=>setTimeout(Q,20)),h.openTimer&&(h.openTimer=0))},"copyDatabase");for(let{key:R,value:b}of u.getRange({transaction:h,start:!1}))if(s.some(C=>R.startsWith?.(C+"/"))){f.put(R,b);let[,C]=R.split("/"),H=!C,v=new uC(!H,H);await S(R,v)}e.include_audit&&await S(z2,Object.assign({},W2)),await E;let T=lC(d.path);return T.headers=l(),T.on("close",()=>{h.done(),d.close()}),T}let o=r[Object.keys(r)[0]].primaryStore,c=$2(o.path);return o.transaction(()=>{let _=Buffer.alloc(Wp);V2(c,_,0,Wp),o.resetReadTxn();let u=o.useReadTransaction();u.renew();let d=lC(null,{fd:c,start:Wp}),E=new q2.from(async function*(){yield _;for await(let f of d)u.openTimer&&(u.openTimer=0),yield f;u.done()}());return E.headers=l(),E});function l(){let _=new Map;return _.set("content-type","application/octet-stream"),_.set("content-disposition",`attachment; filename="${t}"`),_.set("date",n),_}}a(X2,"getBackup")});var mC=g((i_e,hC)=>{"use strict";var j2=K(),{handleHDBError:Z2}=ne(),eJ=wb(),tJ=b_(),rJ=hp(),nJ=NI(),sJ=Qc(),iJ=Ap(),oJ=jI(),aJ=aw(),cJ=jc(),lJ=hw(),uJ=Nw(),_J=Pw(),dJ=vw(),fJ=Gw(),EJ=Kw(),hJ=Lp(),mJ=Jw(),pJ=rC(),SJ=sC(),EC=cC(),TJ=dC(),Qp=class extends eJ{static{a(this,"LMDBBridge")}async searchByConditions(t){return lJ(t)}async getDataByHash(t){return await iJ(t)}async searchByHash(t){return await oJ(t)}async getDataByValue(t,r){return await aJ(t,r)}async searchByValue(t){return await cJ(t)}async createSchema(t){return await nJ(t)}async dropSchema(t){return await uJ(t)}async createTable(t,r){return await _J(t,r)}async dropTable(t){return await hJ(t)}async createAttribute(t){return await tJ(t)}async createRecords(t){return await rJ(t)}async updateRecords(t){return await dJ(t)}async upsertRecords(t){try{return await fJ(t)}catch(r){throw Z2(r,null,null,j2.ERR,r)}}async deleteRecords(t){return await sJ(t)}async dropAttribute(t){return await mJ(t)}async deleteAuditLogsBefore(t){return await EJ(t)}async readAuditLog(t){return await pJ(t)}writeTransaction(t,r,n){return SJ.writeTransaction(t,r,n)}flush(t,r){return EC.flush(t,r)}resetReadTxn(t,r){return EC.resetReadTxn(t,r)}getBackup(t){return TJ(t)}};hC.exports=Qp});function OJ(){AJ=setInterval(function(){for(let e of zp)if(e.stale){let t=e[ye]?.url;gC.error(`Transaction was open too long and has been aborted, from table: ${e.lmdbDb?.name+(t?" path: "+t:"")}`),e.abort()}else e.stale=!0},RJ).unref()}var Jp,TC,gC,RC,AC,OC,pC,zp,gJ,nl,SC,eo,od,RJ,AJ,Xp=Re(()=>{Jp=B(vr()),TC=B(ne()),gC=B(K());yn();RC=B(te()),AC=B(U()),OC=B(z()),pC=100,zp=new Set,gJ=(0,OC.convertToMS)(RC.get(AC.CONFIG_PARAMS.STORAGE_MAXTRANSACTIONQUEUETIME))||45e3,eo=class e{static{a(this,"DatabaseTransaction")}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.readTxnsUsed=1,this.readTxn=this.lmdbDb.useReadTransaction(),this.readTxn.openTimer&&(this.readTxn.openTimer=0),zp.add(this),this.readTxn}useReadTxn(){return this.getReadTxn(),this.readTxn.use(),this.readTxnsUsed++,this.readTxn}doneReadTxn(){this.readTxn&&(this.readTxn.done(),--this.readTxnsUsed===0&&(zp.delete(this),this.readTxn=null))}disregardReadTxn(){--this.readTxnRefCount===0&&this.readTxnsUsed===1&&this.doneReadTxn()}checkOverloaded(){if(nl&&!this.overloadChecked&&performance.now()-SC>gJ)throw new TC.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=t.timestamp||(0,Jp.getNextMonotonicTime)());let n=t.retries||0;if(this.validated<this.writes.length)try{let d=this.validated;this.validated=this.writes.length;for(let f=d;f<this.validated;f++)this.writes[f]?.validate?.(this.timestamp);let E;for(let f=d;f<this.validated;f++){let h=this.writes[f];h&&(h.before||h.beforeIntermediate)&&(E=!0)}if(E)return(async()=>{try{for(let f=0;f<2;f++){let h;for(let p=d;p<this.validated;p++){let S=this.writes[p];if(!S)continue;let T=S[f===0?"before":"beforeIntermediate"];if(T){let R=T();h?h.push?h.push(R):h=[h,R]:h=R}}h&&await(h.push?Promise.all(h):h)}}catch(f){throw this.abort(),f}return this.commit(t)})()}catch(d){throw this.abort(),d}n||this.doneReadTxn(),this.open=t?.letItLinger?2:0;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 E=d.store.ifVersion(d.key,d.entry?.version??null,l);s=s||E}else l();else for(let E of this.writes)c(E)},"nextCondition"),_=this.lmdbDb;if(this.writes.length>0&&(_?.retryRisk&&(_.retryRisk*=.99),this.writes.length+(_?.retryRisk||0)<pC>>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 nl||(nl=s,SC=performance.now(),nl.then(()=>{nl=null})),s.then(d=>d?(this.next&&i.push(this.next.commit(t)),t?.flush&&i.push(this.writes[0].store.flushed),this.writes=[],this.next=null,Promise.all(i).then(()=>({txnTime:r}))):(_&&(_.retryRisk=(_.retryRisk||0)+pC/2),t?t.retries=n+1:t={retries:1},this.commit(t)));let u={txnTime:r};if(this.next){let d=this.next?.commit(t);if(d?.then)return d?.then(E=>({txnTime:r,next:E}));u.next=d}return u}abort(){for(;this.readTxnsUsed>0;)this.doneReadTxn();this.open=0,this.writes=[]}},od=class extends eo{static{a(this,"ImmediateTransaction")}_timestamp;addWrite(t){super.addWrite(t),this.commit()}get timestamp(){return this._timestamp||(this._timestamp=(0,Jp.getNextMonotonicTime)())}getReadTxn(){}},RJ=3e4;a(OJ,"startMonitoringTxns");OJ()});function Je(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 eo;e.timestamp&&(n.timestamp=e.timestamp),n[ye]=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({letItLinger:r?.letItLinger});return l.then?l.then(()=>c):c}function o(c){throw n.abort({}),c}}var bC,to=Re(()=>{bC=require("../index");yn();Xp();a(Je,"transaction");(0,bC._assignPackageExport)("transaction",Je);Je.commit=function(e){let t=(e[ye]||e)?.transaction;if(!t)throw new Error("No active transaction is available to commit");return t.commit()};Je.abort=function(e){let t=(e[ye]||e)?.transaction;if(!t)throw new Error("No active transaction is available to abort");return t.abort()}});var PC={};qe(PC,{ResourceBridge:()=>eS});function tS({get_attributes:e},t){if(e){if(e[0]==="*"){if(t.schemaDefined)return;e=t.attributes.map(r=>r.name)}return e.forceNulls=!0,e}}function NC(e,t){let r=rs(e),n=tS(e,r);if(!r)throw new Mn.ClientError(`Table ${e.table} not found`);let s;n&&r.attributes.length-n.length>2&&n.length<5&&(s=!0);let i={user:e.hdb_user},o;Je(i,()=>new Promise(_=>o=_));let c=e.ids||e.hash_values,l=0;return{[Symbol.asyncIterator](){return{async next(){if(l<c.length){let _=c[l++],u=await r.get({id:_,lazy:s,select:n},i);return u=u&&cd(u),t?{value:{key:_,value:u}}:{value:u}}else return o(),{done:!0}},return(_){return o(),{value:_,done:!0}},throw(_){return o(),{done:!0}}}}}}function rs(e){let t=e.database||e.schema||yJ,r=mr()[t];if(!r)throw(0,Mn.handleHDBError)(new Error,bJ.SCHEMA_NOT_FOUND(t),404);return r[e.table]}function IC(e,t,r){let n=e.length+t.length,s=n===1?"record":"records";return{message:`${e.length} of ${n} ${s} successfully deleted`,deleted_hashes:e,skipped_hashes:t,txn_time:r}}async function*wC(e,t,r){let n;for await(let s of e.getHistory(t,r)){let i=s.type;i==="put"&&(i="upsert");let{id:o,version:c,value:l}=s;n?.timestamp===c?(n.hash_values.push(o),n.records.push(l)):(n&&(yield n),n={operation:i,user_name:s.user,timestamp:c,hash_values:[o],records:[l]})}n&&(yield n)}var CC,ad,Mn,DC,LC,Pn,jp,Zp,MC,bJ,yJ,NJ,IJ,yC,eS,UC=Re(()=>{"use strict";CC=B(mC()),ad=B(ta()),Mn=B(ne());Ae();DC=B(Bc()),LC=B(xc()),Pn=B(U()),jp=B(As()),Zp=B(Ln()),MC=B(z());to();ld();({HDB_ERROR_MSGS:bJ}=Mn.hdb_errors),yJ="data",NJ=1e4,IJ=10,eS=class extends CC.default{static{a(this,"ResourceBridge")}constructor(t){super(t),yC=this}async searchByConditions(t){t.select!==void 0&&(t.get_attributes=t.select);for(let o of t.conditions||[])o?.attribute!==void 0&&(o.search_attribute=o.attribute),o?.comparator!==void 0&&(o.search_type=o.comparator),o?.value!==void 0&&(o.search_value=o.value);let r=(0,ad.default)(t,"conditions");if(r)throw(0,Mn.handleHDBError)(r,r.message,400,void 0,void 0,!0);let n=rs(t);if(!n)throw new Mn.ClientError(`Table ${t.table} not found`);let s=t.conditions.map(i);function i(o){return o.conditions?(o.conditions=o.conditions.map(i),o):{attribute:o.search_attribute??o.attribute,comparator:o.search_type??o.comparator,value:o.search_value!==void 0?o.search_value:o.value}}return a(i,"mapCondition"),n.search({conditions:s,operator:t.operator?t.operator.toLowerCase():void 0,limit:t.limit,offset:t.offset,reverse:t.reverse,select:tS(t,n),sort:t.sort,allowFullScan:!0})}async createTable(t,r){let n=r.attributes,s=!!n,i=r.primary_key||r.hash_attribute;if(n)for(let o of n)o.is_primary_key?(o.isPrimaryKey=!0,delete o.is_primary_key):o.name===i&&i&&(o.isPrimaryKey=!0);else{if(!i)throw new Mn.ClientError("A primary key must be specified with a `primary_key` property or with `attributes`");n=[{name:i,isPrimaryKey:!0},{name:"__createdtime__",indexed:!0},{name:"__updatedtime__",indexed:!0}]}ft({database:r.schema,table:r.table,attributes:n,schemaDefined:s,expiration:r.expiration})}async createAttribute(t){return await rs(t).addAttributes([{name:t.attribute,indexed:t.indexed??!0}]),`attribute ${t.schema}.${t.table}.${t.attribute} successfully created.`}async dropAttribute(t){let r=rs(t);if(await r.removeAttributes([t.attribute]),!r.schemaDefined){let n=t.attribute,s,i=a((o,c,l)=>(c=Object.assign({},c),delete c[n],r.primaryStore.ifVersion(o,l,()=>r.primaryStore.put(o,c,l)).then(_=>{if(!_){let{value:u,version:d}=r.primaryStore.getEntry(o);return i(o,u,d)}})),"deleteRecord");for(let{key:o,value:c,version:l}of r.primaryStore.getRange({start:!0,versions:!0}))s=i(o,c,l),await new Promise(_=>setImmediate(_));await s}return`successfully deleted ${t.schema}.${t.table}.${t.attribute}`}dropTable(t){rs(t).dropTable()}createSchema(t){return sa({database:t.schema,table:null}),jp.signalSchemaChange(new Zp.SchemaEventMsg(process.pid,Pn.OPERATIONS_ENUM.CREATE_SCHEMA,t.schema))}async dropSchema(t){await rS(t.schema),jp.signalSchemaChange(new Zp.SchemaEventMsg(process.pid,Pn.OPERATIONS_ENUM.DROP_SCHEMA,t.schema))}async updateRecords(t){return t.requires_existing=!0,this.upsertRecords(t)}async createRecords(t){return t.requires_no_existing=!0,yC.upsertRecords(t)}async upsertRecords(t){let{schema_table:r,attributes:n}=(0,DC.default)(t);(0,LC.default)(t,n,r.primaryKey);let s,i=mr()[t.schema][t.table],o={user:t.hdb_user,expiresAt:t.expiresAt};return Je(o,async c=>{if(!i.schemaDefined){s=[];for(let u of n)i.attributes.find(E=>E.name==u)||s.push(u);s.length>0&&await i.addAttributes(s.map(u=>({name:u,indexed:!0})))}let l=[],_=[];for(let u of t.records){let d=await i.get(u[i.primaryKey],o);if(t.requires_existing&&!d||t.requires_no_existing&&d){_.push(u[i.primaryKey]);continue}d&&(d=cd(d));for(let E in u)if(Object.prototype.hasOwnProperty.call(u,E)){let f=u[E];if(typeof f=="function")try{let h=f([[d]]);Array.isArray(h)&&(f=h[0].func_val,u[E]=f)}catch(h){throw h.message+="Trying to set key "+E+" on object"+JSON.stringify(u),h}}if(d)for(let E in d)Object.prototype.hasOwnProperty.call(u,E)||(u[E]=d[E]);await i.put(u,o),l.push(u[i.primaryKey])}return{txn_time:c.timestamp,written_hashes:l,new_attributes:s,skipped_hashes:_}})}async deleteRecords(t){let r=mr()[t.schema][t.table],n={user:t.hdb_user};return Je(n,async s=>{let i=t.hash_values||t.records.map(l=>l[r.primaryKey]),o=[],c=[];for(let l of i)await r.delete(l,n)?o.push(l):c.push(l);return IC(o,c,s.timestamp)})}async deleteRecordsBefore(t){let r=mr()[t.schema][t.table];if(!r.createdTimeProperty)throw new Mn.ClientError("Table must have a '__createdtime__' attribute or @createdTime timestamp defined to perform this operation");let n=await r.search({conditions:[{attribute:r.createdTimeProperty.name,value:Date.parse(t.date),comparator:Pn.VALUE_SEARCH_COMPARATORS.LESS}]}),s=!1,i=[],o=[],c=0,l=[],_=a(async()=>{let u=await this.deleteRecords({schema:t.schema,table:t.table,hash_values:l});i.push(...u.deleted_hashes),o.push(...u.skipped_hashes),await(0,MC.async_set_timeout)(IJ),l=[],s=!0},"chunkDelete");for await(let u of n)l.push(u[r.primaryKey]),c++,c%NJ===0&&await _();return l.length>0&&await _(),s?IC(i,o,void 0):{message:"No records found to delete"}}searchByHash(t){t.select!==void 0&&(t.get_attributes=t.select);let r=(0,ad.default)(t,"hashes");if(r)throw r;return NC(t)}async getDataByHash(t){let r=new Map;t._returnKeyValue=!0;for await(let{key:n,value:s}of NC(t,!0))r.set(n,s);return r}searchByValue(t,r){if(r&&Pn.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[r]===void 0)throw new Error(`Value search comparator - ${r} - is not valid`);t.select!==void 0&&(t.get_attributes=t.select),t.attribute!==void 0&&(t.search_attribute=condition.attribute),t.value!==void 0&&(t.search_value=condition.value);let n=(0,ad.default)(t,"value");if(n)throw n;let s=rs(t);if(!s)throw new Mn.ClientError(`Table ${t.table} not found`);let i=t.search_value;i.includes?.("*")&&(i.startsWith("*")?i.endsWith("*")?i!=="*"&&(r="contains",i=i.slice(1,-1)):(r="ends_with",i=i.slice(1)):i.endsWith("*")&&(r="starts_with",i=i.slice(0,-1))),r===Pn.VALUE_SEARCH_COMPARATORS.BETWEEN&&(i=[i,t.end_value]);let o=i==="*"?[]:[{attribute:t.search_attribute,value:i,comparator:r}];return s.search({conditions:o,allowFullScan:!0,limit:t.limit,offset:t.offset,reverse:t.reverse,select:tS(t,s)})}async getDataByValue(t,r){let n=new Map,s=rs(t);t.get_attributes&&!t.get_attributes.includes(s.primaryKey)&&t.get_attributes[0]!=="*"&&t.get_attributes.push(s.primaryKey);for await(let i of this.searchByValue(t,r))n.set(i[s.primaryKey],i);return n}resetReadTxn(t,r){rs({schema:t,table:r})?.primaryStore.resetReadTxn()}async deleteAuditLogsBefore(t){return rs(t).deleteHistory(t.timestamp)}async readAuditLog(t){let r=rs(t),n={};switch(t.search_type){case Pn.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.HASH_VALUE:for(let i of t.search_values)n[i]=(await r.getHistoryOfRecord(i)).map(o=>{let c=o.type;return c==="put"&&(c="upsert"),{operation:c,timestamp:o.version,user_name:o.user,hash_values:[i],records:[o.value]}});return n;case Pn.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.USERNAME:let s=t.search_values;for await(let i of wC(r))s.includes(i.user_name)&&(n[i.user_name]||(n[i.user_name]=[])).push(i);return n;default:return wC(r,t.search_values?.[0],t.search_values?.[1])}}};a(tS,"getSelect");a(NC,"getRecords");a(rs,"getTable");a(IC,"createDeleteResponse");a(wC,"groupRecordsInHistory")});var wn=g((g_e,vC)=>{"use strict";var{ResourceBridge:wJ}=(UC(),ie(PC)),CJ=te();CJ.initSync();var ud;function DJ(){return ud||(ud=new wJ,ud)}a(DJ,"getBridge");vC.exports=DJ()});var GC=g((A_e,xC)=>{"use strict";var BC=require("lodash"),sl=require("mathjs"),LJ=require("jsonata"),HC=z();xC.exports={distinct_array:e=>Array.isArray(e)&&e.length>1?BC.uniqWith(e,BC.isEqual):e,searchJSON:MJ,mad:il.bind(null,sl.mad),mean:il.bind(null,sl.mean),mode:il.bind(null,sl.mode),prod:il.bind(null,sl.prod),median:il.bind(null,sl.median)};function il(e,t,r,n){return n===1?t==null?[]:[t]:n===2?(t!=null&&r.push(t),r):r!=null&&r.length>0?e(r):null}a(il,"aggregateFunction");function MJ(e,t){if(typeof e!="string"||e.length===0)throw new Error("search json expression must be a non-empty string");let r="__"+e+"__";if(HC.isEmpty(this.__ala__.res)&&(this.__ala__.res={}),HC.isEmpty(this.__ala__.res[r])){let n=LJ(e);this.__ala__.res[r]=n}return this.__ala__.res[r].evaluate(t)}a(MJ,"searchJSON")});var qC=g((b_e,FC)=>{"use strict";var gt=require("moment"),nS="YYYY-MM-DDTHH:mm:ss.SSSZZ";gt.suppressDeprecationWarnings=!0;FC.exports={current_date:()=>gt().utc().format("YYYY-MM-DD"),current_time:()=>gt().utc().format("HH:mm:ss.SSS"),extract:(e,t)=>{switch(t.toLowerCase()){case"year":return gt(e).utc().format("YYYY");case"month":return gt(e).utc().format("MM");case"day":return gt(e).utc().format("DD");case"hour":return gt(e).utc().format("HH");case"minute":return gt(e).utc().format("mm");case"second":return gt(e).utc().format("ss");case"millisecond":return gt(e).utc().format("SSS");default:break}},date:e=>gt(e).utc().format(nS),date_format:(e,t)=>gt(e).utc().format(t),date_add:(e,t,r)=>gt(e).utc().add(t,r).valueOf(),date_sub:(e,t,r)=>gt(e).utc().subtract(t,r).valueOf(),date_diff:(e,t,r)=>{let n=gt(e).utc(),s=gt(t).utc();return r?n.diff(s,r,!0):n.diff(s)},now:()=>gt().utc().valueOf(),get_server_time:()=>gt().format(nS),offset_utc:(e,t)=>gt(e).utc().utcOffset(t).format(nS)}});var YC=g((y_e,$C)=>{"use strict";var PJ=require("@turf/area"),UJ=require("@turf/length"),vJ=require("@turf/circle"),BJ=require("@turf/difference"),HJ=require("@turf/distance"),xJ=require("@turf/boolean-contains"),GJ=require("@turf/boolean-equal"),FJ=require("@turf/boolean-disjoint"),qJ=require("@turf/helpers"),kC=U(),Se=z(),ys=K();$C.exports={geoArea:kJ,geoLength:VJ,geoCircle:$J,geoDifference:YJ,geoDistance:VC,geoNear:KJ,geoContains:WJ,geoEqual:QJ,geoCrosses:zJ,geoConvert:JJ};function kJ(e){if(Se.isEmpty(e))return NaN;typeof e=="string"&&(e=Se.autoCastJSON(e));try{return PJ.default(e)}catch(t){return ys.trace(t,e),NaN}}a(kJ,"geoArea");function VJ(e,t){if(Se.isEmpty(e))return NaN;typeof e=="string"&&(e=Se.autoCastJSON(e));try{return UJ.default(e,{units:t||"kilometers"})}catch(r){return ys.trace(r,e),NaN}}a(VJ,"geoLength");function $J(e,t,r){if(Se.isEmpty(e))return NaN;if(Se.isEmpty(t))return NaN;typeof e=="string"&&(e=Se.autoCastJSON(e));try{return vJ.default(e,t,{units:r||"kilometers"})}catch(n){return ys.trace(n,e,t),NaN}}a($J,"geoCircle");function YJ(e,t){if(Se.isEmpty(e))return NaN;if(Se.isEmpty(t))return NaN;typeof e=="string"&&(e=Se.autoCastJSON(e)),typeof t=="string"&&(t=Se.autoCastJSON(t));try{return BJ(e,t)}catch(r){return ys.trace(r,e,t),NaN}}a(YJ,"geoDifference");function VC(e,t,r){if(Se.isEmpty(e))return NaN;if(Se.isEmpty(t))return NaN;typeof e=="string"&&(e=Se.autoCastJSON(e)),typeof t=="string"&&(t=Se.autoCastJSON(t));try{return HJ.default(e,t,{units:r||"kilometers"})}catch(n){return ys.trace(n,e,t),NaN}}a(VC,"geoDistance");function KJ(e,t,r,n){if(Se.isEmpty(e)||Se.isEmpty(t))return!1;if(Se.isEmpty(r))throw new Error("distance is required");if(typeof e=="string"&&(e=Se.autoCastJSON(e)),typeof t=="string"&&(t=Se.autoCastJSON(t)),isNaN(r))throw new Error("distance must be a number");try{return VC(e,t,n)<=r}catch(s){return ys.trace(s,e,t),!1}}a(KJ,"geoNear");function WJ(e,t){if(Se.isEmpty(e)||Se.isEmpty(t)||e.coordinates&&e.coordinates.includes?.(null)||t.coordinates&&t.coordinates.includes?.(null))return!1;typeof e=="string"&&(e=Se.autoCastJSON(e)),typeof t=="string"&&(t=Se.autoCastJSON(t));try{return xJ.default(e,t)}catch(r){return ys.trace(r,e,t),!1}}a(WJ,"geoContains");function QJ(e,t){if(Se.isEmpty(e)||Se.isEmpty(t)||e.coordinates&&e.coordinates.includes?.(null)||t.coordinates&&t.coordinates.includes?.(null))return!1;typeof e=="string"&&(e=Se.autoCastJSON(e)),typeof t=="string"&&(t=Se.autoCastJSON(t));try{return GJ.default(e,t)}catch(r){return ys.trace(r,e,t),!1}}a(QJ,"geoEqual");function zJ(e,t){if(Se.isEmpty(e)||Se.isEmpty(t)||e.coordinates&&e.coordinates.includes?.(null)||t.coordinates&&t.coordinates.includes?.(null))return!1;typeof e=="string"&&(e=Se.autoCastJSON(e)),typeof t=="string"&&(t=Se.autoCastJSON(t));try{return!FJ.default(e,t)}catch(r){return ys.trace(r,e,t),!1}}a(zJ,"geoCrosses");function JJ(e,t,r){if(Se.isEmptyOrZeroLength(e))throw new Error("coordinates is required");if(Se.isEmpty(t))throw new Error("geo_type is required");if(Se.isEmpty(kC.GEO_CONVERSION_ENUM[t]))throw new Error(`geo_type of ${t} is invalid please use one of the following types: ${Object.keys(kC.GEO_CONVERSION_ENUM).join(",")}`);return typeof e=="string"&&(e=Se.autoCastJSON(e)),qJ[t](e,r)}a(JJ,"geoConvert")});var _d=g((I_e,KC)=>{var ro=GC(),Yr=qC(),ns=YC();KC.exports=e=>{e.aggr.mad=e.aggr.MAD=ro.mad,e.aggr.mean=e.aggr.MEAN=ro.mean,e.aggr.mode=e.aggr.MODE=ro.mode,e.aggr.prod=e.aggr.PROD=ro.prod,e.aggr.median=e.aggr.MEDIAN=ro.median,e.fn.distinct_array=e.fn.DISTINCT_ARRAY=ro.distinct_array,e.fn.search_json=e.fn.SEARCH_JSON=ro.searchJSON,e.fn.__ala__=e,e.fn.current_date=e.fn.CURRENT_DATE=Yr.current_date,e.fn.current_time=e.fn.CURRENT_TIME=Yr.current_time,e.fn.extract=e.fn.EXTRACT=Yr.extract,e.fn.date=e.fn.DATE=Yr.date,e.fn.date_format=e.fn.DATE_FORMAT=Yr.date_format,e.fn.date_add=e.fn.DATE_ADD=Yr.date_add,e.fn.date_sub=e.fn.DATE_SUB=Yr.date_sub,e.fn.date_diff=e.fn.DATE_DIFF=e.fn.datediff=e.fn.DATEDIFF=Yr.date_diff,e.fn.now=e.fn.NOW=Yr.now,e.fn.offset_utc=e.fn.OFFSET_UTC=Yr.offset_utc,e.fn.get_server_time=e.fn.GET_SERVER_TIME=Yr.get_server_time,e.fn.getdate=e.fn.GETDATE=Yr.now,e.fn.current_timestamp=e.fn.CURRENT_TIMESTAMP=Yr.now,e.fn.geoarea=e.fn.GEOAREA=e.fn.geoArea=ns.geoArea,e.fn.geocircle=e.fn.GEOCIRCLE=e.fn.geoCircle=ns.geoCircle,e.fn.geocontains=e.fn.GEOCONTAINS=e.fn.geoContains=ns.geoContains,e.fn.geoconvert=e.fn.GEOCONVERT=e.fn.geoConvert=ns.geoConvert,e.fn.geocrosses=e.fn.GEOCROSSES=e.fn.geoCrosses=ns.geoCrosses,e.fn.geodifference=e.fn.GEODIFFERENCE=e.fn.geoDifference=ns.geoDifference,e.fn.geodistance=e.fn.GEODISTANCE=e.fn.geoDistance=ns.geoDistance,e.fn.geoequal=e.fn.GEOEQUAL=e.fn.geoEqual=ns.geoEqual,e.fn.geolength=e.fn.GEOLENGTH=e.fn.geoLength=ns.geoLength,e.fn.geonear=e.fn.GEONEAR=e.fn.geoNear=ns.geoNear}});var JC=g((w_e,zC)=>{"use strict";var ol=require("lodash"),pr=require("alasql");pr.options.cache=!1;var XJ=_d(),WC=require("clone"),dd=require("recursive-iterator"),_e=K(),De=z(),ia=wn(),jJ=U(),{hdb_errors:ZJ}=ne(),{getDatabases:QC}=(Ae(),ie(ke)),e4="IS NULL",Un="There was a problem performing this search. Please check the logs and try again.";XJ(pr);var sS=class{static{a(this,"SQLSearch")}constructor(t,r){if(De.isEmpty(t))throw _e.error("AST statement for SQL select process cannot be empty"),"statement cannot be null";this.statement=t,this.columns={},this.all_table_attributes=r,this.fetch_attributes=[],this.exact_search_values={},this.comparator_search_values={},this.tables=[],this.data={},this.has_aggregator=!1,this.has_ordinal=!1,this.has_outer_join=!1,this._getColumns(),this._getTables(),this._conditionsToFetchAttributeValues(),this._setAliasesForColumns(),De.backtickASTSchemaItems(this.statement)}async search(){let t;try{let n=await this._checkEmptySQL();if(!De.isEmptyOrZeroLength(n))return _e.trace("No results returned from checkEmptySQL SQLSearch method."),n}catch(n){throw _e.error("Error thrown from checkEmptySQL in SQLSearch class method search."),_e.error(n),new Error(Un)}try{let n=await this._getFetchAttributeValues();if(n)return n}catch(n){throw _e.error("Error thrown from getFetchAttributeValues in SQLSearch class method search."),_e.error(n),new Error(Un)}if(Object.keys(this.data).length===0)return _e.trace('SQLSearch class field: "data" is empty.'),[];let r;try{r=await this._processJoins()}catch(n){throw _e.error("Error thrown from processJoins in SQLSearch class method search."),_e.error(n),new Error(Un)}try{await this._getFinalAttributeData(r.existing_attributes,r.joined_length)}catch(n){throw _e.error("Error thrown from getFinalAttributeData in SQLSearch class method search."),_e.error(n),new Error(Un)}try{return t=await this._finalSQL(),t}catch(n){throw _e.error("Error thrown from finalSQL in SQLSearch class method search."),_e.error(n),new Error(Un)}}_getColumns(){let t=new dd(this.statement);for(let{node:r,path:n}of t)r&&r.columnid&&(this.columns[n[0]]||(this.columns[n[0]]=[]),this.columns[n[0]].push(WC(r)))}_getTables(){let t=[];this.all_table_attributes.forEach(r=>{t.push(r.table)}),this.tables=ol.uniqBy(t,r=>[r.databaseid,r.tableid,r.as].join()),this.tables.forEach(r=>{let n=`${r.databaseid}_${r.as?r.as:r.tableid}`;this.data[n]={},this.data[n].__hash_name=QC()[r.databaseid][r.tableid].primaryKey,this.data[n].__merged_data={},this.data[n].__merged_attributes=[],this.data[n].__merged_attr_map={}})}_conditionsToFetchAttributeValues(){if(De.isEmpty(this.statement.where)){_e.trace('AST "where" statement is empty.');return}let t=!1;for(let{node:r}of new dd(this.statement.where))if(r&&r.op&&r.op==="OR"&&(t=!0),!De.isEmpty(r)&&r.right)if(De.isNotEmptyAndHasValue(r.right.value)){let n=De.autoCast(r.right.value);[!0,!1].indexOf(n)>=0&&(r.right=new pr.yy.LogicValue({value:n}))}else Array.isArray(r.right)&&r.right.forEach((n,s)=>{let i=De.autoCast(n.value);[!0,!1].indexOf(i)>=0?r.right[s]=new pr.yy.LogicValue({value:i}):n instanceof pr.yy.StringValue&&De.autoCasterIsNumberCheck(i.toString())&&(r.right[s]=new pr.yy.NumValue({value:i}))});if(t){_e.trace('Where clause contains "OR", exact match search not performed on attributes.');return}for(let{node:r}of new dd(this.statement.where))if(r&&r.left&&r.right&&(r.left.columnid||r.right.value)&&r.op){let n=new Set,s=r.left.columnid?r.left:r.right,i=this._findColumn(s);if(!i)continue;let o=[i.table.databaseid,i.table.tableid,i.attribute].join("/");if(!De.isEmpty(jJ.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[r.op])){if(De.isEmpty(this.comparator_search_values[o])&&(this.comparator_search_values[o]={ignore:!1,comparators:[]}),!this.comparator_search_values[o].ignore){if(De.isEmptyOrZeroLength(r.left.columnid)||De.isEmptyOrZeroLength(r.right.value)){this.comparator_search_values[o].ignore=!0,this.comparator_search_values[o].comparators=[];continue}this.comparator_search_values[o].comparators.push({attribute:r.left.columnid,operation:r.op,search_value:r.right.value})}continue}if(De.isEmpty(this.exact_search_values[o])&&(this.exact_search_values[o]={ignore:!1,values:new Set}),!this.exact_search_values[o].ignore){let c=!1;switch(r.op){case"=":!De.isEmpty(r.right.value)||!De.isEmpty(r.left.value)?n.add(De.isEmpty(r.right.value)?r.left.value:r.right.value):c=!0;break;case"IN":let l=Array.isArray(r.right)?r.right:r.left;for(let _=0;_<l.length;_++)if(l[_].value)n.add(l[_].value);else{c=!0;break}break;default:c=!0;break}this.exact_search_values[o].ignore=c,c?this.exact_search_values[o].values=new Set:this.exact_search_values[o].values=new Set([...this.exact_search_values[o].values,...n])}}}_setAliasesForColumns(){if(De.isEmptyOrZeroLength(this.all_table_attributes)&&De.isEmptyOrZeroLength(this.statement.from)&&De.isEmptyOrZeroLength(this.columns.columns))return;let t=[],r={};this.statement.columns.forEach((n,s)=>{if(n.columnid==="*"){t.push(s);return}if(n.aggregatorid&&(this.has_aggregator=!0),!n.aggregatorid&&!n.funcid)if(n.as_orig=n.as?n.as:n.columnid,this.statement.joins)if(r[n.as_orig]>=0){let i=r[n.as_orig]+1;n.as=`[${n.as_orig+i}]`,r[n.as_orig]=i}else n.as=`[${n.as_orig}]`,r[n.as_orig]=0;else n.as=`[${n.as_orig}]`;!n.aggregatorid&&n.funcid&&n.args&&(n.as_orig=n.as?n.as:n.toString().replace(/'/g,'"'),n.as=`[${n.as_orig}]`),n.aggregatorid&&n.expression.columnid!=="*"&&(n.as_orig=n.as?n.as:n.expression.tableid?`${n.aggregatorid}(${n.expression.tableid}.${n.expression.columnid})`:`${n.aggregatorid}(${n.expression.columnid})`,n.as=`[${n.as_orig}]`)}),this.statement.columns.length>1&&t.length>0&&ol.pullAt(this.statement.columns,t)}_findColumn(t){let r=this.all_table_attributes.filter(n=>{if(t.columnid_orig&&t.tableid_orig)return(n.table.as===t.tableid_orig||n.table.tableid===t.tableid_orig)&&n.attribute===t.columnid_orig;if(t.tableid)return(n.table.as===t.tableid||n.table.tableid===t.tableid)&&n.attribute===t.columnid;let s=t.columnid_orig?t.columnid_orig:t.columnid;return n.attribute===s});if(De.isEmptyOrZeroLength(r)){let n=this.columns.columns.filter(s=>s.as?t.columnid===s.as:!1);De.isEmptyOrZeroLength(n)||(r=this.all_table_attributes.filter(s=>s.attribute===n[0].columnid&&n[0].tableid&&n[0].tableid===(s.table.as?s.table.as:s.table.tableid)))}return r[0]}async _checkEmptySQL(){let t=[];if(De.isEmptyOrZeroLength(this.all_table_attributes)&&!De.isEmptyOrZeroLength(this.columns.columns))return t;if(De.isEmptyOrZeroLength(this.all_table_attributes)&&De.isEmptyOrZeroLength(this.statement.from))try{let r=this._buildSQL(!1);t=await pr.promise(r)}catch(r){throw _e.error("Error thrown from AlaSQL in SQLSearch class method checkEmptySQL."),_e.error(r),new Error("There was a problem with the SQL statement")}return t}_addFetchColumns(t){t&&t.length>0&&t.forEach(r=>{let n=this._findColumn(r);n&&this.fetch_attributes.push(WC(n))})}_addColumnToMergedAttributes(t,r){this.data[t].__merged_attributes.push(r),this.data[t].__merged_attr_map[r]=this.data[t].__merged_attributes.length-1}_setMergedHashAttribute(t,r){this.data[t].__merged_data[r].splice(0,1,r)}_updateMergedAttribute(t,r,n,s){let i=this.data[t].__merged_attr_map[n];this.data[t].__merged_data[r].splice(i,1,s)}async _getFetchAttributeValues(){if(De.isEmptyOrZeroLength(Object.keys(this.columns)))return[];this._addFetchColumns(this.columns.joins);let t=null;try{t=this.statement.where?this.statement.where.toString():""}catch{throw new Error("Could not generate proper where clause")}this.columns.where&&this._addFetchColumns(this.columns.where);let r=this._isSimpleSelect();if(r?this._addFetchColumns(this.columns.columns):(!this.columns.where&&this.fetch_attributes.length===0)|t.indexOf(e4)>-1&&this.tables.forEach(s=>{let i={columnid:QC()[s.databaseid][s.tableid].primaryKey,tableid:s.tableid};this._addFetchColumns([i])}),this.statement.order&&(this._updateOrderByToAliases(),this._addNonAggregatorsToFetchColumns()),this.fetch_attributes=ol.uniqBy(this.fetch_attributes,s=>[s.table.databaseid,s.table.as?s.table.as:s.table.tableid,s.attribute].join()),r)return await this._simpleSQLQuery();let n=this.fetch_attributes.reduce((s,i)=>{let o=`${i.table.databaseid}_${i.table.as?i.table.as:i.table.tableid}`,c=this.data[o].__hash_name;return s[o]||(s[o]=[],s[o].push(null),this._addColumnToMergedAttributes(o,c)),i.attribute!==c&&(s[o].push(null),this._addColumnToMergedAttributes(o,i.attribute)),s},{});for(let s of this.fetch_attributes){let i=`${s.table.databaseid}_${s.table.as?s.table.as:s.table.tableid}`,o=this.data[i].__hash_name,c={schema:s.table.databaseid,table:s.table.tableid,get_attributes:[s.attribute]},l=!1,_=[s.table.databaseid,s.table.tableid,s.attribute].join("/");if(s.attribute===o&&(l=!0),!De.isEmpty(this.exact_search_values[_])&&!this.exact_search_values[_].ignore&&!De.isEmptyOrZeroLength(this.exact_search_values[_].values))if(l)try{c.hash_values=Array.from(this.exact_search_values[_].values);let u=await ia.getDataByHash(c);for(let d of c.hash_values)u.get(d)&&!this.data[i].__merged_data[d]&&(this.data[i].__merged_data[d]=[...n[i]],this._setMergedHashAttribute(i,d))}catch(u){throw _e.error("Error thrown from getDataByHash function in SQLSearch class method getFetchAttributeValues exact match."),_e.error(u),new Error(Un)}else try{c.search_attribute=s.attribute,await Promise.all(Array.from(this.exact_search_values[_].values).map(async u=>{let d=Object.assign({},c);d.search_value=u;let E=await ia.getDataByValue(d);for(let[f,h]of E)this.data[i].__merged_data[f]?this._updateMergedAttribute(i,f,s.attribute,h[s.attribute]):(this.data[i].__merged_data[f]=[...n[i]],this._updateMergedAttribute(i,f,s.attribute,h[s.attribute]),this._setMergedHashAttribute(i,f))}))}catch(u){throw _e.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues exact match."),_e.error(u),new Error(Un)}else if(!De.isEmpty(this.comparator_search_values[_])&&!this.comparator_search_values[_].ignore&&!De.isEmptyOrZeroLength(this.comparator_search_values[_].comparators))try{let u=this.comparator_search_values[_].comparators;for(let d=0,E=u.length;d<E;d++){let f=u[d];c.search_attribute=f.attribute,c.search_value=f.search_value;let h=await ia.getDataByValue(c,f.operation);if(l)for(let[p]of h)this.data[i].__merged_data[p]||(this.data[i].__merged_data[p]=[...n[i]],this._setMergedHashAttribute(i,p));else for(let[p,S]of h)this.data[i].__merged_data[p]?this._updateMergedAttribute(i,p,s.attribute,S[s.attribute]):(this.data[i].__merged_data[p]=[...n[i]],this._updateMergedAttribute(i,p,s.attribute,S[s.attribute]),this._setMergedHashAttribute(i,p))}}catch(u){throw _e.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues comparator search values."),_e.error(u),new Error(Un)}else try{c.search_attribute=s.attribute,c.search_value="*";let u=await ia.getDataByValue(c);if(l)for(let[d]of u)this.data[i].__merged_data[d]||(this.data[i].__merged_data[d]=[...n[i]],this._setMergedHashAttribute(i,d));else for(let[d,E]of u)this.data[i].__merged_data[d]?this._updateMergedAttribute(i,d,s.attribute,E[s.attribute]):(this.data[i].__merged_data[d]=[...n[i]],this._updateMergedAttribute(i,d,s.attribute,E[s.attribute]),this._setMergedHashAttribute(i,d))}catch(u){throw _e.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues no comparator search values."),_e.error(u),new Error(Un)}}}_isSimpleSelect(){let t=!0;return Object.keys(this.statement).length!==2||!this.statement.columns||!this.statement.from||this.statement.from.length!==1?(t=!1,t):(this.statement.columns.forEach(r=>{r instanceof pr.yy.Column||(t=!1)}),t)}_updateOrderByToAliases(){this.statement.order.forEach(t=>{if(t.expression.aggregatorid){t.is_aggregator=!0;return}if(t.expression.value){t.is_ordinal=!0,this.has_ordinal=!0;return}else t.is_ordinal=!1;let r=this.statement.columns.filter(s=>{let i=s.aggregatorid?s.expression:s,o=s.aggregatorid?s.as_orig:i.as_orig;return t.expression.tableid?i.columnid_orig===t.expression.columnid_orig&&i.tableid_orig===t.expression.tableid_orig:i.columnid_orig===t.expression.columnid_orig||t.expression.columnid_orig===o});r[0]||r.push(this._findColumn(t.expression));let n=r[0];if(t.is_func=!!n.funcid,t.is_aggregator=!!n.aggregatorid,n.as)if(n.as&&!t.expression.tableid)t.expression.columnid=n.as,t.expression.columnid_orig=n.as_orig;else{let s=new pr.yy.Column;s.columnid=n.as,s.columnid_orig=n.as_orig,t.expression=s}else{t.initial_select_column=Object.assign(new pr.yy.Column,t.expression),t.initial_select_column.as=`[${t.expression.columnid_orig}]`,t.expression.columnid=t.initial_select_column.as;return}if(!t.is_aggregator){let s=t.is_func?new pr.yy.FuncValue:new pr.yy.Column;t.initial_select_column=Object.assign(s,n)}})}_addNonAggregatorsToFetchColumns(){let r=this.statement.order.filter(n=>!n.is_aggregator&&!n.is_ordinal).map(n=>n.is_func?{columnid:n.initial_select_column.args.filter(i=>!!i.columnid_orig)[0].columnid_orig}:{columnid:n.expression.columnid_orig});this._addFetchColumns(r)}async _processJoins(){let t=[],r=[],n=this.statement.from[0],s=[n],i=["? "+(n.as?" AS "+n.as:n.tableid)];t.push(Object.values(this.data[`${n.databaseid_orig}_${n.as?n.as_orig:n.tableid_orig}`].__merged_data)),this.statement.joins&&this.statement.joins.forEach(f=>{f.joinmode&&f.joinmode!=="INNER"&&(this.has_outer_join=!0),s.push(f.table);let h=f.joinmode+" JOIN ? AS "+(f.as?f.as:f.table.tableid);f.on&&(h+=" ON "+f.on.toString()),i.push(h),t.push(Object.values(this.data[`${f.table.databaseid_orig}_${f.table.as?f.table.as_orig:f.table.tableid_orig}`].__merged_data))});let o=[],c={};s.forEach(f=>{let h=this.data[`${f.databaseid_orig}_${f.as?f.as_orig:f.tableid_orig}`].__hash_name,p=f.as?f.as_orig:f.tableid_orig;o.push({key:`'${p}.${h}'`,schema:f.databaseid_orig,table:f.as?f.as_orig:f.tableid_orig,keys:new Set}),r.push(`${f.as?f.as:f.tableid}.\`${h}\` AS "${p}.${h}"`),c[f.as?f.as_orig:f.tableid_orig]=this.data[`${f.databaseid_orig}_${f.as?f.as_orig:f.tableid_orig}`].__merged_attributes});let l=this.statement.where?"WHERE "+this.statement.where:"";l=l.replace(/NOT\(NULL\)/g,"NOT NULL");let _="";this.statement.order&&!this.has_ordinal&&!this.has_aggregator&&!this.statement.group&&this.statement.limit&&(_="ORDER BY "+this.statement.order.toString(),this.statement.order.forEach(f=>{f.is_func?r.push(f.initial_select_column.toString()):f.initial_select_column.tableid?r.push(`${f.initial_select_column.tableid}.${f.initial_select_column.columnid} AS ${f.expression.columnid}`):r.push(`${f.initial_select_column.columnid} AS ${f.expression.columnid}`)}));let u="",d="";!this.has_aggregator&&!this.statement.group&&!this.has_ordinal&&!this.statement.joins&&(u=this.statement.limit?"LIMIT "+this.statement.limit:"",d=this.statement.offset?"OFFSET "+this.statement.offset:"");let E=[];try{let f=`SELECT ${r.join(", ")} FROM ${i.join(" ")} ${l} ${_} ${u} ${d}`,h=this._convertColumnsToIndexes(f,s);E=await pr.promise(h,t),t=null}catch(f){throw _e.error("Error thrown from AlaSQL in SQLSearch class method processJoins."),_e.error(f),new Error("There was a problem processing the data.")}if(E&&E.length>0){for(let f=0,h=E.length;f<h;f++){let p=E[f];o.forEach(S=>{p[S.key]!==null&&p[S.key]!==void 0&&S.keys.add(p[S.key])})}o.forEach(f=>{let h=Object.keys(this.data[`${f.schema}_${f.table}`].__merged_data),p=ol.difference(h,[...f.keys].map(S=>S.toString()));for(let S=0,T=p.length;S<T;S++){let R=p[S];delete this.data[`${f.schema}_${f.table}`].__merged_data[R]}})}return{existing_attributes:c,joined_length:E?E.length:0}}async _getFinalAttributeData(t,r){if(r===0)return;let n=[],s=new dd(this.columns);for(let{node:i}of s)if(i&&i.columnid){let o=this._findColumn(i);if(o){let c=o.table.as?o.table.as:o.table.tableid;(!t[c]||t[c].indexOf(o.attribute)<0)&&n.push(o)}}n=ol.uniqBy(n,i=>[i.table.databaseid,i.table.as?i.table.as:i.table.tableid,i.attribute].join());try{await this._getData(n)}catch(i){throw _e.error("Error thrown from getData in SQLSearch class method getFinalAttributeData."),_e.error(i),new Error(Un)}}async _getData(t){try{let r=t.reduce((n,s)=>{let i=`${s.table.databaseid}_${s.table.as?s.table.as:s.table.tableid}`;return n[i]?n[i].columns.push(s.attribute):n[i]={schema:s.table.databaseid,table:s.table.tableid,columns:[s.attribute]},n},{});for(let n in r){let s=r[n],i=this.data[n].__merged_data,o=[];for(let u in i)o.push(i[u][0]);this.data[n].__merged_attributes.push(...s.columns);let c={schema:s.schema,table:s.table,hash_values:o,get_attributes:s.columns},l=await ia.getDataByHash(c),_=s.columns.length;for(let u=0,d=o.length;u<d;u++){let E=o[u],f=l.get(E);for(let h=0;h<_;h++){let p=s.columns[h],S=f[p]===void 0?null:f[p];this.data[n].__merged_data[E].push(S)}}}}catch(r){throw _e.error("Error thrown from getDataByHash function in SQLSearch class method getData."),_e.error(r),r}}async _finalSQL(){let t=[],r=this.statement.from[0];t.push(Object.values(this.data[`${r.databaseid_orig}_${r.as?r.as_orig:r.tableid_orig}`].__merged_data)),r.as=r.as?r.as:r.tableid,r.databaseid="",r.tableid="?",this.statement.joins&&this.statement.joins.forEach(s=>{s.as=s.as?s.as:s.table.tableid,t.push(Object.values(this.data[`${s.table.databaseid_orig}_${s.table.as?s.table.as_orig:s.table.tableid_orig}`].__merged_data)),s.table.databaseid="",s.table.tableid="?"}),this.statement.order&&this.statement.order.forEach(s=>{if(s.is_ordinal)return;this.statement.columns.filter(o=>{let c=o.aggregatorid?o.expression:o,l=o.aggregatorid?o.as_orig:c.as_orig;return s.expression.tableid?c.columnid_orig===s.expression.columnid_orig&&c.tableid_orig===s.expression.tableid_orig:c.columnid_orig===s.expression.columnid_orig||s.expression.columnid_orig===l}).length===0&&(s.expression.columnid=s.initial_select_column.columnid)}),!this.has_aggregator&&!this.statement.group&&!this.has_ordinal&&this.statement.limit&&!this.statement.joins&&(delete this.statement.limit,delete this.statement.offset);let n;try{let s=this._buildSQL();_e.trace(`Final SQL: ${s}`),n=await pr.promise(s,t),this.has_outer_join&&(n=this._translateUndefinedValues(n)),_e.trace(`Final AlaSQL results data included ${n.length} rows`)}catch(s){throw _e.error("Error thrown from AlaSQL in SQLSearch class method finalSQL."),_e.error(s),new Error("There was a problem running the generated sql.")}return n}_translateUndefinedValues(t){try{let r=[];for(let n of t){let s=Object.create(null);Object.keys(n).forEach(i=>{n[i]===void 0?s[i]=null:s[i]=n[i]}),r.push(s)}return r}catch(r){return _e.error(ZJ.HDB_ERROR_MSGS.OUTER_JOIN_TRANSLATION_ERROR),_e.trace(r.stack),t}}_buildSQL(t=!0){let r=this.statement.toString();return r=r.replace(/NOT\(NULL\)/g,"NOT NULL"),this.statement.columns.forEach(n=>{if(n.funcid&&n.as){let s=n.toString().replace(" AS "+n.as,"");r=r.replace(n.toString(),s)}}),t===!0?this._convertColumnsToIndexes(r,this.tables):r}_convertColumnsToIndexes(t,r){let n=t,s={};r.forEach(i=>{i.databaseid_orig?s[`${i.databaseid_orig}_${i.as?i.as_orig:i.tableid_orig}`]=i.as?i.as:i.tableid:s[`${i.databaseid}_${i.as?i.as:i.tableid}`]=`\`${i.as?i.as:i.tableid}\``});for(let i in this.data)this.data[i].__merged_attributes.forEach((o,c)=>{let l=s[i],_=new RegExp(`${l}.\`${o}\``,"g"),u=`${l}.[${c}]`;n=n.replace(_,u)});for(let i in this.data)this.data[i].__merged_attributes.forEach((o,c)=>{let l=new RegExp(`\`${o}\``,"g"),_=`[${c}]`;n=n.replace(l,_)});return n}async _simpleSQLQuery(){let t=this.statement.columns.reduce((n,s)=>(s.as_orig&&s.as_orig!=s.columnid_orig?n[s.columnid_orig]=s.as_orig:n[s.columnid_orig]||(n[s.columnid_orig]=s.columnid_orig),n),{}),r=this.fetch_attributes.reduce((n,s)=>{let i=`${s.table.databaseid}_${s.table.as?s.table.as:s.table.tableid}`;return n[i]||(n[i]={}),n[i][t[s.attribute]]=null,n},{});for(let n of this.fetch_attributes){let s=`${n.table.databaseid}_${n.table.as?n.table.as:n.table.tableid}`,i={schema:n.table.databaseid,table:n.table.tableid,get_attributes:[n.attribute]};try{i.search_attribute=n.attribute,i.search_value="*";let o=await ia.getDataByValue(i);for(let[c,l]of o)this.data[s].__merged_data[c]||(l[n.attribute]===void 0&&(l[n.attribute]=null),this.data[s].__merged_data[c]=Object.assign({},r[s])),this.data[s].__merged_data[c][t[n.attribute]]=l[n.attribute]??null}catch(o){throw _e.error("There was an error when processing this SQL operation. Check your logs"),_e.error(o),new Error(Un)}}return Object.values(Object.values(this.data)[0].__merged_data)}};zC.exports=sS});var Gr=g((D_e,XC)=>{"use strict";var t4=Nb();XC.exports={searchByConditions:n4,searchByHash:s4,searchByValue:i4,search:o4};var iS=wn(),{transformReq:oS}=z(),r4=JC();async function n4(e){return oS(e),iS.searchByConditions(e)}a(n4,"searchByConditions");async function s4(e){oS(e),e.ids&&(e.hash_values=e.ids);let t=[];for await(let r of iS.searchByHash(e))r&&t.push(r);return t}a(s4,"searchByHash");async function i4(e){oS(e),e.hasOwnProperty("desc")===!0&&(e.reverse=e.desc);let t=[];for await(let r of iS.searchByValue(e))t.push(r);return t}a(i4,"searchByValue");function o4(e,t){try{let r=new t4(e);r.validate(),new r4(r.statement,r.attributes).search().then(s=>{t(null,s)}).catch(s=>{t(s,null)})}catch(r){return t(r)}}a(o4,"search")});var fd=g((M_e,jC)=>{"use strict";var a4=wn();jC.exports={writeTransaction:c4};function c4(e,t,r){return a4.writeTransaction(e,t,r)}a(c4,"writeTransaction")});var rD=g((v_e,tD)=>{"use strict";var l4=Gr(),u4=ni(),ZC=K(),_4=ln(),U_e=fd(),d4=require("clone"),cS=require("alasql"),f4=_d(),eD=require("util"),E4=eD.promisify(u4.getTableSchema),h4=eD.promisify(l4.search),m4=U(),aS=z();f4(cS);tD.exports={update:S4};var p4="There was a problem performing this update. Please check the logs and try again.";async function S4({statement:e,hdb_user:t}){let r=await E4(e.table.databaseid,e.table.tableid),n=T4(e.columns);aS.backtickASTSchemaItems(e);let{table:s,where:i}=e,o=d4(s),c=aS.isEmpty(i)?"":` WHERE ${i.toString()}`,l=`SELECT ${r.hash_attribute} FROM ${s.toString()} ${c}`,_=cS.parse(l).statements[0],u=await h4(_),d=g4(n,u);return R4(o,d,t)}a(S4,"update");function T4(e){try{let t={};return e.forEach(r=>{"value"in r.expression?t[r.column.columnid]=r.expression.value??null:t[r.column.columnid]=cS.compile(`SELECT ${r.expression.toString()} AS [${m4.FUNC_VAL}] FROM ?`)}),t}catch(t){throw ZC.error(t),new Error(p4)}}a(T4,"createUpdateRecord");function g4(e,t){return aS.isEmptyOrZeroLength(t)?[]:t.map(r=>Object.assign(r,e))}a(g4,"buildUpdateRecords");async function R4(e,t,r){let n={operation:"update",schema:e.databaseid_orig,table:e.tableid_orig,records:t,hdb_user:r},s=await _4.update(n);try{delete s.new_attributes,delete s.txn_time}catch(i){ZC.error(`Error delete new_attributes from update response: ${i}`)}return s}a(R4,"updateRecords")});var sD=g((G_e,nD)=>{var A4=require("alasql"),O4=Gr(),b4=K(),y4=wn(),uS=require("util"),lS=z(),N4=U(),I4=ni(),H_e=fd(),x_e=ln(),w4="record",C4="successfully deleted",D4=uS.callbackify(U4),L4=uS.promisify(O4.search),M4=uS.promisify(I4.getTableSchema);nD.exports={convertDelete:D4};function P4(e){return`${e.deleted_hashes.length} ${w4}${e.deleted_hashes.length===1?"":"s"} ${C4}`}a(P4,"generateReturnMessage");async function U4({statement:e,hdb_user:t}){let r=await M4(e.table.databaseid,e.table.tableid);lS.backtickASTSchemaItems(e);let{table:n,where:s}=e,i=lS.isEmpty(s)?"":` WHERE ${s.toString()}`,o=`SELECT ${r.hash_attribute} FROM ${n.toString()} ${i}`,c=A4.parse(o).statements[0],l={operation:N4.OPERATIONS_ENUM.DELETE,schema:n.databaseid_orig,table:n.tableid_orig,hdb_user:t};try{l.records=await L4(c);let _=await y4.deleteRecords(l);return lS.isEmptyOrZeroLength(_.message)&&(_.message=P4(_)),delete _.txn_time,_}catch(_){throw b4.error(_),_.hdb_code?_.message:_}}a(U4,"convertDelete")});var lD=g((q_e,cD)=>{"use strict";var v4=ri(),{hdb_errors:iD}=ne(),{getDatabases:oD}=(Ae(),ie(ke));cD.exports={checkSchemaExists:aD,checkSchemaTableExists:B4,schema_describe:v4};async function aD(e){if(!oD()[e])return iD.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}a(aD,"checkSchemaExists");async function B4(e,t){let r=await aD(e);if(r)return r;if(!oD()[e][t])return iD.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(B4,"checkSchemaTableExists")});var pd=g(($_e,fD)=>{"use strict";var oa=A_(),aa=lD(),H4=K(),x4=require("uuid").v4,V_e=require("clone"),hd=As(),ca=U(),G4=require("util"),ui=wn(),{handleHDBError:Sr,hdb_errors:F4}=ne(),{HDB_ERROR_MSGS:Ed,HTTP_STATUS_CODES:Tr}=F4,{SchemaEventMsg:md}=Ln(),uD=wt(),{getDatabases:q4}=(Ae(),ie(ke)),{transformReq:la}=z();fD.exports={createSchema:k4,createSchemaStructure:_D,createTable:V4,createTableStructure:dD,createAttribute:Q4,dropSchema:$4,dropTable:Y4,dropAttribute:K4,getBackup:z4};async function k4(e){let t=await _D(e);return hd.signalSchemaChange(new md(process.pid,e.operation,e.schema)),t}a(k4,"createSchema");async function _D(e){let t=oa.schema_object(e);if(t)throw Sr(t,t.message,Tr.BAD_REQUEST,void 0,void 0,!0);if(la(e),!await aa.checkSchemaExists(e.schema))throw Sr(new Error,Ed.SCHEMA_EXISTS_ERR(e.schema),Tr.BAD_REQUEST,ca.LOG_LEVELS.ERROR,Ed.SCHEMA_EXISTS_ERR(e.schema),!0);return await ui.createSchema(e),`database '${e.schema}' successfully created`}a(_D,"createSchemaStructure");async function V4(e){return la(e),e.hash_attribute=e.primary_key??e.hash_attribute,await dD(e)}a(V4,"createTable");async function dD(e){let t=oa.create_table_object(e);if(t)throw Sr(t,t.message,Tr.BAD_REQUEST,void 0,void 0,!0);if(oa.validateTableResidence(e.residence),!await aa.checkSchemaTableExists(e.schema,e.table))throw Sr(new Error,Ed.TABLE_EXISTS_ERR(e.schema,e.table),Tr.BAD_REQUEST,ca.LOG_LEVELS.ERROR,Ed.TABLE_EXISTS_ERR(e.schema,e.table),!0);let n={name:e.table,schema:e.schema,id:x4(),hash_attribute:e.hash_attribute};try{if(e.residence)if(global.clustering_on)n.residence=e.residence,await ui.createTable(n,e);else throw Sr(new Error,"Clustering does not appear to be enabled. Cannot insert table with property 'residence'.",Tr.BAD_REQUEST);else await ui.createTable(n,e);return`table '${e.schema}.${e.table}' successfully created.`}catch(s){throw s}}a(dD,"createTableStructure");async function $4(e){let t=!e.schema&&!e.database?new Error("database is required"):void 0,r=oa.schema_object(e),n=t??r;if(n)throw Sr(n,n.message,Tr.BAD_REQUEST,void 0,void 0,!0);la(e);let s=await aa.checkSchemaExists(e.schema);if(s)throw Sr(new Error,s,Tr.NOT_FOUND,ca.LOG_LEVELS.ERROR,s,!0);let i=await aa.schema_describe.describeSchema({schema:e.schema}),o=Object.keys(global.hdb_schema[e.schema]);return await ui.dropSchema(e),hd.signalSchemaChange(new md(process.pid,e.operation,e.schema)),await uD.purgeSchemaTableStreams(e.schema,o),`successfully deleted '${e.schema}'`}a($4,"dropSchema");async function Y4(e){let t=oa.table_object(e);if(t)throw Sr(t,t.message,Tr.BAD_REQUEST,void 0,void 0,!0);la(e);let r=await aa.checkSchemaTableExists(e.schema,e.table);if(r)throw Sr(new Error,r,Tr.NOT_FOUND,ca.LOG_LEVELS.ERROR,r,!0);return await ui.dropTable(e),await uD.purgeTableStream(e.schema,e.table),`successfully deleted table '${e.schema}.${e.table}'`}a(Y4,"dropTable");async function K4(e){let t=oa.attribute_object(e);if(t)throw Sr(t,t.message,Tr.BAD_REQUEST,void 0,void 0,!0);la(e);let r=await aa.checkSchemaTableExists(e.schema,e.table);if(r)throw Sr(new Error,r,Tr.NOT_FOUND,ca.LOG_LEVELS.ERROR,r,!0);if(e.attribute===global.hdb_schema[e.schema][e.table].hash_attribute)throw Sr(new Error,"You cannot drop a hash attribute",Tr.BAD_REQUEST,void 0,void 0,!0);if(ca.TIME_STAMP_NAMES.indexOf(e.attribute)>=0)throw Sr(new Error,`cannot drop internal timestamp attribute: ${e.attribute}`,Tr.BAD_REQUEST,void 0,void 0,!0);try{return await ui.dropAttribute(e),W4(e),hd.signalSchemaChange(new md(process.pid,e.operation,e.schema,e.table,e.attribute)),`successfully deleted attribute '${e.attribute}'`}catch(n){throw H4.error(`Got an error deleting attribute ${G4.inspect(e)}.`),n}}a(K4,"dropAttribute");function W4(e){let t=Object.values(global.hdb_schema[e.schema][e.table].attributes);for(let r=0;r<t.length;r++)t[r].attribute===e.attribute&&global.hdb_schema[e.schema][e.table].attributes.splice(r,1)}a(W4,"dropAttributeFromGlobal");async function Q4(e){la(e);let t=q4()[e.schema][e.table].attributes;for(let{name:r}of t)if(r===e.attribute)throw Sr(new Error,`attribute '${e.attribute}' already exists in ${e.schema}.${e.table}`,Tr.BAD_REQUEST,void 0,void 0,!0);return await ui.createAttribute(e),hd.signalSchemaChange(new md(process.pid,e.operation,e.schema,e.table,e.attribute)),`attribute '${e.schema}.${e.table}.${e.attribute}' successfully created.`}a(Q4,"createAttribute");function z4(e){return ui.getBackup(e)}a(z4,"getBackup")});var hD=g((K_e,ED)=>{"use strict";var{OPERATIONS_ENUM:J4}=U(),_S=class{static{a(this,"ReadAuditLogObject")}constructor(t,r,n=void 0,s=void 0){this.operation=J4.READ_AUDIT_LOG,this.schema=t,this.table=r,this.search_type=n,this.search_values=s}};ED.exports=_S});var dS=g((z_e,gD)=>{"use strict";var X4=wn(),Q_e=hD(),Sd=z(),Td=U(),j4=te(),{handleHDBError:mD,hdb_errors:Z4}=ne(),{HDB_ERROR_MSGS:pD,HTTP_STATUS_CODES:SD}=Z4,e3=Object.values(Td.READ_AUDIT_LOG_SEARCH_TYPES_ENUM),TD="To use this operation audit log must be enabled in harperdb-config.yaml";gD.exports=t3;async function t3(e){if(Sd.isEmpty(e.schema))throw new Error(pD.SCHEMA_REQUIRED_ERR);if(Sd.isEmpty(e.table))throw new Error(pD.TABLE_REQUIRED_ERR);if(!j4.get(Td.CONFIG_PARAMS.LOGGING_AUDITLOG))throw mD(new Error,TD,SD.BAD_REQUEST,Td.LOG_LEVELS.ERROR,TD,!0);let t=Sd.checkSchemaTableExist(e.schema,e.table);if(t)throw mD(new Error,t,SD.NOT_FOUND,Td.LOG_LEVELS.ERROR,t,!0);if(!Sd.isEmpty(e.search_type)&&e3.indexOf(e.search_type)<0)throw new Error(`Invalid search_type '${e.search_type}'`);return await X4.readAuditLog(e)}a(t3,"readAuditLog")});var AD=g((X_e,RD)=>{"use strict";var{OPERATIONS_ENUM:r3}=U(),fS=class{static{a(this,"GetBackupObject")}constructor(t,r,n=void 0,s=void 0){this.operation=r3.GET_BACKUP,this.schema=t,this.table=r}};RD.exports=fS});var yD=g((tde,bD)=>{"use strict";var n3=wn(),Z_e=AD(),ES=z(),s3=U(),ede=te(),{handleHDBError:i3,hdb_errors:o3}=ne(),{HDB_ERROR_MSGS:OD,HTTP_STATUS_CODES:a3}=o3;bD.exports=c3;async function c3(e){if(ES.isEmpty(e.schema))throw new Error(OD.SCHEMA_REQUIRED_ERR);if(ES.isEmpty(e.table))throw new Error(OD.TABLE_REQUIRED_ERR);let t=ES.checkSchemaTableExist(e.schema,e.table);if(t)throw i3(new Error,t,a3.NOT_FOUND,s3.LOG_LEVELS.ERROR,t,!0);return await n3.getBackup(read_audit_log_object)}a(c3,"getBackup")});var LD=g((nde,DD)=>{var _i=require("validate.js"),ID=at(),ua=U(),{handleHDBError:l3,hdb_errors:u3}=ne(),{HDB_ERROR_MSGS:ht,HTTP_STATUS_CODES:_3}=u3,hS=a(()=>({role:{presence:!0,format:"[\\w\\-\\_]+"},id:{presence:!0,format:"[\\w\\-\\_]+"},permission:{presence:!0}}),"constraintsTemplate"),d3={STRUCTURE_USER:"structure_user"},ND=Object.values(ua.ROLE_TYPES_ENUM),f3="attribute_permissions",E3="attribute_name",{PERMS_CRUD_ENUM:_a}=ua,h3=[f3,...Object.values(_a)],wD=[_a.READ,_a.INSERT,_a.UPDATE],m3=[E3,...wD];function p3(e){let t=hS();return t.role.presence=!0,t.id.presence=!1,t.permission.presence=!0,CD(e,t)}a(p3,"addRoleValidation");function S3(e){let t=hS();return t.role.presence=!1,t.id.presence=!0,t.permission.presence=!0,CD(e,t)}a(S3,"alterRoleValidation");function T3(e){let t=hS();return t.role.presence=!1,t.id.presence=!0,t.permission.presence=!1,ID.validateObject(e,t)}a(T3,"dropRoleValidation");var g3=["operation","role","id","permission","hdb_user","hdb_auth_header"];function CD(e,t){let r={main_permissions:[],schema_permissions:{}},n=Object.keys(e),s=[];for(let o=0,c=n.length;o<c;o++)g3.includes(n[o])||s.push(n[o]);s.length>0&&Rt(ht.INVALID_ROLE_JSON_KEYS(s),r);let i=ID.validateObject(e,t);if(i&&i.message.split(",").forEach(o=>{Rt(o,r)}),e.permission){let o=R3(e);o&&Rt(o,r),ND.forEach(c=>{e.permission[c]&&!_i.isBoolean(e.permission[c])&&Rt(ht.SU_CU_ROLE_BOOLEAN_ERROR(c),r)})}for(let o in e.permission)if(ND.indexOf(o)<0){if(o===d3.STRUCTURE_USER){let l=e.permission[o];if(typeof l=="boolean")continue;if(Array.isArray(l)){for(let _=0,u=l.length;_<u;_++){let d=l[_];global.hdb_schema[d]||Rt(ht.SCHEMA_NOT_FOUND(d),r)}continue}Rt(ht.STRUCTURE_USER_ROLE_TYPE_ERROR(o),r);continue}let c=e.permission[o];if(!o||!global.hdb_schema[o]){Rt(ht.SCHEMA_NOT_FOUND(o),r);continue}if(c.tables)for(let l in c.tables){let _=c.tables[l];if(!l||!global.hdb_schema[o][l]){Rt(ht.TABLE_NOT_FOUND(o,l),r);continue}if(Object.keys(_).forEach(u=>{h3.includes(u)||Rt(ht.INVALID_PERM_KEY(u),r,o,l)}),Object.values(_a).forEach(u=>{_i.isDefined(_[u])?_i.isBoolean(_[u])||Rt(ht.TABLE_PERM_NOT_BOOLEAN(u),r,o,l):Rt(ht.TABLE_PERM_MISSING(u),r,o,l)}),_i.isDefined(_.attribute_permissions)){if(!_i.isArray(_.attribute_permissions)){Rt(ht.ATTR_PERMS_NOT_ARRAY,r,o,l);continue}}else{Rt(ht.ATTR_PERMS_ARRAY_MISSING,r,o,l);continue}if(_.attribute_permissions){let u=global.hdb_schema[o][l].attributes.map(({attribute:E})=>E),d={read:!1,insert:!1,update:!1};for(let E in _.attribute_permissions){let f=_.attribute_permissions[E];if(Object.keys(f).forEach(p=>{!m3.includes(p)&&p!==_a.DELETE&&Rt(ht.INVALID_ATTR_PERM_KEY(p),r,o,l)}),!_i.isDefined(f.attribute_name)){Rt(ht.ATTR_PERM_MISSING_NAME,r,o,l);continue}let h=f.attribute_name;if(!u.includes(h)){Rt(ht.INVALID_ATTRIBUTE_IN_PERMS(h),r,o,l);continue}wD.forEach(p=>{_i.isDefined(f[p])?_i.isBoolean(f[p])||Rt(ht.ATTR_PERM_NOT_BOOLEAN(p,h),r,o,l):Rt(ht.ATTR_PERM_MISSING(p,h),r,o,l)}),!d.read&&f.read===!0&&(d.read=!0),!d.insert&&f.insert===!0&&(d.insert=!0),!d.update&&f.update===!0&&(d.update=!0)}if(_.read===!1&&d.read===!0||_.insert===!1&&d.insert===!0||_.update===!1&&d.update===!0){let E=`${o}.${l}`;Rt(ht.MISMATCHED_TABLE_ATTR_PERMS(E),r,o,l)}}}}return A3(r)}a(CD,"customValidate");DD.exports={addRoleValidation:p3,alterRoleValidation:S3,dropRoleValidation:T3};function R3(e){let{operation:t,permission:r}=e;if(t===ua.OPERATIONS_ENUM.ADD_ROLE||t===ua.OPERATIONS_ENUM.ALTER_ROLE){let n=r.super_user===!0,s=r.cluster_user===!0;if(Object.keys(r).length>1&&(n||s)){if(s&&n)return ht.SU_CU_ROLE_COMBINED_ERROR;{let o=r.super_user?ua.ROLE_TYPES_ENUM.SUPER_USER:ua.ROLE_TYPES_ENUM.CLUSTER_USER;return ht.SU_CU_ROLE_NO_PERMS_ALLOWED(o)}}}return null}a(R3,"validateNoSUPerms");function A3(e){let{main_permissions:t,schema_permissions:r}=e;if(t.length>0||Object.keys(r).length>0){let n={error:ht.ROLE_PERMS_ERROR,...e};return l3(new Error,n,_3.BAD_REQUEST)}else return null}a(A3,"generateRolePermResponse");function Rt(e,t,r,n){if(!r)t.main_permissions.push(e);else{let s=n?r+"_"+n:r;t.schema_permissions[s]?t.schema_permissions[s].push(e):t.schema_permissions[s]=[e]}}a(Rt,"addPermError")});var RS=g((ide,vD)=>{"use strict";var MD=ln(),PD=Gr(),O3=Yi(),pS=LD(),SS=As(),b3=require("uuid").v4,y3=require("util"),gd=U(),N3=z(),TS=PD.searchByValue,I3=PD.searchByHash,w3=y3.promisify(O3.delete),C3=es(),D3=ra(),{hdb_errors:L3,handleHDBError:no}=ne(),{HDB_ERROR_MSGS:UD,HTTP_STATUS_CODES:al}=L3,{UserEventMsg:gS}=Ln();vD.exports={addRole:M3,alterRole:P3,dropRole:U3,listRoles:v3};function mS(e){try{e.hdb_auth_header&&delete e.hdb_auth_header,e.HDB_INTERNAL_PATH&&delete e.HDB_INTERNAL_PATH,e.operation&&delete e.operation,e.hdb_user&&delete e.hdb_user}catch{}return e}a(mS,"scrubRoleDetails");async function M3(e){let t=pS.addRoleValidation(e);if(t)throw t;e=mS(e);let r={schema:"system",table:"hdb_role",search_attribute:"role",search_value:e.role,hash_attribute:"id",get_attributes:["*"]},n;try{n=Array.from(await TS(r)||[])}catch(i){throw no(i)}if(n&&n.length>0)throw no(new Error,UD.ROLE_ALREADY_EXISTS(e.role),al.CONFLICT,void 0,void 0,!0);e.id||(e.id=b3());let s={operation:"insert",schema:"system",table:"hdb_role",hash_attribute:"id",records:[e]};return await MD.insert(s),SS.signalUserChange(new gS(process.pid)),e=mS(e),e}a(M3,"addRole");async function P3(e){let t=pS.alterRoleValidation(e);if(t)throw t;e=mS(e);let r={operation:"update",schema:"system",table:"hdb_role",records:[e]},n;try{n=await MD.update(r)}catch(s){throw no(s)}if(n&&n?.message==="updated 0 of 1 records")throw no(new Error,"Invalid role id",al.BAD_REQUEST,void 0,void 0,!0);return await SS.signalUserChange(new gS(process.pid)),e}a(P3,"alterRole");async function U3(e){let t=pS.dropRoleValidation(e);if(t)throw no(new Error,t,al.BAD_REQUEST,void 0,void 0,!0);let r=new D3(gd.SYSTEM_SCHEMA_NAME,gd.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME,[e.id],["role"]),n=Array.from(await I3(r));if(n.length===0)throw no(new Error,UD.ROLE_NOT_FOUND,al.NOT_FOUND,void 0,void 0,!0);let s=new C3(gd.SYSTEM_SCHEMA_NAME,gd.SYSTEM_TABLE_NAMES.USER_TABLE_NAME,"role",e.id,void 0,["username","active"]),i=Array.from(await TS(s)),o=!1;if(N3.isEmptyOrZeroLength(i)===!1){for(let l=0;l<i.length;l++)if(i[l].active===!0){o=!0;break}}if(o===!0)throw no(new Error,`Cannot drop role ${n[0].role} as it has active user(s) tied to this role`,al.CONFLICT,void 0,void 0,!0);let c={table:"hdb_role",schema:"system",hash_values:[e.id]};return await w3(c),SS.signalUserChange(new gS(process.pid)),`${n[0].role} successfully deleted`}a(U3,"dropRole");async function v3(){return TS({table:"hdb_role",schema:"system",hash_attribute:"id",search_attribute:"id",search_value:"*",get_attributes:["*"]})}a(v3,"listRoles")});var GD=g((ade,xD)=>{"use strict";var B3=te(),di=require("joi"),H3=at(),BD=require("moment"),x3=require("fs-extra"),AS=require("path"),G3=require("lodash"),cl=U(),{LOG_LEVELS:so}=U(),F3="YYYY-MM-DD hh:mm:ss",q3=AS.resolve(__dirname,"../logs");xD.exports=function(e){return H3.validateBySchema(e,k3)};var k3=di.object({from:di.custom(HD),until:di.custom(HD),level:di.valid(so.NOTIFY,so.FATAL,so.ERROR,so.WARN,so.INFO,so.DEBUG,so.TRACE),order:di.valid("asc","desc"),limit:di.number().min(1),start:di.number().min(0),log_name:di.custom(V3)});function HD(e,t){if(BD(e,BD.ISO_8601).format(F3)==="Invalid date")return t.message(`'${t.state.path[0]}' date '${e}' is invalid.`)}a(HD,"validateDatetime");function V3(e,t){if(G3.invert(cl.LOG_NAMES)[e]===void 0)return t.message(`'log_name' '${e}' is invalid.`);let n=B3.get(cl.HDB_SETTINGS_NAMES.LOG_PATH_KEY),s=e===void 0?cl.LOG_NAMES.HDB:e,i=s===cl.LOG_NAMES.INSTALL?AS.join(q3,cl.LOG_NAMES.INSTALL):AS.join(n,s);return x3.existsSync(i)?null:t.message(`'log_name' '${e}' does not exist.`)}a(V3,"validateReadLogPath")});var bS=g((lde,qD)=>{"use strict";var Rd=U(),$3=K(),Y3=te(),K3=GD(),OS=require("path"),FD=require("fs-extra"),{once:W3}=require("events"),{handleHDBError:Q3,hdb_errors:z3}=ne(),{PACKAGE_ROOT:J3}=U(),X3=OS.join(J3,"logs"),j3=1e3,Z3=200;qD.exports=eX;async function eX(e){let t=K3(e);if(t)throw Q3(t,t.message,z3.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0);let r=Y3.get(Rd.HDB_SETTINGS_NAMES.LOG_PATH_KEY),n=e.log_name===void 0?Rd.LOG_NAMES.HDB:e.log_name,s=n===Rd.LOG_NAMES.INSTALL?OS.join(X3,Rd.LOG_NAMES.INSTALL):OS.join(r,n),i=e.level!==void 0,o=i?e.level:void 0,c=e.from!==void 0,l=c?new Date(e.from):void 0,_=e.until!==void 0,u=_?new Date(e.until):void 0,d=e.limit===void 0?j3:e.limit,E=e.order===void 0?void 0:e.order,f=e.start===void 0?0:e.start,h=f+d,p=0;E==="desc"&&!l&&!u&&(p=Math.max(FD.statSync(s).size-(h+5)*Z3,0));let S=FD.createReadStream(s,{start:p});S.on("error",v=>{$3.error(v)});let T=0,R=[],b="",C;S.on("data",v=>{let q=/(?:^|\n)(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:[\d\.]+Z) \[(.+?)]: /g;v=b+v;let M=0,Q;for(;(Q=q.exec(v))&&!S.destroyed;){C&&(C.message=v.slice(M,Q.index),H(C));let[J,X,ae]=Q,ce=ae.split("] ["),ge=ce[0],Ge=ce[1];ce.splice(0,2),C={timestamp:X,thread:ge,level:Ge,tags:ce,message:""},M=Q.index+J.length}b=v.slice(M)}),S.on("end",v=>{S.destroyed||C&&(C.message=b.trim(),H(C))}),S.resume();function H(v){let q,M,Q;switch(!0){case(i&&c&&_):q=new Date(v.timestamp),M=new Date(l),Q=new Date(u),v.level===o&&q>=M&&q<=Q&&T<f?T++:v.level===o&&q>=M&&q<=Q&&(fi(v,E,R),T++,T===h&&S.destroy());break;case(i&&c):q=new Date(v.timestamp),M=new Date(l),v.level===o&&q>=M&&T<f?T++:v.level===o&&q>=M&&(fi(v,E,R),T++,T===h&&S.destroy());break;case(i&&_):q=new Date(v.timestamp),Q=new Date(u),v.level===o&&q<=Q&&T<f?T++:v.level===o&&q<=Q&&(fi(v,E,R),T++,T===h&&S.destroy());break;case(c&&_):q=new Date(v.timestamp),M=new Date(l),Q=new Date(u),q>=M&&q<=Q&&T<f?T++:q>=M&&q<=Q&&(fi(v,E,R),T++,T===h&&S.destroy());break;case i:v.level===o&&T<f?T++:v.level===o&&(fi(v,E,R),T++,T===h&&S.destroy());break;case c:q=new Date(v.timestamp),M=new Date(l),q>=M&&T<f?T++:q>=M&&T>=f&&(fi(v,E,R),T++,T===h&&S.destroy());break;case _:q=new Date(v.timestamp),Q=new Date(u),q<=Q&&T<f?T++:q<=Q&&T>=f&&(fi(v,E,R),T++,T===h&&S.destroy());break;default:T<f?T++:(fi(v,E,R),T++,T===h&&S.destroy())}}return a(H,"onLogMessage"),await W3(S,"close"),R}a(eX,"readLog");function fi(e,t,r){t==="desc"?tX(e,r):t==="asc"?rX(e,r):r.push(e)}a(fi,"pushLineToResult");function tX(e,t){let r=new Date(e.timestamp),n=0,s=t.length;for(;n<s;){let i=n+s>>>1;new Date(t[i].timestamp)>r?n=i+1:s=i}t.splice(n,0,e)}a(tX,"insertDescending");function rX(e,t){let r=new Date(e.timestamp),n=0,s=t.length;for(;n<s;){let i=n+s>>>1;new Date(t[i].timestamp)<r?n=i+1:s=i}t.splice(n,0,e)}a(rX,"insertAscending")});var Ad=g((Ede,YD)=>{"use strict";var yS=require("joi"),{string:ll,boolean:kD,date:nX}=yS.types(),sX=at(),{validateSchemaExists:_de,validateTableExists:dde,validateSchemaName:fde}=zn(),iX=U(),oX=ct(),VD=te();VD.initSync();var aX=ll.invalid(VD.get(iX.CONFIG_PARAMS.CLUSTERING_NODENAME)).pattern(oX.NATS_TERM_CONSTRAINTS_RX).messages({"string.pattern.base":"{:#label} invalid, must not contain ., * or >","any.invalid":"'node_name' cannot be this nodes name"}).empty(null).required(),$D={operation:ll.valid("add_node","update_node","set_node_replication"),node_name:aX,subscriptions:yS.array().items({table:ll.optional(),schema:ll.optional(),database:ll.optional(),subscribe:kD.required(),publish:kD.required().custom(lX),start_time:nX.iso()}).min(1).required()};function cX(e){return sX.validateBySchema(e,yS.object($D))}a(cX,"addUpdateNodeValidator");function lX(e,t){if(t.state.ancestors[2].operation==="add_node"&&e===!1&&t.state.ancestors[0].subscribe===!1)return t.message(`'subscriptions[${t.state.path[1]}]' subscribe and/or publish must be set to true when adding a node`)}a(lX,"checkForFalsy");YD.exports={addUpdateNodeValidator:cX,validation_schema:$D}});var WD=g((mde,KD)=>{var uX=at(),_X={user:{presence:!0},schema:{presence:!0},table:{presence:!0},operation:{presence:!0}};KD.exports=function(e){return uX.validateObject(e,_X)}});var IS=g((pde,QD)=>{"use strict";var dX=U().OPERATIONS_ENUM,NS=class{static{a(this,"UpdateObject")}constructor(t,r,n,s=void 0){this.operation=dX.UPDATE,this.schema=t,this.table=r,this.records=n,this.__origin=s}};QD.exports=NS});var JD=g((Tde,zD)=>{"use strict";var fX={OPERATION:"operation",REFRESH:"refresh"},wS=class{static{a(this,"JWTTokens")}constructor(t,r){this.operation_token=t,this.refresh_token=r}},CS=class{static{a(this,"JWTRSAKeys")}constructor(t,r,n){this.public_key=t,this.private_key=r,this.passphrase=n}};zD.exports={JWTTokens:wS,TOKEN_TYPE_ENUM:fX,JWTRSAKeys:CS}});var dl=g((Rde,eL)=>{"use strict";var _l=require("jsonwebtoken"),DS=require("fs-extra"),LS=z(),_n=U(),{handleHDBError:gr,hdb_errors:EX}=ne(),{HTTP_STATUS_CODES:Rr,AUTHENTICATION_ERROR_MSGS:Ar}=EX,ul=K(),XD=H_(),US=un(),hX=ln().update,mX=IS(),pX=As(),{UserEventMsg:SX}=Ln(),Ei=te();Ei.initSync();var MS=require("path"),{JWTTokens:TX,JWTRSAKeys:gX,TOKEN_TYPE_ENUM:Od}=JD(),RX=Ei.get(_n.HDB_SETTINGS_NAMES.OPERATION_TOKEN_TIMEOUT_KEY)?Ei.get(_n.HDB_SETTINGS_NAMES.OPERATION_TOKEN_TIMEOUT_KEY):"1d",AX=Ei.get(_n.HDB_SETTINGS_NAMES.REFRESH_TOKEN_TIMEOUT_KEY)?Ei.get(_n.HDB_SETTINGS_NAMES.REFRESH_TOKEN_TIMEOUT_KEY):"30d",bd="RS256",PS;eL.exports={createTokens:OX,validateOperationToken:yX,refreshOperationToken:bX,validateRefreshToken:ZD};async function OX(e){if(LS.isEmpty(e)||typeof e!="object")throw gr(new Error,Ar.INVALID_AUTH_OBJECT,Rr.BAD_REQUEST,void 0,void 0,!0);if(LS.isEmpty(e.username))throw gr(new Error,Ar.USERNAME_REQUIRED,Rr.BAD_REQUEST,void 0,void 0,!0);if(LS.isEmpty(e.password))throw gr(new Error,Ar.PASSWORD_REQUIRED,Rr.BAD_REQUEST,void 0,void 0,!0);let t;try{if(t=await US.findAndValidateUser(e.username,e.password),!t)throw gr(new Error,Ar.INVALID_CREDENTIALS,Rr.UNAUTHORIZED,void 0,void 0,!0)}catch(E){throw ul.error(E),gr(new Error,Ar.INVALID_CREDENTIALS,Rr.UNAUTHORIZED,void 0,void 0,!0)}let r=await yd(),n=!1,s=!1;t.role&&t.role.permission&&(n=t.role.permission.super_user===!0,s=t.role.permission.cluster_user===!0);let i={username:e.username,super_user:n,cluster_user:s},o=await jD(i,r.private_key,r.passphrase),c=await _l.sign(i,{key:r.private_key,passphrase:r.passphrase},{expiresIn:AX,algorithm:bd,subject:Od.REFRESH}),l=XD.hash(c),_=new mX(_n.SYSTEM_SCHEMA_NAME,_n.SYSTEM_TABLE_NAMES.USER_TABLE_NAME,[{username:e.username,refresh_token:l}]),u,d;try{u=await hX(_)}catch(E){ul.error(E),d=E}if(d!==void 0||u.skipped_hashes.length>0)throw gr(new Error,Ar.REFRESH_TOKEN_SAVE_FAILED,Rr.INTERNAL_SERVER_ERROR);return pX.signalUserChange(new SX(process.pid)),new TX(o,c)}a(OX,"createTokens");async function jD(e,t,r){return await _l.sign(e,{key:t,passphrase:r},{expiresIn:RX,algorithm:bd,subject:Od.OPERATION})}a(jD,"signOperationToken");async function yd(){if(PS===void 0)try{let e=MS.join(Ei.getHdbBasePath(),_n.LICENSE_KEY_DIR_NAME,_n.JWT_ENUM.JWT_PASSPHRASE_NAME),t=MS.join(Ei.getHdbBasePath(),_n.LICENSE_KEY_DIR_NAME,_n.JWT_ENUM.JWT_PRIVATE_KEY_NAME),r=MS.join(Ei.getHdbBasePath(),_n.LICENSE_KEY_DIR_NAME,_n.JWT_ENUM.JWT_PUBLIC_KEY_NAME),n=(await DS.readFile(e)).toString(),s=(await DS.readFile(t)).toString(),i=(await DS.readFile(r)).toString();PS=new gX(i,s,n)}catch(e){throw ul.error(e),gr(new Error,Ar.NO_ENCRYPTION_KEYS,Rr.INTERNAL_SERVER_ERROR)}return PS}a(yd,"getJWTRSAKeys");async function bX(e){if(!e)throw gr(new Error,Ar.INVALID_BODY,Rr.BAD_REQUEST,void 0,void 0,!0);if(!e.refresh_token)throw gr(new Error,Ar.REFRESH_TOKEN_REQUIRED,Rr.BAD_REQUEST,void 0,void 0,!0);await ZD(e.refresh_token);let t=await yd(),r=await _l.decode(e.refresh_token);return{operation_token:await jD({username:r.username,super_user:r.super_user,cluster_user:r.cluster_user},t.private_key,t.passphrase)}}a(bX,"refreshOperationToken");async function yX(e){try{let t=await yd(),r=await _l.verify(e,t.public_key,{algorithms:bd,subject:Od.OPERATION});return await US.findAndValidateUser(r.username,void 0,!1)}catch(t){throw ul.warn(t),t.name&&t.name==="TokenExpiredError"?gr(new Error,Ar.TOKEN_EXPIRED,Rr.FORBIDDEN):gr(new Error,Ar.INVALID_TOKEN,Rr.UNAUTHORIZED)}}a(yX,"validateOperationToken");async function ZD(e){let t;try{let r=await yd(),n=await _l.verify(e,r.public_key,{algorithms:bd,subject:Od.REFRESH});t=await US.findAndValidateUser(n.username,void 0,!1)}catch(r){throw ul.warn(r),r.name&&r.name==="TokenExpiredError"?gr(new Error,Ar.TOKEN_EXPIRED,Rr.FORBIDDEN):gr(new Error,Ar.INVALID_TOKEN,Rr.UNAUTHORIZED)}if(!XD.validate(t.refresh_token,e))throw gr(new Error,Ar.INVALID_TOKEN,Rr.UNAUTHORIZED);return t}a(ZD,"validateRefreshToken")});var vS=g((bde,nL)=>{"use strict";var NX=WD(),da=require("passport"),IX=require("passport-local").Strategy,wX=require("passport-http").BasicStrategy,CX=require("util"),DX=un(),rL=CX.callbackify(DX.findAndValidateUser),Ode=Ur(),LX=U(),tL=dl();da.use(new IX(function(e,t,r){rL(e,t,r)}));da.use(new wX(function(e,t,r){rL(e,t,r)}));da.serializeUser(function(e,t){t(null,e)});da.deserializeUser(function(e,t){t(null,e)});function MX(e,t,r){if(e.raw?.user!==void 0)return r(null,e.raw.user);let n,s;if(e.headers?.authorization){let o=e.headers.authorization.split(" ");n=o[0],s=o[1]}function i(o,c){return o?r(o):c?r(null,c):r("Must login")}switch(a(i,"handleResponse"),n){case"Basic":da.authenticate("basic",{session:!1},(o,c)=>{i(o,c)})(e,t,r);break;case"Bearer":e.body?.operation&&e.body.operation===LX.OPERATIONS_ENUM.REFRESH_OPERATION_TOKEN?tL.validateRefreshToken(s).then(o=>{e.body.refresh_token=s,r(null,o)}).catch(o=>{r(o)}):tL.validateOperationToken(s).then(o=>{r(null,o)}).catch(o=>{r(o)});break;default:da.authenticate("local",{session:!1},function(o,c){i(o,c)})(e,t,r);break}}a(MX,"authorize");function PX(e,t){let r=NX(e);if(r){t(r);return}let n={authorized:!0,messages:[]},s=e.user.role;if(!s?.permission)return t("Invalid role");let i=JSON.parse(s.permission);if(i.super_user)return t(null,n);if(!i[e.schema])return n.authorized=!1,n.messages.push(`Not authorized to access ${e.schema} schema`),t(null,n);if(!i[e.schema].tables[e.table])return n.authorized=!1,n.messages.push(`Not authorized to access ${e.table} table`),t(null,n);if(!i[e.schema].tables[e.table][e.operation])return n.authorized=!1,n.messages.push(`Not authorized to access ${e.operation} on ${e.table} table`),t(null,n);if(i[e.schema].tables[e.table].attribute_permissions&&!e.attributes)return n.authorized=!1,n.messages.push(`${e.schema}.${e.table} has attribute permissions. Missing attributes to validate`),t(null,n);if(i[e.schema].tables[e.table].attribute_permissions&&e.attributes){let o=i[e.schema].tables[e.table].attribute_permissions;for(let c in o)e.attributes.indexOf(o[c].attribute_name)>-1&&!o[c][e.operation]&&(n.authorized=!1,n.messages.push(`Not authorized to ${e.operation} ${o[c].attribute_name} `))}return t(null,n)}a(PX,"checkPermissions");nL.exports={authorize:MX,checkPermissions:PX}});var fa=g((Nde,sL)=>{"use strict";var BS=class{static{a(this,"Node")}constructor(t,r,n){this.name=t,this.subscriptions=r,this.system_info=n}},HS=class{static{a(this,"NodeSubscription")}constructor(t,r,n,s){this.schema=t,this.table=r,this.publish=n,this.subscribe=s}};sL.exports={Node:BS,NodeSubscription:HS}});var oL=g((wde,iL)=>{"use strict";var UX=U().OPERATIONS_ENUM,xS=class{static{a(this,"UpsertObject")}constructor(t,r,n,s=void 0){this.operation=UX.UPSERT,this.schema=t,this.table=r,this.records=n,this.__origin=s}};iL.exports=xS});var fl=g((Dde,aL)=>{"use strict";var GS=class{static{a(this,"RemotePayloadObject")}constructor(t,r,n,s){this.operation=t,this.node_name=r,this.subscriptions=n,this.system_info=s}},FS=class{static{a(this,"RemotePayloadSubscription")}constructor(t,r,n,s,i,o,c){this.schema=t,this.table=r,this.hash_attribute=n,this.publish=s,this.subscribe=i,this.start_time=o,c!==void 0&&(this.attributes=c)}};aL.exports={RemotePayloadObject:GS,RemotePayloadSubscription:FS}});var lL=g((Mde,cL)=>{"use strict";var qS=class{static{a(this,"TableSizeObject")}constructor(t,r,n=0,s=0,i=0,o=0){this.schema=t,this.table=r,this.table_size=n,this.record_count=s,this.transaction_log_size=i,this.transaction_log_record_count=o}};cL.exports=qS});var dL=g((Hde,_L)=>{"use strict";var vX=lL(),Ude=dt(),uL=Ke(),BX=K(),{getSchemaPath:vde,getTransactionAuditStorePath:Bde}=ze(),{getDatabases:HX}=(Ae(),ie(ke));_L.exports=xX;async function xX(e){let t=new vX;try{let r=HX()[e.schema]?.[e.name],n=r.primaryStore.getStats(),s=r.auditStore?.getStats(),i=await uL.environmentDataSize(schema_path,e.name),o=await uL.environmentDataSize(txn_path,e.name);t.schema=e.schema,t.table=e.name,t.table_size=i,t.record_count=n.entryCount,t.transaction_log_size=o,t.transaction_log_record_count=s.entryCount}catch(r){BX.warn(`unable to stat table dbi due to ${r}`)}return t}a(xX,"lmdbGetTableSize")});var EL=g((Gde,fL)=>{"use strict";var kS=class{static{a(this,"SystemInformationObject")}constructor(t,r,n,s,i,o,c){this.system=t,this.time=r,this.cpu=n,this.memory=s,this.disk=i,this.network=o,this.harperdb_processes=c}};fL.exports=kS});var Ea=g((Yde,SL)=>{"use strict";var GX=require("fs-extra"),FX=require("path"),nr=require("systeminformation"),hi=K(),hL=wt(),qde=ct(),Id=U(),qX=dL(),kX=ri(),{getThreadInfo:mL}=it(),ZS=te();ZS.initSync();var VX=EL(),{openEnvironment:kde}=Ke(),{getSchemaPath:Vde}=ze(),{database:$de,databases:VS}=(Ae(),ie(ke)),Nd;SL.exports={getHDBProcessInfo:WS,getNetworkInfo:zS,getDiskInfo:QS,getMemoryInfo:KS,getCPUInfo:YS,getTimeInfo:$S,getSystemInformation:JS,systemInformation:$X,getTableSize:XS,getMetrics:jS};function $S(){return nr.time()}a($S,"getTimeInfo");async function YS(){try{let{family:e,model:t,stepping:r,revision:n,voltage:s,speedmin:i,speedmax:o,governor:c,socket:l,cache:_,...u}=await nr.cpu();u.cpu_speed=await nr.cpuCurrentSpeed();let{raw_currentload:d,raw_currentload_idle:E,raw_currentload_irq:f,raw_currentload_nice:h,raw_currentload_system:p,raw_currentload_user:S,cpus:T,...R}=await nr.currentLoad();return R.cpus=[],T.forEach(b=>{let{raw_load:C,raw_load_idle:H,raw_load_irq:v,raw_load_nice:q,raw_load_system:M,raw_load_user:Q,...J}=b;R.cpus.push(J)}),u.current_load=R,u}catch(e){return hi.error(`error in getCPUInfo: ${e}`),{}}}a(YS,"getCPUInfo");async function KS(){try{let{buffers:e,cached:t,slab:r,buffcache:n,...s}=await nr.mem();return Object.assign(s,process.memoryUsage())}catch(e){return hi.error(`error in getMemoryInfo: ${e}`),{}}}a(KS,"getMemoryInfo");async function WS(){let e={core:[],clustering:[]};try{let t=await nr.processes(),r;try{r=Number.parseInt(await GX.readFile(FX.join(ZS.get(Id.CONFIG_PARAMS.ROOTPATH),Id.HDB_PID_FILE),"utf8"))}catch(n){if(n.code===Id.NODE_ERROR_CODES.ENOENT)hi.warn("Unable to locate 'hdb.pid' file, try stopping and starting HarperDB. This could be because HarperDB is not running.");else throw n}t.list.forEach(n=>{n.pid===r?e.core.push(n):n.name==="nats-server"&&e.clustering.push(n)});for(let n of e.core)for(let s of t.list)s.pid===n.parentPid&&(s.name==="PM2"||s.command==="PM2")&&(n.parent="PM2");return e}catch(t){return hi.error(`error in getHDBProcessInfo: ${t}`),e}}a(WS,"getHDBProcessInfo");async function QS(){let e={};try{let{rIO_sec:t,wIO_sec:r,tIO_sec:n,ms:s,...i}=await nr.disksIO();e.io=i;let{rx_sec:o,tx_sec:c,wx_sec:l,..._}=await nr.fsStats();return e.read_write=_,e.size=await nr.fsSize(),e}catch(t){return hi.error(`error in getDiskInfo: ${t}`),e}}a(QS,"getDiskInfo");async function zS(){let e={default_interface:null,latency:{},interfaces:[],stats:[],connections:[]};try{return e.default_interface=await nr.networkInterfaceDefault(),e.latency=await nr.inetChecksite("google.com"),(await nr.networkInterfaces()).forEach(n=>{let{internal:s,virtual:i,mtu:o,dhcp:c,dnsSuffix:l,ieee8021xAuth:_,ieee8021xState:u,carrier_changes:d,...E}=n;e.interfaces.push(E)}),(await nr.networkStats()).forEach(n=>{let{rx_sec:s,tx_sec:i,ms:o,...c}=n;e.stats.push(c)}),e}catch(t){return hi.error(`error in getNetworkInfo: ${t}`),e}}a(zS,"getNetworkInfo");async function JS(){if(Nd!==void 0)return Nd;let e={};try{let{codepage:t,logofile:r,serial:n,build:s,servicepack:i,uefi:o,...c}=await nr.osInfo();e=c;let l=await nr.versions("node, npm");return e.node_version=l.node,e.npm_version=l.npm,Nd=e,Nd}catch(t){return hi.error(`error in getSystemInformation: ${t}`),e}}a(JS,"getSystemInformation");async function XS(){let e=[],t=await kX.describeAll();for(let r of Object.values(t))for(let n of Object.values(r))e.push(await qX(n));return e}a(XS,"getTableSize");async function jS(){let e={};for(let t in VS){let r=e[t]={},n=r.tables={};for(let s in VS[t])try{let i=VS[t][s];r.readers||(Object.assign(r,i.primaryStore.rootStore.getStats()),delete r.root,r.readers=i.primaryStore.rootStore.readerList().split(/\n\s+/).slice(1).map(l=>{let[_,u,d]=l.trim().split(" ");return{pid:_,thread:u,txnid:d}}),i.primaryStore.auditStore&&(r.audit=i.auditStore.getStats()));let o=i.primaryStore.getStats(),c={};for(let l of["treeDepth","treeBranchPageCount","treeLeafPageCount","entryCount","overflowPages"])c[l]=o[l];n[s]=c}catch(i){hi.notify(`Error getting stats for table ${s}: ${i}`)}}return e}a(jS,"getMetrics");async function pL(){if(ZS.get(Id.CONFIG_PARAMS.CLUSTERING_ENABLED)){let{jsm:e}=await hL.getNATSReferences(),t=await hL.listStreams(),r=[];for(let n of t){let s=[],i=await e.consumers.list(n.config.name);for await(let c of i)s.push({name:c.name,created:c.created,num_ack_pending:c.num_ack_pending,num_redelivered:c.num_redelivered,num_waiting:c.num_waiting,num_pending:c.num_pending});let o={stream_name:n.config.name,database:n.config.subjects[0].split(".")[1],table:n.config.subjects[0].split(".")[2],state:n.state,consumers:s};r.push(o)}return r}}a(pL,"getNatsStreamInfo");async function $X(e){let t=new VX;if(!Array.isArray(e.attributes)||e.attributes.length===0)return t.system=await JS(),t.time=$S(),t.cpu=await YS(),t.memory=await KS(),t.disk=await QS(),t.network=await zS(),t.harperdb_processes=await WS(),t.table_size=await XS(),t.metrics=await jS(),t.threads=await mL(),t.replication=await pL(),t;for(let r=0;r<e.attributes.length;r++)switch(e.attributes[r]){case"system":t.system=await JS();break;case"time":t.time=$S();break;case"cpu":t.cpu=await YS();break;case"memory":t.memory=await KS();break;case"disk":t.disk=await QS();break;case"network":t.network=await zS();break;case"harperdb_processes":t.harperdb_processes=await WS();break;case"table_size":t.table_size=await XS();break;case"database_metrics":case"metrics":t.metrics=await jS();break;case"threads":t.threads=await mL();break;case"replication":t.replication=await pL();break;default:break}return t}a($X,"systemInformation")});var El=g((Wde,YX)=>{YX.exports={name:"harperdb",version:"4.3.21",description:"HarperDB is a distributed database, caching service, streaming broker, and application development platform focused on performance and ease of use.",keywords:["database","nosql","api","distributed","broker","mqtt","real-time","enterprise","Fastify","NATS","HarperDB","Harper","clustering","replication","REST","WebSockets","decentralized","server-sent events","document store"],main:"harperdb.js",bin:{harperdb:"./bin/harperdb.js"},engines:{"minimum-node":"16.0.0","go-lang":"1.21.7","nats-server":"2.10.11"},exports:{".":"./index.js"},homepage:"https://www.harperdb.io/",bugs:"support@harperdb.io",author:{name:"HarperDB",email:"support@harperdb.io"},license:"SEE LICENSE IN LICENSE",scripts:{submodules:"git submodule update --init --recursive",build:"eslint -c ./.eslintbuild bin/ dataLayer/ security/ server/ sqlTranslator/ upgrade/ utility/ validation/",pretty:"eslint --fix bin/ dataLayer/ security/ server/ sqlTranslator/ upgrade/ utility/ validation/","cover:test":"pm2 kill && rimraf ./.nyc_output/* && node utility/devops/register.js --reset_license && nyc --no-clean --reporter=lcovonly npm run test:apitests && nyc --no-clean --reporter=lcovonly npm run test:resources && nyc --no-clean --reporter=lcovonly npm run test:logging && nyc --no-clean --reporter=lcovonly npm run test:upgrade && nyc --no-clean --reporter=lcovonly npm run test:nats && nyc --no-clean --reporter=lcovonly npm run test:cfserver && nyc --no-clean --reporter=lcovonly npm run test:hdbserver && nyc --no-clean --reporter=lcovonly npm run test:bin && nyc --no-clean --reporter=lcovonly npm run test:main && nyc merge .nyc_output coverage.json && node ./utility/devops/register.js --reset_license",test:"pm2 kill && rimraf ./.nyc_output/* && node utility/devops/register.js --reset_license && npm run test:apitests && npm run test:resources && npm run test:logging && npm run test:upgrade && npm run test:nats && npm run test:cfserver && npm run test:hdbserver && npm run test:bin && npm run test:main && nyc merge .nyc_output coverage.json && node ./utility/devops/register.js --reset_license","test:resources":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/resources/**/*.js' --config '../unitTests/.mocharc.json'","test:bin":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/bin/**/*.js' --config '../unitTests/.mocharc.json'","test:main":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/**/*.js' --config '../unitTests/.mocharc-main.json'","test:lmdbbridge":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/dataLayer/harperBridge/lmdbBridge/**/*.js' --config '../unitTests/.mocharc.json'","test:lmdbutility":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/utility/lmdb/**/*.js' --config '../unitTests/.mocharc.json'","test:hdbserver":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/server/harperdb/hdbServer-test.js' --config '../unitTests/.mocharc.json'","test:cfserver":"npm run submodules && cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/server/fastifyRoutes/customFunctionsServer-test.js' --config '../unitTests/.mocharc.json'","test:nats":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/server/nats/**/*.js' --config '../unitTests/.mocharc.json'","test:upgrade":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/upgrade/**/*.js' --config '../unitTests/.mocharc.json'","test:apitests":"pm2 kill && cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/apiTests/**/*-test.mjs' --config '../unitTests/.mocharc.json'","test:logging":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/utility/logging/*.js' --config '../unitTests/.mocharc.json'","test:ci":" cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/**/*.js' --retries 3 --config '../unitTests/.mocharc-main.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/dataLayer/harperBridge/lmdbBridge/**/*.js' --parallel --retries 3 --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/utility/lmdb/**/*.js' --parallel --retries 3 --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/server/harperdb/hdbServer-test.js' --parallel --retries 3 --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/server/customFunctions/customFunctionsServer-test.js' --parallel --retries 3 --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/upgrade/**/*.js' --parallel --retries 3 --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/server/nats/**/*.js' --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter","hdb-check":"./utility/devops/hdb-check.sh","download-prebuilds":"node ./utility/devops/build/download-prebuilds.js",prebuild:"date",postinstall:"node ./launchServiceScripts/launchInstallNATSServer.js",build_nats_dependency:"node ./utility/devops/nats/builder.js",coverage:"nyc --reporter=lcov npm test"},dependencies:{"@aws-sdk/client-s3":"3.635.0","@aws-sdk/lib-storage":"3.635.0","@endo/static-module-record":"^1.0.4","@fastify/autoload":"5.7.1","@fastify/compress":"~6.5.0","@fastify/cors":"~8.5.0","@fastify/static":"~6.12.0","@turf/area":"6.5.0","@turf/boolean-contains":"6.5.0","@turf/boolean-disjoint":"6.5.0","@turf/boolean-equal":"6.5.0","@turf/circle":"6.5.0","@turf/difference":"6.5.0","@turf/distance":"6.5.0","@turf/helpers":"6.5.0","@turf/length":"6.5.0",alasql:"4.1.10","cbor-x":"1.5.8",chalk:"4.1.2","cli-progress":"3.12.0",clone:"2.1.2","fast-glob":"3.3.2",fastify:"~4.26.2","fastify-plugin":"~4.5.1","fs-extra":"11.2.0",graphql:"^16.8.1","human-readable-ids":"1.0.4",inquirer:"8.2.6","is-number":"7.0.0",joi:"17.12.2","json-bigint-fixes":"1.1.0",json2csv:"5.0.7",jsonata:"1.8.7",jsonwebtoken:"9.0.2",lmdb:"3.0.14",lodash:"4.17.21",mathjs:"11.12.0",minimist:"1.2.8",mkcert:"1.5.1",moment:"2.30.1","mqtt-packet":"~8.2.1",msgpackr:"1.10.1",nats:"2.19.0",needle:"3.3.1","node-stream-zip":"1.15.0","node-unix-socket":"0.2.5","normalize-path":"^3.0.0",ora:"5.4.1","ordered-binary":"1.5.1",papaparse:"5.4.1",passport:"0.6.0","passport-http":"0.3.0","passport-local":"1.0.0",pino:"8.16.0",pm2:"5.4.1",prompt:"1.3.0","properties-reader":"2.3.0","recursive-iterator":"3.3.0",semver:"7.5.4",send:"^0.18.0","serve-static":"1.15.0",ses:"1.1.0","stream-chain":"2.2.5","stream-json":"1.8.0",systeminformation:"5.22.9","tar-fs":"2.1.1",ulidx:"0.5.0",uuid:"9.0.1","validate.js":"0.13.1",ws:"8.17.1",yaml:"2.4.1"},devDependencies:{"@tsconfig/node16":"^1.0.3","@types/node":"latest","@typescript-eslint/eslint-plugin":"^5.55.0","@typescript-eslint/parser":"^5.55.0",axios:"1.6.8",chai:"4.4.1","chai-integer":"0.1.0",esbuild:"^0.20.2",eslint:"8.22.0","eslint-config-prettier":"8.3.0","eslint-plugin-prettier":"3.4.1","eslint-plugin-radar":"0.2.1",eventsource:"^2.0.2","hook-std":"3.0.0","intercept-stdout":"0.1.2",mocha:"^10.3.0","mocha-teamcity-reporter":"3.0.0","mock-require":"3.0.3","mock-stdin":"1.0.0",mqtt:"~4.3.8",newman:"5.3.2","newman-reporter-html":"1.0.5","newman-reporter-htmlextra":"1.22.11","newman-reporter-teamcity":"0.1.12","node-fetch":"2.6.7",nyc:"15.1.0",prettier:"2.8.4",rewire:"5.0.0",rimraf:"3.0.2",sinon:"10.0.0","sinon-chai":"3.7.0","source-map-support":"^0.5.21",typescript:"^5.4.2","why-is-node-still-running":"^1.0.0"},overrides:{"eslint-plugin-radar":{eslint:"8.22.0"},alasql:{xlsx:"0.18.5"}},optionalDependencies:{bufferutil:"^4.0.7","utf-8-validate":"^5.0.10"}}});var Cd=g((Qde,TL)=>{"use strict";TL.exports={version:KX,printVersion:WX};var wd=El();function KX(){if(wd)return wd.version}a(KX,"version");function WX(){wd&&console.log(`HarperDB Version ${wd.version}`)}a(WX,"printVersion")});var Ns=g((jde,OL)=>{"use strict";var QX=ln(),eT=z(),zX=require("util"),io=U(),gL=te();gL.initSync();var JX=vS(),RL=Gr(),{Node:Jde,NodeSubscription:Xde}=fa(),XX=ra(),jX=oL(),{RemotePayloadObject:ZX,RemotePayloadSubscription:ej}=fl(),{handleHDBError:tj,hdb_errors:rj}=ne(),{HTTP_STATUS_CODES:nj,HDB_ERROR_MSGS:sj}=rj,ij=es(),oj=Ea(),aj=Cd(),{getDatabases:cj}=(Ae(),ie(ke)),lj=zX.promisify(JX.authorize),uj=RL.searchByHash,_j=RL.searchByValue;OL.exports={authHeaderToUser:dj,isEmpty:fj,getNodeRecord:Ej,upsertNodeRecord:hj,buildNodePayloads:mj,checkClusteringEnabled:pj,getAllNodeRecords:Sj,getSystemInfo:Tj,reverseSubscription:AL};async function dj(e){let t={headers:{authorization:e.hdb_auth_header}};return e.hdb_user=await lj(t,null),e}a(dj,"authHeaderToUser");function fj(e){return e==null}a(fj,"isEmpty");async function Ej(e){let t=new XX(io.SYSTEM_SCHEMA_NAME,io.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[e],["*"]);return uj(t)}a(Ej,"getNodeRecord");async function hj(e){let t=new jX(io.SYSTEM_SCHEMA_NAME,io.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[e]);return QX.upsert(t)}a(hj,"upsertNodeRecord");function AL(e){if(eT.isEmpty(e.subscribe)||eT.isEmpty(e.publish))throw new Error("Received invalid subscription object");let{schema:t,table:r,hash_attribute:n}=e,s={schema:t,table:r,hash_attribute:n};return e.subscribe===!0&&e.publish===!1?(s.subscribe=!1,s.publish=!0):e.subscribe===!1&&e.publish===!0?(s.subscribe=!0,s.publish=!1):(s.subscribe=e.subscribe,s.publish=e.publish),s}a(AL,"reverseSubscription");function mj(e,t,r,n){let s=[];for(let i=0,o=e.length;i<o;i++){let c=e[i],{schema:l,table:_}=c,u=eT.getTableHashAttribute(l,_),{subscribe:d,publish:E}=AL(c),f=cj()[l]?.[_],h=new ej(l,_,u,E,d,c.start_time,f.schemaDefined?f.attributes:void 0);s.push(h)}return new ZX(r,t,s,n)}a(mj,"buildNodePayloads");function pj(){if(!gL.get(io.CONFIG_PARAMS.CLUSTERING_ENABLED))throw tj(new Error,sj.CLUSTERING_NOT_ENABLED,nj.BAD_REQUEST,void 0,void 0,!0)}a(pj,"checkClusteringEnabled");async function Sj(){let e=new ij(io.SYSTEM_SCHEMA_NAME,io.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,"name","*",void 0,["*"]);return Array.from(await _j(e))}a(Sj,"getAllNodeRecords");async function Tj(){let e=await oj.getSystemInformation();return{hdb_version:aj.version(),node_version:e.node_version,platform:e.platform}}a(Tj,"getSystemInfo")});var tT=g((efe,LL)=>{"use strict";var Dd=wt(),bL=z(),yL=ct(),NL=U(),Ld=K(),IL=pd(),gj=Pp(),{RemotePayloadObject:Rj}=fl(),{handleHDBError:wL,hdb_errors:Aj}=ne(),{HTTP_STATUS_CODES:CL}=Aj,{NodeSubscription:DL}=fa();LL.exports=Oj;async function Oj(e,t){let r;try{r=await Dd.request(`${t}.${yL.REQUEST_SUFFIX}`,new Rj(NL.OPERATIONS_ENUM.DESCRIBE_ALL,t,void 0,void 0)),Ld.trace("Response from remote describe all request:",r)}catch(o){Ld.error(`addNode received error from describe all request to remote node: ${o}`);let c=Dd.requestErrorHandler(o,"add_node",t);throw wL(new Error,c,CL.INTERNAL_SERVER_ERROR,"error",c)}if(r.status===yL.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let o=`Error returned from remote node ${t}: ${r.message}`;throw wL(new Error,o,CL.INTERNAL_SERVER_ERROR,"error",o)}let n=r.message,s=[],i=[];for(let o of e){let{table:c}=o,l=o.database??o.schema??"data";if(l===NL.SYSTEM_SCHEMA_NAME){await Dd.createLocalTableStream(l,c);let h=new DL(l,c,o.publish,o.subscribe);h.start_time=o.start_time,i.push(h);continue}let _=bL.doesSchemaExist(l),u=n[l]!==void 0,d=c?bL.doesTableExist(l,c):!0,E=c?n?.[l]?.[c]!==void 0:!0;if(!_&&!u||!d&&!E){s.push(o);continue}if(!_&&u&&(Ld.trace(`addNode creating schema: ${l}`),await IL.createSchema({operation:"create_schema",schema:l})),!d&&E){Ld.trace(`addNode creating table: ${c} in schema: ${l} with attributes ${JSON.stringify(n[l][c].attributes)}`);let h=new gj(l,c,n[l][c].hash_attribute);n[l][c].attributes&&(h.attributes=n[l][c].attributes),await IL.createTable(h)}await Dd.createLocalTableStream(l,c);let f=new DL(l,c,o.publish,o.subscribe);f.start_time=o.start_time,i.push(f)}return{added:i,skipped:s}}a(Oj,"reviewSubscriptions")});var vd=g((rfe,UL)=>{"use strict";var{handleHDBError:Md,hdb_errors:bj}=ne(),{HTTP_STATUS_CODES:Pd}=bj,{addUpdateNodeValidator:yj}=Ad(),Ud=K(),PL=U(),ML=ct(),Nj=z(),hl=wt(),ml=Ns(),Ij=te(),wj=tT(),{Node:Cj,NodeSubscription:Dj}=fa(),{broadcast:Lj}=it(),Mj="Unable to create subscriptions due to schema and/or tables not existing on the local or remote node",Pj="Some subscriptions were unsuccessful due to schema and/or tables not existing on the local or remote node",Uj=Ij.get(PL.CONFIG_PARAMS.CLUSTERING_NODENAME);UL.exports=vj;async function vj(e,t=!1){Ud.trace("addNode called with:",e),ml.checkClusteringEnabled();let r=yj(e);if(r)throw Md(r,r.message,Pd.BAD_REQUEST,void 0,void 0,!0);let n=e.node_name;if(!t){let d=await ml.getNodeRecord(n);if(!Nj.isEmptyOrZeroLength(d))throw Md(new Error,`Node '${n}' has already been added, perform update_node to proceed.`,Pd.BAD_REQUEST,void 0,void 0,!0)}let{added:s,skipped:i}=await wj(e.subscriptions,n),o={message:void 0,added:s,skipped:i};if(s.length===0)return o.message=Mj,o;let c=ml.buildNodePayloads(s,Uj,PL.OPERATIONS_ENUM.ADD_NODE,await ml.getSystemInfo()),l=[];for(let d=0,E=s.length;d<E;d++){let f=s[d];s[d].start_time===void 0&&delete s[d].start_time,l.push(new Dj(f.schema,f.table,f.publish,f.subscribe))}Ud.trace("addNode sending remote payload:",c);let _;try{_=await hl.request(`${n}.${ML.REQUEST_SUFFIX}`,c)}catch(d){Ud.error(`addNode received error from request: ${d}`);for(let f=0,h=s.length;f<h;f++){let p=s[f];p.publish=!1,p.subscribe=!1,await hl.updateRemoteConsumer(p,n)}let E=hl.requestErrorHandler(d,"add_node",n);throw Md(new Error,E,Pd.INTERNAL_SERVER_ERROR,"error",E)}if(_.status===ML.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let d=`Error returned from remote node ${n}: ${_.message}`;throw Md(new Error,d,Pd.INTERNAL_SERVER_ERROR,"error",d)}Ud.trace(_);for(let d=0,E=s.length;d<E;d++){let f=s[d];await hl.updateRemoteConsumer(f,n),f.subscribe===!0&&await hl.updateConsumerIterator(f.schema,f.table,n,"start")}let u=new Cj(n,l,_.system_info);return await ml.upsertNodeRecord(u),Lj({type:"nats_update"}),i.length>0?o.message=Pj:o.message=`Successfully added '${n}' to manifest`,o}a(vj,"addNode")});var sT=g((ife,HL)=>{"use strict";var{handleHDBError:rT,hdb_errors:Bj}=ne(),{HTTP_STATUS_CODES:nT}=Bj,{addUpdateNodeValidator:Hj}=Ad(),pl=K(),BL=U(),vL=ct(),sfe=z(),Sl=wt(),Tl=Ns(),xj=te(),{cloneDeep:Gj}=require("lodash"),Fj=tT(),{Node:qj,NodeSubscription:kj}=fa(),{broadcast:Vj}=it(),$j="Unable to update subscriptions due to schema and/or tables not existing on the local or remote node",Yj="Some subscriptions were unsuccessful due to schema and/or tables not existing on the local or remote node",Kj=xj.get(BL.CONFIG_PARAMS.CLUSTERING_NODENAME);HL.exports=Wj;async function Wj(e){pl.trace("updateNode called with:",e),Tl.checkClusteringEnabled();let t=Hj(e);if(t)throw rT(t,t.message,nT.BAD_REQUEST,void 0,void 0,!0);let r=e.node_name,n,s=await Tl.getNodeRecord(r);s.length>0&&(n=Gj(s));let{added:i,skipped:o}=await Fj(e.subscriptions,r),c={message:void 0,updated:i,skipped:o};if(i.length===0)return c.message=$j,c;let l=Tl.buildNodePayloads(i,Kj,BL.OPERATIONS_ENUM.UPDATE_NODE,await Tl.getSystemInfo());for(let u=0,d=i.length;u<d;u++){let E=i[u];pl.trace(`updateNode updating work stream for node: ${r} subscription:`,E),i[u].start_time===void 0&&delete i[u].start_time}pl.trace("updateNode sending remote payload:",l);let _;try{_=await Sl.request(`${r}.${vL.REQUEST_SUFFIX}`,l)}catch(u){pl.error(`updateNode received error from request: ${u}`);let d=Sl.requestErrorHandler(u,"update_node",r);throw rT(new Error,d,nT.INTERNAL_SERVER_ERROR,"error",d)}if(_.status===vL.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let u=`Error returned from remote node ${r}: ${_.message}`;throw rT(new Error,u,nT.INTERNAL_SERVER_ERROR,"error",u)}pl.trace(_);for(let u=0,d=i.length;u<d;u++){let E=i[u];await Sl.updateRemoteConsumer(E,r),E.subscribe===!0?await Sl.updateConsumerIterator(E.schema,E.table,r,"start"):await Sl.updateConsumerIterator(E.schema,E.table,r,"stop")}return n||(n=[new qj(r,[],_.system_info)]),await Qj(n[0],i,_.system_info),o.length>0?c.message=Yj:c.message=`Successfully updated '${r}'`,c}a(Wj,"updateNode");async function Qj(e,t,r){let n=e;for(let s=0,i=t.length;s<i;s++){let o=t[s],c=!1;for(let l=0,_=e.subscriptions.length;l<_;l++){let u=n.subscriptions[l];if(u.schema===o.schema&&u.table===o.table){u.publish=o.publish,u.subscribe=o.subscribe,c=!0;break}}c||n.subscriptions.push(new kj(o.schema,o.table,o.publish,o.subscribe))}n.system_info=r,await Tl.upsertNodeRecord(n),Vj({type:"nats_update"})}a(Qj,"updateNodeTable")});var kL=g((afe,qL)=>{"use strict";var FL=require("joi"),{string:xL}=FL.types(),zj=at(),GL=U(),Jj=te(),Xj=ct();qL.exports=jj;function jj(e){let t=xL.invalid(Jj.get(GL.CONFIG_PARAMS.CLUSTERING_NODENAME)).pattern(Xj.NATS_TERM_CONSTRAINTS_RX).messages({"string.pattern.base":"{:#label} invalid, must not contain ., * or >","any.invalid":"'node_name' cannot be this nodes name"}).empty(null),r=FL.object({operation:xL.valid(GL.OPERATIONS_ENUM.REMOVE_NODE).required(),node_name:t});return zj.validateBySchema(e,r)}a(jj,"removeNodeValidator")});var Hd=g((lfe,WL)=>{"use strict";var{handleHDBError:VL,hdb_errors:Zj}=ne(),{HTTP_STATUS_CODES:$L}=Zj,eZ=kL(),gl=K(),YL=Ns(),tZ=z(),Bd=U(),KL=ct(),iT=wt(),rZ=te(),{RemotePayloadObject:nZ}=fl(),{NodeSubscription:sZ}=fa(),iZ=Zc(),oZ=Yi(),{broadcast:aZ}=it(),cZ=rZ.get(Bd.CONFIG_PARAMS.CLUSTERING_NODENAME);WL.exports=lZ;async function lZ(e){gl.trace("removeNode called with:",e),YL.checkClusteringEnabled();let t=eZ(e);if(t)throw VL(t,t.message,$L.BAD_REQUEST,void 0,void 0,!0);let r=e.node_name,n=await YL.getNodeRecord(r);if(tZ.isEmptyOrZeroLength(n))throw VL(new Error,`Node '${r}' was not found.`,$L.BAD_REQUEST,void 0,void 0,!0);n=n[0];let s=new nZ(Bd.OPERATIONS_ENUM.REMOVE_NODE,cZ,[]),i,o=!1;for(let l=0,_=n.subscriptions.length;l<_;l++){let u=n.subscriptions[l];u.subscribe===!0&&await iT.updateConsumerIterator(u.schema,u.table,r,"stop");try{await iT.updateRemoteConsumer(new sZ(u.schema,u.table,!1,!1),r)}catch(d){gl.error(d)}}try{i=await iT.request(`${r}.${KL.REQUEST_SUFFIX}`,s),gl.trace("Remove node reply from remote node:",r,i)}catch(l){gl.error("removeNode received error from request:",l),o=!0}let c=new iZ(Bd.SYSTEM_SCHEMA_NAME,Bd.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[r]);return await oZ.deleteRecord(c),aZ({type:"nats_update"}),i?.status===KL.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR||o?(gl.error("Error returned from remote node:",r,i?.message),`Successfully removed '${r}' from local manifest, however there was an error reaching remote node. Check the logs for more details.`):`Successfully removed '${r}' from manifest`}a(lZ,"removeNode")});var JL=g((_fe,zL)=>{"use strict";var QL=require("joi"),{string:uZ,array:_Z}=QL.types(),dZ=at(),fZ=Ad();zL.exports=EZ;function EZ(e){let t=QL.object({operation:uZ.valid("configure_cluster").required(),connections:_Z.items(fZ.validation_schema).required()});return dZ.validateBySchema(e,t)}a(EZ,"configureClusterValidator")});var oT=g((ffe,tM)=>{"use strict";var hZ=U(),xd=K(),mZ=z(),pZ=Hd(),SZ=vd(),XL=Ns(),TZ=JL(),{handleHDBError:jL,hdb_errors:gZ}=ne(),{HTTP_STATUS_CODES:ZL}=gZ,RZ="Configure cluster complete.",AZ="Failed to configure the cluster. Check the logs for more details.",OZ="Configure cluster was partially successful. Errors occurred when attempting to configure the following nodes. Check the logs for more details.";tM.exports=bZ;async function bZ(e){xd.trace("configure cluster called with:",e),XL.checkClusteringEnabled();let t=TZ(e);if(t)throw jL(t,t.message,ZL.BAD_REQUEST,void 0,void 0,!0);let r=await XL.getAllNodeRecords(),n=[];for(let u=0,d=r.length;u<d;u++){let E=await eM(pZ,{operation:hZ.OPERATIONS_ENUM.REMOVE_NODE,node_name:r[u].name},r[u].name);n.push(E)}xd.trace("All results from configure_cluster remove node:",n);let s=[],i=e.connections.length;for(let u=0;u<i;u++){let d=e.connections[u],E=await eM(SZ,d,d.node_name);s.push(E)}xd.trace("All results from configure_cluster add node:",s);let o=[],c=[],l=!1,_=n.concat(s);for(let u=0,d=_.length;u<d;u++){let E=_[u];E.status==="rejected"&&(xd.error(E),o.includes(E.node_name)||o.push(E.node_name)),(E?.result?.message?.includes?.("Successfully")||E?.result?.includes?.("Successfully"))&&(l=!0),!(typeof E.result=="string"&&E.result.includes("Successfully removed")||E.status==="rejected")&&c.push({node_name:E?.node_name,subscriptions:E?.result})}if(mZ.isEmptyOrZeroLength(o))return{message:RZ,connections:c};if(l)return{message:OZ,failed_nodes:o,connections:c};throw jL(new Error,AZ,ZL.INTERNAL_SERVER_ERROR,void 0,void 0,!0)}a(bZ,"configureCluster");async function eM(e,t,r){try{return{node_name:r,result:await e(t)}}catch(n){return{node_name:r,error:n,status:"rejected"}}}a(eM,"functionWrapper")});var iM=g((hfe,sM)=>{"use strict";var Rl=require("joi"),yZ=at(),{validateSchemaExists:rM,validateTableExists:NZ,validateSchemaName:nM}=zn(),IZ=Rl.object({operation:Rl.string().valid("purge_stream"),schema:Rl.string().custom(rM).custom(nM).optional(),database:Rl.string().custom(rM).custom(nM).optional(),table:Rl.string().custom(NZ).required()});function wZ(e){return yZ.validateBySchema(e,IZ)}a(wZ,"purgeStreamValidator");sM.exports=wZ});var aT=g((pfe,oM)=>{"use strict";var{handleHDBError:CZ,hdb_errors:DZ}=ne(),{HTTP_STATUS_CODES:LZ}=DZ,MZ=iM(),PZ=wt(),UZ=Ns();oM.exports=vZ;async function vZ(e){e.schema=e.schema??e.database;let t=MZ(e);if(t)throw CZ(t,t.message,LZ.BAD_REQUEST,void 0,void 0,!0);UZ.checkClusteringEnabled();let{schema:r,table:n,options:s}=e;return await PZ.purgeTableStream(r,n,s),`Successfully purged table '${r}.${n}'`}a(vZ,"purgeStream")});var uT=g((Tfe,dM)=>{"use strict";var lT=Ns(),BZ=wt(),lM=te(),Gd=U(),oo=ct(),HZ=z(),cT=K(),{RemotePayloadObject:xZ}=fl(),{ErrorCode:aM}=require("nats"),cM=lM.get(Gd.CONFIG_PARAMS.CLUSTERING_ENABLED),uM=lM.get(Gd.CONFIG_PARAMS.CLUSTERING_NODENAME);dM.exports={clusterStatus:GZ,buildNodeStatus:_M};async function GZ(){let e={node_name:uM,is_enabled:cM,connections:[]};if(!cM)return e;let t=await lT.getAllNodeRecords();if(HZ.isEmptyOrZeroLength(t))return e;let r=[];for(let n=0,s=t.length;n<s;n++)r.push(_M(t[n],e.connections));return await Promise.allSettled(r),e}a(GZ,"clusterStatus");async function _M(e,t){let r=e.name,n=new xZ(Gd.OPERATIONS_ENUM.CLUSTER_STATUS,uM,void 0,await lT.getSystemInfo()),s,i,o=oo.CLUSTER_STATUS_STATUSES.OPEN;try{let l=Date.now();s=await BZ.request(oo.REQUEST_SUBJECT(r),n),i=Date.now()-l,s.status===oo.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR&&(o=oo.CLUSTER_STATUS_STATUSES.CLOSED,cT.error(`Error getting node status from ${r} `,s))}catch(l){cT.warn(`Error getting node status from ${r}`,l),l.code===aM.NoResponders?o=oo.CLUSTER_STATUS_STATUSES.NO_RESPONDERS:l.code===aM.Timeout?o=oo.CLUSTER_STATUS_STATUSES.TIMEOUT:o=oo.CLUSTER_STATUS_STATUSES.CLOSED}let c=new FZ(r,o,s?.message?.ports?.clustering,s?.message?.ports?.operations_api,i,s?.message?.uptime,e.subscriptions,s?.message?.system_info);try{let l={name:r,system_info:s?.message?.system_info};e.system_info?.hdb_version!==Gd.PRE_4_0_0_VERSION&&await lT.upsertNodeRecord(l)}catch(l){cT.error("Cluster status encountered an error updating system info for node:",r,l)}t.push(c)}a(_M,"buildNodeStatus");function FZ(e,t,r,n,s,i,o,c){this.node_name=e,this.status=t,this.ports={clustering:r,operations_api:n},this.latency_ms=s,this.uptime=i,this.subscriptions=o,this.system_info=c}a(FZ,"NodeStatusObject")});var dT=g((Rfe,fM)=>{"use strict";var{handleHDBError:qZ,hdb_errors:kZ}=ne(),{HTTP_STATUS_CODES:VZ}=kZ,$Z=wt(),YZ=Ns(),_T=z(),Fd=require("joi"),KZ=at(),WZ=2e3,QZ=Fd.object({timeout:Fd.number().min(1),connected_nodes:Fd.boolean(),routes:Fd.boolean()});fM.exports=zZ;async function zZ(e){YZ.checkClusteringEnabled();let t=KZ.validateBySchema(e,QZ);if(t)throw qZ(t,t.message,VZ.BAD_REQUEST,void 0,void 0,!0);let{timeout:r,connected_nodes:n,routes:s}=e,i=n===void 0||_T.autoCastBoolean(n),o=s===void 0||_T.autoCastBoolean(s),c={nodes:[]},l=await $Z.getServerList(r??WZ),_={};if(i)for(let u=0,d=l.length;u<d;u++){let E=l[u].statsz;E&&(_[l[u].server.name]=E.routes)}for(let u=0,d=l.length;u<d;u++){if(l[u].statsz)continue;let E=l[u].server,f=l[u].data;if(E.name.endsWith("-hub")){let h={name:E.name.slice(0,-4),response_time:l[u].response_time};i&&(h.connected_nodes=[],_[E.name]&&_[E.name].forEach(p=>{h.connected_nodes.includes(p.name.slice(0,-4))||h.connected_nodes.push(p.name.slice(0,-4))})),o&&(h.routes=f.cluster?.urls?f.cluster?.urls.map(p=>({host:p.split(":")[0],port:_T.autoCast(p.split(":")[1])})):[]),c.nodes.push(h)}}return c}a(zZ,"clusterNetwork")});var pM=g((Ofe,mM)=>{"use strict";var fT=require("joi"),EM=at(),{route_constraints:hM}=Ym();mM.exports={setRoutesValidator:JZ,deleteRoutesValidator:XZ};function JZ(e){let t=fT.object({server:fT.valid("hub","leaf").required(),routes:hM.required()});return EM.validateBySchema(e,t)}a(JZ,"setRoutesValidator");function XZ(e){let t=fT.object({routes:hM.required()});return EM.validateBySchema(e,t)}a(XZ,"deleteRoutesValidator")});var hT=g((yfe,RM)=>{"use strict";var ao=Er(),ET=z(),qd=U(),SM=pM(),{handleHDBError:TM,hdb_errors:jZ}=ne(),{HTTP_STATUS_CODES:gM}=jZ,ZZ="cluster routes successfully set",e5="cluster routes successfully deleted";RM.exports={setRoutes:t5,getRoutes:r5,deleteRoutes:n5};function t5(e){let t=SM.setRoutesValidator(e);if(t)throw TM(t,t.message,gM.BAD_REQUEST,void 0,void 0,!0);let r=ao.getClusteringRoutes(),n=e.server==="hub"?r.hub_routes:r.leaf_routes,s=e.server==="hub"?r.leaf_routes:r.hub_routes,i=[],o=[];for(let c=0,l=e.routes.length;c<l;c++){let _=e.routes[c];_.port=ET.autoCast(_.port);let u=n.some(E=>E.host===_.host&&E.port===_.port),d=s.some(E=>E.host===_.host&&E.port===_.port);u||d?i.push(_):(n.push(_),o.push(_))}return e.server==="hub"?ao.updateConfigValue(qd.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,n):ao.updateConfigValue(qd.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,n),{message:ZZ,set:o,skipped:i}}a(t5,"setRoutes");function r5(){let e=ao.getClusteringRoutes();return{hub:e.hub_routes,leaf:e.leaf_routes}}a(r5,"getRoutes");function n5(e){let t=SM.deleteRoutesValidator(e);if(t)throw TM(t,t.message,gM.BAD_REQUEST,void 0,void 0,!0);let r=ao.getClusteringRoutes(),n=r.hub_routes,s=r.leaf_routes,i=[],o=[],c=!1,l=!1;for(let _=0,u=e.routes.length;_<u;_++){let d=e.routes[_],E=!1;for(let f=0,h=n.length;f<h;f++){let p=n[f];if(d.host===p.host&&d.port===p.port){n.splice(f,1),E=!0,c=!0,i.push(d);break}}if(!E){let f=!0;for(let h=0,p=s.length;h<p;h++){let S=s[h];if(d.host===S.host&&d.port===S.port){s.splice(h,1),l=!0,f=!1,i.push(d);break}}f&&o.push(d)}}return c&&(n=ET.isEmptyOrZeroLength(n)?null:n,ao.updateConfigValue(qd.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,n)),l&&(s=ET.isEmptyOrZeroLength(s)?null:s,ao.updateConfigValue(qd.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,s)),{message:e5,deleted:i,skipped:o}}a(n5,"deleteRoutes")});var OM=g((Ife,AM)=>{"use strict";var Al=require("alasql"),co=require("recursive-iterator"),vn=K(),s5=z(),Ol=U(),mT=class{static{a(this,"sql_statement_bucket")}constructor(t){this.ast=t,this.affected_attributes=new Map,this.table_lookup=new Map,this.schema_lookup=new Map,this.table_to_schema_lookup=new Map,o5(this.ast,this.affected_attributes,this.table_lookup,this.schema_lookup,this.table_to_schema_lookup)}getAttributesBySchemaTableName(t,r){if(!t||!r||!this.affected_attributes)return[];if(this.affected_attributes.has(t))return!this.affected_attributes.get(t).has(r)&&(r=this.table_lookup.get(r),!r)?[]:this.affected_attributes.get(t).get(r)}getAllTables(){let t=[];if(!this.affected_attributes)return t;for(let r of this.affected_attributes.keys())t.push(Array.from(this.affected_attributes.get(r).keys()));return t}getTablesBySchemaName(t){return!t||!this.affected_attributes?[]:Array.from(this.affected_attributes.get(t).keys())}getSchemas(){return this.affected_attributes?Array.from(this.affected_attributes.keys()):[]}getAst(){return this.ast}updateAttributeWildcardsForRolePerms(t){let r=this.ast.columns.filter(s=>Ol.SEARCH_WILDCARDS.includes(s.columnid));if(r.length===0)return this.ast;let n=this.ast.from[0].databaseid;return this.ast.columns=this.ast.columns.filter(s=>!Ol.SEARCH_WILDCARDS.includes(s.columnid)),r.forEach(s=>{let i=this.table_to_schema_lookup.has(s.tableid)?this.table_to_schema_lookup.get(s.tableid):n,o=this.table_lookup.has(s.tableid)?this.table_lookup.get(s.tableid):this.ast.from[0].tableid;if(t[i]&&t[i].tables[o]&&t[i].tables[o][Ol.PERMS_CRUD_ENUM.READ]){let c;t[i].tables[o].attribute_permissions.length>0?c=i5(t[i].tables[o].attribute_permissions):c=global.hdb_schema[i][o].attributes.map(_=>({attribute_name:_.attribute}));let l=this.affected_attributes.get(i).get(o).filter(_=>!Ol.SEARCH_WILDCARDS.includes(_));c.forEach(({attribute_name:_})=>{let u=new Al.yy.Column({columnid:_});s.tableid&&(u.tableid=s.tableid),this.ast.columns.push(u),l.includes(_)||l.push(_)}),this.affected_attributes.get(i).set(o,l)}}),this.ast}};function i5(e){return e.filter(t=>t[Ol.PERMS_CRUD_ENUM.READ])}a(i5,"filterReadRestrictedAttrs");function o5(e,t,r,n,s){a5(e,t,r,n,s)}a(o5,"interpretAST");function bl(e,t,r,n,s){if(!(!e||!e.databaseid)&&(t.has(e.databaseid)||t.set(e.databaseid,new Map),t.get(e.databaseid).has(e.tableid)||t.get(e.databaseid).set(e.tableid,[]),e.as&&(r.has(e.as)||r.set(e.as,e.tableid),n&&!n.has(e.as)&&n.set(e.as,e.databaseid)),s)){let i=e.databaseid,o=e.tableid;e.as&&(o=e.as),s.set(o,i)}}a(bl,"addSchemaTableToMap");function a5(e,t,r,n,s){if(!e){vn.info("getRecordAttributesAST: invalid SQL syntax tree");return}e instanceof Al.yy.Insert?_5(e,t,r):e instanceof Al.yy.Select?c5(e,t,r,n,s):e instanceof Al.yy.Update?l5(e,t,r):e instanceof Al.yy.Delete?u5(e,t,r):vn.error("AST in getRecordAttributesAST() is not a valid SQL type.")}a(a5,"getRecordAttributesAST");function c5(e,t,r,n,s){if(!e){vn.info("getSelectAttributes: invalid SQL syntax tree");return}if(!e.from||e.from[0]===void 0)return;let i=e.from[0].databaseid;if(s5.isEmptyOrZeroLength(i)){vn.error("No schema specified");return}e.from.forEach(c=>{bl(c,t,r,n,s)}),e.joins&&e.joins.forEach(c=>{c.as&&(c.table.as=c.as),bl(c.table,t,r,n,s)});let o=new co(e.columns);for(let{node:c}of o)if(c&&c.columnid){let l=c.tableid,_=n.has(l)?n.get(l):i;if(l||(l=e.from[0].tableid),!t.get(_).has(l))if(r.has(l))l=r.get(l);else{vn.info(`table specified as ${l} not found.`);return}t.get(_).get(l).indexOf(c.columnid)<0&&t.get(_).get(l).push(c.columnid)}if(e.where){let c=new co(e.where),l=e.from[0].tableid;for(let{node:_}of c)if(_&&_.columnid){let u=_.tableid?_.tableid:l;if(!t.get(i).has(u))if(r.has(u))u=r.get(u);else{vn.info(`table specified as ${u} not found.`);continue}t.get(i).get(u).indexOf(_.columnid)<0&&t.get(i).get(u).push(_.columnid)}}if(e.joins&&e.joins.forEach(c=>{let l=new co(c.on);for(let{node:_}of l)if(_&&_.columnid){let u=_.tableid,d=s.get(u);if(!t.get(d).has(u))if(r.has(u))u=r.get(u);else{vn.info(`table specified as ${u} not found.`);continue}t.get(d).get(u).indexOf(_.columnid)<0&&t.get(d).get(u).push(_.columnid)}}),e.order){let c=new co(e.order);for(let{node:l}of c)if(l&&l.columnid){let _=l.tableid,u=n.has(_)?n.get(_):i;if(_||(_=e.from[0].tableid),!t.get(u).has(_))if(r.has(_))_=r.get(_);else{vn.info(`table specified as ${_} not found.`);return}t.get(u).get(_).indexOf(l.columnid)<0&&t.get(u).get(_).push(l.columnid)}}}a(c5,"getSelectAttributes");function l5(e,t,r){if(!e){vn.info("getUpdateAttributes: invalid SQL syntax tree");return}let n=new co(e.columns),s=e.table.databaseid;bl(e.table,t,r);for(let{node:i}of n)i&&i.columnid&&pT(e.table.tableid,s,i.columnid,t,r)}a(l5,"getUpdateAttributes");function u5(e,t,r){if(!e){vn.info("getDeleteAttributes: invalid SQL syntax tree");return}let n=new co(e.where),s=e.table.databaseid;bl(e.table,t,r);for(let{node:i}of n)i&&i.columnid&&pT(e.table.tableid,s,i.columnid,t,r)}a(u5,"getDeleteAttributes");function _5(e,t,r){if(!e){vn.info("getInsertAttributes: invalid SQL syntax tree");return}let n=new co(e.columns),s=e.into.databaseid;bl(e.into,t,r);for(let{node:i}of n)i&&i.columnid&&pT(e.into.tableid,s,i.columnid,t,r)}a(_5,"getInsertAttributes");function pT(e,t,r,n,s){if(!n.get(t))return;let i=e;n.get(t).has(i)||(i=s.get(i)),n.get(t).get(i).push(r)}a(pT,"pushAttribute");AM.exports=mT});var gT=g((Cfe,IM)=>{var kd=zi(),bM=require("chalk"),Kr=K(),yM=require("prompt"),{promisify:d5}=require("util"),ST=U(),f5=require("fs-extra"),E5=require("path"),h5=z(),m5=Cd(),NM=te();NM.initSync();var p5=require("moment"),S5=d5(yM.get),T5=E5.join(NM.getHdbBasePath(),ST.LICENSE_KEY_DIR_NAME,ST.LICENSE_FILE_NAME,ST.LICENSE_FILE_NAME);IM.exports={getFingerprint:R5,setLicense:g5,parseLicense:TT,register:A5,getRegistrationInfo:b5};async function g5(e){if(e&&e.key&&e.company){try{Kr.info(`parsing license key: ${e.key} and `);let t=e.company.toString();await TT(e.key.trim(),t.trim())}catch(t){let r="There was an error parsing the license key.";throw Kr.error(r),Kr.error(t),new Error(r)}return"Wrote license key file. Registration successful."}throw new Error("Invalid key or company specified for license file.")}a(g5,"setLicense");async function R5(){let e={};try{e=await kd.generateFingerPrint()}catch(t){let r="Error generating fingerprint.";throw Kr.error(r),Kr.error(t),new Error(r)}return e}a(R5,"getFingerprint");async function TT(e,t){if(!e||!t)throw new Error("Invalid entries for License Key and Customer Company");Kr.info("Validating license input...");let r=kd.validateLicense(e,t);if(Kr.info("checking for valid license..."),!r.valid_license)throw new Error("Invalid license found.");if(Kr.info("checking valid license date..."),!r.valid_date)throw new Error("This License has expired.");if(Kr.info(`checking for valid machine license ${r.valid_machine}`),!r.valid_machine)throw new Error("This license is in use on another machine.");try{Kr.info("writing license to disk"),await f5.writeFile(T5,JSON.stringify({license_key:e,company:t}))}catch(n){throw Kr.error("Failed to write License"),n}return"Registration successful."}a(TT,"parseLicense");async function A5(){let e=await O5();return TT(e.HDB_LICENSE,e.CUSTOMER_COMPANY)}a(A5,"register");async function O5(){let e=await kd.generateFingerPrint(),t={properties:{CUSTOMER_COMPANY:{description:bM.magenta("[COMPANY] Please enter your company name"),required:!0},HDB_LICENSE:{description:bM.magenta(`[HDB_LICENSE] Your fingerprint is ${e} Please enter your license key`),required:!0}}};try{yM.start()}catch(n){Kr.error(n)}let r;try{r=await S5(t)}catch(n){throw console.error("There was a problem prompting for registration input. Exiting."),n}return r}a(O5,"promptForRegistration");async function b5(){let e={registered:!1,version:null,ram_allocation:null,license_expiration_date:null},t;try{t=await kd.getLicense()}catch(r){throw Kr.error(`There was an error when searching licenses due to: ${r.message}`),r}if(h5.isEmptyOrZeroLength(t))throw new Error("There were no licenses found.");if(e.registered=t.enterprise,e.version=m5.version(),e.ram_allocation=t.ram_allocation,isNaN(t.exp_date))e.license_expiration_date=t.enterprise?t.exp_date:null;else{let r=p5.utc(t.exp_date).format("YYYY-MM-DD");e.license_expiration_date=t.enterprise?r:null}return e}a(b5,"getRegistrationInfo")});var CM=g((Lfe,wM)=>{"use strict";var y5=ct(),RT=class{static{a(this,"HubConfigObject")}constructor(t,r,n,s,i,o,c,l,_,u,d,E,f,h){this.port=t,o===null&&(o=void 0),this.server_name=r+y5.SERVER_SUFFIX.HUB,this.pid_file=n,this.max_payload=67108864,this.reconnect_error_reports=100,this.jetstream={enabled:!1},this.tls={cert_file:s,key_file:i,ca_file:o,insecure:c,verify:l},this.leafnodes={port:_,tls:{cert_file:s,key_file:i,ca_file:o,insecure:c}},this.cluster={name:u,port:d,routes:E,tls:{cert_file:s,key_file:i,ca_file:o,insecure:c,verify:l}},this.accounts={SYS:{users:f},HDB:{users:h}},this.system_account="SYS"}};wM.exports=RT});var MM=g((Pfe,LM)=>{"use strict";var DM=ct(),AT=class{static{a(this,"LeafConfigObject")}constructor(t,r,n,s,i,o,c,l,_,u,d){this.port=t,d===null&&(d=void 0),this.server_name=r+DM.SERVER_SUFFIX.LEAF,this.pid_file=n,this.max_payload=67108864,this.jetstream={enabled:!0,store_dir:s,domain:r+DM.SERVER_SUFFIX.LEAF},this.tls={cert_file:_,key_file:u,ca_file:d,insecure:!0},this.leafnodes={remotes:[{tls:{ca_file:d,insecure:!0},urls:i,account:"SYS"},{tls:{ca_file:d,insecure:!0},urls:o,account:"HDB"}]},this.accounts={SYS:{users:c},HDB:{users:l,jetstream:"enabled"}},this.system_account="SYS"}};LM.exports=AT});var UM=g((vfe,PM)=>{"use strict";var OT=class{static{a(this,"HdbUserObject")}constructor(t,r){this.user=t,this.password=r}};PM.exports=OT});var BM=g((Hfe,vM)=>{"use strict";var N5=ct(),bT=class{static{a(this,"SysUserObject")}constructor(t,r){this.user=t+N5.SERVER_SUFFIX.ADMIN,this.password=r}};vM.exports=bT});var IT=g((Gfe,GM)=>{"use strict";var ha=require("path"),Yd=require("fs-extra"),I5=CM(),w5=MM(),C5=UM(),D5=BM(),yT=un(),pa=z(),Or=Er(),$d=U(),yl=ct(),{CONFIG_PARAMS:mt}=$d,Sa=K(),Nl=te(),HM=Rs(),NT=wt(),ma="clustering",L5=1e4,xM=50;GM.exports={generateNatsConfig:P5,removeNatsConfig:U5,getHubConfigPath:M5};function M5(){let e=Nl.get(mt.ROOTPATH);return ha.join(e,ma,yl.NATS_CONFIG_FILES.HUB_SERVER)}a(M5,"getHubConfigPath");async function P5(e=!1,t=void 0){Nl.initSync();let r=Nl.get(mt.ROOTPATH),n=ha.join(r,ma,yl.PID_FILES.HUB),s=ha.join(r,ma,yl.PID_FILES.LEAF),i=Or.getConfigFromFile(mt.CLUSTERING_LEAFSERVER_STREAMS_PATH),o=ha.join(r,ma,yl.NATS_CONFIG_FILES.HUB_SERVER),c=ha.join(r,ma,yl.NATS_CONFIG_FILES.LEAF_SERVER),l=Or.getConfigFromFile(mt.CLUSTERING_TLS_CERTIFICATE),_=Or.getConfigFromFile(mt.CLUSTERING_TLS_PRIVATEKEY),u=Or.getConfigFromFile(mt.CLUSTERING_TLS_CERT_AUTH),d=Or.getConfigFromFile(mt.CLUSTERING_TLS_INSECURE),E=Or.getConfigFromFile(mt.CLUSTERING_TLS_VERIFY),f=Or.getConfigFromFile(mt.CLUSTERING_NODENAME),h=Or.getConfigFromFile(mt.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT);await NT.checkNATSServerInstalled()||Kd("nats-server dependency is either missing or the wrong version. Run 'npm install' to fix");let p=await yT.listUsers(),S=Or.getConfigFromFile(mt.CLUSTERING_USER),T=await yT.getClusterUser();(pa.isEmpty(T)||T.active!==!0)&&Kd(`Invalid cluster user '${S}'. A valid user with the role 'cluster_user' must be defined under clustering.user in harperdb-config.yaml`),e||(await Vd(mt.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),await Vd(mt.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT),await Vd(mt.CLUSTERING_HUBSERVER_NETWORK_PORT),await Vd(mt.CLUSTERING_LEAFSERVER_NETWORK_PORT));let R=[],b=[];for(let[J,X]of p.entries())X.role.role===$d.ROLE_TYPES_ENUM.CLUSTER_USER&&X.active&&(R.push(new D5(X.username,HM.decrypt(X.hash))),b.push(new C5(X.username,HM.decrypt(X.hash))));let C=[],{hub_routes:H}=Or.getClusteringRoutes();if(!pa.isEmptyOrZeroLength(H))for(let J of H)C.push(`tls://${T.sys_name_encoded}:${T.uri_encoded_d_hash}@${J.host}:${J.port}`);let v=new I5(Or.getConfigFromFile(mt.CLUSTERING_HUBSERVER_NETWORK_PORT),f,n,l,_,u,d,E,h,Or.getConfigFromFile(mt.CLUSTERING_HUBSERVER_CLUSTER_NAME),Or.getConfigFromFile(mt.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),C,R,b);u==null&&(delete v.tls.ca_file,delete v.leafnodes.tls.ca_file),t=pa.isEmpty(t)?void 0:t.toLowerCase(),(t===void 0||t===$d.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase())&&(await Yd.writeJson(o,v),Sa.trace(`Hub server config written to ${o}`));let q=`tls://${T.sys_name_encoded}:${T.uri_encoded_d_hash}@0.0.0.0:${h}`,M=`tls://${T.uri_encoded_name}:${T.uri_encoded_d_hash}@0.0.0.0:${h}`,Q=new w5(Or.getConfigFromFile(mt.CLUSTERING_LEAFSERVER_NETWORK_PORT),f,s,i,[q],[M],R,b,l,_,u,d);u==null&&delete Q.tls.ca_file,(t===void 0||t===$d.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())&&(await Yd.writeJson(c,Q),Sa.trace(`Leaf server config written to ${c}`))}a(P5,"generateNatsConfig");async function Vd(e){let t=Nl.get(e);return pa.isEmpty(t)&&Kd(`port undefined for '${e}'`),await pa.isPortTaken(t)&&Kd(`'${e}' port '${t}' is is in use by another process, check to see if HarperDB is already running or another process is using this port.`),!0}a(Vd,"isPortAvailable");function Kd(e){let t=`Error generating clustering config: ${e}`;Sa.error(t),console.error(t),process.exit(1)}a(Kd,"generateNatsConfigError");async function U5(e){let{port:t,config_file:r}=NT.getServerConfig(e),{username:n,decrypt_hash:s}=await yT.getClusterUser(),i=0,o=2e3;for(;i<xM;){try{let u=await NT.createConnection(t,n,s,!1);if(u.protocol.connected===!0){u.close();break}}catch(u){Sa.trace(`removeNatsConfig waiting for ${e}. Caught and swallowed error ${u}`)}if(i++,i>=xM)throw new Error(`Operations API timed out attempting to connect to ${e}. This is commonly caused by incorrect clustering config. Check hdb.log for further details.`);let _=o*(i*2);_>3e4&&Sa.notify("Operations API waiting for Nats server connection. This could be caused by large Nats streams or incorrect clustering config."),await pa.async_set_timeout(_)}let c="0".repeat(L5),l=ha.join(Nl.get(mt.ROOTPATH),ma,r);await Yd.writeFile(l,c),await Yd.remove(l),Sa.notify(e,"started.")}a(U5,"removeNatsConfig")});var YM=g((qfe,$M)=>{"use strict";var Wr=te(),v5=zi(),he=U(),Il=ct(),Is=require("path"),{PACKAGE_ROOT:Qd}=U(),FM=te(),Wd=z(),Ta="/dev/null",B5=Is.join(Qd,"launchServiceScripts"),qM=Is.join(Qd,"utility/scripts"),H5=Is.join(qM,he.HDB_RESTART_SCRIPT),kM=Is.resolve(Qd,"dependencies",`${process.platform}-${process.arch}`,Il.NATS_BINARY_NAME);function VM(){let t=v5.licenseSearch().ram_allocation||he.RAM_ALLOCATION_ENUM.DEFAULT,r=he.MEM_SETTING_KEY+t,n={[he.PROCESS_NAME_ENV_PROP]:he.PROCESS_DESCRIPTORS.HDB,IS_SCRIPTED_SERVICE:!0};return Wd.noBootFile()&&(n[he.CONFIG_PARAMS.ROOTPATH.toUpperCase()]=Wd.getEnvCliRootPath()),{name:he.PROCESS_DESCRIPTORS.HDB,script:he.LAUNCH_SERVICE_SCRIPTS.MAIN,exec_mode:"fork",env:n,node_args:r,cwd:Qd}}a(VM,"generateMainServerConfig");var x5=9930;function G5(){Wr.initSync(!0);let e=Wr.get(he.CONFIG_PARAMS.ROOTPATH),t=Is.join(e,"clustering",Il.NATS_CONFIG_FILES.HUB_SERVER),r=Is.join(Wr.get(he.HDB_SETTINGS_NAMES.LOG_PATH_KEY),he.LOG_NAMES.HDB),n=FM.get(he.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),s=Il.LOG_LEVEL_FLAGS[Wr.get(he.CONFIG_PARAMS.CLUSTERING_LOGLEVEL)]??void 0,i={name:he.PROCESS_DESCRIPTORS.CLUSTERING_HUB+(n!==x5?"-"+n:""),script:kM,args:s?`${s} -c ${t}`:`-c ${t}`,exec_mode:"fork",env:{[he.PROCESS_NAME_ENV_PROP]:he.PROCESS_DESCRIPTORS.CLUSTERING_HUB},merge_logs:!0,out_file:r,error_file:r,instances:1};return Wr.get(he.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(i.out_file=Ta,i.error_file=Ta),i}a(G5,"generateNatsHubServerConfig");var F5=9940;function q5(){Wr.initSync(!0);let e=Wr.get(he.CONFIG_PARAMS.ROOTPATH),t=Is.join(e,"clustering",Il.NATS_CONFIG_FILES.LEAF_SERVER),r=Is.join(Wr.get(he.HDB_SETTINGS_NAMES.LOG_PATH_KEY),he.LOG_NAMES.HDB),n=FM.get(he.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),s=Il.LOG_LEVEL_FLAGS[Wr.get(he.CONFIG_PARAMS.CLUSTERING_LOGLEVEL)]??void 0,i={name:he.PROCESS_DESCRIPTORS.CLUSTERING_LEAF+(n!==F5?"-"+n:""),script:kM,args:s?`${s} -c ${t}`:`-c ${t}`,exec_mode:"fork",env:{[he.PROCESS_NAME_ENV_PROP]:he.PROCESS_DESCRIPTORS.CLUSTERING_LEAF},merge_logs:!0,out_file:r,error_file:r,instances:1};return Wr.get(he.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(i.out_file=Ta,i.error_file=Ta),i}a(q5,"generateNatsLeafServerConfig");function k5(){Wr.initSync();let e=Is.join(Wr.get(he.CONFIG_PARAMS.LOGGING_ROOT),he.LOG_NAMES.HDB),t={name:he.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0,script:he.LAUNCH_SERVICE_SCRIPTS.NODES_UPGRADE_4_0_0,exec_mode:"fork",env:{[he.PROCESS_NAME_ENV_PROP]:he.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0},merge_logs:!0,out_file:e,error_file:e,instances:1,cwd:B5,autorestart:!1};return Wr.get(he.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(t.out_file=Ta,t.error_file=Ta),t}a(k5,"generateClusteringUpgradeV4ServiceConfig");function V5(){let e={[he.PROCESS_NAME_ENV_PROP]:he.PROCESS_DESCRIPTORS.RESTART_HDB};return Wd.noBootFile()&&(e[he.CONFIG_PARAMS.ROOTPATH.toUpperCase()]=Wd.getEnvCliRootPath()),{...{name:he.PROCESS_DESCRIPTORS.RESTART_HDB,exec_mode:"fork",env:e,instances:1,autorestart:!1,cwd:qM},script:H5}}a(V5,"generateRestart");function $5(){return{apps:[VM()]}}a($5,"generateAllServiceConfigs");$M.exports={generateAllServiceConfigs:$5,generateMainServerConfig:VM,generateRestart:V5,generateNatsHubServerConfig:G5,generateNatsLeafServerConfig:q5,generateClusteringUpgradeV4ServiceConfig:k5}});var iP=g(($fe,sP)=>{"use strict";var Ue=U(),Y5=z(),Cs=IT(),zd=wt(),ws=ct(),mi=YM(),Jd=te(),pi=K(),K5=Ns(),{startWorker:KM,onMessageFromWorkers:W5}=it(),Q5=Ea(),Vfe=require("util"),z5=require("child_process"),J5=require("fs"),{execFile:X5}=z5,Ie;sP.exports={enterPM2Mode:j5,start:Si,stop:wT,reload:QM,restart:zM,list:CT,describe:XM,connect:Ds,kill:n8,startAllServices:s8,startService:DT,getUniqueServicesList:jM,restartAllServices:i8,isServiceRegistered:ZM,reloadStopStart:eP,restartHdb:JM,deleteProcess:t8,startClusteringProcesses:rP,startClusteringThreads:nP,isHdbRestartRunning:r8,isClusteringRunning:a8,stopClustering:o8,reloadClustering:c8};var wl=!1;W5(e=>{e.type==="restart"&&Jd.initSync(!0)});function j5(){wl=!0}a(j5,"enterPM2Mode");function Ds(){return Ie||(Ie=require("pm2")),new Promise((e,t)=>{Ie.connect((r,n)=>{pi.setupConsoleLogging(),r&&t(r),e(n)})})}a(Ds,"connect");var br,Z5=10,WM;function Si(e,t=!1){if(wl)return e8(e);let r=X5(e.script,e.args.split(" "),e);r.name=e.name,r.on("exit",async i=>{let o=br.indexOf(r);o>-1&&br.splice(o,1),!WM&&i!==0&&(e.restarts=(e.restarts||0)+1,e.restarts<Z5&&(J5.existsSync(Cs.getHubConfigPath())?Si(e):(await Cs.generateNatsConfig(!0),Si(e),await new Promise(c=>setTimeout(c,3e3)),await Cs.removeNatsConfig(Ue.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await Cs.removeNatsConfig(Ue.PROCESS_DESCRIPTORS.CLUSTERING_LEAF))))});let n={serviceName:e.name.replace(/ /g,"-")};function s(i){let o=Jd.get(Ue.CONFIG_PARAMS.CLUSTERING_LOGLEVEL),c=/\[\d+][^\[]+\[(\w+)]/g,l,_=0,u;for(;l=c.exec(i);){if(l.index&&ws.LOG_LEVEL_HIERARCHY[o]>=ws.LOG_LEVEL_HIERARCHY[u||"info"]){let f=u===ws.LOG_LEVELS.ERR||u===ws.LOG_LEVELS.WRN?pi.OUTPUTS.STDERR:pi.OUTPUTS.STDOUT;pi.logCustomLevel(u||"info",f,n,i.slice(_,l.index).trim())}let[d,E]=l;_=l.index+d.length,u=ws.LOG_LEVELS[E]}if(ws.LOG_LEVEL_HIERARCHY[o]>=ws.LOG_LEVEL_HIERARCHY[u||"info"]){let d=u===ws.LOG_LEVELS.ERR||u===ws.LOG_LEVELS.WRN?pi.OUTPUTS.STDERR:pi.OUTPUTS.STDOUT;pi.logCustomLevel(u||"info",d,n,i.slice(_).trim())}}if(a(s,"extractMessages"),r.stdout.on("data",s),r.stderr.on("data",s),r.unref(),br=[],!br&&!t){let i=a(()=>{WM=!0,br&&(br.map(o=>o.kill()),process.exit(0))},"kill_children");process.on("exit",i),process.on("SIGINT",i),process.on("SIGQUIT",i),process.on("SIGTERM",i)}br.push(r)}a(Si,"start");function e8(e){return new Promise(async(t,r)=>{try{await Ds()}catch(n){r(n)}Ie.start(e,(n,s)=>{n&&(Ie.disconnect(),r(n)),Ie.disconnect(),t(s)})})}a(e8,"startWithPM2");function wT(e){if(!wl){for(let t of br||[])t.name===e&&(br.splice(br.indexOf(t),1),t.kill());return}return new Promise(async(t,r)=>{try{await Ds()}catch(n){r(n)}Ie.stop(e,async(n,s)=>{n&&(Ie.disconnect(),r(n)),Ie.delete(e,(i,o)=>{i&&(Ie.disconnect(),r(n)),Ie.disconnect(),t(o)})})})}a(wT,"stop");function QM(e){return new Promise(async(t,r)=>{try{await Ds()}catch(n){r(n)}Ie.reload(e,(n,s)=>{n&&(Ie.disconnect(),r(n)),Ie.disconnect(),t(s)})})}a(QM,"reload");function zM(e){if(!wl)for(let t of br||[])t.name===e&&t.kill();return new Promise(async(t,r)=>{try{await Ds()}catch(n){r(n)}Ie.restart(e,(n,s)=>{Ie.disconnect(),t(s)})})}a(zM,"restart");function t8(e){return new Promise(async(t,r)=>{try{await Ds()}catch(n){r(n)}Ie.delete(e,(n,s)=>{n&&(Ie.disconnect(),r(n)),Ie.disconnect(),t(s)})})}a(t8,"deleteProcess");async function JM(){await Si(mi.generateRestart())}a(JM,"restartHdb");async function r8(){let e=await CT();for(let t in e)if(e[t].name===Ue.PROCESS_DESCRIPTORS.RESTART_HDB)return!0;return!1}a(r8,"isHdbRestartRunning");function CT(){return new Promise(async(e,t)=>{try{await Ds()}catch(r){t(r)}Ie.list((r,n)=>{r&&(Ie.disconnect(),t(r)),Ie.disconnect(),e(n)})})}a(CT,"list");function XM(e){return new Promise(async(t,r)=>{try{await Ds()}catch(n){r(n)}Ie.describe(e,(n,s)=>{n&&(Ie.disconnect(),r(n)),Ie.disconnect(),t(s)})})}a(XM,"describe");function n8(){if(!wl){for(let e of br||[])e.kill();br=[];return}return new Promise(async(e,t)=>{try{await Ds()}catch(r){t(r)}Ie.killDaemon((r,n)=>{r&&(Ie.disconnect(),t(r)),Ie.disconnect(),e(n)})})}a(n8,"kill");async function s8(){try{await rP(),await nP(),await Si(mi.generateAllServiceConfigs())}catch(e){throw Ie?.disconnect(),e}}a(s8,"startAllServices");async function DT(e,t=!1){try{let r;switch(e=e.toLowerCase(),e){case Ue.PROCESS_DESCRIPTORS.HDB.toLowerCase():r=mi.generateMainServerConfig();break;case Ue.PROCESS_DESCRIPTORS.CLUSTERING_INGEST_SERVICE.toLowerCase():r=mi.generateNatsIngestServiceConfig();break;case Ue.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE.toLowerCase():r=mi.generateNatsReplyServiceConfig();break;case Ue.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase():r=mi.generateNatsHubServerConfig(),await Si(r,t),await Cs.removeNatsConfig(e);return;case Ue.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase():r=mi.generateNatsLeafServerConfig(),await Si(r,t),await Cs.removeNatsConfig(e);return;case Ue.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0.toLowerCase():r=mi.generateClusteringUpgradeV4ServiceConfig();break;default:throw new Error(`Start service called with unknown service config: ${e}`)}await Si(r)}catch(r){throw Ie?.disconnect(),r}}a(DT,"startService");async function jM(){try{let e=await CT(),t={};for(let r=0,n=e.length;r<n;r++){let s=e[r];t[s.name]===void 0&&(t[s.name]={name:s.name,exec_mode:s.pm2_env.exec_mode})}return t}catch(e){throw Ie?.disconnect(),e}}a(jM,"getUniqueServicesList");async function i8(e=[]){try{let t=!1,r=await jM();for(let n=0,s=Object.values(r).length;n<s;n++){let o=Object.values(r)[n].name;e.includes(o)||(o===Ue.PROCESS_DESCRIPTORS.HDB?t=!0:await zM(o))}t&&await eP(Ue.PROCESS_DESCRIPTORS.HDB)}catch(t){throw Ie?.disconnect(),t}}a(i8,"restartAllServices");async function ZM(e){if(br?.find(r=>r.name===e))return!0;let t=await Q5.getHDBProcessInfo();return t.core.length&&t.core[0]?.parent==="PM2"}a(ZM,"isServiceRegistered");async function eP(e){let t=Jd.get(Ue.CONFIG_PARAMS.THREADS_COUNT)??Jd.get(Ue.CONFIG_PARAMS.THREADS),r=await XM(e),n=Y5.isEmptyOrZeroLength(r)?0:r.length;t!==n?(await wT(e),await DT(e)):e===Ue.PROCESS_DESCRIPTORS.HDB?await JM():await QM(e)}a(eP,"reloadStopStart");var tP;async function rP(e=!1){for(let t in Ue.CLUSTERING_PROCESSES){let r=Ue.CLUSTERING_PROCESSES[t];await DT(r,e)}}a(rP,"startClusteringProcesses");async function nP(){tP=KM(Ue.LAUNCH_SERVICE_SCRIPTS.NATS_REPLY_SERVICE,{name:Ue.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE});try{await zd.deleteLocalStream("__HARPERDB_WORK_QUEUE__")}catch{}await zd.updateLocalStreams();let e=await K5.getAllNodeRecords();for(let t=0,r=e.length;t<r;t++)if(e[t].system_info?.hdb_version===Ue.PRE_4_0_0_VERSION){pi.info("Starting clustering upgrade 4.0.0 process"),KM(Ue.LAUNCH_SERVICE_SCRIPTS.NODES_UPGRADE_4_0_0,{name:"Upgrade-4-0-0"});break}}a(nP,"startClusteringThreads");async function o8(){for(let e in Ue.CLUSTERING_PROCESSES)if(e!==Ue.CLUSTERING_PROCESSES.CLUSTERING_INGEST_PROC_DESCRIPTOR)if(e===Ue.CLUSTERING_PROCESSES.CLUSTERING_REPLY_SERVICE_DESCRIPTOR)await tP.terminate();else{let t=Ue.CLUSTERING_PROCESSES[e];await wT(t)}}a(o8,"stopClustering");async function a8(){for(let e in Ue.CLUSTERING_PROCESSES){let t=Ue.CLUSTERING_PROCESSES[e];if(await ZM(t)===!1)return!1}return!0}a(a8,"isClusteringRunning");async function c8(){await Cs.generateNatsConfig(!0),await zd.reloadNATSHub(),await zd.reloadNATSLeaf(),await Cs.removeNatsConfig(Ue.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase()),await Cs.removeNatsConfig(Ue.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())}a(c8,"reloadClustering")});var dP={};qe(dP,{compactOnStart:()=>l8,copyDb:()=>_P});async function l8(){Dl.notify("Running compact on start"),console.log("Running compact on start");let e=(0,LT.get)(Ti.CONFIG_PARAMS.ROOTPATH),t=new Map,r=mr();try{for(let n in r){if(n==="system")continue;let s;for(let l in r[n]){s=r[n][l].primaryStore.path;break}if(!s){console.log("Couldn't find any tables in database",n);continue}let i=(0,Xd.join)(e,"backup",n+".mdb"),o=(0,Xd.join)(e,Ti.DATABASES_DIR_NAME,n+"-copy.mdb"),c=await oP(n);console.log("Database",n,"before compact has a total record count of",c),t.set(n,{db_path:s,copy_dest:o,backup_dest:i,record_count:c}),await _P(n,o),console.log("Backing up",n,"to",i),await(0,lo.move)(s,i,{overwrite:!0})}Cl();for(let[n,{db_path:s,copy_dest:i}]of t)console.log("Moving copy compacted",n,"to",s),await(0,lo.move)(i,s,{overwrite:!0}),await(0,lo.remove)((0,Xd.join)(e,Ti.DATABASES_DIR_NAME,`${n}-copy.mdb-lock`));Cl()}catch(n){Dl.error("Error compacting database, rolling back operation",n),console.error("Error compacting database, rolling back operation",n),(0,MT.updateConfigValue)(Ti.CONFIG_PARAMS.STORAGE_COMPACTONSTART,!1);for(let[s,{db_path:i,backup_dest:o}]of t){console.error("Moving backup database",o,"back to",i);try{await(0,lo.move)(o,i,{overwrite:!0})}catch(c){console.error(c)}}throw Cl(),n}for(let[n,{backup_dest:s,record_count:i}]of t){let o=!0,c=await oP(n);if(console.log("Database",n,"after compact has a total record count of",c),i!==c){o=!1;let l=`There is a discrepancy between pre and post compact record count for database ${n}.
1
+ "use strict";var VV=Object.create;var Ql=Object.defineProperty;var $V=Object.getOwnPropertyDescriptor;var YV=Object.getOwnPropertyNames;var KV=Object.getPrototypeOf,WV=Object.prototype.hasOwnProperty;var a=(e,t)=>Ql(e,"name",{value:t,configurable:!0});var Oe=(e,t)=>()=>(e&&(t=e(e=0)),t);var I=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Ze=(e,t)=>{for(var r in t)Ql(e,r,{get:t[r],enumerable:!0})},xO=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of YV(t))!WV.call(e,s)&&s!==r&&Ql(e,s,{get:()=>t[s],enumerable:!(n=$V(t,s))||n.enumerable});return e};var U=(e,t,r)=>(r=e!=null?VV(KV(e)):{},xO(t||!e||!e.__esModule?Ql(r,"default",{value:e,enumerable:!0}):r,e)),ae=e=>xO(Ql({},"__esModule",{value:!0}),e);var kO=I((Fde,HO)=>{var QV=require("fast-glob"),{statSync:$p,existsSync:Yp,readFileSync:zV,writeFileSync:jV}=require("fs"),{spawnSync:JV,spawn:XV,execFileSync:kde}=require("child_process"),{isMainThread:ZV}=require("worker_threads"),{join:Wi,relative:BO}=require("path"),{PACKAGE_ROOT:as}=H(),{tmpdir:e$,platform:t$}=require("os");require("source-map-support").install();var r$=["resources","server","dataLayer","components"],zl="ts-build",Kp,n$=__filename.endsWith("tsBuild.js");if(n$){if(ZV){let r;try{$p(Wi(as,zl)),r=!0}catch{}if(r)for(let n of QV.sync(r$.map(s=>s+"/**/*.ts"),{cwd:as})){let s=0,i=0;try{s=$p(Wi(as,n)).mtimeMs-5e3,i=$p(Wi(as,zl,n.replace(/.ts$/,".js"))).mtimeMs}catch{}if(s>i){console.warn(`TypeScript ${n} is not compiled`+(i?` (TS source file was modified at ${new Date(s)} and compiled file at ${new Date(i)})`:"")+", consider enabling auto-compilation of TypeScript in your IDE), compiling now."),Kp=!0;break}}else console.log("TypeScript modules are not compiled, compiling now"),Kp=!0;if(Kp){let n=Wi(as,"node_modules/.bin/tsc");t$()==="win32"&&(n+=".cmd");let s=JV(n,{cwd:as});if(s.stdout?.length&&console.log(s.stdout.toString()),s.stderr?.length&&console.log(s.stderr.toString()),r){let i=Wi(e$(),"harperdb-tsc.pid"),o;if(Yp(i))try{process.kill(+zV(i,{encoding:"utf8"}),0),o=!0}catch{}if(!o){console.log("starting tsc background process");let c=XV(n,["--watch"],{cwd:as,detached:!0,stdio:"ignore"});jV(i,c.pid.toString()),c.unref()}}}}let e=HO.constructor,t=e._findPath;e._findPath=function(r,n,s){if(r.startsWith(".")&&!s&&n.length===1&&n[0].startsWith(as)&&!n[0].includes("node_modules")){let i=BO(as,n[0]),o;i.startsWith(zl)?o=Wi(as,BO(zl,i)):o=Wi(as,zl,i);let c=Wi(o,r),l=c+".js";if(Yp(l))return l;if(c.includes(".")&&Yp(c))return c}return t(r,n,s)}}});var H=I((Vde,ZO)=>{"use strict";var Hn=require("path"),s$=require("fs"),{relative:Gde,join:qde}=Hn,{existsSync:i$}=s$;function o$(){let e=__dirname;for(;!i$(Hn.join(e,"package.json"));){let t=Hn.dirname(e);if(t===e)throw new Error("Could not find package root");e=t}return e}a(o$,"getHDBPackageRoot");var Qi=o$(),FO="js",s_=FO,a$="harperdb-config.yaml",c$="defaultConfig.yaml",l$="hdb",GO=`harperdb.${s_}`,qO=`customFunctionsServer.${s_}`,u$=`restartHdb.${s_}`,Qp="HarperDB",n_="Custom Functions",i_="Clustering Hub",o_="Clustering Leaf",d$="Clustering Ingest Service",f$="Clustering Reply Service",_$="foreground.pid",E$="hdb.pid",h$="data",m$={HDB:Qp,CLUSTERING_HUB:i_,CLUSTERING_LEAF:o_,CLUSTERING_INGEST_SERVICE:d$,CLUSTERING_REPLY_SERVICE:f$,CUSTOM_FUNCTIONS:n_,RESTART_HDB:"Restart HDB",INSTALL:"Install",RUN:"Run",STOP:"Stop",UPGRADE:"Upgrade",REGISTER:"Register",JOB:"Job",CLUSTERING_UPGRADE_4_0_0:"Upgrade-4-0-0"},p$={HDB:"hdb.log",INSTALL:"install.log",CLUSTERING_HUB:"clustering_hub.log",CLUSTERING_LEAF:"clustering_leaf.log"},S$={NOTIFY:"notify",FATAL:"fatal",ERROR:"error",WARN:"warn",INFO:"info",DEBUG:"debug",TRACE:"trace"},T$={harperdb:Qp,"clustering hub":i_,"clustering leaf":o_,"custom functions":n_,custom_functions:n_,clustering:"clustering","clustering config":"clustering config",clustering_config:"clustering_config",http_workers:"http_workers",http:"http"},g$={CLUSTERING_HUB_PROC_DESCRIPTOR:i_,CLUSTERING_LEAF_PROC_DESCRIPTOR:o_},Wp={HDB:Hn.join(Qi,"server/harperdb"),CUSTOM_FUNCTIONS:Hn.join(Qi,"server/customFunctions"),CLUSTERING_HUB:Hn.join(Qi,"server/nats"),CLUSTERING_LEAF:Hn.join(Qi,"server/nats")},R$={HDB:Hn.join(Wp.HDB,GO),CUSTOM_FUNCTIONS:Hn.join(Wp.CUSTOM_FUNCTIONS,qO)},A$={MAIN:"bin/harperdb.js",NATS_INGEST_SERVICE:Hn.join(Qi,"launchServiceScripts/launchNatsIngestService.js"),NATS_REPLY_SERVICE:Hn.join(Qi,"launchServiceScripts/launchNatsReplyService.js"),NODES_UPGRADE_4_0_0:Hn.join(Qi,"launchServiceScripts/launchUpdateNodes4-0-0.js")},b$={SUPER_USER:"super_user",CLUSTER_USER:"cluster_user"},VO="support@harperdb.io",y$="customer-success@harperdb.io",$O=1,O$=4141,YO="https://harperdbhelp.zendesk.com/hc/en-us/requests/new",N$="https://www.harperdb.io/product",I$=`For support, please submit a request at ${YO} or contact ${VO}`,KO=`For license support, please contact ${y$}`,w$="None of the specified records were found.",C$="hash attribute not found",D$=`Your current license only supports ${$O} role. ${KO}`,L$="Your current license only supports 3 connections to a node.",P$="127.0.0.1",M$=1,U$=/^\.$/,v$=/^\.\.$/,x$="U+002E",B$=/\//g,H$="U+002F",k$=/U\+002F/g,F$=/^U\+002E$/,G$=/^U\+002EU\+002E$/,q$="d",V$=999999,$$="*",Y$="--max-old-space-size=",K$="system",W$="__hdb_hash",Q$=".harperdb",z$=".hdb",j$="keys",J$="hdb_boot_properties.file",X$=".updateConfig.json",Z$="SIGTSTP",e1=24,t1=6e4,r1=448,n1="blob",s1="trash",i1="database",o1="schema",a1="transactions",c1=".count",l1="id",u1="PROCESS_NAME",WO={SETTINGS_PATH_KEY:"settings_path"},QO=require("lodash"),d1={TC_AGREEMENT:"TC_AGREEMENT",CLUSTERING_USER:"CLUSTERING_USER",CLUSTERING_PASSWORD:"CLUSTERING_PASSWORD",HDB_ADMIN_USERNAME:"HDB_ADMIN_USERNAME",HDB_ADMIN_PASSWORD:"HDB_ADMIN_PASSWORD",OPERATIONSAPI_ROOT:"OPERATIONSAPI_ROOT",ROOTPATH:"ROOTPATH",CLUSTERING_NODENAME:"CLUSTERING_NODENAME",CLUSTERING_ENABLED:"CLUSTERING_ENABLED",HDB_CONFIG:"HDB_CONFIG",DEFAULTS_MODE:"DEFAULTS_MODE",REPLICATION_HOSTNAME:"REPLICATION_HOSTNAME",CLUSTERING_PORT:"CLUSTERING_PORT",HDB_ROOT:"HDB_ROOT",SERVER_PORT:"SERVER_PORT",NODE_NAME:"NODE_NAME",CLUSTERING:"CLUSTERING"},f1={HDB_PATH_KEY:"HDB_INTERNAL_PATH",HDB_AUTH_HEADER:"hdb_auth_header",HDB_USER_DATA_KEY:"hdb_user",CHUNK_SIZE:1e3,MAX_CHARACTER_SIZE:250},_1={DATA_VERSION:"data_version",UPGRADE_VERSION:"upgrade_version"},E1={JOB_TABLE_NAME:"hdb_job",NODE_TABLE_NAME:"hdb_nodes",ATTRIBUTE_TABLE_NAME:"hdb_attribute",LICENSE_TABLE_NAME:"hdb_license",ROLE_TABLE_NAME:"hdb_role",SCHEMA_TABLE_NAME:"hdb_schema",TABLE_TABLE_NAME:"hdb_table",USER_TABLE_NAME:"hdb_user",INFO_TABLE_NAME:"hdb_info"},h1={JOB_TABLE_HASH_ATTRIBUTE:"id",NODE_TABLE_HASH_ATTRIBUTE:"name",ATTRIBUTE_TABLE_HASH_ATTRIBUTE:"id",LICENSE_TABLE_HASH_ATTRIBUTE:"license_key",ROLE_TABLE_HASH_ATTRIBUTE:"id",SCHEMA_TABLE_HASH_ATTRIBUTE:"name",TABLE_TABLE_HASH_ATTRIBUTE:"id",USER_TABLE_HASH_ATTRIBUTE:"username",INFO_TABLE_ATTRIBUTE:"info_id"},_n="hdb_internal:",m1={CREATE_SCHEMA:_n+"create_schema",CREATE_TABLE:_n+"create_table",CREATE_ATTRIBUTE:_n+"create_attribute",ADD_USER:_n+"add_user",ALTER_USER:_n+"alter_user",DROP_USER:_n+"drop_user",HDB_NODES:_n+"hdb_nodes",HDB_USERS:_n+"hdb_users",HDB_WORKERS:_n+"hdb_workers",CATCHUP:_n+"catchup",SCHEMA_CATCHUP:_n+"schema_catchup",WORKER_ROOM:_n+"cluster_workers"},p1={ATTR_ATTRIBUTE_KEY:"attribute",ATTR_CREATEDDATE_KEY:"createddate",ATTR_HASH_ATTRIBUTE_KEY:"hash_attribute",ATTR_ID_KEY:"id",ATTR_NAME_KEY:"name",ATTR_PASSWORD_KEY:"password",ATTR_RESIDENCE_KEY:"residence",ATTR_ROLE_KEY:"role",ATTR_SCHEMA_KEY:"schema",ATTR_SCHEMA_TABLE_KEY:"schema_table",ATTR_TABLE_KEY:"table",ATTR_USERNAME_KEY:"username"},S1="060493.ks",T1=".license",g1={CREATED:"CREATED",IN_PROGRESS:"IN_PROGRESS",COMPLETE:"COMPLETE",ERROR:"ERROR"},oe={INSERT:"insert",UPDATE:"update",UPSERT:"upsert",SEARCH_BY_CONDITIONS:"search_by_conditions",SEARCH_BY_HASH:"search_by_hash",SEARCH_BY_ID:"search_by_id",SEARCH_BY_VALUE:"search_by_value",SEARCH:"search",SQL:"sql",CSV_DATA_LOAD:"csv_data_load",CSV_FILE_LOAD:"csv_file_load",CSV_URL_LOAD:"csv_url_load",CREATE_SCHEMA:"create_schema",CREATE_DATABASE:"create_database",CREATE_TABLE:"create_table",CREATE_ATTRIBUTE:"create_attribute",DROP_SCHEMA:"drop_schema",DROP_DATABASE:"drop_database",DROP_TABLE:"drop_table",DESCRIBE_SCHEMA:"describe_schema",DESCRIBE_DATABASE:"describe_database",DESCRIBE_TABLE:"describe_table",DESCRIBE_ALL:"describe_all",DELETE:"delete",ADD_USER:"add_user",ALTER_USER:"alter_user",DROP_USER:"drop_user",LIST_USERS:"list_users",LIST_ROLES:"list_roles",ADD_ROLE:"add_role",ALTER_ROLE:"alter_role",DROP_ROLE:"drop_role",USER_INFO:"user_info",READ_LOG:"read_log",ADD_NODE:"add_node",UPDATE_NODE:"update_node",SET_NODE_REPLICATION:"set_node_replication",EXPORT_TO_S3:"export_to_s3",IMPORT_FROM_S3:"import_from_s3",DELETE_FILES_BEFORE:"delete_files_before",DELETE_RECORDS_BEFORE:"delete_records_before",EXPORT_LOCAL:"export_local",SEARCH_JOBS_BY_START_DATE:"search_jobs_by_start_date",GET_JOB:"get_job",DELETE_JOB:"delete_job",UPDATE_JOB:"update_job",GET_FINGERPRINT:"get_fingerprint",SET_LICENSE:"set_license",GET_REGISTRATION_INFO:"registration_info",CONFIGURE_CLUSTER:"configure_cluster",SET_CONFIGURATION:"set_configuration",CLUSTER_STATUS:"cluster_status",CLUSTER_NETWORK:"cluster_network",DROP_ATTRIBUTE:"drop_attribute",REMOVE_NODE:"remove_node",RESTART:"restart",RESTART_SERVICE:"restart_service",CATCHUP:"catchup",SYSTEM_INFORMATION:"system_information",DELETE_AUDIT_LOGS_BEFORE:"delete_audit_logs_before",READ_AUDIT_LOG:"read_audit_log",CREATE_AUTHENTICATION_TOKENS:"create_authentication_tokens",LOGIN:"login",LOGOUT:"logout",REFRESH_OPERATION_TOKEN:"refresh_operation_token",GET_CONFIGURATION:"get_configuration",CUSTOM_FUNCTIONS_STATUS:"custom_functions_status",GET_CUSTOM_FUNCTIONS:"get_custom_functions",GET_CUSTOM_FUNCTION:"get_custom_function",SET_CUSTOM_FUNCTION:"set_custom_function",GET_COMPONENTS:"get_components",GET_COMPONENT_FILE:"get_component_file",SET_COMPONENT_FILE:"set_component_file",DROP_COMPONENT:"drop_component",DROP_CUSTOM_FUNCTION:"drop_custom_function",ADD_CUSTOM_FUNCTION_PROJECT:"add_custom_function_project",ADD_COMPONENT:"add_component",DROP_CUSTOM_FUNCTION_PROJECT:"drop_custom_function_project",PACKAGE_CUSTOM_FUNCTION_PROJECT:"package_custom_function_project",DEPLOY_CUSTOM_FUNCTION_PROJECT:"deploy_custom_function_project",PACKAGE_COMPONENT:"package_component",DEPLOY_COMPONENT:"deploy_component",CLUSTER_SET_ROUTES:"cluster_set_routes",CLUSTER_DELETE_ROUTES:"cluster_delete_routes",CLUSTER_GET_ROUTES:"cluster_get_routes",READ_TRANSACTION_LOG:"read_transaction_log",DELETE_TRANSACTION_LOGS_BEFORE:"delete_transaction_logs_before",INSTALL_NODE_MODULES:"install_node_modules",AUDIT_NODE_MODULES:"audit_node_modules",PURGE_STREAM:"purge_stream",GET_BACKUP:"get_backup",SIGN_CERTIFICATE:"sign_certificate",CREATE_CSR:"create_csr",LIST_CERTIFICATES:"list_certificates",ADD_CERTIFICATES:"add_certificate",REMOVE_CERTIFICATE:"remove_certificate",ADD_NODE_BACK:"add_node_back",REMOVE_NODE_BACK:"remove_node_back",ADD_SSH_KEY:"add_ssh_key",UPDATE_SSH_KEY:"update_ssh_key",DELETE_SSH_KEY:"delete_ssh_key",LIST_SSH_KEYS:"list_ssh_keys",SET_SSH_KNOWN_HOSTS:"set_ssh_known_hosts",GET_SSH_KNOWN_HOSTS:"get_ssh_known_hosts"},R1={CSV:".csv",JSON:".json"},A1={AWS_ACCESS_KEY:"aws_access_key_id",AWS_SECRET:"aws_secret_access_key",AWS_BUCKET:"bucket",AWS_FILE_KEY:"key",REGION:"region"},b1={SELECT:"select",INSERT:"insert",UPDATE:"update",DELETE:"delete"},jl={};jl[oe.INSERT]=oe.INSERT;jl[oe.UPDATE]=oe.UPDATE;jl[oe.UPSERT]=oe.UPSERT;jl[oe.DELETE]=oe.DELETE;var ze=Object.create(null);ze[oe.DESCRIBE_ALL]=oe.DESCRIBE_ALL;ze[oe.DESCRIBE_TABLE]=oe.DESCRIBE_TABLE;ze[oe.DESCRIBE_SCHEMA]=oe.DESCRIBE_SCHEMA;ze[oe.READ_LOG]=oe.READ_LOG;ze[oe.ADD_NODE]=oe.ADD_NODE;ze[oe.LIST_USERS]=oe.LIST_USERS;ze[oe.LIST_ROLES]=oe.LIST_ROLES;ze[oe.USER_INFO]=oe.USER_INFO;ze[oe.SQL]=oe.SQL;ze[oe.GET_JOB]=oe.GET_JOB;ze[oe.SEARCH_JOBS_BY_START_DATE]=oe.SEARCH_JOBS_BY_START_DATE;ze[oe.DELETE_FILES_BEFORE]=oe.DELETE_FILES_BEFORE;ze[oe.EXPORT_LOCAL]=oe.EXPORT_LOCAL;ze[oe.EXPORT_TO_S3]=oe.EXPORT_TO_S3;ze[oe.CLUSTER_STATUS]=oe.CLUSTER_STATUS;ze[oe.REMOVE_NODE]=oe.REMOVE_NODE;ze[oe.RESTART]=oe.RESTART;ze[oe.CUSTOM_FUNCTIONS_STATUS]=oe.CUSTOM_FUNCTIONS_STATUS;ze[oe.GET_CUSTOM_FUNCTIONS]=oe.GET_CUSTOM_FUNCTIONS;ze[oe.GET_CUSTOM_FUNCTION]=oe.GET_CUSTOM_FUNCTION;ze[oe.SET_CUSTOM_FUNCTION]=oe.SET_CUSTOM_FUNCTION;ze[oe.DROP_CUSTOM_FUNCTION]=oe.DROP_CUSTOM_FUNCTION;ze[oe.ADD_CUSTOM_FUNCTION_PROJECT]=oe.ADD_CUSTOM_FUNCTION_PROJECT;ze[oe.DROP_CUSTOM_FUNCTION_PROJECT]=oe.DROP_CUSTOM_FUNCTION_PROJECT;ze[oe.PACKAGE_CUSTOM_FUNCTION_PROJECT]=oe.PACKAGE_CUSTOM_FUNCTION_PROJECT;ze[oe.DEPLOY_CUSTOM_FUNCTION_PROJECT]=oe.DEPLOY_CUSTOM_FUNCTION_PROJECT;ze[oe.ADD_SSH_KEY]=oe.ADD_SSH_KEY;ze[oe.UPDATE_SSH_KEY]=oe.UPDATE_SSH_KEY;ze[oe.DELETE_SSH_KEY]=oe.DELETE_SSH_KEY;var y1={DEV:"dev",RUN:"run",START:"start",INSTALL:"install",REGISTER:"register",STOP:"stop",RESTART:"restart",VERSION:"version",UPGRADE:"upgrade",HELP:"help",STATUS:"status",OPERATION:"operation",RENEWCERTS:"renew-certs",COPYDB:"copy-db"},O1={point:"point",lineString:"lineString",multiLineString:"multiLineString",multiPoint:"multiPoint",multiPolygon:"multiPolygon",polygon:"polygon"},zO={HDB_ROOT_KEY:"HDB_ROOT",SERVER_PORT_KEY:"SERVER_PORT",CERT_KEY:"CERTIFICATE",PRIVATE_KEY_KEY:"PRIVATE_KEY",HTTP_SECURE_ENABLED_KEY:"HTTPS_ON",CORS_ENABLED_KEY:"CORS_ON",CORS_WHITELIST_KEY:"CORS_WHITELIST",LOG_LEVEL_KEY:"LOG_LEVEL",LOGGER_KEY:"LOGGER",LOG_PATH_KEY:"LOG_PATH",LOG_ROTATE:"LOG_ROTATE",LOG_ROTATE_MAX_SIZE:"LOG_ROTATE_MAX_SIZE",LOG_ROTATE_RETAIN:"LOG_ROTATE_RETAIN",LOG_ROTATE_COMPRESS:"LOG_ROTATE_COMPRESS",LOG_ROTATE_DATE_FORMAT:"LOG_ROTATE_DATE_FORMAT",LOG_ROTATE_ROTATE_MODULE:"LOG_ROTATE_ROTATE_MODULE",LOG_ROTATE_WORKER_INTERVAL:"LOG_ROTATE_WORKER_INTERVAL",LOG_ROTATE_ROTATE_INTERVAL:"LOG_ROTATE_ROTATE_INTERVAL",LOG_ROTATE_TIMEZONE:"LOG_ROTATE_TIMEZONE",LOG_DAILY_ROTATE_KEY:"LOG_DAILY_ROTATE",LOG_MAX_DAILY_FILES_KEY:"LOG_MAX_DAILY_FILES",PROPS_ENV_KEY:"NODE_ENV",SETTINGS_PATH_KEY:"settings_path",CLUSTERING_PORT_KEY:"CLUSTERING_PORT",CLUSTERING_NODE_NAME_KEY:"NODE_NAME",CLUSTERING_ENABLED_KEY:"CLUSTERING",ALLOW_SELF_SIGNED_SSL_CERTS:"ALLOW_SELF_SIGNED_SSL_CERTS",MAX_HDB_PROCESSES:"MAX_HDB_PROCESSES",INSTALL_USER:"install_user",CLUSTERING_USER_KEY:"CLUSTERING_USER",MAX_CLUSTERING_PROCESSES:"MAX_CLUSTERING_PROCESSES",SERVER_TIMEOUT_KEY:"SERVER_TIMEOUT_MS",SERVER_KEEP_ALIVE_TIMEOUT_KEY:"SERVER_KEEP_ALIVE_TIMEOUT",SERVER_HEADERS_TIMEOUT_KEY:"SERVER_HEADERS_TIMEOUT",DISABLE_TRANSACTION_LOG_KEY:"DISABLE_TRANSACTION_LOG",OPERATION_TOKEN_TIMEOUT_KEY:"OPERATION_TOKEN_TIMEOUT",REFRESH_TOKEN_TIMEOUT_KEY:"REFRESH_TOKEN_TIMEOUT",CUSTOM_FUNCTIONS_ENABLED_KEY:"CUSTOM_FUNCTIONS",CUSTOM_FUNCTIONS_PORT_KEY:"CUSTOM_FUNCTIONS_PORT",CUSTOM_FUNCTIONS_DIRECTORY_KEY:"CUSTOM_FUNCTIONS_DIRECTORY",MAX_CUSTOM_FUNCTION_PROCESSES:"MAX_CUSTOM_FUNCTION_PROCESSES",LOG_TO_FILE:"LOG_TO_FILE",LOG_TO_STDSTREAMS:"LOG_TO_STDSTREAMS",RUN_IN_FOREGROUND:"RUN_IN_FOREGROUND",LOCAL_STUDIO_ON:"LOCAL_STUDIO_ON",STORAGE_WRITE_ASYNC:"STORAGE_WRITE_ASYNC"},N1=QO.invert(zO),I1={CUSTOMFUNCTIONS_ENABLED:"customFunctions_enabled",CUSTOMFUNCTIONS_NETWORK_PORT:"customFunctions_network_port",CUSTOMFUNCTIONS_TLS_CERTIFICATE:"customFunctions_tls_certificate",CUSTOMFUNCTIONS_NETWORK_CORS:"customFunctions_network_cors",CUSTOMFUNCTIONS_NETWORK_CORSACCESSLIST:"customFunctions_network_corsAccessList",CUSTOMFUNCTIONS_NETWORK_HEADERSTIMEOUT:"customFunctions_network_headersTimeout",CUSTOMFUNCTIONS_NETWORK_HTTPS:"customFunctions_network_https",CUSTOMFUNCTIONS_NETWORK_KEEPALIVETIMEOUT:"customFunctions_network_keepAliveTimeout",CUSTOMFUNCTIONS_TLS_PRIVATEKEY:"customFunctions_tls_privateKey",CUSTOMFUNCTIONS_TLS_CERT_AUTH:"customFunctions_tls_certificateAuthority",CUSTOMFUNCTIONS_NETWORK_TIMEOUT:"customFunctions_network_timeout",CUSTOMFUNCTIONS_NODEENV:"customFunctions_nodeEnv",CUSTOMFUNCTIONS_ROOT:"customFunctions_root"},D={ANALYTICS_AGGREGATEPERIOD:"analytics_aggregatePeriod",AUTHENTICATION_AUTHORIZELOCAL:"authentication_authorizeLocal",AUTHENTICATION_CACHETTL:"authentication_cacheTTL",AUTHENTICATION_ENABLESESSIONS:"authentication_enableSessions",AUTHENTICATION_OPERATIONTOKENTIMEOUT:"authentication_operationTokenTimeout",AUTHENTICATION_REFRESHTOKENTIMEOUT:"authentication_refreshTokenTimeout",CLUSTERING_USER:"clustering_user",CLUSTERING_ENABLED:"clustering_enabled",CLUSTERING_HUBSERVER_CLUSTER_NAME:"clustering_hubServer_cluster_name",CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT:"clustering_hubServer_cluster_network_port",CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES:"clustering_hubServer_cluster_network_routes",CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT:"clustering_hubServer_leafNodes_network_port",CLUSTERING_HUBSERVER_NETWORK_PORT:"clustering_hubServer_network_port",CLUSTERING_LEAFSERVER_NETWORK_PORT:"clustering_leafServer_network_port",CLUSTERING_LEAFSERVER_NETWORK_ROUTES:"clustering_leafServer_network_routes",CLUSTERING_LEAFSERVER_STREAMS_MAXAGE:"clustering_leafServer_streams_maxAge",CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES:"clustering_leafServer_streams_maxBytes",CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS:"clustering_leafServer_streams_maxMsgs",CLUSTERING_LEAFSERVER_STREAMS_MAXCONSUMEMSGS:"clustering_leafServer_streams_maxConsumeMsgs",CLUSTERING_LEAFSERVER_STREAMS_MAXINGESTTHREADS:"clustering_leafServer_streams_maxIngestThreads",CLUSTERING_LEAFSERVER_STREAMS_PATH:"clustering_leafServer_streams_path",CLUSTERING_NODENAME:"clustering_nodeName",CLUSTERING_TLS_CERTIFICATE:"clustering_tls_certificate",CLUSTERING_TLS_PRIVATEKEY:"clustering_tls_privateKey",CLUSTERING_TLS_CERT_AUTH:"clustering_tls_certificateAuthority",CLUSTERING_TLS_INSECURE:"clustering_tls_insecure",CLUSTERING_TLS_VERIFY:"clustering_tls_verify",CLUSTERING_LOGLEVEL:"clustering_logLevel",CLUSTERING_REPUBLISHMESSAGES:"clustering_republishMessages",CLUSTERING_DATABASELEVEL:"clustering_databaseLevel",CUSTOMFUNCTIONS_NETWORK_HTTPS:"customFunctions_network_https",THREADS:"threads",THREADS_COUNT:"threads_count",THREADS_DEBUG:"threads_debug",THREADS_DEBUG_STARTINGPORT:"threads_debug_startingPort",THREADS_DEBUG_PORT:"threads_debug_port",THREADS_DEBUG_HOST:"threads_debug_host",THREADS_DEBUG_WAITFORDEBUGGER:"threads_debug_waitForDebugger",THREADS_MAXHEAPMEMORY:"threads_maxHeapMemory",HTTP_SESSIONAFFINITY:"http_sessionAffinity",HTTP_COMPRESSIONTHRESHOLD:"http_compressionThreshold",HTTP_CORS:"http_cors",HTTP_CORSACCESSLIST:"http_corsAccessList",HTTP_HEADERSTIMEOUT:"http_headersTimeout",HTTP_KEEPALIVETIMEOUT:"http_keepAliveTimeout",HTTP_TIMEOUT:"http_timeout",HTTP_PORT:"http_port",HTTP_SECUREPORT:"http_securePort",HTTP_MTLS:"http_mtls",HTTP_MTLS_REQUIRED:"http_mtls_required",HTTP_MTLS_USER:"http_mtls_user",HTTP_MAXHEADERSIZE:"http_maxHeaderSize",HTTP_THREADRANGE:"http_threadRange",LOCALSTUDIO_ENABLED:"localStudio_enabled",LOGGING_FILE:"logging_file",LOGGING_LEVEL:"logging_level",LOGGING_ROOT:"logging_root",LOGGING_ROTATION_ENABLED:"logging_rotation_enabled",LOGGING_ROTATION_COMPRESS:"logging_rotation_compress",LOGGING_ROTATION_INTERVAL:"logging_rotation_interval",LOGGING_ROTATION_MAXSIZE:"logging_rotation_maxSize",LOGGING_ROTATION_PATH:"logging_rotation_path",LOGGING_STDSTREAMS:"logging_stdStreams",LOGGING_AUDITLOG:"logging_auditLog",LOGGING_AUDITRETENTION:"logging_auditRetention",LOGGING_AUDITAUTHEVENTS_LOGFAILED:"logging_auditAuthEvents_logFailed",LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL:"logging_auditAuthEvents_logSuccessful",OPERATIONSAPI_NETWORK_CORS:"operationsApi_network_cors",OPERATIONSAPI_NETWORK_CORSACCESSLIST:"operationsApi_network_corsAccessList",OPERATIONSAPI_NETWORK_HEADERSTIMEOUT:"operationsApi_network_headersTimeout",OPERATIONSAPI_NETWORK_HTTPS:"operationsApi_network_https",OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT:"operationsApi_network_keepAliveTimeout",OPERATIONSAPI_NETWORK_PORT:"operationsApi_network_port",OPERATIONSAPI_NETWORK_DOMAINSOCKET:"operationsApi_network_domainSocket",OPERATIONSAPI_NETWORK_SECUREPORT:"operationsApi_network_securePort",OPERATIONSAPI_TLS:"operationsApi_tls",OPERATIONSAPI_TLS_CERTIFICATE:"operationsApi_tls_certificate",OPERATIONSAPI_TLS_PRIVATEKEY:"operationsApi_tls_privateKey",OPERATIONSAPI_TLS_CERTIFICATEAUTHORITY:"operationsApi_tls_certificateAuthority",OPERATIONSAPI_NETWORK_TIMEOUT:"operationsApi_network_timeout",REPLICATION:"replication",REPLICATION_HOSTNAME:"replication_hostname",REPLICATION_URL:"replication_url",REPLICATION_PORT:"replication_port",REPLICATION_SECUREPORT:"replication_securePort",REPLICATION_ROUTES:"replication_routes",REPLICATION_DATABASES:"replication_databases",ROOTPATH:"rootPath",SERIALIZATION_BIGINT:"serialization_bigInt",STORAGE_WRITEASYNC:"storage_writeAsync",STORAGE_OVERLAPPINGSYNC:"storage_overlappingSync",STORAGE_CACHING:"storage_caching",STORAGE_COMPRESSION:"storage_compression",STORAGE_NOREADAHEAD:"storage_noReadAhead",STORAGE_PREFETCHWRITES:"storage_prefetchWrites",STORAGE_ENCRYPTION:"storage_encryption",STORAGE_MAXTRANSACTIONQUEUETIME:"storage_maxTransactionQueueTime",STORAGE_PATH:"storage_path",STORAGE_AUDIT_PATH:"storage_audit_path",STORAGE_MAXFREESPACETOLOAD:"storage_maxFreeSpaceToLoad",STORAGE_MAXFREESPACETORETAIN:"storage_maxFreeSpaceToRetain",STORAGE_PAGESIZE:"storage_pageSize",STORAGE_COMPRESSION_DICTIONARY:"storage_compression_dictionary",STORAGE_COMPRESSION_THRESHOLD:"storage_compression_threshold",STORAGE_COMPACTONSTART:"storage_compactOnStart",STORAGE_COMPACTONSTARTKEEPBACKUP:"storage_compactOnStartKeepBackup",DATABASES:"databases",IGNORE_SCRIPTS:"ignoreScripts",MQTT_NETWORK_PORT:"mqtt_network_port",MQTT_WEBSOCKET:"mqtt_webSocket",MQTT_NETWORK_SECUREPORT:"mqtt_network_securePort",MQTT_NETWORK_MTLS:"mqtt_network_mtls",MQTT_NETWORK_MTLS_REQUIRED:"mqtt_network_mtls_required",MQTT_NETWORK_MTLS_CERTIFICATEAUTHORITY:"mqtt_network_mtls_certificateAuthority",MQTT_NETWORK_MTLS_USER:"mqtt_network_mtls_user",MQTT_REQUIREAUTHENTICATION:"mqtt_requireAuthentication",COMPONENTSROOT:"componentsRoot",TLS_CERTIFICATE:"tls_certificate",TLS_PRIVATEKEY:"tls_privateKey",TLS_CERTIFICATEAUTHORITY:"tls_certificateAuthority",TLS_CIPHERS:"tls_ciphers",TLS:"tls",CLONED:"cloned"},jO={settings_path:WO.SETTINGS_PATH_KEY,hdb_root_key:D.ROOTPATH,hdb_root:D.ROOTPATH,rootpath:D.ROOTPATH,server_port_key:D.OPERATIONSAPI_NETWORK_PORT,server_port:D.OPERATIONSAPI_NETWORK_PORT,cert_key:D.TLS_CERTIFICATE,certificate:D.TLS_CERTIFICATE,private_key_key:D.TLS_PRIVATEKEY,private_key:D.TLS_PRIVATEKEY,http_secure_enabled_key:D.OPERATIONSAPI_NETWORK_HTTPS,https_on:D.OPERATIONSAPI_NETWORK_HTTPS,cors_enabled_key:D.OPERATIONSAPI_NETWORK_CORS,cors_on:D.OPERATIONSAPI_NETWORK_CORS,cors_whitelist_key:D.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_whitelist:D.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_accesslist_key:D.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_accesslist:D.OPERATIONSAPI_NETWORK_CORSACCESSLIST,log_level_key:D.LOGGING_LEVEL,log_level:D.LOGGING_LEVEL,log_path_key:D.LOGGING_ROOT,log_path:D.LOGGING_ROOT,clustering_node_name_key:D.CLUSTERING_NODENAME,node_name:D.CLUSTERING_NODENAME,clustering_enabled_key:D.CLUSTERING_ENABLED,clustering:D.CLUSTERING_ENABLED,max_http_threads:D.THREADS_COUNT,max_hdb_processes:D.THREADS_COUNT,server_timeout_key:D.OPERATIONSAPI_NETWORK_TIMEOUT,server_timeout_ms:D.OPERATIONSAPI_NETWORK_TIMEOUT,server_keep_alive_timeout_key:D.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT,server_keep_alive_timeout:D.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT,server_headers_timeout_key:D.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT,server_headers_timeout:D.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT,disable_transaction_log_key:D.LOGGING_AUDITLOG,disable_transaction_log:D.LOGGING_AUDITLOG,operation_token_timeout_key:D.AUTHENTICATION_OPERATIONTOKENTIMEOUT,operation_token_timeout:D.AUTHENTICATION_OPERATIONTOKENTIMEOUT,refresh_token_timeout_key:D.AUTHENTICATION_REFRESHTOKENTIMEOUT,refresh_token_timeout:D.AUTHENTICATION_REFRESHTOKENTIMEOUT,custom_functions_port_key:D.HTTP_PORT,custom_functions_port:D.HTTP_PORT,custom_functions_directory_key:D.COMPONENTSROOT,custom_functions_directory:D.COMPONENTSROOT,max_custom_function_processes:D.THREADS_COUNT,log_to_file:D.LOGGING_FILE,log_to_stdstreams:D.LOGGING_STDSTREAMS,local_studio_on:D.LOCALSTUDIO_ENABLED,clustering_port:D.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT,clustering_user:D.CLUSTERING_USER,clustering_enabled:D.CLUSTERING_ENABLED,clustering_hubserver_cluster_name:D.CLUSTERING_HUBSERVER_CLUSTER_NAME,clustering_hubserver_cluster_network_port:D.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT,clustering_hubserver_cluster_network_routes:D.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,clustering_hubserver_leafnodes_network_port:D.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT,clustering_hubserver_network_port:D.CLUSTERING_HUBSERVER_NETWORK_PORT,clustering_leafserver_network_port:D.CLUSTERING_LEAFSERVER_NETWORK_PORT,clustering_leafserver_network_routes:D.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,clustering_leafserver_streams_maxage:D.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE,clustering_leafserver_streams_maxbytes:D.CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES,clustering_leafserver_streams_maxconsumemsgs:D.CLUSTERING_LEAFSERVER_STREAMS_MAXCONSUMEMSGS,clustering_leafserver_streams_maxingestthreads:D.CLUSTERING_LEAFSERVER_STREAMS_MAXINGESTTHREADS,clustering_leafserver_streams_maxmsgs:D.CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS,clustering_leafserver_streams_path:D.CLUSTERING_LEAFSERVER_STREAMS_PATH,clustering_nodename:D.CLUSTERING_NODENAME,clustering_tls_certificate:D.CLUSTERING_TLS_CERTIFICATE,clustering_tls_privatekey:D.CLUSTERING_TLS_PRIVATEKEY,clustering_tls_certificateauthority:D.CLUSTERING_TLS_CERT_AUTH,clustering_tls_insecure:D.CLUSTERING_TLS_INSECURE,clustering_tls_verify:D.CLUSTERING_TLS_VERIFY,clustering_loglevel:D.CLUSTERING_LOGLEVEL,clustering_republishmessages:D.CLUSTERING_REPUBLISHMESSAGES,clustering_databaselevel:D.CLUSTERING_DATABASELEVEL,customfunctions_network_port:D.HTTP_PORT,customfunctions_tls_certificate:D.TLS_CERTIFICATE,customfunctions_network_cors:D.HTTP_CORS,customfunctions_network_corsaccesslist:D.HTTP_CORSACCESSLIST,customfunctions_network_headerstimeout:D.HTTP_HEADERSTIMEOUT,customfunctions_network_https:D.CUSTOMFUNCTIONS_NETWORK_HTTPS,customfunctions_network_keepalivetimeout:D.HTTP_KEEPALIVETIMEOUT,customfunctions_tls_privatekey:D.TLS_PRIVATEKEY,customfunctions_tls_certificateauthority:D.TLS_CERTIFICATEAUTHORITY,customfunctions_network_timeout:D.HTTP_TIMEOUT,customfunctions_tls:D.TLS,http_threads:D.THREADS_COUNT,threads:D.THREADS_COUNT,threads_count:D.THREADS_COUNT,threads_debug:D.THREADS_DEBUG,threads_debug_startingport:D.THREADS_DEBUG_STARTINGPORT,threads_debug_port:D.THREADS_DEBUG_PORT,threads_debug_host:D.THREADS_DEBUG_HOST,threads_debug_waitfordebugger:D.THREADS_DEBUG_WAITFORDEBUGGER,threads_maxheapmemory:D.THREADS_MAXHEAPMEMORY,http_session_affinity:D.HTTP_SESSIONAFFINITY,http_compressionthreshold:D.HTTP_COMPRESSIONTHRESHOLD,http_cors:D.HTTP_CORS,http_corsaccesslist:D.HTTP_CORSACCESSLIST,http_headerstimeout:D.HTTP_HEADERSTIMEOUT,http_keepalivetimeout:D.HTTP_KEEPALIVETIMEOUT,http_timeout:D.HTTP_TIMEOUT,http_port:D.HTTP_PORT,http_secureport:D.HTTP_SECUREPORT,http_mtls:D.HTTP_MTLS,http_mtls_user:D.HTTP_MTLS_USER,http_mtls_required:D.HTTP_MTLS_REQUIRED,http_maxheadersize:D.HTTP_MAXHEADERSIZE,http_threadrange:D.HTTP_THREADRANGE,customfunctions_processes:D.THREADS_COUNT,customfunctions_root:D.COMPONENTSROOT,localstudio_enabled:D.LOCALSTUDIO_ENABLED,logging_file:D.LOGGING_FILE,logging_level:D.LOGGING_LEVEL,logging_root:D.LOGGING_ROOT,logging_rotation_enabled:D.LOGGING_ROTATION_ENABLED,logging_rotation_compress:D.LOGGING_ROTATION_COMPRESS,logging_rotation_interval:D.LOGGING_ROTATION_INTERVAL,logging_rotation_maxsize:D.LOGGING_ROTATION_MAXSIZE,logging_rotation_path:D.LOGGING_ROTATION_PATH,logging_stdstreams:D.LOGGING_STDSTREAMS,logging_auditlog:D.LOGGING_AUDITLOG,logging_auditretention:D.LOGGING_AUDITRETENTION,logging_auditauthevents_logfailed:D.LOGGING_AUDITAUTHEVENTS_LOGFAILED,logging_auditauthevents_logsuccessful:D.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL,operationsapi_authentication_operationtokentimeout:D.AUTHENTICATION_OPERATIONTOKENTIMEOUT,operationsapi_authentication_refreshtokentimeout:D.AUTHENTICATION_REFRESHTOKENTIMEOUT,operationsapi_network_cors:D.OPERATIONSAPI_NETWORK_CORS,operationsapi_network_corsaccesslist:D.OPERATIONSAPI_NETWORK_CORSACCESSLIST,operationsapi_network_headerstimeout:D.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT,operationsapi_network_https:D.OPERATIONSAPI_NETWORK_HTTPS,operationsapi_network_keepalivetimeout:D.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT,operationsapi_network_port:D.OPERATIONSAPI_NETWORK_PORT,operationsapi_network_domainsocket:D.OPERATIONSAPI_NETWORK_DOMAINSOCKET,operationsapi_network_secureport:D.OPERATIONSAPI_NETWORK_SECUREPORT,operationsapi_tls:D.OPERATIONSAPI_TLS,operationsapi_tls_certificate:D.OPERATIONSAPI_TLS_CERTIFICATE,operationsapi_tls_privatekey:D.OPERATIONSAPI_TLS_PRIVATEKEY,operationsapi_tls_certificateauthority:D.OPERATIONSAPI_TLS_CERTIFICATEAUTHORITY,operationsapi_network_timeout:D.OPERATIONSAPI_NETWORK_TIMEOUT,operationsapi_root:D.ROOTPATH,databases:D.DATABASES,storage_path:D.STORAGE_PATH,storage_maxtransactionqueuetime:D.STORAGE_MAXTRANSACTIONQUEUETIME,ignorescripts:D.IGNORE_SCRIPTS,mqtt_network_port:D.MQTT_NETWORK_PORT,mqtt_websocket:D.MQTT_WEBSOCKET,mqtt_network_secureport:D.MQTT_NETWORK_SECUREPORT,mqtt_network_mtls:D.MQTT_NETWORK_MTLS,mqtt_network_mtls_certificateAuthority:D.MQTT_NETWORK_MTLS_CERTIFICATEAUTHORITY,mqtt_network_mtls_user:D.MQTT_NETWORK_MTLS_USER,mqtt_network_mtls_required:D.MQTT_NETWORK_MTLS_REQUIRED,mqtt_requireauthentication:D.MQTT_REQUIREAUTHENTICATION,analytics_aggregatePeriod:D.ANALYTICS_AGGREGATEPERIOD,authentication_authorizelocal:D.AUTHENTICATION_AUTHORIZELOCAL,authentication_cachettl:D.AUTHENTICATION_CACHETTL,authentication_enablesessions:D.AUTHENTICATION_ENABLESESSIONS,authentication_operationtokentimeout:D.AUTHENTICATION_OPERATIONTOKENTIMEOUT,authentication_refreshtokentimeout:D.AUTHENTICATION_REFRESHTOKENTIMEOUT,componentsroot:D.COMPONENTSROOT,replication:D.REPLICATION,replication_port:D.REPLICATION_PORT,replication_secureport:D.REPLICATION_SECUREPORT,replication_hostname:D.REPLICATION_HOSTNAME,replication_url:D.REPLICATION_URL,replication_routes:D.REPLICATION_ROUTES,tls:D.TLS,tls_certificate:D.TLS_CERTIFICATE,tls_privatekey:D.TLS_PRIVATEKEY,tls_certificateauthority:D.TLS_CERTIFICATEAUTHORITY,tls_ciphers:D.TLS_CIPHERS};for(let e in D){let t=D[e];jO[t.toLowerCase()]=t}var w1={TABLES:"tables",PATH:"path",AUDIT_PATH:"auditPath"},C1={csv_file_load:"csv_file_load",csv_data_load:oe.CSV_DATA_LOAD,csv_url_load:oe.CSV_URL_LOAD,delete_files_before:"delete_files_before",delete_records_before:"delete_records_before",delete_audit_logs_before:"delete_audit_logs_before",delete_transaction_logs_before:"delete_transaction_logs_before",empty_trash:"empty_trash",export_local:"export_local",export_to_s3:"export_to_s3",import_from_s3:"import_from_s3",restart_service:"restart_service"},D1={CLUSTERING_PAYLOAD:"clustering_payload",DELEGATE_THREAD_RESPONSE:"delegate_thread_response",CLUSTERING:"clustering",SCHEMA:"schema",CLUSTER_STATUS:"cluster_status",JOB:"job",CHILD_STARTED:"child_started",CHILD_STOPPED:"child_stopped",USER:"user",RESTART:"restart"},L1={BIDIRECTIONAL:"BIDIRECTIONAL",OUTBOUND:"OUTBOUND",INBOUND:"INBOUND"},P1={VERSION_DEFAULT:"2.2.0"},M1={DEVELOPMENT:8192,DEFAULT:512},U1={IDENTIFY:"identify",AUTHENTICATE:"authenticate",AUTHENTICATE_OK:"authenticated",AUTHENTICATE_FAIL:"authenticate_fail",CONNECTION:"connection",CONNECT:"connect",CATCHUP_REQUEST:"catchup_request",CATCHUP_RESPONSE:"catchup",CONFIRM_MSG:"confirm_msg",ERROR:"error",DISCONNECT:"disconnect",SCHEMA_UPDATE_REQ:"schema_update_request",SCHEMA_UPDATE_RES:"schema_update_response",RECONNECT_ATTEMPT:"reconnect_attempt",CONNECT_ERROR:"connect_error",MESSAGE:"msg",VERSION_MISMATCH:"version_mismatch",DIRECTION_CHANGE:"direction_change"},v1={1e3:"SUCCESSFUL_SHUTDOWN",1001:"CLOSE_GOING_AWAY",1002:"CLOSE_PROTOCOL_ERROR",1003:"CLOSE_UNSUPPORTED",1005:"CLOSE_NO_STATUS",1006:"CLOSE_ABNORMAL",1007:"UNSUPPORTED_PAYLOAD",1008:"POLICY_VIOLATION",1009:"CLOSE_TOO_LARGE",1010:"MANDATORY_EXTENSION",1011:"SERVER_ERROR",1012:"SERVICE_RESTART",1013:"SERVER_BUSY",1014:"BAD_GATEWAY",1015:"HANDSHAKE_FAIL",4141:"LICENSE_LIMIT_REACHED"},x1={ENOENT:"ENOENT",EACCES:"EACCES",EEXIST:"EEXIST",ERR_INVALID_ARG_TYPE:"ERR_INVALID_ARG_TYPE"},JO={CREATED_TIME:"__createdtime__",UPDATED_TIME:"__updatedtime__"},B1=Symbol("metadata"),H1="__clustering__",k1=Object.values(JO),F1=15984864e5,XO={LESS:"<",LESS_OR_EQ:"<=",GREATER:">",GREATER_OR_EQ:">=",BETWEEN:"..."},G1=QO.invert(XO),q1={GET_CLUSTER_STATUS:"GET_CLUSTER_STATUS",CLUSTER_STATUS_RESPONSE:"CLUSTER_STATUS_RESPONSE",ERROR_RESPONSE:"ERROR",ADD_USER:"ADD_USER",ALTER_USER:"ALTER_USER",DROP_USER:"DROP_USER",HDB_OPERATION:"HDB_OPERATION",ADD_NODE:"ADD_NODE",UPDATE_NODE:"UPDATE_NODE",REMOVE_NODE:"REMOVE_NODE",HDB_USERS_MSG:"HDB_USERS_MSG",HDB_WORKERS:"HDB_WORKERS",HDB_TRANSACTION:"HDB_TRANSACTION"},V1=111,$1=`\r
2
+ `,Y1={READ:"read",INSERT:"insert",UPDATE:"update",DELETE:"delete"},K1=["*","%"],W1="unauthorized_access",Q1="func_val",z1={HASH_VALUE:"hash_value",TIMESTAMP:"timestamp",USERNAME:"username"},j1={JWT_PRIVATE_KEY_NAME:".jwtPrivate.key",JWT_PUBLIC_KEY_NAME:".jwtPublic.key",JWT_PASSPHRASE_NAME:".jwtPass"},J1={SHUTDOWN:"shutdown",CHILD_STARTED:"child_started",CHILD_STOPPED:"child_stopped",SCHEMA:"schema",USER:"user",CLUSTER_STATUS_RESPONSE:"cluster_status_response",CLUSTER_STATUS_REQUEST:"cluster_status_request",METRICS:"metrics",GET_METRICS:"get_metrics",RESTART:"restart",START_JOB:"start_job",NATS_CONSUMER_UPDATE:"nats_consumer_update"},X1={HDB_CORE:"hdb_core",CUSTOM_FUNCTIONS:"custom_functions"},Z1={HTTP:"http"},eY={STOPPED:"stopped",ONLINE:"online"},tY="3.x.x",rY={SUCCESS:"success",FAILURE:"failure"},nY={AUTHENTICATION:"authentication",AUTHORIZATION:"authorization"};ZO.exports={LOCAL_HARPERDB_OPERATIONS:ze,HDB_SUPPORT_ADDRESS:VO,HDB_SUPPORT_URL:YO,HDB_PRICING_URL:N$,SUPPORT_HELP_MSG:I$,LICENSE_HELP_MSG:KO,HDB_PROC_NAME:GO,HDB_PROC_DESCRIPTOR:Qp,CLUSTERING_LEAF_PROC_DESCRIPTOR:o_,CLUSTERING_HUB_PROC_DESCRIPTOR:i_,SYSTEM_SCHEMA_NAME:K$,HASH_FOLDER_NAME:W$,HDB_HOME_DIR_NAME:Q$,UPDATE_FILE_NAME:X$,LICENSE_KEY_DIR_NAME:j$,BOOT_PROPS_FILE_NAME:J$,JOB_TYPE_ENUM:C1,JOB_STATUS_ENUM:g1,SYSTEM_TABLE_NAMES:E1,SYSTEM_TABLE_HASH_ATTRIBUTES:h1,OPERATIONS_ENUM:oe,VALID_S3_FILE_TYPES:R1,S3_BUCKET_AUTH_KEYS:A1,VALID_SQL_OPS_ENUM:b1,GEO_CONVERSION_ENUM:O1,HDB_SETTINGS_NAMES:zO,HDB_SETTINGS_NAMES_REVERSE_LOOKUP:N1,SERVICE_ACTIONS_ENUM:y1,CLUSTER_MESSAGE_TYPE_ENUM:D1,CLUSTER_CONNECTION_DIRECTION_ENUM:L1,CLUSTER_EVENTS_DEFS_ENUM:U1,PERIOD_REGEX:U$,DOUBLE_PERIOD_REGEX:v$,UNICODE_PERIOD:x$,FORWARD_SLASH_REGEX:B$,UNICODE_FORWARD_SLASH:H$,ESCAPED_FORWARD_SLASH_REGEX:k$,ESCAPED_PERIOD_REGEX:F$,ESCAPED_DOUBLE_PERIOD_REGEX:G$,REG_KEY_FILE_NAME:S1,RESTART_TIMEOUT_MS:t1,HDB_FILE_PERMISSIONS:r1,DATABASES_DIR_NAME:i1,LEGACY_DATABASES_DIR_NAME:o1,TRANSACTIONS_DIR_NAME:a1,LIMIT_COUNT_NAME:c1,ID_ATTRIBUTE_STRING:l1,INSERT_MODULE_ENUM:f1,UPGRADE_JSON_FIELD_NAMES_ENUM:_1,RESTART_CODE:Z$,RESTART_CODE_NUM:e1,CLUSTER_OPERATIONS:jl,SYSTEM_DEFAULT_ATTRIBUTE_NAMES:p1,HDB_INTERNAL_SC_CHANNEL_PREFIX:_n,INTERNAL_SC_CHANNELS:m1,CLUSTERING_MESSAGE_TYPES:q1,HDB_FILE_SUFFIX:z$,BLOB_FOLDER_NAME:n1,HDB_TRASH_DIR:s1,ORIGINATOR_SET_VALUE:V1,LICENSE_VALUES:P1,RAM_ALLOCATION_ENUM:M1,TIME_STAMP_NAMES_ENUM:JO,TIME_STAMP_NAMES:k1,PERMS_UPDATE_RELEASE_TIMESTAMP:F1,SEARCH_NOT_FOUND_MESSAGE:w$,SEARCH_ATTRIBUTE_NOT_FOUND:C$,LICENSE_ROLE_DENIED_RESPONSE:D$,LICENSE_MAX_CONNS_REACHED:L$,BASIC_LICENSE_MAX_NON_CU_ROLES:$O,BASIC_LICENSE_CLUSTER_CONNECTION_LIMIT_WS_ERROR_CODE:O$,VALUE_SEARCH_COMPARATORS:XO,VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP:G1,LICENSE_FILE_NAME:T1,WEBSOCKET_CLOSE_CODE_DESCRIPTION_LOOKUP:v1,NEW_LINE:$1,BASIC_LICENSE_MAX_CLUSTER_USER_ROLES:M$,MOMENT_DAYS_TAG:q$,API_TURNOVER_SEC:V$,LOOPBACK:P$,CODE_EXTENSION:s_,WILDCARD_SEARCH_VALUE:$$,NODE_ERROR_CODES:x1,JAVASCRIPT_EXTENSION:FO,PERMS_CRUD_ENUM:Y1,UNAUTHORIZED_PERMISSION_NAME:W1,SEARCH_WILDCARDS:K1,FUNC_VAL:Q1,READ_AUDIT_LOG_SEARCH_TYPES_ENUM:z1,JWT_ENUM:j1,CLUSTERING_FLAG:H1,ITC_EVENT_TYPES:J1,CUSTOM_FUNCTION_PROC_NAME:qO,CUSTOM_FUNCTION_PROC_DESCRIPTOR:n_,SERVICES:X1,THREAD_TYPES:Z1,MEM_SETTING_KEY:Y$,HDB_RESTART_SCRIPT:u$,PROCESS_DESCRIPTORS:m$,SERVICE_SERVERS:R$,SERVICE_SERVERS_CWD:Wp,PROCESS_DESCRIPTORS_VALIDATE:T$,LAUNCH_SERVICE_SCRIPTS:A$,LOG_LEVELS:S$,PROCESS_NAME_ENV_PROP:u1,LOG_NAMES:p$,PM2_PROCESS_STATUSES:eY,CONFIG_PARAM_MAP:jO,CONFIG_PARAMS:D,HDB_CONFIG_FILE:a$,HDB_DEFAULT_CONFIG_FILE:c$,ROLE_TYPES_ENUM:b$,BOOT_PROP_PARAMS:WO,INSTALL_PROMPTS:d1,HDB_ROOT_DIR_NAME:l$,CLUSTERING_PROCESSES:g$,FOREGROUND_PID_FILE:_$,PACKAGE_ROOT:Qi,PRE_4_0_0_VERSION:tY,DATABASES_PARAM_CONFIG:w1,METADATA_PROPERTY:B1,AUTH_AUDIT_STATUS:rY,AUTH_AUDIT_TYPES:nY,HDB_PID_FILE:E$,DEFAULT_DATABASE_NAME:h$,LEGACY_CONFIG_PARAMS:I1};kO()});var a_=I((Yde,rN)=>{"use strict";var eN=require("minimist");rN.exports=sY;function sY(e=[],t=!1){if(!Array.isArray(e))return{};let r,n;t?(r=tN(process.env),n=tN(eN(process.argv))):(r=process.env,n=eN(process.argv));let s={};for(let i=0,o=e.length;i<o;i++){let c=e[i];n[c]!==void 0?s[c]=n[c].toString().trim():r[c]!==void 0&&(s[c]=r[c].toString().trim())}return s}a(sY,"assignCMDENVVariables");function tN(e){let t,r=Object.keys(e),n=r.length,s={};for(;n--;)t=r[n],s[t.toLowerCase()]=e[t];return s}a(tN,"objKeysToLowerCase")});var X=I((pN,SN)=>{"use strict";var fi=require("fs-extra"),{workerData:iY,threadId:oY,isMainThread:aY}=require("worker_threads"),Ps=require("path"),oN=require("yaml"),aN=require("properties-reader"),Wt=H(),nN=a_(),cY=require("os"),{PACKAGE_ROOT:Jp}=H(),{_assignPackageExport:lY}=require("../index"),sN=process.stdout.nativeWrite||(process.stdout.nativeWrite=process.stdout.write),At={notify:7,fatal:6,error:5,warn:4,info:3,debug:2,trace:1},cN={STDOUT:"stdOut",STDERR:"stdErr"},uY=Ps.join(Jp,"logs"),dY=Ps.join(Jp,"config/yaml/",Wt.HDB_DEFAULT_CONFIG_FILE),fY=1e4,Ls,kn,rr,c_,Jl,l_,Ms,Xl;Xl===void 0&&lN();Object.assign(pN,{notify:EN,fatal:hN,error:u_,warn:mN,info:dN,debug:_N,trace:fN,setLogLevel:gY,log_level:rr,loggerWithTag:hY,suppressLogging:mY,initLogSettings:lN,logCustomLevel:SY,closeLogFile:Xp,logsAtLevel:_Y,getLogFilePath:()=>l_,OUTPUTS:cN,AuthAuditLog:bY});lY("logger",SN.exports);var zp;function _Y(e){return At[rr]<=At[e]}a(_Y,"logsAtLevel");function lN(e=!1){try{if(Xl===void 0||e){Xp();let t=TY(),r=nN(["ROOTPATH"]);try{Xl=aN(t)}catch(n){if(!r.ROOTPATH||r.ROOTPATH&&!fi.pathExistsSync(Ps.join(r.ROOTPATH,Wt.HDB_CONFIG_FILE)))throw n}if({level:rr,config_log_path:Jl,to_file:Ls,to_stream:kn}=RY(r.ROOTPATH?Ps.join(r.ROOTPATH,Wt.HDB_CONFIG_FILE):Xl.get("settings_path")),c_=Wt.LOG_NAMES.HDB,l_=Ps.join(Jl,c_),aY)try{require("segfault-handler").registerHandler(Ps.join(Jl,"crash.log"))}catch{}}}catch(t){if(Xl=void 0,t.code===Wt.NODE_ERROR_CODES.ENOENT||t.code===Wt.NODE_ERROR_CODES.ERR_INVALID_ARG_TYPE){let r=nN(Object.keys(Wt.CONFIG_PARAM_MAP),!0);for(let o in r){let c=Wt.CONFIG_PARAM_MAP[o];c&&c.toLowerCase();let l=r[o];if(c===Wt.CONFIG_PARAMS.LOGGING_LEVEL){rr=l;continue}if(c===Wt.CONFIG_PARAMS.LOGGING_STDSTREAMS){kn=l;continue}c===Wt.CONFIG_PARAMS.LOGGING_FILE&&(Ls=c)}let{default_level:n,default_to_file:s,default_to_stream:i}=AY();Ls=Ls===void 0?s:Ls,Ls=iN(Ls),kn=kn===void 0?i:kn,kn=iN(kn),rr=rr===void 0?n:rr,Jl=uY,c_=Wt.LOG_NAMES.INSTALL,l_=Ps.join(Jl,c_);return}throw u_("Error initializing log settings"),u_(t),t}process.env.DEV_MODE&&(kn=!0),EY()}a(lN,"initLogSettings");var zi=!0;function EY(){Ls&&(process.stdout.write=function(e){return typeof e=="string"&&Ms&&zi&&At[rr]<=At.info&&(jp(),e=e.toString(),e[e.length-1]===`
3
+ `&&(e=e.slice(0,-1)),fi.appendFileSync(Ms,cs("info",[e]))),sN.apply(process.stdout,arguments)},process.stderr.write=function(e){return typeof e=="string"&&Ms&&zi&&At[rr]<=At.error&&(jp(),e[e.length-1]===`
4
+ `&&(e=e.slice(0,-1)),fi.appendFileSync(Ms,cs("error",[e]))),sN.apply(process.stderr,arguments)})}a(EY,"stdioLogging");function hY(e,t){let r={tagName:e.replace(/ /g,"-")};return{notify:n(EN,"notify"),fatal:n(hN,"fatal"),error:n(u_,"error"),warn:n(mN,"warn"),info:n(dN,"info"),debug:n(_N,"debug"),trace:n(fN,"trace")};function n(s,i){return!t||At[rr]<=At[i]?function(...o){return s(r,...o)}:null}}a(hY,"loggerWithTag");function mY(e){try{zi=!1,e()}finally{zi=!0}}a(mY,"suppressLogging");var pY=iY?.name?.replace(/ /g,"-")||"main";function cs(e,t){let r=new Date(Date.now()).toISOString(),n="",s=t.length,i=s-1,o=[e],c=0,l;for(typeof t[0]=="object"&&(t[0]?.tagName?(o.push(t[0]?.tagName),c++):t[0]?.serviceName&&(l=t[0]?.serviceName,c++)),o.unshift(l||pY+"/"+oY);c<s;c++){let d=t[c];d instanceof Error&&d.stack?n+=d.stack:typeof d=="object"?n+=JSON.stringify(d):n+=d,c<i&&(n+=" ")}return`${r} [${o.join("] [")}]: ${n}
5
+ `}a(cs,"createLogRecord");function Zl(e){if(Ls){if(uN(e),kn){zi=!1;try{process.stdout.write(e)}finally{zi=!0}}}else kn&&process.stdout.write(e)}a(Zl,"logStdOut");function d_(e){if(Ls){if(uN(e),kn){zi=!1;try{process.stderr.write(e)}finally{zi=!0}}}else kn&&process.stderr.write(e)}a(d_,"logStdErr");function uN(e){jp(),Ms?fi.appendFileSync(Ms,e):zp||console.log(e)}a(uN,"logToFile");function Xp(){try{fi.closeSync(Ms)}catch{}Ms=null}a(Xp,"closeLogFile");function jp(){if(!Ms){try{Ms=fi.openSync(l_,"a")}catch(e){zp||(zp=!0,console.error(e))}setTimeout(()=>{Xp()},fY).unref()}}a(jp,"openLogFile");function dN(...e){At[rr]<=At.info&&Zl(cs("info",e))}a(dN,"info");function fN(...e){At[rr]<=At.trace&&Zl(cs("trace",e))}a(fN,"trace");function u_(...e){At[rr]<=At.error&&d_(cs("error",e))}a(u_,"error");function _N(...e){At[rr]<=At.debug&&Zl(cs("debug",e))}a(_N,"debug");function EN(...e){At[rr]<=At.notify&&Zl(cs("notify",e))}a(EN,"notify");function hN(...e){At[rr]<=At.fatal&&d_(cs("fatal",e))}a(hN,"fatal");function mN(...e){At[rr]<=At.warn&&d_(cs("warn",e))}a(mN,"warn");function SY(e,t,...r){t===cN.STDERR?d_(cs(e,r)):Zl(cs(e,r))}a(SY,"logCustomLevel");function TY(){let e;try{e=cY.homedir()}catch{e=process.env.HOME}e||(e="~/");let t=Ps.join(e,Wt.HDB_HOME_DIR_NAME,Wt.BOOT_PROPS_FILE_NAME);return fi.existsSync(t)||(t=Ps.join(Jp,"utility/hdb_boot_properties.file")),t}a(TY,"getPropsFilePath");function gY(e){rr=e}a(gY,"setLogLevel");function iN(e){return e===!0||typeof e=="string"&&e.toLowerCase()==="true"}a(iN,"autoCastBoolean");function RY(e){try{if(e.includes("config/settings.js")){let o=aN(e);return{level:o.get(Wt.HDB_SETTINGS_NAMES.LOG_LEVEL_KEY),config_log_path:Ps.dirname(o.get(Wt.HDB_SETTINGS_NAMES.LOG_PATH_KEY)),to_file:o.get(Wt.HDB_SETTINGS_NAMES.LOG_TO_FILE),to_stream:o.get(Wt.HDB_SETTINGS_NAMES.LOG_TO_STDSTREAMS)}}let t=oN.parseDocument(fi.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===Wt.NODE_ERROR_CODES.ENOENT)throw t;console.error("Error accessing config file for logging"),console.error(t)}}a(RY,"getLogConfig");function AY(){try{let e=oN.parseDocument(fi.readFileSync(dY,"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(AY,"getDefaultConfig");function bY(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(bY,"AuthAuditLog")});var gN=I((Qde,TN)=>{"use strict";var yY=require("util"),OY=require("path"),NY=require("child_process"),IY=yY.promisify(NY.execFile),wY=1e3*1e3*10;TN.exports={findPs:CY};async function CY(e){let t={};try{await Promise.all(["comm","args","ppid","uid","%cpu","%mem"].map(async r=>{let{stdout:n}=await IY("ps",["wwxo",`pid,${r}`],{maxBuffer:wY});for(let s of n.trim().split(`
6
+ `).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:OY.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(CY,"findPs")});var Ft=I((jde,AN)=>{"use strict";var DY="__dbis__",LY="__txns__",PY="__environment_name__",MY="__dbi_defintion__",UY={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"},vY=["__createdtime__","__updatedtime__"],xY="\uFFFF",RN={TIMESTAMP:"timestamp",HASH_VALUE:"hash_value",USER_NAME:"user_name"},BY=Object.values(RN);AN.exports={AUDIT_STORE_NAME:LY,INTERNAL_DBIS_NAME:DY,DBI_DEFINITION_NAME:MY,SEARCH_TYPES:UY,TIMESTAMP_NAMES:vY,MAX_SEARCH_KEY_LENGTH:256,ENVIRONMENT_NAME_KEY:PY,TRANSACTIONS_DBI_NAMES_ENUM:RN,TRANSACTIONS_DBIS:BY,OVERFLOW_MARKER:xY}});var En=I((Jde,LN)=>{"use strict";var bN=H(),yN=Ft(),ON={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},NN=a(e=>`${e} Check logs and try again.`,"CHECK_LOGS_WRAPPER"),IN={500:NN("There was an error processing your request."),400:"Invalid request"},HY=IN[ON.INTERNAL_SERVER_ERROR],kY={OP_NOT_SUPPORTED_FOR_FS:e=>`${e} is not available for this instance because it uses the File System data store.`,MISSING_VALUE:e=>`${e} is missing.`,INVALID_VALUE:e=>`${e} is invalid.`,NOT_FOUND:e=>`${e} not found.`},FY={CONFIG_VALIDATION:e=>`HarperDB config file validation error: ${e}`},GY={DEFAULT_BULK_LOAD_ERR:"There was an error during your bulk load into HarperDB.",DOWNLOAD_FILE_ERR:e=>`There was an error downloading '${e}'.`,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:e=>`Bulk load operation failed - ${e} is not a valid 'action' parameter`,INVALID_FILE_EXT_ERR:e=>`Error selecting correct parser - valid file type not found in json - ${e}`,MAX_FILE_SIZE_ERR:(e,t)=>`File size is ${e} bytes, which exceeded the maximum size allowed of: ${t} bytes`,PAPA_PARSE_ERR:"There was an error parsing the downloaded CSV data.",S3_DOWNLOAD_ERR:e=>`There was an error downloading '${e}' from AWS.`,WRITE_TEMP_FILE_ERR:"Error writing temporary file to storage"},qY={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 ${yN.INTERNAL_DBIS_NAME}`,CANNOT_DROP_INTERNAL_DBIS_NAME:`cannot drop a dbi named ${yN.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"},VY={ATTR_NAME_LENGTH_ERR:e=>`transaction aborted due to attribute name ${e} being too long. Attribute names cannot be longer than ${bN.INSERT_MODULE_ENUM.MAX_CHARACTER_SIZE} bytes.`,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 ${bN.INSERT_MODULE_ENUM.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"},wN={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"},$Y={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:e=>`Operation '${e}' is restricted to 'super_user' roles`,OP_NOT_FOUND:e=>`Operation '${e}' 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:(e,t,r)=>`There was an error authorizing ${e} op on table '${t}.${r}'`,USER_HAS_NO_PERMS:e=>`User ${e} has no role or permissions. Please assign the user a valid role.`,DROP_SYSTEM:"The 'system' database, tables and records are used internally by HarperDB and cannot be updated or removed."},YY={ATTR_PERM_MISSING:(e,t)=>`${e.toUpperCase()} attribute permission missing for '${t}'`,ATTR_PERM_MISSING_NAME:"Permission object in 'attribute_permission' missing an 'attribute_name'",ATTR_PERM_NOT_BOOLEAN:(e,t)=>`${e.toUpperCase()} attribute permission for '${t}' must be a 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:e=>`Invalid attribute '${e}' in 'attribute_permissions'`,INVALID_PERM_KEY:e=>`Invalid table permission key value '${e}'`,INVALID_ATTR_PERM_KEY:e=>`Invalid attribute permission key value '${e}'`,INVALID_ROLE_JSON_KEYS:e=>`Invalid ${e.length>1?"keys":"key"} in JSON body - '${e.join("', '")}'`,MISMATCHED_TABLE_ATTR_PERMS:e=>`You have a conflict with TABLE permissions for '${e}' being false and ATTRIBUTE permissions being true`,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:e=>`A role with name '${e}' already exists`,ROLE_NOT_FOUND:"Role not found",ROLE_PERMS_ERROR:"Errors in the role permissions JSON provided",SCHEMA_PERM_ERROR:e=>`Your role does not have permission to view database metadata for '${e}'`,SCHEMA_TABLE_PERM_ERROR:(e,t)=>`Your role does not have permission to view database.table metadata for '${e}.${t}'`,SU_ROLE_MISSING_ERROR:"Missing 'super_user' key/value in permission set",SU_CU_ROLE_BOOLEAN_ERROR:e=>`Value for '${e}' permission must be a boolean`,STRUCTURE_USER_ROLE_TYPE_ERROR:e=>`Value for '${e}' permission must be a boolean or Array`,SU_CU_ROLE_NO_PERMS_ALLOWED:e=>`Roles with '${e}' set to true cannot have other permissions set.`,SU_CU_ROLE_COMBINED_ERROR:"Roles cannot have both 'super_user' and 'cluster_user' values included in their permissions set.",TABLE_PERM_MISSING:e=>`Missing table ${e.toUpperCase()} permission`,TABLE_PERM_NOT_BOOLEAN:e=>`Table ${e.toUpperCase()} permission must be a boolean`},KY={ATTR_NOT_FOUND:(e,t,r)=>`Attribute '${r}' does not exist on '${e}.${t}'`,ATTR_EXISTS_ERR:(e,t,r)=>`Attribute '${r}' already exists in ${e}.${t}'`,DESCRIBE_ALL_ERR:"There was an error during describeAll. Please check the logs and try again.",INVALID_TABLE_ERR:e=>`Invalid table ${JSON.stringify(e)}`,SCHEMA_NOT_FOUND:e=>`database '${e}' does not exist`,SCHEMA_EXISTS_ERR:e=>`database '${e}' already exists`,TABLE_EXISTS_ERR:(e,t)=>`Table '${t}' already exists in '${e}'`,SCHEMA_REQUIRED_ERR:"database is required",TABLE_NOT_FOUND:(e,t)=>`Table '${e}.${t}' does not exist`,TABLE_REQUIRED_ERR:"table is required"},WY={OUTER_JOIN_TRANSLATION_ERROR:"There was an error translating the final SQL outer join data."},QY={ALTER_USER_DUP_ROLES:e=>`Update failed. There are duplicates for the '${e}' role which is not allowed. Update your roles and try again.`,ALTER_USER_ROLE_NOT_FOUND:e=>`Update failed. Requested '${e}' role not found.`,DUP_ROLES_FOUND:e=>`Multiple ${e} roles found. Roles must have unique 'role' value. Please update and try again.`,ROLE_NAME_NOT_FOUND:e=>`${e} role not found`,USER_ALREADY_EXISTS:e=>`User ${e} already exists`,USER_NOT_EXIST:e=>`User ${e} does not exist`},CN={INVALID_DATE:"Invalid date, must be in ISO-8601 format (YYYY-MM-DD).",SEARCH_CONDITIONS_INVALID_SORT_ATTRIBUTE:e=>`invalid sort attribute '${e}', the attribute must either be the table's hash attribute or an attribute used in conditions.`},DN={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:e=>`ITC server received invalid event type: ${e}`},zY={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"},jY={CLUSTERING_NOT_ENABLED:"Clustering must be enabled to perform this operation."},JY={...wN,...GY,...kY,...$Y,...YY,...KY,...WY,...QY,...VY,...CN,...DN,...zY,...jY,...FY};LN.exports={CHECK_LOGS_WRAPPER:NN,HDB_ERROR_MSGS:JY,DEFAULT_ERROR_MSGS:IN,DEFAULT_ERROR_RESP:HY,HTTP_STATUS_CODES:ON,LMDB_ERRORS_ENUM:qY,AUTHENTICATION_ERROR_MSGS:wN,VALIDATION_ERROR_MSGS:CN,ITC_ERRORS:DN}});var ce=I((Zde,UN)=>{"use strict";var sc=En(),XY=X(),ZY=H(),f_=class extends Error{static{a(this,"HdbError")}constructor(t,r,n,s,i){super(),Error.captureStackTrace(this,PN),this.statusCode=n||sc.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR,this.http_resp_msg=r||(sc.DEFAULT_ERROR_MSGS[n]?sc.DEFAULT_ERROR_MSGS[n]:sc.DEFAULT_ERROR_MSGS[sc.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&&XY[s](i)}},Zp=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}},eS=class extends Error{static{a(this,"ServerError")}constructor(t,r){super(t),this.statusCode=r||500}};function PN(e,t,r,n=ZY.LOG_LEVELS.ERROR,s=null,i=!1){if(MN(e))return e;let o=new f_(e,t,r,n,s);return i&&delete o.stack,o}a(PN,"handleHDBError");function MN(e){return e.__proto__.constructor.name===f_.name}a(MN,"isHDBError");UN.exports={isHDBError:MN,handleHDBError:PN,ClientError:Zp,ServerError:eS,hdb_errors:sc}});var ht=I((tfe,GN)=>{"use strict";var su=H(),eK=re(),qr=ie(),iu=require("path"),tK=require("minimist"),vN=require("fs-extra"),xN=require("lodash");qr.initSync();var{CONFIG_PARAMS:ji,DATABASES_PARAM_CONFIG:eu,SYSTEM_SCHEMA_NAME:__}=su,tu,ru,nu;function BN(){if(tu!==void 0)return tu;if(qr.getHdbBasePath()!==void 0)return tu=qr.get(ji.STORAGE_PATH)||iu.join(qr.getHdbBasePath(),su.DATABASES_DIR_NAME),tu}a(BN,"getBaseSchemaPath");function HN(){if(ru!==void 0)return ru;if(qr.getHdbBasePath()!==void 0)return ru=FN(__),ru}a(HN,"getSystemSchemaPath");function kN(){if(nu!==void 0)return nu;if(qr.getHdbBasePath()!==void 0)return nu=qr.get(su.CONFIG_PARAMS.STORAGE_AUDIT_PATH)||iu.join(qr.getHdbBasePath(),su.TRANSACTIONS_DIR_NAME),nu}a(kN,"getTransactionAuditStoreBasePath");function rK(e,t){let r=qr.get(ji.DATABASES)?.[e];return t&&r?.tables?.[t]?.auditPath||r?.auditPath||iu.join(kN(),e.toString())}a(rK,"getTransactionAuditStorePath");function FN(e,t){e=e.toString(),t=t&&t.toString();let r=qr.get(su.CONFIG_PARAMS.DATABASES)?.[e];return t&&r?.tables?.[t]?.path||r?.path||iu.join(BN(),e)}a(FN,"getSchemaPath");function nK(e,t){e=e.toString(),t=t.toString();let r=process.env;Object.assign(r,tK(process.argv));let n=r[ji.DATABASES.toUpperCase()];if(n){let i;try{i=JSON.parse(n)}catch(o){if(!eK.isObject(n))throw o;i=n}for(let o of i){let c=o[__];if(!c)continue;let l=qr.get(ji.DATABASES);l=l??{};let d=c?.tables?.[t]?.[eu.PATH];if(d)return xN.set(l,[__,eu.TABLES,t,eu.PATH],d),qr.setProperty(ji.DATABASES,l),d;let u=c?.[eu.PATH];if(u)return xN.set(l,[__,eu.PATH],u),qr.setProperty(ji.DATABASES,l),u}}let s=r[ji.STORAGE_PATH.toUpperCase()];if(s){if(!vN.pathExistsSync(s))throw new Error(s+" does not exist");let i=iu.join(s,e);return vN.mkdirsSync(i),qr.setProperty(ji.STORAGE_PATH,s),i}return HN()}a(nK,"initSystemSchemaPaths");function sK(){tu=void 0,ru=void 0,nu=void 0}a(sK,"resetPaths");GN.exports={getBaseSchemaPath:BN,getSystemSchemaPath:HN,getTransactionAuditStorePath:rK,getTransactionAuditStoreBasePath:kN,getSchemaPath:FN,initSystemSchemaPaths:nK,resetPaths:sK}});var hn=I((ife,KN)=>{"use strict";var iK=En().LMDB_ERRORS_ENUM,nfe=require("lmdb"),oK=Ft(),sfe=require("buffer").Buffer,{OVERFLOW_MARKER:qN,MAX_SEARCH_KEY_LENGTH:E_}=oK,VN=["number","string","symbol","boolean","bigint"];function aK(e){if(e=e?.primaryStore||e,!e)throw new Error(iK.ENV_REQUIRED)}a(aK,"validateEnv");function cK(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(cK,"stringifyData");function lK(e){return e instanceof Date?e.valueOf():e}a(lK,"convertKeyValueToWrite");function uK(e,t){if(e===null)return t?[null]:void 0;if(e===void 0)return;if(VN.includes(typeof e))return e.length>E_?[e.slice(0,E_)+qN]:[e];let r;if(Array.isArray(e)){r=[];for(let n=0,s=e.length;n<s;n++){let i=e[n];if(VN.includes(typeof i))i.length>E_?r.push(i.slice(0,E_)+qN):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(uK,"getIndexedValues");var h_=0,$N=0;function YN(){$N=Date.now()-performance.now()}a(YN,"adjustStartTime");YN();var dK=6e4;setInterval(YN,dK).unref();function fK(){let e=performance.now()+$N;return e>h_?(h_=e,e):(h_+=488e-6,h_)}a(fK,"getNextMonotonicTime");KN.exports={validateEnv:aK,stringifyData:cK,convertKeyValueToWrite:lK,getNextMonotonicTime:fK,getIndexedValues:uK}});var WN,mn,tS,ic=Oe(()=>{WN=require("events"),mn=class extends WN.EventEmitter{static{a(this,"IterableEventQueue")}resolveNext;queue;hasDataListeners;[Symbol.asyncIterator](){let t=new tS;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(){return this.queue?.shift()}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)}},tS=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}}}});var ko={};Ze(ko,{server:()=>st});var QN,st,Lr=Oe(()=>{QN=require("../index"),st={};(0,QN._assignPackageExport)("server",st)});var sS={};Ze(sS,{loadGQLSchema:()=>hK,start:()=>nS,startOnMainThread:()=>EK});function nS({ensureTable:e}){return{handleFile:t,setupFile:t};async function t(r,n,s,i){let{parse:o,Source:c,Kind:l,NamedTypeNode:d,StringValueNode:u}=await import("graphql"),f=o(new c(r.toString(),s)),E=new Map,_=[],h;for(let g of f.definitions)switch(g.kind){case l.OBJECT_TYPE_DEFINITION:let v=function($){if($.kind==="NonNullType"){let ee=v($.type);return ee.nullable=!1,ee}if($.kind==="ListType")return{type:"array",elements:v($.type)};let ne={type:$.name?.value};return Object.defineProperty(ne,"location",{value:$.loc.startToken}),ne};a(v,"getProperty");let T=g.name.value,A=[],N={table:null,database:null,properties:A};E.set(T,N);for(let $ of g.directives){if($.name.value==="table"){for(let ne of $.arguments)N[ne.name.value]=ne.value.value;N.schema&&(N.database=N.schema),N.table||(N.table=T),N.audit&&(N.audit=N.audit!=="false"),N.attributes=N.properties,_.push(N)}if($.name.value==="sealed"&&(N.sealed=!0),$.name.value==="replicate"&&(N.replicate=!0),$.name.value==="export"){N.export=!0;for(let ne of $.arguments)typeof N.export!="object"&&(N.export={}),N.export[ne.name.value]=ne.value.value}}let V=!1,J={};for(let $ of g.fields){let F=v($.type);F.name=$.name.value,A.push(F),J[F.name]=void 0;for(let ne of $.directives){let ee=ne.name.value;if(ee==="primaryKey")V?console.warn("Can not define two attributes as a primary key at",ne.loc):(F.isPrimaryKey=!0,V=!0);else if(ee==="indexed")F.indexed=!0;else if(ee==="computed"){for(let Z of ne.arguments||[])if(Z.name.value==="from"){let le=Z.value.value;F.computed={from:S(le,Z,J)},F.version==null&&(F.version=le)}else Z.name.value==="version"&&(F.version=Z.value.value);F.computed=F.computed||!0}else if(ee==="relationship"){let Z={};for(let le of ne.arguments)Z[le.name.value]=le.value.value;F.relationship=Z}else if(ee==="createdTime")F.assignCreatedTime=!0;else if(ee==="updatedTime")F.assignUpdatedTime=!0;else if(ee==="expiresAt")F.expiresAt=!0;else if(ee==="allow"){let Z=F.authorizedRoles=[];for(let le of ne.arguments)le.name.value==="role"&&Z.push(le.value.value)}else server.knownGraphQLDirectives.includes(ee)&&console.warn(`@${ee} is an unknown directive, at`,ne.loc)}}N.type=T,T==="Query"&&(h=N)}function p(g){let T=E.get(g.type);T?(Object.defineProperty(g,"properties",{value:T.properties}),Object.defineProperty(g,"definition",{value:T})):g.type==="array"?p(g.elements):_K.includes(g.type)||(0,jN.getWorkerIndex)()===0&&console.error(`The type ${g.type} is unknown at line ${g.location.line}, column ${g.location.column}, in ${s}`)}a(p,"connectPropertyType");for(let g of E.values())for(let T of g.properties)p(T);for(let g of _)g.tableClass=e(g),g.export&&(g.export.name===""?i.set((0,rS.dirname)(n),g.tableClass):i.set((0,rS.dirname)(n)+"/"+(g.export.name||g.type),g.tableClass,g.export));function S(g,T,A){return new zN.Script(`function computed(attributes) { return function(record) { with(attributes) { with (record) { return ${g}; } } } } computed;`,{filename:s,lineOffset:T.loc.startToken.line-1,columnOffset:T.loc.startToken.column}).runInThisContext()(A)}a(S,"createComputedFrom")}}var rS,zN,jN,_K,EK,hK,JN=Oe(()=>{rS=require("path"),zN=require("node:vm");Ne();jN=U(at()),_K=["ID","Int","Float","Long","String","Boolean","Date","Bytes","Any","BigInt"];server.knownGraphQLDirectives&&(server.knownGraphQLDirectives=["table","sealed","export","primaryKey","indexed","computed","relationship","createdTime","updatedTime","expiresAt","allow"]);a(nS,"start");EK=nS,hK=nS({ensureTable:dt}).handleFile});async function m_(e){let t=(0,eI.pathToFileURL)(e).toString();return mK?(ou||(ou=pK(TK)),(await(await ou).import(t)).namespace):import(t)}async function pK(e){let{StaticModuleRecord:t}=await import("@endo/static-module-record");return require("ses"),lockdown({domainTaming:"unsafe",consoleTaming:"unsafe",errorTaming:"unsafe",errorTrapping:"none",stackFiltering:"verbose"}),ou=new Compartment({console,Math,Date,fetch:SK,...e()},{},{name:"h-dapp",resolveHook(r,n){return r==="harperdb"?"harperdb":(r=new URL(r,n).toString(),(0,ZN.extname)(r)||(r+=".js"),r)},importHook:async r=>{if(r==="harperdb")return{imports:[],exports:["Resource","tables","databases"],execute(s){Object.assign(s,{Resource:pr,tables:pn,databases:Ve})}};let n=await(0,XN.readFile)(new URL(r),{encoding:"utf-8"});return new t(n,r)}}),ou}function SK(e,t){let r=typeof e=="string"||e.url;if(new URL(r).protocol!="https")throw new Error("Only https is allowed in fetch");return fetch(e,t)}function TK(){return{Resource:pr,tables:pn}}var XN,ZN,eI,mK,ou,iS=Oe(()=>{ls();Ne();XN=require("fs/promises"),ZN=require("path"),eI=require("url"),mK=!1;a(m_,"secureImport");a(pK,"getCompartment");a(SK,"secureOnlyFetch");a(TK,"getGlobalVars")});var aS={};Ze(aS,{handleFile:()=>gK});async function gK(e,t,r,n){let s=new Map,i=await m_(r);c(i.default)&&n.set((0,oS.dirname)(t),i.default),o(i,(0,oS.dirname)(t));function o(l,d){for(let u in l){let f=l[u];c(f)?n.set(d+"/"+u,f):typeof f=="object"&&o(f,d+"/"+u)}}a(o,"recurseForResources");function c(l){return typeof l=="function"&&(l.get||l.put||l.post||l.delete)}return a(c,"isResource"),s}var oS,tI=Oe(()=>{iS();oS=require("path");a(gK,"handleFile")});var lS={};Ze(lS,{start:()=>RK});function RK({resources:e}){e.set("login",cS),e.loginPath=t=>"/login?redirect="+encodeURIComponent(t.url)}var cS,rI=Oe(()=>{ls();a(RK,"start");cS=class extends pr{static{a(this,"Login")}static async get(t,r,n){}static async post(t,r,n){let{username:s,password:i,redirect:o}=r;return{data:await n.login(s,i)}}}});var lI={};Ze(lI,{parse:()=>dS,streamAsJSON:()=>au,stringify:()=>Fo});function au(e){return new uS({value:e})}function nI(e){return console.error(e),JSON.stringify(e.toString())}function sI(e,t,r){return e?.then?r?e.then(t,r):e.then(t):t(e)}function Fo(e){try{return JSON.stringify(e)??"null"}catch(t){if(t===aI)return cI(e);if(t.resolution)return t.resolution.then(()=>Fo(e));throw t}}function cI(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+=cI(e[n]);return r+"]"}else{r="{";let n=!0;for(let s in e)n?n=!1:r+=",",r+=JSON.stringify(s)+":"+Fo(e[s]);return r+"}"}}else{if(t==="string")return JSON.stringify(e);if(t==="undefined")return"null"}return e.toString()}function dS(e){return yK.test(e)?AK.parse(e):JSON.parse(e)}var iI,oI,AK,bK,aI,uS,yK,fS=Oe(()=>{iI=require("stream"),oI=U(require("json-bigint-fixes")),AK=(0,oI.default)({useNativeBigInt:!0}),bK=1e4,aI={};BigInt.prototype.toJSON=function(){throw aI};a(au,"streamAsJSON");uS=class extends iI.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(;;)if(o=i.next(),o.then&&(yield o.then(c=>(o=c,""))),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),nI)}catch(s){yield nI(s)}else yield Fo(t)}else yield Fo(t)}_read(){if(!this._amReading){if(this._amReading=!0,this.done)return this.push(null);sI(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>bK?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 sI(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(nI,"handleError");a(sI,"when");a(Fo,"stringify");a(cI,"jsStringify");yK=/[[,:]\s*-?\d{16,}/;a(dS,"parse")});var AI=I((Rfe,RI)=>{"use strict";var _S=require("recursive-iterator"),OK=require("alasql"),ES=require("clone"),uI=re(),{handleHDBError:dI,hdb_errors:NK}=ce(),{HDB_ERROR_MSGS:fI,HTTP_STATUS_CODES:_I}=NK,{getDatabases:IK}=(Ne(),ae(it)),wK=["DISTINCT_ARRAY"],EI=Symbol("validateTables"),hS=Symbol("validateTable"),gfe=Symbol("getAllColumns"),hI=Symbol("validateAllColumns"),p_=Symbol("findColumn"),mI=Symbol("validateOrderBy"),cu=Symbol("validateSegment"),mS=Symbol("validateColumn"),pI=Symbol("setColumnsForTable"),SI=Symbol("checkColumnsForAsterisk"),TI=Symbol("validateGroupBy"),gI=Symbol("hasColumns"),pS=class{static{a(this,"SelectValidator")}constructor(t){this.statement=t,this.attributes=[]}validate(){if(!this.statement)throw new Error("invalid sql statement");this[EI](),this[SI](),this[hI]()}[EI](){if(this[gI]()){if(!this.statement.from||this.statement.from.length===0)throw"no from clause";this.statement.from.forEach(t=>{this[hS](t)}),this.statement.joins&&this.statement.joins.forEach(t=>{t.table.as=t.as,this[hS](t.table)})}}[gI](){let t=!1,r=new _S(this.statement);for(let{node:n,path:s}of r)if(n&&n.columnid){t=!0;break}return t}[hS](t){if(!t.databaseid)throw`schema not defined for table ${t.tableid}`;let r=IK();if(!r[t.databaseid])throw dI(new Error,fI.SCHEMA_NOT_FOUND(t.databaseid),_I.NOT_FOUND);if(!r[t.databaseid][t.tableid])throw dI(new Error,fI.TABLE_NOT_FOUND(t.databaseid,t.tableid),_I.NOT_FOUND);r[t.databaseid][t.tableid].attributes.forEach(s=>{let i=ES(s);i.table=ES(t),this.attributes.push(i)})}[p_](t){return this.attributes.filter(r=>t.tableid?(r.table.as===t.tableid||r.table.tableid===t.tableid)&&r.attribute===t.columnid:r.attribute===t.columnid)}[SI](){let t=new _S(this.statement.columns);for(let{node:r,path:n}of t)r&&r.columnid==="*"&&n.indexOf("expression")<0&&this[pI](r.tableid)}[pI](t){this.attributes.forEach(r=>{(!t||t&&(r.table.tableid===t||r.table.as===t))&&!r.relation&&this.statement.columns.push(new OK.yy.Column({columnid:r.attribute,tableid:r.table.as?r.table.as:r.table.tableid}))})}[hI](){this[cu](this.statement.columns,!1),this[cu](this.statement.joins,!1),this[cu](this.statement.where,!1),this[TI](this.statement.group,!1),this[cu](this.statement.order,!0)}[cu](t,r){if(!t)return;let n=new _S(t),s=[];for(let{node:i,path:o}of n)!uI.isEmpty(i)&&!uI.isEmpty(i.columnid)&&i.columnid!=="*"&&(r?this[mI](i):s.push(this[mS](i)));return s}[TI](t){if(!t)return;let r=[];if(this.statement.columns.forEach(n=>{if(!(n.funcid&&wK.indexOf(n.funcid.toUpperCase())>=0)){if(!n.aggregatorid&&!n.columnid){let s=ES(n);delete s.as,r.push(s)}else if(n.columnid){let s=this[p_](n)[0];s&&r.push(s)}}}),this.statement.group.forEach(n=>{let s=null;if(!n.columnid)r.forEach((i,o)=>{if(i.toString()===n.toString()){s=i,r.splice(o,1);return}});else{let i=this[p_](n);if(!i||i.length===0)throw`unknown column '${n.toString()}' in group by`;if(i.length>1)throw`ambiguously defined column '${n.toString()}' in group by`;r.forEach((o,c)=>{if(o.attribute===i[0].attribute&&o.table.tableid===i[0].table.tableid){s=o,r.splice(c,1);return}})}if(!s)throw`group by column '${n.toString()}' must be in select`}),r.length>0)throw`select column '${r[0].attribute?r[0].attribute:r[0].toString()}' must be in group by`}[mI](t){let r=this.statement.columns.filter(n=>n.as===t.columnid);if(r.length>1)throw`ambiguous column reference ${(t.tableid?t.tableid+".":"")+t.columnid} in order by`;r.length===0&&this[mS](t)}[mS](t){let r=this[p_](t),n=(t.tableid?t.tableid+".":"")+t.columnid;if(r.length===0)throw`unknown column ${n}`;if(r.length>1)throw`ambiguous column reference ${n}`;return r[0]}};RI.exports=pS});var yI=I((bfe,bI)=>{"use strict";var SS=class{static{a(this,"BridgeMethods")}createSchema(){throw new Error("createSchema bridge method is not defined")}dropSchema(){throw new Error("dropSchema bridge method is not defined")}createTable(){throw new Error("createTable bridge method is not defined")}dropTable(){throw new Error("dropTable bridge method is not defined")}createRecords(){throw new Error("createRecords bridge method is not defined")}updateRecords(){throw new Error("updateRecords bridge method is not defined")}async upsertRecords(){throw new Error("upsertRecords bridge method is not defined")}deleteRecords(){throw new Error("deleteRecords bridge method is not defined")}createAttribute(){throw new Error("createAttribute bridge method is not defined")}dropAttribute(){throw new Error("dropAttribute bridge method is not defined")}searchByConditions(){throw new Error("searchByConditions bridge method is not defined")}searchByHash(){throw new Error("searchByHash bridge method is not defined")}searchByValue(){throw new Error("searchByValue bridge method is not defined")}getDataByHash(){throw new Error("getDataByHash bridge method is not defined")}getDataByValue(){throw new Error("getDataByValue bridge method is not defined")}deleteRecordsBefore(){throw new Error("deleteRecordsBefore bridge method is not defined")}deleteAuditLogsBefore(){throw new Error("deleteAuditLogsBefore bridge method is not defined")}async readAuditLog(){throw new Error("readAuditLog bridge method is not defined")}};bI.exports=SS});var NI=I((Ofe,OI)=>{"use strict";var TS=class{static{a(this,"DBIDefinition")}constructor(t=!1,r=!1){this.dup_sort=t,this.is_hash_attribute=r,this.useVersions=r}};OI.exports=TS});var DI={};Ze(DI,{HAS_EXPIRATION:()=>g_,HAS_RESIDENCY_ID:()=>IS,HAS_STRUCTURE_UPDATE:()=>R_,LAST_TIMESTAMP_PLACEHOLDER:()=>fu,LOCAL_TIMESTAMP:()=>CK,METADATA:()=>lu,NO_TIMESTAMP:()=>RS,PENDING_LOCAL_TIME:()=>wS,PREVIOUS_TIMESTAMP_PLACEHOLDER:()=>NS,RecordEncoder:()=>OS,TIMESTAMP_ASSIGN_LAST:()=>LK,TIMESTAMP_ASSIGN_NEW:()=>wI,TIMESTAMP_ASSIGN_PREVIOUS:()=>CI,TIMESTAMP_PLACEHOLDER:()=>S_,TIMESTAMP_RECORD_PREVIOUS:()=>AS,getUpdateRecord:()=>CS,handleLocalTimeForGets:()=>A_});function MK(){return du[0]=du[0]^64,DK.getFloat64(0)}function A_(e){let t=e.getEntry;e.readCount=0,e.cachePuts=!1,e.getEntry=function(i,o){e.readCount++;let c=t.call(this,i,o),l=c?.value,d=l?.[lu];return d>=0&&(c.metadataFlags=d,c.localTime=l.localTime,c.value=l.value,c.residencyId=l.residencyId,l.expiresAt>0&&(c.expiresAt=l.expiresAt)),c&&(c.key=i),c};let r=e.get;e.get=function(i,o){let c=r.call(this,i,o);return c?.[lu]>=0?c.value:c};let n=e.getRange;e.getRange=function(i){let o=n.call(this,i);return i.valuesForKey?o.map(c=>c?.value):i.values===!1||i.onlyCount?o:o.map(c=>{let l=c.value,d=l[lu];return d>=0&&(c.metadataFlags=d,c.localTime=l.localTime,c.value=l.value,l.expiresAt>0&&(c.expiresAt=l.expiresAt)),c})};let s=e.useReadTransaction();if(s.done(),!s.done.isTracked){let i=s.constructor,o=s.use,c=s.done;i.prototype.use=function(){this.timerTracked||(this.timerTracked=!0,Go.push(new WeakRef(this))),o.call(this)},i.prototype.done=function(){if(c.call(this),this.isDone)for(let l=0;l<Go.length;l++){let d=Go[l].deref();(!d||d.isDone||d.isCommitted)&&Go.splice(l--,1)}},i.prototype.done.isTracked=!0}return e}function CS(e,t,r){return function(n,s,i,o,c=-1,l,d,u="put",f,E){f||l==null?oc=i?.localTime?AS|CI:RS:oc=l?i?.localTime?AS|16384:wI|16384:RS;let _=d?.expiresAt;if(_>0&&(c|=g_),uu=c,bS=_,i?.version===o&&l===!1)throw new Error("Must retain local time if version is not changed");let h={version:o,instructedWrite:oc>0},p,S=0;try{let g=i?.residencyId,T=d?.residencyId;T&&(yS=T,uu|=IS,S|=qo),g!==T&&(S|=Vo,g||(g=0)),c&g_&&(S|=Eu),d?.originatingOperation&&(S|=_u),f&&(h.ifVersion=p=i?.version??null);let A=e.put(n,s,h);if(l){let N=d?.user?.username;if(E&&(T_=e.encoder.encode(E)),e.encoder.hasStructureUpdate&&(S|=R_,e.encoder.hasStructureUpdate=!1),f&&i?.localTime){let V=i?.localTime,v=r.get(V);if(v){let J=Lt(v).previousLocalTime;return r.put(V,ac(o,t,n,J,d?.nodeId??server.replication.getThisNodeId(r)??0,N,u,T_,S,T,g,_),{ifVersion:p}),A}}r.put(fu,ac(o,t,n,i?.localTime?1:0,d?.nodeId??server.replication?.getThisNodeId(r)??0,N,u,T_,S,T,g,_,d?.originatingOperation),{append:u!=="invalidate",instructedWrite:!0,ifVersion:p})}return A}catch(g){throw g.message+=" id: "+n+" options: "+h,g}}}var II,gS,S_,fu,NS,CK,lu,du,DK,RS,wI,LK,CI,AS,g_,IS,wS,R_,PK,T_,oc,uu,bS,yS,OS,Go,cc=Oe(()=>{II=require("msgpackr");_i();gS=U(X()),S_=new Uint8Array([1,1,1,1,4,64,0,0]),fu=new Uint8Array([1,1,1,1,1,0,0,0]),NS=new Uint8Array([1,1,1,1,3,64,0,0]),CK=Symbol("local-timestamp"),lu=Symbol("metadata"),du=new Uint8Array(8),DK=new DataView(du.buffer,0,8),RS=0,wI=0,LK=1,CI=3,AS=4,g_=16,IS=32,wS=1,R_=256,oc=0,uu=-1,bS=0,yS=0,OS=class extends II.Encoder{static{a(this,"RecordEncoder")}constructor(t){t.useBigIntExtension=!0,super(t);let r=this.encode;this.encode=function(s,i){if(oc||uu>=0){let o=0,c=oc;c&&(o+=8,oc=0);let l=uu,d=bS,u=yS;l>=0&&(o+=2,uu=-1,d&&(o+=8,bS=0),u&&(o+=4,yS=0));let f=PK=r.call(this,s,i|2048|o);T_=f.subarray((f.start||0)+o,f.end);let E=f.start||0;return c&&(S_[4]=c,S_[5]=c>>8,f.set(S_,E),E+=8),l>=0&&(f[E++]=l&31,f[E++]=l>>5,d&&((f.dataView||(f.dataView=new DataView(f.buffer,f.byteOffset,f.byteLength))).setFloat64(E,d),E+=8),u&&(f.dataView||(f.dataView=new DataView(f.buffer,f.byteOffset,f.byteLength))).setUint32(E,u)),f}else return r.call(this,s,i)};let n=this.saveStructures;this.saveStructures=function(s,i){let o=n.call(this,s,i);return this.hasStructureUpdate=!0,o}}decode(t,r){let n=r?.start||0,s=r>-1?r:r?.end||t.length,i=t[n],o=0;try{if(i<32&&s>2){let c=n,l;if(i===2){if(t.copy)t.copy(du,0,c),c+=8;else for(let E=0;E<8;E++)du[E]=t[c++];l=MK(),i=t[c]}let d,u;i<32&&(o=i|t[c+1]<<5,c+=2,o&g_&&(d=(t.dataView||(t.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength))).getFloat64(c),c+=8),o&IS&&(u=(t.dataView||(t.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength))).getUint32(c),c+=4));let f=r?.valueAsBuffer?t.subarray(c,s):super.decode(t.subarray(c,s),s-c);return{localTime:l,value:f,[lu]:o,expiresAt:d,residencyId:u}}return r?.valueAsBuffer?t:super.decode(t,r)}catch(c){throw c.message+=", data: "+t.slice(0,40).toString("hex"),c}}};a(MK,"getTimestamp");a(A_,"handleLocalTimeForGets");Go=[];setInterval(()=>{for(let e=0;e<Go.length;e++){let t=Go[e].deref();!t||t.isDone||t.isCommitted?Go.splice(e--,1):t.notCurrent&&(t.openTimer?(t.openTimer>3&&(t.openTimer>60?(gS.error("Read transaction detected that has been open too long (over 15 minutes), ending transaction",t),t.done()):gS.error("Read transaction detected that has been open too long (over one minute), make sure read transactions are quickly closed",t)),t.openTimer++):t.openTimer=1)}},15e3).unref();a(CS,"getUpdateRecord")});var hu=I((Dfe,PI)=>{"use strict";var LI=ie(),UK=H(),{RecordEncoder:vK}=(cc(),ae(DI)),Cfe=require("fs");LI.initSync();var xK=LI.get(UK.CONFIG_PARAMS.STORAGE_CACHING)!==!1,DS=class{static{a(this,"OpenDBIObject")}constructor(t,r=!1){this.dupSort=t===!0,this.encoding=t?"ordered-binary":"msgpack",this.useVersions=r,this.sharedStructuresKey=Symbol.for("structures"),r&&(this.cache=xK&&{validated:!0},this.randomAccessStructure=!0,this.freezeData=!0,this.encoder={Encoder:vK})}};PI.exports=DS});var mu=I((Pfe,MI)=>{"use strict";var Sn=ie(),Fn=H();Sn.initSync();var b_=class{static{a(this,"OpenEnvironmentObject")}constructor(t,r=!1){this.path=t,this.mapSize=1073741824,this.maxDbs=1e4,this.maxReaders=1e3,this.sharedStructuresKey=Symbol.for("structures"),this.readOnly=r,this.trackMetrics=!0,this.eventTurnBatching=!1,this.noSync=Sn.get(Fn.CONFIG_PARAMS.STORAGE_WRITEASYNC)===!0||Sn.get(Fn.CONFIG_PARAMS.STORAGE_WRITEASYNC)==="true"||Sn.get(Fn.CONFIG_PARAMS.STORAGE_WRITEASYNC)==="TRUE",Sn.get(Fn.CONFIG_PARAMS.STORAGE_OVERLAPPINGSYNC)!==void 0&&(this.overlappingSync=Sn.get(Fn.CONFIG_PARAMS.STORAGE_OVERLAPPINGSYNC)),Sn.get(Fn.CONFIG_PARAMS.STORAGE_MAXFREESPACETOLOAD)&&(this.maxFreeSpaceToLoad=Sn.get(Fn.CONFIG_PARAMS.STORAGE_MAXFREESPACETOLOAD)),Sn.get(Fn.CONFIG_PARAMS.STORAGE_MAXFREESPACETORETAIN)&&(this.maxFreeSpaceToRetain=Sn.get(Fn.CONFIG_PARAMS.STORAGE_MAXFREESPACETORETAIN)),Sn.get(Fn.CONFIG_PARAMS.STORAGE_PAGESIZE)&&(this.pageSize=Sn.get(Fn.CONFIG_PARAMS.STORAGE_PAGESIZE)),this.noReadAhead=Sn.get(Fn.CONFIG_PARAMS.STORAGE_NOREADAHEAD)}};MI.exports=b_;b_.MAX_DBS=1e4});var ft=I((Ufe,VI)=>{"use strict";var PS=require("lmdb"),us=require("fs-extra"),Tn=require("path"),y_=hn(),xI=X(),Vr=En().LMDB_ERRORS_ENUM,O_=NI(),MS=hu(),BI=mu(),Ji=Ft(),UI=H(),{table:BK,resetDatabases:HK}=(Ne(),ae(it)),vI=ie(),ds=Ji.INTERNAL_DBIS_NAME,HI=Ji.DBI_DEFINITION_NAME,kK="data.mdb",FK="lock.mdb",pu=".mdb",GK="-lock",LS=class{static{a(this,"TransactionCursor")}constructor(t,r,n=!1){this.dbi=Gn(t,r),this.key_type=this.dbi[Ji.DBI_DEFINITION_NAME].key_type,this.is_hash_attribute=this.dbi[Ji.DBI_DEFINITION_NAME].is_hash_attribute,this.txn=t.beginTxn({readOnly:n===!1}),this.cursor=new PS.Cursor(this.txn,this.dbi)}close(){this.cursor.close(),this.txn.abort()}commit(){this.cursor.close(),this.txn.commit()}};function N_(e,t){if(e===void 0)throw new Error(Vr.BASE_PATH_REQUIRED);if(t===void 0)throw new Error(Vr.ENV_NAME_REQUIRED)}a(N_,"pathEnvNameValidation");async function US(e,t,r=!0){try{await us.access(e)}catch(n){throw n.code==="ENOENT"?new Error(Vr.INVALID_BASE_PATH):n}try{let n=Tn.join(e,t+pu);return await us.access(n,us.constants.R_OK|us.constants.F_OK),n}catch(n){if(n.code==="ENOENT")if(r)try{return await us.access(Tn.join(e,t,kK),us.constants.R_OK|us.constants.F_OK),Tn.join(e,t)}catch(s){if(s.code==="ENOENT")throw new Error(Vr.INVALID_ENVIRONMENT)}else throw new Error(Vr.INVALID_ENVIRONMENT);throw n}}a(US,"validateEnvironmentPath");function I_(e,t){if(y_.validateEnv(e),t===void 0)throw new Error(Vr.DBI_NAME_REQUIRED)}a(I_,"validateEnvDBIName");async function qK(e,t,r=!1,n=!1){N_(e,t);let s=Tn.basename(e);t=t.toString();let i=vI.get(UI.CONFIG_PARAMS.DATABASES);i||vI.setProperty(UI.CONFIG_PARAMS.DATABASES,i={}),i[s]||(i[s]={}),i[s].path=e;try{return await US(e,t,n),kI(e,t,r)}catch(o){if(o.message===Vr.INVALID_ENVIRONMENT){let c=Tn.join(e,t);await us.mkdirp(n?c:e);let l=new BI(n?c:c+pu,!1),d=PS.open(l);d.dbis=Object.create(null);let u=new MS(!1);d.openDB(ds,u),global.lmdb_map===void 0&&(global.lmdb_map=Object.create(null));let f=vS(e,t,r);return d[Ji.ENVIRONMENT_NAME_KEY]=f,global.lmdb_map[f]=d,d}throw o}}a(qK,"createEnvironment");async function VK(e,t,r,n=!0){N_(e,t),t=t.toString();let s=Tn.join(e,t);return BK({table:t,database:Tn.parse(e).name,path:s,attributes:[{name:"id",isPrimaryKey:!0}]})}a(VK,"copyEnvironment");async function kI(e,t,r=!1){N_(e,t),t=t.toString();let n=vS(e,t,r);if(global.lmdb_map===void 0&&(global.lmdb_map=Object.create(null)),global.lmdb_map[n]!==void 0)return global.lmdb_map[n];let s=await US(e,t),i=Tn.join(e,t+pu),o=s!=i,c=new BI(s,o),l=PS.open(c);l.dbis=Object.create(null);let d=GI(l);for(let u=0;u<d.length;u++)Gn(l,d[u]);return l[Ji.ENVIRONMENT_NAME_KEY]=n,global.lmdb_map[n]=l,l}a(kI,"openEnvironment");async function $K(e,t,r=!1){N_(e,t),t=t.toString();let n=Tn.join(e,t+pu),s=await US(e,t);if(global.lmdb_map!==void 0){let i=vS(e,t,r);if(global.lmdb_map[i]){let o=global.lmdb_map[i];await FI(o),delete global.lmdb_map[i]}}await us.remove(s),await us.remove(s===n?s+GK:Tn.join(Tn.dirname(s),FK))}a($K,"deleteEnvironment");async function FI(e){y_.validateEnv(e);let t=e[Ji.ENVIRONMENT_NAME_KEY];await e.close(),t!==void 0&&global.lmdb_map!==void 0&&delete global.lmdb_map[t]}a(FI,"closeEnvironment");function vS(e,t,r=!1){let s=`${Tn.basename(e)}.${t}`;return r===!0&&(s=`txn.${s}`),s}a(vS,"getCachedEnvironmentName");function YK(e){y_.validateEnv(e);let t=Object.create(null),r=Gn(e,ds);for(let{key:n,value:s}of r.getRange({start:!1}))if(n!==ds)try{t[n]=Object.assign(new O_,s)}catch{xI.warn(`an internal error occurred: unable to parse DBI Definition for ${n}`)}return t}a(YK,"listDBIDefinitions");function GI(e){y_.validateEnv(e);let t=[],r=Gn(e,ds);for(let{key:n}of r.getRange({start:!1}))n!==ds&&t.push(n);return t}a(GI,"listDBIs");function KK(e,t){let n=Gn(e,ds).getEntry(t),s=new O_;if(n!==void 0){try{s=Object.assign(s,n.value)}catch{xI.warn(`an internal error occurred: unable to parse DBI Definition for ${n}`)}return s}}a(KK,"getDBIDefinition");function qI(e,t,r,n=!r){if(I_(e,t),t=t.toString(),t===ds)throw new Error(Vr.CANNOT_CREATE_INTERNAL_DBIS_NAME);try{return Gn(e,t)}catch(s){if(s.message===Vr.DBI_DOES_NOT_EXIST){let i=new MS(r,n===!0),o=e.openDB(t,i),c=new O_(r===!0,n);return o[HI]=c,Gn(e,ds).putSync(t,c),e.dbis[t]=o,o}throw s}}a(qI,"createDBI");function Gn(e,t){if(I_(e,t),t=t.toString(),e.dbis[t]!==void 0)return e.dbis[t];let r;if(t!==ds?r=KK(e,t):r=new O_,r===void 0)throw new Error(Vr.DBI_DOES_NOT_EXIST);let n;try{let s=new MS(r.dup_sort,r.useVersions);if(n=e.openDB(t,s),n.db===void 0)throw new Error("MDB_NOTFOUND")}catch(s){throw s.message.includes("MDB_NOTFOUND")===!0?new Error(Vr.DBI_DOES_NOT_EXIST):s}return n[HI]=r,e.dbis[t]=n,n}a(Gn,"openDBI");function WK(e,t){I_(e,t),t=t.toString();let r=Gn(e,t),n=r.getStats();return r[Ji.DBI_DEFINITION_NAME].is_hash_attribute&&n.entryCount>0&&n.entryCount--,n}a(WK,"statDBI");async function QK(e,t){try{let r=Tn.join(e,t+pu);return(await us.stat(r)).size}catch{throw new Error(Vr.INVALID_ENVIRONMENT)}}a(QK,"environmentDataSize");function zK(e,t){if(I_(e,t),t=t.toString(),t===ds)throw new Error(Vr.CANNOT_DROP_INTERNAL_DBIS_NAME);Gn(e,t).dropSync(),e.dbis!==void 0&&delete e.dbis[t],Gn(e,ds).removeSync(t)}a(zK,"dropDBI");function jK(e,t,r){let n;for(let s=0;s<r.length;s++){let i=r[s];if(!e.dbis[i])try{Gn(e,i)}catch(o){if(o.message===Vr.DBI_DOES_NOT_EXIST)qI(e,i,i!==t,i===t),n=!0;else throw o}}n&&HK()}a(jK,"initializeDBIs");VI.exports={openDBI:Gn,openEnvironment:kI,createEnvironment:qK,listDBIs:GI,listDBIDefinitions:YK,createDBI:qI,dropDBI:zK,statDBI:WK,deleteEnvironment:$K,initializeDBIs:jK,TransactionCursor:LS,environmentDataSize:QK,copyEnvironment:VK,closeEnvironment:FI}});var YI=I((xfe,$I)=>{"use strict";var xS=class{static{a(this,"InsertRecordsResponseObject")}constructor(t=[],r=[],n=void 0){this.written_hashes=t,this.skipped_hashes=r,this.txn_time=n}};$I.exports=xS});var WI=I((Hfe,KI)=>{"use strict";var BS=class{static{a(this,"UpdateRecordsResponseObject")}constructor(t=[],r=[],n=void 0,s=[]){this.written_hashes=t,this.skipped_hashes=r,this.txn_time=n,this.original_records=s}};KI.exports=BS});var zI=I((Ffe,QI)=>{"use strict";var HS=class{static{a(this,"UpsertRecordsResponseObject")}constructor(t=[],r=void 0,n=[]){this.written_hashes=t,this.txn_time=r,this.original_records=n}};QI.exports=HS});var lc=I((Yfe,XI)=>{"use strict";var JK=ft(),XK=YI(),ZK=WI(),eW=zI(),Us=hn(),Su=En().LMDB_ERRORS_ENUM,tW=Ft(),Ei=H(),rW=re(),nW=require("uuid"),qfe=require("lmdb"),{handleHDBError:sW,hdb_errors:iW}=ce(),{OVERFLOW_MARKER:Vfe,MAX_SEARCH_KEY_LENGTH:$fe}=tW,jI=ie();jI.initSync();var w_=jI.get(Ei.CONFIG_PARAMS.STORAGE_PREFETCHWRITES),kS=Ei.TIME_STAMP_NAMES_ENUM.CREATED_TIME,$o=Ei.TIME_STAMP_NAMES_ENUM.UPDATED_TIME;async function oW(e,t,r,n,s=Us.getNextMonotonicTime()){VS(e,t,r,n),FS(e,t,r);let i=new XK,o=[],c=[];for(let l=0;l<n.length;l++){let d=n[l];JI(d,!0,s);let u=aW(e,t,r,d),f=d[t];o.push(u),c.push(f)}return GS(o,c,n,i,s)}a(oW,"insertRecords");function aW(e,t,r,n){let s=n[t];return e.dbis[t].ifNoExists(s,()=>{for(let i=0;i<r.length;i++){let o=r[i];if(o===t||n.hasOwnProperty(o)===!1)continue;let c=n[o];if(typeof c=="function"){let u=c([[{}]]);Array.isArray(u)&&(c=u[0][Ei.FUNC_VAL],n[o]=c)}let l=Us.getIndexedValues(c),d=e.dbis[o];if(l){w_&&d.prefetch(l.map(u=>({key:u,value:s})),C_);for(let u=0,f=l.length;u<f;u++)d.put(l[u],s)}}w_&&e.dbis[t].prefetch([s],C_),e.dbis[t].put(s,n,n[$o])})}a(aW,"insertRecord");function cW(e,t=[]){let r=0;for(let n=0;n<t.length;n++){let s=t[n];e.splice(s-r,1),r++}}a(cW,"removeSkippedRecords");function JI(e,t,r){let n=r>0;(n||!Number.isInteger(e[$o]))&&(e[$o]=r||(r=Us.getNextMonotonicTime())),t===!0?(n||!Number.isInteger(e[kS]))&&(e[kS]=r||Us.getNextMonotonicTime()):delete e[kS]}a(JI,"setTimestamps");function FS(e,t,r){r.indexOf(Ei.TIME_STAMP_NAMES_ENUM.CREATED_TIME)<0&&r.push(Ei.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.indexOf(Ei.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)<0&&r.push(Ei.TIME_STAMP_NAMES_ENUM.UPDATED_TIME),JK.initializeDBIs(e,t,r)}a(FS,"initializeTransaction");async function lW(e,t,r,n,s=Us.getNextMonotonicTime()){VS(e,t,r,n),FS(e,t,r);let i=new ZK,o=[],c=[],l=[];for(let d=0;d<n.length;d++){let u=n[d],f=u[t],E;try{E=qS(e,t,u,f,i,!0,s)}catch{i.skipped_hashes.push(f),o.push(d);continue}c.push(E),l.push(f)}return GS(c,l,n,i,s,o)}a(lW,"updateRecords");async function uW(e,t,r,n,s=Us.getNextMonotonicTime()){try{VS(e,t,r,n)}catch(l){throw sW(l,l.message,iW.HTTP_STATUS_CODES.BAD_REQUEST)}FS(e,t,r);let i=new eW,o=[],c=[];for(let l=0;l<n.length;l++){let d=n[l],u;rW.isEmpty(d[t])?(u=nW.v4(),d[t]=u):u=d[t];let f=qS(e,t,d,u,i,!1,s);o.push(f),c.push(u)}return GS(o,c,n,i,s)}a(uW,"upsertRecords");async function GS(e,t,r,n,s,i=[]){let o=await Promise.all(e);for(let c=0,l=o.length;c<l;c++)o[c]===!0?n.written_hashes.push(t[c]):(n.skipped_hashes.push(t[c]),i.push(c));return n.txn_time=s||Us.getNextMonotonicTime(),cW(r,i),n}a(GS,"finalizeWrite");function qS(e,t,r,n,s,i=!1,o){let c=e.dbis[t],l=c.getEntry(n),d=l?.value,u=d;if(!d){if(i)return!1;d={}}if(JI(r,!u,o),Number.isInteger(r[$o])&&d[$o]>r[$o])return!1;u&&s.original_records.push(d);let f,E=a(()=>{for(let h in r){if(!r.hasOwnProperty(h)||h===t)continue;let p=r[h],S=e.dbis[h];if(S===void 0)continue;let g=d[h];if(typeof p=="function"){let A=p([[d]]);Array.isArray(A)&&(p=A[0][Ei.FUNC_VAL],r[h]=p)}if(p===g)continue;let T=Us.getIndexedValues(g);if(T){w_&&S.prefetch(T.map(A=>({key:A,value:n})),C_);for(let A=0,N=T.length;A<N;A++)S.remove(T[A],n)}if(T=Us.getIndexedValues(p),T){w_&&S.prefetch(T.map(A=>({key:A,value:n})),C_);for(let A=0,N=T.length;A<N;A++)S.put(T[A],n)}}let _=Object.assign({},d,r);c.put(n,_,_[$o])},"do_put");return l?f=c.ifVersion(n,l.version,E):f=c.ifNoExists(n,E),f.then(_=>_?!0:qS(e,t,r,n,s,i,o))}a(qS,"updateUpsertRecord");function dW(e,t,r){if(Us.validateEnv(e),t===void 0)throw new Error(Su.HASH_ATTRIBUTE_REQUIRED);if(!Array.isArray(r))throw r===void 0?new Error(Su.WRITE_ATTRIBUTES_REQUIRED):new Error(Su.WRITE_ATTRIBUTES_MUST_BE_ARRAY)}a(dW,"validateBasic");function VS(e,t,r,n){if(dW(e,t,r),!Array.isArray(n))throw n===void 0?new Error(Su.RECORDS_REQUIRED):new Error(Su.RECORDS_MUST_BE_ARRAY)}a(VS,"validateWrite");function C_(){}a(C_,"noop");XI.exports={insertRecords:oW,updateRecords:lW,upsertRecords:uW}});var Yo=I((Wfe,fW)=>{fW.exports={hdb_user:{hash_attribute:"username",name:"hdb_user",schema:"system",residence:["*"],attributes:[{attribute:"username"},{attribute:"password"},{attribute:"role"},{attribute:"active"},{attribute:"hash"},{attribute:"refresh_token"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_role:{hash_attribute:"id",name:"hdb_role",schema:"system",attributes:[{attribute:"id"},{attribute:"role"},{attribute:"permission"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}],residence:["*"]},hdb_job:{hash_attribute:"id",name:"hdb_job",schema:"system",attributes:[{attribute:"id"},{attribute:"user"},{attribute:"type"},{attribute:"status"},{attribute:"start_datetime"},{attribute:"end_datetime"},{attribute:"message"},{attribute:"created_datetime"},{attribute:"request"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_license:{hash_attribute:"license_key",name:"hdb_license",schema:"system",attributes:[{attribute:"license_key"},{attribute:"company"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_info:{hash_attribute:"info_id",name:"hdb_info",schema:"system",attributes:[{attribute:"info_id"},{attribute:"data_version_num"},{attribute:"hdb_version_num"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_nodes:{hash_attribute:"name",name:"hdb_nodes",schema:"system",attributes:[{attribute:"name"},{attribute:"subscriptions"},{attribute:"system_info"},{attribute:"url"},{attribute:"routes"}]},hdb_certificate:{hash_attribute:"name",name:"hdb_certificate",schema:"system",attributes:[{attribute:"name"},{attribute:"uses"},{attribute:"certificate"},{attribute:"is_authority"},{attribute:"private_key_name"},{attribute:"details"},{attribute:"is_self_signed"},{attribute:"__updatedtime__"}]},hdb_analytics:{hash_attribute:"id",name:"hdb_analytics",schema:"system",audit:!1,attributes:[{attribute:"id"},{name:"metric"},{name:"path"},{name:"method"},{name:"type"}]},hdb_raw_analytics:{hash_attribute:"id",name:"hdb_raw_analytics",schema:"system",audit:!1,attributes:[{attribute:"id"},{attribute:"time"},{attribute:"metrics"}]},hdb_temp:{hash_attribute:"id",name:"hdb_temp",schema:"system",attributes:[{attribute:"id"}]},hdb_durable_session:{hash_attribute:"id",name:"hdb_durable_session",schema:"system",attributes:[{attribute:"id"}]},hdb_session_will:{hash_attribute:"id",name:"hdb_session_will",schema:"system",attributes:[{attribute:"id"}]}}});var xs=I((Qfe,tw)=>{"use strict";var ew=re(),ZI=H(),uc=/^[\x20-\x2E|\x30-\x5F|\x61-\x7E]*$/,vs=require("joi"),Xi={schema_format:{pattern:uc,message:"names cannot include backticks or forward slashes"},schema_length:{minimum:1,maximum:250,tooLong:"cannot exceed 250 characters"}},_W=vs.alternatives(vs.string().min(1).max(Xi.schema_length.maximum).pattern(uc).messages({"string.pattern.base":"{:#label} "+Xi.schema_format.message}),vs.number(),vs.array()).required(),EW=vs.alternatives(vs.string().min(1).max(Xi.schema_length.maximum).pattern(uc).messages({"string.pattern.base":"{:#label} "+Xi.schema_format.message}),vs.number()),hW=vs.alternatives(vs.string().min(1).max(Xi.schema_length.maximum).pattern(uc).messages({"string.pattern.base":"{:#label} "+Xi.schema_format.message}),vs.number()).required();function mW(e,t){return t?typeof t!="string"?`'${e}' must be a string`:t.length?t.length>Xi.schema_length.maximum?`'${e}' maximum of 250 characters`:uc.test(t)?"":`'${e}' has illegal characters`:`'${e}' must be at least one character`:`'${e}' is required`}a(mW,"checkValidTable");function pW(e,t){return ew.doesSchemaExist(e)?e:t.message(`Database '${e}' does not exist`)}a(pW,"validateSchemaExists");function SW(e,t){let r=t.state.ancestors[0].schema;return ew.doesTableExist(r,e)?e:t.message(`Table '${e}' does not exist`)}a(SW,"validateTableExists");function TW(e,t){return e.toLowerCase()===ZI.SYSTEM_SCHEMA_NAME?t.message(`'subscriptions[${t.state.path[1]}]' invalid database name, '${ZI.SYSTEM_SCHEMA_NAME}' name is reserved`):e}a(TW,"validateSchemaName");tw.exports={common_validators:Xi,schema_regex:uc,hdb_schema_table:_W,validateSchemaExists:pW,validateTableExists:SW,validateSchemaName:TW,checkValidTable:mW,hdb_database:EW,hdb_table:hW}});var mt=I((jfe,rw)=>{"use strict";var $r=require("validate.js");$r.validators.type=function(e,t,r,n){return e===null||typeof e>"u"||$r.validators.type.checks[t](e)?null:` must be a '${t}' value`};$r.validators.type.checks={Object:function(e){return $r.isObject(e)&&!$r.isArray(e)},Array:$r.isArray,Integer:$r.isInteger,Number:$r.isNumber,String:$r.isString,Date:$r.isDate,Boolean:function(e){return typeof e=="boolean"}};$r.validators.hasValidFileExt=function(e,t){return $r.isString(e)?e===""?"can't be blank":t.filter(r=>e.endsWith(r)).length>0?null:`must include one of the following valid file extensions - '${t.join("', '")}'`:null};rw.exports={validateObject:gW,validateObjectAsync:RW,validateBySchema:AW};function gW(e,t){if(!e||!t)return new Error("validateObject parameters were null");let r=$r(e,t,{format:"flat"});return r?new Error(r):null}a(gW,"validateObject");async function RW(e,t){if(!e||!t)return new Error("validateObject parameters were null");try{await $r.async(e,t,{format:"flat"})}catch(r){let n=r.join(",");return new Error(n)}return null}a(RW,"validateObjectAsync");function AW(e,t){let r=t.validate(e,{allowUnknown:!0,abortEarly:!1,errors:{wrap:{label:"'"}}});if(r.error)return new Error(r.error.message)}a(AW,"validateBySchema")});var D_=I((Xfe,nw)=>{var{common_validators:Bs}=xs(),gu=mt(),Tu="is required",Qt={database:{presence:!1,format:Bs.schema_format,length:Bs.schema_length},schema:{presence:!1,format:Bs.schema_format,length:Bs.schema_length},table:{presence:!0,format:Bs.schema_format,length:Bs.schema_length},attribute:{presence:!0,format:Bs.schema_format,length:Bs.schema_length},hash_attribute:{presence:!0,format:Bs.schema_format,length:Bs.schema_length}};function Ru(e){for(let t in e)e[t]=e[t]===null||e[t]===void 0||typeof e[t]=="object"?e[t]:e[t].toString();return e}a(Ru,"makeAttributesStrings");function bW(e){return e=Ru(e),Qt.table.presence=!1,Qt.attribute.presence=!1,Qt.hash_attribute.presence=!1,gu.validateObject(e,Qt)}a(bW,"schema_object");function yW(e){return e=Ru(e),Qt.table.presence={message:Tu},Qt.attribute.presence=!1,Qt.hash_attribute.presence=!1,gu.validateObject(e,Qt)}a(yW,"table_object");function OW(e){return e=Ru(e),Qt.table.presence={message:Tu},Qt.attribute.presence=!1,gu.validateObject(e,Qt)}a(OW,"create_table_object");function NW(e){return e=Ru(e),Qt.table.presence={message:Tu},Qt.attribute.presence={message:Tu},Qt.hash_attribute.presence=!1,gu.validateObject(e,Qt)}a(NW,"attribute_object");function IW(e){return e=Ru(e),Qt.table.presence={message:Tu},Qt.attribute.presence=!1,Qt.hash_attribute.presence=!1,gu.validateObject(e,Qt)}a(IW,"describe_table");function wW(e){if(e){if(!Array.isArray(e))throw new Error("residence must be a string array");if(e.length===0)throw new Error("residence cannot be an empty array");for(let t=0;t<e.length;t++)if(typeof e[t]!="string")throw new Error(`residence must be a string array, item '${e[t]}' is not a string`)}}a(wW,"validateTableResidence");nw.exports={schema_object:bW,create_table_object:OW,table_object:yW,attribute_object:NW,describe_table:IW,validateTableResidence:wW}});var iw=I((e_e,sw)=>{"use strict";var CW=require("uuid"),$S=class{static{a(this,"CreateAttributeObject")}constructor(t,r,n,s){this.schema=t,this.table=r,this.attribute=n,this.id=s||CW.v4(),this.schema_table=`${this.schema}.${this.table}`}};sw.exports=$S});var L_=I((r_e,ow)=>{"use strict";var DW=iw(),YS=class extends DW{static{a(this,"LMDBCreateAttributeObject")}constructor(t,r,n,s,i=!0,o=!1){super(t,r,n,s),this.dup_sort=i,this.is_hash_attribute=o}};ow.exports=YS});var cw=I((s_e,aw)=>{"use strict";aw.exports=PW;var LW="inserted";function PW(e,t,r,n){let s={message:`${e} ${t.length} of ${r.records.length} records`,skipped_hashes:n};return e===LW?(s.inserted_hashes=t,s):(s.update_hashes=t,s)}a(PW,"returnObject")});var P_=I((a_e,fw)=>{"use strict";var MW=H(),KS=ft(),UW=lc(),{getSystemSchemaPath:vW,getSchemaPath:xW}=ht(),o_e=Yo(),BW=D_(),HW=L_(),kW=cw(),{handleHDBError:lw,hdb_errors:dw}=ce(),uw=re(),{HTTP_STATUS_CODES:FW}=dw,GW="inserted";fw.exports=qW;async function qW(e){let t=BW.attribute_object(e);if(t)throw lw(new Error,t.message,dw.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0);let r=!e.skip_table_check&&uw.checkGlobalSchemaTable(e.schema,e.table);if(r)throw lw(new Error,r,FW.NOT_FOUND);e.is_hash_attribute=e.is_hash_attribute=="true",e.dup_sort=uw.isEmpty(e.dup_sort)||e.dup_sort=="true";let n=[];if(global.hdb_schema[e.schema]&&global.hdb_schema[e.schema][e.table]&&(n=global.hdb_schema[e.schema][e.table].attributes),Array.isArray(n)&&n.length>0){for(let i of n)if(i.attribute===e.attribute)throw new Error(`attribute '${i.attribute}' already exists in ${e.schema}.${e.table}`)}let s=new HW(e.schema,e.table,e.attribute,e.id);try{let i=await KS.openEnvironment(xW(e.schema,e.table),e.table);if(i.dbis[e.attribute]!==void 0)throw new Error(`attribute '${e.attribute}' already exists in ${e.schema}.${e.table}`);KS.createDBI(i,e.attribute,e.dup_sort,e.is_hash_attribute);let o=await KS.openEnvironment(vW(),MW.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME),{written_hashes:c,skipped_hashes:l}=await UW.insertRecords(o,HDB_TABLE_INFO.hash_attribute,hdb_attribute_attributes,[s]);return kW(GW,c,{records:[s]},l)}catch(i){throw i}}a(qW,"lmdbCreateAttribute")});var QS=I((l_e,Ew)=>{var{hdb_table:VW,hdb_database:_w}=xs(),$W=mt(),WS=require("joi"),YW={undefined:"undefined",null:"null"},KW=a((e,t)=>{let r=Object.keys(e),n=r.length,s;for(let i=0;i<n;i++){let o=r[i];(!o||o.length===0||YW[o]!==void 0)&&(s===void 0?s=`Invalid attribute name: '${o}'`:s+=`. Invalid attribute name: '${o}'`)}return s?t.message(s):e},"custom_records_val"),WW=WS.object({database:_w,schema:_w,table:VW,records:WS.array().items(WS.object().custom(KW)).required()});Ew.exports=function(e){return $W.validateBySchema(e,WW)}});var Au=I((f_e,mw)=>{"use strict";var hi=re(),hw=X(),d_e=QS(),{getDatabases:QW}=(Ne(),ae(it)),{ClientError:Ko}=ce();mw.exports=zW;function zW(e){if(hi.isEmpty(e))throw new Ko("invalid update parameters defined.");if(hi.isEmptyOrZeroLength(e.schema))throw new Ko("invalid schema specified.");if(hi.isEmptyOrZeroLength(e.table))throw new Ko("invalid table specified.");if(!Array.isArray(e.records))throw new Ko("records must be an array");let t=QW()[e.schema]?.[e.table];if(hi.isEmpty(t))throw new Ko(`could not retrieve schema:${e.schema} and table ${e.table}`);let r=t.primaryKey,n=new Set,s={},i=!1;return e.operation==="update"&&(i=!0),e.records.forEach(o=>{if(i&&hi.isEmptyOrZeroLength(o[r]))throw hw.error("a valid hash attribute must be provided with update record:",o),new Ko("a valid hash attribute must be provided with update record, check log for more info");if(!hi.isEmptyOrZeroLength(o[r])&&(o[r]==="null"||o[r]==="undefined"))throw hw.error(`a valid hash value must be provided with ${e.operation} record:`,o),new Ko(`Invalid hash value: '${o[r]}' is not a valid hash attribute value, check log for more info`);!hi.isEmpty(o[r])&&o[r]!==""&&n.has(hi.autoCast(o[r]))&&(o.skip=!0),n.add(hi.autoCast(o[r]));for(let c in o)s[c]=1}),s[r]=1,{schema_table:t,hashes:Array.from(n),attributes:Object.keys(s)}}a(zW,"insertUpdateValidate")});var bu=I((E_e,pw)=>{"use strict";var jW=H().OPERATIONS_ENUM,zS=class{static{a(this,"InsertObject")}constructor(t,r,n,s,i=void 0){this.operation=jW.INSERT,this.schema=t,this.table=r,this.hash_attribute=n,this.records=s,this.__origin=i}};pw.exports=zS});var yu=I((p_e,Tw)=>{"use strict";var m_e=bu(),M_=H(),jS=re(),Sw=X(),JW=require("uuid"),{handleHDBError:U_,hdb_errors:XW}=ce(),{HDB_ERROR_MSGS:v_,HTTP_STATUS_CODES:x_}=XW;Tw.exports=ZW;function ZW(e,t,r){for(let s=0;s<t.length;s++)eQ(t[s]);let{records:n}=e;for(let s=0;s<n.length;s++){let i=n[s];tQ(i,r,e.operation)}}a(ZW,"processRows");function eQ(e){if(Buffer.byteLength(String(e))>M_.INSERT_MODULE_ENUM.MAX_CHARACTER_SIZE)throw U_(new Error,v_.ATTR_NAME_LENGTH_ERR(e),x_.BAD_REQUEST,void 0,void 0,!0);if(jS.isEmptyOrZeroLength(e)||jS.isEmpty(e.trim()))throw U_(new Error,v_.ATTR_NAME_NULLISH_ERR,x_.BAD_REQUEST,void 0,void 0,!0)}a(eQ,"validateAttribute");function tQ(e,t,r){if(!e.hasOwnProperty(t)||jS.isEmptyOrZeroLength(e[t])){if(r===M_.OPERATIONS_ENUM.INSERT||r===M_.OPERATIONS_ENUM.UPSERT){e[t]=JW.v4();return}throw Sw.error("Update transaction aborted due to record with no hash value:",e),U_(new Error,v_.RECORD_MISSING_HASH_ERR,x_.BAD_REQUEST,void 0,void 0,!0)}if(Buffer.byteLength(String(e[t]))>M_.INSERT_MODULE_ENUM.MAX_CHARACTER_SIZE)throw Sw.error(e),U_(new Error,v_.HASH_VAL_LENGTH_ERR,x_.BAD_REQUEST,void 0,void 0,!0)}a(tQ,"validateHash")});var Rw=I((T_e,gw)=>{"use strict";var JS=class{static{a(this,"ITCEventObject")}constructor(t,r){this.type=t,this.message=r}};gw.exports=JS});var yw=I((R_e,bw)=>{"use strict";var XS=ft(),rQ=X(),Aw=En().LMDB_ERRORS_ENUM;bw.exports=nQ;async function nQ(e){try{if(global.lmdb_map!==void 0&&e.operation!==void 0){let t=Object.keys(global.lmdb_map),r;switch(e.operation){case"drop_schema":for(let i=0;i<t.length;i++){let o=t[i];if(o.startsWith(`${e.schema}.`)||o.startsWith(`txn.${e.schema}.`))try{await XS.closeEnvironment(global.lmdb_map[o])}catch(c){if(c.message!==Aw.ENV_REQUIRED)throw c}}break;case"drop_table":let n=`${e.schema}.${e.table}`,s=`txn.${n}`;try{await XS.closeEnvironment(global.lmdb_map[n]),await XS.closeEnvironment(global.lmdb_map[s])}catch(i){if(i.message!==Aw.ENV_REQUIRED)throw i}break;case"drop_attribute":r=global.lmdb_map[`${e.schema}.${e.table}`],r!==void 0&&typeof r.dbis=="object"&&r.dbis[`${e.attribute}`]!==void 0&&delete r.dbis[`${e.attribute}`];break;default:break}}}catch(t){rQ.error(t)}}a(nQ,"cleanLMDBMap")});var mi=I((b_e,ww)=>{"use strict";var Ou=require("crypto"),sQ=ie(),{CONFIG_PARAMS:iQ}=H(),Nw="aes-256-cbc",oQ=32,aQ=16,ZS=64,Iw=32,cQ=ZS+Iw,Ow=new Map;ww.exports={encrypt:lQ,decrypt:uQ,createNatsTableStreamName:dQ};function lQ(e){let t=Ou.randomBytes(oQ),r=Ou.randomBytes(aQ),n=Ou.createCipheriv(Nw,Buffer.from(t),r),s=n.update(e);s=Buffer.concat([s,n.final()]);let i=t.toString("hex"),o=r.toString("hex"),c=s.toString("hex");return i+o+c}a(lQ,"encrypt");function uQ(e){let t=e.substr(0,ZS),r=e.substr(ZS,Iw),n=e.substr(cQ,e.length),s=Buffer.from(r,"hex"),i=Buffer.from(n,"hex"),o=Ou.createDecipheriv(Nw,Buffer.from(t,"hex"),s),c=o.update(i);return c=Buffer.concat([c,o.final()]),c.toString()}a(uQ,"decrypt");function dQ(e,t){let r=sQ.get(iQ.CLUSTERING_DATABASELEVEL)?e:`${e}.${t}`,n=Ow.get(r);return n||(n=Ou.createHash("md5").update(r).digest("hex"),Ow.set(r,n)),n}a(dQ,"createNatsTableStreamName")});var Zi=I((N_e,Dw)=>{"use strict";var O_e=gn(),Nu=X(),Cw=D_(),fQ=mi(),B_=re(),{handleHDBError:H_,hdb_errors:_Q}=ce(),{HDB_ERROR_MSGS:k_,HTTP_STATUS_CODES:eT}=_Q,EQ=ie();EQ.initSync();var{getDatabases:tT}=(Ne(),ae(it)),hQ=require("fs-extra");Dw.exports={describeAll:mQ,describeTable:F_,describeSchema:pQ};async function mQ(e){try{let t=B_.isEmptyOrZeroLength(e),r,n;t||(r=e.hdb_user.role.permission,n=r.super_user||r.cluster_user);let s=tT(),i={},o={},c=[],l=e?.exact_count;for(let u in s){i[u]=!0,!t&&!n&&(o[u]=e.hdb_user.role.permission[u].describe);let f=s[u];for(let E in f)try{let _;if(t||n)_=await F_({schema:u,table:E,exact_count:l});else if(r&&r[u].describe&&r[u].tables[E].describe){let h=r[u].tables[E].attribute_permissions;_=await F_({schema:u,table:E,exact_count:l},h)}_&&c.push(_)}catch(_){Nu.error(_)}}let d={};for(let u in c)t||n?(d[c[u].schema]==null&&(d[c[u].schema]={}),d[c[u].schema][c[u].name]=c[u],i[c[u].schema]&&delete i[c[u].schema]):o[c[u].schema]&&(d[c[u].schema]==null&&(d[c[u].schema]={}),d[c[u].schema][c[u].name]=c[u],i[c[u].schema]&&delete i[c[u].schema]);for(let u in i)t||n?d[u]={}:o[u]&&(d[u]={});return d}catch(t){return Nu.error("Got an error in describeAll"),Nu.error(t),H_(new Error,k_.DESCRIBE_ALL_ERR)}}a(mQ,"describeAll");async function F_(e,t){B_.transformReq(e);let{schema:r,table:n}=e;r=r?.toString(),n=n?.toString();let s=t;e.hdb_user&&!e.hdb_user.role.permission.super_user&&(s=e.hdb_user.role.permission[r].tables[n].attribute_permissions);let i=Cw.describe_table(e);if(i)throw i;let c=tT()[r];if(!c)throw H_(new Error,k_.SCHEMA_NOT_FOUND(e.schema),eT.NOT_FOUND);let l=c[n];if(!l)throw H_(new Error,k_.TABLE_NOT_FOUND(e.schema,e.table),eT.NOT_FOUND);function d(_){u.push(Object.assign({},{attribute:_.attribute,type:_.type,elements:_.elements?.type,indexed:_.indexed,is_primary_key:_.isPrimaryKey,assigned_created_time:_.assignCreatedTime,assigned_updated_time:_.assignUpdatedTime,nullable:_.nullable,properties:_.properties?_.properties.map(h=>({type:h.type,name:h.name})):void 0}))}a(d,"pushAtt");let u=[];if(s){let _={};s.forEach(h=>{h.describe&&(_[h.attribute_name]=!0)}),l.attributes.forEach(h=>{_[h.name]&&d(h)})}else l.attributes?.forEach(_=>d(_));let f;try{f=(await hQ.stat(l.primaryStore.env.path)).size}catch(_){Nu.warn("unable to get database size",_)}let E={schema:r,name:l.tableName,hash_attribute:l.attributes.find(_=>_.isPrimaryKey||_.is_hash_attribute)?.name,audit:l.audit,schema_defined:l.schemaDefined,attributes:u,db_size:f};E.clustering_stream_name=fQ.createNatsTableStreamName(E.schema,E.name);try{let _=l.getRecordCount({exactCount:e.exact_count==="true"});E.record_count=_.recordCount,E.estimated_record_range=_.estimatedRange;let h=l.auditStore;if(h)for(let p of h.getKeys({reverse:!0,limit:1}))E.last_updated_record=p[0];if(!E.last_updated_record&&l.indices.__updatedtime__)for(let p of l.indices.__updatedtime__.getKeys({reverse:!0,limit:1}))E.last_updated_record=p}catch(_){Nu.warn(`unable to stat table dbi due to ${_}`)}return E}a(F_,"descTable");async function pQ(e){B_.transformReq(e);let t=Cw.schema_object(e);if(t)throw t;let r;e.hdb_user&&!e.hdb_user.role.permission.super_user&&(r=e.hdb_user.role.permission[e.schema]);let n=e.schema.toString(),i=tT()[n];if(!i)throw H_(new Error,k_.SCHEMA_NOT_FOUND(e.schema),eT.NOT_FOUND);let o={};for(let c in i){let l;if(r&&r.tables[c]&&(l=r.tables[c]),B_.isEmpty(l)||l.describe){let d=await F_({schema:e.schema,table:c,exact_count:e.exact_count},l?l.attribute_permissions:null);d&&(o[d.name]=d)}}return o}a(pQ,"describeSchema")});var eo=I((D_e,vw)=>{var SQ=Yo(),{callbackify:Pw,promisify:TQ}=require("util"),{getDatabases:Mw}=(Ne(),ae(it));vw.exports={setSchemaDataToGlobal:Lw,getTableSchema:gQ,getSystemSchema:RQ,setSchemaDataToGlobalAsync:TQ(Lw)};var Uw=Zi(),w_e=Pw(Uw.describeAll),C_e=Pw(Uw.describeTable);function Lw(e){global.hdb_schema=Mw(),e&&e()}a(Lw,"setSchemaDataToGlobal");function gQ(e,t,r){let n=Mw()[e];if(!n)return r(`schema ${e} does not exist`);let s=n[t];return s?r(null,{schema:e,name:t,hash_attribute:s.primaryKey}):r(`table ${e}.${t} does not exist`)}a(gQ,"getTableSchema");function RQ(){return SQ}a(RQ,"getSystemSchema")});var qn=I((P_e,kw)=>{"use strict";var q_=QS(),Sr=re(),AQ=require("util"),V_=Vn(),bQ=eo(),xw=X(),{handleHDBError:Wo,hdb_errors:yQ}=ce(),{HTTP_STATUS_CODES:Qo}=yQ,OQ=AQ.promisify(bQ.getTableSchema),NQ="updated",Bw="inserted",Hw="upserted";kw.exports={insert:wQ,update:CQ,upsert:DQ,validation:IQ,flush:LQ};async function IQ(e){if(Sr.isEmpty(e))throw new Error("invalid update parameters defined.");if(Sr.isEmptyOrZeroLength(e.schema))throw new Error("invalid database specified.");if(Sr.isEmptyOrZeroLength(e.table))throw new Error("invalid table specified.");let t=await OQ(e.schema,e.table),r=q_(e);if(r)throw r;if(!Array.isArray(e.records))throw new Error("records must be an array");let n=t.hash_attribute,s=new Set,i={},o=!1;return e.operation==="update"&&(o=!0),e.records.forEach(c=>{if(o&&Sr.isEmptyOrZeroLength(c[n]))throw xw.error("a valid hash attribute must be provided with update record:",c),new Error("a valid hash attribute must be provided with update record");if(!Sr.isEmptyOrZeroLength(c[n])&&(c[n]==="null"||c[n]==="undefined"))throw xw.error(`a valid hash value must be provided with ${e.operation} record:`,c),new Error(`"${c[n]}" is not a valid hash attribute value`);!Sr.isEmpty(c[n])&&c[n]!==""&&s.has(Sr.autoCast(c[n]))&&(c.skip=!0),s.add(Sr.autoCast(c[n]));for(let l in c)i[l]=1}),i[n]=1,{schema_table:t,hashes:Array.from(s),attributes:Object.keys(i)}}a(IQ,"validation");async function wQ(e){if(e.operation!=="insert")throw new Error("invalid operation, must be insert");let t=q_(e);if(t)throw Wo(new Error,t.message,Qo.BAD_REQUEST);Sr.transformReq(e);let r=Sr.checkSchemaTableExist(e.schema,e.table);if(r)throw Wo(new Error,r,Qo.BAD_REQUEST);let n=await V_.createRecords(e);return G_(Bw,n.written_hashes,e,n.skipped_hashes,n.new_attributes,n.txn_time)}a(wQ,"insertData");async function CQ(e){if(e.operation!=="update")throw new Error("invalid operation, must be update");let t=q_(e);if(t)throw Wo(new Error,t.message,Qo.BAD_REQUEST);Sr.transformReq(e);let r=Sr.checkSchemaTableExist(e.schema,e.table);if(r)throw Wo(new Error,r,Qo.BAD_REQUEST);let n=await V_.updateRecords(e);return Sr.isEmpty(n.existing_rows)?G_(NQ,n.written_hashes,e,n.skipped_hashes,n.new_attributes,n.txn_time):G_(n.update_action,[],e,n.hashes,void 0,n.txn_time)}a(CQ,"updateData");async function DQ(e){if(e.operation!=="upsert")throw Wo(new Error,"invalid operation, must be upsert",Qo.INTERNAL_SERVER_ERROR);let t=q_(e);if(t)throw Wo(new Error,t.message,Qo.BAD_REQUEST);Sr.transformReq(e);let r=Sr.checkSchemaTableExist(e.schema,e.table);if(r)throw Wo(new Error,r,Qo.BAD_REQUEST);let n=await V_.upsertRecords(e);return G_(Hw,n.written_hashes,e,[],n.new_attributes,n.txn_time)}a(DQ,"upsertData");function G_(e,t,r,n,s,i){let o={message:`${e} ${t.length} of ${t.length+n.length} records`,new_attributes:s,txn_time:i};return e===Bw?(o.inserted_hashes=t,o.skipped_hashes=n,o):e===Hw?(o.upserted_hashes=t,o):(o.update_hashes=t,o.skipped_hashes=n,o)}a(G_,"returnObject");function LQ(e){return Sr.transformReq(e),V_.flush(e.schema,e.table)}a(LQ,"flush")});var nT=I((U_e,qw)=>{var PQ=mt(),rT=require("joi"),{hdb_table:MQ,hdb_database:Fw}=xs(),Gw={schema:Fw,database:Fw,table:MQ},UQ={date:rT.date().iso().required()},vQ={timestamp:rT.date().timestamp().required().messages({"date.format":"'timestamp' is invalid"})};qw.exports=function(e,t){let r=t==="timestamp"?{...Gw,...vQ}:{...Gw,...UQ},n=rT.object(r);return PQ.validateBySchema(e,n)}});var Yw=I((v_e,$w)=>{var xQ=mt(),sT=require("joi"),{hdb_table:BQ,hdb_database:Vw}=xs(),HQ=sT.object({schema:Vw,database:Vw,table:BQ,hash_values:sT.array().required(),ids:sT.array()});$w.exports=function(e){return xQ.validateBySchema(e,HQ)}});var Ww=I((x_e,Kw)=>{"use strict";var iT=class{static{a(this,"InsertObject")}constructor(t,r,n,s,i){this.operation=t,this.schema=r,this.table=n,this.hash_attribute=s,this.records=i}},oT=class{static{a(this,"NoSQLSeachObject")}constructor(t,r,n,s,i,o){this.schema=t,this.table=r,this.search_attribute=n,this.hash_attribute=s,this.get_attributes=i,this.search_value=o}},aT=class{static{a(this,"DeleteResponseObject")}constructor(){this.message=void 0,this.deleted_hashes=[],this.skipped_hashes=[]}};Kw.exports={InsertObject:iT,NoSQLSeachObject:oT,DeleteResponseObject:aT}});var Jo=I((H_e,Xw)=>{"use strict";var zw=nT(),kQ=Yw(),zo=re(),Qw=require("moment"),jw=X(),{promisify:FQ,callbackify:GQ}=require("util"),jo=H(),qQ=eo(),cT=FQ(qQ.getTableSchema),lT=Vn(),{DeleteResponseObject:VQ}=Ww(),{handleHDBError:to,hdb_errors:$Q}=ce(),{HDB_ERROR_MSGS:$_,HTTP_STATUS_CODES:ro}=$Q,YQ="records successfully deleted",KQ=GQ(Jw);Xw.exports={delete:KQ,deleteRecord:Jw,deleteFilesBefore:WQ,deleteAuditLogsBefore:QQ};async function WQ(e){let t=zw(e,"date");if(t)throw to(t,t.message,ro.BAD_REQUEST,void 0,void 0,!0);if(zo.transformReq(e),!Qw(e.date,Qw.ISO_8601).isValid())throw to(new Error,$_.INVALID_DATE,ro.BAD_REQUEST,jo.LOG_LEVELS.ERROR,$_.INVALID_DATE,!0);let n=zo.checkSchemaTableExist(e.schema,e.table);if(n)throw to(new Error,n,ro.NOT_FOUND,jo.LOG_LEVELS.ERROR,n,!0);let s=await lT.deleteRecordsBefore(e);if(await cT(e.schema,e.table),jw.info(`Finished deleting files before ${e.date}`),s&&s.message)return s.message}a(WQ,"deleteFilesBefore");async function QQ(e){let t=zw(e,"timestamp");if(t)throw to(t,t.message,ro.BAD_REQUEST,void 0,void 0,!0);if(zo.transformReq(e),isNaN(e.timestamp))throw to(new Error,$_.INVALID_VALUE("Timestamp"),ro.BAD_REQUEST,jo.LOG_LEVELS.ERROR,$_.INVALID_VALUE("Timestamp"),!0);let r=zo.checkSchemaTableExist(e.schema,e.table);if(r)throw to(new Error,r,ro.NOT_FOUND,jo.LOG_LEVELS.ERROR,r,!0);let n=await lT.deleteAuditLogsBefore(e);return await cT(e.schema,e.table),jw.info(`Finished deleting audit logs before ${e.timestamp}`),n}a(QQ,"deleteAuditLogsBefore");async function Jw(e){e.ids&&(e.hash_values=e.ids);let t=kQ(e);if(t)throw to(t,t.message,ro.BAD_REQUEST,void 0,void 0,!0);zo.transformReq(e);let r=zo.checkSchemaTableExist(e.schema,e.table);if(r)throw to(new Error,r,ro.NOT_FOUND,jo.LOG_LEVELS.ERROR,r,!0);try{await cT(e.schema,e.table);let n=await lT.deleteRecords(e);return zo.isEmptyOrZeroLength(n.message)&&(n.message=`${n.deleted_hashes.length} of ${e.hash_values.length} ${YQ}`),n}catch(n){if(n.message===jo.SEARCH_NOT_FOUND_MESSAGE){let s=new VQ;return s.message=jo.SEARCH_NOT_FOUND_MESSAGE,s.skipped_hashes=e.hash_values.length,s.deleted_hashes=0,s}throw n}}a(Jw,"deleteRecord")});var Y_=I((F_e,tC)=>{var zQ=require("crypto"),Zw=9;function jQ(e){let t=XQ(Zw),r=eC(e+t);return t+r}a(jQ,"createHash");function JQ(e,t){let r=e?.substr(0,Zw),n=r+eC(t+r);return e===n}a(JQ,"validateHash");function XQ(e){let t="0123456789abcdefghijklmnopqurstuvwxyzABCDEFGHIJKLMNOPQURSTUVWXYZ",r=t.length,n="";for(let s=0;s<e;s++){let i=Math.floor(Math.random()*r);n+=t[i]}return n}a(XQ,"generateSalt");function eC(e){return zQ.createHash("md5").update(e).digest("hex")}a(eC,"md5");tC.exports={hash:jQ,validate:JQ}});var nC=I((q_e,rC)=>{var uT=mt(),Pr={username:{presence:!0,format:"[\\w\\-\\_]+",exclusion:{within:["system"],message:"You cannot create tables within the system schema"}},password:{presence:!0},role:{presence:!0,format:"[\\w\\-\\_]+"},active:{presence:!0,inclusion:{within:[!0,!1],message:"must be a boolean"}}};function ZQ(e){return Pr.password.presence=!0,Pr.username.presence=!0,Pr.role.presence=!0,Pr.active.presence=!0,uT.validateObject(e,Pr)}a(ZQ,"addUserValidation");function ez(e){return Pr.password.presence=!1,Pr.username.presence=!0,Pr.role.presence=!1,Pr.active.presence=!1,uT.validateObject(e,Pr)}a(ez,"alterUserValidation");function tz(e){return Pr.password.presence=!1,Pr.username.presence=!0,Pr.role.presence=!1,Pr.active.presence=!1,uT.validateObject(e,Pr)}a(tz,"dropUserValidation");rC.exports={addUserValidation:ZQ,alterUserValidation:ez,dropUserValidation:tz}});var Pt=I((Y_e,iC)=>{"use strict";var{platform:$_e}=require("os"),rz="nats-server.zip",dT="nats-server",nz=process.platform==="win32"?`${dT}.exe`:dT,sz=/^[^\s.,*>]+$/,sC="__request__",iz=a(e=>`${e}.${sC}`,"REQUEST_SUBJECT"),oz={NATS_MSG_ID:"Nats-Msg-Id",ORIGIN:"origin",TRANSACTED_NODES:"transacted_nodes"},az={HUB_SERVER:"hub.json",LEAF_SERVER:"leaf.json"},cz={HUB:"hub.pid",LEAF:"leaf.pid"},lz={HUB:"-hub",LEAF:"-leaf",ADMIN:"-admin"},uz={SUCCESS:"success",ERROR:"error"},dz={OPEN:"open",CLOSED:"closed",NO_RESPONDERS:"NoResponders",TIMEOUT:"Timeout"},fz={TXN:"txn",MSGID:"msgid"},dc={ERR:"error",WRN:"warn",INF:"info",DBG:"debug",TRC:"trace"},_z={[dc.ERR]:1,[dc.WRN]:2,[dc.INF]:3,[dc.DBG]:4,[dc.TRC]:5},Ez={debug:"-D",trace:"-DVV"};iC.exports={NATS_SERVER_ZIP:rz,NATS_SERVER_NAME:dT,NATS_BINARY_NAME:nz,PID_FILES:cz,NATS_CONFIG_FILES:az,SERVER_SUFFIX:lz,NATS_TERM_CONSTRAINTS_RX:sz,REQUEST_SUFFIX:sC,UPDATE_REMOTE_RESPONSE_STATUSES:uz,CLUSTER_STATUS_STATUSES:dz,REQUEST_SUBJECT:iz,SUBJECT_PREFIXES:fz,MSG_HEADERS:oz,LOG_LEVELS:dc,LOG_LEVEL_FLAGS:Ez,LOG_LEVEL_HIERARCHY:_z}});var fT=I(oC=>{"use strict";var hz={cert:"-----BEGIN CERTIFICATE-----\rMIIDXDCCAkSgAwIBAgIFNTE4MzQwDQYJKoZIhvcNAQELBQAwXTEXMBUGA1UEAxMO\rSGFycGVyREIsIEluYy4xCzAJBgNVBAYTAlVTMQswCQYDVQQIEwJDTzEPMA0GA1UE\rBxMGRGVudmVyMRcwFQYDVQQKEw5IYXJwZXJEQiwgSW5jLjAeFw0yMjAzMTEyMzAz\rNDlaFw0yNzAzMTAyMzAzNDlaMF0xFzAVBgNVBAMTDkhhcnBlckRCLCBJbmMuMQsw\rCQYDVQQGEwJVUzELMAkGA1UECBMCQ08xDzANBgNVBAcTBkRlbnZlcjEXMBUGA1UE\rChMOSGFycGVyREIsIEluYy4wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIB\rAQCsEUlBF8WImS78rCFXVKyntxfrW++4qZ3hGnoD2MHZAuDHyeP/5eGnaE9GQhKc\r4DwG4DGvh0wP2zIYnBfiQ3L2ZtnlDR9ZkKIQYGlVxTUn6T43krhK5nZKqDF43Yg3\rZEvO3cbJBjiKZx0eA2/toehdSsTAHHQx5gTDcggNe2tgoJHYPwi9YF/AxSBZrbgb\ryWlYgtYDmF32ytHP03GUCIdKOFuBPsHTGu4SkdEIdLIqO9oglW1YFH5qZ6NiwApW\rsP+GCuqOwDXXbdjr75iq9Tq/CDrjGFLaTPmvd2Q0qG/BtaCll0ghpG+yIHvt/iQs\rajS+LxEWAnVlGMaDdFErbDUtAgMBAAGjIzAhMA8GA1UdEwEB/wQFMAMBAf8wDgYD\rVR0PAQH/BAQDAgIEMA0GCSqGSIb3DQEBCwUAA4IBAQASR4YW/rPK7PNArHVe9zzM\rb0rKNX/2T9/0nybRhmE/+hdlSgliTAeebmwkUS2APckmekYt/q2ZY2NS65Fo/jjp\rG8TJrtcF4h+ylVqUp0ZXQLFtIsr7r2JZA7hJ6njW6G4DHSZ0gxtECLi4CBlTjzm5\rNmnmIDObvGRTuqmcdAZmXeObbta/He2XIzietukPAYX062pNM+G5XT5UM1eG/Vlp\rN86vjhpyI+ffKy+C60SJqxmKM3ydgN7oLscE7+2wLPN25XqN4W99OwGsp5dTdu/f\r5lPtFayXdJ55e/sNQKmGN+UGLrL05c2MWgjb8U/LFilnupUianceoeSERZmVjzKX\r-----END CERTIFICATE-----\r".replace(/\r/g,`\r
7
+ `),key:"-----BEGIN RSA PRIVATE KEY-----\rMIIEowIBAAKCAQEArBFJQRfFiJku/KwhV1Ssp7cX61vvuKmd4Rp6A9jB2QLgx8nj\r/+Xhp2hPRkISnOA8BuAxr4dMD9syGJwX4kNy9mbZ5Q0fWZCiEGBpVcU1J+k+N5K4\rSuZ2SqgxeN2IN2RLzt3GyQY4imcdHgNv7aHoXUrEwBx0MeYEw3IIDXtrYKCR2D8I\rvWBfwMUgWa24G8lpWILWA5hd9srRz9NxlAiHSjhbgT7B0xruEpHRCHSyKjvaIJVt\rWBR+amejYsAKVrD/hgrqjsA1123Y6++YqvU6vwg64xhS2kz5r3dkNKhvwbWgpZdI\rIaRvsiB77f4kLGo0vi8RFgJ1ZRjGg3RRK2w1LQIDAQABAoIBAQCEOmh78EOpnGZC\rYBjjHrvrysVD5gvLcfVUtl8Ls7gMB60re1eOIF+PoZZCHKZnDd6zPfiQtj1adg0C\rYnnsM/8VoaZS4gm0b3RLd3ubIQifWhuo40RissY2yxfxlPSH9LhZCY8ojnJG0cTL\resK579E8WCfopjUY33XLqEbN7Ylv39J+DSqInjqV3efJZUa+HqUJ98VxxzodcKMD\rP3bwUU4gHoSSp4pAsOFH5sQhaIWH1IcNjrAwpee2cJQuh4G157RRIuuUpagtaEG/\rXJIiAyBguJyu3JQFnIBQF01N5+omJgXYJ1L0m54543/iIRThmF3zDCDgCyUzmOk+\rH6As9fv1AoGBANOpOtOZLSAScjGsgJamT3ceJ2wCa86g2j8Oxu8lJUmUp5s3tA0v\rBFW5O3S4KR1EXwkLMBUMrfFM8YvzHWxsXBI6XV8azGLvyqPHxr65OhmpGYkGZMXu\rn9okgjkqlewnY2I073gvyK7ppX51UL5y9fF1vlsk+UlW+Rgx/vMHbdcjAoGBANAc\rxRUsxs4QJpbS4zD3JOkHjr24a97TrS3kCybAHUMpR2NrEHPZw9zex0/aphOJUHfL\rIMkOZdpfDqMfxWy4FAEmqBEMkO2SB+h0Wp4P+qp81ax4vGFiB0cD3wtixr11U1tt\rlZ/ZTdv4VDpDFNK1KaplhTDeyuCjeYfS3/GJia9vAoGAcOsAgjBevZR5rXx84WH6\rVO8WUu37u7FenXNxt9VWTinrPMh72uixZFY8nOk+rely1e1NCn3IMko9Ns9NbDFm\r8SaH95vhXArXTYbfxZIlp9jp0YtCqcHDL+p4Oq04bFMbFyJseu7rHj1x18QYfnHw\rOY/6LL/N6k1m+Hx7qgXVmIcCgYB/w0nTCBw84XlvWqSTqQaF8VfWbWP79mP5KmkW\rLxdH5g2noVEGbohqDnK6OXd/wusdwByukiJBf94Skyy25AOT+VFwthA7aU1ljhkb\rtJ+lDuJ28eBkwLPLCzthWBC+u0qjdJFJAzVjd/7tjcU43nNn4s90AzL12iaAFhvZ\rwyA+DQKBgGc/4cdyGJ3YkcA8150gQBawgJZ7q8V1JND87ggWA8wnK3cHn7rMZQl2\r3emDp9HEFXFex5dbGDDqZFAoesZCDxjknIn9oNfW4PvaWS8q7b6ZKLZG1p03Pu7/\rtYaD0kPbo0kysfFT/co+NgHbdykvIyboomfGdNLTUjYuy6lpwpvs\r-----END RSA PRIVATE KEY-----\r".replace(/\r/g,`\r
8
+ `)},mz="certificate.pem",pz="privateKey.pem",Sz="caCertificate.pem",Tz="natsCertificate.pem",gz="natsCaCertificate.pem",pt={DEFAULT:"default","DEFAULT-CA":"default-ca",SERVER:"server",CA:"ca","OPERATIONS-API":"operations-api","OPERATIONS-CA":"operations-ca"},Rz={tls_certificate:pt.SERVER,tls_certificateAuthority:pt.CA,customFunctions_tls_certificate:pt.SERVER,customFunctions_tls_certificateAuthority:pt.CA,operationsApi_tls_certificate:pt["OPERATIONS-API"],operationsApi_tls_certificateAuthority:pt["OPERATIONS-CA"]},Az={[pt.SERVER]:2,[pt.DEFAULT]:1},bz={[pt["OPERATIONS-API"]]:3,[pt.SERVER]:2,[pt.DEFAULT]:1},yz={[pt["OPERATIONS-API"]]:3,[pt.SERVER]:2,[pt.DEFAULT]:1},Oz={[pt["OPERATIONS-CA"]]:3,[pt.CA]:2,[pt["DEFAULT-CA"]]:1},Nz={[pt["OPERATIONS-CA"]]:3,[pt.CA]:2,[pt["DEFAULT-CA"]]:1},Iz={[pt.CA]:2,[pt["DEFAULT-CA"]]:1};Object.assign(oC,{CERTIFICATE_PEM_NAME:mz,PRIVATEKEY_PEM_NAME:pz,CA_PEM_NAME:Sz,CERT_NAME:pt,CERT_CONFIG_NAME_MAP:Rz,CERT_PREFERENCE_APP:Az,CERT_PREFERENCE_OPS:bz,CERT_PREFERENCE_REP:yz,CA_CERT_PREFERENCE_REP:Oz,CA_CERT_PREFERENCE_OPS:Nz,CA_CERT_PREFERENCE_APP:Iz,CERTIFICATE_VALUES:hz,NATS_CERTIFICATE_PEM_NAME:Tz,NATS_CA_PEM_NAME:gz})});var ET=I((z_e,fC)=>{"use strict";var uC=require("fs-extra"),de=require("joi"),wz=require("os"),{boolean:Ge,string:St,number:bt,array:wu}=de.types(),{totalmem:aC}=require("os"),Xo=require("path"),Cz=X(),_T=re(),Q_e=fT(),cC=H(),Dz=mt(),lC="log",Lz="components",Pz="Invalid logging.rotation.maxSize unit. Available units are G, M or K",Mz="Invalid logging.rotation.interval unit. Available units are D, H or M (minutes)",Uz="Invalid logging.rotation.maxSize value. Value should be a number followed by unit e.g. '10M'",vz="Invalid logging.rotation.interval value. Value should be a number followed by unit e.g. '10D'",xz="rootPath config parameter is undefined",no=de.alternatives([bt.min(0),St]).required(),K_=de.alternatives([wu.items(St,{host:St.required(),port:no},{hostname:St.required(),port:no}).empty(null),wu.items(St)]),Hs,dC=!1;fC.exports={configValidator:Bz,routesValidator:Vz,route_constraints:K_};function Bz(e,t=!1){if(dC=t,Hs=e.rootPath,_T.isEmpty(Hs))throw xz;let r=Ge.optional(),n=bt.min(0).max(1e3).empty(null).default(qz),s=St.pattern(/^[\\\/]$|([\\\/a-zA-Z_0-9\:-]+)+$/,"directory path").empty(null).default(Iu),i=St.optional().empty(null),o=St.pattern(/^[^\s.,*>]+$/).messages({"string.pattern.base":"{:#label} invalid, must not contain ., * or >"}).empty(null).required(),c=de.string().empty(null).default(Iu),l=de.custom(kz).empty(null).default(Iu),d=e.clustering?.enabled,u=de.object({certificate:i,certificateAuthority:i,privateKey:i}),f;return d===!0?f=de.object({enabled:r,hubServer:de.object({cluster:de.object({name:de.required().empty(null),network:de.object({port:no,routes:K_}).required()}).required(),leafNodes:de.object({network:de.object({port:no}).required()}).required(),network:de.object({port:no}).required()}).required(),leafServer:de.object({network:de.object({port:no,routes:K_}).required(),streams:de.object({maxAge:bt.min(120).allow(null).optional(),maxBytes:bt.min(1).allow(null).optional(),maxMsgs:bt.min(1).allow(null).optional(),path:c}).required()}).required(),logLevel:de.valid("error","warn","info","debug","trace"),nodeName:o,republishMessages:Ge.optional(),databaseLevel:Ge.optional(),tls:de.object({certificate:i,certificateAuthority:i,privateKey:i,insecure:Ge.required(),verify:Ge.optional()}),user:St.optional().empty(null)}).optional():f=de.object({enabled:r,tls:de.object({certificate:i,certificateAuthority:i,privateKey:i,insecure:Ge.optional()})}).optional(),de.object({authentication:de.object({authorizeLocal:Ge,cacheTTL:bt.required(),enableSessions:Ge}),analytics:de.object({aggregatePeriod:bt}),componentsRoot:s.optional(),clustering:f,localStudio:de.object({enabled:r}).required(),logging:de.object({auditAuthEvents:de.object({logFailed:Ge,logSuccessful:Ge}),file:Ge.required(),level:de.valid("notify","fatal","error","warn","info","debug","trace"),rotation:de.object({enabled:Ge.optional(),compress:Ge.optional(),interval:St.custom(Gz).optional().empty(null),maxSize:St.custom(Fz).optional().empty(null),path:St.optional().empty(null).default(Iu)}).required(),root:s,stdStreams:Ge.required(),auditLog:Ge.required()}).required(),operationsApi:de.object({network:de.object({cors:Ge.optional(),corsAccessList:wu.optional(),headersTimeout:bt.min(1).optional(),keepAliveTimeout:bt.min(1).optional(),port:de.alternatives([bt.min(0),St]).optional().empty(null),domainSocket:de.optional().empty("hdb/operations-server").default(Iu),securePort:de.alternatives([bt.min(0),St]).optional().empty(null),timeout:bt.min(1).optional()}).optional(),tls:de.alternatives([de.array().items(u),u])}).required(),rootPath:St.pattern(/^[\\\/]$|([\\\/a-zA-Z_0-9\:-]+)+$/,"directory path").required(),mqtt:de.object({network:de.object({port:no,securePort:no,mtls:de.alternatives([Ge.optional(),de.object({user:St.optional(),certificateAuthority:i,required:Ge.optional()})])}).required(),webSocket:Ge.optional(),requireAuthentication:Ge.optional()}),http:de.object({compressionThreshold:bt.optional(),cors:Ge.optional(),corsAccessList:wu.optional(),headersTimeout:bt.min(1).optional(),port:de.alternatives([bt.min(0),St]).optional().empty(null),securePort:de.alternatives([bt.min(0),St]).optional().empty(null),maxHeaderSize:bt.optional(),mtls:de.alternatives([Ge.optional(),de.object({user:St.optional(),certificateAuthority:i,required:Ge.optional()})]),threadRange:de.alternatives([wu.optional(),St.optional()])}).required(),threads:de.alternatives(n.optional(),de.object({count:n.optional(),debug:de.alternatives(Ge.optional(),de.object({startingPort:bt.min(1).optional(),host:St.optional(),waitForDebugger:Ge.optional()})),maxHeapMemory:bt.min(0).optional()})),storage:de.object({writeAsync:Ge.required(),overlappingSync:Ge.optional(),caching:Ge.optional(),compression:de.alternatives([Ge.optional(),de.object({dictionary:St.optional(),threshold:bt.optional()})]),compactOnStart:Ge.optional(),compactOnStartKeepBackup:Ge.optional(),noReadAhead:Ge.optional(),path:l,prefetchWrites:Ge.optional(),maxFreeSpaceToLoad:bt.optional(),maxFreeSpaceToRetain:bt.optional()}).required(),ignoreScripts:Ge.optional(),tls:de.alternatives([de.array().items(u),u])}).validate(e,{allowUnknown:!0,abortEarly:!1,errors:{wrap:{label:"'"}}})}a(Bz,"configValidator");function Hz(e){return dC||uC.existsSync(e)?null:`Specified path ${e} does not exist.`}a(Hz,"doesPathExist");function kz(e,t){de.assert(e,St.pattern(/^[\\\/]$|([\\\/a-zA-Z_0-9\:-]+)+$/,"directory path"));let r=Hz(e);if(r)return t.message(r)}a(kz,"validatePath");function Fz(e,t){let r=e.slice(-1);if(r!=="G"&&r!=="M"&&r!=="K")return t.message(Pz);let n=e.slice(0,-1);return isNaN(parseInt(n))?t.message(Uz):e}a(Fz,"validateRotationMaxSize");function Gz(e,t){let r=e.slice(-1);if(r!=="D"&&r!=="H"&&r!=="M")return t.message(Mz);let n=e.slice(0,-1);return isNaN(parseInt(n))?t.message(vz):e}a(Gz,"validateRotationInterval");function qz(e,t){let r=t.state.path.join("."),n=wz.cpus().length,s=n-1;s<=2&&(s=2);let i=process.constrainedMemory?.()||aC();return i=Math.round(Math.min(i,aC())/1e6),s=Math.max(Math.min(s,Math.round((i-750)/300)),1),Cz.info(`Detected ${n} cores and ${i}MB on this machine, defaulting ${r} to ${s}`),s}a(qz,"setDefaultThreads");function Iu(e,t){let r=t.state.path.join(".");if(!_T.isEmpty(t.original)&&r!=="operationsApi.network.domainSocket")return t.original;if(_T.isEmpty(Hs))throw new Error(`Error setting default root for: ${r}. HDB root is not defined`);switch(r){case"componentsRoot":return Xo.join(Hs,Lz);case"logging.root":return Xo.join(Hs,lC);case"clustering.leafServer.streams.path":return Xo.join(Hs,"clustering","leaf");case"storage.path":let n=Xo.join(Hs,cC.LEGACY_DATABASES_DIR_NAME);return uC.existsSync(n)?n:Xo.join(Hs,cC.DATABASES_DIR_NAME);case"logging.rotation.path":return Xo.join(Hs,lC);case"operationsApi.network.domainSocket":return r==null?null:Xo.join(Hs,"operations-server");default:throw new Error(`Error setting default root for config parameter: ${r}. Unrecognized config parameter`)}}a(Iu,"setDefaultRoot");function Vz(e){let t=de.object({routes:K_});return Dz.validateBySchema({routes:e},t)}a(Vz,"routesValidator")});var dr=I((J_e,AC)=>{"use strict";var Yr=H(),nr=re(),sr=X(),{configValidator:$z,routesValidator:_C}=ET(),Mr=require("fs-extra"),hC=require("yaml"),An=require("path"),Yz=require("is-number"),mC=require("properties-reader"),Kz=require("lodash"),{handleHDBError:Wz}=ce(),{HTTP_STATUS_CODES:Qz,HDB_ERROR_MSGS:fc}=En(),{server:zz}=(Lr(),ae(ko)),{DATABASES_PARAM_CONFIG:Cu,CONFIG_PARAMS:Rn,CONFIG_PARAM_MAP:_s}=Yr,jz="Unable to get config value because config is uninitialized",Jz="Config successfully initialized",Xz="Error backing up config file",Zz="Empty parameter sent to getConfigValue",pC=An.join(Yr.PACKAGE_ROOT,"config","yaml",Yr.HDB_DEFAULT_CONFIG_FILE),e2=An.join(Yr.PACKAGE_ROOT,"config","yaml","defaultNatsConfig.yaml"),t2="Configuration successfully set. You must restart HarperDB for new config settings to take effect.",EC={logging_rotation_retain:"logging.rotation.retain",logging_rotation_rotate:"logging.rotation.rotate",logging_rotation_rotateinterval:"logging.rotation.rotateInterval",logging_rotation_rotatemodule:"logging.rotation.rotateModule",logging_rotation_timezone:"logging.rotation.timezone",logging_rotation_workerinterval:"logging.rotation.workerInterval"},W_,ir,Q_;AC.exports={createConfigFile:r2,getDefaultConfig:n2,getConfigValue:TC,initConfig:pT,flattenConfig:_c,updateConfigValue:gC,updateConfigObject:i2,getConfiguration:c2,setConfiguration:l2,readConfigFile:TT,getClusteringRoutes:u2,initOldConfig:RC,getConfigFromFile:d2,getConfigFilePath:Zo,addConfig:f2,deleteConfigFromFile:_2,getConfigObj:E2,resolvePath:hT};function hT(e){if(e?.startsWith("~/"))return An.join(nr.getHomeDir(),e.slice(1));let t=ie();return An.resolve(t.getHdbBasePath(),e)}a(hT,"resolvePath");function r2(e,t=!1){let r=so(pC);if(e.clustering_enabled||e.CLUSTERING_ENABLED||e.clustering){let c=hC.parseDocument(Mr.readFileSync(e2,"utf8"),{simpleKeys:!0});r.addIn(["clustering"],c.toJSON().clustering)}W_=_c(r.toJSON());let n;for(let c in e){let l=_s[c.toLowerCase()];if(l===Rn.DATABASES){Array.isArray(e[c])?n=e[c]:n=Object.keys(e[c]).map(d=>({[d]:e[c][d]}));continue}if(!l&&(c.endsWith("_package")||c.endsWith("_port"))&&(l=c),l!==void 0){let d=l.split("_"),u=mT(l,e[c]);l==="rootPath"&&u?.endsWith("/")&&(u=u.slice(0,-1));try{r.setIn([...d],u)}catch(f){sr.error(f)}}}n&&SC(r,n),ST(r,t);let s=r.toJSON();ir=_c(s);let i=r.getIn(["rootPath"]),o=An.join(i,Yr.HDB_CONFIG_FILE);Mr.createFileSync(o),Mr.writeFileSync(o,String(r)),sr.trace(`Config file written to ${o}`)}a(r2,"createConfigFile");function SC(e,t){let r;try{try{r=JSON.parse(t)}catch(n){if(!nr.isObject(t))throw n;r=t}for(let n of r){let s=Object.keys(n)[0];if(n[s].hasOwnProperty(Cu.TABLES))for(let i in n[s][Cu.TABLES])for(let o in n[s][Cu.TABLES][i]){let c=n[s][Cu.TABLES][i][o],l=[Rn.DATABASES,s,Cu.TABLES,i,o];e.hasIn(l)?e.setIn(l,c):e.addIn(l,c)}else for(let i in n[s]){let o=n[s][i],c=[Rn.DATABASES,s,i];e.hasIn(c)?e.setIn(c,o):e.addIn(c,o)}}}catch(n){sr.error("Error parsing schemas CLI/env config arguments",n)}}a(SC,"setSchemasConfig");function n2(e){if(W_===void 0){let r=so(pC);W_=_c(r.toJSON())}let t=_s[e.toLowerCase()];if(t!==void 0)return W_[t.toLowerCase()]}a(n2,"getDefaultConfig");function TC(e){if(e==null){sr.info(Zz);return}if(ir===void 0){sr.trace(jz);return}let t=_s[e.toLowerCase()];if(t!==void 0)return ir[t.toLowerCase()]}a(TC,"getConfigValue");function Zo(e=nr.getPropsFilePath()){let t=nr.getEnvCliRootPath();if(t)return hT(An.join(t,Yr.HDB_CONFIG_FILE));let r=mC(e);return hT(r.get(Yr.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY))}a(Zo,"getConfigFilePath");function pT(e=!1){if(ir===void 0||e){let t;if(!nr.noBootFile()){t=nr.getPropsFilePath();try{Mr.accessSync(t,Mr.constants.F_OK|Mr.constants.R_OK)}catch(i){throw sr.error(i),new Error(`HarperDB properties file at path ${t} does not exist`)}}let r=Zo(t),n;if(r.includes("config/settings.js"))try{RC(r);return}catch(i){if(i.code!==Yr.NODE_ERROR_CODES.ENOENT)throw i}try{n=so(r)}catch(i){if(i.code===Yr.NODE_ERROR_CODES.ENOENT){sr.trace(`HarperDB config file not found at ${r}.
9
+ This can occur during early stages of install where the config file has not yet been created`);return}else throw sr.error(i),new Error(`Error reading HarperDB config file at ${r}`)}s2(n,r),ST(n);let s=n.toJSON();if(zz.config=s,ir=_c(s),ir.logging_rotation_rotate)for(let i in EC)ir[i]&&sr.error(`Config ${EC[i]} has been deprecated. Please check https://docs.harperdb.io/docs/ for further details.`);sr.trace(Jz)}}a(pT,"initConfig");function s2(e,t){let r=e.getIn(["rootPath"]),n=!1;e.hasIn(["storage","path"])||(e.setIn(["storage","path"],An.join(r,"database")),n=!0),e.hasIn(["logging","rotation","path"])||(e.setIn(["logging","rotation","path"],An.join(r,"log")),n=!0),e.hasIn(["authentication"])||(e.addIn(["authentication"],{cacheTTL:3e4,enableSessions:!0,operationTokenTimeout:e.getIn(["operationsApi","authentication","operationTokenTimeout"])??"1d",refreshTokenTimeout:e.getIn(["operationsApi","authentication","refreshTokenTimeout"])??"30d"}),n=!0),e.hasIn(["analytics"])||(e.addIn(["analytics"],{aggregatePeriod:60}),n=!0),n&&(sr.trace("Updating config file with missing config params"),Mr.writeFileSync(t,String(e)))}a(s2,"checkForUpdatedConfig");function ST(e,t=!1){let r=e.toJSON();if(r.componentsRoot=r.componentsRoot??r?.customFunctions?.root,r?.http?.threads&&(r.threads=r?.http?.threads),r.http?.port&&r.http?.port===r.http?.securePort)throw fc.CONFIG_VALIDATION("http.port and http.securePort cannot be the same value");if(r.operationsApi?.network?.port&&r.operationsApi?.network?.port===r.operationsApi?.network?.securePort)throw fc.CONFIG_VALIDATION("operationsApi.network.port and operationsApi.network.securePort cannot be the same value");let n=$z(r,t);if(n.error)throw fc.CONFIG_VALIDATION(n.error.message);typeof n.value.threads=="object"?e.setIn(["threads","count"],n.value.threads.count):e.setIn(["threads"],n.value.threads),e.setIn(["componentsRoot"],n.value.componentsRoot),e.setIn(["logging","root"],n.value.logging.root),e.setIn(["storage","path"],n.value.storage.path),e.setIn(["logging","rotation","path"],n.value.logging.rotation.path),e.setIn(["operationsApi","network","domainSocket"],n.value?.operationsApi?.network?.domainSocket),r?.clustering?.enabled&&e.setIn(["clustering","leafServer","streams","path"],n.value.clustering.leafServer.streams?.path)}a(ST,"validateConfig");function i2(e,t){ir===void 0&&(ir={});let r=_s[e.toLowerCase()];if(r===void 0){sr.trace(`Unable to update config object because config param '${e}' does not exist`);return}ir[r.toLowerCase()]=t}a(i2,"updateConfigObject");function gC(e,t,r=void 0,n=!1,s=!1,i=!1){ir===void 0&&pT();let o=TC(_s.hdb_root),c=An.join(o,Yr.HDB_CONFIG_FILE),l=so(c),d;if(r===void 0&&e.toLowerCase()===Rn.DATABASES)d=t;else if(r===void 0){let E;if(i)E=e;else if(E=_s[e.toLowerCase()],E===void 0)throw new Error(`Unable to update config, unrecognized config parameter: ${e}`);let _=E.split("_"),h=mT(E,t);l.setIn([..._],h)}else for(let E in r){let _=_s[E.toLowerCase()];if(_===Rn.HTTP_SECUREPORT&&r[E]===ir[Rn.HTTP_PORT]?.toString()&&l.setIn(["http","port"],null),_===Rn.OPERATIONSAPI_NETWORK_SECUREPORT&&r[E]===ir[Rn.OPERATIONSAPI_NETWORK_PORT.toLowerCase()]?.toString()&&l.setIn(["operationsApi","network","port"],null),_===Rn.DATABASES){d=r[E];continue}if(_?.startsWith("threads_")){let h=l.getIn(["threads"]);h>=0&&(l.deleteIn(["threads"]),l.setIn(["threads","count"],h))}if(!_&&(E.endsWith("_package")||E.endsWith("_port"))&&(_=E),_!==void 0){let h=_.split("_"),p=Yr.LEGACY_CONFIG_PARAMS[E.toUpperCase()];p&&p.startsWith("customFunctions")&&l.hasIn(p.split("_"))&&(_=p,h=p.split("_"));let S=mT(_,r[E]);_==="rootPath"&&S?.endsWith("/")&&(S=S.slice(0,-1));try{h.length>1&&typeof l.getIn(h.slice(0,-1))=="boolean"&&l.deleteIn(h.slice(0,-1)),l.setIn([...h],S)}catch(g){sr.error(g)}}}d&&SC(l,d),ST(l);let u=l.getIn(["rootPath"]),f=An.join(u,Yr.HDB_CONFIG_FILE);n===!0&&o2(c,u),Mr.writeFileSync(f,String(l)),s&&(ir=_c(l.toJSON())),sr.trace(`Config parameter: ${e} updated with value: ${t}`)}a(gC,"updateConfigValue");function o2(e,t){try{let r=An.join(t,"backup",`${new Date(Date.now()).toISOString().replaceAll(":","-")}-${Yr.HDB_CONFIG_FILE}.bak`);Mr.copySync(e,r),sr.trace(`Config file: ${e} backed up to: ${r}`)}catch(r){sr.error(Xz),sr.error(r)}}a(o2,"backupConfigFile");var a2=["databases"];function _c(e){return e.http&&Object.assign(e.http,e?.customFunctions?.network),e?.operationsApi?.network&&(e.operationsApi.network=Object.assign({},e.http,e.operationsApi.network)),e?.operationsApi&&(e.operationsApi.tls=Object.assign({},e.tls,e.operationsApi.tls)),Q_=e,r(e);function r(n){let s={};for(let i in n)if(n.hasOwnProperty(i)){if(typeof n[i]=="object"&&n[i]!==null&&!Array.isArray(n[i])&&!a2.includes(i)){let o=r(n[i]);for(let c in o){if(!o.hasOwnProperty(c))continue;c!=="package"&&(i=i.toLowerCase());let l=i+"_"+c;!Rn[l.toUpperCase()]&&_s[l]&&(s[_s[l].toLowerCase()]=o[c]),s[l]=o[c]}}n[i]!==void 0&&(s[i.toLowerCase()]=n[i])}return s}a(r,"squashObj")}a(_c,"flattenConfig");function mT(e,t){if(e===Rn.CLUSTERING_NODENAME||e===Rn.CLUSTERING_USER){if(t==null)return t;if(!isNaN(t))return t.toString();if(typeof t=="string"&&t.toLowerCase()==="true"||typeof t=="string"&&t.toLowerCase()==="false")return t}else{if(Yz(t))return parseFloat(t);if(t===!0||t===!1||Array.isArray(t)||nr.isObject(t)||t===null)return t;if(typeof t=="string"&&t.toLowerCase()==="true")return!0;if(typeof t=="string"&&t.toLowerCase()==="false")return!1}if(t===void 0||t.toLowerCase()==="undefined")return null;if(typeof t=="string"&&(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]")))try{return JSON.parse(t)}catch{}return nr.autoCast(t)}a(mT,"castConfigValue");function c2(){let e=nr.getPropsFilePath(),t=Zo(e);return so(t).toJSON()}a(c2,"getConfiguration");async function l2(e){let{operation:t,hdb_user:r,hdb_auth_header:n,...s}=e;try{return gC(void 0,void 0,s,!0),t2}catch(i){throw typeof i=="string"||i instanceof String?Wz(i,i,Qz.BAD_REQUEST,void 0,void 0,!0):i}}a(l2,"setConfiguration");function TT(){let e=nr.getPropsFilePath();try{Mr.accessSync(e,Mr.constants.F_OK|Mr.constants.R_OK)}catch(n){if(!nr.noBootFile())throw sr.error(n),new Error(`HarperDB properties file at path ${e} does not exist`)}let t=Zo(e);return so(t).toJSON()}a(TT,"readConfigFile");function so(e){return hC.parseDocument(Mr.readFileSync(e,"utf8"),{simpleKeys:!0})}a(so,"parseYamlDoc");function u2(){let e=TT(),t=e?.clustering?.hubServer?.cluster?.network?.routes;t=nr.isEmptyOrZeroLength(t)?[]:t;let r=_C(t);if(r)throw fc.CONFIG_VALIDATION(r.message);let n=e?.clustering?.leafServer?.network?.routes;n=nr.isEmptyOrZeroLength(n)?[]:n;let s=_C(n);if(s)throw fc.CONFIG_VALIDATION(s.message);if(!nr.isEmptyOrZeroLength(n)&&!nr.isEmptyOrZeroLength(t)){let i=t.filter(o=>n.some(c=>c.host===o.host&&c.port===o.port));if(!nr.isEmptyOrZeroLength(i)){let o=`Duplicate hub and leaf routes found ${JSON.stringify(i)}`;throw fc.CONFIG_VALIDATION(o)}}return{hub_routes:t,leaf_routes:n}}a(u2,"getClusteringRoutes");function RC(e){let t=mC(e);ir={};for(let r in _s){let n=t.get(r.toUpperCase());if(nr.isEmpty(n)||typeof n=="string"&&n.trim().length===0)continue;let s=_s[r].toLowerCase();s===Rn.LOGGING_ROOT?ir[s]=An.dirname(n):ir[s]=n}return ir}a(RC,"initOldConfig");function d2(e){let t=TT();return Kz.get(t,e.replaceAll("_","."))}a(d2,"getConfigFromFile");async function f2(e,t){let r=so(Zo());r.hasIn([e])?r.setIn([e],t):r.addIn([e],t),await Mr.writeFile(Zo(),String(r))}a(f2,"addConfig");function _2(e){let t=Zo(nr.getPropsFilePath()),r=so(t);r.deleteIn(e);let n=r.getIn(["rootPath"]),s=An.join(n,Yr.HDB_CONFIG_FILE);Mr.writeFileSync(s,String(r))}a(_2,"deleteConfigFromFile");function E2(){return Q_||(pT(),Q_)}a(E2,"getConfigObj")});var yC=I((Z_e,bC)=>{"use strict";var z_=H(),j_=class{static{a(this,"BaseLicense")}constructor(t=0,r=z_.RAM_ALLOCATION_ENUM.DEFAULT,n=z_.LICENSE_VALUES.VERSION_DEFAULT,s){this.exp_date=t,this.ram_allocation=r,this.version=n,this.fingerprint=s}},gT=class extends j_{static{a(this,"ExtendedLicense")}constructor(t=0,r=z_.RAM_ALLOCATION_ENUM.DEFAULT,n=z_.LICENSE_VALUES.VERSION_DEFAULT,s,i=!1){super(t,r,n,s),this.enterprise=i}};bC.exports={BaseLicense:j_,ExtendedLicense:gT}});var ea=I((tEe,LC)=>{"use strict";var hc=require("fs-extra"),NC=Y_(),IC=require("crypto"),h2=require("moment"),m2=require("uuid").v4,Ur=X(),AT=require("path"),p2=re(),io=H(),{totalmem:OC}=require("os"),S2=yC().ExtendedLicense,Ec="invalid license key format",T2="061183",g2="mofi25",R2="aes-256-cbc",A2=16,b2=32,wC=ie(),{resolvePath:CC}=dr();wC.initSync();var RT;LC.exports={validateLicense:DC,generateFingerPrint:O2,licenseSearch:OT,getLicense:w2,checkMemoryLimit:C2};function bT(){return AT.join(wC.getHdbBasePath(),io.LICENSE_KEY_DIR_NAME,io.LICENSE_FILE_NAME)}a(bT,"getLicenseDirPath");function y2(){let e=bT();return CC(AT.join(e,io.LICENSE_FILE_NAME))}a(y2,"getLicenseFilePath");function yT(){let e=bT();return CC(AT.join(e,io.REG_KEY_FILE_NAME))}a(yT,"getFingerPrintFilePath");async function O2(){let e=yT();try{return await hc.readFile(e,"utf8")}catch(t){if(t.code==="ENOENT")return await N2();throw Ur.error(`Error writing fingerprint file to ${e}`),Ur.error(t),new Error("There was an error generating the fingerprint")}}a(O2,"generateFingerPrint");async function N2(){let e=m2(),t=NC.hash(e),r=yT();try{await hc.mkdirp(bT()),await hc.writeFile(r,t)}catch(n){if(n.code==="EEXIST")return t;throw Ur.error(`Error writing fingerprint file to ${r}`),Ur.error(n),new Error("There was an error generating the fingerprint")}return t}a(N2,"writeFingerprint");function DC(e,t){let r={valid_license:!1,valid_date:!1,valid_machine:!1,exp_date:null,ram_allocation:io.RAM_ALLOCATION_ENUM.DEFAULT,version:io.LICENSE_VALUES.VERSION_DEFAULT};if(!e)return Ur.error("empty license key passed to validate."),r;let n=yT(),s=!1;try{s=hc.statSync(n)}catch(i){Ur.error(i)}if(s){let i;try{i=hc.readFileSync(n,"utf8")}catch{Ur.error("error validating this machine in the license"),r.valid_machine=!1;return}let o=e.split(g2),c=o[1];c=Buffer.concat([Buffer.from(c)],A2);let l=Buffer.concat([Buffer.from(i)],b2),d=IC.createDecipheriv(R2,l,c);r.valid_date=!0,r.valid_license=!0,r.valid_machine=!0;let u=null;try{u=d.update(o[0],"hex","utf8"),u.trim(),u+=d.final("utf8")}catch{let _=I2(o[0],i);if(_)u=_;else throw r.valid_license=!1,r.valid_machine=!1,console.error(Ec),Ur.error(Ec),new Error(Ec)}let f;if(isNaN(u))try{f=JSON.parse(u),r.version=f.version,r.exp_date=f.exp_date,isNaN(r.exp_date)&&(r.exp_date=new Date(r.exp_date).getTime()),f.ram_allocation&&(r.ram_allocation=f.ram_allocation)}catch{throw console.error(Ec),Ur.error(Ec),new Error(Ec)}else r.exp_date=u;r.exp_date<h2().valueOf()&&(r.valid_date=!1),NC.validate(o[1],`${T2}${i}${t}`)||(r.valid_license=!1)}else r.valid_license=!1,r.valid_machine=!1;return r.valid_license&&r.valid_machine&&r.valid_date||Ur.error("Invalid licence"),r}a(DC,"validateLicense");function I2(e,t){try{let r=IC.createDecipher("aes192",t),n=r.update(e,"hex","utf8");return n.trim(),n+=r.final("utf8"),n}catch{Ur.warn("Check old license failed")}}a(I2,"checkOldLicense");function OT(){let e=new S2,t=[];try{t=hc.readFileSync(y2(),"utf-8").split(io.NEW_LINE)}catch(r){r.code==="ENOENT"?Ur.debug("no license file found"):Ur.error(`could not search for licenses due to: '${r.message}`)}for(let r=0;r<t.length;++r){let n=t[r];try{if(p2.isEmptyOrZeroLength(n))continue;let s=JSON.parse(n),i=DC(s.license_key,s.company);i.valid_machine===!0&&i.valid_date===!0&&i.valid_machine===!0&&(e.exp_date=i.exp_date>e.exp_date?i.exp_date:e.exp_date,e.ram_allocation=i.ram_allocation,e.enterprise=!0)}catch(s){Ur.error("There was an error parsing the license string."),Ur.error(s),e.ram_allocation=io.RAM_ALLOCATION_ENUM.DEFAULT,e.enterprise=!1}}return RT=e,e}a(OT,"licenseSearch");async function w2(){return RT||await OT(),RT}a(w2,"getLicense");function C2(){let e=OT().ram_allocation,t=process.constrainedMemory?.()||OC();if(t=Math.round(Math.min(t,OC())/2**20),t>e)return`This server has more memory (${t}MB) than HarperDB is licensed for (${e}MB), this should only be used for educational and development purposes.`}a(C2,"checkMemoryLimit")});var $n=I((oEe,WC)=>{"use strict";var vC="username is required",xC="nothing to update, must supply active, role or password to update",BC="password cannot be an empty string",HC="If role is specified, it cannot be empty.",kC="active must be true or false";WC.exports={addUser:H2,alterUser:k2,dropUser:G2,getSuperUser:Y2,userInfo:q2,listUsers:X_,listUsersExternal:V2,setUsersToGlobal:pc,findAndValidateUser:YC,getClusterUser:K2,USERNAME_REQUIRED:vC,ALTERUSER_NOTHING_TO_UPDATE:xC,EMPTY_PASSWORD:BC,EMPTY_ROLE:HC,ACTIVE_BOOLEAN:kC};var FC=qn(),D2=Jo(),wT=Y_(),GC=nC(),qC=gn(),CT=pi(),bn=re(),VC=require("validate.js"),ke=X(),{promisify:L2}=require("util"),DT=mi(),PC=H(),MC=Pt(),P2=dr(),nEe=ie(),sEe=ea(),M2=Yo(),{table:iEe}=(Ne(),ae(it)),{handleHDBError:ks,hdb_errors:U2}=ce(),{HTTP_STATUS_CODES:Fs,AUTHENTICATION_ERROR_MSGS:NT,HDB_ERROR_MSGS:mc}=U2,{UserEventMsg:LT}=Es(),IT=require("lodash"),{server:PT}=(Lr(),ae(ko)),v2=X();PT.getUser=(e,t)=>YC(e,t,t!=null);var $C={username:!0,active:!0,role:!0,password:!0},UC=new Map,J_=qC.searchByValue,x2=qC.searchByHash,B2=L2(D2.delete);async function H2(e){let t=VC.cleanAttributes(e,$C),r=GC.addUserValidation(t);if(r)throw ks(new Error,r.message,Fs.BAD_REQUEST,void 0,void 0,!0);let n={schema:"system",table:"hdb_role",search_attribute:"role",search_value:t.role,get_attributes:["id","permission","role"]},s;try{s=await J_(n),s=s&&Array.from(s)}catch(l){throw ke.error("There was an error searching for a role in add user"),ke.error(l),l}if(!s||s.length<1)throw ks(new Error,mc.ROLE_NAME_NOT_FOUND(t.role),Fs.NOT_FOUND,void 0,void 0,!0);if(s.length>1)throw ks(new Error,mc.DUP_ROLES_FOUND(t.role),Fs.CONFLICT,void 0,void 0,!0);s[0].permission.cluster_user===!0&&(t.hash=DT.encrypt(t.password)),t.password=wT.hash(t.password),t.role=s[0].id;let i={operation:"insert",schema:"system",table:"hdb_user",records:[t]},o;try{o=await FC.insert(i)}catch(l){throw ke.error("There was an error searching for a user."),ke.error(l),l}ke.debug(o);try{await pc()}catch(l){throw ke.error("Got an error setting users to global"),ke.error(l),l}if(o.skipped_hashes.length===1)throw ks(new Error,mc.USER_ALREADY_EXISTS(t.username),Fs.CONFLICT,void 0,void 0,!0);let c=Object.assign({},t);return c.role=s[0],CT.signalUserChange(new LT(process.pid)),`${c.username} successfully added`}a(H2,"addUser");async function k2(e){let t=VC.cleanAttributes(e,$C);if(bn.isEmptyOrZeroLength(t.username))throw new Error(vC);if(bn.isEmptyOrZeroLength(t.password)&&bn.isEmptyOrZeroLength(t.role)&&bn.isEmptyOrZeroLength(t.active))throw new Error(xC);if(!bn.isEmpty(t.password)&&bn.isEmptyOrZeroLength(t.password.trim()))throw new Error(BC);if(!bn.isEmpty(t.active)&&!bn.isBoolean(t.active))throw new Error(kC);let r=F2(t.username);if(!bn.isEmpty(t.password)&&!bn.isEmptyOrZeroLength(t.password.trim())&&(r&&(t.hash=DT.encrypt(t.password)),t.password=wT.hash(t.password)),t.role==="")throw new Error(HC);if(t.role){let i={schema:"system",table:"hdb_role",search_attribute:"role",search_value:t.role,get_attributes:["*"]},o;try{o=Array.from(await J_(i)||[])}catch(c){throw ke.error("Got an error searching for a role."),ke.error(c),c}if(!o||o.length===0){let c=mc.ALTER_USER_ROLE_NOT_FOUND(t.role);throw ke.error(c),ks(new Error,c,Fs.NOT_FOUND,void 0,void 0,!0)}if(o.length>1){let c=mc.ALTER_USER_DUP_ROLES(t.role);throw ke.error(c),ks(new Error,c,Fs.CONFLICT,void 0,void 0,!0)}t.role=o[0].id}let n={operation:"update",schema:"system",table:"hdb_user",records:[t]},s;try{s=await FC.update(n)}catch(i){throw ke.error("Error during update."),ke.error(i),i}try{await pc()}catch(i){throw ke.error("Got an error setting users to global"),ke.error(i),i}return CT.signalUserChange(new LT(process.pid)),s}a(k2,"alterUser");function F2(e){let t=!1,r=global.hdb_users.get(e);return r&&r.role.permission.cluster_user===!0&&(t=!0),t}a(F2,"isClusterUser");async function G2(e){try{let t=GC.dropUserValidation(e);if(t)throw new Error(t);let r={table:"hdb_user",schema:"system",hash_values:[e.username]};if(bn.isEmpty(global.hdb_users.get(e.username)))throw ks(new Error,mc.USER_NOT_EXIST(e.username),Fs.NOT_FOUND,void 0,void 0,!0);let n;try{n=await B2(r)}catch(s){throw ke.error("Got an error deleting a user."),ke.error(s),s}ke.debug(n);try{await pc()}catch(s){throw ke.error("Got an error setting users to global."),ke.error(s),s}return CT.signalUserChange(new LT(process.pid)),`${e.username} successfully deleted`}catch(t){throw t}}a(G2,"dropUser");async function q2(e){let t={};try{if(!e||!e.hdb_user)return"There was no user info in the body";t=IT.cloneDeep(e.hdb_user);let r={schema:"system",table:"hdb_role",hash_values:[t.role.id],get_attributes:["*"]},n;try{n=await x2(r)}catch(s){throw ke.error("Got an error searching for a role."),ke.error(s),s}t.role=n[0],delete t.password,delete t.refresh_token,delete t.hash}catch(r){throw ke.error(r),r}return t}a(q2,"userInfo");async function V2(){let e;try{e=await X_()}catch(t){throw ke.error("Got an error listing users."),ke.error(t),t}try{e.forEach(t=>{delete t.password,delete t.hash,delete t.refresh_token})}catch{throw new Error("there was an error massaging the user data")}return[...e.values()]}a(V2,"listUsersExternal");async function X_(){try{let e={schema:"system",table:"hdb_role",search_value:"*",search_attribute:"role",get_attributes:["*"]},t;try{t=await J_(e)}catch(o){throw ke.error("Got an error searching for roles."),ke.error(o),o}let r={};for(let o of t)r[o.id]=IT.cloneDeep(o);if(Object.keys(r).length===0)return null;let n={schema:"system",table:"hdb_user",search_value:"*",search_attribute:"username",get_attributes:["*"]},s;try{s=await J_(n)}catch(o){throw ke.error("Got an error searching for users."),ke.error(o),o}let i=new Map;for(let o of s)o=IT.cloneDeep(o),o.role=r[o.role],$2(o.role),i.set(o.username,o);return i}catch(e){throw ke.error("got an error listing users"),ke.error(e),bn.errorizeMessage(e)}return null}a(X_,"listUsers");function $2(e){try{if(!e){ke.error("invalid user role found.");return}e.permission.system||(e.permission.system={}),e.permission.system.tables||(e.permission.system.tables={});for(let t of Object.keys(M2)){let r={read:!!e.permission.super_user,insert:!1,update:!1,delete:!1,attribute_permissions:[]};e.permission.system.tables[t]=r}}catch(t){ke.error("Got an error trying to set system permissions."),ke.error(t)}}a($2,"appendSystemTablesToRole");async function pc(){try{let e=await X_();global.hdb_users=e}catch(e){throw ke.error(e),e}}a(pc,"setUsersToGlobal");async function YC(e,t,r=!0){global.hdb_users||await pc();let n=global.hdb_users.get(e);if(!n){if(!r)return{username:e};throw ks(new Error,NT.GENERIC_AUTH_FAIL,Fs.UNAUTHORIZED,void 0,void 0,!0)}if(n&&!n.active)throw ks(new Error,NT.USER_INACTIVE,Fs.UNAUTHORIZED,void 0,void 0,!0);let s={active:n.active,username:n.username};if(n.refresh_token&&(s.refresh_token=n.refresh_token),n.role&&(s.role=n.role),r===!0){if(UC.get(t)===n.password)return s;if(wT.validate(n.password,t))UC.set(t,n.password);else throw ks(new Error,NT.GENERIC_AUTH_FAIL,Fs.UNAUTHORIZED,void 0,void 0,!0)}return s}a(YC,"findAndValidateUser");async function Y2(){global.hdb_users||await pc();for(let[,e]of global.hdb_users)if(e.role.role==="super_user")return e}a(Y2,"getSuperUser");async function K2(){let e=await X_(),t=P2.getConfigFromFile(PC.CONFIG_PARAMS.CLUSTERING_USER),r=e.get(t);if(!bn.isEmpty(r)&&r?.role?.role===PC.ROLE_TYPES_ENUM.CLUSTER_USER)return r.decrypt_hash=DT.decrypt(r.hash),r.uri_encoded_d_hash=encodeURIComponent(r.decrypt_hash),r.uri_encoded_name=encodeURIComponent(r.username),r.sys_name=r.username+MC.SERVER_SUFFIX.ADMIN,r.sys_name_encoded=r.uri_encoded_name+MC.SERVER_SUFFIX.ADMIN,r}a(K2,"getClusterUser");var KC=[];PT.invalidateUser=function(e){for(let t of KC)try{t(e)}catch(r){v2.error("Error invalidating user",r)}};PT.onInvalidatedUser=function(e){KC.push(e)}});var Lu=I((uEe,JC)=>{"use strict";var ta=X(),yn=H(),W2=yw(),cEe=eo(),lEe=Zi(),Q2=$n(),{validateEvent:QC}=Es(),Du=Vn(),z2=require("process"),{resetDatabases:j2}=(Ne(),ae(it)),J2={[yn.ITC_EVENT_TYPES.SCHEMA]:X2,[yn.ITC_EVENT_TYPES.USER]:jC};async function X2(e){let t=QC(e);if(t){ta.error(t);return}ta.trace("ITC schemaHandler received schema event:",e),await W2(e.message),await Z2(e.message)}a(X2,"schemaHandler");async function Z2(e){try{Du.resetReadTxn(yn.SYSTEM_SCHEMA_NAME,yn.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME),Du.resetReadTxn(yn.SYSTEM_SCHEMA_NAME,yn.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME),Du.resetReadTxn(yn.SYSTEM_SCHEMA_NAME,yn.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME);let t=j2();e.table&&e.database&&await t[e.database][e.table].put(Symbol.for("write-verify"),null)}catch(t){ta.error(t)}}a(Z2,"syncSchemaMetadata");var zC=[];async function jC(e){try{try{Du.resetReadTxn(yn.SYSTEM_SCHEMA_NAME,yn.SYSTEM_TABLE_NAMES.USER_TABLE_NAME),Du.resetReadTxn(yn.SYSTEM_SCHEMA_NAME,yn.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME)}catch(r){ta.warn(r)}let t=QC(e);if(t){ta.error(t);return}ta.trace(`ITC userHandler ${yn.HDB_ITC_CLIENT_PREFIX}${z2.pid} received user event:`,e),await Q2.setUsersToGlobal();for(let r of zC)r()}catch(t){ta.error(t)}}a(jC,"userHandler");jC.addListener=function(e){zC.push(e)};JC.exports=J2});var Es=I((mEe,ZC)=>{"use strict";var fEe=X(),MT=re(),ej=H(),{ITC_ERRORS:Pu}=En(),{parentPort:_Ee,threadId:tj,isMainThread:rj,workerData:EEe}=require("worker_threads"),{onMessageFromWorkers:nj,broadcast:hEe,broadcastWithAcknowledgement:sj}=at();ZC.exports={sendItcEvent:ij,validateEvent:XC,SchemaEventMsg:oj,UserEventMsg:aj};var Z_;nj(async(e,t)=>{Z_=Z_||Lu(),XC(e),Z_[e.type]&&await Z_[e.type](e),e.requestId&&t&&t.postMessage({type:"ack",id:e.requestId})});function ij(e){return!rj&&e.message&&(e.message.originator=tj),sj(e)}a(ij,"sendItcEvent");function XC(e){if(typeof e!="object")return Pu.INVALID_ITC_DATA_TYPE;if(!e.hasOwnProperty("type")||MT.isEmpty(e.type))return Pu.MISSING_TYPE;if(!e.hasOwnProperty("message")||MT.isEmpty(e.message))return Pu.MISSING_MSG;if(!e.message.hasOwnProperty("originator")||MT.isEmpty(e.message.originator))return Pu.MISSING_ORIGIN;if(ej.ITC_EVENT_TYPES[e.type.toUpperCase()]===void 0)return Pu.INVALID_EVENT(e.type)}a(XC,"validateEvent");function oj(e,t,r,n=void 0,s=void 0){this.originator=e,this.operation=t,this.schema=r,this.table=n,this.attribute=s}a(oj,"SchemaEventMsg");function aj(e){this.originator=e}a(aj,"UserEventMsg")});var pi=I((TEe,nD)=>{"use strict";var eD=H(),SEe=re(),eE=X(),tD=Rw(),Sc,{sendItcEvent:rD}=Es();function cj(e){try{eE.info("signalSchemaChange called with message:",e),Sc=Sc||Lu();let t=new tD(eD.ITC_EVENT_TYPES.SCHEMA,e);return Sc.schema(t),rD(t)}catch(t){eE.error(t)}}a(cj,"signalSchemaChange");function lj(e){try{eE.trace("signalUserChange called with message:",e),Sc=Sc||Lu();let t=new tD(eD.ITC_EVENT_TYPES.USER,e);return Sc.user(t),rD(t)}catch(t){eE.error(t)}}a(lj,"signalUserChange");nD.exports={signalSchemaChange:cj,signalUserChange:lj}});var tE=I((REe,iD)=>{"use strict";var sD=re(),uj=H(),dj=X(),fj=P_(),_j=L_(),Ej=pi(),{SchemaEventMsg:hj}=Es(),mj="already exists in";iD.exports=pj;async function pj(e,t,r){if(sD.isEmptyOrZeroLength(r))return r;let n=[];sD.isEmptyOrZeroLength(t.attributes)||t.attributes.forEach(i=>{n.push(i.attribute)});let s=r.filter(i=>n.indexOf(i)<0);return s.length===0||await Promise.all(s.map(async i=>{await Sj(e,t.schema,t.name,i)})),s}a(pj,"lmdbCheckForNewAttributes");async function Sj(e,t,r,n){let s=new _j(t,r,n,void 0,!0);e&&(s.hdb_auth_header=e);try{await Tj(s)}catch(i){if(typeof i=="object"&&i.message!==void 0&&i.message.includes(mj))dj.warn(`attribute ${t}.${r}.${n} already exists`);else throw i}}a(Sj,"createNewAttribute");async function Tj(e){let t;return t=await fj(e),Ej.signalSchemaChange(new hj(process.pid,uj.OPERATIONS_ENUM.CREATE_ATTRIBUTE,e.schema,e.table,e.attribute)),t}a(Tj,"createAttribute")});var Tc=I((bEe,oD)=>{"use strict";var UT=class{static{a(this,"LMDBTransactionObject")}constructor(t,r,n,s,i=void 0){this.operation=t,this.user_name=r,this.timestamp=n,this.hash_values=s,this.origin=i}};oD.exports=UT});var cD=I((OEe,aD)=>{"use strict";var gj=Tc(),Rj=H().OPERATIONS_ENUM,vT=class extends gj{static{a(this,"LMDBInsertTransactionObject")}constructor(t,r,n,s,i=void 0){super(Rj.INSERT,r,n,s,i),this.records=t}};aD.exports=vT});var uD=I((IEe,lD)=>{"use strict";var Aj=Tc(),bj=H().OPERATIONS_ENUM,xT=class extends Aj{static{a(this,"LMDBUpdateTransactionObject")}constructor(t,r,n,s,i,o=void 0){super(bj.UPDATE,n,s,i,o),this.records=t,this.original_records=r}};lD.exports=xT});var fD=I((CEe,dD)=>{"use strict";var yj=Tc(),Oj=H().OPERATIONS_ENUM,BT=class extends yj{static{a(this,"LMDBUpsertTransactionObject")}constructor(t,r,n,s,i,o=void 0){super(Oj.UPSERT,n,s,i,o),this.records=t,this.original_records=r}};dD.exports=BT});var ED=I((LEe,_D)=>{"use strict";var Nj=Tc(),Ij=H().OPERATIONS_ENUM,HT=class extends Nj{static{a(this,"LMDBDeleteTransactionObject")}constructor(t,r,n,s,i=void 0){super(Ij.DELETE,n,s,t,i),this.original_records=r}};_D.exports=HT});var Mu=I((UEe,SD)=>{"use strict";var MEe=require("path"),hD=ft(),wj=cD(),Cj=uD(),Dj=fD(),Lj=ED(),gc=Ft(),mD=re(),{CONFIG_PARAMS:Pj}=H(),pD=ie();pD.initSync();var rE=H().OPERATIONS_ENUM,{getTransactionAuditStorePath:Mj}=ht();SD.exports=Uj;async function Uj(e,t){if(pD.get(Pj.LOGGING_AUDITLOG)===!1)return;let r=Mj(e.schema,e.table),n=await hD.openEnvironment(r,e.table,!0),s=vj(e,t);if(!(s===void 0||s.hash_values.length===0)&&n!==void 0){hD.initializeDBIs(n,gc.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,gc.TRANSACTIONS_DBIS);let i=s.timestamp;return await n.dbis[gc.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP].ifNoExists(i,()=>{n.dbis[gc.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP].put(i,s),mD.isEmpty(s.user_name)||n.dbis[gc.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].put(s.user_name,i);for(let o=0;o<s.hash_values.length;o++)n.dbis[gc.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE].put(s.hash_values[o],i)})}}a(Uj,"writeTransaction");function vj(e,t){let r=mD.isEmpty(e.hdb_user)?void 0:e.hdb_user.username;if(e.operation===rE.INSERT)return new wj(e.records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===rE.UPDATE)return new Cj(e.records,t.original_records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===rE.UPSERT)return new Dj(e.records,t.original_records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===rE.DELETE)return new Lj(t.deleted,t.original_records,r,t.txn_time,e.__origin)}a(vj,"createTransactionObject")});var kT=I((BEe,TD)=>{"use strict";var xj=Au(),xEe=bu(),Uu=H(),Bj=yu(),Hj=lc().insertRecords,kj=ft(),Fj=X(),Gj=tE(),{getSchemaPath:qj}=ht(),Vj=Mu();TD.exports=$j;async function $j(e){try{let{schema_table:t,attributes:r}=xj(e);Bj(e,r,t.hash_attribute),e.schema!==Uu.SYSTEM_SCHEMA_NAME&&(r.includes(Uu.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||r.push(Uu.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.includes(Uu.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||r.push(Uu.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let n=await Gj(e.hdb_auth_header,t,r),s=qj(e.schema,e.table),i=await kj.openEnvironment(s,e.table),o=await Hj(i,t.hash_attribute,r,e.records,e.__origin?.timestamp);try{await Vj(e,o)}catch(c){Fj.error(`unable to write transaction due to ${c.message}`)}return{written_hashes:o.written_hashes,skipped_hashes:o.skipped_hashes,schema_table:t,new_attributes:n,txn_time:o.txn_time}}catch(t){throw t}}a($j,"lmdbCreateRecords")});var AD=I((kEe,RD)=>{"use strict";var gD=H(),Yj=kT(),Kj=bu(),Wj=require("fs-extra"),{getSchemaPath:Qj}=ht();RD.exports=zj;async function zj(e){let t=[{name:e.schema,createddate:Date.now()}],r=new Kj(gD.SYSTEM_SCHEMA_NAME,gD.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,void 0,t);await Yj(r),await Wj.mkdirp(Qj(e.schema))}a(zj,"lmdbCreateSchema")});var yD=I((GEe,bD)=>{"use strict";var FT=class{static{a(this,"DeleteRecordsResponseObject")}constructor(t=[],r=[],n=void 0,s=[]){this.deleted=t,this.skipped=r,this.txn_time=n,this.original_records=s}};bD.exports=FT});var wD=I((KEe,ID)=>{"use strict";var OD=ft(),GT=hn(),qT=En().LMDB_ERRORS_ENUM,jj=Ft(),ND=X(),VEe=re(),Jj=require("lmdb"),Xj=yD(),Zj=H(),{OVERFLOW_MARKER:$Ee,MAX_SEARCH_KEY_LENGTH:YEe}=jj,e4=Zj.TIME_STAMP_NAMES_ENUM.UPDATED_TIME;async function t4(e,t,r,n){if(GT.validateEnv(e),t===void 0)throw new Error(qT.HASH_ATTRIBUTE_REQUIRED);if(!Array.isArray(r))throw r===void 0?new Error(qT.IDS_REQUIRED):new Error(qT.IDS_MUST_BE_ITERABLE);try{let s=OD.listDBIs(e);OD.initializeDBIs(e,t,s);let i=new Xj,o,c=[],l=[];for(let E=0,_=r.length;E<_;E++)try{o=r[E];let h=e.dbis[t].get(o);if(!h||n&&h[e4]>n){i.skipped.push(o);continue}let p=e.dbis[t].ifVersion(o,Jj.IF_EXISTS,()=>{e.dbis[t].remove(o);for(let S=0;S<s.length;S++){let g=s[S];if(!h.hasOwnProperty(g)||g===t)continue;let T=e.dbis[g],A=h[g];if(A!=null)try{let N=GT.getIndexedValues(A);if(N)for(let V=0,v=N.length;V<v;V++)T.remove(N[V],o)}catch{ND.warn(`cannot delete from attribute: ${g}, ${A}:${o}`)}}});c.push(p),l.push(o),i.original_records.push(h)}catch(h){ND.warn(h),i.skipped.push(o)}let d=[],u=await Promise.all(c);for(let E=0,_=u.length;E<_;E++)u[E]===!0?i.deleted.push(l[E]):(i.skipped.push(l[E]),d.push(E));let f=0;for(let E=0;E<d.length;E++){let _=d[E];i.original_records.splice(_-f,1),f++}return i.txn_time=GT.getNextMonotonicTime(),i}catch(s){throw s}}a(t4,"deleteRecords");ID.exports={deleteRecords:t4}});var vu=I((QEe,DD)=>{"use strict";var Rc=re(),r4=wD(),n4=ft(),{getSchemaPath:s4}=ht(),i4=Mu(),o4=X();DD.exports=a4;async function a4(e,t=!0){let n=global.hdb_schema[e.schema][e.table].hash_attribute;if(Rc.isEmpty(n))throw new Error(`could not retrieve hash attribute for schema:${e.schema} and table ${e.table}`);try{if(Rc.isEmptyOrZeroLength(e.hash_values)&&!Rc.isEmptyOrZeroLength(e.records)){e.hash_values=[];for(let c=0;c<e.records.length;c++){let l=e.records[c][n];Rc.isEmpty(l)||e.hash_values.push(l)}}if(Rc.isEmptyOrZeroLength(e.hash_values))return CD([],[]);if(!Array.isArray(e.hash_values))throw new Error("hash_values must be an array");if(Rc.isEmptyOrZeroLength(e.records)){e.records=[];for(let c=0;c<e.hash_values.length;c++)e.records[c]={[n]:e.hash_values[c]}}let s=s4(e.schema,e.table),i=await n4.openEnvironment(s,e.table),o=await r4.deleteRecords(i,n,e.hash_values,e.__origin?.timestamp);try{t===!0&&await i4(e,o)}catch(c){o4.error(`unable to write transaction due to ${c.message}`)}return CD(o.deleted,o.skipped,o.txn_time)}catch(s){throw s}}a(a4,"lmdbDeleteRecords");function CD(e,t,r){let n=e.length+t.length,s=n===1?"record":"records";return{message:`${e.length} of ${n} ${s} successfully deleted`,deleted_hashes:e,skipped_hashes:t,txn_time:r}}a(CD,"createDeleteResponse")});var $T=I((JEe,LD)=>{"use strict";var c4=H(),jEe=hn();function VT(e,t){let r=Object.create(null);if(t.length===1&&c4.SEARCH_WILDCARDS.indexOf(t[0])>=0)Object.assign(r,e);else for(let n=0;n<t.length;n++){let s=t[n],i=e[s];r[s]=i===void 0?null:i}return r}a(VT,"parseRow");function l4(e,t,r,n){let s=VT(r,e);n.push(s)}a(l4,"searchAll");function u4(e,t,r,n){let s=VT(r,e);n[t]=s}a(u4,"searchAllToMap");function d4(e,t,r){r[e]===void 0&&(r[e]=[]),r[e].push(t)}a(d4,"iterateDBI");function ra(e,t,r,n,s){let i=Object.create(null);i[s]=e;let o;n===s?o=e:(o=t,n!==void 0&&(i[n]=o)),r[0].push(o),r[1].push(i)}a(ra,"pushResults");function f4(e,t,r,n,s,i){t.toString().endsWith(e)&&ra(t,r,n,s,i)}a(f4,"endsWith");function _4(e,t,r,n,s,i){t.toString().includes(e)&&ra(t,r,n,s,i)}a(_4,"contains");function E4(e,t,r,n,s,i){t>e&&ra(t,r,n,s,i)}a(E4,"greaterThanCompare");function h4(e,t,r,n,s,i){t>=e&&ra(t,r,n,s,i)}a(h4,"greaterThanEqualCompare");function m4(e,t,r,n,s,i){t<e&&ra(t,r,n,s,i)}a(m4,"lessThanCompare");function p4(e,t,r,n,s,i){t<=e&&ra(t,r,n,s,i)}a(p4,"lessThanEqualCompare");LD.exports={parseRow:VT,searchAll:l4,searchAllToMap:u4,iterateDBI:d4,endsWith:f4,contains:_4,greaterThanCompare:E4,greaterThanEqualCompare:h4,lessThanCompare:m4,lessThanEqualCompare:p4,pushResults:ra}});var Ac=I((rhe,HD)=>{"use strict";var oo=ft(),ZEe=X(),On=hn(),nE=Ft(),Gt=En().LMDB_ERRORS_ENUM,ehe=re(),S4=H(),sE=$T(),{parseRow:T4}=sE,the=require("lmdb"),{OVERFLOW_MARKER:PD,MAX_SEARCH_KEY_LENGTH:g4}=nE;function MD(e,t,r,n=!1,s=void 0,i=void 0){return na(e,t,r,(o,c)=>c.getRange({transaction:o,start:n?void 0:!1,end:n?!1:void 0,limit:s,offset:i,reverse:n}))}a(MD,"iterateFullIndex");function xu(e,t,r,n,s,i=!1,o=void 0,c=void 0,l=!1,d=!1){return na(e,t,r,(u,f,E,_)=>{let T={transaction:u,start:i===!0?s:n,end:i===!0?n:s,reverse:i,limit:o,offset:c,inclusiveEnd:i===!0?!l:!d,exclusiveStart:i===!0?d:l};return _===r?(T.values=!1,f.getRange(T).map(A=>({value:A}))):f.getRange(T)})}a(xu,"iterateRangeBetween");function na(e,t,r,n){let s=e.database||e,i=oo.openDBI(s,r);i[nE.DBI_DEFINITION_NAME].is_hash_attribute?t=r:t&&oo.openDBI(s,t);let o;e.database?o=e:(o=e.useReadTransaction(),o.database=e);let c=n(o,i,s,t);return c.transaction=o,e.database||(c.onDone=()=>{o.done()}),c}a(na,"setupTransaction");function UD(e,t,r,n){let s;return function(i,o){if(typeof i=="string"&&i.endsWith(PD)){if(!s)if(r)s=oo.openDBI(e,r);else{let l=oo.listDBIs(e);for(let d=0,u=l.length;d<u&&(s=oo.openDBI(e,l[d]),!s[nE.DBI_DEFINITION_NAME].is_hash_attribute);d++);}i=s.get(o,{transaction:t,lazy:!0})[n]}return i}}a(UD,"getOverflowCheck");function R4(e,t,r,n=!1,s=void 0,i=void 0){if(On.validateEnv(e),t===void 0)throw new Error(Gt.HASH_ATTRIBUTE_REQUIRED);return na(e,t,t,(o,c,l)=>(iE(r),r=Bu(l,r),c.getRange({transaction:o,start:n?void 0:!1,end:n?!1:void 0,limit:s,offset:i,reverse:n}).map(d=>T4(d.value,r))))}a(R4,"searchAll");function A4(e,t,r,n=!1,s=void 0,i=void 0){if(On.validateEnv(e),t===void 0)throw new Error(Gt.HASH_ATTRIBUTE_REQUIRED);iE(r),r=Bu(e.database||e,r);let o=new Map;for(let{key:c,value:l}of MD(e,t,t,n,s,i))o.set(c,sE.parseRow(l,r));return o}a(A4,"searchAllToMap");function b4(e,t,r=!1,n=void 0,s=void 0){if(On.validateEnv(e),t===void 0)throw new Error(Gt.ATTRIBUTE_REQUIRED);let i=Object.create(null),o=MD(e,void 0,t,r,n,s),c=o.transaction,l=UD(c.database,c,void 0,t);for(let{key:d,value:u}of o){let f=l(d,u);i[f]===void 0&&(i[f]=[]),i[f].push(u)}return i}a(b4,"iterateDBI");function y4(e,t){if(On.validateEnv(e),t===void 0)throw new Error(Gt.HASH_ATTRIBUTE_REQUIRED);return oo.statDBI(e,t).entryCount}a(y4,"countAll");function O4(e,t,r,n,s=!1,i=void 0,o=void 0){return ao(e,r,n),na(e,t,r,(c,l,d,u)=>(n=On.convertKeyValueToWrite(n),u===r?l.get(n,{transaction:c,lazy:!0})===void 0?[]:[{key:n,value:n}]:l.getValues(n,{transaction:c,reverse:s,limit:i,offset:o}).map(f=>({key:n,value:f}))))}a(O4,"equals");function N4(e,t,r){return ao(e,t,r),oo.openDBI(e,t).getValuesCount(r)}a(N4,"count");function I4(e,t,r,n,s=!1,i=void 0,o=void 0){return ao(e,r,n),na(e,null,r,(c,l)=>{n=On.convertKeyValueToWrite(n);let d=!0;typeof n=="number"&&(d=!1);let u;if(s===!0){let f;for(let E of l.getKeys({transaction:c,start:n}))if(!E.startsWith(n)){f=E;break}return f!==void 0&&(Number.isInteger(o)?o++:i++),u=l.getRange({transaction:c,start:f,end:void 0,reverse:s,limit:i,offset:o}).map(E=>{let{key:_}=E;if(_!==f){if(_.toString().startsWith(n))return E;if(d===!0)return u.DONE}}),u.filter(E=>E)}else return u=l.getRange({transaction:c,start:n,reverse:s,limit:i,offset:o}).map(f=>{if(f.key.toString().startsWith(n))return f;if(d===!0)return u.DONE}),d?u:u.filter(f=>f)})}a(I4,"startsWith");function w4(e,t,r,n,s=!1,i=void 0,o=void 0){return vD(e,t,r,n,s,i,o,!0)}a(w4,"endsWith");function vD(e,t,r,n,s=!1,i=void 0,o=void 0,c=!1){return ao(e,r,n),na(e,null,r,(l,d,u,f)=>{let E=UD(u,l,f,r);return o=Number.isInteger(o)?o:0,d.getKeys({transaction:l,end:s?!1:void 0,reverse:s}).flatMap(_=>{let h=_.toString();return h.endsWith(PD)?d.getValues(_,{transaction:l}).map(p=>{let S=E(_,p);if(c?S.endsWith(n):S.includes(n))return{key:S,value:p}}).filter(p=>p):(c?h.endsWith(n):h.includes(n))?d[nE.DBI_DEFINITION_NAME].is_hash_attribute?{key:_,value:_}:d.getValues(_,{transaction:l}).map(p=>({key:_,value:p})):[]}).slice(o,i===void 0?void 0:i+(o||0))})}a(vD,"contains");function C4(e,t,r,n,s=!1,i=void 0,o=void 0){ao(e,r,n);let c=typeof n,l;return c==="string"?l="\uFFFF":c==="number"?l=1/0:c==="boolean"&&(l=!0),xu(e,t,r,n,l,s,i,o,!0,!1)}a(C4,"greaterThan");function D4(e,t,r,n,s=!1,i=void 0,o=void 0){ao(e,r,n);let c=typeof n,l;return c==="string"?l="\uFFFF":c==="number"?l=1/0:c==="boolean"&&(l=!0),xu(e,t,r,n,l,s,i,o,!1,!1)}a(D4,"greaterThanEqual");function L4(e,t,r,n,s=!1,i=void 0,o=void 0){ao(e,r,n);let c=typeof n,l;return c==="string"?l="\0":c==="number"?l=-1/0:c==="boolean"&&(l=!1),xu(e,t,r,l,n,s,i,o,!1,!0)}a(L4,"lessThan");function P4(e,t,r,n,s=!1,i=void 0,o=void 0){ao(e,r,n);let c=typeof n,l;return c==="string"?l="\0":c==="number"?l=-1/0:c==="boolean"&&(l=!1),xu(e,t,r,l,n,s,i,o,!1,!1)}a(P4,"lessThanEqual");function M4(e,t,r,n,s,i=!1,o=void 0,c=void 0){if(On.validateEnv(e),r===void 0)throw new Error(Gt.ATTRIBUTE_REQUIRED);if(n===void 0)throw new Error(Gt.START_VALUE_REQUIRED);if(s===void 0)throw new Error(Gt.END_VALUE_REQUIRED);if(n=On.convertKeyValueToWrite(n),s=On.convertKeyValueToWrite(s),n>s)throw new Error(Gt.END_VALUE_MUST_BE_GREATER_THAN_START_VALUE);return xu(e,t,r,n,s,i,o,c)}a(M4,"between");function U4(e,t,r,n){On.validateEnv(e);let s=e.database||e,i=e.database?e:null;if(t===void 0)throw new Error(Gt.HASH_ATTRIBUTE_REQUIRED);if(iE(r),r=Bu(s,r),n===void 0)throw new Error(Gt.ID_REQUIRED);let o=null,c=s.dbis[t].get(n,{transaction:i,lazy:r.length<3});return c&&(o=sE.parseRow(c,r)),o}a(U4,"searchByHash");function v4(e,t,r){On.validateEnv(e);let n=e.database||e,s=e.database?e:null;if(t===void 0)throw new Error(Gt.HASH_ATTRIBUTE_REQUIRED);if(r===void 0)throw new Error(Gt.ID_REQUIRED);let i=!0;return n.dbis[t].get(r,{transaction:s,lazy:!0})===void 0&&(i=!1),i}a(v4,"checkHashExists");function x4(e,t,r,n,s=[]){return BD(e,t,r,n,s),xD(e,t,r,n,s).map(i=>i[1])}a(x4,"batchSearchByHash");function B4(e,t,r,n,s=[]){BD(e,t,r,n,s);let i=new Map;for(let[o,c]of xD(e,t,r,n,s))i.set(o,c);return i}a(B4,"batchSearchByHashToMap");function xD(e,t,r,n,s=[]){return na(e,t,t,(i,o,c)=>{r=Bu(c,r);let l=r.length<3;return n.map(d=>{let u=c.dbis[t].get(d,{transaction:i,lazy:l});if(u)return[d,sE.parseRow(u,r)];s.push(d)}).filter(d=>d)})}a(xD,"batchHashSearch");function BD(e,t,r,n,s){if(On.validateEnv(e),t===void 0)throw new Error(Gt.HASH_ATTRIBUTE_REQUIRED);if(iE(r),n==null)throw new Error(Gt.IDS_REQUIRED);if(!n[Symbol.iterator])throw new Error(Gt.IDS_MUST_BE_ITERABLE)}a(BD,"initializeBatchSearchByHash");function iE(e){if(!Array.isArray(e))throw e===void 0?new Error(Gt.FETCH_ATTRIBUTES_REQUIRED):new Error(Gt.FETCH_ATTRIBUTES_MUST_BE_ARRAY)}a(iE,"validateFetchAttributes");function ao(e,t,r){if(On.validateEnv(e),t===void 0)throw new Error(Gt.ATTRIBUTE_REQUIRED);if(r===void 0)throw new Error(Gt.SEARCH_VALUE_REQUIRED);if(r?.length>g4)throw new Error(Gt.SEARCH_VALUE_TOO_LARGE)}a(ao,"validateComparisonFunctions");function Bu(e,t){return t.length===1&&S4.SEARCH_WILDCARDS.indexOf(t[0])>=0&&(t=oo.listDBIs(e)),t}a(Bu,"setGetWholeRowAttributes");HD.exports={searchAll:R4,searchAllToMap:A4,count:N4,countAll:y4,equals:O4,startsWith:I4,endsWith:w4,contains:vD,searchByHash:U4,setGetWholeRowAttributes:Bu,batchSearchByHash:x4,batchSearchByHashToMap:B4,checkHashExists:v4,iterateDBI:b4,greaterThan:C4,greaterThanEqual:D4,lessThan:L4,lessThanEqual:P4,between:M4}});var bc=I((she,VD)=>{var kD=require("lodash"),FD=mt(),Le=require("joi"),H4=re(),{hdb_schema_table:Hu,checkValidTable:GD,hdb_table:qD,hdb_database:oE}=xs(),{handleHDBError:k4,hdb_errors:F4}=ce(),{getDatabases:G4}=(Ne(),ae(it)),{HTTP_STATUS_CODES:q4}=F4,V4=Le.object({database:oE,schema:oE,table:qD,search_attribute:Hu,search_value:Le.any().required(),get_attributes:Le.array().min(1).items(Le.alternatives(Hu,Le.object())).optional(),desc:Le.bool(),limit:Le.number().integer().min(1),offset:Le.number().integer().min(0)}),$4=Le.object({database:oE,schema:oE,table:qD,operator:Le.string().valid("and","or").default("and").lowercase(),offset:Le.number().integer().min(0),limit:Le.number().integer().min(1),get_attributes:Le.array().min(1).items(Le.alternatives(Hu,Le.object())).optional(),sort:Le.object({attribute:Le.alternatives(Hu,Le.array().min(1)),descending:Le.bool().optional()}).optional(),conditions:Le.array().min(1).items(Le.alternatives(Le.object({operator:Le.string().valid("and","or").default("and").lowercase(),conditions:Le.array()}),Le.object({search_attribute:Le.alternatives(Hu,Le.array().min(1)),search_type:Le.string().valid("equals","contains","starts_with","ends_with","greater_than","greater_than_equal","less_than","less_than_equal","between","not_equal").optional(),search_value:Le.when("search_type",{switch:[{is:"equals",then:Le.any()},{is:"between",then:Le.array().items(Le.alternatives([Le.string(),Le.number()])).length(2)}],otherwise:Le.alternatives(Le.string(),Le.number())}).required()}))).required()});VD.exports=function(e,t){let r=null;switch(t){case"value":r=FD.validateBySchema(e,V4);break;case"hashes":let i=function(o){s?s+=". "+o:s=o};var n=i;a(i,"addError");let s;i(GD("database",e.schema)),i(GD("table",e.table)),e.hash_values?Array.isArray(e.hash_values)?e.hash_values.every(o=>typeof o=="string"||typeof o=="number")||i("'hash_values' must be strings or numbers"):i("'hash_values' must be an array"):i("'hash_values' is required"),e.get_attributes?Array.isArray(e.get_attributes)?e.get_attributes.length===0?i("'get_attributes' must contain at least 1 item"):e.get_attributes.every(o=>typeof o=="string"||typeof o=="number")||i("'get_attributes' must be strings or numbers"):i("'get_attributes' must be an array"):i("'get_attributes' is required"),s&&(r=new Error(s.trim()));break;case"conditions":r=FD.validateBySchema(e,$4);break;default:throw new Error(`Error validating search, unknown type: ${t}`)}if(!r&&e.schema!=="system"){let s=H4.checkGlobalSchemaTable(e.schema,e.table);if(s)return k4(new Error,s,q4.NOT_FOUND);let o=G4()[e.schema][e.table].attributes,c=e.get_attributes?[...e.get_attributes]:[];t==="value"&&c.push(e.search_attribute);let l=a(u=>{for(let f=0,E=u.conditions.length;f<E;f++){let _=u.conditions[f];_.conditions?l(_):c.push(_.search_attribute)}},"addConditions");t==="conditions"&&l(e);let d=kD.filter(c,u=>u!=="*"&&u.attribute!=="*"&&!Array.isArray(u)&&!u.name&&!kD.some(o,f=>f===u||f.attribute===u||f.attribute===u.attribute));if(d&&d.length>0){let u=d.join(", ");return u=u.replace(/,([^,]*)$/," and$1"),new Error(`unknown attribute '${u}'`)}}return r}});var YT=I((ohe,$D)=>{"use strict";var Y4=ft(),K4=bc(),{getSchemaPath:W4}=ht();$D.exports=Q4;function Q4(e){let t=K4(e,"hashes");if(t)throw t;let r=W4(e.schema,e.table);return Y4.openEnvironment(r,e.table)}a(Q4,"initialize")});var KT=I((che,YD)=>{"use strict";var z4=Ac(),j4=YT();YD.exports=J4;async function J4(e){let t=await j4(e),r=t.useReadTransaction();r.database=t;let n=global.hdb_schema[e.schema][e.table];try{return z4.batchSearchByHashToMap(r,n.hash_attribute,e.get_attributes,e.hash_values)}finally{r.done()}}a(J4,"lmdbGetDataByHash")});var yc=I((uhe,KD)=>{"use strict";var WT=class{static{a(this,"SearchByHashObject")}constructor(t,r,n,s){this.schema=t,this.table=r,this.hash_values=n,this.get_attributes=s}};KD.exports=WT});var QD=I((_he,WD)=>{"use strict";var fhe=yc(),X4=Ac(),Z4=YT();WD.exports=eJ;async function eJ(e){let t=await Z4(e),r=global.hdb_schema[e.schema][e.table];return X4.batchSearchByHash(t,r.hash_attribute,e.get_attributes,e.hash_values)}a(eJ,"lmdbSearchByHash")});var Gs=I((hhe,zD)=>{"use strict";var QT=class{static{a(this,"SearchObject")}constructor(t,r,n,s,i,o,c,l=!1,d=void 0,u=void 0){this.schema=t,this.table=r,this.search_attribute=n,this.search_value=s,this.hash_attribute=i,this.get_attributes=o,this.end_value=c,this.reverse=l,this.limit=d,this.offset=u}};zD.exports=QT});var aE=I((phe,tL)=>{"use strict";var vr=Ac(),tJ=ft(),rJ=re(),Pe=Ft(),sa=H(),nJ=Yo(),jD=En().LMDB_ERRORS_ENUM,{getSchemaPath:sJ}=ht(),Si=sa.SEARCH_WILDCARDS;async function iJ(e,t,r){let n;e.schema===sa.SYSTEM_SCHEMA_NAME?n=nJ[e.table]:n=global.hdb_schema[e.schema][e.table];let s=eL(e,n.hash_attribute,r,t);return XD(e,s,n.hash_attribute,r)}a(iJ,"prepSearch");async function XD(e,t,r,n){let s=sJ(e.schema,e.table),i=await tJ.openEnvironment(s,e.table),o=ZD(i,e,t,r),c=o.transaction||i;if([Pe.SEARCH_TYPES.BATCH_SEARCH_BY_HASH,Pe.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP,Pe.SEARCH_TYPES.SEARCH_ALL,Pe.SEARCH_TYPES.SEARCH_ALL_TO_MAP].indexOf(t)>=0)return o;if(oJ(e,r)===!1){let u=e.search_attribute;if(u===r)return n?JD(o,()=>!0):o.map(E=>({[r]:E.key}));let f=a(E=>({[r]:E.value,[u]:E.key}),"toObject");return n?JD(o,f):o.map(f)}let d=e.search_attribute===r?o.map(u=>u.key):o.map(u=>u.value);return n===!0?vr.batchSearchByHashToMap(c,r,e.get_attributes,d):vr.batchSearchByHash(c,r,e.get_attributes,d)}a(XD,"executeSearch");function ZD(e,t,r,n){let s,i=n;t.get_attributes.indexOf(n)<0&&(i=void 0);let{reverse:o,limit:c,offset:l}=t;switch(o=typeof o=="boolean"?o:!1,c=Number.isInteger(c)?c:void 0,l=Number.isInteger(l)?l:void 0,r){case Pe.SEARCH_TYPES.EQUALS:s=vr.equals(e,i,t.search_attribute,t.search_value,o,c,l);break;case Pe.SEARCH_TYPES.CONTAINS:s=vr.contains(e,i,t.search_attribute,t.search_value,o,c,l);break;case Pe.SEARCH_TYPES.ENDS_WITH:case Pe.SEARCH_TYPES._ENDS_WITH:s=vr.endsWith(e,i,t.search_attribute,t.search_value,o,c,l);break;case Pe.SEARCH_TYPES.STARTS_WITH:case Pe.SEARCH_TYPES._STARTS_WITH:s=vr.startsWith(e,i,t.search_attribute,t.search_value,o,c,l);break;case Pe.SEARCH_TYPES.BATCH_SEARCH_BY_HASH:return vr.batchSearchByHash(e,t.search_attribute,t.get_attributes,[t.search_value]);case Pe.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP:return vr.batchSearchByHashToMap(e,t.search_attribute,t.get_attributes,[t.search_value]);case Pe.SEARCH_TYPES.SEARCH_ALL:return vr.searchAll(e,n,t.get_attributes,o,c,l);case Pe.SEARCH_TYPES.SEARCH_ALL_TO_MAP:return vr.searchAllToMap(e,n,t.get_attributes,o,c,l);case Pe.SEARCH_TYPES.BETWEEN:s=vr.between(e,i,t.search_attribute,t.search_value,t.end_value,o,c,l);break;case Pe.SEARCH_TYPES.GREATER_THAN:case Pe.SEARCH_TYPES._GREATER_THAN:s=vr.greaterThan(e,i,t.search_attribute,t.search_value,o,c,l);break;case Pe.SEARCH_TYPES.GREATER_THAN_EQUAL:case Pe.SEARCH_TYPES._GREATER_THAN_EQUAL:s=vr.greaterThanEqual(e,i,t.search_attribute,t.search_value,o,c,l);break;case Pe.SEARCH_TYPES.LESS_THAN:case Pe.SEARCH_TYPES._LESS_THAN:s=vr.lessThan(e,i,t.search_attribute,t.search_value,o,c,l);break;case Pe.SEARCH_TYPES.LESS_THAN_EQUAL:case Pe.SEARCH_TYPES._LESS_THAN_EQUAL:s=vr.lessThanEqual(e,i,t.search_attribute,t.search_value,o,c,l);break;default:return Object.create(null)}return s}a(ZD,"searchByType");function JD(e,t){let r=new Map;for(let n of e)r.set(n.value,t(n));return r}a(JD,"createMapFromIterable");function oJ(e,t){if(e.get_attributes.length===1&&e.get_attributes[0]==="*")return!0;let r=[e.search_attribute];e.get_attributes.indexOf(t)>=0&&r.push(t);let n=!1;for(let s=0;s<e.get_attributes.length;s++)if(r.indexOf(e.get_attributes[s])<0){n=!0;break}return n}a(oJ,"checkToFetchMore");function eL(e,t,r,n){if(rJ.isEmpty(n)){let s=e.search_value;typeof s=="object"?s=JSON.stringify(s):s=s.toString();let i=s.charAt(0),o=s.charAt(s.length-1),c=!1;if(e.search_attribute===t&&(c=!0),Si.indexOf(s)>-1)return r===!0?Pe.SEARCH_TYPES.SEARCH_ALL_TO_MAP:Pe.SEARCH_TYPES.SEARCH_ALL;if(s.indexOf(Si[0])<0&&s.indexOf(Si[1])<0)return c===!0?r===!0?Pe.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP:Pe.SEARCH_TYPES.BATCH_SEARCH_BY_HASH:Pe.SEARCH_TYPES.EQUALS;if(Si.indexOf(i)>=0&&Si.indexOf(o)>=0)return e.search_value=e.search_value.slice(1,-1),Pe.SEARCH_TYPES.CONTAINS;if(Si.indexOf(i)>=0)return e.search_value=e.search_value.substr(1),Pe.SEARCH_TYPES.ENDS_WITH;if(Si.indexOf(o)>=0)return e.search_value=e.search_value.slice(0,-1),Pe.SEARCH_TYPES.STARTS_WITH;if(s.includes(Si[0])||s.includes(Si[1]))return Pe.SEARCH_TYPES.EQUALS;throw new Error(jD.UNKNOWN_SEARCH_TYPE)}else switch(n){case sa.VALUE_SEARCH_COMPARATORS.BETWEEN:return Pe.SEARCH_TYPES.BETWEEN;case sa.VALUE_SEARCH_COMPARATORS.GREATER:return Pe.SEARCH_TYPES.GREATER_THAN;case sa.VALUE_SEARCH_COMPARATORS.GREATER_OR_EQ:return Pe.SEARCH_TYPES.GREATER_THAN_EQUAL;case sa.VALUE_SEARCH_COMPARATORS.LESS:return Pe.SEARCH_TYPES.LESS_THAN;case sa.VALUE_SEARCH_COMPARATORS.LESS_OR_EQ:return Pe.SEARCH_TYPES.LESS_THAN_EQUAL;default:throw new Error(jD.UNKNOWN_SEARCH_TYPE)}}a(eL,"createSearchTypeFromSearchObject");tL.exports={executeSearch:XD,createSearchTypeFromSearchObject:eL,prepSearch:iJ,searchByType:ZD}});var nL=I((ghe,rL)=>{"use strict";var The=Gs(),aJ=bc(),cJ=re(),lJ=H(),uJ=aE();rL.exports=dJ;function dJ(e,t){if(!cJ.isEmpty(t)&&lJ.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[t]===void 0)throw new Error(`Value search comparator - ${t} - is not valid`);let n=aJ(e,"value");if(n)throw n;return uJ.prepSearch(e,t,!0)}a(dJ,"lmdbGetDataByValue")});var ku=I((bhe,sL)=>{"use strict";var Ahe=Gs(),fJ=bc(),_J=re(),EJ=H(),hJ=aE();sL.exports=mJ;async function mJ(e,t){if(!_J.isEmpty(t)&&EJ.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[t]===void 0)throw new Error(`Value search comparator - ${t} - is not valid`);let n=fJ(e,"value");if(n)throw n;return hJ.prepSearch(e,t,!1)}a(mJ,"lmdbSearchByValue")});var oL=I((Nhe,iL)=>{"use strict";var Ohe=Ft(),zT=class{static{a(this,"SearchByConditionsObject")}constructor(t,r,n,s,i=void 0,o=void 0,c="and"){this.schema=t,this.table=r,this.get_attributes=n,this.limit=i,this.offset=o,this.conditions=s,this.operator=c}},jT=class{static{a(this,"SearchCondition")}constructor(t,r,n){this.search_attribute=t,this.search_type=r,this.search_value=n}},JT=class{static{a(this,"SortAttribute")}constructor(t,r){this.attribute=t,this.desc=r}};iL.exports={SearchByConditionsObject:zT,SearchCondition:jT,SortAttribute:JT}});var dL=I((Dhe,uL)=>{"use strict";var whe=oL().SearchByConditionsObject,pJ=Gs(),SJ=bc(),XT=Ac(),cE=Ft(),{Resource:Che}=(ls(),ae(ZT)),lL=aE(),TJ=$T(),gJ=require("lodash"),{getSchemaPath:RJ}=ht(),aL=ft(),{handleHDBError:AJ,hdb_errors:bJ}=ce(),{HTTP_STATUS_CODES:yJ}=bJ,OJ=1e8;uL.exports=NJ;async function NJ(e){let t=SJ(e,"conditions");if(t)throw AJ(t,t.message,yJ.BAD_REQUEST,void 0,void 0,!0);e.operator=e.operator?e.operator.toLowerCase():void 0,e.offset=Number.isInteger(e.offset)?e.offset:0;let r=RJ(e.schema,e.table),n=await aL.openEnvironment(r,e.table),s=global.hdb_schema[e.schema][e.table];for(let d of e.conditions)aL.openDBI(n,d.search_attribute);let i=gJ.sortBy(e.conditions,d=>{if(d.estimated_count===void 0){let u=d.search_type;u===cE.SEARCH_TYPES.EQUALS?d.estimated_count=XT.count(n,d.search_attribute,d.search_value):u===cE.SEARCH_TYPES.CONTAINS||u===cE.SEARCH_TYPES.ENDS_WITH?d.estimated_count=1/0:d.estimated_count=OJ}return d.estimated_count}),o=n.useReadTransaction();o.database=n;let c=await cL(o,e,i[0],s.hash_attribute),l;if(!e.operator||e.operator.toLowerCase()==="and"){let d=n.dbis[s.hash_attribute],u=i.slice(1).map(lL.filterByType),f=u.length,E=XT.setGetWholeRowAttributes(n,e.get_attributes);l=c.map(_=>d.get(_,{transaction:o,lazy:!0})),f>0&&(l=l.filter(_=>{for(let h=0;h<f;h++)if(!u[h](_))return!1;return!0})),(e.offset||e.limit!==void 0)&&(l=l.slice(e.offset,e.limit!==void 0?(e.offset||0)+e.limit:void 0)),l=l.map(_=>TJ.parseRow(_,E))}else{for(let f=1;f<i.length;f++){let E=i[f],_=await cL(o,e,E,s.hash_attribute);c=c.concat(_)}let d=new Set,u=e.offset||0;c=c.filter(f=>d.has(f)?!1:(d.add(f),!0)).slice(u,e.limit&&e.limit+u),l=XT.batchSearchByHash(o,s.hash_attribute,e.get_attributes,c)}return l.onDone=()=>{o.done()},l}a(NJ,"lmdbSearchByConditions");async function cL(e,t,r,n){let s=new pJ(t.schema,t.table,void 0,void 0,n,t.get_attributes),i=r.search_type;return s.search_attribute=r.search_attribute,i===cE.SEARCH_TYPES.BETWEEN?(s.search_value=r.search_value[0],s.end_value=r.search_value[1]):s.search_value=r.search_value,lL.searchByType(e,s,i,n).map(o=>o.value)}a(cL,"executeConditionSearch")});var Fu=I((Phe,fL)=>{"use strict";var IJ=H().OPERATIONS_ENUM,eg=class{static{a(this,"DeleteObject")}constructor(t,r,n,s=void 0){this.operation=IJ.DELETE,this.schema=t,this.table=r,this.hash_values=n,this.__origin=s}};fL.exports=eg});var tg=I((Uhe,gL)=>{"use strict";var mL=Gs(),pL=Fu(),SL=ku(),TL=vu(),Kr=H(),_L=re(),EL=ft(),{getTransactionAuditStorePath:wJ,getSchemaPath:CJ}=ht(),hL=X();gL.exports=DJ;async function DJ(e){try{if(_L.isEmpty(global.hdb_schema[e.schema])||_L.isEmpty(global.hdb_schema[e.schema][e.table]))throw new Error(`unknown schema:${e.schema} and table ${e.table}`);await LJ(e),await PJ(e);let t=CJ(e.schema,e.table);try{await EL.deleteEnvironment(t,e.table)}catch(r){if(r.message==="invalid environment")hL.warn(`cannot delete environment for ${e.schema}.${e.table}, environment not found`);else throw r}try{let r=wJ(e.schema,e.table);await EL.deleteEnvironment(r,e.table,!0)}catch(r){if(r.message==="invalid environment")hL.warn(`cannot delete environment for ${e.schema}.${e.table}, environment not found`);else throw r}}catch(t){throw t}}a(DJ,"lmdbDropTable");async function LJ(e){let t=new mL(Kr.SYSTEM_SCHEMA_NAME,Kr.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,Kr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_TABLE_KEY,`${e.schema}.${e.table}`,void 0,[Kr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),r=Array.from(await SL(t)),n=[];for(let i=0;i<r.length;i++){let o=r[i];n.push(o.id)}if(n.length===0)return;let s=new pL(Kr.SYSTEM_SCHEMA_NAME,Kr.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,n);await TL(s)}a(LJ,"deleteAttributesFromSystem");async function PJ(e){let t=new mL(Kr.SYSTEM_SCHEMA_NAME,Kr.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,Kr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY,e.table,void 0,[Kr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY,Kr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_KEY,Kr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),r,n;try{r=Array.from(await SL(t))}catch(i){throw i}for(let i=0;i<r.length;i++){let o=r[i];o.name===e.table&&o.schema===e.schema&&(n=o)}if(!n)throw new Error(`${e.schema}.${e.table} was not found`);let s=new pL(Kr.SYSTEM_SCHEMA_NAME,Kr.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,[n.id]);try{await TL(s)}catch(i){throw i}}a(PJ,"dropTableFromSystem")});var AL=I((xhe,RL)=>{"use strict";var MJ=require("fs-extra"),UJ=Gs(),vJ=yc(),xJ=Fu(),BJ=tg(),HJ=vu(),kJ=KT(),FJ=ku(),Ti=H(),{getSchemaPath:GJ}=ht(),{handleHDBError:qJ,hdb_errors:VJ}=ce(),{HDB_ERROR_MSGS:$J,HTTP_STATUS_CODES:YJ}=VJ;RL.exports=KJ;async function KJ(e){let t;try{t=await WJ(e.schema);let r=new UJ(Ti.SYSTEM_SCHEMA_NAME,Ti.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,Ti.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_KEY,t,void 0,[Ti.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY]),n=Array.from(await FJ(r));for(let o=0;o<n.length;o++){let c={schema:t,table:n[o].name};try{await BJ(c)}catch(l){if(l.message!=="invalid environment")throw l}}let s=new xJ(Ti.SYSTEM_SCHEMA_NAME,Ti.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,[t]);await HJ(s);let i=GJ(t);await MJ.remove(i)}catch(r){throw r}}a(KJ,"lmdbDropSchema");async function WJ(e){let t=new vJ(Ti.SYSTEM_SCHEMA_NAME,Ti.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,[e],[Ti.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY]),r,n;try{r=Array.from(await kJ(t))}catch(s){throw s}for(let[,s]of r)s.name===e&&(n=e);if(!n)throw qJ(new Error,$J.SCHEMA_NOT_FOUND(e),YJ.NOT_FOUND,void 0,void 0,!0);return n}a(WJ,"validateDropSchema")});var ng=I((Hhe,bL)=>{"use strict";var rg=class{static{a(this,"CreateTableObject")}constructor(t,r,n){this.schema=t,this.table=r,this.hash_attribute=n}};bL.exports=rg});var OL=I((Ghe,yL)=>{"use strict";var QJ=require("fs-extra"),lE=ft(),{getTransactionAuditStorePath:zJ}=ht(),sg=Ft(),Fhe=ng();yL.exports=jJ;async function jJ(e){let t;try{let r=zJ(e.schema,e.table);await QJ.mkdirp(r),t=await lE.createEnvironment(r,e.table,!0)}catch(r){throw r.message=`unable to create transactions audit environment for ${e.schema}.${e.table} due to: ${r.message}`,r}try{lE.createDBI(t,sg.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,!1,!0),lE.createDBI(t,sg.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE,!0,!1),lE.createDBI(t,sg.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME,!0,!1)}catch(r){throw r.message=`unable to create dbi for ${e.schema}.${e.table} due to: ${r.message}`,r}return t}a(jJ,"createTransactionsAuditEnvironment")});var wL=I(($he,IL)=>{"use strict";var ig=H(),NL=ft(),JJ=lc(),{getSystemSchemaPath:XJ,getSchemaPath:ZJ}=ht(),Vhe=Yo(),e3=P_(),og=L_(),t3=X(),r3=OL();IL.exports=n3;async function n3(e,t){let r=ZJ(t.schema,t.table),n=new og(t.schema,t.table,ig.TIME_STAMP_NAMES_ENUM.CREATED_TIME,void 0,!0),s=new og(t.schema,t.table,ig.TIME_STAMP_NAMES_ENUM.UPDATED_TIME,void 0,!0),i=new og(t.schema,t.table,t.hash_attribute,void 0,!1,!0);try{if(await NL.createEnvironment(r,t.table),e!==void 0){let o=await NL.openEnvironment(XJ(),ig.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME);await JJ.insertRecords(o,HDB_TABLE_INFO.hash_attribute,hdb_table_attributes,[e]),n.skip_table_check=!0,s.skip_table_check=!0,i.skip_table_check=!0,await ag(n),await ag(s),await ag(i)}await r3(t)}catch(o){throw o}}a(n3,"lmdbCreateTable");async function ag(e){try{await e3(e)}catch(t){t3.warn(`failed to create attribute ${e.attribute} due to ${t.message}`)}}a(ag,"createAttribute")});var DL=I((Khe,CL)=>{"use strict";var s3=Au(),i3=yu(),o3=tE(),Gu=H(),a3=lc().updateRecords,c3=ft(),{getSchemaPath:l3}=ht(),u3=Mu(),d3=X();CL.exports=f3;async function f3(e){try{let{schema_table:t,attributes:r}=s3(e);i3(e,r,t.hash_attribute),e.schema!==Gu.SYSTEM_SCHEMA_NAME&&(r.includes(Gu.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||r.push(Gu.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.includes(Gu.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||r.push(Gu.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let n=await o3(e.hdb_auth_header,t,r),s=l3(e.schema,e.table),i=await c3.openEnvironment(s,e.table),o=await a3(i,t.hash_attribute,r,e.records,e.__origin?.timestamp);try{await u3(e,o)}catch(c){d3.error(`unable to write transaction due to ${c.message}`)}return{written_hashes:o.written_hashes,skipped_hashes:o.skipped_hashes,schema_table:t,new_attributes:n,txn_time:o.txn_time}}catch(t){throw t}}a(f3,"lmdbUpdateRecords")});var PL=I((Qhe,LL)=>{"use strict";var _3=H().OPERATIONS_ENUM,cg=class{static{a(this,"UpsertObject")}constructor(t,r,n,s=void 0){this.operation=_3.UPSERT,this.schema=t,this.table=r,this.records=n,this.__origin=s}};LL.exports=cg});var UL=I((Jhe,ML)=>{"use strict";var jhe=PL(),E3=Au(),h3=yu(),m3=tE(),qu=H(),p3=lc().upsertRecords,S3=ft(),{getSchemaPath:T3}=ht(),g3=Mu(),R3=X(),{handleHDBError:A3,hdb_errors:b3}=ce();ML.exports=y3;async function y3(e){let t;try{t=E3(e)}catch(l){throw A3(l,l.message,b3.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0)}let{schema_table:r,attributes:n}=t;h3(e,n,r.hash_attribute),e.schema!==qu.SYSTEM_SCHEMA_NAME&&(n.includes(qu.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||n.push(qu.TIME_STAMP_NAMES_ENUM.CREATED_TIME),n.includes(qu.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||n.push(qu.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let s=await m3(e.hdb_auth_header,r,n),i=T3(e.schema,e.table),o=await S3.openEnvironment(i,e.table),c=await p3(o,r.hash_attribute,n,e.records,e.__origin?.timestamp);try{await g3(e,c)}catch(l){R3.error(`unable to write transaction due to ${l.message}`)}return{written_hashes:c.written_hashes,schema_table:r,new_attributes:s,txn_time:c.txn_time}}a(y3,"lmdbUpsertRecords")});var xL=I((Zhe,vL)=>{"use strict";var lg=class{static{a(this,"DeleteBeforeObject")}constructor(t,r,n){this.schema=t,this.table=r,this.timestamp=n}};vL.exports=lg});var HL=I((tme,BL)=>{"use strict";var ug=class{static{a(this,"DeleteAuditLogsBeforeResults")}constructor(t=void 0,r=void 0,n=0){this.start_timestamp=t,this.end_timestamp=r,this.transactions_deleted=n}};BL.exports=ug});var GL=I((sme,FL)=>{"use strict";var dg=ft(),{getTransactionAuditStorePath:O3}=ht(),nme=xL(),Vu=Ft(),N3=re(),kL=HL(),I3=require("util").promisify,w3=I3(setTimeout),C3=1e4,D3=100;FL.exports=L3;async function L3(e){let t=O3(e.schema,e.table),r=await dg.openEnvironment(t,e.table,!0),n=dg.listDBIs(r);dg.initializeDBIs(r,Vu.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,n);let s,i=new kL;do s=await P3(r,e.timestamp),i.start_timestamp===void 0&&(i.start_timestamp=s.start_timestamp),s.end_timestamp!==void 0&&(i.end_timestamp=s.end_timestamp),i.transactions_deleted+=s.transactions_deleted,await w3(D3);while(s.transactions_deleted>0);return i}a(L3,"deleteAuditLogsBefore");async function P3(e,t){let r=new kL;try{let n=e.dbis[Vu.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP],s;for(let{key:i,value:o}of n.getRange({start:!1})){if(i>=t)break;r.start_timestamp===void 0&&(r.start_timestamp=i),s=n.remove(i);let c=o[Vu.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME];N3.isEmpty(c)||(s=e.dbis[Vu.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].remove(c,i));for(let l=0;l<o.hash_values.length;l++)s=e.dbis[Vu.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE].remove(o.hash_values[l],i);if(r.transactions_deleted++,r.end_timestamp=i,r.transactions_deleted>C3)break}return await s,r}catch(n){throw n}}a(P3,"deleteTransactions")});var VL=I((ome,qL)=>{"use strict";var fg=class{static{a(this,"DropAttributeObject")}constructor(t,r,n){this.schema=t,this.table=r,this.attribute=n}};qL.exports=fg});var YL=I((lme,$L)=>{"use strict";var M3=Gs(),U3=Fu(),cme=VL(),qs=H(),v3=re(),_g=ft(),x3=Yo(),B3=ku(),H3=vu(),{getSchemaPath:k3}=ht();$L.exports=F3;async function F3(e,t=!0){let r;e.schema===qs.SYSTEM_SCHEMA_NAME?r=x3[e.table]:r=global.hdb_schema[e.schema][e.table];let n=await q3(e),s=k3(e.schema,e.table),i=await _g.openEnvironment(s,e.table);return t===!0&&await G3(e,i,r.hash_attribute),_g.dropDBI(i,e.attribute),n}a(F3,"lmdbDropAttribute");async function G3(e,t,r){let n=_g.openDBI(t,r),s,i=e.attribute;for(let{key:o,value:c,version:l}of n.getRange({start:!1,versions:!0})){let d={};for(let u in c)u!==i&&(d[u]=c[u]);s=t.dbis[r].put(o,d,l)}await s}a(G3,"removeAttributeFromAllObjects");async function q3(e){let t=new M3(qs.SYSTEM_SCHEMA_NAME,qs.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,qs.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_TABLE_KEY,`${e.schema}.${e.table}`,void 0,[qs.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY,qs.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ATTRIBUTE_KEY]),n=Array.from(await B3(t)).filter(o=>o[qs.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ATTRIBUTE_KEY]===e.attribute);if(v3.isEmptyOrZeroLength(n))throw new Error(`Attribute '${e.attribute}' was not found in '${e.schema}.${e.table}'`);let s=n.map(o=>o[qs.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),i=new U3(qs.SYSTEM_SCHEMA_NAME,qs.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,s);return H3(i)}a(q3,"dropAttributeFromSystem")});var JL=I((fme,jL)=>{"use strict";var Eg=ft(),Oc=Ft(),dme=hn(),hg=H(),KL=re(),{getTransactionAuditStorePath:V3}=ht(),$3=Ac(),uE=Tc(),Y3=X();jL.exports=K3;async function K3(e){let t=V3(e.schema,e.table),r=await Eg.openEnvironment(t,e.table,!0),n=Eg.listDBIs(r);Eg.initializeDBIs(r,Oc.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,n);let s;switch(e.search_type){case hg.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.TIMESTAMP:return WL(r,e.search_values);case hg.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.HASH_VALUE:return s=global.hdb_schema[e.schema][e.table].hash_attribute,Q3(r,e.search_values,s);case hg.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.USERNAME:return W3(r,e.search_values);default:return WL(r)}}a(K3,"readAuditLog");function WL(e,t=[0,Date.now()]){KL.isEmpty(t[0])&&(t[0]=0),KL.isEmpty(t[1])&&(t[1]=Date.now());let r=e.dbis[Oc.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP],n;for(let s of r.getKeys({start:t[1]}))if(s!==t[1]){n=s;break}return r.getRange({start:t[0],end:n}).map(({value:s})=>Object.assign(new uE,s))}a(WL,"searchTransactionsByTimestamp");function W3(e,t=[]){let r=new Map;for(let n=0;n<t.length;n++){let s=t[n],i=[];for(let o of e.dbis[Oc.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].getValues(s))i.push(o);r.set(s,zL(e,i))}return Object.fromEntries(r)}a(W3,"searchTransactionsByUsername");function Q3(e,t,r){let n=new Map;for(let c=0,l=t.length;c<l;c++){let d=t[c],u=$3.equals(e,Oc.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,Oc.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE,d);for(let{value:f}of u){let E=Number(f);n.has(E)?n.get(E).push(d.toString()):n.set(E,[d.toString()])}}let s=Array.from(n.keys()),i=zL(e,s),o=new Map;for(let c=0;c<i.length;c++){let l=i[c],d=l.timestamp,u=n.get(d);QL(l,"records",r,u,o),QL(l,"original_records",r,u,o)}return Object.fromEntries(o)}a(Q3,"searchTransactionsByHashValues");function QL(e,t,r,n,s){let i=e.timestamp;if(e[t])for(let o=0;o<e[t].length;o++){let c=e[t][o],l=c[r].toString();if(n.indexOf(l)>=0)if(s.has(l)){let d=s.get(l),u=d[d.length-1];if(u.timestamp===i)u[t]=[c];else{let f=new uE(e.operation,e.user_name,i,void 0);f[t]=[c],d.push(f)}}else{let d=new uE(e.operation,e.user_name,i,void 0);d[t]=[c],s.set(l,[d])}}}a(QL,"loopRecords");function zL(e,t){let r=[];try{let n=e.dbis[Oc.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP];for(let s=0;s<t.length;s++)try{let i=n.get(t[s]);if(i){let o=Object.assign(new uE,i);r.push(o)}}catch(i){Y3.warn(i)}return r}catch(n){throw n}}a(zL,"batchSearchTransactions")});var ZL=I((mme,XL)=>{"use strict";var{getSchemaPath:Eme}=ht(),hme=ft(),{database:z3}=(Ne(),ae(it));XL.exports={writeTransaction:j3};async function j3(e,t,r){return z3({database:e,table:t}).transaction(r)}a(j3,"writeTransaction")});var nP=I((Sme,rP)=>{"use strict";var{getSchemaPath:eP}=ht(),tP=ft();rP.exports={flush:J3,resetReadTxn:X3};async function J3(e,t){return(await tP.openEnvironment(eP(e,t),t.toString())).flushed}a(J3,"flush");async function X3(e,t){try{(await tP.openEnvironment(eP(e,t),t.toString())).resetReadTxn()}catch{}}a(X3,"resetReadTxn")});var aP=I((gme,oP)=>{"use strict";var{Readable:Z3}=require("stream"),{getDatabases:eX}=(Ne(),ae(it)),{readSync:tX,openSync:rX,createReadStream:sP}=require("fs"),{open:nX}=require("lmdb"),iP=hu(),sX=mu(),{AUDIT_STORE_OPTIONS:iX}=(_i(),ae(cP)),{INTERNAL_DBIS_NAME:oX,AUDIT_STORE_NAME:aX}=Ft();oP.exports=lX;var mg=32768,cX=100;async function lX(e){let t=e.database||e.schema||"data",r=eX()[t],n=new Date().toISOString(),s=e.tables||e.table&&[e.table];if(s){let d=r[s[0]];if(!d)throw new Error(`Can not find table ${s[0]}`);let u=d.dbisDB,f=nX({noSync:!0,maxDbs:sX.MAX_DBS}),E,_=f.openDB(oX,new iP(!1)),h=u.useReadTransaction(),p=0,S=a(async function(T,A){A.encoding="binary",A.encoder=void 0;let N=f.openDB(T,A),V=u.openDB(T,A);for(let{key:v,version:J,value:$}of V.getRange({start:null,transaction:h,versions:V.useVersions}))E=N.put(v,$,J),p++%cX===0&&(await new Promise(F=>setTimeout(F,20)),h.openTimer&&(h.openTimer=0))},"copyDatabase");for(let{key:T,value:A}of u.getRange({transaction:h,start:!1}))if(s.some(N=>T.startsWith?.(N+"/"))){_.put(T,A);let[,N]=T.split("/"),V=!N,v=new iP(!V,V);await S(T,v)}e.include_audit&&await S(aX,Object.assign({},iX)),await E;let g=sP(f.path);return g.headers=l(),g.on("close",()=>{h.done(),f.close()}),g}let o=r[Object.keys(r)[0]].primaryStore,c=rX(o.path);return o.transaction(()=>{let d=Buffer.alloc(mg);tX(c,d,0,mg),o.resetReadTxn();let u=o.useReadTransaction();u.renew();let f=sP(null,{fd:c,start:mg}),E=new Z3.from(async function*(){yield d;for await(let _ of f)u.openTimer&&(u.openTimer=0),yield _;u.done()}());return E.headers=l(),E});function l(){let d=new Map;return d.set("content-type","application/octet-stream"),d.set("content-disposition",`attachment; filename="${t}"`),d.set("date",n),d}}a(lX,"getBackup")});var dP=I((Ame,uP)=>{"use strict";var uX=X(),{handleHDBError:dX}=ce(),fX=yI(),_X=P_(),EX=kT(),hX=AD(),mX=vu(),pX=KT(),SX=QD(),TX=nL(),gX=ku(),RX=dL(),AX=AL(),bX=wL(),yX=DL(),OX=UL(),NX=GL(),IX=tg(),wX=YL(),CX=JL(),DX=ZL(),lP=nP(),LX=aP(),pg=class extends fX{static{a(this,"LMDBBridge")}async searchByConditions(t){return RX(t)}async getDataByHash(t){return await pX(t)}async searchByHash(t){return await SX(t)}async getDataByValue(t,r){return await TX(t,r)}async searchByValue(t){return await gX(t)}async createSchema(t){return await hX(t)}async dropSchema(t){return await AX(t)}async createTable(t,r){return await bX(t,r)}async dropTable(t){return await IX(t)}async createAttribute(t){return await _X(t)}async createRecords(t){return await EX(t)}async updateRecords(t){return await yX(t)}async upsertRecords(t){try{return await OX(t)}catch(r){throw dX(r,null,null,uX.ERR,r)}}async deleteRecords(t){return await mX(t)}async dropAttribute(t){return await wX(t)}async deleteAuditLogsBefore(t){return await NX(t)}async readAuditLog(t){return await CX(t)}writeTransaction(t,r,n){return DX.writeTransaction(t,r,n)}flush(t,r){return lP.flush(t,r)}resetReadTxn(t,r){return lP.resetReadTxn(t,r)}getBackup(t){return LX(t)}};uP.exports=pg});function TP(e){Tg=e}function vX(){UX=setInterval(function(){for(let e of Sg)if(e.stale){let t=e[Me]?.url;hP.error(`Transaction was open too long and has been aborted, from table: ${e.lmdbDb?.name+(t?" path: "+t:"")}`),e.abort()}else e.stale=!0},MX).unref()}var gg,EP,hP,mP,pP,SP,fP,Sg,PX,$u,_P,Tg,ia,dE,MX,UX,fE=Oe(()=>{gg=U(hn()),EP=U(ce()),hP=U(X());ls();mP=U(ie()),pP=U(H()),SP=U(re()),fP=100,Sg=new Set,PX=(0,SP.convertToMS)(mP.get(pP.CONFIG_PARAMS.STORAGE_MAXTRANSACTIONQUEUETIME))||45e3;a(TP,"replicationConfirmation");ia=class e{static{a(this,"DatabaseTransaction")}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.readTxnsUsed=1,this.readTxn=this.lmdbDb.useReadTransaction(),this.readTxn.openTimer&&(this.readTxn.openTimer=0),Sg.add(this),this.readTxn}useReadTxn(){return this.getReadTxn(),this.readTxn.use(),this.readTxnsUsed++,this.readTxn}doneReadTxn(){this.readTxn&&(this.readTxn.done(),--this.readTxnsUsed===0&&(Sg.delete(this),this.readTxn=null))}disregardReadTxn(){--this.readTxnRefCount===0&&this.readTxnsUsed===1&&this.doneReadTxn()}checkOverloaded(){if($u&&!this.overloadChecked&&performance.now()-_P>PX)throw new EP.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=t.timestamp||(0,gg.getNextMonotonicTime)());let n=t.retries||0;if(this.validated<this.writes.length)try{let f=this.validated;this.validated=this.writes.length;for(let _=f;_<this.validated;_++)this.writes[_]?.validate?.(this.timestamp);let E;for(let _=f;_<this.validated;_++){let h=this.writes[_];h&&(h.before||h.beforeIntermediate)&&(E=!0)}if(E)return(async()=>{try{for(let _=0;_<2;_++){let h;for(let p=f;p<this.validated;p++){let S=this.writes[p];if(!S)continue;let g=S[_===0?"before":"beforeIntermediate"];if(g){let T=g();h?h.push?h.push(T):h=[h,T]:h=T}}h&&await(h.push?Promise.all(h):h)}}catch(_){throw this.abort(),_}return this.commit(t)})()}catch(f){throw this.abort(),f}n||this.doneReadTxn(),this.open=t?.letItLinger?2:0;let s,i=[],o=0;this.writes=this.writes.filter(f=>f);let c=a(f=>{f.commit(r,f.entry,n)},"doWrite"),l=a(()=>{let f=this.writes[o++];if(f)if(f.key){n>0&&(f.entry=f.store.getEntry(f.key));let E=f.store.ifVersion(f.key,f.entry?.version??null,l);s=s||E}else l();else for(let E of this.writes)c(E)},"nextCondition"),d=this.lmdbDb;if(this.writes.length>0&&(d?.retryRisk&&(d.retryRisk*=.99),this.writes.length+(d?.retryRisk||0)<fP>>n?l():s=this.writes[0].store.transaction(()=>{for(let f of this.writes)f.entry=f.store.getEntry(f.key),c(f);return!0})),s)return $u||($u=s,_P=performance.now(),$u.then(()=>{$u=null})),s.then(f=>{if(f){if(this.next&&i.push(this.next.commit(t)),t?.flush&&i.push(this.writes[0].store.flushed),this.replicatedConfirmation){let E=this.writes[0].store.rootStore.databaseName,_=this.writes[this.writes.length-1];Tg&&_&&i.push(Tg(E,_.store.getEntry(_.key).localTime,this.replicatedConfirmation))}return this.writes=[],this.next=null,Promise.all(i).then(()=>({txnTime:r}))}else return d&&(d.retryRisk=(d.retryRisk||0)+fP/2),t?t.retries=n+1:t={retries:1},this.commit(t)});let u={txnTime:r};if(this.next){let f=this.next?.commit(t);if(f?.then)return f?.then(E=>({txnTime:r,next:E}));u.next=f}return u}abort(){for(;this.readTxnsUsed>0;)this.doneReadTxn();this.open=0,this.writes=[]}},dE=class extends ia{static{a(this,"ImmediateTransaction")}_timestamp;addWrite(t){super.addWrite(t),this.commit()}get timestamp(){return this._timestamp||(this._timestamp=(0,gg.getNextMonotonicTime)())}getReadTxn(){}},MX=3e4;a(vX,"startMonitoringTxns");vX()});function Tt(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 ia;e.timestamp&&(n.timestamp=e.timestamp),e.replicatedConfirmation&&(n.replicatedConfirmation=e.replicatedConfirmation),n[Me]=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({letItLinger:r?.letItLinger});return l.then?l.then(()=>c):c}function o(c){throw n.abort({}),c}}var gP,oa=Oe(()=>{gP=require("../index");ls();fE();a(Tt,"transaction");(0,gP._assignPackageExport)("transaction",Tt);Tt.commit=function(e){let t=(e[Me]||e)?.transaction;if(!t)throw new Error("No active transaction is available to commit");return t.commit()};Tt.abort=function(e){let t=(e[Me]||e)?.transaction;if(!t)throw new Error("No active transaction is available to abort");return t.abort()}});var CP={};Ze(CP,{ResourceBridge:()=>bg});function yg({get_attributes:e},t){if(e){if(e[0]==="*"){if(t.schemaDefined)return;e=t.attributes.map(r=>r.name)}return e.forceNulls=!0,e}}function AP(e,t){let r=Vs(e),n=yg(e,r);if(!r)throw new hs.ClientError(`Table ${e.table} not found`);let s;n&&r.attributes.length-n.length>2&&n.length<5&&(s=!0);let i={user:e.hdb_user},o;Tt(i,()=>new Promise(d=>o=d));let c=e.ids||e.hash_values,l=0;return{[Symbol.asyncIterator](){return{async next(){if(l<c.length){let d=c[l++],u=await r.get({id:d,lazy:s,select:n},i);return u=u&&EE(u),t?{value:{key:d,value:u}}:{value:u}}else return o(),{done:!0}},return(d){return o(),{value:d,done:!0}},throw(d){return o(),{done:!0}}}}}}function Vs(e){let t=e.database||e.schema||BX,r=ct()[t];if(!r)throw(0,hs.handleHDBError)(new Error,xX.SCHEMA_NOT_FOUND(t),404);return r[e.table]}function bP(e,t,r){let n=e.length+t.length,s=n===1?"record":"records";return{message:`${e.length} of ${n} ${s} successfully deleted`,deleted_hashes:e,skipped_hashes:t,txn_time:r}}async function*yP(e,t,r,n){let s,i=0;for await(let o of e.getHistory(t,r)){let c=o.operation??o.type;c==="put"&&(c="upsert");let{id:l,version:d,value:u}=o;if(s?.timestamp===d)s.hash_values.push(l),s.records.push(u);else{if(s&&(yield s,i++,n&&n<=i)){s=void 0;break}s={operation:c,user_name:o.user,timestamp:d,hash_values:[l],records:[u]}}}s&&(yield s)}var OP,_E,hs,NP,IP,ms,Rg,Ag,wP,xX,BX,HX,kX,RP,bg,DP=Oe(()=>{"use strict";OP=U(dP()),_E=U(bc()),hs=U(ce());Ne();NP=U(Au()),IP=U(yu()),ms=U(H()),Rg=U(pi()),Ag=U(Es()),wP=U(re());oa();hE();({HDB_ERROR_MSGS:xX}=hs.hdb_errors),BX="data",HX=1e4,kX=10,bg=class extends OP.default{static{a(this,"ResourceBridge")}constructor(t){super(t),RP=this}async searchByConditions(t){t.select!==void 0&&(t.get_attributes=t.select);for(let o of t.conditions||[])o?.attribute!==void 0&&(o.search_attribute=o.attribute),o?.comparator!==void 0&&(o.search_type=o.comparator),o?.value!==void 0&&(o.search_value=o.value);let r=(0,_E.default)(t,"conditions");if(r)throw(0,hs.handleHDBError)(r,r.message,400,void 0,void 0,!0);let n=Vs(t);if(!n)throw new hs.ClientError(`Table ${t.table} not found`);let s=t.conditions.map(i);function i(o){return o.conditions?(o.conditions=o.conditions.map(i),o):{attribute:o.search_attribute??o.attribute,comparator:o.search_type??o.comparator,value:o.search_value!==void 0?o.search_value:o.value}}return a(i,"mapCondition"),n.search({conditions:s,operator:t.operator?t.operator.toLowerCase():void 0,limit:t.limit,offset:t.offset,reverse:t.reverse,select:yg(t,n),sort:t.sort,allowFullScan:!0})}async createTable(t,r){let n=r.attributes,s=!!n,i=r.primary_key||r.hash_attribute;if(n)for(let o of n)o.is_primary_key?(o.isPrimaryKey=!0,delete o.is_primary_key):o.name===i&&i&&(o.isPrimaryKey=!0);else{if(!i)throw new hs.ClientError("A primary key must be specified with a `primary_key` property or with `attributes`");n=[{name:i,isPrimaryKey:!0},{name:"__createdtime__",indexed:!0},{name:"__updatedtime__",indexed:!0}]}dt({database:r.database??r.schema,table:r.table,attributes:n,schemaDefined:s,expiration:r.expiration})}async createAttribute(t){return await Vs(t).addAttributes([{name:t.attribute,indexed:t.indexed??!0}]),`attribute ${t.schema}.${t.table}.${t.attribute} successfully created.`}async dropAttribute(t){let r=Vs(t);if(await r.removeAttributes([t.attribute]),!r.schemaDefined){let n=t.attribute,s,i=a((o,c,l)=>(c=Object.assign({},c),delete c[n],r.primaryStore.ifVersion(o,l,()=>r.primaryStore.put(o,c,l)).then(d=>{if(!d){let{value:u,version:f}=r.primaryStore.getEntry(o);return i(o,u,f)}})),"deleteRecord");for(let{key:o,value:c,version:l}of r.primaryStore.getRange({start:!0,versions:!0}))s=i(o,c,l),await new Promise(d=>setImmediate(d));await s}return`successfully deleted ${t.schema}.${t.table}.${t.attribute}`}dropTable(t){Vs(t).dropTable()}createSchema(t){return Nc({database:t.schema,table:null}),Rg.signalSchemaChange(new Ag.SchemaEventMsg(process.pid,ms.OPERATIONS_ENUM.CREATE_SCHEMA,t.schema))}async dropSchema(t){await Og(t.schema),Rg.signalSchemaChange(new Ag.SchemaEventMsg(process.pid,ms.OPERATIONS_ENUM.DROP_SCHEMA,t.schema))}async updateRecords(t){return t.requires_existing=!0,this.upsertRecords(t)}async createRecords(t){return t.requires_no_existing=!0,RP.upsertRecords(t)}async upsertRecords(t){let{schema_table:r,attributes:n}=(0,NP.default)(t);(0,IP.default)(t,n,r.primaryKey);let s,i=ct()[t.schema][t.table],o={user:t.hdb_user,expiresAt:t.expiresAt,originatingOperation:t.operation};return t.replicateTo&&(o.replicateTo=t.replicateTo),t.replicatedConfirmation&&(o.replicatedConfirmation=t.replicatedConfirmation),Tt(o,async c=>{if(!i.schemaDefined){s=[];for(let u of n)i.attributes.find(E=>E.name==u)||s.push(u);s.length>0&&await i.addAttributes(s.map(u=>({name:u,indexed:!0})))}let l=[],d=[];for(let u of t.records){let f=await i.get(u[i.primaryKey],o);if(t.requires_existing&&!f||t.requires_no_existing&&f){d.push(u[i.primaryKey]);continue}f&&(f=EE(f));for(let E in u)if(Object.prototype.hasOwnProperty.call(u,E)){let _=u[E];if(typeof _=="function")try{let h=_([[f]]);Array.isArray(h)&&(_=h[0].func_val,u[E]=_)}catch(h){throw h.message+="Trying to set key "+E+" on object"+JSON.stringify(u),h}}if(f)for(let E in f)Object.prototype.hasOwnProperty.call(u,E)||(u[E]=f[E]);await i.put(u,o),l.push(u[i.primaryKey])}return{txn_time:c.timestamp,written_hashes:l,new_attributes:s,skipped_hashes:d}})}async deleteRecords(t){let r=ct()[t.schema][t.table],n={user:t.hdb_user};return t.replicateTo&&(n.replicateTo=t.replicateTo),t.replicatedConfirmation&&(n.replicatedConfirmation=t.replicatedConfirmation),Tt(n,async s=>{let i=t.hash_values||t.records.map(l=>l[r.primaryKey]),o=[],c=[];for(let l of i)await r.delete(l,n)?o.push(l):c.push(l);return bP(o,c,s.timestamp)})}async deleteRecordsBefore(t){let r=ct()[t.schema][t.table];if(!r.createdTimeProperty)throw new hs.ClientError("Table must have a '__createdtime__' attribute or @createdTime timestamp defined to perform this operation");let n=await r.search({conditions:[{attribute:r.createdTimeProperty.name,value:Date.parse(t.date),comparator:ms.VALUE_SEARCH_COMPARATORS.LESS}]}),s=!1,i=[],o=[],c=0,l=[],d=a(async()=>{let u=await this.deleteRecords({schema:t.schema,table:t.table,hash_values:l});i.push(...u.deleted_hashes),o.push(...u.skipped_hashes),await(0,wP.async_set_timeout)(kX),l=[],s=!0},"chunkDelete");for await(let u of n)l.push(u[r.primaryKey]),c++,c%HX===0&&await d();return l.length>0&&await d(),s?bP(i,o,void 0):{message:"No records found to delete"}}searchByHash(t){t.select!==void 0&&(t.get_attributes=t.select);let r=(0,_E.default)(t,"hashes");if(r)throw r;return AP(t)}async getDataByHash(t){let r=new Map;t._returnKeyValue=!0;for await(let{key:n,value:s}of AP(t,!0))r.set(n,s);return r}searchByValue(t,r){if(r&&ms.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[r]===void 0)throw new Error(`Value search comparator - ${r} - is not valid`);t.select!==void 0&&(t.get_attributes=t.select),t.attribute!==void 0&&(t.search_attribute=condition.attribute),t.value!==void 0&&(t.search_value=condition.value);let n=(0,_E.default)(t,"value");if(n)throw n;let s=Vs(t);if(!s)throw new hs.ClientError(`Table ${t.table} not found`);let i=t.search_value;i.includes?.("*")&&(i.startsWith("*")?i.endsWith("*")?i!=="*"&&(r="contains",i=i.slice(1,-1)):(r="ends_with",i=i.slice(1)):i.endsWith("*")&&(r="starts_with",i=i.slice(0,-1))),r===ms.VALUE_SEARCH_COMPARATORS.BETWEEN&&(i=[i,t.end_value]);let o=i==="*"?[]:[{attribute:t.search_attribute,value:i,comparator:r}];return s.search({conditions:o,allowFullScan:!0,limit:t.limit,offset:t.offset,reverse:t.reverse,select:yg(t,s)})}async getDataByValue(t,r){let n=new Map,s=Vs(t);t.get_attributes&&!t.get_attributes.includes(s.primaryKey)&&t.get_attributes[0]!=="*"&&t.get_attributes.push(s.primaryKey);for await(let i of this.searchByValue(t,r))n.set(i[s.primaryKey],i);return n}resetReadTxn(t,r){Vs({schema:t,table:r})?.primaryStore.resetReadTxn()}async deleteAuditLogsBefore(t){return Vs(t).deleteHistory(t.timestamp)}async readAuditLog(t){let r=Vs(t),n={};switch(t.search_type){case ms.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.HASH_VALUE:for(let i of t.search_values)n[i]=(await r.getHistoryOfRecord(i)).map(o=>{let c=o.operation??o.type;return c==="put"&&(c="upsert"),{operation:c,timestamp:o.version,user_name:o.user,hash_values:[i],records:[o.value]}});return n;case ms.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.USERNAME:let s=t.search_values;for await(let i of yP(r))s.includes(i.user_name)&&(n[i.user_name]||(n[i.user_name]=[])).push(i);return n;default:return yP(r,t.search_values?.[0],t.search_values?.[1],t.limit)}}};a(yg,"getSelect");a(AP,"getRecords");a(Vs,"getTable");a(bP,"createDeleteResponse");a(yP,"groupRecordsInHistory")});var Vn=I((Bme,LP)=>{"use strict";var{ResourceBridge:FX}=(DP(),ae(CP)),GX=ie();GX.initSync();var mE;function qX(){return mE||(mE=new FX,mE)}a(qX,"getBridge");LP.exports=qX()});var vP=I((kme,UP)=>{"use strict";var PP=require("lodash"),Yu=require("mathjs"),VX=require("jsonata"),MP=re();UP.exports={distinct_array:e=>Array.isArray(e)&&e.length>1?PP.uniqWith(e,PP.isEqual):e,searchJSON:$X,mad:Ku.bind(null,Yu.mad),mean:Ku.bind(null,Yu.mean),mode:Ku.bind(null,Yu.mode),prod:Ku.bind(null,Yu.prod),median:Ku.bind(null,Yu.median)};function Ku(e,t,r,n){return n===1?t==null?[]:[t]:n===2?(t!=null&&r.push(t),r):r!=null&&r.length>0?e(r):null}a(Ku,"aggregateFunction");function $X(e,t){if(typeof e!="string"||e.length===0)throw new Error("search json expression must be a non-empty string");let r="__"+e+"__";if(MP.isEmpty(this.__ala__.res)&&(this.__ala__.res={}),MP.isEmpty(this.__ala__.res[r])){let n=VX(e);this.__ala__.res[r]=n}return this.__ala__.res[r].evaluate(t)}a($X,"searchJSON")});var BP=I((Gme,xP)=>{"use strict";var zt=require("moment"),Ng="YYYY-MM-DDTHH:mm:ss.SSSZZ";zt.suppressDeprecationWarnings=!0;xP.exports={current_date:()=>zt().utc().format("YYYY-MM-DD"),current_time:()=>zt().utc().format("HH:mm:ss.SSS"),extract:(e,t)=>{switch(t.toLowerCase()){case"year":return zt(e).utc().format("YYYY");case"month":return zt(e).utc().format("MM");case"day":return zt(e).utc().format("DD");case"hour":return zt(e).utc().format("HH");case"minute":return zt(e).utc().format("mm");case"second":return zt(e).utc().format("ss");case"millisecond":return zt(e).utc().format("SSS");default:break}},date:e=>zt(e).utc().format(Ng),date_format:(e,t)=>zt(e).utc().format(t),date_add:(e,t,r)=>zt(e).utc().add(t,r).valueOf(),date_sub:(e,t,r)=>zt(e).utc().subtract(t,r).valueOf(),date_diff:(e,t,r)=>{let n=zt(e).utc(),s=zt(t).utc();return r?n.diff(s,r,!0):n.diff(s)},now:()=>zt().utc().valueOf(),get_server_time:()=>zt().format(Ng),offset_utc:(e,t)=>zt(e).utc().utcOffset(t).format(Ng)}});var GP=I((qme,FP)=>{"use strict";var YX=require("@turf/area"),KX=require("@turf/length"),WX=require("@turf/circle"),QX=require("@turf/difference"),zX=require("@turf/distance"),jX=require("@turf/boolean-contains"),JX=require("@turf/boolean-equal"),XX=require("@turf/boolean-disjoint"),ZX=require("@turf/helpers"),HP=H(),Be=re(),gi=X();FP.exports={geoArea:eZ,geoLength:tZ,geoCircle:rZ,geoDifference:nZ,geoDistance:kP,geoNear:sZ,geoContains:iZ,geoEqual:oZ,geoCrosses:aZ,geoConvert:cZ};function eZ(e){if(Be.isEmpty(e))return NaN;typeof e=="string"&&(e=Be.autoCastJSON(e));try{return YX.default(e)}catch(t){return gi.trace(t,e),NaN}}a(eZ,"geoArea");function tZ(e,t){if(Be.isEmpty(e))return NaN;typeof e=="string"&&(e=Be.autoCastJSON(e));try{return KX.default(e,{units:t||"kilometers"})}catch(r){return gi.trace(r,e),NaN}}a(tZ,"geoLength");function rZ(e,t,r){if(Be.isEmpty(e))return NaN;if(Be.isEmpty(t))return NaN;typeof e=="string"&&(e=Be.autoCastJSON(e));try{return WX.default(e,t,{units:r||"kilometers"})}catch(n){return gi.trace(n,e,t),NaN}}a(rZ,"geoCircle");function nZ(e,t){if(Be.isEmpty(e))return NaN;if(Be.isEmpty(t))return NaN;typeof e=="string"&&(e=Be.autoCastJSON(e)),typeof t=="string"&&(t=Be.autoCastJSON(t));try{return QX(e,t)}catch(r){return gi.trace(r,e,t),NaN}}a(nZ,"geoDifference");function kP(e,t,r){if(Be.isEmpty(e))return NaN;if(Be.isEmpty(t))return NaN;typeof e=="string"&&(e=Be.autoCastJSON(e)),typeof t=="string"&&(t=Be.autoCastJSON(t));try{return zX.default(e,t,{units:r||"kilometers"})}catch(n){return gi.trace(n,e,t),NaN}}a(kP,"geoDistance");function sZ(e,t,r,n){if(Be.isEmpty(e)||Be.isEmpty(t))return!1;if(Be.isEmpty(r))throw new Error("distance is required");if(typeof e=="string"&&(e=Be.autoCastJSON(e)),typeof t=="string"&&(t=Be.autoCastJSON(t)),isNaN(r))throw new Error("distance must be a number");try{return kP(e,t,n)<=r}catch(s){return gi.trace(s,e,t),!1}}a(sZ,"geoNear");function iZ(e,t){if(Be.isEmpty(e)||Be.isEmpty(t)||e.coordinates&&e.coordinates.includes?.(null)||t.coordinates&&t.coordinates.includes?.(null))return!1;typeof e=="string"&&(e=Be.autoCastJSON(e)),typeof t=="string"&&(t=Be.autoCastJSON(t));try{return jX.default(e,t)}catch(r){return gi.trace(r,e,t),!1}}a(iZ,"geoContains");function oZ(e,t){if(Be.isEmpty(e)||Be.isEmpty(t)||e.coordinates&&e.coordinates.includes?.(null)||t.coordinates&&t.coordinates.includes?.(null))return!1;typeof e=="string"&&(e=Be.autoCastJSON(e)),typeof t=="string"&&(t=Be.autoCastJSON(t));try{return JX.default(e,t)}catch(r){return gi.trace(r,e,t),!1}}a(oZ,"geoEqual");function aZ(e,t){if(Be.isEmpty(e)||Be.isEmpty(t)||e.coordinates&&e.coordinates.includes?.(null)||t.coordinates&&t.coordinates.includes?.(null))return!1;typeof e=="string"&&(e=Be.autoCastJSON(e)),typeof t=="string"&&(t=Be.autoCastJSON(t));try{return!XX.default(e,t)}catch(r){return gi.trace(r,e,t),!1}}a(aZ,"geoCrosses");function cZ(e,t,r){if(Be.isEmptyOrZeroLength(e))throw new Error("coordinates is required");if(Be.isEmpty(t))throw new Error("geo_type is required");if(Be.isEmpty(HP.GEO_CONVERSION_ENUM[t]))throw new Error(`geo_type of ${t} is invalid please use one of the following types: ${Object.keys(HP.GEO_CONVERSION_ENUM).join(",")}`);return typeof e=="string"&&(e=Be.autoCastJSON(e)),ZX[t](e,r)}a(cZ,"geoConvert")});var pE=I(($me,qP)=>{var aa=vP(),Nn=BP(),$s=GP();qP.exports=e=>{e.aggr.mad=e.aggr.MAD=aa.mad,e.aggr.mean=e.aggr.MEAN=aa.mean,e.aggr.mode=e.aggr.MODE=aa.mode,e.aggr.prod=e.aggr.PROD=aa.prod,e.aggr.median=e.aggr.MEDIAN=aa.median,e.fn.distinct_array=e.fn.DISTINCT_ARRAY=aa.distinct_array,e.fn.search_json=e.fn.SEARCH_JSON=aa.searchJSON,e.fn.__ala__=e,e.fn.current_date=e.fn.CURRENT_DATE=Nn.current_date,e.fn.current_time=e.fn.CURRENT_TIME=Nn.current_time,e.fn.extract=e.fn.EXTRACT=Nn.extract,e.fn.date=e.fn.DATE=Nn.date,e.fn.date_format=e.fn.DATE_FORMAT=Nn.date_format,e.fn.date_add=e.fn.DATE_ADD=Nn.date_add,e.fn.date_sub=e.fn.DATE_SUB=Nn.date_sub,e.fn.date_diff=e.fn.DATE_DIFF=e.fn.datediff=e.fn.DATEDIFF=Nn.date_diff,e.fn.now=e.fn.NOW=Nn.now,e.fn.offset_utc=e.fn.OFFSET_UTC=Nn.offset_utc,e.fn.get_server_time=e.fn.GET_SERVER_TIME=Nn.get_server_time,e.fn.getdate=e.fn.GETDATE=Nn.now,e.fn.current_timestamp=e.fn.CURRENT_TIMESTAMP=Nn.now,e.fn.geoarea=e.fn.GEOAREA=e.fn.geoArea=$s.geoArea,e.fn.geocircle=e.fn.GEOCIRCLE=e.fn.geoCircle=$s.geoCircle,e.fn.geocontains=e.fn.GEOCONTAINS=e.fn.geoContains=$s.geoContains,e.fn.geoconvert=e.fn.GEOCONVERT=e.fn.geoConvert=$s.geoConvert,e.fn.geocrosses=e.fn.GEOCROSSES=e.fn.geoCrosses=$s.geoCrosses,e.fn.geodifference=e.fn.GEODIFFERENCE=e.fn.geoDifference=$s.geoDifference,e.fn.geodistance=e.fn.GEODISTANCE=e.fn.geoDistance=$s.geoDistance,e.fn.geoequal=e.fn.GEOEQUAL=e.fn.geoEqual=$s.geoEqual,e.fn.geolength=e.fn.GEOLENGTH=e.fn.geoLength=$s.geoLength,e.fn.geonear=e.fn.GEONEAR=e.fn.geoNear=$s.geoNear}});var KP=I((Yme,YP)=>{"use strict";var Wu=require("lodash"),Wr=require("alasql");Wr.options.cache=!1;var lZ=pE(),VP=require("clone"),SE=require("recursive-iterator"),we=X(),Qe=re(),Ic=Vn(),uZ=H(),{hdb_errors:dZ}=ce(),{getDatabases:$P}=(Ne(),ae(it)),fZ="IS NULL",ps="There was a problem performing this search. Please check the logs and try again.";lZ(Wr);var Ig=class{static{a(this,"SQLSearch")}constructor(t,r){if(Qe.isEmpty(t))throw we.error("AST statement for SQL select process cannot be empty"),"statement cannot be null";this.statement=t,this.columns={},this.all_table_attributes=r,this.fetch_attributes=[],this.exact_search_values={},this.comparator_search_values={},this.tables=[],this.data={},this.has_aggregator=!1,this.has_ordinal=!1,this.has_outer_join=!1,this._getColumns(),this._getTables(),this._conditionsToFetchAttributeValues(),this._setAliasesForColumns(),Qe.backtickASTSchemaItems(this.statement)}async search(){let t;try{let n=await this._checkEmptySQL();if(!Qe.isEmptyOrZeroLength(n))return we.trace("No results returned from checkEmptySQL SQLSearch method."),n}catch(n){throw we.error("Error thrown from checkEmptySQL in SQLSearch class method search."),we.error(n),new Error(ps)}try{let n=await this._getFetchAttributeValues();if(n)return n}catch(n){throw we.error("Error thrown from getFetchAttributeValues in SQLSearch class method search."),we.error(n),new Error(ps)}if(Object.keys(this.data).length===0)return we.trace('SQLSearch class field: "data" is empty.'),[];let r;try{r=await this._processJoins()}catch(n){throw we.error("Error thrown from processJoins in SQLSearch class method search."),we.error(n),new Error(ps)}try{await this._getFinalAttributeData(r.existing_attributes,r.joined_length)}catch(n){throw we.error("Error thrown from getFinalAttributeData in SQLSearch class method search."),we.error(n),new Error(ps)}try{return t=await this._finalSQL(),t}catch(n){throw we.error("Error thrown from finalSQL in SQLSearch class method search."),we.error(n),new Error(ps)}}_getColumns(){let t=new SE(this.statement);for(let{node:r,path:n}of t)r&&r.columnid&&(this.columns[n[0]]||(this.columns[n[0]]=[]),this.columns[n[0]].push(VP(r)))}_getTables(){let t=[];this.all_table_attributes.forEach(r=>{t.push(r.table)}),this.tables=Wu.uniqBy(t,r=>[r.databaseid,r.tableid,r.as].join()),this.tables.forEach(r=>{let n=`${r.databaseid}_${r.as?r.as:r.tableid}`;this.data[n]={},this.data[n].__hash_name=$P()[r.databaseid][r.tableid].primaryKey,this.data[n].__merged_data={},this.data[n].__merged_attributes=[],this.data[n].__merged_attr_map={}})}_conditionsToFetchAttributeValues(){if(Qe.isEmpty(this.statement.where)){we.trace('AST "where" statement is empty.');return}let t=!1;for(let{node:r}of new SE(this.statement.where))if(r&&r.op&&r.op==="OR"&&(t=!0),!Qe.isEmpty(r)&&r.right)if(Qe.isNotEmptyAndHasValue(r.right.value)){let n=Qe.autoCast(r.right.value);[!0,!1].indexOf(n)>=0&&(r.right=new Wr.yy.LogicValue({value:n}))}else Array.isArray(r.right)&&r.right.forEach((n,s)=>{let i=Qe.autoCast(n.value);[!0,!1].indexOf(i)>=0?r.right[s]=new Wr.yy.LogicValue({value:i}):n instanceof Wr.yy.StringValue&&Qe.autoCasterIsNumberCheck(i.toString())&&(r.right[s]=new Wr.yy.NumValue({value:i}))});if(t){we.trace('Where clause contains "OR", exact match search not performed on attributes.');return}for(let{node:r}of new SE(this.statement.where))if(r&&r.left&&r.right&&(r.left.columnid||r.right.value)&&r.op){let n=new Set,s=r.left.columnid?r.left:r.right,i=this._findColumn(s);if(!i)continue;let o=[i.table.databaseid,i.table.tableid,i.attribute].join("/");if(!Qe.isEmpty(uZ.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[r.op])){if(Qe.isEmpty(this.comparator_search_values[o])&&(this.comparator_search_values[o]={ignore:!1,comparators:[]}),!this.comparator_search_values[o].ignore){if(Qe.isEmptyOrZeroLength(r.left.columnid)||Qe.isEmptyOrZeroLength(r.right.value)){this.comparator_search_values[o].ignore=!0,this.comparator_search_values[o].comparators=[];continue}this.comparator_search_values[o].comparators.push({attribute:r.left.columnid,operation:r.op,search_value:r.right.value})}continue}if(Qe.isEmpty(this.exact_search_values[o])&&(this.exact_search_values[o]={ignore:!1,values:new Set}),!this.exact_search_values[o].ignore){let c=!1;switch(r.op){case"=":!Qe.isEmpty(r.right.value)||!Qe.isEmpty(r.left.value)?n.add(Qe.isEmpty(r.right.value)?r.left.value:r.right.value):c=!0;break;case"IN":let l=Array.isArray(r.right)?r.right:r.left;for(let d=0;d<l.length;d++)if(l[d].value)n.add(l[d].value);else{c=!0;break}break;default:c=!0;break}this.exact_search_values[o].ignore=c,c?this.exact_search_values[o].values=new Set:this.exact_search_values[o].values=new Set([...this.exact_search_values[o].values,...n])}}}_setAliasesForColumns(){if(Qe.isEmptyOrZeroLength(this.all_table_attributes)&&Qe.isEmptyOrZeroLength(this.statement.from)&&Qe.isEmptyOrZeroLength(this.columns.columns))return;let t=[],r={};this.statement.columns.forEach((n,s)=>{if(n.columnid==="*"){t.push(s);return}if(n.aggregatorid&&(this.has_aggregator=!0),!n.aggregatorid&&!n.funcid)if(n.as_orig=n.as?n.as:n.columnid,this.statement.joins)if(r[n.as_orig]>=0){let i=r[n.as_orig]+1;n.as=`[${n.as_orig+i}]`,r[n.as_orig]=i}else n.as=`[${n.as_orig}]`,r[n.as_orig]=0;else n.as=`[${n.as_orig}]`;!n.aggregatorid&&n.funcid&&n.args&&(n.as_orig=n.as?n.as:n.toString().replace(/'/g,'"'),n.as=`[${n.as_orig}]`),n.aggregatorid&&n.expression.columnid!=="*"&&(n.as_orig=n.as?n.as:n.expression.tableid?`${n.aggregatorid}(${n.expression.tableid}.${n.expression.columnid})`:`${n.aggregatorid}(${n.expression.columnid})`,n.as=`[${n.as_orig}]`)}),this.statement.columns.length>1&&t.length>0&&Wu.pullAt(this.statement.columns,t)}_findColumn(t){let r=this.all_table_attributes.filter(n=>{if(t.columnid_orig&&t.tableid_orig)return(n.table.as===t.tableid_orig||n.table.tableid===t.tableid_orig)&&n.attribute===t.columnid_orig;if(t.tableid)return(n.table.as===t.tableid||n.table.tableid===t.tableid)&&n.attribute===t.columnid;let s=t.columnid_orig?t.columnid_orig:t.columnid;return n.attribute===s});if(Qe.isEmptyOrZeroLength(r)){let n=this.columns.columns.filter(s=>s.as?t.columnid===s.as:!1);Qe.isEmptyOrZeroLength(n)||(r=this.all_table_attributes.filter(s=>s.attribute===n[0].columnid&&n[0].tableid&&n[0].tableid===(s.table.as?s.table.as:s.table.tableid)))}return r[0]}async _checkEmptySQL(){let t=[];if(Qe.isEmptyOrZeroLength(this.all_table_attributes)&&!Qe.isEmptyOrZeroLength(this.columns.columns))return t;if(Qe.isEmptyOrZeroLength(this.all_table_attributes)&&Qe.isEmptyOrZeroLength(this.statement.from))try{let r=this._buildSQL(!1);t=await Wr.promise(r)}catch(r){throw we.error("Error thrown from AlaSQL in SQLSearch class method checkEmptySQL."),we.error(r),new Error("There was a problem with the SQL statement")}return t}_addFetchColumns(t){t&&t.length>0&&t.forEach(r=>{let n=this._findColumn(r);n&&this.fetch_attributes.push(VP(n))})}_addColumnToMergedAttributes(t,r){this.data[t].__merged_attributes.push(r),this.data[t].__merged_attr_map[r]=this.data[t].__merged_attributes.length-1}_setMergedHashAttribute(t,r){this.data[t].__merged_data[r].splice(0,1,r)}_updateMergedAttribute(t,r,n,s){let i=this.data[t].__merged_attr_map[n];this.data[t].__merged_data[r].splice(i,1,s)}async _getFetchAttributeValues(){if(Qe.isEmptyOrZeroLength(Object.keys(this.columns)))return[];this._addFetchColumns(this.columns.joins);let t=null;try{t=this.statement.where?this.statement.where.toString():""}catch{throw new Error("Could not generate proper where clause")}this.columns.where&&this._addFetchColumns(this.columns.where);let r=this._isSimpleSelect();if(r?this._addFetchColumns(this.columns.columns):(!this.columns.where&&this.fetch_attributes.length===0)|t.indexOf(fZ)>-1&&this.tables.forEach(s=>{let i={columnid:$P()[s.databaseid][s.tableid].primaryKey,tableid:s.tableid};this._addFetchColumns([i])}),this.statement.order&&(this._updateOrderByToAliases(),this._addNonAggregatorsToFetchColumns()),this.fetch_attributes=Wu.uniqBy(this.fetch_attributes,s=>[s.table.databaseid,s.table.as?s.table.as:s.table.tableid,s.attribute].join()),r)return await this._simpleSQLQuery();let n=this.fetch_attributes.reduce((s,i)=>{let o=`${i.table.databaseid}_${i.table.as?i.table.as:i.table.tableid}`,c=this.data[o].__hash_name;return s[o]||(s[o]=[],s[o].push(null),this._addColumnToMergedAttributes(o,c)),i.attribute!==c&&(s[o].push(null),this._addColumnToMergedAttributes(o,i.attribute)),s},{});for(let s of this.fetch_attributes){let i=`${s.table.databaseid}_${s.table.as?s.table.as:s.table.tableid}`,o=this.data[i].__hash_name,c={schema:s.table.databaseid,table:s.table.tableid,get_attributes:[s.attribute]},l=!1,d=[s.table.databaseid,s.table.tableid,s.attribute].join("/");if(s.attribute===o&&(l=!0),!Qe.isEmpty(this.exact_search_values[d])&&!this.exact_search_values[d].ignore&&!Qe.isEmptyOrZeroLength(this.exact_search_values[d].values))if(l)try{c.hash_values=Array.from(this.exact_search_values[d].values);let u=await Ic.getDataByHash(c);for(let f of c.hash_values)u.get(f)&&!this.data[i].__merged_data[f]&&(this.data[i].__merged_data[f]=[...n[i]],this._setMergedHashAttribute(i,f))}catch(u){throw we.error("Error thrown from getDataByHash function in SQLSearch class method getFetchAttributeValues exact match."),we.error(u),new Error(ps)}else try{c.search_attribute=s.attribute,await Promise.all(Array.from(this.exact_search_values[d].values).map(async u=>{let f=Object.assign({},c);f.search_value=u;let E=await Ic.getDataByValue(f);for(let[_,h]of E)this.data[i].__merged_data[_]?this._updateMergedAttribute(i,_,s.attribute,h[s.attribute]):(this.data[i].__merged_data[_]=[...n[i]],this._updateMergedAttribute(i,_,s.attribute,h[s.attribute]),this._setMergedHashAttribute(i,_))}))}catch(u){throw we.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues exact match."),we.error(u),new Error(ps)}else if(!Qe.isEmpty(this.comparator_search_values[d])&&!this.comparator_search_values[d].ignore&&!Qe.isEmptyOrZeroLength(this.comparator_search_values[d].comparators))try{let u=this.comparator_search_values[d].comparators;for(let f=0,E=u.length;f<E;f++){let _=u[f];c.search_attribute=_.attribute,c.search_value=_.search_value;let h=await Ic.getDataByValue(c,_.operation);if(l)for(let[p]of h)this.data[i].__merged_data[p]||(this.data[i].__merged_data[p]=[...n[i]],this._setMergedHashAttribute(i,p));else for(let[p,S]of h)this.data[i].__merged_data[p]?this._updateMergedAttribute(i,p,s.attribute,S[s.attribute]):(this.data[i].__merged_data[p]=[...n[i]],this._updateMergedAttribute(i,p,s.attribute,S[s.attribute]),this._setMergedHashAttribute(i,p))}}catch(u){throw we.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues comparator search values."),we.error(u),new Error(ps)}else try{c.search_attribute=s.attribute,c.search_value="*";let u=await Ic.getDataByValue(c);if(l)for(let[f]of u)this.data[i].__merged_data[f]||(this.data[i].__merged_data[f]=[...n[i]],this._setMergedHashAttribute(i,f));else for(let[f,E]of u)this.data[i].__merged_data[f]?this._updateMergedAttribute(i,f,s.attribute,E[s.attribute]):(this.data[i].__merged_data[f]=[...n[i]],this._updateMergedAttribute(i,f,s.attribute,E[s.attribute]),this._setMergedHashAttribute(i,f))}catch(u){throw we.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues no comparator search values."),we.error(u),new Error(ps)}}}_isSimpleSelect(){let t=!0;return Object.keys(this.statement).length!==2||!this.statement.columns||!this.statement.from||this.statement.from.length!==1?(t=!1,t):(this.statement.columns.forEach(r=>{r instanceof Wr.yy.Column||(t=!1)}),t)}_updateOrderByToAliases(){this.statement.order.forEach(t=>{if(t.expression.aggregatorid){t.is_aggregator=!0;return}if(t.expression.value){t.is_ordinal=!0,this.has_ordinal=!0;return}else t.is_ordinal=!1;let r=this.statement.columns.filter(s=>{let i=s.aggregatorid?s.expression:s,o=s.aggregatorid?s.as_orig:i.as_orig;return t.expression.tableid?i.columnid_orig===t.expression.columnid_orig&&i.tableid_orig===t.expression.tableid_orig:i.columnid_orig===t.expression.columnid_orig||t.expression.columnid_orig===o});r[0]||r.push(this._findColumn(t.expression));let n=r[0];if(t.is_func=!!n.funcid,t.is_aggregator=!!n.aggregatorid,n.as)if(n.as&&!t.expression.tableid)t.expression.columnid=n.as,t.expression.columnid_orig=n.as_orig;else{let s=new Wr.yy.Column;s.columnid=n.as,s.columnid_orig=n.as_orig,t.expression=s}else{t.initial_select_column=Object.assign(new Wr.yy.Column,t.expression),t.initial_select_column.as=`[${t.expression.columnid_orig}]`,t.expression.columnid=t.initial_select_column.as;return}if(!t.is_aggregator){let s=t.is_func?new Wr.yy.FuncValue:new Wr.yy.Column;t.initial_select_column=Object.assign(s,n)}})}_addNonAggregatorsToFetchColumns(){let r=this.statement.order.filter(n=>!n.is_aggregator&&!n.is_ordinal).map(n=>n.is_func?{columnid:n.initial_select_column.args.filter(i=>!!i.columnid_orig)[0].columnid_orig}:{columnid:n.expression.columnid_orig});this._addFetchColumns(r)}async _processJoins(){let t=[],r=[],n=this.statement.from[0],s=[n],i=["? "+(n.as?" AS "+n.as:n.tableid)];t.push(Object.values(this.data[`${n.databaseid_orig}_${n.as?n.as_orig:n.tableid_orig}`].__merged_data)),this.statement.joins&&this.statement.joins.forEach(_=>{_.joinmode&&_.joinmode!=="INNER"&&(this.has_outer_join=!0),s.push(_.table);let h=_.joinmode+" JOIN ? AS "+(_.as?_.as:_.table.tableid);_.on&&(h+=" ON "+_.on.toString()),i.push(h),t.push(Object.values(this.data[`${_.table.databaseid_orig}_${_.table.as?_.table.as_orig:_.table.tableid_orig}`].__merged_data))});let o=[],c={};s.forEach(_=>{let h=this.data[`${_.databaseid_orig}_${_.as?_.as_orig:_.tableid_orig}`].__hash_name,p=_.as?_.as_orig:_.tableid_orig;o.push({key:`'${p}.${h}'`,schema:_.databaseid_orig,table:_.as?_.as_orig:_.tableid_orig,keys:new Set}),r.push(`${_.as?_.as:_.tableid}.\`${h}\` AS "${p}.${h}"`),c[_.as?_.as_orig:_.tableid_orig]=this.data[`${_.databaseid_orig}_${_.as?_.as_orig:_.tableid_orig}`].__merged_attributes});let l=this.statement.where?"WHERE "+this.statement.where:"";l=l.replace(/NOT\(NULL\)/g,"NOT NULL");let d="";this.statement.order&&!this.has_ordinal&&!this.has_aggregator&&!this.statement.group&&this.statement.limit&&(d="ORDER BY "+this.statement.order.toString(),this.statement.order.forEach(_=>{_.is_func?r.push(_.initial_select_column.toString()):_.initial_select_column.tableid?r.push(`${_.initial_select_column.tableid}.${_.initial_select_column.columnid} AS ${_.expression.columnid}`):r.push(`${_.initial_select_column.columnid} AS ${_.expression.columnid}`)}));let u="",f="";!this.has_aggregator&&!this.statement.group&&!this.has_ordinal&&!this.statement.joins&&(u=this.statement.limit?"LIMIT "+this.statement.limit:"",f=this.statement.offset?"OFFSET "+this.statement.offset:"");let E=[];try{let _=`SELECT ${r.join(", ")} FROM ${i.join(" ")} ${l} ${d} ${u} ${f}`,h=this._convertColumnsToIndexes(_,s);E=await Wr.promise(h,t),t=null}catch(_){throw we.error("Error thrown from AlaSQL in SQLSearch class method processJoins."),we.error(_),new Error("There was a problem processing the data.")}if(E&&E.length>0){for(let _=0,h=E.length;_<h;_++){let p=E[_];o.forEach(S=>{p[S.key]!==null&&p[S.key]!==void 0&&S.keys.add(p[S.key])})}o.forEach(_=>{let h=Object.keys(this.data[`${_.schema}_${_.table}`].__merged_data),p=Wu.difference(h,[..._.keys].map(S=>S.toString()));for(let S=0,g=p.length;S<g;S++){let T=p[S];delete this.data[`${_.schema}_${_.table}`].__merged_data[T]}})}return{existing_attributes:c,joined_length:E?E.length:0}}async _getFinalAttributeData(t,r){if(r===0)return;let n=[],s=new SE(this.columns);for(let{node:i}of s)if(i&&i.columnid){let o=this._findColumn(i);if(o){let c=o.table.as?o.table.as:o.table.tableid;(!t[c]||t[c].indexOf(o.attribute)<0)&&n.push(o)}}n=Wu.uniqBy(n,i=>[i.table.databaseid,i.table.as?i.table.as:i.table.tableid,i.attribute].join());try{await this._getData(n)}catch(i){throw we.error("Error thrown from getData in SQLSearch class method getFinalAttributeData."),we.error(i),new Error(ps)}}async _getData(t){try{let r=t.reduce((n,s)=>{let i=`${s.table.databaseid}_${s.table.as?s.table.as:s.table.tableid}`;return n[i]?n[i].columns.push(s.attribute):n[i]={schema:s.table.databaseid,table:s.table.tableid,columns:[s.attribute]},n},{});for(let n in r){let s=r[n],i=this.data[n].__merged_data,o=[];for(let u in i)o.push(i[u][0]);this.data[n].__merged_attributes.push(...s.columns);let c={schema:s.schema,table:s.table,hash_values:o,get_attributes:s.columns},l=await Ic.getDataByHash(c),d=s.columns.length;for(let u=0,f=o.length;u<f;u++){let E=o[u],_=l.get(E);for(let h=0;h<d;h++){let p=s.columns[h],S=_[p]===void 0?null:_[p];this.data[n].__merged_data[E].push(S)}}}}catch(r){throw we.error("Error thrown from getDataByHash function in SQLSearch class method getData."),we.error(r),r}}async _finalSQL(){let t=[],r=this.statement.from[0];t.push(Object.values(this.data[`${r.databaseid_orig}_${r.as?r.as_orig:r.tableid_orig}`].__merged_data)),r.as=r.as?r.as:r.tableid,r.databaseid="",r.tableid="?",this.statement.joins&&this.statement.joins.forEach(s=>{s.as=s.as?s.as:s.table.tableid,t.push(Object.values(this.data[`${s.table.databaseid_orig}_${s.table.as?s.table.as_orig:s.table.tableid_orig}`].__merged_data)),s.table.databaseid="",s.table.tableid="?"}),this.statement.order&&this.statement.order.forEach(s=>{if(s.is_ordinal)return;this.statement.columns.filter(o=>{let c=o.aggregatorid?o.expression:o,l=o.aggregatorid?o.as_orig:c.as_orig;return s.expression.tableid?c.columnid_orig===s.expression.columnid_orig&&c.tableid_orig===s.expression.tableid_orig:c.columnid_orig===s.expression.columnid_orig||s.expression.columnid_orig===l}).length===0&&(s.expression.columnid=s.initial_select_column.columnid)}),!this.has_aggregator&&!this.statement.group&&!this.has_ordinal&&this.statement.limit&&!this.statement.joins&&(delete this.statement.limit,delete this.statement.offset);let n;try{let s=this._buildSQL();we.trace(`Final SQL: ${s}`),n=await Wr.promise(s,t),this.has_outer_join&&(n=this._translateUndefinedValues(n)),we.trace(`Final AlaSQL results data included ${n.length} rows`)}catch(s){throw we.error("Error thrown from AlaSQL in SQLSearch class method finalSQL."),we.error(s),new Error("There was a problem running the generated sql.")}return n}_translateUndefinedValues(t){try{let r=[];for(let n of t){let s=Object.create(null);Object.keys(n).forEach(i=>{n[i]===void 0?s[i]=null:s[i]=n[i]}),r.push(s)}return r}catch(r){return we.error(dZ.HDB_ERROR_MSGS.OUTER_JOIN_TRANSLATION_ERROR),we.trace(r.stack),t}}_buildSQL(t=!0){let r=this.statement.toString();return r=r.replace(/NOT\(NULL\)/g,"NOT NULL"),this.statement.columns.forEach(n=>{if(n.funcid&&n.as){let s=n.toString().replace(" AS "+n.as,"");r=r.replace(n.toString(),s)}}),t===!0?this._convertColumnsToIndexes(r,this.tables):r}_convertColumnsToIndexes(t,r){let n=t,s={};r.forEach(i=>{i.databaseid_orig?s[`${i.databaseid_orig}_${i.as?i.as_orig:i.tableid_orig}`]=i.as?i.as:i.tableid:s[`${i.databaseid}_${i.as?i.as:i.tableid}`]=`\`${i.as?i.as:i.tableid}\``});for(let i in this.data)this.data[i].__merged_attributes.forEach((o,c)=>{let l=s[i],d=new RegExp(`${l}.\`${o}\``,"g"),u=`${l}.[${c}]`;n=n.replace(d,u)});for(let i in this.data)this.data[i].__merged_attributes.forEach((o,c)=>{let l=new RegExp(`\`${o}\``,"g"),d=`[${c}]`;n=n.replace(l,d)});return n}async _simpleSQLQuery(){let t=this.statement.columns.reduce((n,s)=>(s.as_orig&&s.as_orig!=s.columnid_orig?n[s.columnid_orig]=s.as_orig:n[s.columnid_orig]||(n[s.columnid_orig]=s.columnid_orig),n),{}),r=this.fetch_attributes.reduce((n,s)=>{let i=`${s.table.databaseid}_${s.table.as?s.table.as:s.table.tableid}`;return n[i]||(n[i]={}),n[i][t[s.attribute]]=null,n},{});for(let n of this.fetch_attributes){let s=`${n.table.databaseid}_${n.table.as?n.table.as:n.table.tableid}`,i={schema:n.table.databaseid,table:n.table.tableid,get_attributes:[n.attribute]};try{i.search_attribute=n.attribute,i.search_value="*";let o=await Ic.getDataByValue(i);for(let[c,l]of o)this.data[s].__merged_data[c]||(l[n.attribute]===void 0&&(l[n.attribute]=null),this.data[s].__merged_data[c]=Object.assign({},r[s])),this.data[s].__merged_data[c][t[n.attribute]]=l[n.attribute]??null}catch(o){throw we.error("There was an error when processing this SQL operation. Check your logs"),we.error(o),new Error(ps)}}return Object.values(Object.values(this.data)[0].__merged_data)}};YP.exports=Ig});var gn=I((Wme,WP)=>{"use strict";var _Z=AI();WP.exports={searchByConditions:hZ,searchByHash:mZ,searchByValue:pZ,search:SZ};var wg=Vn(),{transformReq:Cg}=re(),EZ=KP();async function hZ(e){return Cg(e),wg.searchByConditions(e)}a(hZ,"searchByConditions");async function mZ(e){Cg(e),e.ids&&(e.hash_values=e.ids);let t=[];for await(let r of wg.searchByHash(e))r&&t.push(r);return t}a(mZ,"searchByHash");async function pZ(e){Cg(e),e.hasOwnProperty("desc")===!0&&(e.reverse=e.desc);let t=[];for await(let r of wg.searchByValue(e))t.push(r);return t}a(pZ,"searchByValue");function SZ(e,t){try{let r=new _Z(e);r.validate(),new EZ(r.statement,r.attributes).search().then(s=>{t(null,s)}).catch(s=>{t(s,null)})}catch(r){return t(r)}}a(SZ,"search")});var TE=I((zme,QP)=>{"use strict";var TZ=Vn();QP.exports={writeTransaction:gZ};function gZ(e,t,r){return TZ.writeTransaction(e,t,r)}a(gZ,"writeTransaction")});var XP=I((Xme,JP)=>{"use strict";var RZ=gn(),AZ=eo(),zP=X(),bZ=qn(),Jme=TE(),yZ=require("clone"),Lg=require("alasql"),OZ=pE(),jP=require("util"),NZ=jP.promisify(AZ.getTableSchema),IZ=jP.promisify(RZ.search),wZ=H(),Dg=re();OZ(Lg);JP.exports={update:DZ};var CZ="There was a problem performing this update. Please check the logs and try again.";async function DZ({statement:e,hdb_user:t}){let r=await NZ(e.table.databaseid,e.table.tableid),n=LZ(e.columns);Dg.backtickASTSchemaItems(e);let{table:s,where:i}=e,o=yZ(s),c=Dg.isEmpty(i)?"":` WHERE ${i.toString()}`,l=`SELECT ${r.hash_attribute} FROM ${s.toString()} ${c}`,d=Lg.parse(l).statements[0],u=await IZ(d),f=PZ(n,u);return MZ(o,f,t)}a(DZ,"update");function LZ(e){try{let t={};return e.forEach(r=>{"value"in r.expression?t[r.column.columnid]=r.expression.value??null:t[r.column.columnid]=Lg.compile(`SELECT ${r.expression.toString()} AS [${wZ.FUNC_VAL}] FROM ?`)}),t}catch(t){throw zP.error(t),new Error(CZ)}}a(LZ,"createUpdateRecord");function PZ(e,t){return Dg.isEmptyOrZeroLength(t)?[]:t.map(r=>Object.assign(r,e))}a(PZ,"buildUpdateRecords");async function MZ(e,t,r){let n={operation:"update",schema:e.databaseid_orig,table:e.tableid_orig,records:t,hdb_user:r},s=await bZ.update(n);try{delete s.new_attributes,delete s.txn_time}catch(i){zP.error(`Error delete new_attributes from update response: ${i}`)}return s}a(MZ,"updateRecords")});var eM=I((rpe,ZP)=>{var UZ=require("alasql"),vZ=gn(),xZ=X(),BZ=Vn(),Mg=require("util"),Pg=re(),HZ=H(),kZ=eo(),epe=TE(),tpe=qn(),FZ="record",GZ="successfully deleted",qZ=Mg.callbackify(KZ),VZ=Mg.promisify(vZ.search),$Z=Mg.promisify(kZ.getTableSchema);ZP.exports={convertDelete:qZ};function YZ(e){return`${e.deleted_hashes.length} ${FZ}${e.deleted_hashes.length===1?"":"s"} ${GZ}`}a(YZ,"generateReturnMessage");async function KZ({statement:e,hdb_user:t}){let r=await $Z(e.table.databaseid,e.table.tableid);Pg.backtickASTSchemaItems(e);let{table:n,where:s}=e,i=Pg.isEmpty(s)?"":` WHERE ${s.toString()}`,o=`SELECT ${r.hash_attribute} FROM ${n.toString()} ${i}`,c=UZ.parse(o).statements[0],l={operation:HZ.OPERATIONS_ENUM.DELETE,schema:n.databaseid_orig,table:n.tableid_orig,hdb_user:t};try{l.records=await VZ(c);let d=await BZ.deleteRecords(l);return Pg.isEmptyOrZeroLength(d.message)&&(d.message=YZ(d)),delete d.txn_time,d}catch(d){throw xZ.error(d),d.hdb_code?d.message:d}}a(KZ,"convertDelete")});var iM=I((spe,sM)=>{"use strict";var WZ=Zi(),{hdb_errors:tM}=ce(),{getDatabases:rM}=(Ne(),ae(it));sM.exports={checkSchemaExists:nM,checkSchemaTableExists:QZ,schema_describe:WZ};async function nM(e){if(!rM()[e])return tM.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}a(nM,"checkSchemaExists");async function QZ(e,t){let r=await nM(e);if(r)return r;if(!rM()[e][t])return tM.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(QZ,"checkSchemaTableExists")});var bE=I((ape,lM)=>{"use strict";var wc=D_(),Cc=iM(),zZ=X(),jZ=require("uuid").v4,ope=require("clone"),RE=pi(),Dc=H(),JZ=require("util"),co=Vn(),{handleHDBError:Qr,hdb_errors:XZ}=ce(),{HDB_ERROR_MSGS:gE,HTTP_STATUS_CODES:zr}=XZ,{SchemaEventMsg:AE}=Es(),oM=or(),{getDatabases:ZZ}=(Ne(),ae(it)),{transformReq:Lc}=re();lM.exports={createSchema:e5,createSchemaStructure:aM,createTable:t5,createTableStructure:cM,createAttribute:o5,dropSchema:r5,dropTable:n5,dropAttribute:s5,getBackup:a5};async function e5(e){let t=await aM(e);return RE.signalSchemaChange(new AE(process.pid,e.operation,e.schema)),t}a(e5,"createSchema");async function aM(e){let t=wc.schema_object(e);if(t)throw Qr(t,t.message,zr.BAD_REQUEST,void 0,void 0,!0);if(Lc(e),!await Cc.checkSchemaExists(e.schema))throw Qr(new Error,gE.SCHEMA_EXISTS_ERR(e.schema),zr.BAD_REQUEST,Dc.LOG_LEVELS.ERROR,gE.SCHEMA_EXISTS_ERR(e.schema),!0);return await co.createSchema(e),`database '${e.schema}' successfully created`}a(aM,"createSchemaStructure");async function t5(e){return Lc(e),e.hash_attribute=e.primary_key??e.hash_attribute,await cM(e)}a(t5,"createTable");async function cM(e){let t=wc.create_table_object(e);if(t)throw Qr(t,t.message,zr.BAD_REQUEST,void 0,void 0,!0);if(wc.validateTableResidence(e.residence),!await Cc.checkSchemaTableExists(e.schema,e.table))throw Qr(new Error,gE.TABLE_EXISTS_ERR(e.schema,e.table),zr.BAD_REQUEST,Dc.LOG_LEVELS.ERROR,gE.TABLE_EXISTS_ERR(e.schema,e.table),!0);let n={name:e.table,schema:e.schema,id:jZ(),hash_attribute:e.hash_attribute};try{if(e.residence)if(global.clustering_on)n.residence=e.residence,await co.createTable(n,e);else throw Qr(new Error,"Clustering does not appear to be enabled. Cannot insert table with property 'residence'.",zr.BAD_REQUEST);else await co.createTable(n,e);return`table '${e.schema}.${e.table}' successfully created.`}catch(s){throw s}}a(cM,"createTableStructure");async function r5(e){let t=!e.schema&&!e.database?new Error("database is required"):void 0,r=wc.schema_object(e),n=t??r;if(n)throw Qr(n,n.message,zr.BAD_REQUEST,void 0,void 0,!0);Lc(e);let s=await Cc.checkSchemaExists(e.schema);if(s)throw Qr(new Error,s,zr.NOT_FOUND,Dc.LOG_LEVELS.ERROR,s,!0);let i=await Cc.schema_describe.describeSchema({schema:e.schema}),o=Object.keys(global.hdb_schema[e.schema]);return await co.dropSchema(e),RE.signalSchemaChange(new AE(process.pid,e.operation,e.schema)),await oM.purgeSchemaTableStreams(e.schema,o),`successfully deleted '${e.schema}'`}a(r5,"dropSchema");async function n5(e){let t=wc.table_object(e);if(t)throw Qr(t,t.message,zr.BAD_REQUEST,void 0,void 0,!0);Lc(e);let r=await Cc.checkSchemaTableExists(e.schema,e.table);if(r)throw Qr(new Error,r,zr.NOT_FOUND,Dc.LOG_LEVELS.ERROR,r,!0);return await co.dropTable(e),await oM.purgeTableStream(e.schema,e.table),`successfully deleted table '${e.schema}.${e.table}'`}a(n5,"dropTable");async function s5(e){let t=wc.attribute_object(e);if(t)throw Qr(t,t.message,zr.BAD_REQUEST,void 0,void 0,!0);Lc(e);let r=await Cc.checkSchemaTableExists(e.schema,e.table);if(r)throw Qr(new Error,r,zr.NOT_FOUND,Dc.LOG_LEVELS.ERROR,r,!0);if(e.attribute===global.hdb_schema[e.schema][e.table].hash_attribute)throw Qr(new Error,"You cannot drop a hash attribute",zr.BAD_REQUEST,void 0,void 0,!0);if(Dc.TIME_STAMP_NAMES.indexOf(e.attribute)>=0)throw Qr(new Error,`cannot drop internal timestamp attribute: ${e.attribute}`,zr.BAD_REQUEST,void 0,void 0,!0);try{return await co.dropAttribute(e),i5(e),RE.signalSchemaChange(new AE(process.pid,e.operation,e.schema,e.table,e.attribute)),`successfully deleted attribute '${e.attribute}'`}catch(n){throw zZ.error(`Got an error deleting attribute ${JZ.inspect(e)}.`),n}}a(s5,"dropAttribute");function i5(e){let t=Object.values(global.hdb_schema[e.schema][e.table].attributes);for(let r=0;r<t.length;r++)t[r].attribute===e.attribute&&global.hdb_schema[e.schema][e.table].attributes.splice(r,1)}a(i5,"dropAttributeFromGlobal");async function o5(e){Lc(e);let t=ZZ()[e.schema][e.table].attributes;for(let{name:r}of t)if(r===e.attribute)throw Qr(new Error,`attribute '${e.attribute}' already exists in ${e.schema}.${e.table}`,zr.BAD_REQUEST,void 0,void 0,!0);return await co.createAttribute(e),RE.signalSchemaChange(new AE(process.pid,e.operation,e.schema,e.table,e.attribute)),`attribute '${e.schema}.${e.table}.${e.attribute}' successfully created.`}a(o5,"createAttribute");function a5(e){return co.getBackup(e)}a(a5,"getBackup")});var dM=I((lpe,uM)=>{"use strict";var{OPERATIONS_ENUM:c5}=H(),Ug=class{static{a(this,"ReadAuditLogObject")}constructor(t,r,n=void 0,s=void 0){this.operation=c5.READ_AUDIT_LOG,this.schema=t,this.table=r,this.search_type=n,this.search_values=s}};uM.exports=Ug});var vg=I((fpe,mM)=>{"use strict";var l5=Vn(),dpe=dM(),yE=re(),OE=H(),u5=ie(),{handleHDBError:fM,hdb_errors:d5}=ce(),{HDB_ERROR_MSGS:_M,HTTP_STATUS_CODES:EM}=d5,f5=Object.values(OE.READ_AUDIT_LOG_SEARCH_TYPES_ENUM),hM="To use this operation audit log must be enabled in harperdb-config.yaml";mM.exports=_5;async function _5(e){if(yE.isEmpty(e.schema))throw new Error(_M.SCHEMA_REQUIRED_ERR);if(yE.isEmpty(e.table))throw new Error(_M.TABLE_REQUIRED_ERR);if(!u5.get(OE.CONFIG_PARAMS.LOGGING_AUDITLOG))throw fM(new Error,hM,EM.BAD_REQUEST,OE.LOG_LEVELS.ERROR,hM,!0);let t=yE.checkSchemaTableExist(e.schema,e.table);if(t)throw fM(new Error,t,EM.NOT_FOUND,OE.LOG_LEVELS.ERROR,t,!0);if(!yE.isEmpty(e.search_type)&&f5.indexOf(e.search_type)<0)throw new Error(`Invalid search_type '${e.search_type}'`);return await l5.readAuditLog(e)}a(_5,"readAuditLog")});var SM=I((Epe,pM)=>{"use strict";var{OPERATIONS_ENUM:E5}=H(),xg=class{static{a(this,"GetBackupObject")}constructor(t,r,n=void 0,s=void 0){this.operation=E5.GET_BACKUP,this.schema=t,this.table=r}};pM.exports=xg});var RM=I((Spe,gM)=>{"use strict";var h5=Vn(),mpe=SM(),Bg=re(),m5=H(),ppe=ie(),{handleHDBError:p5,hdb_errors:S5}=ce(),{HDB_ERROR_MSGS:TM,HTTP_STATUS_CODES:T5}=S5;gM.exports=g5;async function g5(e){if(Bg.isEmpty(e.schema))throw new Error(TM.SCHEMA_REQUIRED_ERR);if(Bg.isEmpty(e.table))throw new Error(TM.TABLE_REQUIRED_ERR);let t=Bg.checkSchemaTableExist(e.schema,e.table);if(t)throw p5(new Error,t,T5.NOT_FOUND,m5.LOG_LEVELS.ERROR,t,!0);return await h5.getBackup(read_audit_log_object)}a(g5,"getBackup")});var IM=I((gpe,NM)=>{var lo=require("validate.js"),bM=mt(),Pc=H(),{handleHDBError:R5,hdb_errors:A5}=ce(),{HDB_ERROR_MSGS:qt,HTTP_STATUS_CODES:b5}=A5,Hg=a(()=>({role:{presence:!0,format:"[\\w\\-\\_]+"},id:{presence:!0,format:"[\\w\\-\\_]+"},permission:{presence:!0}}),"constraintsTemplate"),y5={STRUCTURE_USER:"structure_user"},AM=Object.values(Pc.ROLE_TYPES_ENUM),O5="attribute_permissions",N5="attribute_name",{PERMS_CRUD_ENUM:Mc}=Pc,I5=[O5,...Object.values(Mc)],yM=[Mc.READ,Mc.INSERT,Mc.UPDATE],w5=[N5,...yM];function C5(e){let t=Hg();return t.role.presence=!0,t.id.presence=!1,t.permission.presence=!0,OM(e,t)}a(C5,"addRoleValidation");function D5(e){let t=Hg();return t.role.presence=!1,t.id.presence=!0,t.permission.presence=!0,OM(e,t)}a(D5,"alterRoleValidation");function L5(e){let t=Hg();return t.role.presence=!1,t.id.presence=!0,t.permission.presence=!1,bM.validateObject(e,t)}a(L5,"dropRoleValidation");var P5=["operation","role","id","permission","hdb_user","hdb_auth_header"];function OM(e,t){let r={main_permissions:[],schema_permissions:{}},n=Object.keys(e),s=[];for(let o=0,c=n.length;o<c;o++)P5.includes(n[o])||s.push(n[o]);s.length>0&&jt(qt.INVALID_ROLE_JSON_KEYS(s),r);let i=bM.validateObject(e,t);if(i&&i.message.split(",").forEach(o=>{jt(o,r)}),e.permission){let o=M5(e);o&&jt(o,r),AM.forEach(c=>{e.permission[c]&&!lo.isBoolean(e.permission[c])&&jt(qt.SU_CU_ROLE_BOOLEAN_ERROR(c),r)})}for(let o in e.permission)if(AM.indexOf(o)<0){if(o===y5.STRUCTURE_USER){let l=e.permission[o];if(typeof l=="boolean")continue;if(Array.isArray(l)){for(let d=0,u=l.length;d<u;d++){let f=l[d];global.hdb_schema[f]||jt(qt.SCHEMA_NOT_FOUND(f),r)}continue}jt(qt.STRUCTURE_USER_ROLE_TYPE_ERROR(o),r);continue}let c=e.permission[o];if(!o||!global.hdb_schema[o]){jt(qt.SCHEMA_NOT_FOUND(o),r);continue}if(c.tables)for(let l in c.tables){let d=c.tables[l];if(!l||!global.hdb_schema[o][l]){jt(qt.TABLE_NOT_FOUND(o,l),r);continue}if(Object.keys(d).forEach(u=>{I5.includes(u)||jt(qt.INVALID_PERM_KEY(u),r,o,l)}),Object.values(Mc).forEach(u=>{lo.isDefined(d[u])?lo.isBoolean(d[u])||jt(qt.TABLE_PERM_NOT_BOOLEAN(u),r,o,l):jt(qt.TABLE_PERM_MISSING(u),r,o,l)}),lo.isDefined(d.attribute_permissions)){if(!lo.isArray(d.attribute_permissions)){jt(qt.ATTR_PERMS_NOT_ARRAY,r,o,l);continue}}else{jt(qt.ATTR_PERMS_ARRAY_MISSING,r,o,l);continue}if(d.attribute_permissions){let u=global.hdb_schema[o][l].attributes.map(({attribute:E})=>E),f={read:!1,insert:!1,update:!1};for(let E in d.attribute_permissions){let _=d.attribute_permissions[E];if(Object.keys(_).forEach(p=>{!w5.includes(p)&&p!==Mc.DELETE&&jt(qt.INVALID_ATTR_PERM_KEY(p),r,o,l)}),!lo.isDefined(_.attribute_name)){jt(qt.ATTR_PERM_MISSING_NAME,r,o,l);continue}let h=_.attribute_name;if(!u.includes(h)){jt(qt.INVALID_ATTRIBUTE_IN_PERMS(h),r,o,l);continue}yM.forEach(p=>{lo.isDefined(_[p])?lo.isBoolean(_[p])||jt(qt.ATTR_PERM_NOT_BOOLEAN(p,h),r,o,l):jt(qt.ATTR_PERM_MISSING(p,h),r,o,l)}),!f.read&&_.read===!0&&(f.read=!0),!f.insert&&_.insert===!0&&(f.insert=!0),!f.update&&_.update===!0&&(f.update=!0)}if(d.read===!1&&f.read===!0||d.insert===!1&&f.insert===!0||d.update===!1&&f.update===!0){let E=`${o}.${l}`;jt(qt.MISMATCHED_TABLE_ATTR_PERMS(E),r,o,l)}}}}return U5(r)}a(OM,"customValidate");NM.exports={addRoleValidation:C5,alterRoleValidation:D5,dropRoleValidation:L5};function M5(e){let{operation:t,permission:r}=e;if(t===Pc.OPERATIONS_ENUM.ADD_ROLE||t===Pc.OPERATIONS_ENUM.ALTER_ROLE){let n=r.super_user===!0,s=r.cluster_user===!0;if(Object.keys(r).length>1&&(n||s)){if(s&&n)return qt.SU_CU_ROLE_COMBINED_ERROR;{let o=r.super_user?Pc.ROLE_TYPES_ENUM.SUPER_USER:Pc.ROLE_TYPES_ENUM.CLUSTER_USER;return qt.SU_CU_ROLE_NO_PERMS_ALLOWED(o)}}}return null}a(M5,"validateNoSUPerms");function U5(e){let{main_permissions:t,schema_permissions:r}=e;if(t.length>0||Object.keys(r).length>0){let n={error:qt.ROLE_PERMS_ERROR,...e};return R5(new Error,n,b5.BAD_REQUEST)}else return null}a(U5,"generateRolePermResponse");function jt(e,t,r,n){if(!r)t.main_permissions.push(e);else{let s=n?r+"_"+n:r;t.schema_permissions[s]?t.schema_permissions[s].push(e):t.schema_permissions[s]=[e]}}a(jt,"addPermError")});var $g=I((bpe,LM)=>{"use strict";var wM=qn(),CM=gn(),v5=Jo(),Fg=IM(),Gg=pi(),Ape=require("uuid").v4,x5=require("util"),NE=H(),B5=re(),qg=CM.searchByValue,H5=CM.searchByHash,k5=x5.promisify(v5.delete),F5=Gs(),G5=yc(),{hdb_errors:q5,handleHDBError:ca}=ce(),{HDB_ERROR_MSGS:DM,HTTP_STATUS_CODES:Qu}=q5,{UserEventMsg:Vg}=Es();LM.exports={addRole:V5,alterRole:$5,dropRole:Y5,listRoles:K5};function kg(e){try{e.hdb_auth_header&&delete e.hdb_auth_header,e.HDB_INTERNAL_PATH&&delete e.HDB_INTERNAL_PATH,e.operation&&delete e.operation,e.hdb_user&&delete e.hdb_user}catch{}return e}a(kg,"scrubRoleDetails");async function V5(e){let t=Fg.addRoleValidation(e);if(t)throw t;e=kg(e);let r={schema:"system",table:"hdb_role",search_attribute:"role",search_value:e.role,hash_attribute:"id",get_attributes:["*"]},n;try{n=Array.from(await qg(r)||[])}catch(i){throw ca(i)}if(n&&n.length>0)throw ca(new Error,DM.ROLE_ALREADY_EXISTS(e.role),Qu.CONFLICT,void 0,void 0,!0);e.id||(e.id=e.role);let s={operation:"insert",schema:"system",table:"hdb_role",hash_attribute:"id",records:[e]};return await wM.insert(s),Gg.signalUserChange(new Vg(process.pid)),e=kg(e),e}a(V5,"addRole");async function $5(e){let t=Fg.alterRoleValidation(e);if(t)throw t;e=kg(e);let r={operation:"update",schema:"system",table:"hdb_role",records:[e]},n;try{n=await wM.update(r)}catch(s){throw ca(s)}if(n&&n?.message==="updated 0 of 1 records")throw ca(new Error,"Invalid role id",Qu.BAD_REQUEST,void 0,void 0,!0);return await Gg.signalUserChange(new Vg(process.pid)),e}a($5,"alterRole");async function Y5(e){let t=Fg.dropRoleValidation(e);if(t)throw ca(new Error,t,Qu.BAD_REQUEST,void 0,void 0,!0);let r=new G5(NE.SYSTEM_SCHEMA_NAME,NE.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME,[e.id],["role"]),n=Array.from(await H5(r));if(n.length===0)throw ca(new Error,DM.ROLE_NOT_FOUND,Qu.NOT_FOUND,void 0,void 0,!0);let s=new F5(NE.SYSTEM_SCHEMA_NAME,NE.SYSTEM_TABLE_NAMES.USER_TABLE_NAME,"role",e.id,void 0,["username","active"]),i=Array.from(await qg(s)),o=!1;if(B5.isEmptyOrZeroLength(i)===!1){for(let l=0;l<i.length;l++)if(i[l].active===!0){o=!0;break}}if(o===!0)throw ca(new Error,`Cannot drop role ${n[0].role} as it has active user(s) tied to this role`,Qu.CONFLICT,void 0,void 0,!0);let c={table:"hdb_role",schema:"system",hash_values:[e.id]};return await k5(c),Gg.signalUserChange(new Vg(process.pid)),`${n[0].role} successfully deleted`}a(Y5,"dropRole");async function K5(){return qg({table:"hdb_role",schema:"system",hash_attribute:"id",search_attribute:"id",search_value:"*",get_attributes:["*"]})}a(K5,"listRoles")});var vM=I((Ope,UM)=>{"use strict";var W5=ie(),uo=require("joi"),Q5=mt(),PM=require("moment"),z5=require("fs-extra"),Yg=require("path"),j5=require("lodash"),zu=H(),{LOG_LEVELS:la}=H(),J5="YYYY-MM-DD hh:mm:ss",X5=Yg.resolve(__dirname,"../logs");UM.exports=function(e){return Q5.validateBySchema(e,Z5)};var Z5=uo.object({from:uo.custom(MM),until:uo.custom(MM),level:uo.valid(la.NOTIFY,la.FATAL,la.ERROR,la.WARN,la.INFO,la.DEBUG,la.TRACE),order:uo.valid("asc","desc"),limit:uo.number().min(1),start:uo.number().min(0),log_name:uo.custom(e8)});function MM(e,t){if(PM(e,PM.ISO_8601).format(J5)==="Invalid date")return t.message(`'${t.state.path[0]}' date '${e}' is invalid.`)}a(MM,"validateDatetime");function e8(e,t){if(j5.invert(zu.LOG_NAMES)[e]===void 0)return t.message(`'log_name' '${e}' is invalid.`);let n=W5.get(zu.HDB_SETTINGS_NAMES.LOG_PATH_KEY),s=e===void 0?zu.LOG_NAMES.HDB:e,i=s===zu.LOG_NAMES.INSTALL?Yg.join(X5,zu.LOG_NAMES.INSTALL):Yg.join(n,s);return z5.existsSync(i)?null:t.message(`'log_name' '${e}' does not exist.`)}a(e8,"validateReadLogPath")});var Wg=I((Ipe,BM)=>{"use strict";var IE=H(),t8=X(),r8=ie(),n8=vM(),Kg=require("path"),xM=require("fs-extra"),{once:s8}=require("events"),{handleHDBError:i8,hdb_errors:o8}=ce(),{PACKAGE_ROOT:a8}=H(),c8=Kg.join(a8,"logs"),l8=1e3,u8=200;BM.exports=d8;async function d8(e){let t=n8(e);if(t)throw i8(t,t.message,o8.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0);let r=r8.get(IE.HDB_SETTINGS_NAMES.LOG_PATH_KEY),n=e.log_name===void 0?IE.LOG_NAMES.HDB:e.log_name,s=n===IE.LOG_NAMES.INSTALL?Kg.join(c8,IE.LOG_NAMES.INSTALL):Kg.join(r,n),i=e.level!==void 0,o=i?e.level:void 0,c=e.from!==void 0,l=c?new Date(e.from):void 0,d=e.until!==void 0,u=d?new Date(e.until):void 0,f=e.limit===void 0?l8:e.limit,E=e.order===void 0?void 0:e.order,_=e.start===void 0?0:e.start,h=_+f,p=0;E==="desc"&&!l&&!u&&(p=Math.max(xM.statSync(s).size-(h+5)*u8,0));let S=xM.createReadStream(s,{start:p});S.on("error",v=>{t8.error(v)});let g=0,T=[],A="",N;S.on("data",v=>{let J=/(?:^|\n)(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:[\d\.]+Z) \[(.+?)]: /g;v=A+v;let $=0,F;for(;(F=J.exec(v))&&!S.destroyed;){N&&(N.message=v.slice($,F.index),V(N));let[ne,ee,Z]=F,le=Z.split("] ["),fe=le[0],je=le[1];le.splice(0,2),N={timestamp:ee,thread:fe,level:je,tags:le,message:""},$=F.index+ne.length}A=v.slice($)}),S.on("end",v=>{S.destroyed||N&&(N.message=A.trim(),V(N))}),S.resume();function V(v){let J,$,F;switch(!0){case(i&&c&&d):J=new Date(v.timestamp),$=new Date(l),F=new Date(u),v.level===o&&J>=$&&J<=F&&g<_?g++:v.level===o&&J>=$&&J<=F&&(fo(v,E,T),g++,g===h&&S.destroy());break;case(i&&c):J=new Date(v.timestamp),$=new Date(l),v.level===o&&J>=$&&g<_?g++:v.level===o&&J>=$&&(fo(v,E,T),g++,g===h&&S.destroy());break;case(i&&d):J=new Date(v.timestamp),F=new Date(u),v.level===o&&J<=F&&g<_?g++:v.level===o&&J<=F&&(fo(v,E,T),g++,g===h&&S.destroy());break;case(c&&d):J=new Date(v.timestamp),$=new Date(l),F=new Date(u),J>=$&&J<=F&&g<_?g++:J>=$&&J<=F&&(fo(v,E,T),g++,g===h&&S.destroy());break;case i:v.level===o&&g<_?g++:v.level===o&&(fo(v,E,T),g++,g===h&&S.destroy());break;case c:J=new Date(v.timestamp),$=new Date(l),J>=$&&g<_?g++:J>=$&&g>=_&&(fo(v,E,T),g++,g===h&&S.destroy());break;case d:J=new Date(v.timestamp),F=new Date(u),J<=F&&g<_?g++:J<=F&&g>=_&&(fo(v,E,T),g++,g===h&&S.destroy());break;default:g<_?g++:(fo(v,E,T),g++,g===h&&S.destroy())}}return a(V,"onLogMessage"),await s8(S,"close"),T}a(d8,"readLog");function fo(e,t,r){t==="desc"?f8(e,r):t==="asc"?_8(e,r):r.push(e)}a(fo,"pushLineToResult");function f8(e,t){let r=new Date(e.timestamp),n=0,s=t.length;for(;n<s;){let i=n+s>>>1;new Date(t[i].timestamp)>r?n=i+1:s=i}t.splice(n,0,e)}a(f8,"insertDescending");function _8(e,t){let r=new Date(e.timestamp),n=0,s=t.length;for(;n<s;){let i=n+s>>>1;new Date(t[i].timestamp)<r?n=i+1:s=i}t.splice(n,0,e)}a(_8,"insertAscending")});var wE=I((Mpe,GM)=>{"use strict";var Qg=require("joi"),{string:Uc,boolean:HM,date:E8}=Qg.types(),h8=mt(),{validateSchemaExists:Cpe,validateTableExists:Dpe,validateSchemaName:Lpe}=xs(),m8=H(),p8=Pt(),kM=ie();kM.initSync();var Ppe=Uc.invalid(kM.get(m8.CONFIG_PARAMS.CLUSTERING_NODENAME)??"node_name").pattern(p8.NATS_TERM_CONSTRAINTS_RX).messages({"string.pattern.base":"{:#label} invalid, must not contain ., * or >","any.invalid":"'node_name' cannot be this nodes name"}).empty(null),FM={operation:Uc.valid("add_node","update_node","set_node_replication"),node_name:Uc.optional(),subscriptions:Qg.array().items({table:Uc.optional(),schema:Uc.optional(),database:Uc.optional(),subscribe:HM.required(),publish:HM.required().custom(T8),start_time:E8.iso()})};function S8(e){return h8.validateBySchema(e,Qg.object(FM))}a(S8,"addUpdateNodeValidator");function T8(e,t){if(t.state.ancestors[2].operation==="add_node"&&e===!1&&t.state.ancestors[0].subscribe===!1)return t.message(`'subscriptions[${t.state.path[1]}]' subscribe and/or publish must be set to true when adding a node`)}a(T8,"checkForFalsy");GM.exports={addUpdateNodeValidator:S8,validation_schema:FM}});var VM=I((vpe,qM)=>{var g8=mt(),R8={user:{presence:!0},schema:{presence:!0},table:{presence:!0},operation:{presence:!0}};qM.exports=function(e){return g8.validateObject(e,R8)}});var jg=I((xpe,$M)=>{"use strict";var A8=H().OPERATIONS_ENUM,zg=class{static{a(this,"UpdateObject")}constructor(t,r,n,s=void 0){this.operation=A8.UPDATE,this.schema=t,this.table=r,this.records=n,this.__origin=s}};$M.exports=zg});var KM=I((Hpe,YM)=>{"use strict";var b8={OPERATION:"operation",REFRESH:"refresh"},Jg=class{static{a(this,"JWTTokens")}constructor(t,r){this.operation_token=t,this.refresh_token=r}},Xg=class{static{a(this,"JWTRSAKeys")}constructor(t,r,n){this.public_key=t,this.private_key=r,this.passphrase=n}};YM.exports={JWTTokens:Jg,TOKEN_TYPE_ENUM:b8,JWTRSAKeys:Xg}});var Xu=I((Fpe,jM)=>{"use strict";var Ju=require("jsonwebtoken"),Zg=require("fs-extra"),eR=re(),Yn=H(),{handleHDBError:jr,hdb_errors:y8}=ce(),{HTTP_STATUS_CODES:Jr,AUTHENTICATION_ERROR_MSGS:Xr}=y8,ju=X(),WM=Y_(),nR=$n(),O8=qn().update,N8=jg(),I8=pi(),{UserEventMsg:w8}=Es(),_o=ie();_o.initSync();var tR=require("path"),{JWTTokens:C8,JWTRSAKeys:D8,TOKEN_TYPE_ENUM:CE}=KM(),L8=_o.get(Yn.HDB_SETTINGS_NAMES.OPERATION_TOKEN_TIMEOUT_KEY)?_o.get(Yn.HDB_SETTINGS_NAMES.OPERATION_TOKEN_TIMEOUT_KEY):"1d",P8=_o.get(Yn.HDB_SETTINGS_NAMES.REFRESH_TOKEN_TIMEOUT_KEY)?_o.get(Yn.HDB_SETTINGS_NAMES.REFRESH_TOKEN_TIMEOUT_KEY):"30d",DE="RS256",rR;jM.exports={createTokens:M8,validateOperationToken:v8,refreshOperationToken:U8,validateRefreshToken:zM};async function M8(e){if(eR.isEmpty(e)||typeof e!="object")throw jr(new Error,Xr.INVALID_AUTH_OBJECT,Jr.BAD_REQUEST,void 0,void 0,!0);if(eR.isEmpty(e.username))throw jr(new Error,Xr.USERNAME_REQUIRED,Jr.BAD_REQUEST,void 0,void 0,!0);if(eR.isEmpty(e.password))throw jr(new Error,Xr.PASSWORD_REQUIRED,Jr.BAD_REQUEST,void 0,void 0,!0);let t;try{if(t=await nR.findAndValidateUser(e.username,e.password),!t)throw jr(new Error,Xr.INVALID_CREDENTIALS,Jr.UNAUTHORIZED,void 0,void 0,!0)}catch(E){throw ju.error(E),jr(new Error,Xr.INVALID_CREDENTIALS,Jr.UNAUTHORIZED,void 0,void 0,!0)}let r=await LE(),n=!1,s=!1;t.role&&t.role.permission&&(n=t.role.permission.super_user===!0,s=t.role.permission.cluster_user===!0);let i={username:e.username,super_user:n,cluster_user:s},o=await QM(i,r.private_key,r.passphrase),c=await Ju.sign(i,{key:r.private_key,passphrase:r.passphrase},{expiresIn:P8,algorithm:DE,subject:CE.REFRESH}),l=WM.hash(c),d=new N8(Yn.SYSTEM_SCHEMA_NAME,Yn.SYSTEM_TABLE_NAMES.USER_TABLE_NAME,[{username:e.username,refresh_token:l}]),u,f;try{u=await O8(d)}catch(E){ju.error(E),f=E}if(f!==void 0||u.skipped_hashes.length>0)throw jr(new Error,Xr.REFRESH_TOKEN_SAVE_FAILED,Jr.INTERNAL_SERVER_ERROR);return I8.signalUserChange(new w8(process.pid)),new C8(o,c)}a(M8,"createTokens");async function QM(e,t,r){return await Ju.sign(e,{key:t,passphrase:r},{expiresIn:L8,algorithm:DE,subject:CE.OPERATION})}a(QM,"signOperationToken");async function LE(){if(rR===void 0)try{let e=tR.join(_o.getHdbBasePath(),Yn.LICENSE_KEY_DIR_NAME,Yn.JWT_ENUM.JWT_PASSPHRASE_NAME),t=tR.join(_o.getHdbBasePath(),Yn.LICENSE_KEY_DIR_NAME,Yn.JWT_ENUM.JWT_PRIVATE_KEY_NAME),r=tR.join(_o.getHdbBasePath(),Yn.LICENSE_KEY_DIR_NAME,Yn.JWT_ENUM.JWT_PUBLIC_KEY_NAME),n=(await Zg.readFile(e)).toString(),s=(await Zg.readFile(t)).toString(),i=(await Zg.readFile(r)).toString();rR=new D8(i,s,n)}catch(e){throw ju.error(e),jr(new Error,Xr.NO_ENCRYPTION_KEYS,Jr.INTERNAL_SERVER_ERROR)}return rR}a(LE,"getJWTRSAKeys");async function U8(e){if(!e)throw jr(new Error,Xr.INVALID_BODY,Jr.BAD_REQUEST,void 0,void 0,!0);if(!e.refresh_token)throw jr(new Error,Xr.REFRESH_TOKEN_REQUIRED,Jr.BAD_REQUEST,void 0,void 0,!0);await zM(e.refresh_token);let t=await LE(),r=await Ju.decode(e.refresh_token);return{operation_token:await QM({username:r.username,super_user:r.super_user,cluster_user:r.cluster_user},t.private_key,t.passphrase)}}a(U8,"refreshOperationToken");async function v8(e){try{let t=await LE(),r=await Ju.verify(e,t.public_key,{algorithms:DE,subject:CE.OPERATION});return await nR.findAndValidateUser(r.username,void 0,!1)}catch(t){throw ju.warn(t),t.name&&t.name==="TokenExpiredError"?jr(new Error,Xr.TOKEN_EXPIRED,Jr.FORBIDDEN):jr(new Error,Xr.INVALID_TOKEN,Jr.UNAUTHORIZED)}}a(v8,"validateOperationToken");async function zM(e){let t;try{let r=await LE(),n=await Ju.verify(e,r.public_key,{algorithms:DE,subject:CE.REFRESH});t=await nR.findAndValidateUser(n.username,void 0,!1)}catch(r){throw ju.warn(r),r.name&&r.name==="TokenExpiredError"?jr(new Error,Xr.TOKEN_EXPIRED,Jr.FORBIDDEN):jr(new Error,Xr.INVALID_TOKEN,Jr.UNAUTHORIZED)}if(!WM.validate(t.refresh_token,e))throw jr(new Error,Xr.INVALID_TOKEN,Jr.UNAUTHORIZED);return t}a(zM,"validateRefreshToken")});var sR=I((Vpe,ZM)=>{"use strict";var x8=VM(),vc=require("passport"),B8=require("passport-local").Strategy,H8=require("passport-http").BasicStrategy,k8=require("util"),F8=$n(),XM=k8.callbackify(F8.findAndValidateUser),qpe=En(),G8=H(),JM=Xu();vc.use(new B8(function(e,t,r){XM(e,t,r)}));vc.use(new H8(function(e,t,r){XM(e,t,r)}));vc.serializeUser(function(e,t){t(null,e)});vc.deserializeUser(function(e,t){t(null,e)});function q8(e,t,r){if(e.raw?.user!==void 0)return r(null,e.raw.user);let n,s;if(e.headers?.authorization){let o=e.headers.authorization.split(" ");n=o[0],s=o[1]}function i(o,c){return o?r(o):c?r(null,c):r("Must login")}switch(a(i,"handleResponse"),n){case"Basic":vc.authenticate("basic",{session:!1},(o,c)=>{i(o,c)})(e,t,r);break;case"Bearer":e.body?.operation&&e.body.operation===G8.OPERATIONS_ENUM.REFRESH_OPERATION_TOKEN?JM.validateRefreshToken(s).then(o=>{e.body.refresh_token=s,r(null,o)}).catch(o=>{r(o)}):JM.validateOperationToken(s).then(o=>{r(null,o)}).catch(o=>{r(o)});break;default:vc.authenticate("local",{session:!1},function(o,c){i(o,c)})(e,t,r);break}}a(q8,"authorize");function V8(e,t){let r=x8(e);if(r){t(r);return}let n={authorized:!0,messages:[]},s=e.user.role;if(!s?.permission)return t("Invalid role");let i=JSON.parse(s.permission);if(i.super_user)return t(null,n);if(!i[e.schema])return n.authorized=!1,n.messages.push(`Not authorized to access ${e.schema} schema`),t(null,n);if(!i[e.schema].tables[e.table])return n.authorized=!1,n.messages.push(`Not authorized to access ${e.table} table`),t(null,n);if(!i[e.schema].tables[e.table][e.operation])return n.authorized=!1,n.messages.push(`Not authorized to access ${e.operation} on ${e.table} table`),t(null,n);if(i[e.schema].tables[e.table].attribute_permissions&&!e.attributes)return n.authorized=!1,n.messages.push(`${e.schema}.${e.table} has attribute permissions. Missing attributes to validate`),t(null,n);if(i[e.schema].tables[e.table].attribute_permissions&&e.attributes){let o=i[e.schema].tables[e.table].attribute_permissions;for(let c in o)e.attributes.indexOf(o[c].attribute_name)>-1&&!o[c][e.operation]&&(n.authorized=!1,n.messages.push(`Not authorized to ${e.operation} ${o[c].attribute_name} `))}return t(null,n)}a(V8,"checkPermissions");ZM.exports={authorize:q8,checkPermissions:V8}});var xc=I((Ype,eU)=>{"use strict";var iR=class{static{a(this,"Node")}constructor(t,r,n){this.name=t,this.subscriptions=r,this.system_info=n}},oR=class{static{a(this,"NodeSubscription")}constructor(t,r,n,s){this.schema=t,this.table=r,this.publish=n,this.subscribe=s}};eU.exports={Node:iR,NodeSubscription:oR}});var rU=I((Wpe,tU)=>{"use strict";var $8=H().OPERATIONS_ENUM,aR=class{static{a(this,"UpsertObject")}constructor(t,r,n,s=void 0){this.operation=$8.UPSERT,this.schema=t,this.table=r,this.records=n,this.__origin=s}};tU.exports=aR});var Zu=I((zpe,nU)=>{"use strict";var cR=class{static{a(this,"RemotePayloadObject")}constructor(t,r,n,s){this.operation=t,this.node_name=r,this.subscriptions=n,this.system_info=s}},lR=class{static{a(this,"RemotePayloadSubscription")}constructor(t,r,n,s,i,o,c){this.schema=t,this.table=r,this.hash_attribute=n,this.publish=s,this.subscribe=i,this.start_time=o,c!==void 0&&(this.attributes=c)}};nU.exports={RemotePayloadObject:cR,RemotePayloadSubscription:lR}});var iU=I((Jpe,sU)=>{"use strict";var uR=class{static{a(this,"TableSizeObject")}constructor(t,r,n=0,s=0,i=0,o=0){this.schema=t,this.table=r,this.table_size=n,this.record_count=s,this.transaction_log_size=i,this.transaction_log_record_count=o}};sU.exports=uR});var aU=I((nSe,oU)=>{"use strict";var Y8=iU(),Zpe=Ft(),eSe=ft(),K8=X(),{getSchemaPath:tSe,getTransactionAuditStorePath:rSe}=ht(),{getDatabases:W8}=(Ne(),ae(it));oU.exports=Q8;async function Q8(e){let t=new Y8;try{let r=W8()[e.schema]?.[e.name],n=r.primaryStore.getStats(),s=r.auditStore?.getStats();t.schema=e.schema,t.table=e.name,t.record_count=n.entryCount,t.transaction_log_record_count=s.entryCount}catch(r){K8.warn(`unable to stat table dbi due to ${r}`)}return t}a(Q8,"lmdbGetTableSize")});var lU=I((iSe,cU)=>{"use strict";var dR=class{static{a(this,"SystemInformationObject")}constructor(t,r,n,s,i,o,c){this.system=t,this.time=r,this.cpu=n,this.memory=s,this.disk=i,this.network=o,this.harperdb_processes=c}};cU.exports=dR});var Bc=I((dSe,_U)=>{"use strict";var z8=require("fs-extra"),j8=require("path"),xr=require("systeminformation"),Eo=X(),uU=or(),aSe=Pt(),ME=H(),J8=aU(),X8=Zi(),{getThreadInfo:dU}=at(),AR=ie();AR.initSync();var Z8=lU(),{openEnvironment:cSe}=ft(),{getSchemaPath:lSe}=ht(),{database:uSe,databases:fR}=(Ne(),ae(it)),PE;_U.exports={getHDBProcessInfo:mR,getNetworkInfo:SR,getDiskInfo:pR,getMemoryInfo:hR,getCPUInfo:ER,getTimeInfo:_R,getSystemInformation:TR,systemInformation:e6,getTableSize:gR,getMetrics:RR};function _R(){return xr.time()}a(_R,"getTimeInfo");async function ER(){try{let{family:e,model:t,stepping:r,revision:n,voltage:s,speedmin:i,speedmax:o,governor:c,socket:l,cache:d,...u}=await xr.cpu();u.cpu_speed=await xr.cpuCurrentSpeed();let{raw_currentload:f,raw_currentload_idle:E,raw_currentload_irq:_,raw_currentload_nice:h,raw_currentload_system:p,raw_currentload_user:S,cpus:g,...T}=await xr.currentLoad();return T.cpus=[],g.forEach(A=>{let{raw_load:N,raw_load_idle:V,raw_load_irq:v,raw_load_nice:J,raw_load_system:$,raw_load_user:F,...ne}=A;T.cpus.push(ne)}),u.current_load=T,u}catch(e){return Eo.error(`error in getCPUInfo: ${e}`),{}}}a(ER,"getCPUInfo");async function hR(){try{let{buffers:e,cached:t,slab:r,buffcache:n,...s}=await xr.mem();return Object.assign(s,process.memoryUsage())}catch(e){return Eo.error(`error in getMemoryInfo: ${e}`),{}}}a(hR,"getMemoryInfo");async function mR(){let e={core:[],clustering:[]};try{let t=await xr.processes(),r;try{r=Number.parseInt(await z8.readFile(j8.join(AR.get(ME.CONFIG_PARAMS.ROOTPATH),ME.HDB_PID_FILE),"utf8"))}catch(n){if(n.code===ME.NODE_ERROR_CODES.ENOENT)Eo.warn("Unable to locate 'hdb.pid' file, try stopping and starting HarperDB. This could be because HarperDB is not running.");else throw n}t.list.forEach(n=>{n.pid===r?e.core.push(n):n.name==="nats-server"&&e.clustering.push(n)});for(let n of e.core)for(let s of t.list)s.pid===n.parentPid&&(s.name==="PM2"||s.command==="PM2")&&(n.parent="PM2");return e}catch(t){return Eo.error(`error in getHDBProcessInfo: ${t}`),e}}a(mR,"getHDBProcessInfo");async function pR(){let e={};try{let{rIO_sec:t,wIO_sec:r,tIO_sec:n,ms:s,...i}=await xr.disksIO();e.io=i;let{rx_sec:o,tx_sec:c,wx_sec:l,...d}=await xr.fsStats();return e.read_write=d,e.size=await xr.fsSize(),e}catch(t){return Eo.error(`error in getDiskInfo: ${t}`),e}}a(pR,"getDiskInfo");async function SR(){let e={default_interface:null,latency:{},interfaces:[],stats:[],connections:[]};try{return e.default_interface=await xr.networkInterfaceDefault(),e.latency=await xr.inetChecksite("google.com"),(await xr.networkInterfaces()).forEach(n=>{let{internal:s,virtual:i,mtu:o,dhcp:c,dnsSuffix:l,ieee8021xAuth:d,ieee8021xState:u,carrier_changes:f,...E}=n;e.interfaces.push(E)}),(await xr.networkStats()).forEach(n=>{let{rx_sec:s,tx_sec:i,ms:o,...c}=n;e.stats.push(c)}),e}catch(t){return Eo.error(`error in getNetworkInfo: ${t}`),e}}a(SR,"getNetworkInfo");async function TR(){if(PE!==void 0)return PE;let e={};try{let{codepage:t,logofile:r,serial:n,build:s,servicepack:i,uefi:o,...c}=await xr.osInfo();e=c;let l=await xr.versions("node, npm");return e.node_version=l.node,e.npm_version=l.npm,PE=e,PE}catch(t){return Eo.error(`error in getSystemInformation: ${t}`),e}}a(TR,"getSystemInformation");async function gR(){let e=[],t=await X8.describeAll();for(let r of Object.values(t))for(let n of Object.values(r))e.push(await J8(n));return e}a(gR,"getTableSize");async function RR(){let e={};for(let t in fR){let r=e[t]={},n=r.tables={};for(let s in fR[t])try{let i=fR[t][s];r.readers||(Object.assign(r,i.primaryStore.rootStore.getStats()),delete r.root,r.readers=i.primaryStore.rootStore.readerList().split(/\n\s+/).slice(1).map(l=>{let[d,u,f]=l.trim().split(" ");return{pid:d,thread:u,txnid:f}}),i.primaryStore.auditStore&&(r.audit=i.auditStore.getStats()));let o=i.primaryStore.getStats(),c={};for(let l of["treeDepth","treeBranchPageCount","treeLeafPageCount","entryCount","overflowPages"])c[l]=o[l];n[s]=c}catch(i){Eo.notify(`Error getting stats for table ${s}: ${i}`)}}return e}a(RR,"getMetrics");async function fU(){if(AR.get(ME.CONFIG_PARAMS.CLUSTERING_ENABLED)){let{jsm:e}=await uU.getNATSReferences(),t=await uU.listStreams(),r=[];for(let n of t){let s=[],i=await e.consumers.list(n.config.name);for await(let c of i)s.push({name:c.name,created:c.created,num_ack_pending:c.num_ack_pending,num_redelivered:c.num_redelivered,num_waiting:c.num_waiting,num_pending:c.num_pending});let o={stream_name:n.config.name,database:n.config.subjects[0].split(".")[1],table:n.config.subjects[0].split(".")[2],state:n.state,consumers:s};r.push(o)}return r}}a(fU,"getNatsStreamInfo");async function e6(e){let t=new Z8;if(!Array.isArray(e.attributes)||e.attributes.length===0)return t.system=await TR(),t.time=_R(),t.cpu=await ER(),t.memory=await hR(),t.disk=await pR(),t.network=await SR(),t.harperdb_processes=await mR(),t.table_size=await gR(),t.metrics=await RR(),t.threads=await dU(),t.replication=await fU(),t;for(let r=0;r<e.attributes.length;r++)switch(e.attributes[r]){case"system":t.system=await TR();break;case"time":t.time=_R();break;case"cpu":t.cpu=await ER();break;case"memory":t.memory=await hR();break;case"disk":t.disk=await pR();break;case"network":t.network=await SR();break;case"harperdb_processes":t.harperdb_processes=await mR();break;case"table_size":t.table_size=await gR();break;case"database_metrics":case"metrics":t.metrics=await RR();break;case"threads":t.threads=await dU();break;case"replication":t.replication=await fU();break;default:break}return t}a(e6,"systemInformation")});var ed=I((_Se,t6)=>{t6.exports={name:"harperdb",version:"4.4.0-alpha.1",description:"HarperDB is a distributed database, caching service, streaming broker, and application development platform focused on performance and ease of use.",keywords:["database","nosql","api","distributed","broker","mqtt","real-time","enterprise","Fastify","NATS","HarperDB","Harper","clustering","replication","REST","WebSockets","decentralized","server-sent events","document store"],main:"harperdb.js",bin:{harperdb:"./bin/harperdb.js"},engines:{"minimum-node":"16.0.0","go-lang":"1.21.7","nats-server":"2.10.11"},exports:{".":"./index.js"},homepage:"https://www.harperdb.io/",bugs:"support@harperdb.io",author:{name:"HarperDB",email:"support@harperdb.io"},license:"SEE LICENSE IN LICENSE",scripts:{submodules:"git submodule update --init --recursive",build:"eslint -c ./.eslintbuild bin/ dataLayer/ security/ server/ sqlTranslator/ upgrade/ utility/ validation/",pretty:"eslint --fix bin/ dataLayer/ security/ server/ sqlTranslator/ upgrade/ utility/ validation/","cover:test":"pm2 kill && rimraf ./.nyc_output/* && node utility/devops/register.js --reset_license && nyc --no-clean --reporter=lcovonly npm run test:replication && nyc --no-clean --reporter=lcovonly npm run test:apitests && nyc --no-clean --reporter=lcovonly npm run test:resources && nyc --no-clean --reporter=lcovonly npm run test:logging && nyc --no-clean --reporter=lcovonly npm run test:upgrade && nyc --no-clean --reporter=lcovonly npm run test:nats && nyc --no-clean --reporter=lcovonly npm run test:cfserver && nyc --no-clean --reporter=lcovonly npm run test:hdbserver && nyc --no-clean --reporter=lcovonly npm run test:bin && nyc --no-clean --reporter=lcovonly npm run test:main && nyc --no-clean --reporter=lcovonly npm run test:security && nyc merge .nyc_output coverage.json && node ./utility/devops/register.js --reset_license",test:"pm2 kill && rimraf ./.nyc_output/* && node utility/devops/register.js --reset_license && npm run test:replication && npm run test:apitests && npm run test:resources && npm run test:logging && npm run test:upgrade && npm run test:nats && npm run test:cfserver && npm run test:hdbserver && npm run test:bin && npm run test:main && npm run test:security && nyc merge .nyc_output coverage.json && node ./utility/devops/register.js --reset_license","test:resources":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/resources/**/*.js' --config '../unitTests/.mocharc.json'","test:bin":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/bin/**/*.js' --config '../unitTests/.mocharc.json'","test:main":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/**/*.js' --config '../unitTests/.mocharc-main.json'","test:lmdbbridge":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/dataLayer/harperBridge/lmdbBridge/**/*.js' --config '../unitTests/.mocharc.json'","test:lmdbutility":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/utility/lmdb/**/*.js' --config '../unitTests/.mocharc.json'","test:hdbserver":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/server/harperdb/hdbServer-test.js' --config '../unitTests/.mocharc.json'","test:cfserver":"npm run submodules && cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/server/fastifyRoutes/customFunctionsServer-test.js' --config '../unitTests/.mocharc.json'","test:nats":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/server/nats/**/*.js' --config '../unitTests/.mocharc.json'","test:upgrade":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/upgrade/**/*.js' --config '../unitTests/.mocharc.json'","test:apitests":"pm2 kill && cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/apiTests/**/*-test.mjs' --config '../unitTests/.mocharc.json'","test:logging":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/utility/logging/*.js' --config '../unitTests/.mocharc.json'","test:ci":" cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/**/*.js' --retries 3 --config '../unitTests/.mocharc-main.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/dataLayer/harperBridge/lmdbBridge/**/*.js' --parallel --retries 3 --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/utility/lmdb/**/*.js' --parallel --retries 3 --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/server/harperdb/hdbServer-test.js' --parallel --retries 3 --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/server/customFunctions/customFunctionsServer-test.js' --parallel --retries 3 --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/upgrade/**/*.js' --parallel --retries 3 --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/server/nats/**/*.js' --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter","test:security":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/security/**/*.js' --config '../unitTests/.mocharc.json'","test:replication":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/server/replication/**/*.js' --config '../unitTests/.mocharc.json'","hdb-check":"./utility/devops/hdb-check.sh","download-prebuilds":"node ./utility/devops/build/download-prebuilds.js",prebuild:"date",postinstall:"node ./launchServiceScripts/launchInstallNATSServer.js",build_nats_dependency:"node ./utility/devops/nats/builder.js",coverage:"nyc --reporter=lcov npm test"},dependencies:{"@aws-sdk/client-s3":"3.635.0","@aws-sdk/lib-storage":"3.635.0","@endo/static-module-record":"^1.0.4","@fastify/autoload":"5.10.0","@fastify/compress":"~6.5.0","@fastify/cors":"~9.0.1","@fastify/static":"~7.0.4","@turf/area":"6.5.0","@turf/boolean-contains":"6.5.0","@turf/boolean-disjoint":"6.5.0","@turf/boolean-equal":"6.5.0","@turf/circle":"6.5.0","@turf/difference":"6.5.0","@turf/distance":"6.5.0","@turf/helpers":"6.5.0","@turf/length":"6.5.0",alasql:"4.1.10","cbor-x":"1.6.0",chalk:"4.1.2","cli-progress":"3.12.0",clone:"2.1.2","fast-glob":"3.3.2",fastify:"~4.28.1","fastify-plugin":"~4.5.1","fs-extra":"11.2.0",graphql:"^16.9.0","gunzip-maybe":"1.4.2","human-readable-ids":"1.0.4",inquirer:"8.2.6","is-number":"7.0.0",joi:"17.12.2","json-bigint-fixes":"1.1.0",json2csv:"5.0.7",jsonata:"1.8.7",jsonwebtoken:"9.0.2",lmdb:"3.0.14",lodash:"4.17.21",mathjs:"11.12.0",minimist:"1.2.8",moment:"2.30.1","mqtt-packet":"~9.0.0",msgpackr:"1.11.0",nats:"2.19.0",needle:"3.3.1","node-forge":"^1.3.1","node-stream-zip":"1.15.0","node-unix-socket":"0.2.5","normalize-path":"^3.0.0",ora:"5.4.1","ordered-binary":"1.5.1",papaparse:"5.4.1",passport:"0.6.0","passport-http":"0.3.0","passport-local":"1.0.0",pino:"8.16.0",pm2:"5.4.1",prompt:"1.3.0","properties-reader":"2.3.0","recursive-iterator":"3.3.0",semver:"7.5.4",send:"^0.18.0","serve-static":"1.15.0",ses:"1.1.0","stream-chain":"2.2.5","stream-json":"1.8.0",systeminformation:"5.23.5","tar-fs":"3.0.6",ulidx:"0.5.0",uuid:"10.0.0","validate.js":"0.13.1",ws:"8.18.0",yaml:"2.5.0"},devDependencies:{"@tsconfig/node16":"^1.0.3","@types/node":"20.14.8","@typescript-eslint/eslint-plugin":"^5.55.0","@typescript-eslint/parser":"^5.55.0",axios:"1.7.5",chai:"4.4.1","chai-integer":"0.1.0",esbuild:"^0.20.2",eslint:"8.22.0","eslint-config-prettier":"8.3.0","eslint-plugin-prettier":"3.4.1","eslint-plugin-radar":"0.2.1",eventsource:"^2.0.2","hook-std":"3.0.0","intercept-stdout":"0.1.2",mkcert:"1.5.1",mocha:"^10.3.0","mocha-teamcity-reporter":"3.0.0","mock-require":"3.0.3","mock-stdin":"1.0.0",mqtt:"~4.3.8",newman:"6.1.3","node-fetch":"2.6.7",nyc:"15.1.0",prettier:"2.8.4",rewire:"5.0.0",rimraf:"3.0.2",sinon:"10.0.0","sinon-chai":"3.7.0","source-map-support":"^0.5.21",typescript:"^5.4.2","why-is-node-still-running":"^1.0.0"},overrides:{"eslint-plugin-radar":{eslint:"8.22.0"},alasql:{xlsx:"0.18.5"}},optionalDependencies:{bufferutil:"^4.0.7","segfault-handler":"^1.3.0","utf-8-validate":"^5.0.10"}}});var vE=I((ESe,EU)=>{"use strict";EU.exports={version:r6,printVersion:n6};var UE=ed();function r6(){if(UE)return UE.version}a(r6,"version");function n6(){UE&&console.log(`HarperDB Version ${UE.version}`)}a(n6,"printVersion")});var Ri=I((SSe,SU)=>{"use strict";var s6=qn(),bR=re(),i6=require("util"),ua=H(),hU=ie();hU.initSync();var o6=sR(),mU=gn(),{Node:mSe,NodeSubscription:pSe}=xc(),a6=yc(),c6=rU(),{RemotePayloadObject:l6,RemotePayloadSubscription:u6}=Zu(),{handleHDBError:d6,hdb_errors:f6}=ce(),{HTTP_STATUS_CODES:_6,HDB_ERROR_MSGS:E6}=f6,h6=Gs(),m6=Bc(),p6=vE(),{getDatabases:S6}=(Ne(),ae(it)),T6=i6.promisify(o6.authorize),g6=mU.searchByHash,R6=mU.searchByValue;SU.exports={authHeaderToUser:A6,isEmpty:b6,getNodeRecord:y6,upsertNodeRecord:O6,buildNodePayloads:N6,checkClusteringEnabled:I6,getAllNodeRecords:w6,getSystemInfo:C6,reverseSubscription:pU};async function A6(e){let t={headers:{authorization:e.hdb_auth_header}};return e.hdb_user=await T6(t,null),e}a(A6,"authHeaderToUser");function b6(e){return e==null}a(b6,"isEmpty");async function y6(e){let t=new a6(ua.SYSTEM_SCHEMA_NAME,ua.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[e],["*"]);return g6(t)}a(y6,"getNodeRecord");async function O6(e){let t=new c6(ua.SYSTEM_SCHEMA_NAME,ua.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[e]);return s6.upsert(t)}a(O6,"upsertNodeRecord");function pU(e){if(bR.isEmpty(e.subscribe)||bR.isEmpty(e.publish))throw new Error("Received invalid subscription object");let{schema:t,table:r,hash_attribute:n}=e,s={schema:t,table:r,hash_attribute:n};return e.subscribe===!0&&e.publish===!1?(s.subscribe=!1,s.publish=!0):e.subscribe===!1&&e.publish===!0?(s.subscribe=!0,s.publish=!1):(s.subscribe=e.subscribe,s.publish=e.publish),s}a(pU,"reverseSubscription");function N6(e,t,r,n){let s=[];for(let i=0,o=e.length;i<o;i++){let c=e[i],{schema:l,table:d}=c,u=bR.getTableHashAttribute(l,d),{subscribe:f,publish:E}=pU(c),_=S6()[l]?.[d],h=new u6(l,d,u,E,f,c.start_time,_.schemaDefined?_.attributes:void 0);s.push(h)}return new l6(r,t,s,n)}a(N6,"buildNodePayloads");function I6(){if(!hU.get(ua.CONFIG_PARAMS.CLUSTERING_ENABLED))throw d6(new Error,E6.CLUSTERING_NOT_ENABLED,_6.BAD_REQUEST,void 0,void 0,!0)}a(I6,"checkClusteringEnabled");async function w6(){let e=new h6(ua.SYSTEM_SCHEMA_NAME,ua.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,"name","*",void 0,["*"]);return Array.from(await R6(e))}a(w6,"getAllNodeRecords");async function C6(){let e=await m6.getSystemInformation();return{hdb_version:p6.version(),node_version:e.node_version,platform:e.platform}}a(C6,"getSystemInfo")});var yR=I((gSe,NU)=>{"use strict";var xE=or(),TU=re(),gU=Pt(),RU=H(),BE=X(),AU=bE(),D6=ng(),{RemotePayloadObject:L6}=Zu(),{handleHDBError:bU,hdb_errors:P6}=ce(),{HTTP_STATUS_CODES:yU}=P6,{NodeSubscription:OU}=xc();NU.exports=M6;async function M6(e,t){let r;try{r=await xE.request(`${t}.${gU.REQUEST_SUFFIX}`,new L6(RU.OPERATIONS_ENUM.DESCRIBE_ALL,t,void 0,void 0)),BE.trace("Response from remote describe all request:",r)}catch(o){BE.error(`addNode received error from describe all request to remote node: ${o}`);let c=xE.requestErrorHandler(o,"add_node",t);throw bU(new Error,c,yU.INTERNAL_SERVER_ERROR,"error",c)}if(r.status===gU.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let o=`Error returned from remote node ${t}: ${r.message}`;throw bU(new Error,o,yU.INTERNAL_SERVER_ERROR,"error",o)}let n=r.message,s=[],i=[];for(let o of e){let{table:c}=o,l=o.database??o.schema??"data";if(l===RU.SYSTEM_SCHEMA_NAME){await xE.createLocalTableStream(l,c);let h=new OU(l,c,o.publish,o.subscribe);h.start_time=o.start_time,i.push(h);continue}let d=TU.doesSchemaExist(l),u=n[l]!==void 0,f=c?TU.doesTableExist(l,c):!0,E=c?n?.[l]?.[c]!==void 0:!0;if(!d&&!u||!f&&!E){s.push(o);continue}if(!d&&u&&(BE.trace(`addNode creating schema: ${l}`),await AU.createSchema({operation:"create_schema",schema:l})),!f&&E){BE.trace(`addNode creating table: ${c} in schema: ${l} with attributes ${JSON.stringify(n[l][c].attributes)}`);let h=new D6(l,c,n[l][c].hash_attribute);n[l][c].attributes&&(h.attributes=n[l][c].attributes),await AU.createTable(h)}await xE.createLocalTableStream(l,c);let _=new OU(l,c,o.publish,o.subscribe);_.start_time=o.start_time,i.push(_)}return{added:i,skipped:s}}a(M6,"reviewSubscriptions")});var td=I(kE=>{var HE=X();for(let e of["trace","debug","info","warn","error","fatal","notify"])HE.logsAtLevel(e)&&(kE[e]=HE[e]);kE.loggerWithTag=e=>HE.loggerWithTag(e,!0);kE.setLogLevel=HE.setLogLevel});function OR(e){let t=e.idMapping;if(!t){let r=e.get(Symbol.for("remote-ids"));e.idMapping=t=r?(0,Hc.unpack)(r):null}return t||(t={nodeName:ot(),remoteNameToId:{[ot()]:0}},e.putSync(Symbol.for("remote-ids"),(0,Hc.pack)(t))),t}function rd(e){return OR(e).remoteNameToId}function wU(e,t,r){let n=OR(r),s=n.remoteNameToId,i=new Map,o=!1;t[e]=0;for(let c in t){let l=t[c],d=s[c];if(d==null){let u=0;for(let f in s){let E=s[f];E>u&&(u=E)}d=u+1,s[c]=d,o=!0}i.set(l,d)}return o&&r.putSync(Symbol.for("remote-ids"),(0,Hc.pack)(n)),i}function NR(e,t){let r=OR(t),n=r.remoteNameToId,s=n[e];if(s==null){let i=0;for(let o in n){let c=n[o];c>i&&(i=c)}s=i+1,n[e]=s,t.putSync(Symbol.for("remote-ids"),(0,Hc.pack)(r))}return IU.info?.("The remote node name map",e,n,s),s}var IU,Hc,IR=Oe(()=>{IU=U(td());Ai();Hc=require("msgpackr");a(OR,"getIdMappingRecord");a(rd,"exportIdMapping");a(wU,"remoteToLocalNodeId");a(NR,"getIdOfRemoteNode")});var CU={};Ze(CU,{Resources:()=>FE,keyArrayToString:()=>kc,resetResources:()=>U6,resources:()=>ho});function U6(){return ho=new FE}function kc(e){return Array.isArray(e)?e[e.length-1]===null?e.slice(0,-1).join("/")+"/":e.join("/"):e}var FE,ho,nd=Oe(()=>{oa();FE=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)throw new Error(`Conflicting paths for ${t}`);super.set(t,i);for(let[c,l]of this){let d=2;for(;(d=c.indexOf("/",d))>-1;){let u=this.get(c.slice(0,d));u&&(u.hasSubPaths=!0),d+=2}}}getMatch(t,r){let n=2,s;for(;(n=t.indexOf("/",n))>-1;){let c=t.slice(0,n),l=this.get(c);if(l&&(!r||l.exportTypes?.[r]!==!1)){if(l.relativeURL=t.slice(n),!l.hasSubPaths)return l;s=l}n+=2}if(s)return s;let i=t.indexOf("?"),o=i>-1?t.slice(0,i):t;return s=this.get(o),s&&(!r||s.exportTypes?.[r]!==!1)?s.relativeURL=i>-1?t.slice(i):"":s||(s=this.get(""),s&&(!r||s.exportTypes?.[r]!==!1)&&(t[0]!=="/"&&(t="/"+t),s.relativeURL=t)),s}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 Tt(r,async()=>{let s=this.getMatch(t);if(s)return t=s.relativeURL,n(s.Resource,s.path,t)})}setRepresentation(t,r,n){}};a(U6,"resetResources");a(kc,"keyArrayToString")});function DR(e,t,r,n,s){let i=e.primaryStore.env.path,o=e.primaryStore.tableId,c;s?.crossThreads===!1?(c=LU,v6(e.primaryStore,e.auditStore)):(c=DU,e.primaryStore.env.hasSubscriptionCommitListener||(e.primaryStore.env.hasSubscriptionCommitListener=!0,e.primaryStore.on("committed",()=>{PU(DU[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 d=l[o];d||(d=l[o]=new Map,d.envs=l,d.tableId=o,d.store=e.primaryStore),t=kc(t);let u=new CR(r);u.startTime=n;let f=d.get(t);return f?f.push(u):(d.set(t,f=[u]),f.tables=d,f.key=t),u.subscriptions=f,u}function PU(e){if(!e)return;let t=e.auditStore;t.resetReadTxn(),MU(e.auditStore);let r;for(let{key:n,value:s}of t.getRange({start:e.lastTxnTime,exclusiveStart:!0})){e.lastTxnTime=n;let i=Lt(s),o=e[i.tableId];if(!o)continue;let c=i.recordId,l=kc(c),d=0;do{let u=o.get(l);if(u){for(let E of u)if(!(d>0&&!(E.includeDescendants&&!(E.onlyChildren&&d>1)))){if(E.startTime>=n){(0,wR.info)("omitting",c,E.startTime,n);continue}try{let _;E.supportsTransactions&&E.txnInProgress!==i.version&&(_=!0,E.txnInProgress||(r?r.push(E):r=[E]),E.txnInProgress=i.version),E.listener(c,i,n,_)}catch(_){console.error(_),(0,wR.info)(_)}}}if(l==null)break;let f=l.lastIndexOf?.("/",l.length-2);f>-1?l=l.slice(0,f):l=null,d++}while(!0)}if(r)for(let n of r)n.txnInProgress=null,n.listener(null,{type:"end_txn"},e.lastTxnTime,!0)}function v6(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=LU[s];if(!l)return;let d=a(()=>{r.threadLocalWrites||(r.threadLocalWrites=new Float64Array(r.getUserSharedBuffer("last-thread-local-write",new ArrayBuffer(8)))),l.txnTime=r.threadLocalWrites[0]||Date.now();try{PU(l)}finally{r.threadLocalWrites[0]=l.lastTxnTime,r.unlock("thread-local-writes")}},"acquiredLock");r.attemptLock("thread-local-writes",d)&&d()})}}function MU(e){e.nextTransaction?.resolve();let t;e.nextTransaction=new Promise(r=>{t=r}),e.nextTransaction.resolve=t}function UU(e){return e.nextTransaction||(DR({primaryStore:e,auditStore:e},null,null,0,{scope:"full-database"}),MU(e)),e.nextTransaction}var wR,DU,LU,CR,LR=Oe(()=>{wR=U(X());ic();nd();_i();DU=Object.create(null),LU=Object.create(null);a(DR,"addSubscription");CR=class extends mn{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(PU,"notifyFromTransactionData");a(v6,"listenToCommits");a(MU,"nextTransaction");a(UU,"whenNextTransaction")});function Br(){return vU||(vU=dt({table:"hdb_nodes",database:"system",attributes:[{name:"name",isPrimaryKey:!0},{attribute:"subscriptions"},{attribute:"system_info"},{attribute:"url"},{attribute:"routes"},{attribute:"ca"},{attribute:"replicates"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]}))}function id(e){Br().subscribe({}).then(async t=>{for await(let r of t){let n=r?.value?.name;server.nodes=server.nodes.filter(s=>s!==n),r.type==="put"&&n!==ot()&&server.nodes.push(n),(r.type==="put"||r.type==="delete")&&e(r.value,r.id)}})}function GE(e,t){return(e.replicates===!0||e.replicates?.sends)&&databases[t]&&Br().primaryStore.get(ot())?.replicates||e.subscriptions?.some(r=>(r.database||r.schema)===t&&r.subscribe)}function x6(){id(e=>{mo({},(t,r)=>{let n=e.name,s=xU.get(n);if(s||xU.set(n,s=new Map),s.has(r))return;let i;for(let o in t)if(i=t[o].auditStore,i)break;if(i){let o=new Float64Array(i.getUserSharedBuffer(["replicated",r,n],new ArrayBuffer(8),{callback:()=>{let c=o[0],l=o.lastTime;for(let{txnTime:d,onConfirm:u}of sd.get(r)||[])d>l&&d<=c&&u();o.lastTime=c}}));o.lastTime=0,s.set(r,o)}})})}function*qE(e){for(let t of e.routes||[]){let r=t.url,n;if(typeof t=="string"?t.includes("://")?r=t:n=t:n=t.hostname??t.host,n&&!r){let s=Fc.default.get(Gc.CONFIG_PARAMS.REPLICATION_SECUREPORT)??(!Fc.default.get(Gc.CONFIG_PARAMS.REPLICATION_PORT)&&Fc.default.get(Gc.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_SECUREPORT)),i;(i=n.match(/:(\d+)$/)?.[1])?n=n.slice(0,-i[0].length-1):t.port?i=t.port:i=s||Fc.default.get(Gc.CONFIG_PARAMS.REPLICATION_PORT)||Fc.default.get(Gc.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_PORT);let o=i?.lastIndexOf?.(":");o>0&&(i=+i.slice(o+1).replace(/[\[\]]/g,"")),r=(s?"wss://":"ws://")+n+":"+i}if(!r){BU.isMainThread&&console.error("Invalid route, must specify a url or host (with port)");continue}yield{url:r,subscription:t.subscriptions,routes:t.routes}}}var BU,Fc,Gc,vU,xU,sd,od=Oe(()=>{Ne();Ai();fE();BU=require("worker_threads"),Fc=U(ie()),Gc=U(H());server.nodes=[];a(Br,"getHDBNodeTable");a(id,"subscribeToNodeUpdates");a(GE,"shouldReplicateToNode");xU=new Map;TP((e,t,r)=>{sd||(sd=new Map,x6());let n=sd.get(e);return n||sd.set(e,n=[]),new Promise(s=>{let i=0;n.push({txnTime:t,onConfirm:()=>{++i===r&&s()}})})});a(x6,"startSubscriptionToReplications");a(qE,"iterateRoutes")});var kU={};Ze(kU,{connectedToNode:()=>fa,disconnectedFromNode:()=>Vc,ensureNode:()=>yi,requestClusterStatus:()=>HU,startOnMainThread:()=>MR});async function MR(e){let t=[],r,n=0;Ys.whenThreadsStarted.then(async()=>{let o=[];for await(let c of ct().system.hdb_nodes.search([]))o.push(c);for(let c of qE(e))try{let l=!c.subscriptions;if(l){let u=ot();Br().primaryStore.get(u)===void 0&&await yi(u,{name:u,url:e.url??po(),replicates:!0})}let d=c.trusted!==!1;if(l&&c.replicates==null&&(c.replicates=!0),o.find(u=>u.url===c.url))continue;i(c)}catch(l){console.error(l)}id(i)});let s;function i(o,c=o?.name){let l=ot()&&c===ot()||po()&&o?.url===po();if(l){let E=!!o?.replicates;if(s!==void 0&&s!==E)for(let _ of Br().search([]))_.replicates&&_.name!==c&&i(_,_.name);s=E}if(Tr.trace("Setting up node replication for",o),!o){for(let[E,_]of bi){let h;for(let[p,{worker:S,nodes:g}]of _){let T=g[0];if(T&&T.name==c){h=!0;for(let[A,{worker:N}]of _)_.delete(A),N?.postMessage({type:"unsubscribe-from-node",node:c,database:A,url:E});break}}if(h){bi.get(E).iterator.remove(),bi.delete(E);return}}return}if(l)return;if(!o.url){Tr.info(`Node ${o.name} is missing url`);return}let d=bi.get(o.url);if(d&&d.iterator.remove(),!(o.replicates===!0||o.replicates?.sends)&&!o.subscriptions?.length&&!d)return;if(Tr.info(`Added node ${o.name} at ${o.url} for process ${ot()}`),o.name){for(let[E,_]of da)if(o.url===_.url){da.delete(E);break}da.set(o.name,o)}let u=ct();if(d||(d=new Map,bi.set(o.url,d)),d.iterator=mo(e,(E,_,h)=>{h?f(_,!0):f(_,!1)}),o.subscriptions)for(let E of o.subscriptions){let _=E.database||E.schema;u[_]||(Tr.warn(`Database ${_} not found for node ${o.name}, making a subscription anyway`),f(_,!1))}function f(E,_){Tr.trace("Setting up replication for database",E,"on node",o.name);let h=d.get(E),p,S=[Object.assign({replicateByDefault:_},o)],g=GE(o,E),T=Ys.workers.filter(A=>A.name==="http");if(h?(p=h.worker,h.nodes=S):g&&(n=n%T.length,p=T[n++],d.set(E,{worker:p,nodes:S,url:o.url}),p?.on("exit",()=>{d.get(E)?.worker===p&&(d.delete(E),f(E,_))})),g)setTimeout(()=>{let A={type:"subscribe-to-node",database:E,nodes:S};p?p.postMessage(A):qc(A)},B6);else{Br().primaryStore.get(ot())?.replicates||(s=!1);let A={type:"unsubscribe-from-node",database:E,url:o.url};p?p.postMessage(A):$E(A)}}a(f,"onDatabase")}a(i,"onNodeUpdate"),Vc=a(function(o){let c=Array.from(da.keys()).sort(),l=c.indexOf(o.name||Ks(o.url));if(l===-1){Tr.warn("Disconnected node not found in node map",o.name,da.keys());return}let d=bi.get(o.url),u=d?.get(o.database);if(!u){Tr.warn("Disconnected node not found in replication map",o.database,d);return}if(u.connected=!1,o.finished)return;let f=u.nodes[0];if(!(f.replicates===!0||f.replicates?.sends||f.subscriptions?.length))return;let E=(l+1)%c.length;for(;l!==E;){let _=c[E],h=da.get(_);d=bi.get(h.url);let p=d?.get(o.database);if(!p){E=(E+1)%c.length;continue}let{worker:S,nodes:g}=p,T=!1;for(let A of u.nodes){if(g.some(N=>N.name===A.name)){Tr.info(`Disconnected node is already failing over to ${_} for ${o.database}`);continue}g.push(A),T=!0}if(!T)return;u.redirectingTo=p,Tr.info(`Failing over ${o.database} from ${o.name} to ${_}`),S?S.postMessage({type:"subscribe-to-node",database:o.database,nodes:g}):qc({database:o.database,nodes:g});break}},"disconnectedFromNode"),fa=a(function(o){let c=bi.get(o.url),l=c?.get(o.database);if(!l){Tr.warn("Connected node not found in replication map, this may be because the node is being removed",o.database,c);return}if(l.connected=!0,l.latency=o.latency,l.redirectingTo){let{worker:d,nodes:u}=l.redirectingTo,f=u.find(E=>E.name===o.name);l.redirectingTo=null,f&&(u.splice(u.indexOf(f),1),d?d.postMessage({type:"subscribe-to-node",database:o.database,nodes:u}):qc({database:o.database,nodes:u}))}},"connectedToNode"),(0,Ys.onMessageByType)("disconnected-from-node",Vc),(0,Ys.onMessageByType)("connected-to-node",fa),(0,Ys.onMessageByType)("request-cluster-status",HU)}function HU(e,t){let r=[];for(let[,n]of da)try{let s=bi.get(n.url),i=[];if(s){for(let[c,{worker:l,connected:d,nodes:u,latency:f}]of s)i.push({database:c,connected:d,latency:f,threadId:l?.threadId,nodes:u.map(E=>E.name)});let o=(0,PR.cloneDeep)(n);o.database_sockets=i,delete o.ca,delete o.node_name,delete o.__updatedtime__,delete o.__createdtime__,r.push(o)}}catch(s){Tr.warn("Error getting cluster status for",n?.url,s)}return t?.postMessage({type:"cluster-status",connections:r}),{connections:r}}async function yi(e,t){let r=Br();e=e??Ks(t.url),t.name=e;let n=r.primaryStore.get(e);if(Tr.info(`Ensuring node ${e} at ${t.url}, existing record:`,n),!n)await r.put(t);else{t.replicates&&(t.subscriptions=null);for(let s in t)if(n[s]!==t[s]&&s==="subscriptions"&&t[s]&&n[s]){let i=[],o=(0,PR.cloneDeep)(n[s]);for(let c of t[s]){let l=!1;for(let d of o)if((c.database??c.schema)===(d.database??d.schema)&&c.table===d.table){d.publish=c.publish,d.subscribe=c.subscribe,l=!0;break}l||i.push(c)}t.subscriptions=[...o,...i];break}Tr.info(`Updating node ${e} at ${t.url}`),await r.patch(t)}}var Ys,VE,Tr,PR,B6,bi,Vc,fa,da,ad=Oe(()=>{Ne();Ys=U(at());Ai();VE=require("worker_threads");od();Tr=U(X()),PR=require("lodash"),B6=200,bi=new Map,da=new Map;a(MR,"startOnMainThread");a(HU,"requestClusterStatus");VE.parentPort&&(Vc=a(e=>{VE.parentPort.postMessage(Object.assign({type:"disconnected-from-node"},e))},"disconnectedFromNode"),fa=a(e=>{VE.parentPort.postMessage(Object.assign({type:"connected-to-node"},e))},"connectedToNode"),(0,Ys.onMessageByType)("subscribe-to-node",e=>{qc(e)}),(0,Ys.onMessageByType)("unsubscribe-from-node",e=>{$E(e)}));a(yi,"ensureNode")});async function kR(e,t){let{authorization:r,rejectUnauthorized:n}=t||{},s=ot(),i;if(e.includes("wss://")){if(!vR){let l=(0,ev.createTLSSelector)("operations-api"),d={secureContexts:null};await l.initialize(d),vR=d.secureContexts}if(i=vR.get(s),i&&_e.debug?.("Creating web socket for URL",e,"with certificate named:",i.name),!i&&n!==!1)throw new Error("Unable to find a valid certificate to use for replication to connect to "+e)}let o={};r&&(o.Authorization=r);let c={headers:o,localAddress:s?.startsWith("127.0")?s:void 0,servername:(0,rv.isIP)(t?.serverName)?void 0:t?.serverName,noDelay:!0,highWaterMark:128*1024,ALPNProtocols:["http/1.1","harperdb-replication"],rejectUnauthorized:n!==!1,secureContext:void 0};return n!==!1&&i&&(c.secureContext=tv.createSecureContext(Object.assign({},i.options,{ca:Array.from(Ea)}))),new XU.WebSocket(e,"harperdb-replication-v1",c)}function jE(e,t,r){let n=t.port||t.securePort,s=HR.pid%1e3+"-"+ZU.threadId+(n?"s:"+n:"c:"+t.url?.slice(-4))+" "+Math.random().toString().slice(2,3),i=0,o=Buffer.allocUnsafeSlow(1024),c=0,l=new DataView(o.buffer,0,1024),d=t.database,u=t.databaseSubscriptions||_a,f,E,_=!1,h=t.subscription;h?.then&&h.then(te=>h=te);let p=t.tables||d&&ct()[d];if(!r){_e.error?.("No authorization provided"),dn(1008,"Unauthorized");return}let S=new Map,g=[],T=r.name;T&&t.connection&&(t.connection.nodeName=T);let A,N,V=JU.default.get("replication_url"),v,J,$,F;if(t.url){let te=a(()=>{$?e.terminate():($=performance.now(),e.ping())},"send_ping");v=setInterval(te,jU).unref(),te()}else ne();function ne(){clearTimeout(J),J=setTimeout(()=>{_e.warn?.(`Timeout waiting for ping from ${T}, terminating connection and reconnecting`),e.terminate()},jU*2).unref()}a(ne,"resetPingTimer"),d&&ve(d);let ee,Z,le=[],fe=[],je,ye=[],Ht=[],Bo=[],tc=150,Gr=0,Yl=0,Vi,$i,Cs,Ds,Ct;e.on("message",te=>{try{let me=te.dataView=new Yc(te.buffer,te.byteOffset,te.byteLength);if(te[0]>127){let Fe=(0,et.decode)(te),[tt,Ee,Dt]=Fe;switch(tt){case GU:{if(Ee){if(T){if(T!==Ee){_e.error?.(s,`Node name mismatch, expecting to connect to ${T}, but peer reported name as ${Ee}, disconnecting`),e.send((0,et.encode)([$c])),dn(1008,"Node name mismatch");return}}else if(T=Ee,t.connection?.tentativeNode){let x=t.connection.tentativeNode;x.name=T,t.connection.tentativeNode=null,yi(T,x)}if(t.connection&&(t.connection.nodeName=T),_e.info?.(s,"received node id",T,d),!d)try{ve(d=Fe[2]),d==="system"&&(ee=mo(t,(x,k)=>{Kl(k)&&Yi(k)}),e.on("close",()=>{ee?.remove()}))}catch(x){_e.warn?.(s,"Error setting database",x),e.send((0,et.encode)([$c])),dn(1008,x.message);return}_e.info?.(s,"setDatabase",d,p&&Object.keys(p)),e_()}break}case QU:{_e.info?.(s,"Received table definitions for",Ee.map(x=>x.table));for(let x of Ee){let k=Fe[2];x.database=k;let se;Kl(k)&&(k==="system"?Ve[k]?.[x.table]||(se=xR(x,Ve[k]?.[x.table])):se=xR(x,Ve[k]?.[x.table]),f||(f=se.auditStore),p||(p=ct()?.[k]))}break}case $c:dn();break;case YU:try{let x=r?.replicates||r?.subscribers||r?.name;server.operation(Ee,{user:r},!x).then(k=>{k.requestId=Ee.requestId,e.send((0,et.encode)([KE,k]))},k=>{e.send((0,et.encode)([KE,{requestId:Ee.requestId,error:k instanceof Error?k.toString():k}]))})}catch(x){e.send((0,et.encode)([KE,{requestId:Ee.requestId,error:x instanceof Error?x.toString():x}]))}break;case KE:let{resolve:q,reject:m}=S.get(Ee.requestId);Ee.error?m(new Error(Ee.error)):q(Ee),S.delete(Ee.requestId);break;case UR:let R=Fe[3];p||(d?_e.error?.(s,"No tables found for",d):_e.error?.(s,"Database name never received"));let w=p[R];w=xR({table:R,database:d,attributes:Ee.attributes,schemaDefined:Ee.schemaDefined},w),le[Dt]={name:R,decoder:new et.Packr({useBigIntExtension:!0,randomAccessStructure:!0,freezeData:!0,typedStructs:Ee.typedStructs,structures:Ee.structures}),getEntry(x){return w.primaryStore.getEntry(x)},rootStore:w.primaryStore.rootStore};break;case qU:Ct=f?wU(T,Ee,f):new Map,je=Fe[2],_e.info?.(s,`Acknowledged subscription request, receiving messages for nodes: ${je}`);break;case VU:let b=Dt;Bo[b]=Ee;break;case WU:let y=["replicated",d,T];E||(E=new Float64Array(f.getUserSharedBuffer(y,new ArrayBuffer(8)))),E[0]=Ee,_e.info?.(s,"received and broadcasting committed update",Ee),E.buffer.notify();break;case KU:A=Ee,h.send({type:"end_txn",localTime:A,remoteNodeIds:g});break;case $U:{let x=Ee,k;try{let se=Fe[3],ue=fe[Dt]||(fe[Dt]=p[Fe[4]]);if(!ue)return _e.warn?.("Unknown table id trying to handle record request",Dt);let pe=ue.primaryStore.getBinaryFast(Symbol.for("structures")),rt=pe.length;if(rt!==Yl){Yl=rt;let He=(0,et.decode)(pe);e.send((0,et.encode)([UR,{typedStructs:He.typed,structures:He.named},Dt,ue.tableName]))}let xe=ue.primaryStore.getBinaryFast(se);if(xe){let He=ue.primaryStore.decoder.decode(xe,{valueAsBuffer:!0});k=(0,et.encode)([YE,x,{value:He.value,expiresAt:He.expiresAt,version:He.version,residencyId:He.residencyId,nodeId:He.nodeId,user:He.user}])}else k=(0,et.encode)([YE,x])}catch(se){k=(0,et.encode)([YE,x,{error:se.message}])}e.send(k);break}case YE:{let{resolve:x,reject:k,tableId:se,key:ue}=S.get(Fe[1]),pe=Fe[2];if(pe?.error)k(new Error(pe.error));else if(pe){let rt=le[se].decoder.decode(pe.value);pe.value=rt,pe.key=ue,x(pe)}else x();S.delete(Fe[1]);break}case FU:Ds=Ee;let C,O,P=!1;if(h){if(d!==h.databaseName&&!h.then){_e.error?.("Subscription request for wrong database",d,h.databaseName);return}}else h=u.get(d);if(_e.info?.(s,"received subscription request for",d,"at",Ds),!h){let x;h=new Promise(k=>{_e.info?.("Waiting for subscription to database "+d),x=k}),h.ready=x,_a.set(d,h)}if(r.name)O=Br().subscribe(r.name),O.then(async x=>{C=x;for await(let k of C){let se=k.value;if(!(se?.replicates===!0||se?.replicates?.receives||se?.subscriptions?.some(ue=>(ue.database||ue.schema)===d&&ue.publish!==!1))){P=!0,e.send((0,et.encode)([$c])),dn(1008,`Unauthorized database subscription to ${d}`);return}}},x=>{_e.error?.(s,"Error subscribing to HDB nodes",x)});else if(!(r?.permissions?.super_user||r.replicates)){e.send((0,et.encode)([$c])),dn(1008,`Unauthorized database subscription to ${d}`);return}if(Cs&&(_e.info?.(s,"stopping previous subscription",d),Cs.emit("close")),Ds.length===0)return;let M,L=Ds[0],B=a(x=>{if(x&&(L.replicateByDefault?!L.tables.includes(x.tableName):L.tables.includes(x.tableName)))return M=x,{table:x}},"tableToTableEntry"),Y={txnTime:0},K,Te,j=1/0,Ie,he=a((x,k)=>{if(j=k,x.type==="end_txn"){Y.txnTime&&(o[i]!==66&&_e.error?.("Invalid encoding of message"),ui(9),ui(zE),Dr(Ie=k),De()),i=c,Y.txnTime=0;return}let se=x.nodeId,ue=x.tableId,pe=Te[ue];if(!pe&&(pe=Te[ue]=B(h.tableById[ue]),!pe))return _e.trace?.("Not subscribed to table",ue);let rt=pe.table,xe=rt.primaryStore,He=xe.encoder;if(x.extendedType&R_||!He.typedStructs){let Ki=x.getValue(xe,!0);JSON.stringify(Ki)}if(K[se]>=k)return cd&&_e.info?.(s,"skipping replication update",x.recordId,"to:",T,"from:",se,"subscribed:",K),di();cd&&_e.info?.(s,"sending replication update",x.recordId,"to:",T,"from:",se,"subscribed:",K);let nt=x.version;Y.txnTime!==nt&&(Y.txnTime&&(cd&&_e.info?.(s,"new txn time, sending queued txn",Y.txnTime),o[i]!==66&&_e.error?.("Invalid encoding of message"),De()),Y.txnTime=nt,i=c,Dr(nt));let tr=x.residencyId,kt=t_(tr,rt),fn;if(kt&&!kt.includes(T)){let Ki=t_(x.previousResidencyId,rt);if(Ki&&!Ki.includes(T)&&(x.type==="put"||x.type==="patch")||rt.getResidencyById)return di();let Wl=x.recordId;_e.info?.(s,"sending invalidation",Wl,T,"from",se);let qp=0;tr&&(qp|=qo),x.previousResidencyId&&(qp|=Vo);let Vp,r_=null;for(let vO in rt.indices){if(!r_){if(Vp=x.getValue(xe,!0),!Vp)break;r_={}}r_[vO]=Vp[vO]}fn=ac(x.version,ue,Wl,null,se,x.user,x.type==="put"||x.type==="patch"?"invalidate":x.type,He.encode(r_),qp,tr,x.previousResidencyId,x.expiresAt)}function di(){F||(F=setTimeout(()=>{F=null,(Ie||0)+zU/2<j&&(cd&&_e.info?.(s,"sending skipped sequence update",j),e.send((0,et.encode)([KU,j])))},zU).unref())}a(di,"skipAuditRecord");let Fp=He.typedStructs,Gp=He.structures;if((Fp?.length!=pe.typed_length||Gp?.length!=pe.structure_length)&&(pe.typed_length=Fp?.length,pe.structure_length=Gp.length,_e.info?.(s,"send table struct",pe.typed_length,pe.structure_length),pe.sentName||(pe.sentName=!0),e.send((0,et.encode)([UR,{typedStructs:Fp,structures:Gp,attributes:rt.attributes,schemaDefined:rt.schemaDefined},ue,pe.table.tableName]))),tr&&!Ht[tr]&&(e.send((0,et.encode)([VU,kt,tr])),Ht[tr]=!0),fn)ui(fn.length),nc(fn);else{let Ki=x.encoded,Wl=Ki[0]===66?8:0;ui(Ki.length-Wl),nc(Ki,Wl)}},"sendAuditRecord"),De=a(()=>{e.send(o.subarray(i,c))},"sendQueuedData");Cs=new BR.EventEmitter,Cs.once("close",()=>{P=!0,C?.end()});for(let{startTime:x}of Ds)x<j&&(j=x);(O||Promise.resolve()).then(async()=>{h=await h,f=h.auditStore,Te=h.tableById.map(B),K=[];for(let{name:k,startTime:se}of Ds){let ue=NR(k,f);_e.info?.("subscription to",k,"using local id",ue,"starting",se),K[ue]=se}Yi(d),ee||(ee=ha(k=>{k.databaseName===d&&Yi(d)}),Z=ld(k=>{k===d&&(e.send((0,et.encode)([$c])),dn())}),e.on("close",()=>{ee?.remove(),Z?.remove()})),e.send((0,et.encode)([qU,rd(h.auditStore),Ds.map(({name:k})=>k)]));let x=!0;do{isFinite(j)||(_e.warn?.("Invalid sequence id "+j),dn(1008,"Invalid sequence id"+j));let k;if(x&&!P&&(x=!1,FR(f)>j&&server.nodes[0]===T)){let pe=j,rt=JE(f);for(let xe in p){let He=p[xe];for(let nt of He.primaryStore.getRange({snapshot:!1})){if(P)return;nt.localTime>=j&&(_e.info?.(s,"Copying record from",d,xe,nt.key,nt.localTime),pe=Math.max(nt.localTime,pe),k=!0,he({recordId:nt.key,tableId:He.tableId,type:"put",getValue(){return nt.value},encoded:He.primaryStore.getBinary(nt.key),version:nt.version,residencyId:nt.residencyId,nodeId:rt},nt.localTime))}}j=pe}for(let{key:ue,value:pe}of f.getRange({start:(j||1)+1/4096,snapshot:!1})){if(P)return;let rt=Lt(pe);he(rt,ue),e._socket.writableNeedDrain&&await new Promise(xe=>e._socket.once("drain",xe)),Cs.startTime=ue,k=!0}k&&he({type:"end_txn"},j);let se=WE.get(M);se||WE.set(M,se=[]),se.push(ue=>{}),await UU(f)}while(!P)}).catch(x=>{_e.error?.(s,"Error handling subscription to node",x),dn(1008,"Error handling subscription to node")});break}return}me.position=8;let Je=!0,Ae;do{let Fe=me.readInt();if(Fe===9&&me.getUint8(me.position)==zE){me.position++,A=Ae=me.readFloat64(),_e.info?.("received remote sequence update",A,d);break}let tt=me.position,Ee=Lt(te.subarray(tt,tt+Fe)),Dt=le[Ee.tableId];Dt||_e.error?.(`No table found with an id of ${Ee.tableId}`);let q;Ee.residencyId&&(q=Bo[Ee.residencyId],_e.info?.(s,"received residency list",q,Ee.type,Ee.recordId));let m={table:Dt.name,id:Ee.recordId,type:Ee.type,nodeId:Ct.get(Ee.nodeId),residencyList:q,timestamp:Ee.version,value:Ee.getValue(Dt),user:Ee.user,beginTxn:Je,expiresAt:Ee.expiresAt};Je=!1,cd&&_e.info?.(s,"received replication message",Ee.type,"id",m.id,"version",Ee.version,"nodeId",m.nodeId,"name",m.value?.name),h.send(m),me.position=tt+Fe}while(me.position<te.byteLength);Gr++,Gr>tc&&!Vi&&(Vi=!0,e.pause()),h.send({type:"end_txn",localTime:A,remoteNodeIds:g,onCommit(){Gr--,Vi&&(Vi=!1,e.resume()),!N&&Ae&&(_e.info?.(s,"queuing confirmation of a commit at",Ae),setTimeout(()=>{e.send((0,et.encode)([WU,N])),_e.info?.(s,"sent confirmation of a commit at",N),N=null},H6)),N=Ae}})}catch(me){_e.error?.(s,"Error handling incoming replication message",me)}}),e.on("ping",ne),e.on("pong",()=>{t.connection&&fa({name:T,database:d,url:t.url,latency:performance.now()-$}),$=null}),e.on("close",(te,me)=>{clearInterval(v),clearTimeout(J),Cs&&Cs.emit("close"),$i&&$i.end();for(let[Je,{reject:Ae}]of S)Ae(new Error("Connection closed"));_e.info?.(s,"closed",te,me?.toString())});function Hp(){}a(Hp,"recordRemoteNodeSequence");function dn(te,me){e.isFinished=!0,e.close(te,me)}a(dn,"close");function e_(){if(_||(_=!0,t.connection?.on("subscriptions-updated",e_)),t.connection?.isFinished)throw new Error("Can not make a subscription request on a connection that is already closed");let te=new Map;try{for(let Ae of h?.dbisDB?.getRange({start:Symbol.for("seq"),end:[Symbol.for("seq"),Buffer.from([255])]})||[])for(let Fe of Ae.value.nodes||[])Fe.seqId>(te.get(Fe.id)??0)&&te.set(Fe.id,Fe.seqId)}catch(Ae){if(!Ae.message.includes("Can not re"))throw Ae}let me=t.connection?.nodeSubscriptions?.[0];g=[];let Je=t.connection?.nodeSubscriptions.map((Ae,Fe)=>{let tt=[],{replicateByDefault:Ee}=Ae;if(Ae.subscriptions){for(let R of Ae.subscriptions)if(R.subscribe&&(R.schema||R.database)===d){let w=R.table;p?.[w]?.replicate!==!1&&tt.push(w)}Ee=!1}else for(let R in p)(Ee?p[R].replicate===!1:p[R].replicate)&&tt.push(R);let Dt=f&&NR(Ae.name,f),q=h?.dbisDB?.get([Symbol.for("seq"),Dt])??1,m=q?.seqId??(typeof Ae.start_time=="string"?new Date(Ae.start_time).getTime():Ae.start_time)??1;if(me!==Ae){m>5e3&&(m-=5e3);for(let R of q?.nodes||[])R.name===Ae.name&&(m=R.seqId)}return g.push(Dt),te.get(Dt)>m&&(m=te.get(Dt)),{name:Ae.name,replicateByDefault:Ee,tables:tt,startTime:m}});_e.info?.(s,"sending subscription request",Je,h?.dbisDB?.path),Je&&(Je.length>0?e.send((0,et.encode)([FU,Je])):dn(1008,"No nodes to subscribe to"))}a(e_,"sendSubscriptionRequestUpdate");function t_(te,me){if(!te)return;let Je=ye[te];return Je||(Je=me.getResidencyRecord(te),ye[te]=Je),Je}a(t_,"getResidence");function Kl(te){return!(So&&So!="*"&&!So[te]&&!So.includes?.(te)&&!So.some?.(me=>me.name===te))}a(Kl,"checkDatabaseAccess");function ve(te){if(h=h||u.get(te),!Kl(te))throw new Error(`Access to database "${te}" is not permitted`);h||_e.warn?.(`No database named "${te}" was declared and registered`),f=h?.auditStore,f||_e.warn?.("No audit store found in "+te+" creating it"),p||(p=ct()?.[te]);let me=ot();if(me===T)throw me?new Error("Should not connect to self",me):new Error("Node name not defined");return kp(me,te),!0}a(ve,"setDatabase");function kp(te,me){let Je=ct()?.[me],Ae=[];for(let Fe in Je){let tt=Je[Fe];Ae.push({table:Fe,schemaDefined:tt.schemaDefined,attributes:tt.attributes.map(Ee=>({name:Ee.name,type:Ee.type,isPrimaryKey:Ee.isPrimaryKey}))})}_e.trace?.("Sending database info for node",te,"database name",me),e.send((0,et.encode)([GU,te,me,Ae]))}a(kp,"sendNodeDBName");function Yi(te){let me=ct()?.[te],Je=[];for(let Ae in me){if(Ds&&!Ds.some(tt=>tt.replicateByDefault?!tt.tables.includes(Ae):tt.tables.includes(Ae)))continue;let Fe=me[Ae];Je.push({table:Ae,schemaDefined:Fe.schemaDefined,attributes:Fe.attributes.map(tt=>({name:tt.name,type:tt.type,isPrimaryKey:tt.isPrimaryKey}))})}e.send((0,et.encode)([QU,Je,te]))}a(Yi,"sendDBSchema");let li=1,rc=[];return{end(){$i&&$i.end(),Cs&&Cs.emit("close")},getRecord(te){let me=li++;return new Promise((Je,Ae)=>{let Fe=[$U,me,te.table.tableId,te.id];rc[te.table.tableId]||(Fe.push(te.table.tableName),rc[te.table.tableId]=!0),e.send((0,et.encode)(Fe)),S.set(me,{tableId:te.table.tableId,key:te.id,resolve(tt){let{table:Ee,entry:Dt}=te;Je(tt),tt&&Ee._recordRelocate(Dt,tt)},reject:Ae})})},sendOperation(te){let me=li++;return te.requestId=me,e.send((0,et.encode)([YU,te])),new Promise((Je,Ae)=>{S.set(me,{resolve:Je,reject:Ae})})}};function ui(te){Ho(5),te<128?o[c++]=te:te<16384?(l.setUint16(c,te|32768),c+=2):te<1056964608?(l.setUint32(c,te|3221225472),c+=4):(o[c]=255,l.setUint32(c+1,te),c+=5)}function nc(te,me=0,Je=te.length){let Ae=Je-me;Ho(Ae),te.copy(o,c,me,Je),c+=Ae}function Dr(te){Ho(8),l.setFloat64(c,te),c+=8}function Ho(te){if(te+16>o.length-c){let me=Buffer.allocUnsafeSlow(c+te-i+65536>>10<<11);o.copy(me,0,i,c),c=c-i,i=0,o=me,l=new DataView(o.buffer,0,o.length)}}}function xR(e,t){t||(t={});let r=!1,n=e.schemaDefined,s=t.attributes||[];for(let i=0;i<e.attributes?.length;i++){let o=e.attributes[i],c=s[i];(!c||c.name!==o.name||c.type!==o.type)&&(r=!0,n||(o.indexed=!0),s[i]=o)}return r?(_e.info?.("(Re)creating",e),dt({table:e.table,database:e.database,schemaDefined:e.schemaDefined,attributes:s,...t})):t}var JU,et,XU,ZU,_e,BR,ev,tv,HR,rv,FU,GU,qU,$c,VU,UR,$U,YE,YU,KE,KU,WU,QU,WE,_a,cd,zU,H6,jU,vR,QE,nv=Oe(()=>{Ne();_i();IR();LR();Ai();JU=U(ie());cc();et=require("msgpackr"),XU=require("ws"),ZU=require("worker_threads"),_e=U(td());ad();BR=require("events"),ev=U(To()),tv=U(require("node:tls"));od();HR=U(require("node:process")),rv=require("node:net"),FU=129,GU=140,qU=141,$c=142,VU=130,UR=132,$U=133,YE=134,YU=136,KE=137,KU=143,WU=144,QU=145,WE=new Map,_a=new Map,cd=!0,zU=300,H6=2,jU=3e5;a(kR,"createWebSocket");QE=class extends BR.EventEmitter{constructor(r,n,s){super();this.url=r;this.subscription=n;this.databaseName=s;this.nodeName=Ks(r)}static{a(this,"NodeReplicationConnection")}socket;startTime;retryTime=2e3;retries=0;isConnected=!0;isFinished=!1;nodeSubscriptions=[];replicateTablesByDefault;session;sessionResolve;sessionReject;nodeName;async connect(){this.session||this.resetSession();let r=[];this.socket=await kR(this.url,{serverName:this.nodeName});let n;_e.info?.(`Connecting to ${this.url}, db: ${this.databaseName}, process ${HR.pid}`),this.socket.on("open",()=>{this.socket._socket.unref(),_e.info?.(`Connected to ${this.url}, db: ${this.databaseName}`),this.retries=0,this.retryTime=2e3,fa({name:this.nodeName,database:this.databaseName,url:this.url}),this.isConnected=!0,n=jE(this.socket,{database:this.databaseName,subscription:this.subscription,url:this.url,connection:this},{replicates:!0}),this.sessionResolve(n)}),this.socket.on("error",s=>{s.code==="SELF_SIGNED_CERT_IN_CHAIN"?(_e.warn?.(`Can not connect to ${this.url}, this server does not have a certificate authority for the certificate provided by ${this.url}`),s.isHandled=!0):s.code!=="ECONNREFUSED"&&(s.code==="UNABLE_TO_VERIFY_LEAF_SIGNATURE"?_e.error?.(`Can not connect to ${this.url}, the certificate provided by ${this.url} is not trusted, this node needs to be added to the cluster, or a certificate authority needs to be added`):_e.error?.(`Error in connection to ${this.url} due to ${s.message}`)),this.sessionReject(s)}),this.socket.on("close",(s,i)=>{if(this.isConnected&&(Vc({name:this.nodeName,database:this.databaseName,url:this.url,finished:this.socket.isFinished}),this.isConnected=!1),this.socket.isFinished){this.isFinished=!0,n?.end(),this.emit("finished");return}if(++this.retries%20===1){let o=i?.toString();_e.warn?.(`${n?"Disconnected from":"Failed to connect to"} ${this.url} (db: "${this.databaseName}"), due to ${o?'"'+o+'" ':""}(code: ${s})`)}n=null,this.resetSession(),setTimeout(()=>{this.connect()},this.retryTime).unref(),this.retryTime+=this.retryTime>>3})}resetSession(){this.session=new Promise((r,n)=>{this.sessionResolve=r,this.sessionReject=n})}subscribe(r,n){this.nodeSubscriptions=r,this.replicateTablesByDefault=n,this.emit("subscriptions-updated",r)}unsubscribe(){this.socket.isFinished=!0,this.socket.close(1008,"No longer subscribed")}getRecord(r){return this.session.then(n=>n.getRecord(r))}};a(jE,"replicateOverWS");a(xR,"ensureTableIfChanged")});var dd={};Ze(dd,{clearThisNodeName:()=>$6,disableReplication:()=>G6,enabled_databases:()=>So,forEachReplicatedDatabase:()=>mo,getThisNodeId:()=>JE,getThisNodeName:()=>ot,getThisNodeUrl:()=>po,hostnameToUrl:()=>rh,replication_certificate_authorities:()=>Ea,sendOperationToNode:()=>th,servers:()=>lv,setReplicator:()=>dv,start:()=>F6,startOnMainThread:()=>MR,subscribeToNode:()=>qc,unsubscribeFromNode:()=>$E,urlToNodeName:()=>Ks});function F6(e){if(e.port||(e.port=Ws.default.get(ud.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_PORT)),e.securePort||(e.securePort=Ws.default.get(ud.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_SECUREPORT)),!ot())throw new Error("Can not load replication without a url (see replication.url in the config)");let t=new Map;for(let n of qE(e))t.set(Ks(n.url),n);q6(e),e=Object.assign({subProtocol:"harperdb-replication-v1",mtls:!0,isOperationsServer:!0},e);let r=st.ws(async(n,s,i)=>{await i,n._socket.unref(),jE(n,e,s?.user),n.on("error",o=>{o.code!=="ECONNREFUSED"&&gr.error("Error in connection to "+this.url,o.message)})},e);e.runFirst=!0,st.http((n,s)=>{if(n.isWebSocket&&n.headers.get("Sec-WebSocket-Protocol")==="harperdb-replication-v1"){!n.authorized&&n._nodeRequest.socket.authorizationError&&gr.error(`Incoming client connection from ${n.ip} did not have valid certificate `,n._nodeRequest.socket.authorizationError);let i=Br().primaryStore;if(n.authorized&&n.peerCertificate.subject){let o=n.peerCertificate.subject,c=o&&(i.get(o.CN)||t.get(o.CN));c?n.user=c:gr.warn(`No node found for certificate common name ${o.CN}, available nodes are ${Array.from(new Set([...i.getKeys(),...t.keys()])).join(", ")}, connection will require credentials.`)}else{let o=i.get(n.ip)||t.get(n.ip);o?n.user=o:gr.warn(`No node found for IP address ${n.ip}, available nodes are ${Array.from(new Set([...i.getKeys(),...t.keys()])).join(", ")}, connection will require credentials.`)}}return s(n)},e);for(let n of r)if(lv.push(n),n.secureContexts){let s=0,i=a(()=>{let o=new Set(n.secureContexts.values());n.defaultContext&&o.add(n.defaultContext);for(let c of o)try{let l=Array.from(Ea);c.options.ca&&l.push(...c.options.ca);let d=Object.assign({},c.options,{ca:l});c.replicationContext=eh.createSecureContext(d)}catch(l){gr.error("Error creating replication TLS config",l)}},"updateContexts");n.secureContextsListeners.push(i),id(o=>{o?.ca&&(Ea.add(o.ca),Ea.size!==s&&(s=Ea.size,i()))})}}function G6(e=!0){cv=e}function q6(e){cv||(ct(),So=e.databases,mo(e,(t,r)=>{if(!t){let n=e.databaseSubscriptions||_a;for(let[s,i]of ZE){let o=i.get(r);o&&(o.subscribe([],!1),i.delete(r))}n.delete(r);return}for(let n in t){let s=t[n];dv(r,s,e),WE.get(s)?.forEach(i=>i(s))}}))}function dv(e,t,r){if(!t)return console.error(`Attempt to replicate non-existent table ${t.name} from database ${e}`);if(t.replicate===!1||t.sources?.some(s=>s.isReplicator))return;let n;t.sourcedFrom(class uv extends pr{static{a(this,"Replicator")}static connection;static subscription;static async subscribe(){let i=r.databaseSubscriptions||_a,o=i.get(e),c=o?.tableById||[];c[t.tableId]=t;let l=o?.ready;if(gr.trace("Setting up replicator subscription to database",e,o&&Object.keys(o)),!o?.auditStore)return this.subscription=o=new mn,i.set(e,o),o.tableById=c,o.auditStore=t.auditStore,o.dbisDB=t.dbisDB,o.databaseName=e,l&&l(o),o;this.subscription=o}static subscribeOnThisThread(i,o){return!0}static async load(i){if(i){let o=i.residencyId,c=i.residency||t.dbisDB.get([Symbol.for("residency_by_id"),o]);if(c){let l;for(let d of c)try{let u=Br().primaryStore.get(d);if(u){let f=fv(u.url,uv.subscription,e),E={requestId:k6++,table:t,entry:i,id:i.key};return await f.getRecord(E)}}catch(u){gr.warn("Error in load from node",d,u),l||(l=u)}if(l)throw l}}}static isReplicator=!0},{intermediateSource:!0})}function fv(e,t,r){let n=ZE.get(e);n||ZE.set(e,n=new Map);let s=n.get(r);if(s)return s;if(t)return n.set(r,s=new QE(e,t,r)),s.connect(),s.once("finished",()=>n.delete(r)),s}async function th(e,t,r){r||(r={}),r.serverName=e.name;let n=await kR(e.url,r),s=jE(n,{},{});return new Promise((i,o)=>{n.on("open",()=>{i(s.sendOperation(t))}),n.on("error",c=>{o(c)}),n.on("close",c=>{gr.error("Sending operation connection to "+e.url+" closed",c)})}).finally(()=>{n.close()})}function qc(e){try{av.isMainThread&&gr.trace("Subscribing on main thread (should not happen in multi-threaded instance)",e.nodes[0].url,e.database);let t=_a.get(e.database);if(!t){let n;t=new Promise(s=>{gr.info("Waiting for subscription to database "+e.database),n=s}),t.ready=n,_a.set(e.database,t)}let r=fv(e.nodes[0].url,t,e.database);e.nodes[0].name===void 0&&(r.tentativeNode=e.nodes[0]),r.subscribe(e.nodes.filter(n=>GE(n,e.database)),e.replicateByDefault)}catch(t){gr.error("Error in subscription to node",e.nodes[0]?.url,t)}}async function $E({url:e,database:t}){let r=ZE.get(e);if(r){let n=r.get(t);n&&(n.unsubscribe(),r.delete(t))}}function V6(){if(GR!==void 0)return GR;let e=Ws.default.get(ud.CONFIG_PARAMS.OPERATIONSAPI_TLS_CERTIFICATE)||Ws.default.get(ud.CONFIG_PARAMS.TLS_CERTIFICATE);if(e)return GR=new iv.X509Certificate((0,ov.readFileSync)(e)).subject.match(/CN=(.*)/)?.[1]??null}function ot(){return qR||(qR=Ws.default.get("replication_hostname")??Ks(Ws.default.get("replication_url"))??V6()??sv("operationsapi_network_secureport")??sv("operationsapi_network_port")??"127.0.0.1")}function $6(){qR=void 0}function sv(e){let t=Ws.default.get(e),r=t?.lastIndexOf?.(":");if(r>0)return t.slice(0,r)}function XE(e){let t=Ws.default.get(e),r=t?.lastIndexOf?.(":");return r>0?+t.slice(r+1).replace(/[\[\]]/g,""):+t}function JE(e){return rd(e)?.[ot()]}function po(){let e=Ws.default.get("replication_url");return e||rh(ot())}function rh(e){let t=XE("replication_port");if(t)return`ws://${e}:${t}`;if(t=XE("replication_secureport"),t)return`wss://${e}:${t}`;if(t=XE("operationsapi_network_port"),t)return`ws://${e}:${t}`;if(t=XE("operationsapi_network_secureport"),t)return`wss://${e}:${t}`}function Ks(e){if(e)return new URL(e).hostname}function mo(e,t){for(let n of Object.getOwnPropertyNames(Ve))r(n);return ld(n=>{r(n)}),ha((n,s)=>{r(n.databaseName)});function r(n){let s=Ve[n];gr.trace("Checking replication status of ",n,e?.databases),e?.databases===void 0||e.databases==="*"||e.databases.includes(n)||e.databases.some?.(i=>i.name===n)||!s?t(s,n,!0):Y6(n)&&t(s,n,!1)}a(r,"forDatabase")}function Y6(e){let t=Ve[e];for(let r in t)if(t[r].replicate)return!0}var Ws,gr,iv,ov,ud,eh,av,cv,k6,lv,Ea,So,ZE,GR,qR,Ai=Oe(()=>{Ne();ls();ic();nv();Lr();Ws=U(ie()),gr=U(X()),iv=require("crypto"),ov=require("fs");ad();od();ud=U(H());IR();eh=U(require("node:tls")),av=require("worker_threads"),k6=1,lv=[],Ea=new Set(eh.rootCertificates);a(F6,"start");a(G6,"disableReplication");a(q6,"assignReplicationSource");a(dv,"setReplicator");ZE=new Map;a(fv,"getConnection");a(th,"sendOperationToNode");a(qc,"subscribeToNode");a($E,"unsubscribeFromNode");a(V6,"getCommonNameFromCert");a(ot,"getThisNodeName");a($6,"clearThisNodeName");Object.defineProperty(st,"hostname",{get(){return ot()}});a(sv,"getHostFromListeningPort");a(XE,"getPortFromListeningPort");a(JE,"getThisNodeId");st.replication={getThisNodeId:JE,exportIdMapping:rd};a(po,"getThisNodeUrl");a(rh,"hostnameToUrl");a(Ks,"urlToNodeName");a(mo,"forEachReplicatedDatabase");a(Y6,"hasExplicitlyReplicatedTable")});var To=I(vv=>{"use strict";var fr=require("path"),Kn=require("fs-extra"),Wc=require("node-forge"),Sv=require("net"),{generateKeyPair:$R,X509Certificate:go,createPrivateKey:Tv}=require("crypto"),K6=require("util");$R=K6.promisify($R);var yt=Wc.pki,Oi=require("joi"),{v4:W6}=require("uuid"),{validateBySchema:gv}=mt(),_t=X(),Ss=ie(),Ts=H(),{CONFIG_PARAMS:Qc}=Ts,Qs=fT(),{ClientError:fd}=ce(),pa=require("node:tls"),{relative:Q6,join:z6}=require("node:path"),{CERT_PREFERENCE_APP:hTe,CERTIFICATE_VALUES:j6}=Qs,J6=a_(),YR=dr(),_v=parseInt(process.version.slice(1))<20,{table:X6,getDatabases:Z6,databases:VR}=(Ne(),ae(it));Object.assign(vv,{generateKeys:Iv,updateConfigCert:Dv,createCsr:a9,signCertificate:c9,setCertTable:zc,loadCertificates:Ov,reviewSelfSignedCert:Cv,createTLSSelector:Mv,listCertificates:Uv,addCertificate:_9,removeCertificate:h9,createNatsCerts:d9,generateCertsKeys:u9,getReplicationCert:Ed,getReplicationCertAuth:o9});var{urlToNodeName:Rv,getThisNodeUrl:e9,getThisNodeName:sh,clearThisNodeName:t9}=(Ai(),ae(dd)),{readFileSync:r9,watchFile:n9,statSync:Av}=require("node:fs"),mTe=ie(),{getTicketKeys:s9,onMessageFromWorkers:i9}=at(),ma=X(),{isMainThread:bv}=require("worker_threads"),{TLSSocket:yv,createSecureContext:pTe}=require("node:tls"),WR=3650,_d=["127.0.0.1","localhost","::1"],QR=[{name:"countryName",value:"USA"},{name:"stateOrProvinceName",value:"Colorado"},{name:"localityName",value:"Denver"},{name:"organizationName",value:"HarperDB, Inc."}];i9(async e=>{e.type===Ts.ITC_EVENT_TYPES.RESTART&&(Ss.initSync(!0),await Cv())});var Zr;function Ta(){return Zr||(Zr=Z6().system.hdb_certificate,Zr||(Zr=X6({table:"hdb_certificate",database:"system",attributes:[{name:"name",isPrimaryKey:!0},{attribute:"uses"},{attribute:"certificate"},{attribute:"is_authority"},{attribute:"private_key_name"},{attribute:"details"},{attribute:"is_self_signed"},{attribute:"__updatedtime__"}]}))),Zr}a(Ta,"getCertTable");async function Ed(){let e=Mv("operations-api"),t={secureContexts:null,setSecureContext:s=>{}};await e.initialize(t);let r=t.secureContexts.get(sh());if(!r)return;let n=new go(r.options.cert);return r.cert_parsed=n,r.issuer=n.issuer,r}a(Ed,"getReplicationCert");async function o9(){Ta();let e=(await Ed()).options.cert,r=new go(e).issuer.match(/CN=(.*)/)?.[1];return Zr.get(r)}a(o9,"getReplicationCertAuth");var Ev,Sa=new Map;function Ov(){if(Ev)return;Ev=!0;let e=[{configKey:Qc.TLS},{configKey:Qc.OPERATIONSAPI_TLS}];Ta();let t=fr.dirname(YR.getConfigFilePath()),r;for(let{configKey:n}of e){let s=YR.getConfigFromFile(n);if(s){Array.isArray(s)||(s=[s]);for(let i of s){let o=i.privateKey,c=o&&Q6(z6(t,"keys"),o);c&&hv(o,l=>{Sa.set(c,l)},"private key");for(let l of[!1,!0]){let d=i[l?"certificateAuthority":"certificate"];if(d&&bv){let u;hv(d,f=>{if(j6.cert===f)return;let E=i.hostname??i.hostnames??i.host??i.hosts;E&&!Array.isArray(E)&&(E=[E]);let _=Lv(d),h=new go(_),p;try{p=jR(h)}catch(A){_t.error("error extracting common name from certificate",A);return}if(p==null){_t.error("error extracting common name from certificate");return}let S=Zr.primaryStore.get(p),g=Av(d).mtimeMs,T=!S||S.is_self_signed?1:S.file_timestamp??S.__updatedtime__;if(S&&g<=T){g<T&&_t.info(`Certificate ${p} at ${d} is older (${new Date(g)}) than the certificate in the database (${T>1?new Date(T):"only self signed certificate available"})`);return}r=Zr.put({name:p,uses:["https",...n.includes("operations")?["operations"]:[]],ciphers:i.ciphers,certificate:_,private_key_name:c,is_authority:l,hostnames:E,file_timestamp:g,details:{issuer:h.issuer.replace(/\n/g," "),subject:h.subject.replace(/\n/g," "),subject_alt_name:h.subjectAltName,serial_number:h.serialNumber,valid_from:h.validFrom,valid_to:h.validTo}})},l?"certificate authority":"certificate")}}}}}return r}a(Ov,"loadCertificates");function hv(e,t,r){let n,s=a((i,o)=>{try{let c=i.mtimeMs;c&&c!==n&&(o&&bv&&_t.warn(`Reloading ${r}:`,e),n=c,t(Lv(e)))}catch(c){_t.error(`Error loading ${r}:`,e,c)}},"loadFile");Kn.existsSync(e)?s(Av(e)):_t.error(`${r} file not found:`,e),n9(e,{persistent:!1},s)}a(hv,"loadAndWatch");function mv(){let e=e9();if(e==null){let t=_d[0];return _t.info("replication url is missing from harperdb-config.yaml, using default host"+t),t}return Rv(e)}a(mv,"getHost");function nh(){let e=sh();if(e==null){let t=_d[0];return _t.info("replication url is missing from harperdb-config.yaml, using default host"+t),t}return e}a(nh,"getCommonName");async function a9(){let e=await Ed(),t=yt.certificateFromPem(e.options.cert),r=yt.privateKeyFromPem(e.options.key);_t.info("Creating CSR with cert named:",e.name);let n=yt.createCertificationRequest();n.publicKey=t.publicKey;let s=[{name:"commonName",value:nh()},...QR];_t.info("Creating CSR with subject",s),n.setSubject(s);let i=[{name:"unstructuredName",value:"HarperDB, Inc."},{name:"extensionRequest",extensions:Nv()}];return _t.info("Creating CSR with attributes",i),n.setAttributes(i),n.sign(r),Wc.pki.certificationRequestToPem(n)}a(a9,"createCsr");function Nv(){let e=_d.includes(nh())?_d:[..._d,nh()];return e.includes(mv())||e.push(mv()),[{name:"basicConstraints",cA:!1,critical:!0},{name:"keyUsage",digitalSignature:!0,keyEncipherment:!0,critical:!0},{name:"extKeyUsage",serverAuth:!0,clientAuth:!0},{name:"nsCertType",client:!0,server:!0},{name:"subjectAltName",altNames:e.map(t=>Sv.isIP(t)?{type:7,ip:t}:{type:2,value:t})}]}a(Nv,"certExtensions");async function c9(e){let t={},r=fr.join(Ss.getHdbBasePath(),Ts.LICENSE_KEY_DIR_NAME);if(e.csr){let n,s;Ta();for await(let u of Zr.search([]))if(u.is_authority&&!u.details.issuer.includes("HarperDB-Certificate-Authority")){if(Sa.has(u.private_key_name)){n=Sa.get(u.private_key_name),s=u;break}else if(u.private_key_name&&await Kn.exists(fr.join(r,u.private_key_name))){n=Kn.readFile(fr.join(r,u.private_key_name)),s=u;break}}if(!n){let u=await KR();s=u.ca,n=u.private_key}n=yt.privateKeyFromPem(n),t.signingCA=s.certificate;let i=yt.certificateFromPem(s.certificate);_t.info("Signing CSR with cert named",s.name);let o=yt.certificationRequestFromPem(e.csr);try{o.verify()}catch(u){return _t.error(u),new Error("Error verifying CSR: "+u.message)}let c=Wc.pki.createCertificate();c.serialNumber=Math.random().toString().slice(2,10),c.validity.notBefore=new Date;let l=new Date;c.validity.notAfter=l,c.validity.notAfter.setDate(l.getDate()+WR),_t.info("sign cert setting validity:",c.validity),_t.info("sign cert setting subject from CSR:",o.subject.attributes),c.setSubject(o.subject.attributes),_t.info("sign cert setting issuer:",i.subject.attributes),c.setIssuer(i.subject.attributes);let d=o.getAttribute({name:"extensionRequest"}).extensions;_t.info("sign cert adding extensions from CSR:",d),c.setExtensions(d),c.publicKey=o.publicKey,c.sign(n,Wc.md.sha256.create()),t.certificate=yt.certificateToPem(c)}else _t.info("Sign cert did not receive a CSR from:",e.url,"only the CA will be returned");return t}a(c9,"signCertificate");async function l9(e,t){await zc({name:sh(),uses:["https","wss"],certificate:e,private_key_name:"privateKey.pem",is_authority:!1,is_self_signed:!0}),await zc({name:t.subject.getField("CN").value,uses:["https","wss"],certificate:yt.certificateToPem(t),private_key_name:"privateKey.pem",is_authority:!0,is_self_signed:!0})}a(l9,"createCertificateTable");async function zc(e){let t=new go(e.certificate);e.details={issuer:t.issuer.replace(/\n/g," "),subject:t.subject.replace(/\n/g," "),subject_alt_name:t.subjectAltName,serial_number:t.serialNumber,valid_from:t.validFrom,valid_to:t.validTo},Ta(),await Zr.patch(e)}a(zc,"setCertTable");async function Iv(){let e=await $R("rsa",{modulusLength:4096,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}});return{public_key:yt.publicKeyFromPem(e.publicKey),private_key:yt.privateKeyFromPem(e.privateKey)}}a(Iv,"generateKeys");async function zR(e,t,r){let n=yt.createCertificate();if(!t){let o=await Ed();t=yt.certificateFromPem(o.options.cert).publicKey}n.publicKey=t,n.serialNumber=Math.random().toString().slice(2,10),n.validity.notBefore=new Date;let s=new Date;n.validity.notAfter=s,n.validity.notAfter.setDate(s.getDate()+WR);let i=[{name:"commonName",value:nh()},...QR];return n.setSubject(i),n.setIssuer(r.subject.attributes),n.setExtensions(Nv()),n.sign(e,Wc.md.sha256.create()),yt.certificateToPem(n)}a(zR,"generateCertificates");async function KR(){let e=await Uv(),t;for(let r of e){if(!r.is_authority)continue;let n=Sa.get(r.private_key_name);if(r.private_key_name&&n){let s=new go(r.certificate).checkPrivateKey(Tv(n));if(_t.trace(`CA named: ${r.name} found with matching private key`),s){t={ca:r,private_key:n};break}}}if(t)return t;_t.trace("No CA found with matching private key")}a(KR,"getCertAuthority");async function wv(e,t){let r=yt.createCertificate();r.publicKey=t,r.serialNumber=Math.random().toString().slice(2,10),r.validity.notBefore=new Date;let n=new Date;r.validity.notAfter=n,r.validity.notAfter.setDate(n.getDate()+WR);let s=[{name:"commonName",value:`HarperDB-Certificate-Authority-${Ss.get(Qc.REPLICATION_HOSTNAME)??Rv(Ss.get(Qc.REPLICATION_URL))??W6().split("-")[0]}`},...QR];r.setSubject(s),r.setIssuer(s),r.setExtensions([{name:"basicConstraints",cA:!0,critical:!0},{name:"keyUsage",keyCertSign:!0,critical:!0}]),r.sign(e,Wc.md.sha256.create());let i=fr.join(Ss.getHdbBasePath(),Ts.LICENSE_KEY_DIR_NAME),o=fr.join(i,Qs.PRIVATEKEY_PEM_NAME);return await Kn.writeFile(o,yt.privateKeyToPem(e)),r}a(wv,"generateCertAuthority");async function u9(){let{private_key:e,public_key:t}=await Iv(),r=await wv(e,t),n=await zR(e,t,r);await l9(n,r),Dv()}a(u9,"generateCertsKeys");async function d9(){let e=await zR(yt.privateKeyFromPem(Qs.CERTIFICATE_VALUES.key),void 0,yt.certificateFromPem(Qs.CERTIFICATE_VALUES.cert)),t=fr.join(Ss.getHdbBasePath(),Ts.LICENSE_KEY_DIR_NAME),r=fr.join(t,Qs.NATS_CERTIFICATE_PEM_NAME);await Kn.exists(r)||await Kn.writeFile(r,e);let n=fr.join(t,Qs.NATS_CA_PEM_NAME);await Kn.exists(n)||await Kn.writeFile(n,Qs.CERTIFICATE_VALUES.cert)}a(d9,"createNatsCerts");async function Cv(){t9(),await Ov(),Ta();let e,t=Ss.get(Qc.TLS_PRIVATEKEY),r=a(async()=>e||(e=yt.privateKeyFromPem(await Kn.readFile(t)),e),"getPrivateKey"),n,s=await KR();if(!s){n=!0,_t.info("No self signed Cert Authority found, generating new self signed CA"),await r();let o=await wv(e,yt.setRsaPublicKey(e.n,e.e));await zc({name:o.subject.getField("CN").value,uses:["https","wss"],certificate:yt.certificateToPem(o),private_key_name:fr.basename(t),is_authority:!0,is_self_signed:!0})}if(!await Ed()||n){let o=sh();_t.info(`A suitable replication certificate was not found, creating new self singed cert named: ${o}`),s=s??await KR();let c=yt.certificateFromPem(s.ca.certificate),l=c.publicKey,d=await zR(yt.privateKeyFromPem(s.private_key),l,c);await zc({name:o,uses:["https","operations","wss"],certificate:d,is_authority:!1,private_key_name:s.ca.private_key_name})}}a(Cv,"reviewSelfSignedCert");function Dv(){let e=J6(Object.keys(Ts.CONFIG_PARAM_MAP),!0),t=fr.join(Ss.getHdbBasePath(),Ts.LICENSE_KEY_DIR_NAME),r=fr.join(t,Qs.PRIVATEKEY_PEM_NAME),n=fr.join(t,Qs.NATS_CERTIFICATE_PEM_NAME),s=fr.join(t,Qs.NATS_CA_PEM_NAME),i=Ts.CONFIG_PARAMS,o={[i.TLS_PRIVATEKEY]:e[i.TLS_PRIVATEKEY.toLowerCase()]?e[i.TLS_PRIVATEKEY.toLowerCase()]:r};e[i.TLS_CERTIFICATE.toLowerCase()]&&(o[i.TLS_CERTIFICATE]=e[i.TLS_CERTIFICATE.toLowerCase()]),e[i.TLS_CERTIFICATEAUTHORITY.toLowerCase()]&&(o[i.TLS_CERTIFICATEAUTHORITY]=e[i.TLS_CERTIFICATEAUTHORITY.toLowerCase()]),e[i.OPERATIONSAPI_TLS_CERTIFICATE.toLowerCase()]&&(o[i.OPERATIONSAPI_TLS_CERTIFICATE]=e[i.OPERATIONSAPI_TLS_CERTIFICATE.toLowerCase()]),e[i.OPERATIONSAPI_TLS_PRIVATEKEY.toLowerCase()]&&(o[i.OPERATIONSAPI_TLS_PRIVATEKEY]=e[i.OPERATIONSAPI_TLS_PRIVATEKEY.toLowerCase()]),e[i.OPERATIONSAPI_TLS_CERTIFICATEAUTHORITY.toLowerCase()]&&(o[i.OPERATIONSAPI_TLS_CERTIFICATEAUTHORITY]=e[i.OPERATIONSAPI_TLS_CERTIFICATEAUTHORITY.toLowerCase()]),(e[i.CLUSTERING_ENABLED.toLowerCase()]||e.clustering)&&(o[i.CLUSTERING_TLS_CERTIFICATE]=e[i.CLUSTERING_TLS_CERTIFICATE.toLowerCase()]??n,o[i.CLUSTERING_TLS_CERT_AUTH]=e[i.CLUSTERING_TLS_CERT_AUTH.toLowerCase()]??s,o[i.CLUSTERING_TLS_PRIVATEKEY]=e[i.CLUSTERING_TLS_PRIVATEKEY.toLowerCase()]??r),YR.updateConfigValue(void 0,void 0,o,!1,!0)}a(Dv,"updateConfigCert");function Lv(e){return e.startsWith("-----BEGIN")?e:r9(e,"utf8")}a(Lv,"readPEM");var pv=pa.createSecureContext;pa.createSecureContext=function(e){if(!e.cert||!e.key)return pv(e);let t={...e};delete t.key,delete t.cert;let r=pv(t);return r.context.setCert(e.cert),r.context.setKey(e.key,void 0),r};var Pv=pa.Server;pa.Server=function(e,t){return e.ALPNCallback&&(e.ALPNProtocols=null),Pv.call(this,e,t)};pa.Server.prototype=Pv.prototype;var f9=yv.prototype._init;yv.prototype._init=function(e,t){f9.call(this,e,t);let r=this;this._handle.oncertcb=function(n){let s=n.servername;r._SNICallback(s,(i,o)=>{this.sni_context=o.context||o,this.certCbDone()})}};var Kc=new Map;function Mv(e,t){let r=new Map,n,s=!1;return i.initialize=o=>i.ready?i.ready:(o&&(o.secureContexts=r,o.secureContextsListeners=[]),i.ready=new Promise((c,l)=>{async function d(){try{r.clear(),Kc.clear();let u=0;for await(let f of VR.system.hdb_certificate.search([])){if(e!=="operations-api"&&f.uses?.includes?.("operations"))continue;let E=f.certificate,_=new go(E);f.is_authority&&(_.asString=E,Kc.set(_.subject,E))}for await(let f of VR.system.hdb_certificate.search([]))try{if(f.is_authority||!(e==="operations-api")&&f.uses?.includes?.("operations"))continue;let _=f.is_self_signed?1:2,h=Sa.get(f.private_key_name);!h&&f.private_key_name&&(h=await Kn.readFile(fr.join(Ss.get(Qc.ROOTPATH),Ts.LICENSE_KEY_DIR_NAME,f.private_key_name)));let p=f.certificate,S=new go(p);if(Kc.has(S.issuer)&&(p+=`
10
+ `+Kc.get(S.issuer)),!h||!p)throw new Error("Missing private key or certificate for secure server");let g={ciphers:f.ciphers,ticketKeys:s9(),ca:t&&Array.from(Kc.values()),cert:p,key:h,key_file:f.private_key_name,is_self_signed:f.is_self_signed};o&&(g.sessionIdContext=o.sessionIdContext);let T=pa.createSecureContext(g);T.name=f.name,T.options=g,T.quality=_,T.certificateAuthorities=Array.from(Kc),T.certStart=p.toString().slice(0,100);let A=f.hostnames??(S.subjectAltName?S.subjectAltName.split(",").map(V=>{let v=V.indexOf(":");return V.slice(v+1)}):[jR(S)]);Array.isArray(A)||(A=[A]);let N;for(let V of A)if(V){V[0]==="*"&&(s=!0,V=V.slice(1)),Sv.isIP(V)&&(N=!0);let v=r.get(V)?.quality??0;_>v&&r.set(V,T)}else ma.error("No hostname found for certificate at",pa.certificate);_>u&&(i.defaultContext=n=T,u=_,o&&(o.defaultContext=T,ma.trace("Applying default TLS",T.name,"for",o.ports,"cert named",f.name)))}catch(E){ma.error("Error applying TLS for",f.name,E)}o?.secureContextsListeners.forEach(f=>f()),c(n)}catch(u){l(u)}}a(d,"updateTLS"),VR.system.hdb_certificate.subscribe({listener:d,omitCurrent:!0}),d()})),i;function i(o,c){ma.info("TLS requested for",o,this.isReplicationConnection);let l=o;for(;;){let u=r.get(l);if(u)return ma.debug("Found certificate for",o,u.certStart),u.replicationContext&&(this.isReplicationConnection||_v)&&(u=u.replicationContext),c(null,u);if(s&&l){let f=l.indexOf(".",1);f<0?l="":l=l.slice(f)}else break}o?ma.debug("No certificate found to match",o,"using the default certificate"):ma.debug("No SNI, using the default certificate");let d=n;d.replicationContext&&(this.isReplicationConnection||_v)&&(d=d.replicationContext),c(null,d)}a(i,"SNICallback")}a(Mv,"createTLSSelector");async function Uv(){Ta();let e=[];for await(let t of Zr.search([]))e.push(t);return e}a(Uv,"listCertificates");async function _9(e){let t=gv(e,Oi.object({name:Oi.string().required(),certificate:Oi.string().required(),is_authority:Oi.boolean().required(),private_key:Oi.string(),hosts:Oi.array(),uses:Oi.array()}));if(t)throw new fd(t.message);let{name:r,certificate:n,private_key:s,is_authority:i}=e,o=new go(n),c=!1,l=!1,d;for(let[_,h]of Sa)!s&&!c&&o.checkPrivateKey(Tv(h))&&(c=!0,d=_),s&&s===h&&(l=!0,d=_);if(!i&&!s&&!c)throw new fd("A suitable private key was not found for this certificate");let u;if(!r){try{u=jR(o)}catch(_){_t.error(_)}if(u==null)throw new fd("Error extracting certificate common name, please provide a name parameter")}let f=E9(r??u);s&&!c&&!l&&(await Kn.writeFile(fr.join(Ss.getHdbBasePath(),Ts.LICENSE_KEY_DIR_NAME,f+".pem"),s),Sa.set(f,s));let E={name:r??u,certificate:n,is_authority:i,hosts:e.hosts,uses:e.uses};return(!i||i&&d||i&&s)&&(E.private_key_name=d??f+".pem"),await zc(E),"Successfully added certificate: "+f}a(_9,"addCertificate");function E9(e){return e.replace(/[^a-z0-9\.]/gi,"-")}a(E9,"sanitizeName");async function h9(e){let t=gv(e,Oi.object({name:Oi.string().required()}));if(t)throw new fd(t.message);let{name:r}=e;Ta();let n=await Zr.get(r);if(!n)throw new fd(r+" not found");let{private_key_name:s}=n;if(s){let i=Array.from(await Zr.search([{attribute:"private_key_name",value:s}]));i.length===1&&i[0].name===r&&(_t.info("Removing private key named",s),await Kn.remove(fr.join(Ss.getHdbBasePath(),Ts.LICENSE_KEY_DIR_NAME,s)))}return await Zr.delete(r),"Successfully removed "+r}a(h9,"removeCertificate");function jR(e){return e.subject.match(/CN=(.*)/)?.[1]}a(jR,"extractCommonName")});var ga={};Ze(ga,{addNodeBack:()=>g9,removeNodeBack:()=>R9,setNode:()=>T9});async function T9(e){e.node_name&&!e.hostname&&(e.hostname=e.node_name),e.verify_tls!==void 0&&(e.rejectUnauthorized=e.verify_tls);let{url:t,hostname:r}=e;t?r||(r=e.hostname=Ks(t)):t=rh(r);let n=(0,Bv.validateBySchema)(e,S9);if(n)throw(0,zs.handleHDBError)(n,n.message,p9.BAD_REQUEST,void 0,void 0,!0);if(e.operation==="remove_node"){if(!t&&!r)throw new zs.ClientError("url or hostname is required for remove_node operation");let f=r,E=Br(),_=await E.get(f);if(!_)throw new zs.ClientError(f+" does not exist");try{await th({url:_.url},{operation:hd.OPERATIONS_ENUM.REMOVE_NODE_BACK,name:_?.subscriptions?.length>0?ot():f},void 0)}catch(h){Wn.warn(`Error removing node from target node ${f}, if it is offline and we be online in the future, you may need to clean up this node manually, or retry:`,h)}return await E.delete(f),`Successfully removed '${f}' from cluster`}if(!t)throw new zs.ClientError("url required for this operation");let s=po();if(s==null)throw new zs.ClientError("replication url is missing from harperdb-config.yaml");let i,o,c;if(t?.startsWith("wss:")){if(e.operation==="add_node"&&!e.authorization)throw new zs.ClientError("authorization parameter is required");i=await(0,Qn.getReplicationCert)();let f=await(0,Qn.getReplicationCertAuth)();if(!i)throw new Error("Unable to find a certificate to use for replication");i.options.is_self_signed?(o=await(0,Qn.createCsr)(),Wn.info("Sending CSR to target node:",t)):(c=f?.certificate,Wn.info("Sending CA named",f?.name,"to target node",t))}let l={operation:hd.OPERATIONS_ENUM.ADD_NODE_BACK,hostname:(0,Hv.get)(hd.CONFIG_PARAMS.REPLICATION_HOSTNAME),target_hostname:r,url:s,csr:o,cert_auth:c};if(e.subscriptions&&(l.subscriptions=e.subscriptions.map(xv)),e.hasOwnProperty("subscribe")||e.hasOwnProperty("publish")){let f=xv(e);l.subscribe=f.subscribe,l.publish=f.publish}e?.authorization?.username&&e?.authorization?.password&&(e.authorization="Basic "+Buffer.from(e.authorization.username+":"+e.authorization.password).toString("base64"));let d;try{d=await th({url:t},l,e)}catch(f){throw f.message=`Error returned from ${t}: `+f.message,f}if(o&&(!d?.certificate||!d?.certificate?.includes?.("BEGIN CERTIFICATE")))throw new Error(`Unexpected certificate signature response from node ${t} response: ${JSON.stringify(d)}`);o&&(Wn.info("CSR response received from node:",t,"saving certificate and CA in hdb_certificate"),await(0,Qn.setCertTable)({name:m9.certificateFromPem(d.signingCA).issuer.getField("CN").value,certificate:d.signingCA,is_authority:!0}),d.certificate&&await(0,Qn.setCertTable)({name:ot(),uses:["https","operations","wss"],certificate:d.certificate,private_key_name:i?.options?.key_file,is_authority:!1,is_self_signed:!1}),c=d.signingCA);let u={url:t,ca:d.usingCA};if(e.hostname&&(u.name=e.hostname),e.subscriptions?u.subscriptions=e.subscriptions:u.replicates=!0,e.start_time&&(u.start_time=typeof e.start_time=="string"?new Date(e.start_time).getTime():e.start_time),u.replicates){let f={url:s,ca:c,replicates:!0};e.start_time&&(f.start_time=e.start_time),await yi(ot(),f)}return await yi(d.nodeName,u),e.operation==="update_node"?`Successfully updated '${t}'`:`Successfully added '${t}' to cluster`}async function g9(e){Wn.trace("addNodeBack received request:",e);let t=await(0,Qn.signCertificate)(e),r;e.csr?(r=t.signingCA,Wn.info("addNodeBack received CSR from node:",e.url,"this node will use and respond with CA that was used to issue CSR")):(r=e?.cert_auth,Wn.info("addNodeBack received CA from node:",e.url));let n={url:e.url,ca:r};e.subscriptions?n.subscriptions=e.subscriptions:n.replicates=!0,e.start_time&&(n.start_time=e.start_time);let s=await(0,Qn.getReplicationCertAuth)();if(n.replicates){let i={url:po(),ca:s?.certificate,replicates:!0};e.start_time&&(i.start_time=e.start_time),await yi(ot(),i)}return await yi(e.hostname,n),t.nodeName=ot(),t.usingCA=s?.certificate,Wn.info("addNodeBack responding to:",e.url,"with CA named:",s?.name),t}async function R9(e){Wn.trace("removeNodeBack received request:",e),await Br().delete(e.name)}function xv(e){let{subscribe:t,publish:r}=e;return{...e,subscribe:r,publish:t}}var Qn,Bv,jc,Hv,hd,Wn,zs,m9,p9,S9,Ra=Oe(()=>{Qn=U(To()),Bv=U(mt()),jc=U(require("joi")),Hv=U(ie()),hd=U(H());ad();od();Ai();Wn=U(X()),zs=U(ce()),{pki:m9}=require("node-forge"),{HTTP_STATUS_CODES:p9}=zs.hdb_errors,S9=jc.default.object({hostname:jc.default.string(),verify_tls:jc.default.boolean(),replicates:jc.default.boolean(),subscriptions:jc.default.array()});a(T9,"setNode");a(g9,"addNodeBack");a(R9,"removeNodeBack");a(xv,"reverseSubscription")});var lh=I((NTe,Fv)=>{"use strict";var{handleHDBError:ih,hdb_errors:A9}=ce(),{HTTP_STATUS_CODES:oh}=A9,{addUpdateNodeValidator:b9}=wE(),ah=X(),ch=H(),kv=Pt(),y9=re(),md=or(),pd=Ri(),JR=ie(),O9=yR(),{Node:N9,NodeSubscription:I9}=xc(),{broadcast:w9}=at(),{setNode:C9}=(Ra(),ae(ga)),yTe=ie(),OTe=H(),D9="Unable to create subscriptions due to schema and/or tables not existing on the local or remote node",L9="Some subscriptions were unsuccessful due to schema and/or tables not existing on the local or remote node",P9=JR.get(ch.CONFIG_PARAMS.CLUSTERING_NODENAME);Fv.exports=M9;async function M9(e,t=!1){if(ah.trace("addNode called with:",e),JR.get(ch.CONFIG_PARAMS.REPLICATION_URL)||JR.get(ch.CONFIG_PARAMS.REPLICATION_HOSTNAME))return C9(e);pd.checkClusteringEnabled();let r=b9(e);if(r)throw ih(r,r.message,oh.BAD_REQUEST,void 0,void 0,!0);let n=e.node_name;if(!t){let f=await pd.getNodeRecord(n);if(!y9.isEmptyOrZeroLength(f))throw ih(new Error,`Node '${n}' has already been added, perform update_node to proceed.`,oh.BAD_REQUEST,void 0,void 0,!0)}let{added:s,skipped:i}=await O9(e.subscriptions,n),o={message:void 0,added:s,skipped:i};if(s.length===0)return o.message=D9,o;let c=pd.buildNodePayloads(s,P9,ch.OPERATIONS_ENUM.ADD_NODE,await pd.getSystemInfo()),l=[];for(let f=0,E=s.length;f<E;f++){let _=s[f];s[f].start_time===void 0&&delete s[f].start_time,l.push(new I9(_.schema,_.table,_.publish,_.subscribe))}ah.trace("addNode sending remote payload:",c);let d;try{d=await md.request(`${n}.${kv.REQUEST_SUFFIX}`,c)}catch(f){ah.error(`addNode received error from request: ${f}`);for(let _=0,h=s.length;_<h;_++){let p=s[_];p.publish=!1,p.subscribe=!1,await md.updateRemoteConsumer(p,n)}let E=md.requestErrorHandler(f,"add_node",n);throw ih(new Error,E,oh.INTERNAL_SERVER_ERROR,"error",E)}if(d.status===kv.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let f=`Error returned from remote node ${n}: ${d.message}`;throw ih(new Error,f,oh.INTERNAL_SERVER_ERROR,"error",f)}ah.trace(d);for(let f=0,E=s.length;f<E;f++){let _=s[f];await md.updateRemoteConsumer(_,n),_.subscribe===!0&&await md.updateConsumerIterator(_.schema,_.table,n,"start")}let u=new N9(n,l,d.system_info);return await pd.upsertNodeRecord(u),w9({type:"nats_update"}),i.length>0?o.message=L9:o.message=`Successfully added '${n}' to manifest`,o}a(M9,"addNode")});var tA=I((CTe,qv)=>{"use strict";var{handleHDBError:XR,hdb_errors:U9}=ce(),{HTTP_STATUS_CODES:ZR}=U9,{addUpdateNodeValidator:v9}=wE(),Sd=X(),uh=H(),Gv=Pt(),wTe=re(),Td=or(),gd=Ri(),eA=ie(),{cloneDeep:x9}=require("lodash"),B9=yR(),{Node:H9,NodeSubscription:k9}=xc(),{broadcast:F9}=at(),{setNode:G9}=(Ra(),ae(ga)),q9="Unable to update subscriptions due to schema and/or tables not existing on the local or remote node",V9="Some subscriptions were unsuccessful due to schema and/or tables not existing on the local or remote node",$9=eA.get(uh.CONFIG_PARAMS.CLUSTERING_NODENAME);qv.exports=Y9;async function Y9(e){if(Sd.trace("updateNode called with:",e),eA.get(uh.CONFIG_PARAMS.REPLICATION_URL)??eA.get(uh.CONFIG_PARAMS.REPLICATION_HOSTNAME))return G9(e);gd.checkClusteringEnabled();let t=v9(e);if(t)throw XR(t,t.message,ZR.BAD_REQUEST,void 0,void 0,!0);let r=e.node_name,n,s=await gd.getNodeRecord(r);s.length>0&&(n=x9(s));let{added:i,skipped:o}=await B9(e.subscriptions,r),c={message:void 0,updated:i,skipped:o};if(i.length===0)return c.message=q9,c;let l=gd.buildNodePayloads(i,$9,uh.OPERATIONS_ENUM.UPDATE_NODE,await gd.getSystemInfo());for(let u=0,f=i.length;u<f;u++){let E=i[u];Sd.trace(`updateNode updating work stream for node: ${r} subscription:`,E),i[u].start_time===void 0&&delete i[u].start_time}Sd.trace("updateNode sending remote payload:",l);let d;try{d=await Td.request(`${r}.${Gv.REQUEST_SUFFIX}`,l)}catch(u){Sd.error(`updateNode received error from request: ${u}`);let f=Td.requestErrorHandler(u,"update_node",r);throw XR(new Error,f,ZR.INTERNAL_SERVER_ERROR,"error",f)}if(d.status===Gv.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let u=`Error returned from remote node ${r}: ${d.message}`;throw XR(new Error,u,ZR.INTERNAL_SERVER_ERROR,"error",u)}Sd.trace(d);for(let u=0,f=i.length;u<f;u++){let E=i[u];await Td.updateRemoteConsumer(E,r),E.subscribe===!0?await Td.updateConsumerIterator(E.schema,E.table,r,"start"):await Td.updateConsumerIterator(E.schema,E.table,r,"stop")}return n||(n=[new H9(r,[],d.system_info)]),await K9(n[0],i,d.system_info),o.length>0?c.message=V9:c.message=`Successfully updated '${r}'`,c}a(Y9,"updateNode");async function K9(e,t,r){let n=e;for(let s=0,i=t.length;s<i;s++){let o=t[s],c=!1;for(let l=0,d=e.subscriptions.length;l<d;l++){let u=n.subscriptions[l];if(u.schema===o.schema&&u.table===o.table){u.publish=o.publish,u.subscribe=o.subscribe,c=!0;break}}c||n.subscriptions.push(new k9(o.schema,o.table,o.publish,o.subscribe))}n.system_info=r,await gd.upsertNodeRecord(n),F9({type:"nats_update"})}a(K9,"updateNodeTable")});var Wv=I((LTe,Kv)=>{"use strict";var Yv=require("joi"),{string:Vv}=Yv.types(),W9=mt(),$v=H(),Q9=ie(),z9=Pt();Kv.exports=j9;function j9(e){let t=Vv.invalid(Q9.get($v.CONFIG_PARAMS.CLUSTERING_NODENAME)).pattern(z9.NATS_TERM_CONSTRAINTS_RX).messages({"string.pattern.base":"{:#label} invalid, must not contain ., * or >","any.invalid":"'node_name' cannot be this nodes name"}).empty(null),r=Yv.object({operation:Vv.valid($v.OPERATIONS_ENUM.REMOVE_NODE).required(),node_name:t});return W9.validateBySchema(e,r)}a(j9,"removeNodeValidator")});var dh=I((MTe,Xv)=>{"use strict";var{handleHDBError:Qv,hdb_errors:J9}=ce(),{HTTP_STATUS_CODES:zv}=J9,X9=Wv(),Rd=X(),jv=Ri(),Z9=re(),Jc=H(),Jv=Pt(),rA=or(),nA=ie(),{RemotePayloadObject:e7}=Zu(),{NodeSubscription:t7}=xc(),r7=Fu(),n7=Jo(),{broadcast:s7}=at(),{setNode:i7}=(Ra(),ae(ga)),o7=nA.get(Jc.CONFIG_PARAMS.CLUSTERING_NODENAME);Xv.exports=a7;async function a7(e){if(Rd.trace("removeNode called with:",e),nA.get(Jc.CONFIG_PARAMS.REPLICATION_URL)??nA.get(Jc.CONFIG_PARAMS.REPLICATION_HOSTNAME))return i7(e);jv.checkClusteringEnabled();let t=X9(e);if(t)throw Qv(t,t.message,zv.BAD_REQUEST,void 0,void 0,!0);let r=e.node_name,n=await jv.getNodeRecord(r);if(Z9.isEmptyOrZeroLength(n))throw Qv(new Error,`Node '${r}' was not found.`,zv.BAD_REQUEST,void 0,void 0,!0);n=n[0];let s=new e7(Jc.OPERATIONS_ENUM.REMOVE_NODE,o7,[]),i,o=!1;for(let l=0,d=n.subscriptions.length;l<d;l++){let u=n.subscriptions[l];u.subscribe===!0&&await rA.updateConsumerIterator(u.schema,u.table,r,"stop");try{await rA.updateRemoteConsumer(new t7(u.schema,u.table,!1,!1),r)}catch(f){Rd.error(f)}}try{i=await rA.request(`${r}.${Jv.REQUEST_SUFFIX}`,s),Rd.trace("Remove node reply from remote node:",r,i)}catch(l){Rd.error("removeNode received error from request:",l),o=!0}let c=new r7(Jc.SYSTEM_SCHEMA_NAME,Jc.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[r]);return await n7.deleteRecord(c),s7({type:"nats_update"}),i?.status===Jv.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR||o?(Rd.error("Error returned from remote node:",r,i?.message),`Successfully removed '${r}' from local manifest, however there was an error reaching remote node. Check the logs for more details.`):`Successfully removed '${r}' from manifest`}a(a7,"removeNode")});var t0=I((vTe,e0)=>{"use strict";var Zv=require("joi"),{string:c7,array:l7}=Zv.types(),u7=mt(),d7=wE();e0.exports=f7;function f7(e){let t=Zv.object({operation:c7.valid("configure_cluster").required(),connections:l7.items(d7.validation_schema).required()});return u7.validateBySchema(e,t)}a(f7,"configureClusterValidator")});var sA=I((BTe,o0)=>{"use strict";var r0=H(),fh=X(),_7=re(),E7=ie(),h7=dh(),m7=lh(),p7=Ri(),S7=t0(),{handleHDBError:n0,hdb_errors:T7}=ce(),{HTTP_STATUS_CODES:s0}=T7,g7="Configure cluster complete.",R7="Failed to configure the cluster. Check the logs for more details.",A7="Configure cluster was partially successful. Errors occurred when attempting to configure the following nodes. Check the logs for more details.";o0.exports=b7;async function b7(e){fh.trace("configure cluster called with:",e);let t=S7(e);if(t)throw n0(t,t.message,s0.BAD_REQUEST,void 0,void 0,!0);let r=await p7.getAllNodeRecords(),n=[];if(E7.get(r0.CONFIG_PARAMS.CLUSTERING_ENABLED)){for(let u=0,f=r.length;u<f;u++){let E=await i0(h7,{operation:r0.OPERATIONS_ENUM.REMOVE_NODE,node_name:r[u].name},r[u].name);n.push(E)}fh.trace("All results from configure_cluster remove node:",n)}let s=[],i=e.connections.length;for(let u=0;u<i;u++){let f=e.connections[u],E=await i0(m7,f,f.node_name);s.push(E)}fh.trace("All results from configure_cluster add node:",s);let o=[],c=[],l=!1,d=n.concat(s);for(let u=0,f=d.length;u<f;u++){let E=d[u];E.status==="rejected"&&(fh.error(E.node_name,E?.error?.message,E?.error?.stack),o.includes(E.node_name)||o.push(E.node_name)),(E?.result?.message?.includes?.("Successfully")||E?.result?.includes?.("Successfully"))&&(l=!0),!(typeof E.result=="string"&&E.result.includes("Successfully removed")||E.status==="rejected")&&c.push({node_name:E?.node_name,response:E?.result})}if(_7.isEmptyOrZeroLength(o))return{message:g7,connections:c};if(l)return{message:A7,failed_nodes:o,connections:c};throw n0(new Error,R7,s0.INTERNAL_SERVER_ERROR,void 0,void 0,!0)}a(b7,"configureCluster");async function i0(e,t,r){try{return{node_name:r,result:await e(t)}}catch(n){return{node_name:r,error:n,status:"rejected"}}}a(i0,"functionWrapper")});var u0=I((kTe,l0)=>{"use strict";var Ad=require("joi"),y7=mt(),{validateSchemaExists:a0,validateTableExists:O7,validateSchemaName:c0}=xs(),N7=Ad.object({operation:Ad.string().valid("purge_stream"),schema:Ad.string().custom(a0).custom(c0).optional(),database:Ad.string().custom(a0).custom(c0).optional(),table:Ad.string().custom(O7).required()});function I7(e){return y7.validateBySchema(e,N7)}a(I7,"purgeStreamValidator");l0.exports=I7});var iA=I((GTe,d0)=>{"use strict";var{handleHDBError:w7,hdb_errors:C7}=ce(),{HTTP_STATUS_CODES:D7}=C7,L7=u0(),P7=or(),M7=Ri();d0.exports=U7;async function U7(e){e.schema=e.schema??e.database;let t=L7(e);if(t)throw w7(t,t.message,D7.BAD_REQUEST,void 0,void 0,!0);M7.checkClusteringEnabled();let{schema:r,table:n,options:s}=e;return await P7.purgeTableStream(r,n,s),`Successfully purged table '${r}.${n}'`}a(U7,"purgeStream")});var cA=I((VTe,S0)=>{"use strict";var aA=Ri(),v7=or(),_h=ie(),Xc=H(),Aa=Pt(),x7=re(),oA=X(),{RemotePayloadObject:B7}=Zu(),{ErrorCode:f0}=require("nats"),{parentPort:_0}=require("worker_threads"),{onMessageByType:H7}=at(),{getThisNodeName:k7}=(Ai(),ae(dd)),{requestClusterStatus:F7}=(ad(),ae(kU)),E0=_h.get(Xc.CONFIG_PARAMS.CLUSTERING_ENABLED),h0=_h.get(Xc.CONFIG_PARAMS.CLUSTERING_NODENAME);S0.exports={clusterStatus:G7,buildNodeStatus:p0};var m0;H7("cluster-status",async e=>{m0(e)});async function G7(){if(_h.get(Xc.CONFIG_PARAMS.REPLICATION_URL)||_h.get(Xc.CONFIG_PARAMS.REPLICATION_HOSTNAME)){let n;return _0?(_0.postMessage({type:"request-cluster-status"}),n=await new Promise(s=>{m0=s})):n=await F7(),n.node_name=k7(),n.is_enabled=!0,n}let e={node_name:h0,is_enabled:E0,connections:[]};if(!E0)return e;let t=await aA.getAllNodeRecords();if(x7.isEmptyOrZeroLength(t))return e;let r=[];for(let n=0,s=t.length;n<s;n++)r.push(p0(t[n],e.connections));return await Promise.allSettled(r),e}a(G7,"clusterStatus");async function p0(e,t){let r=e.name,n=new B7(Xc.OPERATIONS_ENUM.CLUSTER_STATUS,h0,void 0,await aA.getSystemInfo()),s,i,o=Aa.CLUSTER_STATUS_STATUSES.OPEN;try{let l=Date.now();s=await v7.request(Aa.REQUEST_SUBJECT(r),n),i=Date.now()-l,s.status===Aa.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR&&(o=Aa.CLUSTER_STATUS_STATUSES.CLOSED,oA.error(`Error getting node status from ${r} `,s))}catch(l){oA.warn(`Error getting node status from ${r}`,l),l.code===f0.NoResponders?o=Aa.CLUSTER_STATUS_STATUSES.NO_RESPONDERS:l.code===f0.Timeout?o=Aa.CLUSTER_STATUS_STATUSES.TIMEOUT:o=Aa.CLUSTER_STATUS_STATUSES.CLOSED}let c=new q7(r,o,s?.message?.ports?.clustering,s?.message?.ports?.operations_api,i,s?.message?.uptime,e.subscriptions,s?.message?.system_info);try{let l={name:r,system_info:s?.message?.system_info};e.system_info?.hdb_version!==Xc.PRE_4_0_0_VERSION&&await aA.upsertNodeRecord(l)}catch(l){oA.error("Cluster status encountered an error updating system info for node:",r,l)}t.push(c)}a(p0,"buildNodeStatus");function q7(e,t,r,n,s,i,o,c){this.node_name=e,this.status=t,this.ports={clustering:r,operations_api:n},this.latency_ms=s,this.uptime=i,this.subscriptions=o,this.system_info=c}a(q7,"NodeStatusObject")});var uA=I((YTe,T0)=>{"use strict";var{handleHDBError:V7,hdb_errors:$7}=ce(),{HTTP_STATUS_CODES:Y7}=$7,K7=or(),W7=Ri(),lA=re(),Eh=require("joi"),Q7=mt(),z7=2e3,j7=Eh.object({timeout:Eh.number().min(1),connected_nodes:Eh.boolean(),routes:Eh.boolean()});T0.exports=J7;async function J7(e){W7.checkClusteringEnabled();let t=Q7.validateBySchema(e,j7);if(t)throw V7(t,t.message,Y7.BAD_REQUEST,void 0,void 0,!0);let{timeout:r,connected_nodes:n,routes:s}=e,i=n===void 0||lA.autoCastBoolean(n),o=s===void 0||lA.autoCastBoolean(s),c={nodes:[]},l=await K7.getServerList(r??z7),d={};if(i)for(let u=0,f=l.length;u<f;u++){let E=l[u].statsz;E&&(d[l[u].server.name]=E.routes)}for(let u=0,f=l.length;u<f;u++){if(l[u].statsz)continue;let E=l[u].server,_=l[u].data;if(E.name.endsWith("-hub")){let h={name:E.name.slice(0,-4),response_time:l[u].response_time};i&&(h.connected_nodes=[],d[E.name]&&d[E.name].forEach(p=>{h.connected_nodes.includes(p.name.slice(0,-4))||h.connected_nodes.push(p.name.slice(0,-4))})),o&&(h.routes=_.cluster?.urls?_.cluster?.urls.map(p=>({host:p.split(":")[0],port:lA.autoCast(p.split(":")[1])})):[]),c.nodes.push(h)}}return c}a(J7,"clusterNetwork")});var b0=I((WTe,A0)=>{"use strict";var dA=require("joi"),g0=mt(),{route_constraints:R0}=ET();A0.exports={setRoutesValidator:X7,deleteRoutesValidator:Z7};function X7(e){let t=dA.object({server:dA.valid("hub","leaf"),routes:R0.required()});return g0.validateBySchema(e,t)}a(X7,"setRoutesValidator");function Z7(e){let t=dA.object({routes:R0.required()});return g0.validateBySchema(e,t)}a(Z7,"deleteRoutesValidator")});var _A=I((zTe,D0)=>{"use strict";var Ni=dr(),fA=re(),zn=H(),Zc=ie(),y0=b0(),{handleHDBError:O0,hdb_errors:eee}=ce(),{HTTP_STATUS_CODES:N0}=eee,I0="cluster routes successfully set",w0="cluster routes successfully deleted";D0.exports={setRoutes:ree,getRoutes:nee,deleteRoutes:see};function tee(e){let t=Ni.getClusteringRoutes(),r=e.server==="hub"?t.hub_routes:t.leaf_routes,n=e.server==="hub"?t.leaf_routes:t.hub_routes,s=[],i=[];for(let o=0,c=e.routes.length;o<c;o++){let l=e.routes[o];l.port=fA.autoCast(l.port);let d=r.some(f=>f.host===l.host&&f.port===l.port),u=n.some(f=>f.host===l.host&&f.port===l.port);d||u?s.push(l):(r.push(l),i.push(l))}return e.server==="hub"?Ni.updateConfigValue(zn.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,r):Ni.updateConfigValue(zn.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,r),{message:I0,set:i,skipped:s}}a(tee,"setRoutesNats");function ree(e){let t=y0.setRoutesValidator(e);if(t)throw O0(t,t.message,N0.BAD_REQUEST,void 0,void 0,!0);if(Zc.get(zn.CONFIG_PARAMS.CLUSTERING_ENABLED))return tee(e);let r=[],n=[],s=Zc.get(zn.CONFIG_PARAMS.REPLICATION_ROUTES)??[];return e.routes.forEach(i=>{C0(s,i)?n.push(i):(s.push(i),r.push(i))}),Ni.updateConfigValue(zn.CONFIG_PARAMS.REPLICATION_ROUTES,s),{message:I0,set:r,skipped:n}}a(ree,"setRoutes");function C0(e,t){return typeof t=="string"?e.includes(t):typeof t=="object"&&t!==null?e.some(r=>(r.host===t.host||r.hostname===t.hostname)&&r.port===t.port):!1}a(C0,"existsInArray");function nee(){if(Zc.get(zn.CONFIG_PARAMS.CLUSTERING_ENABLED)){let e=Ni.getClusteringRoutes();return{hub:e.hub_routes,leaf:e.leaf_routes}}else return Zc.get(zn.CONFIG_PARAMS.REPLICATION_ROUTES)??[]}a(nee,"getRoutes");function see(e){let t=y0.deleteRoutesValidator(e);if(t)throw O0(t,t.message,N0.BAD_REQUEST,void 0,void 0,!0);if(Zc.get(zn.CONFIG_PARAMS.CLUSTERING_ENABLED))return iee(e);let r=[],n=[],s=Zc.get(zn.CONFIG_PARAMS.REPLICATION_ROUTES)??[],i=[];return s.forEach(o=>{C0(e.routes,o)?r.push(o):(i.push(o),n.push(o))}),Ni.updateConfigValue(zn.CONFIG_PARAMS.REPLICATION_ROUTES,i),{message:w0,deleted:r,skipped:n}}a(see,"deleteRoutes");function iee(e){let t=Ni.getClusteringRoutes(),r=t.hub_routes,n=t.leaf_routes,s=[],i=[],o=!1,c=!1;for(let l=0,d=e.routes.length;l<d;l++){let u=e.routes[l],f=!1;for(let E=0,_=r.length;E<_;E++){let h=r[E];if(u.host===h.host&&u.port===h.port){r.splice(E,1),f=!0,o=!0,s.push(u);break}}if(!f){let E=!0;for(let _=0,h=n.length;_<h;_++){let p=n[_];if(u.host===p.host&&u.port===p.port){n.splice(_,1),c=!0,E=!1,s.push(u);break}}E&&i.push(u)}}return o&&(r=fA.isEmptyOrZeroLength(r)?null:r,Ni.updateConfigValue(zn.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,r)),c&&(n=fA.isEmptyOrZeroLength(n)?null:n,Ni.updateConfigValue(zn.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,n)),{message:w0,deleted:s,skipped:i}}a(iee,"deleteRoutesNats")});var P0=I((JTe,L0)=>{"use strict";var bd=require("alasql"),ba=require("recursive-iterator"),gs=X(),oee=re(),yd=H(),EA=class{static{a(this,"sql_statement_bucket")}constructor(t){this.ast=t,this.affected_attributes=new Map,this.table_lookup=new Map,this.schema_lookup=new Map,this.table_to_schema_lookup=new Map,cee(this.ast,this.affected_attributes,this.table_lookup,this.schema_lookup,this.table_to_schema_lookup)}getAttributesBySchemaTableName(t,r){if(!t||!r||!this.affected_attributes)return[];if(this.affected_attributes.has(t))return!this.affected_attributes.get(t).has(r)&&(r=this.table_lookup.get(r),!r)?[]:this.affected_attributes.get(t).get(r)}getAllTables(){let t=[];if(!this.affected_attributes)return t;for(let r of this.affected_attributes.keys())t.push(Array.from(this.affected_attributes.get(r).keys()));return t}getTablesBySchemaName(t){return!t||!this.affected_attributes?[]:Array.from(this.affected_attributes.get(t).keys())}getSchemas(){return this.affected_attributes?Array.from(this.affected_attributes.keys()):[]}getAst(){return this.ast}updateAttributeWildcardsForRolePerms(t){let r=this.ast.columns.filter(s=>yd.SEARCH_WILDCARDS.includes(s.columnid));if(r.length===0)return this.ast;let n=this.ast.from[0].databaseid;return this.ast.columns=this.ast.columns.filter(s=>!yd.SEARCH_WILDCARDS.includes(s.columnid)),r.forEach(s=>{let i=this.table_to_schema_lookup.has(s.tableid)?this.table_to_schema_lookup.get(s.tableid):n,o=this.table_lookup.has(s.tableid)?this.table_lookup.get(s.tableid):this.ast.from[0].tableid;if(t[i]&&t[i].tables[o]&&t[i].tables[o][yd.PERMS_CRUD_ENUM.READ]){let c;t[i].tables[o].attribute_permissions.length>0?c=aee(t[i].tables[o].attribute_permissions):c=global.hdb_schema[i][o].attributes.map(d=>({attribute_name:d.attribute}));let l=this.affected_attributes.get(i).get(o).filter(d=>!yd.SEARCH_WILDCARDS.includes(d));c.forEach(({attribute_name:d})=>{let u=new bd.yy.Column({columnid:d});s.tableid&&(u.tableid=s.tableid),this.ast.columns.push(u),l.includes(d)||l.push(d)}),this.affected_attributes.get(i).set(o,l)}}),this.ast}};function aee(e){return e.filter(t=>t[yd.PERMS_CRUD_ENUM.READ])}a(aee,"filterReadRestrictedAttrs");function cee(e,t,r,n,s){lee(e,t,r,n,s)}a(cee,"interpretAST");function Od(e,t,r,n,s){if(!(!e||!e.databaseid)&&(t.has(e.databaseid)||t.set(e.databaseid,new Map),t.get(e.databaseid).has(e.tableid)||t.get(e.databaseid).set(e.tableid,[]),e.as&&(r.has(e.as)||r.set(e.as,e.tableid),n&&!n.has(e.as)&&n.set(e.as,e.databaseid)),s)){let i=e.databaseid,o=e.tableid;e.as&&(o=e.as),s.set(o,i)}}a(Od,"addSchemaTableToMap");function lee(e,t,r,n,s){if(!e){gs.info("getRecordAttributesAST: invalid SQL syntax tree");return}e instanceof bd.yy.Insert?_ee(e,t,r):e instanceof bd.yy.Select?uee(e,t,r,n,s):e instanceof bd.yy.Update?dee(e,t,r):e instanceof bd.yy.Delete?fee(e,t,r):gs.error("AST in getRecordAttributesAST() is not a valid SQL type.")}a(lee,"getRecordAttributesAST");function uee(e,t,r,n,s){if(!e){gs.info("getSelectAttributes: invalid SQL syntax tree");return}if(!e.from||e.from[0]===void 0)return;let i=e.from[0].databaseid;if(oee.isEmptyOrZeroLength(i)){gs.error("No schema specified");return}e.from.forEach(c=>{Od(c,t,r,n,s)}),e.joins&&e.joins.forEach(c=>{c.as&&(c.table.as=c.as),Od(c.table,t,r,n,s)});let o=new ba(e.columns);for(let{node:c}of o)if(c&&c.columnid){let l=c.tableid,d=n.has(l)?n.get(l):i;if(l||(l=e.from[0].tableid),!t.get(d).has(l))if(r.has(l))l=r.get(l);else{gs.info(`table specified as ${l} not found.`);return}t.get(d).get(l).indexOf(c.columnid)<0&&t.get(d).get(l).push(c.columnid)}if(e.where){let c=new ba(e.where),l=e.from[0].tableid;for(let{node:d}of c)if(d&&d.columnid){let u=d.tableid?d.tableid:l;if(!t.get(i).has(u))if(r.has(u))u=r.get(u);else{gs.info(`table specified as ${u} not found.`);continue}t.get(i).get(u).indexOf(d.columnid)<0&&t.get(i).get(u).push(d.columnid)}}if(e.joins&&e.joins.forEach(c=>{let l=new ba(c.on);for(let{node:d}of l)if(d&&d.columnid){let u=d.tableid,f=s.get(u);if(!t.get(f).has(u))if(r.has(u))u=r.get(u);else{gs.info(`table specified as ${u} not found.`);continue}t.get(f).get(u).indexOf(d.columnid)<0&&t.get(f).get(u).push(d.columnid)}}),e.order){let c=new ba(e.order);for(let{node:l}of c)if(l&&l.columnid){let d=l.tableid,u=n.has(d)?n.get(d):i;if(d||(d=e.from[0].tableid),!t.get(u).has(d))if(r.has(d))d=r.get(d);else{gs.info(`table specified as ${d} not found.`);return}t.get(u).get(d).indexOf(l.columnid)<0&&t.get(u).get(d).push(l.columnid)}}}a(uee,"getSelectAttributes");function dee(e,t,r){if(!e){gs.info("getUpdateAttributes: invalid SQL syntax tree");return}let n=new ba(e.columns),s=e.table.databaseid;Od(e.table,t,r);for(let{node:i}of n)i&&i.columnid&&hA(e.table.tableid,s,i.columnid,t,r)}a(dee,"getUpdateAttributes");function fee(e,t,r){if(!e){gs.info("getDeleteAttributes: invalid SQL syntax tree");return}let n=new ba(e.where),s=e.table.databaseid;Od(e.table,t,r);for(let{node:i}of n)i&&i.columnid&&hA(e.table.tableid,s,i.columnid,t,r)}a(fee,"getDeleteAttributes");function _ee(e,t,r){if(!e){gs.info("getInsertAttributes: invalid SQL syntax tree");return}let n=new ba(e.columns),s=e.into.databaseid;Od(e.into,t,r);for(let{node:i}of n)i&&i.columnid&&hA(e.into.tableid,s,i.columnid,t,r)}a(_ee,"getInsertAttributes");function hA(e,t,r,n,s){if(!n.get(t))return;let i=e;n.get(t).has(i)||(i=s.get(i)),n.get(t).get(i).push(r)}a(hA,"pushAttribute");L0.exports=EA});var SA=I((ZTe,x0)=>{var hh=ea(),M0=require("chalk"),In=X(),U0=require("prompt"),{promisify:Eee}=require("util"),mA=H(),hee=require("fs-extra"),mee=require("path"),pee=re(),See=vE(),v0=ie();v0.initSync();var Tee=require("moment"),gee=Eee(U0.get),Ree=mee.join(v0.getHdbBasePath(),mA.LICENSE_KEY_DIR_NAME,mA.LICENSE_FILE_NAME,mA.LICENSE_FILE_NAME);x0.exports={getFingerprint:bee,setLicense:Aee,parseLicense:pA,register:yee,getRegistrationInfo:Nee};async function Aee(e){if(e&&e.key&&e.company){try{In.info(`parsing license key: ${e.key} and `);let t=e.company.toString();await pA(e.key.trim(),t.trim())}catch(t){let r="There was an error parsing the license key.";throw In.error(r),In.error(t),new Error(r)}return"Wrote license key file. Registration successful."}throw new Error("Invalid key or company specified for license file.")}a(Aee,"setLicense");async function bee(){let e={};try{e=await hh.generateFingerPrint()}catch(t){let r="Error generating fingerprint.";throw In.error(r),In.error(t),new Error(r)}return e}a(bee,"getFingerprint");async function pA(e,t){if(!e||!t)throw new Error("Invalid entries for License Key and Customer Company");In.info("Validating license input...");let r=hh.validateLicense(e,t);if(In.info("checking for valid license..."),!r.valid_license)throw new Error("Invalid license found.");if(In.info("checking valid license date..."),!r.valid_date)throw new Error("This License has expired.");if(In.info(`checking for valid machine license ${r.valid_machine}`),!r.valid_machine)throw new Error("This license is in use on another machine.");try{In.info("writing license to disk"),await hee.writeFile(Ree,JSON.stringify({license_key:e,company:t}))}catch(n){throw In.error("Failed to write License"),n}return"Registration successful."}a(pA,"parseLicense");async function yee(){let e=await Oee();return pA(e.HDB_LICENSE,e.CUSTOMER_COMPANY)}a(yee,"register");async function Oee(){let e=await hh.generateFingerPrint(),t={properties:{CUSTOMER_COMPANY:{description:M0.magenta("[COMPANY] Please enter your company name"),required:!0},HDB_LICENSE:{description:M0.magenta(`[HDB_LICENSE] Your fingerprint is ${e} Please enter your license key`),required:!0}}};try{U0.start()}catch(n){In.error(n)}let r;try{r=await gee(t)}catch(n){throw console.error("There was a problem prompting for registration input. Exiting."),n}return r}a(Oee,"promptForRegistration");async function Nee(){let e={registered:!1,version:null,ram_allocation:null,license_expiration_date:null},t;try{t=await hh.getLicense()}catch(r){throw In.error(`There was an error when searching licenses due to: ${r.message}`),r}if(pee.isEmptyOrZeroLength(t))throw new Error("There were no licenses found.");if(e.registered=t.enterprise,e.version=See.version(),e.ram_allocation=t.ram_allocation,isNaN(t.exp_date))e.license_expiration_date=t.enterprise?t.exp_date:null;else{let r=Tee.utc(t.exp_date).format("YYYY-MM-DD");e.license_expiration_date=t.enterprise?r:null}return e}a(Nee,"getRegistrationInfo")});var H0=I((tge,B0)=>{"use strict";var Iee=Pt(),TA=class{static{a(this,"HubConfigObject")}constructor(t,r,n,s,i,o,c,l,d,u,f,E,_,h){this.port=t,o===null&&(o=void 0),this.server_name=r+Iee.SERVER_SUFFIX.HUB,this.pid_file=n,this.max_payload=67108864,this.reconnect_error_reports=100,this.jetstream={enabled:!1},this.tls={cert_file:s,key_file:i,ca_file:o,insecure:c,verify:l},this.leafnodes={port:d,tls:{cert_file:s,key_file:i,ca_file:o,insecure:c}},this.cluster={name:u,port:f,routes:E,tls:{cert_file:s,key_file:i,ca_file:o,insecure:c,verify:l}},this.accounts={SYS:{users:_},HDB:{users:h}},this.system_account="SYS"}};B0.exports=TA});var G0=I((nge,F0)=>{"use strict";var k0=Pt(),gA=class{static{a(this,"LeafConfigObject")}constructor(t,r,n,s,i,o,c,l,d,u,f){this.port=t,f===null&&(f=void 0),this.server_name=r+k0.SERVER_SUFFIX.LEAF,this.pid_file=n,this.max_payload=67108864,this.jetstream={enabled:!0,store_dir:s,domain:r+k0.SERVER_SUFFIX.LEAF},this.tls={cert_file:d,key_file:u,ca_file:f,insecure:!0},this.leafnodes={remotes:[{tls:{ca_file:f,insecure:!0},urls:i,account:"SYS"},{tls:{ca_file:f,insecure:!0},urls:o,account:"HDB"}]},this.accounts={SYS:{users:c},HDB:{users:l,jetstream:"enabled"}},this.system_account="SYS"}};F0.exports=gA});var V0=I((ige,q0)=>{"use strict";var RA=class{static{a(this,"HdbUserObject")}constructor(t,r){this.user=t,this.password=r}};q0.exports=RA});var Y0=I((age,$0)=>{"use strict";var wee=Pt(),AA=class{static{a(this,"SysUserObject")}constructor(t,r){this.user=t+wee.SERVER_SUFFIX.ADMIN,this.password=r}};$0.exports=AA});var OA=I((lge,Q0)=>{"use strict";var el=require("path"),tl=require("fs-extra"),Cee=H0(),Dee=G0(),Lee=V0(),Pee=Y0(),bA=$n(),nl=re(),en=dr(),ph=H(),Nd=Pt(),{CONFIG_PARAMS:Vt}=ph,sl=X(),Id=ie(),K0=mi(),yA=or(),Mee=To(),rl="clustering",Uee=1e4,W0=50;Q0.exports={generateNatsConfig:xee,removeNatsConfig:Bee,getHubConfigPath:vee};function vee(){let e=Id.get(Vt.ROOTPATH);return el.join(e,rl,Nd.NATS_CONFIG_FILES.HUB_SERVER)}a(vee,"getHubConfigPath");async function xee(e=!1,t=void 0){Id.initSync();let r=en.getConfigFromFile(Vt.CLUSTERING_TLS_CERT_AUTH),n=en.getConfigFromFile(Vt.CLUSTERING_TLS_PRIVATEKEY),s=en.getConfigFromFile(Vt.CLUSTERING_TLS_CERTIFICATE);!await tl.exists(s)&&!await tl.exists(!r)&&await Mee.createNatsCerts();let i=Id.get(Vt.ROOTPATH),o=el.join(i,rl,Nd.PID_FILES.HUB),c=el.join(i,rl,Nd.PID_FILES.LEAF),l=en.getConfigFromFile(Vt.CLUSTERING_LEAFSERVER_STREAMS_PATH),d=el.join(i,rl,Nd.NATS_CONFIG_FILES.HUB_SERVER),u=el.join(i,rl,Nd.NATS_CONFIG_FILES.LEAF_SERVER),f=en.getConfigFromFile(Vt.CLUSTERING_TLS_INSECURE),E=en.getConfigFromFile(Vt.CLUSTERING_TLS_VERIFY),_=en.getConfigFromFile(Vt.CLUSTERING_NODENAME),h=en.getConfigFromFile(Vt.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT);await yA.checkNATSServerInstalled()||Sh("nats-server dependency is either missing or the wrong version. Run 'npm install' to fix");let p=await bA.listUsers(),S=en.getConfigFromFile(Vt.CLUSTERING_USER),g=await bA.getClusterUser();(nl.isEmpty(g)||g.active!==!0)&&Sh(`Invalid cluster user '${S}'. A valid user with the role 'cluster_user' must be defined under clustering.user in harperdb-config.yaml`),e||(await mh(Vt.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),await mh(Vt.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT),await mh(Vt.CLUSTERING_HUBSERVER_NETWORK_PORT),await mh(Vt.CLUSTERING_LEAFSERVER_NETWORK_PORT));let T=[],A=[];for(let[ne,ee]of p.entries())ee.role.role===ph.ROLE_TYPES_ENUM.CLUSTER_USER&&ee.active&&(T.push(new Pee(ee.username,K0.decrypt(ee.hash))),A.push(new Lee(ee.username,K0.decrypt(ee.hash))));let N=[],{hub_routes:V}=en.getClusteringRoutes();if(!nl.isEmptyOrZeroLength(V))for(let ne of V)N.push(`tls://${g.sys_name_encoded}:${g.uri_encoded_d_hash}@${ne.host}:${ne.port}`);let v=new Cee(en.getConfigFromFile(Vt.CLUSTERING_HUBSERVER_NETWORK_PORT),_,o,s,n,r,f,E,h,en.getConfigFromFile(Vt.CLUSTERING_HUBSERVER_CLUSTER_NAME),en.getConfigFromFile(Vt.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),N,T,A);r==null&&(delete v.tls.ca_file,delete v.leafnodes.tls.ca_file),t=nl.isEmpty(t)?void 0:t.toLowerCase(),(t===void 0||t===ph.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase())&&(await tl.writeJson(d,v),sl.trace(`Hub server config written to ${d}`));let J=`tls://${g.sys_name_encoded}:${g.uri_encoded_d_hash}@0.0.0.0:${h}`,$=`tls://${g.uri_encoded_name}:${g.uri_encoded_d_hash}@0.0.0.0:${h}`,F=new Dee(en.getConfigFromFile(Vt.CLUSTERING_LEAFSERVER_NETWORK_PORT),_,c,l,[J],[$],T,A,s,n,r,f);r==null&&delete F.tls.ca_file,(t===void 0||t===ph.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())&&(await tl.writeJson(u,F),sl.trace(`Leaf server config written to ${u}`))}a(xee,"generateNatsConfig");async function mh(e){let t=Id.get(e);return nl.isEmpty(t)&&Sh(`port undefined for '${e}'`),await nl.isPortTaken(t)&&Sh(`'${e}' port '${t}' is is in use by another process, check to see if HarperDB is already running or another process is using this port.`),!0}a(mh,"isPortAvailable");function Sh(e){let t=`Error generating clustering config: ${e}`;sl.error(t),console.error(t),process.exit(1)}a(Sh,"generateNatsConfigError");async function Bee(e){let{port:t,config_file:r}=yA.getServerConfig(e),{username:n,decrypt_hash:s}=await bA.getClusterUser(),i=0,o=2e3;for(;i<W0;){try{let u=await yA.createConnection(t,n,s,!1);if(u.protocol.connected===!0){u.close();break}}catch(u){sl.trace(`removeNatsConfig waiting for ${e}. Caught and swallowed error ${u}`)}if(i++,i>=W0)throw new Error(`Operations API timed out attempting to connect to ${e}. This is commonly caused by incorrect clustering config. Check hdb.log for further details.`);let d=o*(i*2);d>3e4&&sl.notify("Operations API waiting for Nats server connection. This could be caused by large Nats streams or incorrect clustering config."),await nl.async_set_timeout(d)}let c="0".repeat(Uee),l=el.join(Id.get(Vt.ROOTPATH),rl,r);await tl.writeFile(l,c),await tl.remove(l),sl.notify(e,"started.")}a(Bee,"removeNatsConfig")});var ex=I((dge,Z0)=>{"use strict";var wn=ie(),Hee=ea(),Ue=H(),wd=Pt(),Ii=require("path"),{PACKAGE_ROOT:gh}=H(),z0=ie(),Th=re(),il="/dev/null",kee=Ii.join(gh,"launchServiceScripts"),j0=Ii.join(gh,"utility/scripts"),Fee=Ii.join(j0,Ue.HDB_RESTART_SCRIPT),J0=Ii.resolve(gh,"dependencies",`${process.platform}-${process.arch}`,wd.NATS_BINARY_NAME);function X0(){let t=Hee.licenseSearch().ram_allocation||Ue.RAM_ALLOCATION_ENUM.DEFAULT,r=Ue.MEM_SETTING_KEY+t,n={[Ue.PROCESS_NAME_ENV_PROP]:Ue.PROCESS_DESCRIPTORS.HDB,IS_SCRIPTED_SERVICE:!0};return Th.noBootFile()&&(n[Ue.CONFIG_PARAMS.ROOTPATH.toUpperCase()]=Th.getEnvCliRootPath()),{name:Ue.PROCESS_DESCRIPTORS.HDB,script:Ue.LAUNCH_SERVICE_SCRIPTS.MAIN,exec_mode:"fork",env:n,node_args:r,cwd:gh}}a(X0,"generateMainServerConfig");var Gee=9930;function qee(){wn.initSync(!0);let e=wn.get(Ue.CONFIG_PARAMS.ROOTPATH),t=Ii.join(e,"clustering",wd.NATS_CONFIG_FILES.HUB_SERVER),r=Ii.join(wn.get(Ue.HDB_SETTINGS_NAMES.LOG_PATH_KEY),Ue.LOG_NAMES.HDB),n=z0.get(Ue.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),s=wd.LOG_LEVEL_FLAGS[wn.get(Ue.CONFIG_PARAMS.CLUSTERING_LOGLEVEL)]??void 0,i={name:Ue.PROCESS_DESCRIPTORS.CLUSTERING_HUB+(n!==Gee?"-"+n:""),script:J0,args:s?`${s} -c ${t}`:`-c ${t}`,exec_mode:"fork",env:{[Ue.PROCESS_NAME_ENV_PROP]:Ue.PROCESS_DESCRIPTORS.CLUSTERING_HUB},merge_logs:!0,out_file:r,error_file:r,instances:1};return wn.get(Ue.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(i.out_file=il,i.error_file=il),i}a(qee,"generateNatsHubServerConfig");var Vee=9940;function $ee(){wn.initSync(!0);let e=wn.get(Ue.CONFIG_PARAMS.ROOTPATH),t=Ii.join(e,"clustering",wd.NATS_CONFIG_FILES.LEAF_SERVER),r=Ii.join(wn.get(Ue.HDB_SETTINGS_NAMES.LOG_PATH_KEY),Ue.LOG_NAMES.HDB),n=z0.get(Ue.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),s=wd.LOG_LEVEL_FLAGS[wn.get(Ue.CONFIG_PARAMS.CLUSTERING_LOGLEVEL)]??void 0,i={name:Ue.PROCESS_DESCRIPTORS.CLUSTERING_LEAF+(n!==Vee?"-"+n:""),script:J0,args:s?`${s} -c ${t}`:`-c ${t}`,exec_mode:"fork",env:{[Ue.PROCESS_NAME_ENV_PROP]:Ue.PROCESS_DESCRIPTORS.CLUSTERING_LEAF},merge_logs:!0,out_file:r,error_file:r,instances:1};return wn.get(Ue.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(i.out_file=il,i.error_file=il),i}a($ee,"generateNatsLeafServerConfig");function Yee(){wn.initSync();let e=Ii.join(wn.get(Ue.CONFIG_PARAMS.LOGGING_ROOT),Ue.LOG_NAMES.HDB),t={name:Ue.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0,script:Ue.LAUNCH_SERVICE_SCRIPTS.NODES_UPGRADE_4_0_0,exec_mode:"fork",env:{[Ue.PROCESS_NAME_ENV_PROP]:Ue.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0},merge_logs:!0,out_file:e,error_file:e,instances:1,cwd:kee,autorestart:!1};return wn.get(Ue.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(t.out_file=il,t.error_file=il),t}a(Yee,"generateClusteringUpgradeV4ServiceConfig");function Kee(){let e={[Ue.PROCESS_NAME_ENV_PROP]:Ue.PROCESS_DESCRIPTORS.RESTART_HDB};return Th.noBootFile()&&(e[Ue.CONFIG_PARAMS.ROOTPATH.toUpperCase()]=Th.getEnvCliRootPath()),{...{name:Ue.PROCESS_DESCRIPTORS.RESTART_HDB,exec_mode:"fork",env:e,instances:1,autorestart:!1,cwd:j0},script:Fee}}a(Kee,"generateRestart");function Wee(){return{apps:[X0()]}}a(Wee,"generateAllServiceConfigs");Z0.exports={generateAllServiceConfigs:Wee,generateMainServerConfig:X0,generateRestart:Kee,generateNatsHubServerConfig:qee,generateNatsLeafServerConfig:$ee,generateClusteringUpgradeV4ServiceConfig:Yee}});var Ex=I((Ege,_x)=>{"use strict";var Xe=H(),Qee=re(),Ci=OA(),Rh=or(),wi=Pt(),Ro=ex(),Ah=ie(),ya=X(),zee=Ri(),{startWorker:tx,onMessageFromWorkers:jee}=at(),Jee=Bc(),_ge=require("util"),Xee=require("child_process"),Zee=require("fs"),{execFile:ete}=Xee,$e;_x.exports={enterPM2Mode:tte,start:Ao,stop:NA,reload:nx,restart:sx,list:IA,describe:ox,connect:Di,kill:ote,startAllServices:ate,startService:wA,getUniqueServicesList:ax,restartAllServices:cte,isServiceRegistered:cx,reloadStopStart:lx,restartHdb:ix,deleteProcess:ste,startClusteringProcesses:dx,startClusteringThreads:fx,isHdbRestartRunning:ite,isClusteringRunning:ute,stopClustering:lte,reloadClustering:dte};var Cd=!1;jee(e=>{e.type==="restart"&&Ah.initSync(!0)});function tte(){Cd=!0}a(tte,"enterPM2Mode");function Di(){return $e||($e=require("pm2")),new Promise((e,t)=>{$e.connect((r,n)=>{r&&t(r),e(n)})})}a(Di,"connect");var tn,rte=10,rx;function Ao(e,t=!1){if(Cd)return nte(e);let r=ete(e.script,e.args.split(" "),e);r.name=e.name,r.on("exit",async i=>{let o=tn.indexOf(r);o>-1&&tn.splice(o,1),!rx&&i!==0&&(e.restarts=(e.restarts||0)+1,e.restarts<rte&&(Zee.existsSync(Ci.getHubConfigPath())?Ao(e):(await Ci.generateNatsConfig(!0),Ao(e),await new Promise(c=>setTimeout(c,3e3)),await Ci.removeNatsConfig(Xe.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await Ci.removeNatsConfig(Xe.PROCESS_DESCRIPTORS.CLUSTERING_LEAF))))});let n={serviceName:e.name.replace(/ /g,"-")};function s(i){let o=Ah.get(Xe.CONFIG_PARAMS.CLUSTERING_LOGLEVEL),c=/\[\d+][^\[]+\[(\w+)]/g,l,d=0,u;for(;l=c.exec(i);){if(l.index&&wi.LOG_LEVEL_HIERARCHY[o]>=wi.LOG_LEVEL_HIERARCHY[u||"info"]){let _=u===wi.LOG_LEVELS.ERR||u===wi.LOG_LEVELS.WRN?ya.OUTPUTS.STDERR:ya.OUTPUTS.STDOUT;ya.logCustomLevel(u||"info",_,n,i.slice(d,l.index).trim())}let[f,E]=l;d=l.index+f.length,u=wi.LOG_LEVELS[E]}if(wi.LOG_LEVEL_HIERARCHY[o]>=wi.LOG_LEVEL_HIERARCHY[u||"info"]){let f=u===wi.LOG_LEVELS.ERR||u===wi.LOG_LEVELS.WRN?ya.OUTPUTS.STDERR:ya.OUTPUTS.STDOUT;ya.logCustomLevel(u||"info",f,n,i.slice(d).trim())}}if(a(s,"extractMessages"),r.stdout.on("data",s),r.stderr.on("data",s),r.unref(),tn=[],!tn&&!t){let i=a(()=>{rx=!0,tn&&(tn.map(o=>o.kill()),process.exit(0))},"kill_children");process.on("exit",i),process.on("SIGINT",i),process.on("SIGQUIT",i),process.on("SIGTERM",i)}tn.push(r)}a(Ao,"start");function nte(e){return new Promise(async(t,r)=>{try{await Di()}catch(n){r(n)}$e.start(e,(n,s)=>{n&&($e.disconnect(),r(n)),$e.disconnect(),t(s)})})}a(nte,"startWithPM2");function NA(e){if(!Cd){for(let t of tn||[])t.name===e&&(tn.splice(tn.indexOf(t),1),t.kill());return}return new Promise(async(t,r)=>{try{await Di()}catch(n){r(n)}$e.stop(e,async(n,s)=>{n&&($e.disconnect(),r(n)),$e.delete(e,(i,o)=>{i&&($e.disconnect(),r(n)),$e.disconnect(),t(o)})})})}a(NA,"stop");function nx(e){return new Promise(async(t,r)=>{try{await Di()}catch(n){r(n)}$e.reload(e,(n,s)=>{n&&($e.disconnect(),r(n)),$e.disconnect(),t(s)})})}a(nx,"reload");function sx(e){if(!Cd)for(let t of tn||[])t.name===e&&t.kill();return new Promise(async(t,r)=>{try{await Di()}catch(n){r(n)}$e.restart(e,(n,s)=>{$e.disconnect(),t(s)})})}a(sx,"restart");function ste(e){return new Promise(async(t,r)=>{try{await Di()}catch(n){r(n)}$e.delete(e,(n,s)=>{n&&($e.disconnect(),r(n)),$e.disconnect(),t(s)})})}a(ste,"deleteProcess");async function ix(){await Ao(Ro.generateRestart())}a(ix,"restartHdb");async function ite(){let e=await IA();for(let t in e)if(e[t].name===Xe.PROCESS_DESCRIPTORS.RESTART_HDB)return!0;return!1}a(ite,"isHdbRestartRunning");function IA(){return new Promise(async(e,t)=>{try{await Di()}catch(r){t(r)}$e.list((r,n)=>{r&&($e.disconnect(),t(r)),$e.disconnect(),e(n)})})}a(IA,"list");function ox(e){return new Promise(async(t,r)=>{try{await Di()}catch(n){r(n)}$e.describe(e,(n,s)=>{n&&($e.disconnect(),r(n)),$e.disconnect(),t(s)})})}a(ox,"describe");function ote(){if(!Cd){for(let e of tn||[])e.kill();tn=[];return}return new Promise(async(e,t)=>{try{await Di()}catch(r){t(r)}$e.killDaemon((r,n)=>{r&&($e.disconnect(),t(r)),$e.disconnect(),e(n)})})}a(ote,"kill");async function ate(){try{await dx(),await fx(),await Ao(Ro.generateAllServiceConfigs())}catch(e){throw $e?.disconnect(),e}}a(ate,"startAllServices");async function wA(e,t=!1){try{let r;switch(e=e.toLowerCase(),e){case Xe.PROCESS_DESCRIPTORS.HDB.toLowerCase():r=Ro.generateMainServerConfig();break;case Xe.PROCESS_DESCRIPTORS.CLUSTERING_INGEST_SERVICE.toLowerCase():r=Ro.generateNatsIngestServiceConfig();break;case Xe.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE.toLowerCase():r=Ro.generateNatsReplyServiceConfig();break;case Xe.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase():r=Ro.generateNatsHubServerConfig(),await Ao(r,t),await Ci.removeNatsConfig(e);return;case Xe.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase():r=Ro.generateNatsLeafServerConfig(),await Ao(r,t),await Ci.removeNatsConfig(e);return;case Xe.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0.toLowerCase():r=Ro.generateClusteringUpgradeV4ServiceConfig();break;default:throw new Error(`Start service called with unknown service config: ${e}`)}await Ao(r)}catch(r){throw $e?.disconnect(),r}}a(wA,"startService");async function ax(){try{let e=await IA(),t={};for(let r=0,n=e.length;r<n;r++){let s=e[r];t[s.name]===void 0&&(t[s.name]={name:s.name,exec_mode:s.pm2_env.exec_mode})}return t}catch(e){throw $e?.disconnect(),e}}a(ax,"getUniqueServicesList");async function cte(e=[]){try{let t=!1,r=await ax();for(let n=0,s=Object.values(r).length;n<s;n++){let o=Object.values(r)[n].name;e.includes(o)||(o===Xe.PROCESS_DESCRIPTORS.HDB?t=!0:await sx(o))}t&&await lx(Xe.PROCESS_DESCRIPTORS.HDB)}catch(t){throw $e?.disconnect(),t}}a(cte,"restartAllServices");async function cx(e){if(tn?.find(r=>r.name===e))return!0;let t=await Jee.getHDBProcessInfo();return t.core.length&&t.core[0]?.parent==="PM2"}a(cx,"isServiceRegistered");async function lx(e){let t=Ah.get(Xe.CONFIG_PARAMS.THREADS_COUNT)??Ah.get(Xe.CONFIG_PARAMS.THREADS),r=await ox(e),n=Qee.isEmptyOrZeroLength(r)?0:r.length;t!==n?(await NA(e),await wA(e)):e===Xe.PROCESS_DESCRIPTORS.HDB?await ix():await nx(e)}a(lx,"reloadStopStart");var ux;async function dx(e=!1){for(let t in Xe.CLUSTERING_PROCESSES){let r=Xe.CLUSTERING_PROCESSES[t];await wA(r,e)}}a(dx,"startClusteringProcesses");async function fx(){ux=tx(Xe.LAUNCH_SERVICE_SCRIPTS.NATS_REPLY_SERVICE,{name:Xe.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE});try{await Rh.deleteLocalStream("__HARPERDB_WORK_QUEUE__")}catch{}await Rh.updateLocalStreams();let e=await zee.getAllNodeRecords();for(let t=0,r=e.length;t<r;t++)if(e[t].system_info?.hdb_version===Xe.PRE_4_0_0_VERSION){ya.info("Starting clustering upgrade 4.0.0 process"),tx(Xe.LAUNCH_SERVICE_SCRIPTS.NODES_UPGRADE_4_0_0,{name:"Upgrade-4-0-0"});break}}a(fx,"startClusteringThreads");async function lte(){for(let e in Xe.CLUSTERING_PROCESSES)if(e!==Xe.CLUSTERING_PROCESSES.CLUSTERING_INGEST_PROC_DESCRIPTOR)if(e===Xe.CLUSTERING_PROCESSES.CLUSTERING_REPLY_SERVICE_DESCRIPTOR)await ux.terminate();else{let t=Xe.CLUSTERING_PROCESSES[e];await NA(t)}}a(lte,"stopClustering");async function ute(){for(let e in Xe.CLUSTERING_PROCESSES){let t=Xe.CLUSTERING_PROCESSES[e];if(await cx(t)===!1)return!1}return!0}a(ute,"isClusteringRunning");async function dte(){await Ci.generateNatsConfig(!0),await Rh.reloadNATSHub(),await Rh.reloadNATSLeaf(),await Ci.removeNatsConfig(Xe.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase()),await Ci.removeNatsConfig(Xe.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())}a(dte,"reloadClustering")});var Rx={};Ze(Rx,{compactOnStart:()=>fte,copyDb:()=>gx});async function fte(){Ld.notify("Running compact on start"),console.log("Running compact on start");let e=(0,CA.get)(bo.CONFIG_PARAMS.ROOTPATH),t=new Map,r=ct();try{for(let n in r){if(n==="system")continue;let s;for(let l in r[n]){s=r[n][l].primaryStore.path;break}if(!s){console.log("Couldn't find any tables in database",n);continue}let i=(0,bh.join)(e,"backup",n+".mdb"),o=(0,bh.join)(e,bo.DATABASES_DIR_NAME,n+"-copy.mdb"),c=await hx(n);console.log("Database",n,"before compact has a total record count of",c),t.set(n,{db_path:s,copy_dest:o,backup_dest:i,record_count:c}),await gx(n,o),console.log("Backing up",n,"to",i),await(0,Oa.move)(s,i,{overwrite:!0})}Dd();for(let[n,{db_path:s,copy_dest:i}]of t)console.log("Moving copy compacted",n,"to",s),await(0,Oa.move)(i,s,{overwrite:!0}),await(0,Oa.remove)((0,bh.join)(e,bo.DATABASES_DIR_NAME,`${n}-copy.mdb-lock`));Dd()}catch(n){Ld.error("Error compacting database, rolling back operation",n),console.error("Error compacting database, rolling back operation",n),(0,DA.updateConfigValue)(bo.CONFIG_PARAMS.STORAGE_COMPACTONSTART,!1);for(let[s,{db_path:i,backup_dest:o}]of t){console.error("Moving backup database",o,"back to",i);try{await(0,Oa.move)(o,i,{overwrite:!0})}catch(c){console.error(c)}}throw Dd(),n}for(let[n,{backup_dest:s,record_count:i}]of t){let o=!0,c=await hx(n);if(console.log("Database",n,"after compact has a total record count of",c),i!==c){o=!1;let l=`There is a discrepancy between pre and post compact record count for database ${n}.
8
11
  Total record count before compaction: ${i}, total after: ${c}.
9
- Database backup has not been removed and can be found here: ${s}`;Dl.error(l),console.error(l)}(0,LT.get)(Ti.CONFIG_PARAMS.STORAGE_COMPACTONSTARTKEEPBACKUP)===!0||o===!1||(console.log("Removing backup",s),await(0,lo.remove)(s))}(0,MT.updateConfigValue)(Ti.CONFIG_PARAMS.STORAGE_COMPACTONSTART,!1)}async function oP(e){let t=await(0,uP.describeSchema)({database:e}),r=0;for(let n in t)r+=t[n].record_count;return r}async function _P(e,t){console.log("copyDb start");let r=mr()[e],n;for(let d in r){n=r[d].primaryStore.rootStore;break}let s=n.dbisDb,i=n.auditStore,o=(0,aP.open)(new cP.default(t)),c=o.openDB(jd.INTERNAL_DBIS_NAME),l,_=0,u=s.useReadTransaction();try{for(let{key:f,value:h}of s.getRange({transaction:u})){let p=h.is_hash_attribute||h.isPrimaryKey,S,T;if(p&&(S=h.compression,T=ef(),T?h.compression=T:delete h.compression,S?.dictionary?.toString()===T?.dictionary?.toString()&&(S=null,T=null)),c.put(f,h),!(p||h.indexed))continue;let R=new lP.default(!p,p);R.encoding="binary",R.compression=S;let b=n.openDB(f,R);b.decoder=null,R.compression=T;let C=o.openDB(f,R);C.encoder=null,console.log("copying",f,"from",e,"to",t),await E(b,C,p,u)}let d=n.openDB(jd.AUDIT_STORE_NAME,Zd);console.log("copying audit log"),E(i,d,!1,u);async function E(f,h,p,S){let T=0,R=0;for(let{key:b,value:C,version:H}of f.getRange({start:null,versions:p,transaction:S}))l=h.put(b,C,H),T++,S.openTimer&&(S.openTimer=0),R+=(b?.length||10)+C.length,_++>5e3&&(await l,console.log("copied",T,"entries",R,"bytes"),_=0);console.log("finish copying, copied",T,"entries",R,"bytes")}a(E,"copyDbi"),await l,console.log("copied database "+e+" to "+t)}finally{u.done(),o.close()}}var aP,Xd,lo,LT,cP,lP,jd,Ti,uP,MT,Dl,fP=Re(()=>{Ae();aP=require("lmdb"),Xd=require("path"),lo=require("fs-extra"),LT=B(te()),cP=B(Dc()),lP=B(Cc()),jd=B(dt()),Ti=B(U());Zs();uP=B(ri()),MT=B(Er()),Dl=B(K());a(l8,"compactOnStart");a(oP,"getTotalDBRecordCount");a(_P,"copyDb")});var Ul=g((Xfe,TP)=>{"use strict";var u8=require("minimist"),{isMainThread:vT,parentPort:PT,threadId:zfe}=require("worker_threads"),et=U(),{PROCESS_DESCRIPTORS_VALIDATE:Ll}=et,ss=K(),BT=z(),rf=IT(),tf=wt(),Jfe=ct(),mP=Er(),is=iP(),EP=Ea(),{compactOnStart:_8}=(fP(),ie(dP)),d8=bh(),{restartWorkers:nf,onMessageByType:f8}=it(),{handleHDBError:E8,hdb_errors:h8}=ne(),{HTTP_STATUS_CODES:m8}=h8,Pl=te();Pl.initSync();var Ml=`Restarting HarperDB. This may take up to ${et.RESTART_TIMEOUT_MS/1e3} seconds.`,p8="Restart is not available from the CLI when running in non-pm2 mode. Either call restart from the API or stop and start HarperDB.",hP="Clustering is not enabled so cannot be restarted",S8="Invalid service",ga,dn;TP.exports={restart:pP,restartService:HT};vT&&f8(et.ITC_EVENT_TYPES.RESTART,async(e,t)=>{e.workerType?await HT({service:e.workerType}):pP({operation:"restart"}),t.postMessage({type:"restart-complete"})});async function pP(e){dn=Object.keys(e).length===0,ga=await is.isServiceRegistered(et.HDB_PROC_DESCRIPTOR);let t=u8(process.argv);if(t.service){await HT(t);return}if(dn&&!ga){console.error(p8);return}if(dn&&console.log(Ml),ga){is.enterPM2Mode(),ss.notify(Ml);let r=d8(Object.keys(et.CONFIG_PARAM_MAP),!0);return BT.isEmptyOrZeroLength(Object.keys(r))||mP.updateConfigValue(void 0,void 0,r,!0,!0),T8(),Ml}return vT?(ss.notify(Ml),Pl.get(et.CONFIG_PARAMS.STORAGE_COMPACTONSTART)&&await _8(),setTimeout(()=>{nf()},50)):PT.postMessage({type:et.ITC_EVENT_TYPES.RESTART}),Ml}a(pP,"restart");async function HT(e){let{service:t}=e;if(et.PROCESS_DESCRIPTORS_VALIDATE[t]===void 0)throw E8(new Error,S8,m8.BAD_REQUEST,void 0,void 0,!0);if(ga=await is.isServiceRegistered(et.HDB_PROC_DESCRIPTOR),!vT)return PT.postMessage({type:et.ITC_EVENT_TYPES.RESTART,workerType:t}),new Promise(n=>{PT.on("message",s=>{s.type==="restart-complete"&&n()})});let r;switch(t){case Ll.clustering:if(!Pl.get(et.CONFIG_PARAMS.CLUSTERING_ENABLED)){r=hP;break}dn&&console.log("Restarting clustering"),ss.notify("Restarting clustering"),await SP();break;case Ll.clustering_config:case Ll["clustering config"]:if(!Pl.get(et.CONFIG_PARAMS.CLUSTERING_ENABLED)){r=hP;break}dn&&console.log("Restarting clustering_config"),ss.notify("Restarting clustering_config"),await is.reloadClustering();break;case"custom_functions":case"custom functions":case Ll.harperdb:case Ll.http_workers:if(dn&&!ga){r=`Restart ${t} is not available from the CLI when running in non-pm2 mode. Either call restart ${t} from the API or stop and start HarperDB.`;break}dn&&console.log("Restarting http_workers"),ss.notify("Restarting http_workers"),dn?await is.restart(et.HDB_PROC_DESCRIPTOR):await nf("http");break;default:r=`Unrecognized service: ${t}`;break}return r?(ss.error(r),dn&&console.error(r),r):(t==="custom_functions"&&(t="Custom Functions"),`Restarting ${t}`)}a(HT,"restartService");async function T8(){await SP(),await is.restart(et.HDB_PROC_DESCRIPTOR),await BT.async_set_timeout(2e3),Pl.get(et.CONFIG_PARAMS.CLUSTERING_ENABLED)&&await UT(),dn&&(await tf.closeConnection(),process.exit(0))}a(T8,"restartPM2Mode");async function SP(){if(!mP.getConfigFromFile(et.CONFIG_PARAMS.CLUSTERING_ENABLED))return;if((await EP.getHDBProcessInfo()).clustering.length===0)ss.trace("Clustering not running, restart will start clustering services"),await rf.generateNatsConfig(!0),await is.startClusteringProcesses(),await is.startClusteringThreads(),await UT(),dn&&await tf.closeConnection();else{await rf.generateNatsConfig(!0),ga?(ss.trace("Restart clustering restarting PM2 managed Hub and Leaf servers"),await is.restart(et.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await is.restart(et.PROCESS_DESCRIPTORS.CLUSTERING_LEAF)):(await EP.getHDBProcessInfo()).clustering.forEach(s=>{ss.trace("Restart clustering killing process pid",s.pid),process.kill(s.pid)}),await BT.async_set_timeout(3e3),await UT(),await tf.updateLocalStreams(),dn&&await tf.closeConnection(),ss.trace("Restart clustering restarting ingest and reply service threads");let t=nf(et.LAUNCH_SERVICE_SCRIPTS.NATS_INGEST_SERVICE),r=nf(et.LAUNCH_SERVICE_SCRIPTS.NATS_REPLY_SERVICE);await t,await r}}a(SP,"restartClustering");async function UT(){await rf.removeNatsConfig(et.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await rf.removeNatsConfig(et.PROCESS_DESCRIPTORS.CLUSTERING_LEAF)}a(UT,"removeNatsConfig")});var DP=g((eEe,CP)=>{"use strict";var Zfe=require("lodash"),yr=U(),{handleHDBError:gP,hdb_errors:g8}=ne(),{HDB_ERROR_MSGS:R8,HTTP_STATUS_CODES:A8}=g8,xT=K();CP.exports={getRolePermissions:b8};var uo=Object.create(null),O8=a(e=>({key:e,perms:{}}),"perms_template_obj"),bP=a((e=!1)=>({describe:e,tables:{}}),"schema_perms_template"),yP=a((e=!1,t=!1,r=!1,n=!1)=>({[yr.PERMS_CRUD_ENUM.READ]:e,[yr.PERMS_CRUD_ENUM.INSERT]:t,[yr.PERMS_CRUD_ENUM.UPDATE]:r,[yr.PERMS_CRUD_ENUM.DELETE]:n}),"permissions_template"),GT=a((e=!1,t=!1,r=!1,n=!1,s=!1)=>({attribute_permissions:[],describe:e,...yP(t,r,n,s)}),"table_perms_template"),RP=a((e,t=yP())=>({attribute_name:e,describe:wP(t),[vl]:t[vl],[FT]:t[FT],[qT]:t[qT]}),"attr_perms_template"),AP=a((e,t=!1)=>({attribute_name:e,describe:t,[vl]:t}),"timestamp_attr_perms_template"),{READ:vl,INSERT:FT,UPDATE:qT}=yr.PERMS_CRUD_ENUM,NP=Object.values(yr.PERMS_CRUD_ENUM),IP=[vl,FT,qT];function b8(e){let t;try{if(e.permission.super_user||e.permission.cluster_user)return e.permission;let r=Object.assign({},global.hdb_schema);delete r[yr.SYSTEM_SCHEMA_NAME],t=e.role;let n=JSON.stringify([e.__updatedtime__,r]);if(uo[t]&&uo[t].key===n)return uo[t].perms;let s=y8(e,r);return uo[t]?uo[t].key=n:uo[t]=O8(n),uo[t].perms=s,s}catch(r){if(!e[yr.TIME_STAMP_NAMES_ENUM.UPDATED_TIME]||e[yr.TIME_STAMP_NAMES_ENUM.UPDATED_TIME]<yr.PERMS_UPDATE_RELEASE_TIMESTAMP){let n=`Role permissions for role '${t}' must be updated to align with new structure from the 2.2.0 release.`;throw xT.error(n),xT.debug(r),gP(new Error,R8.OUTDATED_PERMS_TRANSLATION_ERROR,A8.BAD_REQUEST)}else{let n=`There was an error while translating role permissions for role: ${t}.
10
- ${r.stack}`;throw xT.error(n),gP(new Error)}}}a(b8,"getRolePermissions");function y8(e,t){let r=Object.create(null);r.super_user=!1;let n=e.permission;r[yr.SYSTEM_SCHEMA_NAME]=n[yr.SYSTEM_SCHEMA_NAME],r.structure_user=n.structure_user;let s=Array.isArray(e.permission.structure_user)||e.permission.structure_user===!0?e.permission.structure_user:[];return Object.keys(t).forEach(i=>{if(s===!0||s.indexOf(i)>-1){r[i]=N8(t[i]);return}r[i]=bP(),n[i]?(n[i].describe&&(r[i].describe=!0),Object.keys(t[i]).forEach(o=>{if(n[i].tables[o]){let c=n[i].tables[o],l=t[i][o],_=I8(c,l);r[i].describe||NP.forEach(u=>{_[u]&&(r[i].describe=!0)}),r[i].tables[o]=_}else r[i].tables[o]=GT()})):Object.keys(t[i]).forEach(o=>{r[i].tables[o]=GT()})}),r}a(y8,"translateRolePermissions");function N8(e){let t=bP(!0);return Object.keys(e).forEach(r=>{t.tables[r]=GT(!0,!0,!0,!0,!0)}),t}a(N8,"createStructureUserPermissions");function I8(e,t){let{attribute_permissions:r}=e;if(r.length>0){let s=Object.assign({},e);s.attribute_permissions=[];let i=r.reduce((_,u)=>{let{attribute_name:d}=u,E=u;return yr.TIME_STAMP_NAMES.includes(d)&&(E=AP(d,u[vl])),_[d]=E,_},{}),o=t.primaryKey||t.hash_attribute,c=!!i[o],l=RP(o);return t.attributes.forEach(({attribute:_})=>{if(i[_]){let u=i[_];u.describe=wP(u),s.attribute_permissions.push(u),c||w8(u,l)}else if(_!==o){let u;yr.TIME_STAMP_NAMES.includes(_)?u=AP(_):u=RP(_),s.attribute_permissions.push(u)}}),c||s.attribute_permissions.push(l),s.describe=OP(s),s}else return e.describe=OP(e),e}a(I8,"getTableAttrPerms");function OP(e){return NP.filter(t=>e[t]).length>0}a(OP,"getSchemaTableDescribePerm");function wP(e){return IP.filter(t=>e[t]).length>0}a(wP,"getAttributeDescribePerm");function w8(e,t){IP.forEach(r=>{e[r]&&!t[r]&&(t[r]=!0,t.describe=!0)})}a(w8,"checkForHashPerms")});var LP={};qe(LP,{Resources:()=>sf,keyArrayToString:()=>Ra,resetResources:()=>C8,resources:()=>gi});function C8(){return gi=new sf}function Ra(e){return Array.isArray(e)?e[e.length-1]===null?e.slice(0,-1).join("/")+"/":e.join("/"):e}var sf,gi,Bl=Re(()=>{to();sf=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,type:n,hasSubPaths:!1,relativeURL:""},o=super.get(t);if(o&&(o.Resource.databaseName!==r.databaseName||o.Resource.tableName!==r.tableName)&&!s)throw new Error(`Conflicting paths for ${t}`);super.set(t,i);for(let[c,l]of this){let _=2;for(;(_=c.indexOf("/",_))>-1;){let u=this.get(c.slice(0,_));u&&(u.hasSubPaths=!0),_+=2}}}getMatch(t,r){let n=2,s;for(;(n=t.indexOf("/",n))>-1;){let c=t.slice(0,n),l=this.get(c);if(l){if(l.relativeURL=t.slice(n),!l.hasSubPaths)return l;s=l}n+=2}if(s)return s;let i=t.indexOf("?"),o=i>-1?t.slice(0,i):t;return s=this.get(o),s?s.relativeURL=i>-1?t.slice(i):"":s||(s=this.get(""),s&&(t[0]!=="/"&&(t="/"+t),s.relativeURL=t)),s}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 Je(r,async()=>{let s=this.getMatch(t);if(s)return t=s.relativeURL,n(s.Resource,s.path,t)})}setRepresentation(t,r,n){}};a(C8,"resetResources");a(Ra,"keyArrayToString")});var MP={};qe(MP,{Headers:()=>Ri,appendHeader:()=>kT});function kT(e,t,r,n){if(e.append)e.append(t,r,n);else if(e.set){let s=e.get(t);if(s)if(n)r=(typeof s=="string"?s:s.join(", "))+", "+r;else if(typeof s=="string")r=[s,r];else{s.push(r);return}return e.set(t,r)}else e[t]=(e[t]?e[t]+", ":"")+r}var Ri,Hl=Re(()=>{Ri=class extends Map{static{a(this,"Headers")}set(t,r){return typeof t!="string"&&(t=""+t),typeof r!="string"&&(r=""+r),super.set(t.toLowerCase(),[t,r])}get(t){return typeof t!="string"&&(t=""+t),super.get(t.toLowerCase())?.[1]}has(t){return typeof t!="string"&&(t=""+t),super.has(t.toLowerCase())}setIfNone(t,r){typeof t!="string"&&(t=""+t),typeof r!="string"&&(r=""+r);let n=t.toLowerCase();if(!super.has(n))return super.set(n,[t,r])}append(t,r,n){typeof t!="string"&&(t=""+t),typeof r!="string"&&(r=""+r);let s=t.toLowerCase(),i=super.get(s);if(i){let o=i[1];if(n)r=(typeof o=="string"?o:o.join(", "))+", "+r;else if(typeof o=="string")r=[o,r];else{o.push(r);return}}return super.set(s,[t,r])}[Symbol.iterator](){return super.values()[Symbol.iterator]()}};a(kT,"appendHeader")});var xl={};qe(xl,{authentication:()=>FP,bypassAuth:()=>B8,login:()=>x8,logout:()=>G8,start:()=>H8});function B8(){GP=!0}async function FP(e,t){let r=e.headers.asObject,n=r.authorization,s=r.cookie,i=r.origin,o=[];try{if(i){let f=e.isOperationsServer?P8?M8:[]:L8?D8:[];if(f.includes(i)||f.includes("*")){if(e.method==="OPTIONS"){let h=new Ri([["Access-Control-Allow-Methods","POST, GET, PUT, DELETE, PATCH, OPTIONS"],["Access-Control-Allow-Headers","Accept, Content-Type, Authorization"],["Access-Control-Allow-Origin",i]]);return of&&h.set("Access-Control-Allow-Credentials","true"),{status:200,headers:h}}o.push("Access-Control-Allow-Origin",i),of&&o.push("Access-Control-Allow-Credentials","true")}}let l,_;if(of){i||(i=r.host);let f=(i?i.replace(/^https?:\/\//,"").replace(/\W/,"_")+"-":"")+"hdb-session=",h=s?.split(/;\s+/)||[];for(let p of h)if(p.startsWith(f)){let S=p.indexOf(";");l=p.slice(f.length,S===-1?p.length:S),_=await UP.get(l);break}e.session=_||(_={})}let u=a((f,h,p)=>{let S=new Aa.AuthAuditLog(f,h,Ht.AUTH_AUDIT_TYPES.AUTHENTICATION,r["x-forwarded-for"]??e.ip,e.method,e.pathname);S.auth_strategy=p,l&&(S.session_id=l),r.referer&&(S.referer=r.referer),r.origin&&(S.origin=r.origin),h===Ht.AUTH_AUDIT_STATUS.SUCCESS?PP.notify(S):PP.error(S)},"authAuditLog");if(e.mtlsConfig&&e.authorized){let f=e.mtlsConfig.user;f!==null?((f===void 0||f==="Common Name"||f==="CN")&&(f=e.peerCertificate.subject.CN),e.user=await st.getUser(f,null,null),u(f,Ht.AUTH_AUDIT_STATUS.SUCCESS,"mTLS")):(0,Aa.debug)("HTTPS/WSS mTLS authorized connection (mTLS did not authorize a user)","from",e.ip)}let d;if(!e.user)if(n){if(d=_o.get(n),!d){let f=n.indexOf(" "),h=n.slice(0,f),p=n.slice(f+1),S,T;try{switch(h){case"Basic":let R=atob(p),b=R.indexOf(":");S=R.slice(0,b),T=R.slice(b+1),d=S||T?await st.getUser(S,T,e):null;break;case"Bearer":try{d=await(0,af.validateOperationToken)(p)}catch(C){if(C.message==="invalid token")try{return await(0,af.validateRefreshToken)(p),c({status:-1})}catch{throw C}}break}}catch(R){return v8&&(_o.get(p)||(_o.set(p,p),u(S,Ht.AUTH_AUDIT_STATUS.FAILURE,h))),c({status:401,body:fo({error:R.message},e)})}_o.set(n,d),U8&&u(d.username,Ht.AUTH_AUDIT_STATUS.SUCCESS,h)}e.user=d}else _?.user?e.user=await st.getUser(_.user,null,e):(GP&&(e.ip?.includes("127.0.0.1")||e.ip=="::1")||e?._nodeRequest?.socket?.server?._pipeName&&e.ip===void 0)&&(e.user=await(0,BP.getSuperUser)());of&&(e.session.update=function(f){if(!l){l=(0,HP.v4)();let p=`${(i?i.replace(/^https?:\/\//,"").replace(/\W/,"_")+"-":"")+"hdb-session="}${l}; Path=/; Expires=Tue, 01 Oct 8307 19:33:20 GMT; HttpOnly${e.protocol==="https"?"; SameSite=None; Secure":""}`;o?o.push("Set-Cookie",p):E?.headers?.set&&E.headers.set("Set-Cookie",p)}return e.protocol==="https"&&(o?(i&&o.push("Access-Control-Expose-Headers","X-Hdb-Session"),o.push("X-Hdb-Session","Secure")):E?.headers?.set&&(i&&E.headers.set("Access-Control-Expose-Headers","X-Hdb-Session"),E.headers.set("X-Hdb-Session","Secure"))),f.id=l,UP.put(f)},e.login=async function(f,h){e.user=await st.getUser(f,h,e),e.session.update({user:e.user.username})},(d&&!_||_?.user?.username!==d?.username)&&r["user-agent"]?.startsWith("Mozilla")&&e.session.update({user:e.user.username}));let E=await t(e);return E&&(E.status===401&&(r["user-agent"]?.startsWith("Mozilla")&&r.accept?.startsWith("text/html")&&gi.loginPath?(E.status=302,E.headers.set("Location",gi.loginPath(e))):E.headers.set("WWW-Authenticate","Basic")),c(E))}catch(l){throw c(l)}function c(l){let _=o.length;if(_>0){let u=l.headers;u||(l.headers=u=new Ri);for(let d=0;d<_;){let E=o[d++];u.set(E,o[d++])}}return o=null,l}a(c,"applyResponseHeaders")}function H8({server:e,port:t}){e.http(FP,{port:t||"all"}),vP||(vP=!0,setInterval(()=>{_o=new Map},fn.get(Ht.CONFIG_PARAMS.AUTHENTICATION_CACHETTL)).unref(),xP.user.addListener(()=>{_o=new Map}))}async function x8(e){if(!e.baseRequest?.login)throw new Error("No session for login");return e.baseResponse.headers.set=(t,r)=>{e.fastifyResponse.header(t,r)},await e.baseRequest.login(e.username,e.password),"Login successful"}async function G8(e){if(!e.baseRequest.session)throw new Error("No session for logout");return await e.baseRequest.session.update({user:null}),"Logout successful"}var BP,af,HP,fn,Ht,Aa,xP,PP,D8,L8,M8,P8,UP,of,GP,U8,v8,_o,vP,cf=Re(()=>{BP=B(un());ur();Bl();af=B(dl());Ae();HP=require("uuid"),fn=B(te()),Ht=B(U()),Aa=B(K()),xP=B($c());Hl();Oa();PP=(0,Aa.loggerWithTag)("auth-event");fn.initSync();D8=fn.get(Ht.CONFIG_PARAMS.HTTP_CORSACCESSLIST),L8=fn.get(Ht.CONFIG_PARAMS.HTTP_CORS),M8=fn.get(Ht.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_CORSACCESSLIST),P8=fn.get(Ht.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_CORS),UP=ft({table:"hdb_session",database:"system",attributes:[{name:"id",isPrimaryKey:!0},{name:"user"}]}),of=fn.get(Ht.CONFIG_PARAMS.AUTHENTICATION_ENABLESESSIONS)??!0,GP=fn.get(Ht.CONFIG_PARAMS.AUTHENTICATION_AUTHORIZELOCAL)??process.env.DEV_MODE,U8=fn.get(Ht.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)??!1,v8=fn.get(Ht.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGFAILED)??!1,_o=new Map;st.onInvalidatedUser(()=>{_o=new Map});a(B8,"bypassAuth");a(FP,"authentication");a(H8,"start");a(x8,"login");a(G8,"logout")});var WP=g((_Ee,KP)=>{"use strict";var we=require("joi"),qP=require("fs-extra"),kP=require("path"),Ms=at(),VP=te(),$P=U(),YP=K(),{hdb_errors:F8}=ne(),{HDB_ERROR_MSGS:sr}=F8,Ls=/^[a-zA-Z0-9-_]+$/;KP.exports={getDropCustomFunctionValidator:k8,setCustomFunctionValidator:V8,addComponentValidator:W8,dropCustomFunctionProjectValidator:Q8,packageComponentValidator:z8,deployComponentValidator:J8,setComponentFileValidator:$8,getComponentFileValidator:K8,dropComponentFileValidator:Y8};function lf(e,t,r){try{let n=VP.get($P.CONFIG_PARAMS.COMPONENTSROOT),s=kP.join(n,t);return qP.existsSync(s)?e?t:r.message(sr.PROJECT_EXISTS):e?r.message(sr.NO_PROJECT):t}catch(n){return YP.error(n),r.message(sr.VALIDATION_ERR)}}a(lf,"checkProjectExists");function Gl(e,t){return e.includes("..")?t.message("Invalid file path"):e}a(Gl,"checkFilePath");function q8(e,t,r,n){try{let s=VP.get($P.CONFIG_PARAMS.COMPONENTSROOT),i=kP.join(s,e,t,r+".js");return qP.existsSync(i)?r:n.message(sr.NO_FILE)}catch(s){return YP.error(s),n.message(sr.VALIDATION_ERR)}}a(q8,"checkFileExists");function k8(e){let t=we.object({project:we.string().pattern(Ls).custom(lf.bind(null,!0)).required().messages({"string.pattern.base":sr.BAD_PROJECT_NAME}),type:we.string().valid("helpers","routes").required(),file:we.string().pattern(Ls).custom(q8.bind(null,e.project,e.type)).custom(Gl).required().messages({"string.pattern.base":sr.BAD_FILE_NAME})});return Ms.validateBySchema(e,t)}a(k8,"getDropCustomFunctionValidator");function V8(e){let t=we.object({project:we.string().pattern(Ls).custom(lf.bind(null,!0)).required().messages({"string.pattern.base":sr.BAD_PROJECT_NAME}),type:we.string().valid("helpers","routes").required(),file:we.string().custom(Gl).required(),function_content:we.string().required()});return Ms.validateBySchema(e,t)}a(V8,"setCustomFunctionValidator");function $8(e){let t=we.object({project:we.string().pattern(Ls).required().messages({"string.pattern.base":sr.BAD_PROJECT_NAME}),file:we.string().custom(Gl).required(),payload:we.string().allow("").optional(),encoding:we.string().valid("utf8","ASCII","binary","hex","base64","utf16le","latin1","ucs2").optional()});return Ms.validateBySchema(e,t)}a($8,"setComponentFileValidator");function Y8(e){let t=we.object({project:we.string().pattern(Ls).required().messages({"string.pattern.base":sr.BAD_PROJECT_NAME}),file:we.string().custom(Gl).optional()});return Ms.validateBySchema(e,t)}a(Y8,"dropComponentFileValidator");function K8(e){let t=we.object({project:we.string().required(),file:we.string().custom(Gl).required(),encoding:we.string().valid("utf8","ASCII","binary","hex","base64","utf16le","latin1","ucs2").optional()});return Ms.validateBySchema(e,t)}a(K8,"getComponentFileValidator");function W8(e){let t=we.object({project:we.string().pattern(Ls).custom(lf.bind(null,!1)).required().messages({"string.pattern.base":sr.BAD_PROJECT_NAME})});return Ms.validateBySchema(e,t)}a(W8,"addComponentValidator");function Q8(e){let t=we.object({project:we.string().pattern(Ls).custom(lf.bind(null,!0)).required().messages({"string.pattern.base":sr.BAD_PROJECT_NAME})});return Ms.validateBySchema(e,t)}a(Q8,"dropCustomFunctionProjectValidator");function z8(e){let t=we.object({project:we.string().pattern(Ls).required().messages({"string.pattern.base":sr.BAD_PROJECT_NAME}),skip_node_modules:we.boolean()});return Ms.validateBySchema(e,t)}a(z8,"packageComponentValidator");function J8(e){let t=we.object({project:we.string().pattern(Ls).required().messages({"string.pattern.base":sr.BAD_PROJECT_NAME}),payload:we.string().optional().messages({"string.pattern.base":sr.BAD_PACKAGE}),package:we.string().optional()});return Ms.validateBySchema(e,t)}a(J8,"deployComponentValidator")});var ff=g((fEe,eU)=>{"use strict";var uf=require("joi"),_f=require("path"),QP=require("fs-extra"),{exec:X8}=require("child_process"),j8=require("util"),zP=j8.promisify(X8),Fl=U(),{handleHDBError:ba,hdb_errors:Z8}=ne(),{HTTP_STATUS_CODES:ya}=Z8,ql=te(),e6=at(),Na=K();ql.initSync();var VT=ql.get(Fl.CONFIG_PARAMS.COMPONENTSROOT),JP="npm install --omit=dev --json",t6=`${JP} --dry-run`;eU.exports={installModules:i6,auditModules:o6,installAllRootModules:r6,uninstallRootModule:n6,linkHarperdb:s6};async function r6(e=!1){await df(),await kl(e?"npm install --ignore-scripts":"npm install",ql.get(Fl.CONFIG_PARAMS.ROOTPATH))}a(r6,"installAllRootModules");async function n6(e){await kl(`npm uninstall ${e}`,ql.get(Fl.CONFIG_PARAMS.ROOTPATH))}a(n6,"uninstallRootModule");async function s6(){await df(),await kl(`npm link ${Fl.PACKAGE_ROOT}`,ql.get(Fl.CONFIG_PARAMS.ROOTPATH))}a(s6,"linkHarperdb");async function kl(e,t=void 0){let r,n;try{({stdout:r,stderr:n}=await zP(e,{cwd:t}))}catch(s){throw new Error(s.stderr.replace(`
11
- `,""))}return n&&!n.includes("Debugger listening")&&Na.error("Error running NPM command:",e,n),Na.trace(r,n),r?.replace(`
12
- `,"")}a(kl,"runCommand");async function i6(e){Na.info(`starting installModules for request: ${e}`);let t=ZP(e);if(t)throw ba(t,t.message,ya.BAD_REQUEST);let{projects:r,dry_run:n}=e,s=n===!0?t6:JP;await df(),await jP(r);let i={};for(let o=0,c=r.length;o<c;o++){let l=r[o];i[l]={npm_output:null,npm_error:null};let _=_f.join(VT,l),u,d=null;try{let{stdout:E,stderr:f}=await zP(s,{cwd:_});u=E?E.replace(`
13
- `,""):null,d=f?f.replace(`
14
- `,""):null}catch(E){E.stderr?i[l].npm_error=XP(E.stderr):i[l].npm_error=E.message;continue}try{i[l].npm_output=JSON.parse(u)}catch{i[l].npm_output=u}try{i[l].npm_error=JSON.parse(d)}catch{i[l].npm_error=d}}return Na.info(`finished installModules with response ${i}`),i}a(i6,"installModules");function XP(e){let t='"error": {',r=e.indexOf('"error": {'),n=e.indexOf(`}
15
- `);return r>-1&&n>-1?JSON.parse(e.substring(r+t.length-1,n+1)):e}a(XP,"parseNPMStdErr");async function o6(e){Na.info(`starting auditModules for request: ${e}`);let t=ZP(e);if(t)throw ba(t,t.message,ya.BAD_REQUEST);let{projects:r}=e;await df(),await jP(r);let n={};for(let s=0,i=r.length;s<i;s++){let o=r[s],c=_f.join(VT,o);n[o]={npm_output:null,npm_error:null};try{let l=await kl("npm audit --json",c);n[o].npm_output=JSON.parse(l)}catch(l){n[o].npm_error=XP(l.stderr)}}return Na.info(`finished auditModules with response ${n}`),n}a(o6,"auditModules");async function df(){try{return await kl("npm -v"),!0}catch{throw ba(new Error,"Unable to install project dependencies: npm is not installed on this instance of HarperDB.",ya.BAD_REQUEST,void 0,void 0,!0)}}a(df,"checkNPMInstalled");async function jP(e){if(!Array.isArray(e)||e.length===0)throw ba(new Error,"projects argument must be an array with at least 1 element",ya.BAD_REQUEST,void 0,void 0,!0);let t=[],r=[];for(let n=0,s=e.length;n<s;n++){let i=e[n],o=_f.join(VT,i.toString());if(!await QP.pathExists(o)){t.push(i);continue}let l=_f.join(o,"package.json");await QP.pathExists(l)||r.push(i)}if(t.length>0)throw ba(new Error,`Unable to install project dependencies: custom function projects '${t.join(",")}' does not exist.`,ya.BAD_REQUEST,void 0,void 0,!0);if(r.length>0)throw ba(new Error,`Unable to install project dependencies: custom function projects '${r.join(",")}' do not have a package.json file.`,ya.BAD_REQUEST,void 0,void 0,!0)}a(jP,"checkProjectPaths");function ZP(e){let t=uf.object({projects:uf.array().min(1).items(uf.string()).required(),dry_run:uf.boolean().default(!1)});return e6.validateBySchema(e,t)}a(ZP,"modulesValidator")});var YT=g((hEe,iU)=>{"use strict";var Ia=require("fs-extra"),$T=require("path"),Ef=K(),tU=z(),hf=U(),sU=te(),a6=Er();iU.exports=c6;async function c6(){let e=l6(),t=sU.get(hf.CONFIG_PARAMS.ROOTPATH),r=$T.join(t,"package.json"),n={dependencies:{harperdb:"file:"+hf.PACKAGE_ROOT}},s=$T.join(t,"node_modules");await Ia.ensureDir(s);let i,o=!0,c=!1;try{i=await Ia.readJson(r)}catch(l){if(tU.isEmptyOrZeroLength(e))return;if(l.code!==hf.NODE_ERROR_CODES.ENOENT)throw l;o=!1}if(!tU.isEmptyOrZeroLength(e)){for(let{name:l,package:_}of e){let u=await rU(_);n.dependencies[l]=u+_}if(!o){Ef.notify("Installing components"),await nU(r,n,null);return}for(let{name:l,package:_}of e){let u=i.dependencies[l],d=await rU(_);if(u===void 0||u!==d+_){c=!0;break}}}for(let l in i.dependencies)n.dependencies[l]===void 0&&(Ef.notify("Removing component",l),c=!0);c&&(Ef.notify("Updating components."),await nU(r,n,i))}a(c6,"installComponents");function l6(){let e=a6.getConfiguration(),t=[];for(let r in e)e[r]?.package&&t.push(Object.assign(e[r],{name:r}));return t}a(l6,"getComponentsConfig");async function rU(e){return e.includes(":")?"":e.startsWith("@")||!e.startsWith("@")&&!e.includes("/")?"npm:":$T.extname(e)||await Ia.pathExists(e)?"file:":"github:"}a(rU,"getPkgPrefix");async function nU(e,t,r){Ef.trace("npm installing components package.json",t),await Ia.writeFile(e,JSON.stringify(t,null," "));try{await ff().installAllRootModules(sU.get(hf.CONFIG_PARAMS.IGNORE_SCRIPTS)===!0)}catch(n){throw r?await Ia.writeFile(e,JSON.stringify(r,null," ")):await Ia.unlink(e),n}}a(nU,"installPackages")});var QT=g((SEe,lU)=>{"use strict";var Ve=require("fs-extra"),KT=require("fast-glob"),Te=require("path"),aU=require("tar-fs"),pEe=require("uuid").v4,WT=require("normalize-path"),os=WP(),Ct=K(),We=U(),At=te(),Vl=Er(),u6=z(),{PACKAGE_ROOT:_6}=U(),{handleHDBError:xt,hdb_errors:d6}=ne(),{basename:f6}=require("path"),E6=YT(),cU=te(),h6=U(),{Readable:m6}=require("stream"),{isMainThread:p6}=require("worker_threads"),{HDB_ERROR_MSGS:Eo,HTTP_STATUS_CODES:Gt}=d6,S6=Te.join(_6,"application-template"),oU=Te.join(At.get(We.HDB_SETTINGS_NAMES.HDB_ROOT_KEY),"tmp");function T6(){Ct.trace("getting custom api status");let e={};try{e={port:At.get(We.CONFIG_PARAMS.HTTP_PORT),directory:At.get(We.CONFIG_PARAMS.COMPONENTSROOT),is_enabled:!0}}catch(t){throw xt(new Error,Eo.FUNCTION_STATUS,Gt.INTERNAL_SERVER_ERROR,Ct.ERR,t)}return e}a(T6,"customFunctionsStatus");function g6(){Ct.trace("getting custom api endpoints");let e={},t=At.get(We.CONFIG_PARAMS.COMPONENTSROOT);try{KT.sync(WT(`${t}/*`),{onlyDirectories:!0}).forEach(n=>{let s=n.split("/").pop();e[s]={routes:KT.sync(WT(`${n}/routes/*.js`)).map(i=>i.split("/").pop().split(".js")[0]),helpers:KT.sync(WT(`${n}/helpers/*.js`)).map(i=>i.split("/").pop().split(".js")[0])}})}catch(r){throw xt(new Error,Eo.GET_FUNCTIONS,Gt.INTERNAL_SERVER_ERROR,Ct.ERR,r)}return e}a(g6,"getCustomFunctions");function R6(e){e.project&&(e.project=Te.parse(e.project).name),e.file&&(e.file=Te.parse(e.file).name);let t=os.getDropCustomFunctionValidator(e);if(t)throw xt(t,t.message,Gt.BAD_REQUEST);Ct.trace("getting custom api endpoint file content");let r=At.get(We.CONFIG_PARAMS.COMPONENTSROOT),{project:n,type:s,file:i}=e,o=Te.join(r,n,s,i+".js");try{return Ve.readFileSync(o,{encoding:"utf8"})}catch(c){throw xt(new Error,Eo.GET_FUNCTION,Gt.INTERNAL_SERVER_ERROR,Ct.ERR,c)}}a(R6,"getCustomFunction");function A6(e){e.project&&(e.project=Te.parse(e.project).name),e.file&&(e.file=Te.parse(e.file).name);let t=os.setCustomFunctionValidator(e);if(t)throw xt(t,t.message,Gt.BAD_REQUEST);Ct.trace("setting custom function file content");let r=At.get(We.CONFIG_PARAMS.COMPONENTSROOT),{project:n,type:s,file:i,function_content:o}=e;try{return Ve.outputFileSync(Te.join(r,n,s,i+".js"),o),`Successfully updated custom function: ${i}.js`}catch(c){throw xt(new Error,Eo.SET_FUNCTION,Gt.INTERNAL_SERVER_ERROR,Ct.ERR,c)}}a(A6,"setCustomFunction");function O6(e){e.project&&(e.project=Te.parse(e.project).name),e.file&&(e.file=Te.parse(e.file).name);let t=os.getDropCustomFunctionValidator(e);if(t)throw xt(t,t.message,Gt.BAD_REQUEST);Ct.trace("dropping custom function file");let r=At.get(We.CONFIG_PARAMS.COMPONENTSROOT),{project:n,type:s,file:i}=e;try{return Ve.unlinkSync(Te.join(r,n,s,i+".js")),`Successfully deleted custom function: ${i}.js`}catch(o){throw xt(new Error,Eo.DROP_FUNCTION,Gt.INTERNAL_SERVER_ERROR,Ct.ERR,o)}}a(O6,"dropCustomFunction");function b6(e){e.project&&(e.project=Te.parse(e.project).name);let t=os.addComponentValidator(e);if(t)throw xt(t,t.message,Gt.BAD_REQUEST);Ct.trace("adding component");let r=At.get(We.CONFIG_PARAMS.COMPONENTSROOT),{project:n}=e;try{let s=Te.join(r,n);return Ve.mkdirSync(s,{recursive:!0}),Ve.copySync(S6,s),`Successfully added project: ${n}`}catch(s){throw xt(new Error,Eo.ADD_FUNCTION,Gt.INTERNAL_SERVER_ERROR,Ct.ERR,s)}}a(b6,"addComponent");function y6(e){e.project&&(e.project=Te.parse(e.project).name);let t=os.dropCustomFunctionProjectValidator(e);if(t)throw xt(t,t.message,Gt.BAD_REQUEST);Ct.trace("dropping custom function project");let r=At.get(We.CONFIG_PARAMS.COMPONENTSROOT),{project:n}=e,s=At.get(We.CONFIG_PARAMS.APPS);if(!u6.isEmptyOrZeroLength(s)){let i=!1;for(let[o,c]of s.entries())if(c.name===n){s.splice(o,1),i=!0;break}if(i)return Vl.updateConfigValue(We.CONFIG_PARAMS.APPS,s),`Successfully deleted project: ${n}`}try{let i=Te.join(r,n);return Ve.rmSync(i,{recursive:!0}),`Successfully deleted project: ${n}`}catch(i){throw xt(new Error,Eo.DROP_FUNCTION_PROJECT,Gt.INTERNAL_SERVER_ERROR,Ct.ERR,i)}}a(y6,"dropCustomFunctionProject");async function N6(e){e.project&&(e.project=Te.parse(e.project).name);let t=os.packageComponentValidator(e);if(t)throw xt(t,t.message,Gt.BAD_REQUEST);let r=At.get(We.CONFIG_PARAMS.COMPONENTSROOT),{project:n}=e;Ct.trace("packaging component",n);let s;try{s=await Ve.realpath(Te.join(r,n))}catch(l){if(l.code!==We.NODE_ERROR_CODES.ENOENT)throw l;try{s=await Ve.realpath(Te.join(At.get(We.CONFIG_PARAMS.ROOTPATH),"node_modules",n))}catch(_){if(_.code===We.NODE_ERROR_CODES.ENOENT)throw new Error(`Unable to locate project '${n}'`)}}await Ve.ensureDir(oU);let i=Te.join(oU,`${n}.tar`),o={};(e.skip_node_modules===!0||e.skip_node_modules==="true")&&(o={ignore:l=>l.includes(Te.join(s,"node_modules"))}),aU.pack(s,o).pipe(Ve.createWriteStream(i,{overwrite:!0})),await new Promise(l=>setTimeout(l,2e3));let c=Ve.readFileSync(i,{encoding:"base64"});return await Ve.remove(i),{project:n,payload:c}}a(N6,"packageComponent");async function I6(e){e.project&&(e.project=Te.parse(e.project).name);let t=os.deployComponentValidator(e);if(t)throw xt(t,t.message,Gt.BAD_REQUEST);let r=At.get(We.CONFIG_PARAMS.COMPONENTSROOT),{project:n,payload:s,package:i}=e;if(Ct.trace("deploying component",n),!s&&!i)throw new Error("'payload' or 'package' must be provided");let o;if(s){o=Te.join(r,n),i="file:"+o,await Ve.emptyDir(o);let E=m6.from(Buffer.from(s,"base64"));await new Promise((h,p)=>{E.pipe(aU.extract(o,{finish:h})).on("error",p)});let f=await Ve.readdir(o);f.length===1&&f[0]==="package"&&(await Ve.copy(Te.join(o,"package"),o),await Ve.remove(Te.join(o,"package")))}if(await Vl.addConfig(n,{package:i}),!s){await E6();let E=cU.get(h6.CONFIG_PARAMS.ROOTPATH);o=Te.join(E,"node_modules",n)}if(p6)return;let c=new Map;c.isWorker=!0;let l=(pf(),ie(mf)),_;l.setErrorReporter(E=>_=E);let u=f6(o),d=l.component_errors.get(u);try{await l.loadComponent(o,c)}finally{l.component_errors.set(u,d)}if(_)throw _;return Ct.info("Installed component"),`Successfully deployed: ${n}`}a(I6,"deployComponent");async function w6(){let e=Vl.getConfiguration(),t=[];for(let o in e)if(e[o]?.package){if(e[o].package.startsWith("file:"))continue;t.push(Object.assign({},e[o],{name:o}))}let r=a(async(o,c)=>{try{let l=await Ve.readdir(o,{withFileTypes:!0});for(let _ of l){let u=_.name;if(u.startsWith(".")||u==="node_modules")continue;let d=Te.join(o,u);if(_.isDirectory()||_.isSymbolicLink()){let E={name:u,entries:[]};c.entries.push(E),await r(d,E)}else{let E=await Ve.stat(d),f={name:Te.basename(u),mtime:E.mtime,size:E.size};c.entries.push(f)}}return c}catch(l){return Ct.warn("Error loading package",l),{error:l.toString(),entries:[]}}},"walk_dir"),n=await r(At.get(We.CONFIG_PARAMS.COMPONENTSROOT),{name:At.get(We.CONFIG_PARAMS.COMPONENTSROOT).split(Te.sep).slice(-1).pop(),entries:t});for(let o of n.entries)if(o.package){let c=await r(Te.join(At.get(We.CONFIG_PARAMS.ROOTPATH),"node_modules",o.name),{name:o.name,entries:[]});Object.assign(o,c)}let i=(pf(),ie(mf)).component_errors;for(let o of t){let c=i.get(o.name);c?o.error=i.get(o.name):c===void 0&&(o.error="The component has not been loaded yet (may need a restart)")}return n}a(w6,"getComponents");async function C6(e){let t=os.getComponentFileValidator(e);if(t)throw xt(t,t.message,Gt.BAD_REQUEST);let n=Vl.getConfigObj()[e.project]||e.project==="harperdb"?Te.join(cU.get(We.CONFIG_PARAMS.ROOTPATH),"node_modules"):At.get(We.CONFIG_PARAMS.COMPONENTSROOT),s=e.encoding?{encoding:e.encoding}:{encoding:"utf8"};try{let i=await Ve.stat(Te.join(n,e.project,e.file));return{message:await Ve.readFile(Te.join(n,e.project,e.file),s),size:i.size,birthtime:i.birthtime,mtime:i.mtime}}catch(i){throw i.code===We.NODE_ERROR_CODES.ENOENT?new Error(`Component file not found '${Te.join(e.project,e.file)}'`):i}}a(C6,"getComponentFile");async function D6(e){let t=os.setComponentFileValidator(e);if(t)throw xt(t,t.message,Gt.BAD_REQUEST);let r=e.encoding?{encoding:e.encoding}:{encoding:"utf8"},n=Te.join(At.get(We.CONFIG_PARAMS.COMPONENTSROOT),e.project,e.file);return e.payload!==void 0?(await Ve.ensureFile(n),await Ve.outputFile(n,e.payload,r)):await Ve.ensureDir(n),"Successfully set component: "+e.file}a(D6,"setComponentFile");async function L6(e){let t=os.dropComponentFileValidator(e);if(t)throw xt(t,t.message,Gt.BAD_REQUEST);let r=e.file?Te.join(e.project,e.file):e.project,n=Te.join(At.get(We.CONFIG_PARAMS.COMPONENTSROOT),r);return await Ve.pathExists(n)&&await Ve.remove(n),Vl.deleteConfigFromFile([e.project]),"Successfully dropped: "+r}a(L6,"dropComponent");lU.exports={customFunctionsStatus:T6,getCustomFunctions:g6,getCustomFunction:R6,setCustomFunction:A6,dropCustomFunction:O6,addComponent:b6,dropCustomFunctionProject:y6,packageComponent:N6,deployComponent:I6,getComponents:w6,getComponentFile:C6,setComponentFile:D6,dropComponent:L6}});var zT=g((gEe,_U)=>{"use strict";var as=require("joi"),uU=at();_U.exports={readTransactionLogValidator:M6,deleteTransactionLogsBeforeValidator:P6};function M6(e){let t=as.object({schema:as.string().required(),table:as.string().required(),from:as.date().timestamp(),to:as.date().timestamp(),limit:as.number().min(1)});return uU.validateBySchema(e,t)}a(M6,"readTransactionLogValidator");function P6(e){let t=as.object({schema:as.string().required(),table:as.string().required(),timestamp:as.date().timestamp().required()});return uU.validateBySchema(e,t)}a(P6,"deleteTransactionLogsBeforeValidator")});var Sf=g((AEe,mU)=>{"use strict";var JT=U(),$l=wt(),dU=z(),fU=te(),EU=Rs(),{handleHDBError:wa,hdb_errors:U6}=ne(),{HTTP_STATUS_CODES:Ca}=U6,{readTransactionLogValidator:v6,deleteTransactionLogsBeforeValidator:B6}=zT(),hU="This operation relies on clustering and cannot run with it disable.",H6="Logs successfully deleted from transaction log.",x6="All logs successfully deleted from transaction log.";mU.exports={readTransactionLog:G6,deleteTransactionLogsBefore:F6};async function*G6(e){let t=v6(e);if(t)throw wa(t,t.message,Ca.BAD_REQUEST,void 0,void 0,!0);if(!fU.get(JT.CONFIG_PARAMS.CLUSTERING_ENABLED))throw wa(new Error,hU,Ca.NOT_FOUND,void 0,void 0,!0);let{schema:r,table:n}=e,s=dU.checkSchemaTableExist(r,n);if(s)throw wa(new Error,s,Ca.NOT_FOUND,void 0,void 0,!0);let i=EU.createNatsTableStreamName(r,n),o=await $l.viewStreamIterator(i,parseInt(e.from),e.limit);for await(let c of o){let l=Math.floor(c?.nats_timestamp/1e6);if(e.to&&l>e.to)break;let _={operation:c?.entry?.operation,user:c?.entry?.__origin?.user,timestamp:l,records:c?.entry?.records,attributes:c?.entry?.attributes};c?.entry?.operation===JT.OPERATIONS_ENUM.DELETE&&(_.hash_values=c?.entry?.hash_values),yield _}}a(G6,"readTransactionLog");async function F6(e){let t=B6(e);if(t)throw wa(t,t.message,Ca.BAD_REQUEST,void 0,void 0,!0);if(!fU.get(JT.CONFIG_PARAMS.CLUSTERING_ENABLED))throw wa(new Error,hU,Ca.NOT_FOUND,void 0,void 0,!0);let{schema:r,table:n,timestamp:s}=e,i=dU.checkSchemaTableExist(r,n);if(i)throw wa(new Error,i,Ca.NOT_FOUND,void 0,void 0,!0);let o=EU.createNatsTableStreamName(r,n),{jsm:c}=await $l.getNATSReferences(),l=await $l.getStreamInfo(o),_=new Date(l.state.first_ts).getTime();if(s<=_)return`No transactions exist before: ${s}`;let u=H6,d,E=new Date(l.state.last_ts).getTime();return s>E?(d=l.state.last_seq+1,u=x6):d=(await $l.viewStream(o,parseInt(s),1))[0].nats_sequence,await $l.purgeTableStream(r,n,{seq:d}),u}a(F6,"deleteTransactionLogsBefore")});var SU=g((bEe,pU)=>{"use strict";var XT=class{static{a(this,"PermissionTableResponseObject")}constructor(t,r,n=[],s=[]){this.schema=t,this.table=r,this.required_table_permissions=n,this.required_attribute_permissions=s}};pU.exports=XT});var gU=g((NEe,TU)=>{"use strict";var jT=class{static{a(this,"PermissionAttributeResponseObject")}constructor(t,r=[]){this.attribute_name=t,this.required_permissions=r}};TU.exports=jT});var eg=g((wEe,AU)=>{"use strict";var RU=SU(),q6=gU(),{HDB_ERROR_MSGS:k6}=Ur(),ZT=class{static{a(this,"PermissionResponseObject")}constructor(){this.error=k6.OP_AUTH_PERMS_ERROR,this.unauthorized_access={},this.invalid_schema_items=[]}handleUnauthorizedItem(t){return this.invalid_schema_items=[],this.unauthorized_access=[t],this}handleInvalidItem(t){return this.invalid_schema_items=[t],this.unauthorized_access=[],this}addInvalidItem(t,r,n){if(r&&n){let s=`${r}_${n}`;if(this.unauthorized_access[s])return}this.invalid_schema_items.push(t)}addUnauthorizedTable(t,r,n){let s=new RU(t,r,n),i=`${t}_${r}`;this.unauthorized_access[i]=s}addUnauthorizedAttributes(t,r,n,s){let i=[];t.forEach(c=>{let l=new q6(c,s[c]);i.push(l)});let o=`${r}_${n}`;if(this.unauthorized_access[o])this.unauthorized_access[o].required_attribute_permissions=i;else{let c=new RU(r,n,[],i);this.unauthorized_access[o]=c}}getPermsResponse(){let t=Object.values(this.unauthorized_access);return t.length>0||this.invalid_schema_items.length>0?(this.unauthorized_access=t,this):null}};AU.exports=ZT});var Af=g((DEe,xU)=>{"use strict";var tg=ln(),Tf=Gr(),hn=pd(),Wl=ri(),rg=Yi(),V6=dS(),$6=yD(),Ql=un(),gf=RS(),Dt=K(),Y6=bS(),K6=vd(),W6=sT(),Q6=Hd(),z6=oT(),J6=aT(),X6=uT(),j6=dT(),ng=hT(),Ps=z(),Z6=OM(),sg=gT(),yU=Ul(),En=U(),NU=DP(),e9=Ea(),IU=dl(),wU=(cf(),ie(xl)),CU=Er(),Qr=QT(),t9=require("alasql"),DU=Sf(),LU=ff(),MU=eg(),{handleHDBError:Nr,hdb_errors:PU}=ne(),{HDB_ERROR_MSGS:Kt,HTTP_STATUS_CODES:Yl}=PU,V=new Map,UU="delete",Ai="insert",Us="read",ho="update",Kl="describe",OU=Wl.describeSchema.name,bU=Wl.describeTable.name,vU={delete:!0,deleteRecord:!0,update:!0,updateData:!0,dropAttribute:!0,dropTable:!0,dropSchema:!0,upsert:!0,upsertData:!0},r9="catchup",n9="handleGetJob",s9="handleGetJobsByStartDate",Rf={CSV_DATA_LOAD:"csvDataLoad",CSV_URL_LOAD:"csvURLLoad",CSV_FILE_LOAD:"csvFileLoad",IMPORT_FROM_S3:"importFromS3"},i9=[hn.createTable.name,hn.createAttribute.name,hn.dropTable.name,hn.dropAttribute.name],BU={EXPORT_TO_S3:"export_to_s3",EXPORT_LOCAL:"export_local"},W=class{static{a(this,"permission")}constructor(t,r){this.requires_su=t,this.perms=r}};V.set(tg.insert.name,new W(!1,[Ai]));V.set(tg.update.name,new W(!1,[ho]));V.set(tg.upsert.name,new W(!1,[Ai,ho]));V.set(Tf.searchByConditions.name,new W(!1,[Us]));V.set(Tf.searchByHash.name,new W(!1,[Us]));V.set(Tf.searchByValue.name,new W(!1,[Us]));V.set(Tf.search.name,new W(!1,[Us]));V.set(hn.createSchema.name,new W(!0,[]));V.set(hn.createTable.name,new W(!0,[]));V.set(hn.createAttribute.name,new W(!1,[Ai]));V.set(hn.dropSchema.name,new W(!0,[]));V.set(hn.dropTable.name,new W(!0,[]));V.set(hn.dropAttribute.name,new W(!0,[]));V.set(Wl.describeSchema.name,new W(!1,[Us]));V.set(Wl.describeTable.name,new W(!1,[Us]));V.set(rg.deleteRecord.name,new W(!1,[UU]));V.set(Ql.addUser.name,new W(!0,[]));V.set(Ql.alterUser.name,new W(!0,[]));V.set(Ql.dropUser.name,new W(!0,[]));V.set(Ql.listUsersExternal.name,new W(!0,[]));V.set(gf.listRoles.name,new W(!0,[]));V.set(gf.addRole.name,new W(!0,[]));V.set(gf.alterRole.name,new W(!0,[]));V.set(gf.dropRole.name,new W(!0,[]));V.set(Y6.name,new W(!0,[]));V.set(K6.name,new W(!0,[]));V.set(W6.name,new W(!0,[]));V.set(Q6.name,new W(!0,[]));V.set(z6.name,new W(!0,[]));V.set(J6.name,new W(!0,[]));V.set(ng.setRoutes.name,new W(!0,[]));V.set(ng.getRoutes.name,new W(!0,[]));V.set(ng.deleteRoutes.name,new W(!0,[]));V.set(CU.setConfiguration.name,new W(!0,[]));V.set(X6.clusterStatus.name,new W(!0,[]));V.set(j6.name,new W(!0,[]));V.set(sg.getFingerprint.name,new W(!0,[]));V.set(sg.setLicense.name,new W(!0,[]));V.set(rg.deleteFilesBefore.name,new W(!0,[]));V.set(rg.deleteAuditLogsBefore.name,new W(!0,[]));V.set(yU.restart.name,new W(!0,[]));V.set(yU.restartService.name,new W(!0,[]));V.set(V6.name,new W(!0,[]));V.set($6.name,new W(!0,[Us]));V.set(e9.systemInformation.name,new W(!0,[]));V.set(CU.getConfiguration.name,new W(!0,[]));V.set(DU.readTransactionLog.name,new W(!0,[]));V.set(DU.deleteTransactionLogsBefore.name,new W(!0,[]));V.set(LU.installModules.name,new W(!0,[]));V.set(LU.auditModules.name,new W(!0,[]));V.set(IU.createTokens.name,new W(!1,[]));V.set(IU.refreshOperationToken.name,new W(!1,[]));V.set(wU.login.name,new W(!1,[]));V.set(wU.logout.name,new W(!1,[]));V.set(Qr.customFunctionsStatus.name,new W(!0,[]));V.set(Qr.getCustomFunctions.name,new W(!0,[]));V.set(Qr.getComponents.name,new W(!0,[]));V.set(Qr.getComponentFile.name,new W(!0,[]));V.set(Qr.setComponentFile.name,new W(!0,[]));V.set(Qr.dropComponent.name,new W(!0,[]));V.set(Qr.getCustomFunction.name,new W(!0,[]));V.set(Qr.setCustomFunction.name,new W(!0,[]));V.set(Qr.dropCustomFunction.name,new W(!0,[]));V.set(Qr.addComponent.name,new W(!0,[]));V.set(Qr.dropCustomFunctionProject.name,new W(!0,[]));V.set(Qr.packageComponent.name,new W(!0,[]));V.set(Qr.deployComponent.name,new W(!0,[]));V.set(sg.getRegistrationInfo.name,new W(!1,[]));V.set(Ql.userInfo.name,new W(!1,[]));V.set(Wl.describeAll.name,new W(!1,[]));V.set(n9,new W(!1,[]));V.set(s9,new W(!0,[]));V.set(r9,new W(!0,[]));V.set(Rf.CSV_DATA_LOAD,new W(!1,[Ai,ho]));V.set(Rf.CSV_URL_LOAD,new W(!1,[Ai,ho]));V.set(Rf.CSV_FILE_LOAD,new W(!1,[Ai,ho]));V.set(Rf.IMPORT_FROM_S3,new W(!1,[Ai,ho]));V.set(BU.EXPORT_TO_S3,new W(!0,[]));V.set(BU.EXPORT_LOCAL,new W(!0,[]));V.set(En.VALID_SQL_OPS_ENUM.DELETE,new W(!1,[UU]));V.set(En.VALID_SQL_OPS_ENUM.SELECT,new W(!1,[Us]));V.set(En.VALID_SQL_OPS_ENUM.INSERT,new W(!1,[Ai]));V.set(En.VALID_SQL_OPS_ENUM.UPDATE,new W(!1,[ho]));xU.exports={verifyPerms:a9,verifyPermsAst:o9,verifyBulkLoadAttributePerms:l9};function o9(e,t,r){if(Ps.isEmptyOrZeroLength(e))throw Dt.info("verify_perms_ast has an empty user parameter"),Nr(new Error);if(Ps.isEmptyOrZeroLength(t))throw Dt.info("verify_perms_ast has an empty user parameter"),Nr(new Error);if(Ps.isEmptyOrZeroLength(r))throw Dt.info("verify_perms_ast has a null operation parameter"),Nr(new Error);try{let n=new MU,s=new Z6(e),i=s.getSchemas(),o=new Map;if((!i||i.length===0)&&s.affected_attributes&&s.affected_attributes.size>0)throw Dt.info("No schemas defined in verifyPermsAst(), will not continue."),Nr(new Error);let c=!!t.role.permission.super_user,l=i.includes("system");if(l&&vU[r])throw Nr(new Error,Kt.DROP_SYSTEM,Yl.FORBIDDEN);if(c&&!l)return null;let _=NU.getRolePermissions(t.role);t.role.permission=_,!c&&e instanceof t9.yy.Select&&(e=s.updateAttributeWildcardsForRolePerms(_));for(let d=0;d<i.length;d++){let E=s.getTablesBySchemaName(i[d]);E&&o.set(i[d],E)}let u=HU(t,r,o,n);return u||(o.forEach((d,E)=>{for(let f=0;f<d.length;f++){let h=s.getAttributesBySchemaTableName(E,d[f]),p=og(t.role.permission,E,d[f]);ig(h,p,r,d[f],E,n)}}),n.getPermsResponse())}catch(n){throw Nr(n)}}a(o9,"verifyPermsAst");function a9(e,t){if(e===null||t===null||e.hdb_user===void 0||e.hdb_user===null)throw Dt.info("null required parameter in verifyPerms"),Nr(new Error,Kt.DEFAULT_INVALID_REQUEST,Yl.BAD_REQUEST);let r;t instanceof Function?r=t.name:r=t;let n=e.action,s=e.schema??e.database,i=e.table,o=new Map;s&&i&&o.set(s,[i]);let c=new MU;if(Ps.isEmptyOrZeroLength(e.hdb_user.role)||Ps.isEmptyOrZeroLength(e.hdb_user.role.permission))return Dt.info(`User ${e.hdb_user.username} has no role or permissions. Please assign the user a valid role.`),c.handleUnauthorizedItem(Kt.USER_HAS_NO_PERMS(e.hdb_user.username));let l=!!e.hdb_user.role.permission.super_user,_=e.hdb_user.role.permission.structure_user,u=o.has(En.SYSTEM_SCHEMA_NAME)||s===En.SYSTEM_SCHEMA_NAME;if(u&&vU[r])throw Nr(new Error,Kt.DROP_SYSTEM,Yl.FORBIDDEN);if(l&&!u||_===!0&&(r===hn.createSchema.name||r===hn.dropSchema.name))return null;if(i9.indexOf(r)>=0&&(_===!0||Array.isArray(_)))return _===!0||_.indexOf(s)>=0?null:c.handleUnauthorizedItem(`User does not have access to perform '${e.operation}' against schema '${s}'`);let d=NU.getRolePermissions(e.hdb_user.role);if(e.hdb_user.role.permission=d,r===OU||r===bU){if(s===En.SYSTEM_SCHEMA_NAME)return c.handleUnauthorizedItem(Kt.SCHEMA_PERM_ERROR(s));if(!d.super_user){if(r===OU&&(!d[s]||!d[s][Kl]))return c.handleInvalidItem(Kt.SCHEMA_NOT_FOUND(s));if(r===bU&&(!d[s]||!d[s].tables[i]||!d[s].tables[i][Kl]))return c.handleInvalidItem(Kt.TABLE_NOT_FOUND(s,i))}}let E=HU(e.hdb_user,r,o,c,n);if(E)return E;if(V.get(r)&&V.get(r).perms.length===0)return null;if(!l&&e.get_attributes&&En.SEARCH_WILDCARDS.includes(e.get_attributes[0])){let p=[],S=d[s].tables[i];S[En.PERMS_CRUD_ENUM.READ]&&(S.attribute_permissions.length>0?S.attribute_permissions.filter(R=>R[En.PERMS_CRUD_ENUM.READ]).forEach(R=>{p.push(R.attribute_name)}):p=global.hdb_schema[s][i].attributes.map(T=>T.attribute),e.get_attributes=p)}let f=c9(e),h=og(e.hdb_user.role.permission,s,i);return ig(f,h,r,i,s,c,n),c.getPermsResponse()}a(a9,"verifyPerms");function HU(e,t,r,n,s){if(Ps.arrayHasEmptyValues([e,t,r]))throw Dt.info("hasPermissions has an invalid parameter"),Nr(new Error);let i=r.has("system"),o=e.role.permission;if(o.super_user&&(!i||V.get(t).requires_su))return null;if(!V.get(t))throw Dt.info(`operation ${t} not found.`),Nr(new Error,Kt.OP_NOT_FOUND(t),Yl.BAD_REQUEST);if(V.get(t)&&V.get(t).requires_su)return Dt.info(`operation ${t} requires SU permissions.`),n.handleUnauthorizedItem(Kt.OP_IS_SU_ONLY(t));let c=r.keys();for(let l of c){try{if(l&&!o[l]||o[l][Kl]===!1){n.addInvalidItem(Kt.SCHEMA_NOT_FOUND(l));continue}}catch{n.addInvalidItem(Kt.SCHEMA_NOT_FOUND(l));continue}let _=r.get(l);for(let u of _){let d=o[l].tables[u];if(!d||d[Kl]===!1)n.addInvalidItem(Kt.TABLE_NOT_FOUND(l,u));else try{let E=[],f=V.get(t).perms;!Ps.isEmpty(s)&&f.includes(s)&&(f=[s]);for(let h=0;h<f.length;h++){let p=f[h],S=d[p];(S==null||S===!1)&&(Dt.info(`Required ${p} permission not found for ${t} ${s?`${s} `:""}operation in role ${e.role.id}`),E.push(p))}E.length>0&&n.addUnauthorizedTable(l,u,E)}catch(E){let f=Kt.UNKNOWN_OP_AUTH_ERROR(t,l,u);throw Dt.error(f),Dt.error(E),Nr(PU.CHECK_LOGS_WRAPPER(f))}}}return r.size<2?n.getPermsResponse():null}a(HU,"hasPermissions");function ig(e,t,r,n,s,i,o){if(!e||!t)throw Dt.info("no attributes specified in checkAttributePerms."),Nr(new Error);let c=V.get(r).perms;if(!c||c==="")throw Dt.info(`no permissions found for ${r} in checkAttributePerms().`),Nr(new Error);if(Ps.isEmptyOrZeroLength(t))return Dt.info("No role permissions set (this is OK)."),null;o&&c.includes(o)&&(c=[o]);let l={};for(let u of e){let d=t.get(u);if(d){if(d[Kl]===!1){i.addInvalidItem(Kt.ATTR_NOT_FOUND(s,n,u),s,n);continue}if(c)for(let E of c){if(En.TIME_STAMP_NAMES.includes(d.attribute_name)&&E!==Us)throw Nr(new Error,Kt.SYSTEM_TIMESTAMP_PERMS_ERR,Yl.FORBIDDEN);d[E]===!1&&(l[d.attribute_name]?l[d.attribute_name].push(E):l[d.attribute_name]=[E])}}else i.addInvalidItem(Kt.ATTR_NOT_FOUND(s,n,u),s,n)}let _=Object.keys(l);_.length>0&&i.addUnauthorizedAttributes(_,s,n,l)}a(ig,"checkAttributePerms");function c9(e){let t=new Set;try{if(e.action)return t;if(e.operation===En.OPERATIONS_ENUM.SEARCH_BY_CONDITIONS&&e.conditions.forEach(r=>{t.add(r.search_attribute)}),e&&e.search_attribute&&t.add(e.search_attribute),!e.records||e.records.length===0){if(!e.get_attributes||!e.get_attributes.length===0)return t;for(let r=0;r<e.get_attributes.length;r++)t.add(e.get_attributes[r])}else for(let r=0;r<e.records.length;r++){let n=Object.keys(e.records[r]);for(let s=0;s<n.length;s++)t.add(n[s])}}catch(r){Dt.info(r)}return t}a(c9,"getRecordAttributes");function og(e,t,r){let n=new Map;if(Ps.isEmpty(e))return Dt.info("no hdb_user specified in getAttributePermissions"),n;if(e.super_user||!t||!r)return n;try{e[t].tables[r].attribute_permissions.forEach(s=>{n.has(s.attribute_name)||n.set(s.attribute_name,s)})}catch{Dt.info(`No attribute permissions found for schema ${t} and table ${r}.`)}return n}a(og,"getAttributePermissions");function l9(e,t,r,n,s,i,o){let c=new Set(i),l=og(e,n,s);ig(c,l,t,s,n,o,r)}a(l9,"verifyBulkLoadAttributePerms")});var bf=g((MEe,VU)=>{"use strict";VU.exports={evaluateSQL:A9,processAST:kU,convertSQLToAST:qU,checkASTPermissions:FU};var u9=ln(),GU=require("util"),_9=GU.callbackify(u9.insert),d9=Gr().search,f9=rD().update,E9=GU.callbackify(f9),h9=sD().convertDelete,Oi=require("alasql"),m9=Af(),Of=K(),p9=_d(),S9=z(),zl=U(),{hdb_errors:T9,handleHDBError:ag}=ne(),{HTTP_STATUS_CODES:cg}=T9;p9(Oi);var g9=403,R9="There was a problem performing this insert. Please check the logs and try again.",lg=class{static{a(this,"ParsedSQLObject")}constructor(){this.ast=void 0,this.variant=void 0,this.permissions_checked=!1}};function A9(e,t){let r=e.parsed_sql_object;if(!r){r=qU(e.sql);let n,s=r.ast.statements[0];if(s instanceof Oi.yy.Insert?n=s.into.databaseid:s instanceof Oi.yy.Select?n=s.from?s.from[0].databaseid:null:s instanceof Oi.yy.Update||s instanceof Oi.yy.Delete?n=s.table.databaseid:Of.error("AST in evaluateSQL is not a valid SQL type."),!(s instanceof Oi.yy.Select)&&S9.isEmptyOrZeroLength(n))return t("No schema specified",null)}kU(e,r,(n,s)=>{if(n)return t(n);t(null,s)})}a(A9,"evaluateSQL");function FU(e,t){let r;try{r=m9.verifyPermsAst(t.ast.statements[0],e.hdb_user,t.variant),t.permissions_checked=!0}catch(n){throw n}return r||null}a(FU,"checkASTPermissions");function qU(e){let t=new lg;if(!e)throw ag(new Error,"The 'sql' parameter is missing from the request body",cg.BAD_REQUEST);try{let r=e.trim(),n=Oi.parse(r),s=r.split(" ")[0].toLowerCase();t.ast=n,t.variant=s}catch(r){let n=r.message.split(`
16
- `);throw n[1]?ag(r,`Invalid SQL at: ${n[1]}. Please ensure your SQL is valid. Try adding backticks to reserved words and schema table references.`,cg.BAD_REQUEST):ag(r,"We had trouble parsing your request. Please ensure your SQL is valid. Try adding backticks to reserved words and schema table references.",cg.BAD_REQUEST)}return t}a(qU,"convertSQLToAST");function kU(e,t,r){try{let n=O9;if(!e.bypass_auth&&!t.permissions_checked){let i=FU(e,t);if(i&&i.length>0)return r(g9,i)}let s={statement:t.ast.statements[0],hdb_user:e.hdb_user};switch(t.variant){case zl.VALID_SQL_OPS_ENUM.SELECT:n=d9,s=t.ast.statements[0];break;case zl.VALID_SQL_OPS_ENUM.INSERT:n=b9;break;case zl.VALID_SQL_OPS_ENUM.UPDATE:n=E9;break;case zl.VALID_SQL_OPS_ENUM.DELETE:n=h9;break;default:throw new Error(`unsupported SQL type ${t.variant} in SQL: ${e}`)}n(s,(i,o)=>{if(i){r(i);return}r(null,o)})}catch(n){return r(n)}}a(kU,"processAST");function O9(e,t){Of.info(e),t("unknown sql statement")}a(O9,"nullFunction");function b9({statement:e,hdb_user:t},r){let n=e.into,s={schema:n.databaseid,table:n.tableid,operation:"insert",hdb_user:t},i=e.columns.map(o=>o.columnid);try{s.records=y9(i,e.values)}catch(o){return r(o)}_9(s,(o,c)=>{if(o)return r(o);try{delete c.new_attributes,delete c.txn_time}catch(l){Of.error(`Error delete new_attributes from insert response: ${l}`)}r(null,c)})}a(b9,"convertInsert");function y9(e,t){try{return t.map(r=>{if(e.length!==r.length)throw"number of values do not match number of columns in insert";let n={};return r.forEach((s,i)=>{if(s.columnid)throw"cannot use a column in insert value";"value"in s?n[e[i]]=s.value:n[e[i]]=Oi.compile(`SELECT ${s.toString()} AS [${zl.FUNC_VAL}] FROM ?`)}),n})}catch(r){throw Of.error(r),new Error(R9)}}a(y9,"createDataObjects")});var ug=g((UEe,YU)=>{"use strict";var{S3:N9,GetObjectCommand:I9}=require("@aws-sdk/client-s3");YU.exports={getFileStreamFromS3:w9,getS3AuthObj:$U};async function w9(e){let{s3:t}=e,r={Bucket:t.bucket,Key:t.key};return(await $U(t.aws_access_key_id,t.aws_secret_access_key,t.region).send(new I9(r))).Body}a(w9,"getFileStreamFromS3");function $U(e,t,r){return new N9({credentials:{accessKeyId:e,secretAccessKey:t},region:r})}a($U,"getS3AuthObj")});var yf=g((BEe,ev)=>{"use strict";var dg=Gr(),C9=bf(),D9=ug(),{AsyncParser:L9,Transform:M9}=require("json2csv"),Xl=require("stream"),zr=z(),_g=require("fs-extra"),P9=require("path"),mn=K(),{promisify:QU}=require("util"),Jl=z(),{handleHDBError:Ot,hdb_errors:U9}=ne(),{HDB_ERROR_MSGS:Ir,HTTP_STATUS_CODES:bt}=U9,{streamAsJSON:v9}=(Yh(),ie(fb)),{Upload:B9}=require("@aws-sdk/lib-storage"),KU=["search_by_value","search_by_hash","sql","search_by_conditions"],WU=["json","csv"],zU="json",JU="csv",H9="Successfully exported JSON locally.",x9="Successfully exported CSV locally.",G9=1e3,F9=dg.searchByHash,q9=dg.searchByValue,k9=QU(C9.evaluateSQL),V9=QU(Xl.finished);ev.exports={export_to_s3:W9,export_local:$9,toCsvStream:XU};async function $9(e){mn.trace(`export_local request to path: ${e.path}, filename: ${e.filename}, format: ${e.format}`);let t=jU(e);if(!zr.isEmpty(t))throw mn.error(t),Ot(new Error,t,bt.BAD_REQUEST,void 0,void 0,!0);if(zr.isEmpty(e.path))throw mn.error(Ir.MISSING_VALUE("path")),Ot(new Error,Ir.MISSING_VALUE("path"),bt.BAD_REQUEST,void 0,void 0,!0);let r=(zr.isEmpty(e.filename)?new Date().getTime():e.filename)+"."+e.format;e.path.endsWith(P9.sep)&&(e.path=e.path.substring(0,e.path.length-1));let n=zr.buildFolderPath(e.path,r);await Y9(e.path);let s=await ZU(e);return await K9(n,e.format,s)}a($9,"export_local");async function Y9(e){if(mn.trace("in confirmPath"),zr.isEmptyOrZeroLength(e))throw Ot(new Error,`Invalid path: ${e}`,bt.BAD_REQUEST,void 0,void 0,!0);let t;try{t=await _g.stat(e)}catch(r){let n;throw r.code==="ENOENT"?n=`path '${e}' does not exist`:r.code==="EACCES"?n=`access to path '${e}' is denied`:n=r.message,mn.error(n),Ot(new Error,n,bt.BAD_REQUEST,void 0,void 0,!0)}if(!t.isDirectory()){let r=`path '${e}' is not a directory, please supply a valid folder path`;throw mn.error(r),Ot(new Error,r,bt.BAD_REQUEST,void 0,void 0,!0)}return!0}a(Y9,"confirmPath");async function K9(e,t,r){if(mn.trace("in saveToLocal"),Jl.isEmptyOrZeroLength(e))throw Ot(new Error,Ir.INVALID_VALUE("file_path"),bt.BAD_REQUEST,void 0,void 0,!0);if(Jl.isEmptyOrZeroLength(t))throw Ot(new Error,Ir.INVALID_VALUE("Source format"),bt.BAD_REQUEST,void 0,void 0,!0);if(Jl.isEmpty(r))throw Ot(new Error,Ir.NOT_FOUND("Data"),bt.BAD_REQUEST,void 0,void 0,!0);if(t===zU){let n=_g.createWriteStream(e);return v9(r).pipe(n),await V9(n),{message:H9,path:e}}else if(t===JU){let n=_g.createWriteStream(e),s=Xl.Readable.from(r),i={},o=r.getColumns?.();o&&(i.fields=o.map(u=>({label:u,value:u})));let c={objectMode:!0};return await new L9(i,c).fromInput(s).toOutput(n).promise(!1),{message:x9,path:e}}throw Ot(new Error,Ir.INVALID_VALUE("format"),bt.BAD_REQUEST)}a(K9,"saveToLocal");async function W9(e){if(!e.s3||Object.keys(e.s3).length===0)throw Ot(new Error,Ir.MISSING_VALUE("S3 object"),bt.BAD_REQUEST);if(zr.isEmptyOrZeroLength(e.s3.aws_access_key_id))throw Ot(new Error,Ir.MISSING_VALUE("aws_access_key_id"),bt.BAD_REQUEST);if(zr.isEmptyOrZeroLength(e.s3.aws_secret_access_key))throw Ot(new Error,Ir.MISSING_VALUE("aws_secret_access_key"),bt.BAD_REQUEST);if(zr.isEmptyOrZeroLength(e.s3.bucket))throw Ot(new Error,Ir.MISSING_VALUE("bucket"),bt.BAD_REQUEST);if(zr.isEmptyOrZeroLength(e.s3.key))throw Ot(new Error,Ir.MISSING_VALUE("key"),bt.BAD_REQUEST);if(zr.isEmptyOrZeroLength(e.s3.region))throw Ot(new Error,Ir.MISSING_VALUE("region"),bt.BAD_REQUEST);let t=jU(e);if(!zr.isEmpty(t))throw Ot(new Error,t,bt.BAD_REQUEST);mn.trace(`called export_to_s3 to bucket: ${e.s3.bucket} and query ${e.search_operation.sql}`);let r;try{r=await ZU(e)}catch(l){throw mn.error(l),l}let n,s=await D9.getS3AuthObj(e.s3.aws_access_key_id,e.s3.aws_secret_access_key,e.s3.region),i,o=new Xl.PassThrough;if(e.format===JU){i=e.s3.key+".csv";let l=XU(r,r.getColumns?.());l.on("error",_=>{throw _}),l.pipe(o)}else if(e.format===zU){i=e.s3.key+".json";let l=new Xl.Readable;l.pipe(o),l.on("error",d=>{throw d}),l.push("[");let _=r.length,u="";for(let[d,E]of r.entries()){let f=d===_-1?JSON.stringify(E):JSON.stringify(E)+",";u+=f,d!==0&&d%G9===0&&(l.push(u),u="")}u.length!==0&&l.push(u),l.push("]"),l.push(null)}else throw Ot(new Error,Ir.INVALID_VALUE("format"),bt.BAD_REQUEST);return new B9({client:s,params:{Bucket:e.s3.bucket,Key:i,Body:o}}).done()}a(W9,"export_to_s3");function XU(e,t){let r=Xl.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 M9(n,s);return r.pipe(i)}a(XU,"toCsvStream");function jU(e){if(mn.trace("in exportCoreValidation"),zr.isEmpty(e.format))return"format missing";if(WU.indexOf(e.format)<0)return`format invalid. must be one of the following values: ${WU.join(", ")}`;let t=e.search_operation.operation;if(zr.isEmpty(t))return"search_operation.operation missing";if(KU.indexOf(t)<0)return`search_operation.operation must be one of the following values: ${KU.join(", ")}`}a(jU,"exportCoreValidation");async function ZU(e){mn.trace("in getRecords");let t,r;if(Jl.isEmpty(e.search_operation)||Jl.isEmptyOrZeroLength(e.search_operation.operation))throw Ot(new Error,Ir.INVALID_VALUE("Search operation"),bt.BAD_REQUEST);switch(e.search_operation.operation){case"search_by_value":t=q9;break;case"search_by_hash":t=F9;break;case"search_by_conditions":t=dg.searchByConditions;break;case"sql":t=k9;break;default:throw r=`Operation ${e.search_operation.operation} is not support by export.`,mn.error(r),Ot(new Error,r,bt.BAD_REQUEST)}return e.search_operation.hdb_user=e.hdb_user,t(e.search_operation)}a(ZU,"getRecords")});var lv={};qe(lv,{contentTypes:()=>mg,findBestSerializer:()=>wf,getDeserializer:()=>po,registerContentHandlers:()=>pg,serialize:()=>Cf,serializeMessage:()=>fo});function Q9(e){try{return e?.[0]===123?hg(e):e}catch{return e}}function pg(e){e.register(J9,{serializers:[{regex:/^application\/json$/,serializer:Oc},{regex:/^application\/cbor$/,serializer:function(t){return new mo.EncoderStream(Zl).end(t)}},{regex:/^application\/(x-)?msgpack$/,serializer:function(t){return(t?.[Symbol.iterator]||t?.[Symbol.asyncIterator])&&!Array.isArray(t)?If.Readable.from((0,cs.encodeIter)(t,Zl)):(0,cs.pack)(t)}},{regex:/^text\/csv$/,serializer:function(t){return this.header("Content-Disposition",'attachment; filename="data.csv"'),(0,Nf.toCsvStream)(t)}}]}),e.addContentTypeParser("application/x-msgpack",{parseAs:"buffer"},(t,r,n)=>{try{n(null,(0,cs.unpack)(r))}catch(s){s.statusCode=400,n(s)}}),e.addContentTypeParser("application/cbor",{parseAs:"buffer"},(t,r,n)=>{try{n(null,(0,mo.decode)(r))}catch(s){s.statusCode=400,n(s)}})}function wf(e){let r=(e.headers.asObject||e.headers).accept,n,s=0,i,o,c=r?r.toLowerCase().split(/\s*,\s*/):[];for(let l of c){let[_,...u]=l.split(/\s*;\s*/),d=1,E={q:1};for(let h of u){let p=h.indexOf("=");E[h.substring(0,p)]=h.substring(p+1)}d=+E.q;let f=Ft.get(_);if(f){let h=(f.q||1)*d;h>s&&(n=f,i=f.type||_,s=h,o=E)}}if(!n){if(r)throw new sv.ClientError("No supported content types found in Accept header, supported types include: "+Array.from(Ft.keys()).join(", "),406);n=Ft.get("application/json"),i="application/json"}return{serializer:n,type:i,parameters:o}}function Cf(e,t,r){let n=rv&&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)r.headers.set("Content-Type","application/octet-stream"),r.headers.set("Vary","Accept-Encoding"),s=e;else{let i=wf(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[Symbol.iterator]||e[Symbol.asyncIterator])&&i.serializer.serializeStream){let o=i.serializer.serializeStream(e,r);return n&&(r.headers.set("Content-Encoding","br"),o=o.pipe((0,vs.createBrotliCompress)({params:{[vs.constants.BROTLI_PARAM_MODE]:i.type.includes("json")||i.type.includes("text")?vs.constants.BROTLI_MODE_TEXT:vs.constants.BROTLI_MODE_GENERIC,[vs.constants.BROTLI_PARAM_QUALITY]:2}}))),o}s=i.serializer.serialize(e,r)}return n&&s?.length>rv?(r.headers.set("Content-Encoding","br"),new Promise((i,o)=>(0,vs.brotliCompress)(s,(c,l)=>{c?o(c):i(l)}))):s}function fo(e,t){if(e?.contentType!=null&&e.data!=null)return e.data;if(!t)return jl(e);let r=t.serialize;if(r)return r(e);let n=wf(t);return r=t.serialize=n.serializer.serialize,r(e)}function X9(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 po(e,t){e||(e="");let r=e.indexOf(";"),n;r>-1&&(n=e.slice(r+1),e=e.slice(0,r));let s=Ft.get(e);if(t){if(s?.deserializeStream)return s.deserializeStream;let i=Ft.get(e)?.deserialize||nv(e,n);return o=>X9(o).then(i)}return e&&Ft.get(e)?.deserialize||nv(e,n)}function nv(e,t){if(e.startsWith("text/")){let r=t?.match(/charset=(.+)/)?.[1]||"utf-8";return n=>({contentType:e,data:n.toString(r)})}else return e==="application/octet-stream"?r=>r:r=>{if(!e)try{if(r?.[0]===123)return hg(r)}catch{}return{contentType:e||"application/octet-stream",data:r}}}function j9(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)}}}}}var Nf,cs,mo,vs,sv,If,iv,fg,Eg,ov,av,jl,hg,Zl,Ft,mg,tv,cv,z9,J9,rv,Oa=Re(()=>{Yh();Nf=B(yf()),cs=require("msgpackr"),mo=require("cbor-x"),vs=require("zlib"),sv=B(ne()),If=require("stream");ur();iv=require("../index"),fg=B(te()),Eg=B(U()),ov=B(require("yaml")),av=fg.default.get(Eg.CONFIG_PARAMS.SERIALIZATION_BIGINT)!==!1,jl=av?Bi:JSON.stringify,hg=av?$h:JSON.parse,Zl={useRecords:!1,useToJSON:!0},Ft=new Map,mg=Ft;st.contentTypes=mg;(0,iv._assignPackageExport)("contentTypes",mg);Ft.set("application/json",{serializeStream:Oc,serialize:jl,deserialize:hg,q:.8});tv=new mo.Encoder(Zl);Ft.set("application/cbor",{serializeStream(e){return e[Symbol.asyncIterator]&&(e[Symbol.iterator]=null),new mo.EncoderStream(Zl).end(e)},serialize:tv.encode,deserialize:tv.decode,q:1});Ft.set("application/x-msgpack",{serializeStream(e){return(e?.[Symbol.iterator]||e?.[Symbol.asyncIterator])&&!Array.isArray(e)?If.Readable.from((0,cs.encodeIter)(e,Zl)):(0,cs.pack)(e)},serialize:cs.pack,deserialize:cs.unpack,q:.9});Ft.set("text/csv",{serializeStream(e,t){return t.headers.set("Content-Disposition",'attachment; filename="data.csv"'),(0,Nf.toCsvStream)(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]),(0,Nf.toCsvStream)(e,e?.getColumns?.())},q:.1});Ft.set("text/plain",{serialize(e){return e.toString()},deserialize(e){return e.toString()},q:.2});Ft.set("text/yaml",{serialize(e){return ov.stringify(e,{aliasDuplicateObjects:!1})},q:.7});Ft.set("text/event-stream",{serializeStream:function(e){return If.Readable.from(j9(e,this.serialize))},serialize: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+`
17
- `),e.data){let r=e.data;typeof r=="object"&&(r=jl(r)),t+="data: "+r+`
12
+ Database backup has not been removed and can be found here: ${s}`;Ld.error(l),console.error(l)}(0,CA.get)(bo.CONFIG_PARAMS.STORAGE_COMPACTONSTARTKEEPBACKUP)===!0||o===!1||(console.log("Removing backup",s),await(0,Oa.remove)(s))}(0,DA.updateConfigValue)(bo.CONFIG_PARAMS.STORAGE_COMPACTONSTART,!1)}async function hx(e){let t=await(0,Tx.describeSchema)({database:e}),r=0;for(let n in t)r+=t[n].record_count;return r}async function gx(e,t){console.log("copyDb start");let r=ct()[e],n;for(let f in r){n=r[f].primaryStore.rootStore;break}let s=n.dbisDb,i=n.auditStore,o=(0,mx.open)(new px.default(t)),c=o.openDB(yh.INTERNAL_DBIS_NAME),l,d=0,u=s.useReadTransaction();try{for(let{key:_,value:h}of s.getRange({transaction:u})){let p=h.is_hash_attribute||h.isPrimaryKey,S,g;if(p&&(S=h.compression,g=Oh(),g?h.compression=g:delete h.compression,S?.dictionary?.toString()===g?.dictionary?.toString()&&(S=null,g=null)),c.put(_,h),!(p||h.indexed))continue;let T=new Sx.default(!p,p);T.encoding="binary",T.compression=S;let A=n.openDB(_,T);A.decoder=null,T.compression=g;let N=o.openDB(_,T);N.encoder=null,console.log("copying",_,"from",e,"to",t),await E(A,N,p,u)}let f=n.openDB(yh.AUDIT_STORE_NAME,Pd);console.log("copying audit log"),E(i,f,!1,u);async function E(_,h,p,S){let g=0,T=0;for(let{key:A,value:N,version:V}of _.getRange({start:null,versions:p,transaction:S}))l=h.put(A,N,V),g++,S.openTimer&&(S.openTimer=0),T+=(A?.length||10)+N.length,d++>5e3&&(await l,console.log("copied",g,"entries",T,"bytes"),d=0);console.log("finish copying, copied",g,"entries",T,"bytes")}a(E,"copyDbi"),await l,console.log("copied database "+e+" to "+t)}finally{u.done(),o.close()}}var mx,bh,Oa,CA,px,Sx,yh,bo,Tx,DA,Ld,Ax=Oe(()=>{Ne();mx=require("lmdb"),bh=require("path"),Oa=require("fs-extra"),CA=U(ie()),px=U(mu()),Sx=U(hu()),yh=U(Ft()),bo=U(H());_i();Tx=U(Zi()),DA=U(dr()),Ld=U(X());a(fte,"compactOnStart");a(hx,"getTotalDBRecordCount");a(gx,"copyDb")});var xd=I((Rge,wx)=>{"use strict";var _te=require("minimist"),{isMainThread:PA,parentPort:Ud,threadId:Tge}=require("worker_threads"),Ot=H(),{PROCESS_DESCRIPTORS_VALIDATE:ol}=Ot,js=X(),MA=re(),Ih=OA(),Nh=or(),gge=Pt(),Ox=dr(),Js=Ex(),bx=Bc(),{compactOnStart:Ete}=(Ax(),ae(Rx)),hte=a_(),{restartWorkers:wh,onMessageByType:mte}=at(),{handleHDBError:pte,hdb_errors:Ste}=ce(),{HTTP_STATUS_CODES:Tte}=Ste,vd=ie();vd.initSync();var Md=`Restarting HarperDB. This may take up to ${Ot.RESTART_TIMEOUT_MS/1e3} seconds.`,gte="Restart is not available from the CLI when running in non-pm2 mode. Either call restart from the API or stop and start HarperDB.",yx="Clustering is not enabled so cannot be restarted",Rte="Invalid service",al,jn;wx.exports={restart:Nx,restartService:UA};PA&&mte(Ot.ITC_EVENT_TYPES.RESTART,async(e,t)=>{e.workerType?await UA({service:e.workerType}):Nx({operation:"restart"}),t.postMessage({type:"restart-complete"})});async function Nx(e){jn=Object.keys(e).length===0,al=await Js.isServiceRegistered(Ot.HDB_PROC_DESCRIPTOR);let t=_te(process.argv);if(t.service){await UA(t);return}if(jn&&!al){console.error(gte);return}if(jn&&console.log(Md),al){Js.enterPM2Mode(),js.notify(Md);let r=hte(Object.keys(Ot.CONFIG_PARAM_MAP),!0);return MA.isEmptyOrZeroLength(Object.keys(r))||Ox.updateConfigValue(void 0,void 0,r,!0,!0),Ate(),Md}return PA?(js.notify(Md),vd.get(Ot.CONFIG_PARAMS.STORAGE_COMPACTONSTART)&&await Ete(),setTimeout(()=>{wh()},50)):Ud.postMessage({type:Ot.ITC_EVENT_TYPES.RESTART}),Md}a(Nx,"restart");async function UA(e){let{service:t}=e;if(Ot.PROCESS_DESCRIPTORS_VALIDATE[t]===void 0)throw pte(new Error,Rte,Tte.BAD_REQUEST,void 0,void 0,!0);if(al=await Js.isServiceRegistered(Ot.HDB_PROC_DESCRIPTOR),!PA)return Ud.postMessage({type:Ot.ITC_EVENT_TYPES.RESTART,workerType:t}),Ud.ref(),new Promise(n=>{Ud.on("message",s=>{s.type==="restart-complete"&&(n(),Ud.unref())})});let r;switch(t){case ol.clustering:if(!vd.get(Ot.CONFIG_PARAMS.CLUSTERING_ENABLED)){r=yx;break}jn&&console.log("Restarting clustering"),js.notify("Restarting clustering"),await Ix();break;case ol.clustering_config:case ol["clustering config"]:if(!vd.get(Ot.CONFIG_PARAMS.CLUSTERING_ENABLED)){r=yx;break}jn&&console.log("Restarting clustering_config"),js.notify("Restarting clustering_config"),await Js.reloadClustering();break;case"custom_functions":case"custom functions":case ol.harperdb:case ol.http_workers:case ol.http:if(jn&&!al){r=`Restart ${t} is not available from the CLI when running in non-pm2 mode. Either call restart ${t} from the API or stop and start HarperDB.`;break}jn&&console.log("Restarting http_workers"),js.notify("Restarting http_workers"),jn?await Js.restart(Ot.HDB_PROC_DESCRIPTOR):await wh("http");break;default:r=`Unrecognized service: ${t}`;break}return r?(js.error(r),jn&&console.error(r),r):(t==="custom_functions"&&(t="Custom Functions"),`Restarting ${t}`)}a(UA,"restartService");async function Ate(){await Ix(),await Js.restart(Ot.HDB_PROC_DESCRIPTOR),await MA.async_set_timeout(2e3),vd.get(Ot.CONFIG_PARAMS.CLUSTERING_ENABLED)&&await LA(),jn&&(await Nh.closeConnection(),process.exit(0))}a(Ate,"restartPM2Mode");async function Ix(){if(!Ox.getConfigFromFile(Ot.CONFIG_PARAMS.CLUSTERING_ENABLED))return;if((await bx.getHDBProcessInfo()).clustering.length===0)js.trace("Clustering not running, restart will start clustering services"),await Ih.generateNatsConfig(!0),await Js.startClusteringProcesses(),await Js.startClusteringThreads(),await LA(),jn&&await Nh.closeConnection();else{await Ih.generateNatsConfig(!0),al?(js.trace("Restart clustering restarting PM2 managed Hub and Leaf servers"),await Js.restart(Ot.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await Js.restart(Ot.PROCESS_DESCRIPTORS.CLUSTERING_LEAF)):(await bx.getHDBProcessInfo()).clustering.forEach(s=>{js.trace("Restart clustering killing process pid",s.pid),process.kill(s.pid)}),await MA.async_set_timeout(3e3),await LA(),await Nh.updateLocalStreams(),jn&&await Nh.closeConnection(),js.trace("Restart clustering restarting ingest and reply service threads");let t=wh(Ot.LAUNCH_SERVICE_SCRIPTS.NATS_INGEST_SERVICE),r=wh(Ot.LAUNCH_SERVICE_SCRIPTS.NATS_REPLY_SERVICE);await t,await r}}a(Ix,"restartClustering");async function LA(){await Ih.removeNatsConfig(Ot.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await Ih.removeNatsConfig(Ot.PROCESS_DESCRIPTORS.CLUSTERING_LEAF)}a(LA,"removeNatsConfig")});var kx=I((yge,Hx)=>{"use strict";var bge=require("lodash"),rn=H(),{handleHDBError:Cx,hdb_errors:bte}=ce(),{HDB_ERROR_MSGS:yte,HTTP_STATUS_CODES:Ote}=bte,vA=X();Hx.exports={getRolePermissions:Ite};var Na=Object.create(null),Nte=a(e=>({key:e,perms:{}}),"perms_template_obj"),Mx=a((e=!1)=>({describe:e,tables:{}}),"schema_perms_template"),Ux=a((e=!1,t=!1,r=!1,n=!1)=>({[rn.PERMS_CRUD_ENUM.READ]:e,[rn.PERMS_CRUD_ENUM.INSERT]:t,[rn.PERMS_CRUD_ENUM.UPDATE]:r,[rn.PERMS_CRUD_ENUM.DELETE]:n}),"permissions_template"),xA=a((e=!1,t=!1,r=!1,n=!1,s=!1)=>({attribute_permissions:[],describe:e,...Ux(t,r,n,s)}),"table_perms_template"),Dx=a((e,t=Ux())=>({attribute_name:e,describe:Bx(t),[Bd]:t[Bd],[BA]:t[BA],[HA]:t[HA]}),"attr_perms_template"),Lx=a((e,t=!1)=>({attribute_name:e,describe:t,[Bd]:t}),"timestamp_attr_perms_template"),{READ:Bd,INSERT:BA,UPDATE:HA}=rn.PERMS_CRUD_ENUM,vx=Object.values(rn.PERMS_CRUD_ENUM),xx=[Bd,BA,HA];function Ite(e){let t;try{if(e.permission.super_user||e.permission.cluster_user)return e.permission;let r=Object.assign({},global.hdb_schema);delete r[rn.SYSTEM_SCHEMA_NAME],t=e.role;let n=JSON.stringify([e.__updatedtime__,r]);if(Na[t]&&Na[t].key===n)return Na[t].perms;let s=wte(e,r);return Na[t]?Na[t].key=n:Na[t]=Nte(n),Na[t].perms=s,s}catch(r){if(!e[rn.TIME_STAMP_NAMES_ENUM.UPDATED_TIME]||e[rn.TIME_STAMP_NAMES_ENUM.UPDATED_TIME]<rn.PERMS_UPDATE_RELEASE_TIMESTAMP){let n=`Role permissions for role '${t}' must be updated to align with new structure from the 2.2.0 release.`;throw vA.error(n),vA.debug(r),Cx(new Error,yte.OUTDATED_PERMS_TRANSLATION_ERROR,Ote.BAD_REQUEST)}else{let n=`There was an error while translating role permissions for role: ${t}.
13
+ ${r.stack}`;throw vA.error(n),Cx(new Error)}}}a(Ite,"getRolePermissions");function wte(e,t){let r=Object.create(null);r.super_user=!1;let n=e.permission;r[rn.SYSTEM_SCHEMA_NAME]=n[rn.SYSTEM_SCHEMA_NAME],r.structure_user=n.structure_user;let s=Array.isArray(e.permission.structure_user)||e.permission.structure_user===!0?e.permission.structure_user:[];return Object.keys(t).forEach(i=>{if(s===!0||s.indexOf(i)>-1){r[i]=Cte(t[i]);return}r[i]=Mx(),n[i]?(n[i].describe&&(r[i].describe=!0),Object.keys(t[i]).forEach(o=>{if(n[i].tables[o]){let c=n[i].tables[o],l=t[i][o],d=Dte(c,l);r[i].describe||vx.forEach(u=>{d[u]&&(r[i].describe=!0)}),r[i].tables[o]=d}else r[i].tables[o]=xA()})):Object.keys(t[i]).forEach(o=>{r[i].tables[o]=xA()})}),r}a(wte,"translateRolePermissions");function Cte(e){let t=Mx(!0);return Object.keys(e).forEach(r=>{t.tables[r]=xA(!0,!0,!0,!0,!0)}),t}a(Cte,"createStructureUserPermissions");function Dte(e,t){let{attribute_permissions:r}=e;if(r.length>0){let s=Object.assign({},e);s.attribute_permissions=[];let i=r.reduce((d,u)=>{let{attribute_name:f}=u,E=u;return rn.TIME_STAMP_NAMES.includes(f)&&(E=Lx(f,u[Bd])),d[f]=E,d},{}),o=t.primaryKey||t.hash_attribute,c=!!i[o],l=Dx(o);return t.attributes.forEach(({attribute:d})=>{if(i[d]){let u=i[d];u.describe=Bx(u),s.attribute_permissions.push(u),c||Lte(u,l)}else if(d!==o){let u;rn.TIME_STAMP_NAMES.includes(d)?u=Lx(d):u=Dx(d),s.attribute_permissions.push(u)}}),c||s.attribute_permissions.push(l),s.describe=Px(s),s}else return e.describe=Px(e),e}a(Dte,"getTableAttrPerms");function Px(e){return vx.filter(t=>e[t]).length>0}a(Px,"getSchemaTableDescribePerm");function Bx(e){return xx.filter(t=>e[t]).length>0}a(Bx,"getAttributeDescribePerm");function Lte(e,t){xx.forEach(r=>{e[r]&&!t[r]&&(t[r]=!0,t.describe=!0)})}a(Lte,"checkForHashPerms")});var Fx={};Ze(Fx,{Headers:()=>Li,appendHeader:()=>kA,mergeHeaders:()=>FA});function kA(e,t,r,n){if(e.append)e.append(t,r,n);else if(e.set){let s=e.get(t);if(s)if(n)r=(typeof s=="string"?s:s.join(", "))+", "+r;else if(typeof s=="string")r=[s,r];else{s.push(r);return}return e.set(t,r)}else e[t]=(e[t]?e[t]+", ":"")+r}function FA(e,t){(typeof e.set!="function"||typeof e.has!="function")&&(e=new Li(e));for(let[r,n]of t)e.has(r)?r.toLowerCase()==="set-cookie"&&e.append?.(r,n,!0):e.set(r,n);return e}var Li,Hd=Oe(()=>{Li=class extends Map{static{a(this,"Headers")}constructor(t){if(t)if(t[Symbol.iterator])super(t);else{super();for(let r in t)this.set(r,t[r])}else super()}set(t,r){return typeof t!="string"&&(t=""+t),typeof r!="string"&&(r=""+r),super.set(t.toLowerCase(),[t,r])}get(t){return typeof t!="string"&&(t=""+t),super.get(t.toLowerCase())?.[1]}has(t){return typeof t!="string"&&(t=""+t),super.has(t.toLowerCase())}setIfNone(t,r){typeof t!="string"&&(t=""+t),typeof r!="string"&&(r=""+r);let n=t.toLowerCase();if(!super.has(n))return super.set(n,[t,r])}append(t,r,n){typeof t!="string"&&(t=""+t),typeof r!="string"&&(r=""+r);let s=t.toLowerCase(),i=super.get(s);if(i){let o=i[1];if(n)r=(typeof o=="string"?o:o.join(", "))+", "+r;else if(typeof o=="string")r=[o,r];else{o.push(r);return}}return super.set(s,[t,r])}[Symbol.iterator](){return super.values()[Symbol.iterator]()}};a(kA,"appendHeader");a(FA,"mergeHeaders")});var kd={};Ze(kd,{authentication:()=>Wx,bypassAuth:()=>Hte,login:()=>Fte,logout:()=>Gte,start:()=>kte});function Hte(){Kx=!0}async function Wx(e,t){let r=e.headers.asObject,n=r.authorization,s=r.cookie,i=r.origin,o=[];try{if(i){let _=e.isOperationsServer?vte?Ute:[]:Mte?Pte:[];if(_.includes(i)||_.includes("*")){if(e.method==="OPTIONS"){let h=new Li([["Access-Control-Allow-Methods","POST, GET, PUT, DELETE, PATCH, OPTIONS"],["Access-Control-Allow-Headers","Accept, Content-Type, Authorization"],["Access-Control-Allow-Origin",i]]);return Ch&&h.set("Access-Control-Allow-Credentials","true"),{status:200,headers:h}}o.push("Access-Control-Allow-Origin",i),Ch&&o.push("Access-Control-Allow-Credentials","true")}}let l,d;if(Ch){i||(i=r.host);let _=(i?i.replace(/^https?:\/\//,"").replace(/\W/,"_")+"-":"")+"hdb-session=",h=s?.split(/;\s+/)||[];for(let p of h)if(p.startsWith(_)){let S=p.indexOf(";");l=p.slice(_.length,S===-1?p.length:S),d=await Gx.get(l);break}e.session=d||(d={})}let u=a((_,h,p)=>{let S=new cl.AuthAuditLog(_,h,_r.AUTH_AUDIT_TYPES.AUTHENTICATION,r["x-forwarded-for"]??e.ip,e.method,e.pathname);S.auth_strategy=p,l&&(S.session_id=l),r.referer&&(S.referer=r.referer),r.origin&&(S.origin=r.origin),h===_r.AUTH_AUDIT_STATUS.SUCCESS?GA.notify(S):GA.error(S)},"authAuditLog");if(!e.authorized&&e.mtlsConfig&&e.peerCertificate.subject&&e?._nodeRequest?.socket?.authorizationError&&GA.error("Authorization error:",e._nodeRequest.socket.authorizationError),e.mtlsConfig&&e.authorized&&e.peerCertificate.subject){let _=e.mtlsConfig.user;_!==null?((_===void 0||_==="Common Name"||_==="CN")&&(_=e.peerCertificate.subject.CN),e.user=await st.getUser(_,null,null),u(_,_r.AUTH_AUDIT_STATUS.SUCCESS,"mTLS")):(0,cl.debug)("HTTPS/WSS mTLS authorized connection (mTLS did not authorize a user)","from",e.ip)}let f;if(!e.user)if(n){if(f=Ia.get(n),!f){let _=n.indexOf(" "),h=n.slice(0,_),p=n.slice(_+1),S,g;try{switch(h){case"Basic":let T=atob(p),A=T.indexOf(":");S=T.slice(0,A),g=T.slice(A+1),f=S||g?await st.getUser(S,g,e):null;break;case"Bearer":try{f=await(0,Dh.validateOperationToken)(p)}catch(N){if(N.message==="invalid token")try{return await(0,Dh.validateRefreshToken)(p),c({status:-1})}catch{throw N}}break}}catch(T){return Bte&&(Ia.get(p)||(Ia.set(p,p),u(S,_r.AUTH_AUDIT_STATUS.FAILURE,h))),c({status:401,body:wa({error:T.message},e)})}Ia.set(n,f),xte&&u(f.username,_r.AUTH_AUDIT_STATUS.SUCCESS,h)}e.user=f}else d?.user?e.user=await st.getUser(d.user,null,e):(Kx&&(e.ip?.includes("127.0.0.")||e.ip=="::1")||e?._nodeRequest?.socket?.server?._pipeName&&e.ip===void 0)&&(e.user=await(0,Vx.getSuperUser)());Ch&&(e.session.update=function(_){if(!l){l=(0,$x.v4)();let p=`${(i?i.replace(/^https?:\/\//,"").replace(/\W/,"_")+"-":"")+"hdb-session="}${l}; Path=/; Expires=Tue, 01 Oct 8307 19:33:20 GMT; HttpOnly${e.protocol==="https"?"; SameSite=None; Secure":""}`;o?o.push("Set-Cookie",p):E?.headers?.set&&E.headers.set("Set-Cookie",p)}return e.protocol==="https"&&(o?(i&&o.push("Access-Control-Expose-Headers","X-Hdb-Session"),o.push("X-Hdb-Session","Secure")):E?.headers?.set&&(i&&E.headers.set("Access-Control-Expose-Headers","X-Hdb-Session"),E.headers.set("X-Hdb-Session","Secure"))),_.id=l,Gx.put(_)},e.login=async function(_,h){e.user=await st.getUser(_,h,e),e.session.update({user:e.user.username})},(f&&!d||d?.user?.username!==f?.username)&&r["user-agent"]?.startsWith("Mozilla")&&e.session.update({user:e.user.username}));let E=await t(e);return E&&(E.status===401&&(r["user-agent"]?.startsWith("Mozilla")&&r.accept?.startsWith("text/html")&&ho.loginPath?(E.status=302,E.headers.set("Location",ho.loginPath(e))):E.headers.set("WWW-Authenticate","Basic")),c(E))}catch(l){throw c(l)}function c(l){let d=o.length;if(d>0){let u=l.headers;u||(l.headers=u=new Li);for(let f=0;f<d;){let E=o[f++];u.set(E,o[f++])}}return o=null,l}a(c,"applyResponseHeaders")}function kte({server:e,port:t}){e.http(Wx,{port:t||"all"}),qx||(qx=!0,setInterval(()=>{Ia=new Map},Jn.get(_r.CONFIG_PARAMS.AUTHENTICATION_CACHETTL)).unref(),Yx.user.addListener(()=>{Ia=new Map}))}async function Fte(e){if(!e.baseRequest?.login)throw new Error("No session for login");return e.baseResponse.headers.set=(t,r)=>{e.fastifyResponse.header(t,r)},await e.baseRequest.login(e.username,e.password),"Login successful"}async function Gte(e){if(!e.baseRequest.session)throw new Error("No session for logout");return await e.baseRequest.session.update({user:null}),"Logout successful"}var Vx,Dh,$x,Jn,_r,cl,Yx,GA,Pte,Mte,Ute,vte,Gx,Ch,Kx,xte,Bte,Ia,qx,Lh=Oe(()=>{Vx=U($n());Lr();nd();Dh=U(Xu());Ne();$x=require("uuid"),Jn=U(ie()),_r=U(H()),cl=U(X()),Yx=U(Lu());Hd();ll();GA=(0,cl.loggerWithTag)("auth-event");Jn.initSync();Pte=Jn.get(_r.CONFIG_PARAMS.HTTP_CORSACCESSLIST),Mte=Jn.get(_r.CONFIG_PARAMS.HTTP_CORS),Ute=Jn.get(_r.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_CORSACCESSLIST),vte=Jn.get(_r.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_CORS),Gx=dt({table:"hdb_session",database:"system",attributes:[{name:"id",isPrimaryKey:!0},{name:"user"}]}),Ch=Jn.get(_r.CONFIG_PARAMS.AUTHENTICATION_ENABLESESSIONS)??!0,Kx=process.env.AUTHENTICATION_AUTHORIZELOCAL??Jn.get(_r.CONFIG_PARAMS.AUTHENTICATION_AUTHORIZELOCAL)??process.env.DEV_MODE,xte=Jn.get(_r.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)??!1,Bte=Jn.get(_r.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGFAILED)??!1,Ia=new Map;st.onInvalidatedUser(()=>{Ia=new Map});a(Hte,"bypassAuth");a(Wx,"authentication");a(kte,"start");a(Fte,"login");a(Gte,"logout")});var eB=I((Mge,Zx)=>{"use strict";var ge=require("joi"),Qx=require("fs-extra"),zx=require("path"),Cn=mt(),jx=ie(),Jx=H(),Xx=X(),{hdb_errors:qte}=ce(),{HDB_ERROR_MSGS:Rr}=qte,Pi=/^[a-zA-Z0-9-_]+$/,Vte=/^[a-zA-Z0-9-_]+$/;Zx.exports={getDropCustomFunctionValidator:Yte,setCustomFunctionValidator:Kte,addComponentValidator:jte,dropCustomFunctionProjectValidator:Jte,packageComponentValidator:Xte,deployComponentValidator:Zte,setComponentFileValidator:Wte,getComponentFileValidator:zte,dropComponentFileValidator:Qte,addSSHKeyValidator:ere,updateSSHKeyValidator:tre,deleteSSHKeyValidator:rre,setSSHKnownHostsValidator:nre};function Ph(e,t,r){try{let n=jx.get(Jx.CONFIG_PARAMS.COMPONENTSROOT),s=zx.join(n,t);return Qx.existsSync(s)?e?t:r.message(Rr.PROJECT_EXISTS):e?r.message(Rr.NO_PROJECT):t}catch(n){return Xx.error(n),r.message(Rr.VALIDATION_ERR)}}a(Ph,"checkProjectExists");function Fd(e,t){return e.includes("..")?t.message("Invalid file path"):e}a(Fd,"checkFilePath");function $te(e,t,r,n){try{let s=jx.get(Jx.CONFIG_PARAMS.COMPONENTSROOT),i=zx.join(s,e,t,r+".js");return Qx.existsSync(i)?r:n.message(Rr.NO_FILE)}catch(s){return Xx.error(s),n.message(Rr.VALIDATION_ERR)}}a($te,"checkFileExists");function Yte(e){let t=ge.object({project:ge.string().pattern(Pi).custom(Ph.bind(null,!0)).required().messages({"string.pattern.base":Rr.BAD_PROJECT_NAME}),type:ge.string().valid("helpers","routes").required(),file:ge.string().pattern(Pi).custom($te.bind(null,e.project,e.type)).custom(Fd).required().messages({"string.pattern.base":Rr.BAD_FILE_NAME})});return Cn.validateBySchema(e,t)}a(Yte,"getDropCustomFunctionValidator");function Kte(e){let t=ge.object({project:ge.string().pattern(Pi).custom(Ph.bind(null,!0)).required().messages({"string.pattern.base":Rr.BAD_PROJECT_NAME}),type:ge.string().valid("helpers","routes").required(),file:ge.string().custom(Fd).required(),function_content:ge.string().required()});return Cn.validateBySchema(e,t)}a(Kte,"setCustomFunctionValidator");function Wte(e){let t=ge.object({project:ge.string().pattern(Pi).required().messages({"string.pattern.base":Rr.BAD_PROJECT_NAME}),file:ge.string().custom(Fd).required(),payload:ge.string().allow("").optional(),encoding:ge.string().valid("utf8","ASCII","binary","hex","base64","utf16le","latin1","ucs2").optional()});return Cn.validateBySchema(e,t)}a(Wte,"setComponentFileValidator");function Qte(e){let t=ge.object({project:ge.string().pattern(Pi).required().messages({"string.pattern.base":Rr.BAD_PROJECT_NAME}),file:ge.string().custom(Fd).optional()});return Cn.validateBySchema(e,t)}a(Qte,"dropComponentFileValidator");function zte(e){let t=ge.object({project:ge.string().required(),file:ge.string().custom(Fd).required(),encoding:ge.string().valid("utf8","ASCII","binary","hex","base64","utf16le","latin1","ucs2").optional()});return Cn.validateBySchema(e,t)}a(zte,"getComponentFileValidator");function jte(e){let t=ge.object({project:ge.string().pattern(Pi).custom(Ph.bind(null,!1)).required().messages({"string.pattern.base":Rr.BAD_PROJECT_NAME})});return Cn.validateBySchema(e,t)}a(jte,"addComponentValidator");function Jte(e){let t=ge.object({project:ge.string().pattern(Pi).custom(Ph.bind(null,!0)).required().messages({"string.pattern.base":Rr.BAD_PROJECT_NAME})});return Cn.validateBySchema(e,t)}a(Jte,"dropCustomFunctionProjectValidator");function Xte(e){let t=ge.object({project:ge.string().pattern(Pi).required().messages({"string.pattern.base":Rr.BAD_PROJECT_NAME}),skip_node_modules:ge.boolean()});return Cn.validateBySchema(e,t)}a(Xte,"packageComponentValidator");function Zte(e){let t=ge.object({project:ge.string().pattern(Pi).required().messages({"string.pattern.base":Rr.BAD_PROJECT_NAME}),payload:ge.string().optional().messages({"string.pattern.base":Rr.BAD_PACKAGE}),package:ge.string().optional(),restart:ge.boolean().optional()});return Cn.validateBySchema(e,t)}a(Zte,"deployComponentValidator");function ere(e){let t=ge.object({name:ge.string().pattern(Vte).required().messages({"string.pattern.base":Rr.BAD_SSH_KEY_NAME}),key:ge.string().required(),host:ge.string().required(),hostname:ge.string().required(),known_hosts:ge.string().optional()});return Cn.validateBySchema(e,t)}a(ere,"addSSHKeyValidator");function tre(e){let t=ge.object({name:ge.string().required(),key:ge.string().required()});return Cn.validateBySchema(e,t)}a(tre,"updateSSHKeyValidator");function rre(e){let t=ge.object({name:ge.string().required()});return Cn.validateBySchema(e,t)}a(rre,"deleteSSHKeyValidator");function nre(e){let t=ge.object({known_hosts:ge.string().required()});return Cn.validateBySchema(e,t)}a(nre,"setSSHKnownHostsValidator")});var Bh=I((vge,oB)=>{"use strict";var Mh=require("joi"),Ca=require("path"),vh=require("fs-extra"),{exec:sre}=require("child_process"),ire=require("util"),tB=ire.promisify(sre),fl=H(),{handleHDBError:ul,hdb_errors:ore}=ce(),{HTTP_STATUS_CODES:dl}=ore,El=ie(),are=mt(),_l=X();El.initSync();var qA=El.get(fl.CONFIG_PARAMS.COMPONENTSROOT),rB="npm install --omit=dev --json",cre=`${rB} --dry-run`,lre=El.get(fl.CONFIG_PARAMS.ROOTPATH),Uh=Ca.join(lre,"ssh");oB.exports={installModules:_re,auditModules:Ere,installAllRootModules:ure,uninstallRootModule:dre,linkHarperdb:fre};async function ure(e=!1){await xh();let t=!1,r=process.env;vh.pathExistsSync(Uh)&&vh.readdirSync(Uh).forEach(n=>{n.includes(".key")&&!t&&(r=Object.assign({GIT_SSH_COMMAND:"ssh -F "+Ca.join(Uh,"config")+" -o UserKnownHostsFile="+Ca.join(Uh,"known_hosts")},process.env),t=!0)}),await Gd(e?"npm install --ignore-scripts":"npm install",El.get(fl.CONFIG_PARAMS.ROOTPATH),r)}a(ure,"installAllRootModules");async function dre(e){await Gd(`npm uninstall ${e}`,El.get(fl.CONFIG_PARAMS.ROOTPATH))}a(dre,"uninstallRootModule");async function fre(){await xh(),await Gd(`npm link ${fl.PACKAGE_ROOT}`,El.get(fl.CONFIG_PARAMS.ROOTPATH))}a(fre,"linkHarperdb");async function Gd(e,t=void 0,r=process.env){let n,s;try{({stdout:n,stderr:s}=await tB(e,{cwd:t,env:r}))}catch(i){throw new Error(i.stderr.replace(`
14
+ `,""))}return s&&!s.includes("Debugger listening")&&_l.error("Error running NPM command:",e,s),_l.trace(n,s),n?.replace(`
15
+ `,"")}a(Gd,"runCommand");async function _re(e){_l.info(`starting installModules for request: ${e}`);let t=iB(e);if(t)throw ul(t,t.message,dl.BAD_REQUEST);let{projects:r,dry_run:n}=e,s=n===!0?cre:rB;await xh(),await sB(r);let i={};for(let o=0,c=r.length;o<c;o++){let l=r[o];i[l]={npm_output:null,npm_error:null};let d=Ca.join(qA,l),u,f=null;try{let{stdout:E,stderr:_}=await tB(s,{cwd:d});u=E?E.replace(`
16
+ `,""):null,f=_?_.replace(`
17
+ `,""):null}catch(E){E.stderr?i[l].npm_error=nB(E.stderr):i[l].npm_error=E.message;continue}try{i[l].npm_output=JSON.parse(u)}catch{i[l].npm_output=u}try{i[l].npm_error=JSON.parse(f)}catch{i[l].npm_error=f}}return _l.info(`finished installModules with response ${i}`),i}a(_re,"installModules");function nB(e){let t='"error": {',r=e.indexOf('"error": {'),n=e.indexOf(`}
18
+ `);return r>-1&&n>-1?JSON.parse(e.substring(r+t.length-1,n+1)):e}a(nB,"parseNPMStdErr");async function Ere(e){_l.info(`starting auditModules for request: ${e}`);let t=iB(e);if(t)throw ul(t,t.message,dl.BAD_REQUEST);let{projects:r}=e;await xh(),await sB(r);let n={};for(let s=0,i=r.length;s<i;s++){let o=r[s],c=Ca.join(qA,o);n[o]={npm_output:null,npm_error:null};try{let l=await Gd("npm audit --json",c);n[o].npm_output=JSON.parse(l)}catch(l){n[o].npm_error=nB(l.stderr)}}return _l.info(`finished auditModules with response ${n}`),n}a(Ere,"auditModules");async function xh(){try{return await Gd("npm -v"),!0}catch{throw ul(new Error,"Unable to install project dependencies: npm is not installed on this instance of HarperDB.",dl.BAD_REQUEST,void 0,void 0,!0)}}a(xh,"checkNPMInstalled");async function sB(e){if(!Array.isArray(e)||e.length===0)throw ul(new Error,"projects argument must be an array with at least 1 element",dl.BAD_REQUEST,void 0,void 0,!0);let t=[],r=[];for(let n=0,s=e.length;n<s;n++){let i=e[n],o=Ca.join(qA,i.toString());if(!await vh.pathExists(o)){t.push(i);continue}let l=Ca.join(o,"package.json");await vh.pathExists(l)||r.push(i)}if(t.length>0)throw ul(new Error,`Unable to install project dependencies: custom function projects '${t.join(",")}' does not exist.`,dl.BAD_REQUEST,void 0,void 0,!0);if(r.length>0)throw ul(new Error,`Unable to install project dependencies: custom function projects '${r.join(",")}' do not have a package.json file.`,dl.BAD_REQUEST,void 0,void 0,!0)}a(sB,"checkProjectPaths");function iB(e){let t=Mh.object({projects:Mh.array().min(1).items(Mh.string()).required(),dry_run:Mh.boolean().default(!1)});return are.validateBySchema(e,t)}a(iB,"modulesValidator")});var $A=I((Bge,dB)=>{"use strict";var hl=require("fs-extra"),VA=require("path"),Hh=X(),aB=re(),kh=H(),uB=ie(),hre=dr();dB.exports=mre;async function mre(){let e=pre(),t=uB.get(kh.CONFIG_PARAMS.ROOTPATH),r=VA.join(t,"package.json"),n={dependencies:{harperdb:"file:"+kh.PACKAGE_ROOT}},s=VA.join(t,"node_modules");hl.ensureDirSync(s);let i,o=!0,c=!1;try{i=hl.readJsonSync(r)}catch(l){if(aB.isEmptyOrZeroLength(e))return;if(l.code!==kh.NODE_ERROR_CODES.ENOENT)throw l;o=!1}if(!aB.isEmptyOrZeroLength(e)){for(let{name:l,package:d}of e){let u=cB(d);n.dependencies[l]=u+d}if(!o){Hh.notify("Installing components"),await lB(r,n,null);return}for(let{name:l,package:d}of e){let u=i.dependencies[l],f=cB(d);if(u===void 0||u!==f+d){c=!0;break}}}for(let l in i.dependencies)n.dependencies[l]===void 0&&(Hh.notify("Removing component",l),c=!0);c&&(Hh.notify("Updating components."),await lB(r,n,i))}a(mre,"installComponents");function pre(){let e=hre.getConfiguration(),t=[];for(let r in e)e[r]?.package&&t.push(Object.assign(e[r],{name:r}));return t}a(pre,"getComponentsConfig");function cB(e){return e.includes(":")?"":e.startsWith("@")||!e.startsWith("@")&&!e.includes("/")?"npm:":VA.extname(e)||hl.existsSync(e)?"file:":"github:"}a(cB,"getPkgPrefix");async function lB(e,t,r){Hh.trace("npm installing components package.json",t),hl.writeFileSync(e,JSON.stringify(t,null," "));try{await Bh().installAllRootModules(uB.get(kh.CONFIG_PARAMS.IGNORE_SCRIPTS)===!0)}catch(n){throw r?hl.writeFileSync(e,JSON.stringify(r,null," ")):hl.unlinkSync(e),n}}a(lB,"installPackages")});var WA=I(hB=>{"use strict";var Se=require("fs-extra"),YA=require("fast-glob"),Re=require("path"),_B=require("tar-fs"),Sre=require("gunzip-maybe"),kge=require("uuid").v4,KA=require("normalize-path"),nn=eB(),Mt=X(),lt=H(),$t=ie(),qd=dr(),Tre=re(),{PACKAGE_ROOT:gre}=H(),{handleHDBError:Ut,hdb_errors:Rre}=ce(),{basename:Are}=require("path"),bre=$A(),EB=ie(),yre=H(),{Readable:Ore}=require("stream"),{isMainThread:Nre}=require("worker_threads"),{HDB_ERROR_MSGS:Da,HTTP_STATUS_CODES:vt}=Rre,Ire=at(),wre=Re.join(gre,"application-template"),fB=Re.join($t.get(lt.HDB_SETTINGS_NAMES.HDB_ROOT_KEY),"tmp"),Cre=$t.get(lt.CONFIG_PARAMS.ROOTPATH),yo=Re.join(Cre,"ssh"),Mi=Re.join(yo,"known_hosts");function Dre(){Mt.trace("getting custom api status");let e={};try{e={port:$t.get(lt.CONFIG_PARAMS.HTTP_PORT),directory:$t.get(lt.CONFIG_PARAMS.COMPONENTSROOT),is_enabled:!0}}catch(t){throw Ut(new Error,Da.FUNCTION_STATUS,vt.INTERNAL_SERVER_ERROR,Mt.ERR,t)}return e}a(Dre,"customFunctionsStatus");function Lre(){Mt.trace("getting custom api endpoints");let e={},t=$t.get(lt.CONFIG_PARAMS.COMPONENTSROOT);try{YA.sync(KA(`${t}/*`),{onlyDirectories:!0}).forEach(n=>{let s=n.split("/").pop();e[s]={routes:YA.sync(KA(`${n}/routes/*.js`)).map(i=>i.split("/").pop().split(".js")[0]),helpers:YA.sync(KA(`${n}/helpers/*.js`)).map(i=>i.split("/").pop().split(".js")[0])}})}catch(r){throw Ut(new Error,Da.GET_FUNCTIONS,vt.INTERNAL_SERVER_ERROR,Mt.ERR,r)}return e}a(Lre,"getCustomFunctions");function Pre(e){e.project&&(e.project=Re.parse(e.project).name),e.file&&(e.file=Re.parse(e.file).name);let t=nn.getDropCustomFunctionValidator(e);if(t)throw Ut(t,t.message,vt.BAD_REQUEST);Mt.trace("getting custom api endpoint file content");let r=$t.get(lt.CONFIG_PARAMS.COMPONENTSROOT),{project:n,type:s,file:i}=e,o=Re.join(r,n,s,i+".js");try{return Se.readFileSync(o,{encoding:"utf8"})}catch(c){throw Ut(new Error,Da.GET_FUNCTION,vt.INTERNAL_SERVER_ERROR,Mt.ERR,c)}}a(Pre,"getCustomFunction");function Mre(e){e.project&&(e.project=Re.parse(e.project).name),e.file&&(e.file=Re.parse(e.file).name);let t=nn.setCustomFunctionValidator(e);if(t)throw Ut(t,t.message,vt.BAD_REQUEST);Mt.trace("setting custom function file content");let r=$t.get(lt.CONFIG_PARAMS.COMPONENTSROOT),{project:n,type:s,file:i,function_content:o}=e;try{return Se.outputFileSync(Re.join(r,n,s,i+".js"),o),`Successfully updated custom function: ${i}.js`}catch(c){throw Ut(new Error,Da.SET_FUNCTION,vt.INTERNAL_SERVER_ERROR,Mt.ERR,c)}}a(Mre,"setCustomFunction");function Ure(e){e.project&&(e.project=Re.parse(e.project).name),e.file&&(e.file=Re.parse(e.file).name);let t=nn.getDropCustomFunctionValidator(e);if(t)throw Ut(t,t.message,vt.BAD_REQUEST);Mt.trace("dropping custom function file");let r=$t.get(lt.CONFIG_PARAMS.COMPONENTSROOT),{project:n,type:s,file:i}=e;try{return Se.unlinkSync(Re.join(r,n,s,i+".js")),`Successfully deleted custom function: ${i}.js`}catch(o){throw Ut(new Error,Da.DROP_FUNCTION,vt.INTERNAL_SERVER_ERROR,Mt.ERR,o)}}a(Ure,"dropCustomFunction");function vre(e){e.project&&(e.project=Re.parse(e.project).name);let t=nn.addComponentValidator(e);if(t)throw Ut(t,t.message,vt.BAD_REQUEST);Mt.trace("adding component");let r=$t.get(lt.CONFIG_PARAMS.COMPONENTSROOT),{project:n}=e;try{let s=Re.join(r,n);return Se.mkdirSync(s,{recursive:!0}),Se.copySync(wre,s),`Successfully added project: ${n}`}catch(s){throw Ut(new Error,Da.ADD_FUNCTION,vt.INTERNAL_SERVER_ERROR,Mt.ERR,s)}}a(vre,"addComponent");function xre(e){e.project&&(e.project=Re.parse(e.project).name);let t=nn.dropCustomFunctionProjectValidator(e);if(t)throw Ut(t,t.message,vt.BAD_REQUEST);Mt.trace("dropping custom function project");let r=$t.get(lt.CONFIG_PARAMS.COMPONENTSROOT),{project:n}=e,s=$t.get(lt.CONFIG_PARAMS.APPS);if(!Tre.isEmptyOrZeroLength(s)){let i=!1;for(let[o,c]of s.entries())if(c.name===n){s.splice(o,1),i=!0;break}if(i)return qd.updateConfigValue(lt.CONFIG_PARAMS.APPS,s),`Successfully deleted project: ${n}`}try{let i=Re.join(r,n);return Se.rmSync(i,{recursive:!0}),`Successfully deleted project: ${n}`}catch(i){throw Ut(new Error,Da.DROP_FUNCTION_PROJECT,vt.INTERNAL_SERVER_ERROR,Mt.ERR,i)}}a(xre,"dropCustomFunctionProject");async function Bre(e){e.project&&(e.project=Re.parse(e.project).name);let t=nn.packageComponentValidator(e);if(t)throw Ut(t,t.message,vt.BAD_REQUEST);let r=$t.get(lt.CONFIG_PARAMS.COMPONENTSROOT),{project:n}=e;Mt.trace("packaging component",n);let s;try{s=await Se.realpath(Re.join(r,n))}catch(l){if(l.code!==lt.NODE_ERROR_CODES.ENOENT)throw l;try{s=await Se.realpath(Re.join($t.get(lt.CONFIG_PARAMS.ROOTPATH),"node_modules",n))}catch(d){if(d.code===lt.NODE_ERROR_CODES.ENOENT)throw new Error(`Unable to locate project '${n}'`)}}await Se.ensureDir(fB);let i=Re.join(fB,`${n}.tar`),o={};(e.skip_node_modules===!0||e.skip_node_modules==="true")&&(o={ignore:l=>l.includes(Re.join(s,"node_modules"))}),_B.pack(s,o).pipe(Se.createWriteStream(i,{overwrite:!0})),await new Promise(l=>setTimeout(l,2e3));let c=Se.readFileSync(i,{encoding:"base64"});return await Se.remove(i),{project:n,payload:c}}a(Bre,"packageComponent");async function Hre(e){e.project&&(e.project=Re.parse(e.project).name);let t=nn.deployComponentValidator(e);if(t)throw Ut(t,t.message,vt.BAD_REQUEST);let r=$t.get(lt.CONFIG_PARAMS.COMPONENTSROOT),{project:n,payload:s,package:i}=e;if(Mt.trace("deploying component",n),!s&&!i)throw new Error("'payload' or 'package' must be provided");let o;if(s){o=Re.join(r,n),i="file:"+o,await Se.emptyDir(o);let E=Ore.from(Buffer.from(s,"base64"));await new Promise((h,p)=>{E.pipe(Sre()).pipe(_B.extract(o,{finish:h})).on("error",p)});let _=await Se.readdir(o);_.length===1&&_[0]==="package"&&(await Se.copy(Re.join(o,"package"),o),await Se.remove(Re.join(o,"package")))}if(await qd.addConfig(n,{package:i}),!s){await bre();let E=EB.get(yre.CONFIG_PARAMS.ROOTPATH);o=Re.join(E,"node_modules",n)}if(Nre)return;let c=new Map;c.isWorker=!0;let l=(Gh(),ae(Fh)),d;l.setErrorReporter(E=>d=E);let u=Are(o),f=l.component_errors.get(u);try{await l.loadComponent(o,c)}finally{l.component_errors.set(u,f)}if(d)throw d;return Mt.info("Installed component"),e.restart===!0?(Ire.restartWorkers("http"),`Successfully deployed: ${n}, restarting HarperDB`):`Successfully deployed: ${n}`}a(Hre,"deployComponent");async function kre(){let e=qd.getConfiguration(),t=[];for(let o in e)if(e[o]?.package){if(e[o].package.startsWith("file:"))continue;t.push(Object.assign({},e[o],{name:o}))}let r=a(async(o,c)=>{try{let l=await Se.readdir(o,{withFileTypes:!0});for(let d of l){let u=d.name;if(u.startsWith(".")||u==="node_modules")continue;let f=Re.join(o,u);if(d.isDirectory()||d.isSymbolicLink()){let E={name:u,entries:[]};c.entries.push(E),await r(f,E)}else{let E=await Se.stat(f),_={name:Re.basename(u),mtime:E.mtime,size:E.size};c.entries.push(_)}}return c}catch(l){return Mt.warn("Error loading package",l),{error:l.toString(),entries:[]}}},"walk_dir"),n=await r($t.get(lt.CONFIG_PARAMS.COMPONENTSROOT),{name:$t.get(lt.CONFIG_PARAMS.COMPONENTSROOT).split(Re.sep).slice(-1).pop(),entries:t});for(let o of n.entries)if(o.package){let c=await r(Re.join($t.get(lt.CONFIG_PARAMS.ROOTPATH),"node_modules",o.name),{name:o.name,entries:[]});Object.assign(o,c)}let i=(Gh(),ae(Fh)).component_errors;for(let o of t){let c=i.get(o.name);c?o.error=i.get(o.name):c===void 0&&(o.error="The component has not been loaded yet (may need a restart)")}return n}a(kre,"getComponents");async function Fre(e){let t=nn.getComponentFileValidator(e);if(t)throw Ut(t,t.message,vt.BAD_REQUEST);let n=qd.getConfigObj()[e.project]||e.project==="harperdb"?Re.join(EB.get(lt.CONFIG_PARAMS.ROOTPATH),"node_modules"):$t.get(lt.CONFIG_PARAMS.COMPONENTSROOT),s=e.encoding?{encoding:e.encoding}:{encoding:"utf8"};try{let i=await Se.stat(Re.join(n,e.project,e.file));return{message:await Se.readFile(Re.join(n,e.project,e.file),s),size:i.size,birthtime:i.birthtime,mtime:i.mtime}}catch(i){throw i.code===lt.NODE_ERROR_CODES.ENOENT?new Error(`Component file not found '${Re.join(e.project,e.file)}'`):i}}a(Fre,"getComponentFile");async function Gre(e){let t=nn.setComponentFileValidator(e);if(t)throw Ut(t,t.message,vt.BAD_REQUEST);let r=e.encoding?{encoding:e.encoding}:{encoding:"utf8"},n=Re.join($t.get(lt.CONFIG_PARAMS.COMPONENTSROOT),e.project,e.file);return e.payload!==void 0?(await Se.ensureFile(n),await Se.outputFile(n,e.payload,r)):await Se.ensureDir(n),"Successfully set component: "+e.file}a(Gre,"setComponentFile");async function qre(e){let t=nn.dropComponentFileValidator(e);if(t)throw Ut(t,t.message,vt.BAD_REQUEST);let r=e.file?Re.join(e.project,e.file):e.project,n=Re.join($t.get(lt.CONFIG_PARAMS.COMPONENTSROOT),r);return await Se.pathExists(n)&&await Se.remove(n),qd.deleteConfigFromFile([e.project]),"Successfully dropped: "+r}a(qre,"dropComponent");async function Vre(e){let t=nn.addSSHKeyValidator(e);if(t)throw Ut(t,t.message,vt.BAD_REQUEST);let{name:r,key:n,host:s,hostname:i,known_hosts:o}=e;Mt.trace("adding ssh key",r);let c=Re.join(yo,r+".key"),l=Re.join(yo,"config");if(await Se.pathExists(c))throw new Error("Key already exists. Use update_ssh_key or delete_ssh_key and then add_ssh_key");await Se.outputFile(c,n),await Se.chmod(c,"0600");let d=`#${r}
19
+ Host ${s}
20
+ HostName ${i}
21
+ User git
22
+ IdentityFile ${c}
23
+ IdentitiesOnly yes`;await Se.pathExists(l)?await Se.appendFile(l,`
24
+ `+d):await Se.outputFile(l,d);let u="";if(await Se.pathExists(Mi)||(await Se.writeFile(Mi,""),await Se.chmod(Mi,"0600")),i=="github.com"&&!(await Se.readFile(Mi,"utf8")).includes("github.com"))try{let p=(await(await fetch("https://api.github.com/meta")).json()).ssh_keys;for(var f of p)Se.appendFile(Mi,"github.com "+f+`
25
+ `)}catch{u=". Unable to get known hosts from github.com. Set your known hosts manually using set_ssh_known_hosts."}return o&&await Se.appendFile(Mi,o),`Added ssh key: ${r}${u}`}a(Vre,"addSSHKey");async function $re(e){let t=nn.updateSSHKeyValidator(e);if(t)throw Ut(t,t.message,vt.BAD_REQUEST);let{name:r,key:n}=e;Mt.trace("updating ssh key",r);let s=Re.join(yo,r+".key");if(!await Se.pathExists(s))throw new Error("Key does not exist. Use add_ssh_key");return await Se.outputFile(s,n),`Updated ssh key: ${r}`}a($re,"updateSSHKey");async function Yre(e){let t=nn.deleteSSHKeyValidator(e);if(t)throw Ut(t,t.message,vt.BAD_REQUEST);let{name:r}=e;Mt.trace("deleting ssh key",r);let n=Re.join(yo,r+".key"),s=Re.join(yo,"config");if(!await Se.pathExists(n))throw new Error("Key does not exist");let i=await Se.readFile(s,"utf8"),o=new RegExp(`#${r}[\\S\\s]*?IdentitiesOnly yes`,"g");return i=i.replace(o,""),await Se.outputFile(s,i),Se.removeSync(n),`Deleted ssh key: ${r}`}a(Yre,"deleteSSHKey");async function Kre(e){let t=[];return await Se.pathExists(yo)&&(await Se.readdir(yo)).forEach(r=>{r!="known_hosts"&&r!="config"&&t.push({name:r.split(".")[0]})}),t}a(Kre,"listSSHKeys");async function Wre(e){let t=nn.setSSHKnownHostsValidator(e);if(t)throw Ut(t,t.message,vt.BAD_REQUEST);let{known_hosts:r}=e;return await Se.outputFile(Mi,r),"Known hosts successfully set"}a(Wre,"setSSHKnownHosts");async function Qre(e){return await Se.pathExists(Mi)?{known_hosts:await Se.readFile(Mi,"utf8")}:{known_hosts:null}}a(Qre,"getSSHKnownHosts");Object.assign(hB,{customFunctionsStatus:Dre,getCustomFunctions:Lre,getCustomFunction:Pre,setCustomFunction:Mre,dropCustomFunction:Ure,addComponent:vre,dropCustomFunctionProject:xre,packageComponent:Bre,deployComponent:Hre,getComponents:kre,getComponentFile:Fre,setComponentFile:Gre,dropComponent:qre,addSSHKey:Vre,updateSSHKey:$re,deleteSSHKey:Yre,listSSHKeys:Kre,setSSHKnownHosts:Wre,getSSHKnownHosts:Qre})});var QA=I((qge,pB)=>{"use strict";var Xn=require("joi"),mB=mt();pB.exports={readTransactionLogValidator:zre,deleteTransactionLogsBeforeValidator:jre};function zre(e){let t=Xn.object({schema:Xn.string(),database:Xn.string(),table:Xn.string().required(),from:Xn.date().timestamp(),to:Xn.date().timestamp(),limit:Xn.number().min(1)});return mB.validateBySchema(e,t)}a(zre,"readTransactionLogValidator");function jre(e){let t=Xn.object({schema:Xn.string(),database:Xn.string(),table:Xn.string().required(),timestamp:Xn.date().timestamp().required()});return mB.validateBySchema(e,t)}a(jre,"deleteTransactionLogsBeforeValidator")});var $h=I(($ge,bB)=>{"use strict";var zA=H(),Vd=or(),SB=re(),TB=ie(),gB=mi(),RB=X(),{handleHDBError:qh,hdb_errors:Jre}=ce(),{HTTP_STATUS_CODES:Vh}=Jre,{readTransactionLogValidator:Xre,deleteTransactionLogsBeforeValidator:Zre}=QA(),AB=Vn(),ene="Logs successfully deleted from transaction log.",tne="All logs successfully deleted from transaction log.";bB.exports={readTransactionLog:rne,deleteTransactionLogsBefore:sne};async function rne(e){let t=Xre(e);if(t)throw qh(t,t.message,Vh.BAD_REQUEST,void 0,void 0,!0);e.database=e.database??e.schema??"data";let r=SB.checkSchemaTableExist(e.database,e.table);if(r)throw qh(new Error,r,Vh.NOT_FOUND,void 0,void 0,!0);return TB.get(zA.CONFIG_PARAMS.CLUSTERING_ENABLED)?await nne(e):(RB.info("Reading HarperDB logs used by Plexus"),(e.from||e.to)&&(e.search_type="timestamp",e.search_values=[e.from??0],e.to&&(e.search_values[1]=e.to)),AB.readAuditLog(e))}a(rne,"readTransactionLog");async function*nne(e){let t=gB.createNatsTableStreamName(e.database,e.table),r=await Vd.viewStreamIterator(t,parseInt(e.from),e.limit);for await(let n of r){let s=Math.floor(n?.nats_timestamp/1e6);if(e.to&&s>e.to)break;let i={operation:n?.entry?.operation,user:n?.entry?.__origin?.user,timestamp:s,records:n?.entry?.records,attributes:n?.entry?.attributes};n?.entry?.operation===zA.OPERATIONS_ENUM.DELETE&&(i.hash_values=n?.entry?.hash_values),yield i}}a(nne,"readTransactionLogNats");async function sne(e){let t=Zre(e);if(t)throw qh(t,t.message,Vh.BAD_REQUEST,void 0,void 0,!0);if(e.database=e.database??e.schema??"data",!TB.get(zA.CONFIG_PARAMS.CLUSTERING_ENABLED))return RB.info("Delete transaction logs called for Plexus"),AB.deleteAuditLogsBefore(e);let{database:r,table:n,timestamp:s}=e,i=SB.checkSchemaTableExist(r,n);if(i)throw qh(new Error,i,Vh.NOT_FOUND,void 0,void 0,!0);let o=gB.createNatsTableStreamName(r,n),{jsm:c}=await Vd.getNATSReferences(),l=await Vd.getStreamInfo(o),d=new Date(l.state.first_ts).getTime();if(s<=d)return`No transactions exist before: ${s}`;let u=ene,f,E=new Date(l.state.last_ts).getTime();return s>E?(f=l.state.last_seq+1,u=tne):f=(await Vd.viewStream(o,parseInt(s),1))[0].nats_sequence,await Vd.purgeTableStream(r,n,{seq:f}),u}a(sne,"deleteTransactionLogsBefore")});var OB=I((Kge,yB)=>{"use strict";var jA=class{static{a(this,"PermissionTableResponseObject")}constructor(t,r,n=[],s=[]){this.schema=t,this.table=r,this.required_table_permissions=n,this.required_attribute_permissions=s}};yB.exports=jA});var IB=I((Qge,NB)=>{"use strict";var JA=class{static{a(this,"PermissionAttributeResponseObject")}constructor(t,r=[]){this.attribute_name=t,this.required_permissions=r}};NB.exports=JA});var ZA=I((jge,CB)=>{"use strict";var wB=OB(),ine=IB(),{HDB_ERROR_MSGS:one}=En(),XA=class{static{a(this,"PermissionResponseObject")}constructor(){this.error=one.OP_AUTH_PERMS_ERROR,this.unauthorized_access={},this.invalid_schema_items=[]}handleUnauthorizedItem(t){return this.invalid_schema_items=[],this.unauthorized_access=[t],this}handleInvalidItem(t){return this.invalid_schema_items=[t],this.unauthorized_access=[],this}addInvalidItem(t,r,n){if(r&&n){let s=`${r}_${n}`;if(this.unauthorized_access[s])return}this.invalid_schema_items.push(t)}addUnauthorizedTable(t,r,n){let s=new wB(t,r,n),i=`${t}_${r}`;this.unauthorized_access[i]=s}addUnauthorizedAttributes(t,r,n,s){let i=[];t.forEach(c=>{let l=new ine(c,s[c]);i.push(l)});let o=`${r}_${n}`;if(this.unauthorized_access[o])this.unauthorized_access[o].required_attribute_permissions=i;else{let c=new wB(r,n,[],i);this.unauthorized_access[o]=c}}getPermsResponse(){let t=Object.values(this.unauthorized_access);return t.length>0||this.invalid_schema_items.length>0?(this.unauthorized_access=t,this):null}};CB.exports=XA});var Qh=I((eRe,KB)=>{"use strict";var eb=qn(),Yh=gn(),es=bE(),Kd=Zi(),tb=Jo(),ane=vg(),cne=RM(),Wd=$n(),Kh=$g(),ar=X(),lne=Wg(),une=lh(),dne=tA(),fne=dh(),_ne=sA(),Ene=iA(),hne=cA(),mne=uA(),rb=_A(),Ui=re(),pne=P0(),nb=SA(),PB=xd(),Zn=H(),MB=kx(),Sne=Bc(),UB=Xu(),vB=(Lh(),ae(kd)),xB=dr(),Jt=WA(),Tne=require("alasql"),BB=$h(),HB=Bh(),Qd=To(),kB=(Ra(),ae(ga)),FB=ZA(),{handleHDBError:sn,hdb_errors:GB}=ce(),{addNodeBack:Xge,removeNodeBack:Zge}=(Ra(),ae(ga)),{HDB_ERROR_MSGS:Ar,HTTP_STATUS_CODES:$d}=GB,W=new Map,qB="delete",Oo="insert",vi="read",La="update",Yd="describe",DB=Kd.describeSchema.name,LB=Kd.describeTable.name,VB={delete:!0,deleteRecord:!0,update:!0,updateData:!0,dropAttribute:!0,dropTable:!0,dropSchema:!0,upsert:!0,upsertData:!0},gne="catchup",Rne="handleGetJob",Ane="handleGetJobsByStartDate",Wh={CSV_DATA_LOAD:"csvDataLoad",CSV_URL_LOAD:"csvURLLoad",CSV_FILE_LOAD:"csvFileLoad",IMPORT_FROM_S3:"importFromS3"},bne=[es.createTable.name,es.createAttribute.name,es.dropTable.name,es.dropAttribute.name],$B={EXPORT_TO_S3:"export_to_s3",EXPORT_LOCAL:"export_local"},z=class{static{a(this,"permission")}constructor(t,r){this.requires_su=t,this.perms=r}};W.set(eb.insert.name,new z(!1,[Oo]));W.set(eb.update.name,new z(!1,[La]));W.set(eb.upsert.name,new z(!1,[Oo,La]));W.set(Yh.searchByConditions.name,new z(!1,[vi]));W.set(Yh.searchByHash.name,new z(!1,[vi]));W.set(Yh.searchByValue.name,new z(!1,[vi]));W.set(Yh.search.name,new z(!1,[vi]));W.set(es.createSchema.name,new z(!0,[]));W.set(es.createTable.name,new z(!0,[]));W.set(es.createAttribute.name,new z(!1,[Oo]));W.set(es.dropSchema.name,new z(!0,[]));W.set(es.dropTable.name,new z(!0,[]));W.set(es.dropAttribute.name,new z(!0,[]));W.set(Kd.describeSchema.name,new z(!1,[vi]));W.set(Kd.describeTable.name,new z(!1,[vi]));W.set(tb.deleteRecord.name,new z(!1,[qB]));W.set(Wd.addUser.name,new z(!0,[]));W.set(Wd.alterUser.name,new z(!0,[]));W.set(Wd.dropUser.name,new z(!0,[]));W.set(Wd.listUsersExternal.name,new z(!0,[]));W.set(Kh.listRoles.name,new z(!0,[]));W.set(Kh.addRole.name,new z(!0,[]));W.set(Kh.alterRole.name,new z(!0,[]));W.set(Kh.dropRole.name,new z(!0,[]));W.set(lne.name,new z(!0,[]));W.set(une.name,new z(!0,[]));W.set(dne.name,new z(!0,[]));W.set(fne.name,new z(!0,[]));W.set(_ne.name,new z(!0,[]));W.set(Ene.name,new z(!0,[]));W.set(rb.setRoutes.name,new z(!0,[]));W.set(rb.getRoutes.name,new z(!0,[]));W.set(rb.deleteRoutes.name,new z(!0,[]));W.set(xB.setConfiguration.name,new z(!0,[]));W.set(hne.clusterStatus.name,new z(!0,[]));W.set(mne.name,new z(!0,[]));W.set(nb.getFingerprint.name,new z(!0,[]));W.set(nb.setLicense.name,new z(!0,[]));W.set(tb.deleteFilesBefore.name,new z(!0,[]));W.set(tb.deleteAuditLogsBefore.name,new z(!0,[]));W.set(PB.restart.name,new z(!0,[]));W.set(PB.restartService.name,new z(!0,[]));W.set(ane.name,new z(!0,[]));W.set(cne.name,new z(!0,[vi]));W.set(Sne.systemInformation.name,new z(!0,[]));W.set(xB.getConfiguration.name,new z(!0,[]));W.set(BB.readTransactionLog.name,new z(!0,[]));W.set(BB.deleteTransactionLogsBefore.name,new z(!0,[]));W.set(HB.installModules.name,new z(!0,[]));W.set(HB.auditModules.name,new z(!0,[]));W.set(Qd.createCsr.name,new z(!0,[]));W.set(Qd.signCertificate.name,new z(!0,[]));W.set(Qd.listCertificates.name,new z(!0,[]));W.set(Qd.addCertificate.name,new z(!0,[]));W.set(Qd.removeCertificate.name,new z(!0,[]));W.set(kB.addNodeBack.name,new z(!0,[]));W.set(kB.removeNodeBack.name,new z(!0,[]));W.set(UB.createTokens.name,new z(!1,[]));W.set(UB.refreshOperationToken.name,new z(!1,[]));W.set(vB.login.name,new z(!1,[]));W.set(vB.logout.name,new z(!1,[]));W.set(Jt.customFunctionsStatus.name,new z(!0,[]));W.set(Jt.getCustomFunctions.name,new z(!0,[]));W.set(Jt.getComponents.name,new z(!0,[]));W.set(Jt.getComponentFile.name,new z(!0,[]));W.set(Jt.setComponentFile.name,new z(!0,[]));W.set(Jt.dropComponent.name,new z(!0,[]));W.set(Jt.getCustomFunction.name,new z(!0,[]));W.set(Jt.setCustomFunction.name,new z(!0,[]));W.set(Jt.dropCustomFunction.name,new z(!0,[]));W.set(Jt.addComponent.name,new z(!0,[]));W.set(Jt.dropCustomFunctionProject.name,new z(!0,[]));W.set(Jt.packageComponent.name,new z(!0,[]));W.set(Jt.deployComponent.name,new z(!0,[]));W.set(Jt.addSSHKey.name,new z(!0,[]));W.set(Jt.updateSSHKey.name,new z(!0,[]));W.set(Jt.deleteSSHKey.name,new z(!0,[]));W.set(Jt.listSSHKeys.name,new z(!0,[]));W.set(Jt.setSSHKnownHosts.name,new z(!0,[]));W.set(Jt.getSSHKnownHosts.name,new z(!0,[]));W.set(nb.getRegistrationInfo.name,new z(!1,[]));W.set(Wd.userInfo.name,new z(!1,[]));W.set(Kd.describeAll.name,new z(!1,[]));W.set(Rne,new z(!1,[]));W.set(Ane,new z(!0,[]));W.set(gne,new z(!0,[]));W.set(Wh.CSV_DATA_LOAD,new z(!1,[Oo,La]));W.set(Wh.CSV_URL_LOAD,new z(!1,[Oo,La]));W.set(Wh.CSV_FILE_LOAD,new z(!1,[Oo,La]));W.set(Wh.IMPORT_FROM_S3,new z(!1,[Oo,La]));W.set($B.EXPORT_TO_S3,new z(!0,[]));W.set($B.EXPORT_LOCAL,new z(!0,[]));W.set(Zn.VALID_SQL_OPS_ENUM.DELETE,new z(!1,[qB]));W.set(Zn.VALID_SQL_OPS_ENUM.SELECT,new z(!1,[vi]));W.set(Zn.VALID_SQL_OPS_ENUM.INSERT,new z(!1,[Oo]));W.set(Zn.VALID_SQL_OPS_ENUM.UPDATE,new z(!1,[La]));KB.exports={verifyPerms:One,verifyPermsAst:yne,verifyBulkLoadAttributePerms:Ine};function yne(e,t,r){if(Ui.isEmptyOrZeroLength(e))throw ar.info("verify_perms_ast has an empty user parameter"),sn(new Error);if(Ui.isEmptyOrZeroLength(t))throw ar.info("verify_perms_ast has an empty user parameter"),sn(new Error);if(Ui.isEmptyOrZeroLength(r))throw ar.info("verify_perms_ast has a null operation parameter"),sn(new Error);try{let n=new FB,s=new pne(e),i=s.getSchemas(),o=new Map;if((!i||i.length===0)&&s.affected_attributes&&s.affected_attributes.size>0)throw ar.info("No schemas defined in verifyPermsAst(), will not continue."),sn(new Error);let c=!!t.role.permission.super_user,l=i.includes("system");if(l&&VB[r])throw sn(new Error,Ar.DROP_SYSTEM,$d.FORBIDDEN);if(c&&!l)return null;let d=MB.getRolePermissions(t.role);t.role.permission=d,!c&&e instanceof Tne.yy.Select&&(e=s.updateAttributeWildcardsForRolePerms(d));for(let f=0;f<i.length;f++){let E=s.getTablesBySchemaName(i[f]);E&&o.set(i[f],E)}let u=YB(t,r,o,n);return u||(o.forEach((f,E)=>{for(let _=0;_<f.length;_++){let h=s.getAttributesBySchemaTableName(E,f[_]),p=ib(t.role.permission,E,f[_]);sb(h,p,r,f[_],E,n)}}),n.getPermsResponse())}catch(n){throw sn(n)}}a(yne,"verifyPermsAst");function One(e,t){if(e===null||t===null||e.hdb_user===void 0||e.hdb_user===null)throw ar.info("null required parameter in verifyPerms"),sn(new Error,Ar.DEFAULT_INVALID_REQUEST,$d.BAD_REQUEST);let r;t instanceof Function?r=t.name:r=t;let n=e.action,s=e.schema??e.database,i=e.table,o=new Map;s&&i&&o.set(s,[i]);let c=new FB;if(Ui.isEmptyOrZeroLength(e.hdb_user.role)||Ui.isEmptyOrZeroLength(e.hdb_user.role.permission))return ar.info(`User ${e.hdb_user.username} has no role or permissions. Please assign the user a valid role.`),c.handleUnauthorizedItem(Ar.USER_HAS_NO_PERMS(e.hdb_user.username));let l=!!e.hdb_user.role.permission.super_user,d=e.hdb_user.role.permission.structure_user,u=o.has(Zn.SYSTEM_SCHEMA_NAME)||s===Zn.SYSTEM_SCHEMA_NAME;if(u&&VB[r])throw sn(new Error,Ar.DROP_SYSTEM,$d.FORBIDDEN);if(l&&!u||d===!0&&(r===es.createSchema.name||r===es.dropSchema.name))return null;if(bne.indexOf(r)>=0&&(d===!0||Array.isArray(d)))return d===!0||d.indexOf(s)>=0?null:c.handleUnauthorizedItem(`User does not have access to perform '${e.operation}' against schema '${s}'`);let f=MB.getRolePermissions(e.hdb_user.role);if(e.hdb_user.role.permission=f,r===DB||r===LB){if(s===Zn.SYSTEM_SCHEMA_NAME)return c.handleUnauthorizedItem(Ar.SCHEMA_PERM_ERROR(s));if(!f.super_user){if(r===DB&&(!f[s]||!f[s][Yd]))return c.handleInvalidItem(Ar.SCHEMA_NOT_FOUND(s));if(r===LB&&(!f[s]||!f[s].tables[i]||!f[s].tables[i][Yd]))return c.handleInvalidItem(Ar.TABLE_NOT_FOUND(s,i))}}let E=YB(e.hdb_user,r,o,c,n);if(E)return E;if(W.get(r)&&W.get(r).perms.length===0)return null;if(!l&&e.get_attributes&&Zn.SEARCH_WILDCARDS.includes(e.get_attributes[0])){let p=[],S=f[s].tables[i];S[Zn.PERMS_CRUD_ENUM.READ]&&(S.attribute_permissions.length>0?S.attribute_permissions.filter(T=>T[Zn.PERMS_CRUD_ENUM.READ]).forEach(T=>{p.push(T.attribute_name)}):p=global.hdb_schema[s][i].attributes.map(g=>g.attribute),e.get_attributes=p)}let _=Nne(e),h=ib(e.hdb_user.role.permission,s,i);return sb(_,h,r,i,s,c,n),c.getPermsResponse()}a(One,"verifyPerms");function YB(e,t,r,n,s){if(Ui.arrayHasEmptyValues([e,t,r]))throw ar.info("hasPermissions has an invalid parameter"),sn(new Error);let i=r.has("system"),o=e.role.permission;if(o.super_user&&(!i||W.get(t).requires_su))return null;if(!W.get(t))throw ar.info(`operation ${t} not found.`),sn(new Error,Ar.OP_NOT_FOUND(t),$d.BAD_REQUEST);if(W.get(t)&&W.get(t).requires_su)return ar.info(`operation ${t} requires SU permissions.`),n.handleUnauthorizedItem(Ar.OP_IS_SU_ONLY(t));let c=r.keys();for(let l of c){try{if(l&&!o[l]||o[l][Yd]===!1){n.addInvalidItem(Ar.SCHEMA_NOT_FOUND(l));continue}}catch{n.addInvalidItem(Ar.SCHEMA_NOT_FOUND(l));continue}let d=r.get(l);for(let u of d){let f=o[l].tables[u];if(!f||f[Yd]===!1)n.addInvalidItem(Ar.TABLE_NOT_FOUND(l,u));else try{let E=[],_=W.get(t).perms;!Ui.isEmpty(s)&&_.includes(s)&&(_=[s]);for(let h=0;h<_.length;h++){let p=_[h],S=f[p];(S==null||S===!1)&&(ar.info(`Required ${p} permission not found for ${t} ${s?`${s} `:""}operation in role ${e.role.id}`),E.push(p))}E.length>0&&n.addUnauthorizedTable(l,u,E)}catch(E){let _=Ar.UNKNOWN_OP_AUTH_ERROR(t,l,u);throw ar.error(_),ar.error(E),sn(GB.CHECK_LOGS_WRAPPER(_))}}}return r.size<2?n.getPermsResponse():null}a(YB,"hasPermissions");function sb(e,t,r,n,s,i,o){if(!e||!t)throw ar.info("no attributes specified in checkAttributePerms."),sn(new Error);let c=W.get(r).perms;if(!c||c==="")throw ar.info(`no permissions found for ${r} in checkAttributePerms().`),sn(new Error);if(Ui.isEmptyOrZeroLength(t))return ar.info("No role permissions set (this is OK)."),null;o&&c.includes(o)&&(c=[o]);let l={};for(let u of e){let f=t.get(u);if(f){if(f[Yd]===!1){i.addInvalidItem(Ar.ATTR_NOT_FOUND(s,n,u),s,n);continue}if(c)for(let E of c){if(Zn.TIME_STAMP_NAMES.includes(f.attribute_name)&&E!==vi)throw sn(new Error,Ar.SYSTEM_TIMESTAMP_PERMS_ERR,$d.FORBIDDEN);f[E]===!1&&(l[f.attribute_name]?l[f.attribute_name].push(E):l[f.attribute_name]=[E])}}else i.addInvalidItem(Ar.ATTR_NOT_FOUND(s,n,u),s,n)}let d=Object.keys(l);d.length>0&&i.addUnauthorizedAttributes(d,s,n,l)}a(sb,"checkAttributePerms");function Nne(e){let t=new Set;try{if(e.action)return t;if(e.operation===Zn.OPERATIONS_ENUM.SEARCH_BY_CONDITIONS&&e.conditions.forEach(r=>{t.add(r.search_attribute)}),e&&e.search_attribute&&t.add(e.search_attribute),!e.records||e.records.length===0){if(!e.get_attributes||!e.get_attributes.length===0)return t;for(let r=0;r<e.get_attributes.length;r++)t.add(e.get_attributes[r])}else for(let r=0;r<e.records.length;r++){let n=Object.keys(e.records[r]);for(let s=0;s<n.length;s++)t.add(n[s])}}catch(r){ar.info(r)}return t}a(Nne,"getRecordAttributes");function ib(e,t,r){let n=new Map;if(Ui.isEmpty(e))return ar.info("no hdb_user specified in getAttributePermissions"),n;if(e.super_user||!t||!r)return n;try{e[t].tables[r].attribute_permissions.forEach(s=>{n.has(s.attribute_name)||n.set(s.attribute_name,s)})}catch{ar.info(`No attribute permissions found for schema ${t} and table ${r}.`)}return n}a(ib,"getAttributePermissions");function Ine(e,t,r,n,s,i,o){let c=new Set(i),l=ib(e,n,s);sb(c,l,t,s,n,o,r)}a(Ine,"verifyBulkLoadAttributePerms")});var jh=I((rRe,JB)=>{"use strict";JB.exports={evaluateSQL:Fne,processAST:jB,convertSQLToAST:zB,checkASTPermissions:QB};var wne=qn(),WB=require("util"),Cne=WB.callbackify(wne.insert),Dne=gn().search,Lne=XP().update,Pne=WB.callbackify(Lne),Mne=eM().convertDelete,No=require("alasql"),Une=Qh(),zh=X(),vne=pE(),xne=re(),zd=H(),{hdb_errors:Bne,handleHDBError:ob}=ce(),{HTTP_STATUS_CODES:ab}=Bne;vne(No);var Hne=403,kne="There was a problem performing this insert. Please check the logs and try again.",cb=class{static{a(this,"ParsedSQLObject")}constructor(){this.ast=void 0,this.variant=void 0,this.permissions_checked=!1}};function Fne(e,t){let r=e.parsed_sql_object;if(!r){r=zB(e.sql);let n,s=r.ast.statements[0];if(s instanceof No.yy.Insert?n=s.into.databaseid:s instanceof No.yy.Select?n=s.from?s.from[0].databaseid:null:s instanceof No.yy.Update||s instanceof No.yy.Delete?n=s.table.databaseid:zh.error("AST in evaluateSQL is not a valid SQL type."),!(s instanceof No.yy.Select)&&xne.isEmptyOrZeroLength(n))return t("No schema specified",null)}jB(e,r,(n,s)=>{if(n)return t(n);t(null,s)})}a(Fne,"evaluateSQL");function QB(e,t){let r;try{r=Une.verifyPermsAst(t.ast.statements[0],e.hdb_user,t.variant),t.permissions_checked=!0}catch(n){throw n}return r||null}a(QB,"checkASTPermissions");function zB(e){let t=new cb;if(!e)throw ob(new Error,"The 'sql' parameter is missing from the request body",ab.BAD_REQUEST);try{let r=e.trim(),n=No.parse(r),s=r.split(" ")[0].toLowerCase();t.ast=n,t.variant=s}catch(r){let n=r.message.split(`
26
+ `);throw n[1]?ob(r,`Invalid SQL at: ${n[1]}. Please ensure your SQL is valid. Try adding backticks to reserved words and schema table references.`,ab.BAD_REQUEST):ob(r,"We had trouble parsing your request. Please ensure your SQL is valid. Try adding backticks to reserved words and schema table references.",ab.BAD_REQUEST)}return t}a(zB,"convertSQLToAST");function jB(e,t,r){try{let n=Gne;if(!e.bypass_auth&&!t.permissions_checked){let i=QB(e,t);if(i&&i.length>0)return r(Hne,i)}let s={statement:t.ast.statements[0],hdb_user:e.hdb_user};switch(t.variant){case zd.VALID_SQL_OPS_ENUM.SELECT:n=Dne,s=t.ast.statements[0];break;case zd.VALID_SQL_OPS_ENUM.INSERT:n=qne;break;case zd.VALID_SQL_OPS_ENUM.UPDATE:n=Pne;break;case zd.VALID_SQL_OPS_ENUM.DELETE:n=Mne;break;default:throw new Error(`unsupported SQL type ${t.variant} in SQL: ${e}`)}n(s,(i,o)=>{if(i){r(i);return}r(null,o)})}catch(n){return r(n)}}a(jB,"processAST");function Gne(e,t){zh.info(e),t("unknown sql statement")}a(Gne,"nullFunction");function qne({statement:e,hdb_user:t},r){let n=e.into,s={schema:n.databaseid,table:n.tableid,operation:"insert",hdb_user:t},i=e.columns.map(o=>o.columnid);try{s.records=Vne(i,e.values)}catch(o){return r(o)}Cne(s,(o,c)=>{if(o)return r(o);try{delete c.new_attributes,delete c.txn_time}catch(l){zh.error(`Error delete new_attributes from insert response: ${l}`)}r(null,c)})}a(qne,"convertInsert");function Vne(e,t){try{return t.map(r=>{if(e.length!==r.length)throw"number of values do not match number of columns in insert";let n={};return r.forEach((s,i)=>{if(s.columnid)throw"cannot use a column in insert value";"value"in s?n[e[i]]=s.value:n[e[i]]=No.compile(`SELECT ${s.toString()} AS [${zd.FUNC_VAL}] FROM ?`)}),n})}catch(r){throw zh.error(r),new Error(kne)}}a(Vne,"createDataObjects")});var lb=I((sRe,ZB)=>{"use strict";var{S3:$ne,GetObjectCommand:Yne}=require("@aws-sdk/client-s3");ZB.exports={getFileStreamFromS3:Kne,getS3AuthObj:XB};async function Kne(e){let{s3:t}=e,r={Bucket:t.bucket,Key:t.key};return(await XB(t.aws_access_key_id,t.aws_secret_access_key,t.region).send(new Yne(r))).Body}a(Kne,"getFileStreamFromS3");function XB(e,t,r){return new $ne({credentials:{accessKeyId:e,secretAccessKey:t},region:r})}a(XB,"getS3AuthObj")});var Jh=I((oRe,cH)=>{"use strict";var db=gn(),Wne=jh(),Qne=lb(),{AsyncParser:zne,Transform:jne}=require("json2csv"),Jd=require("stream"),Dn=re(),ub=require("fs-extra"),Jne=require("path"),ts=X(),{promisify:rH}=require("util"),jd=re(),{handleHDBError:Xt,hdb_errors:Xne}=ce(),{HDB_ERROR_MSGS:on,HTTP_STATUS_CODES:Zt}=Xne,{streamAsJSON:Zne}=(fS(),ae(lI)),{Upload:ese}=require("@aws-sdk/lib-storage"),eH=["search_by_value","search_by_hash","sql","search_by_conditions"],tH=["json","csv"],nH="json",sH="csv",tse="Successfully exported JSON locally.",rse="Successfully exported CSV locally.",nse=1e3,sse=db.searchByHash,ise=db.searchByValue,ose=rH(Wne.evaluateSQL),ase=rH(Jd.finished);cH.exports={export_to_s3:dse,export_local:cse,toCsvStream:iH};async function cse(e){ts.trace(`export_local request to path: ${e.path}, filename: ${e.filename}, format: ${e.format}`);let t=oH(e);if(!Dn.isEmpty(t))throw ts.error(t),Xt(new Error,t,Zt.BAD_REQUEST,void 0,void 0,!0);if(Dn.isEmpty(e.path))throw ts.error(on.MISSING_VALUE("path")),Xt(new Error,on.MISSING_VALUE("path"),Zt.BAD_REQUEST,void 0,void 0,!0);let r=(Dn.isEmpty(e.filename)?new Date().getTime():e.filename)+"."+e.format;e.path.endsWith(Jne.sep)&&(e.path=e.path.substring(0,e.path.length-1));let n=Dn.buildFolderPath(e.path,r);await lse(e.path);let s=await aH(e);return await use(n,e.format,s)}a(cse,"export_local");async function lse(e){if(ts.trace("in confirmPath"),Dn.isEmptyOrZeroLength(e))throw Xt(new Error,`Invalid path: ${e}`,Zt.BAD_REQUEST,void 0,void 0,!0);let t;try{t=await ub.stat(e)}catch(r){let n;throw r.code==="ENOENT"?n=`path '${e}' does not exist`:r.code==="EACCES"?n=`access to path '${e}' is denied`:n=r.message,ts.error(n),Xt(new Error,n,Zt.BAD_REQUEST,void 0,void 0,!0)}if(!t.isDirectory()){let r=`path '${e}' is not a directory, please supply a valid folder path`;throw ts.error(r),Xt(new Error,r,Zt.BAD_REQUEST,void 0,void 0,!0)}return!0}a(lse,"confirmPath");async function use(e,t,r){if(ts.trace("in saveToLocal"),jd.isEmptyOrZeroLength(e))throw Xt(new Error,on.INVALID_VALUE("file_path"),Zt.BAD_REQUEST,void 0,void 0,!0);if(jd.isEmptyOrZeroLength(t))throw Xt(new Error,on.INVALID_VALUE("Source format"),Zt.BAD_REQUEST,void 0,void 0,!0);if(jd.isEmpty(r))throw Xt(new Error,on.NOT_FOUND("Data"),Zt.BAD_REQUEST,void 0,void 0,!0);if(t===nH){let n=ub.createWriteStream(e);return Zne(r).pipe(n),await ase(n),{message:tse,path:e}}else if(t===sH){let n=ub.createWriteStream(e),s=Jd.Readable.from(r),i={},o=r.getColumns?.();o&&(i.fields=o.map(u=>({label:u,value:u})));let c={objectMode:!0};return await new zne(i,c).fromInput(s).toOutput(n).promise(!1),{message:rse,path:e}}throw Xt(new Error,on.INVALID_VALUE("format"),Zt.BAD_REQUEST)}a(use,"saveToLocal");async function dse(e){if(!e.s3||Object.keys(e.s3).length===0)throw Xt(new Error,on.MISSING_VALUE("S3 object"),Zt.BAD_REQUEST);if(Dn.isEmptyOrZeroLength(e.s3.aws_access_key_id))throw Xt(new Error,on.MISSING_VALUE("aws_access_key_id"),Zt.BAD_REQUEST);if(Dn.isEmptyOrZeroLength(e.s3.aws_secret_access_key))throw Xt(new Error,on.MISSING_VALUE("aws_secret_access_key"),Zt.BAD_REQUEST);if(Dn.isEmptyOrZeroLength(e.s3.bucket))throw Xt(new Error,on.MISSING_VALUE("bucket"),Zt.BAD_REQUEST);if(Dn.isEmptyOrZeroLength(e.s3.key))throw Xt(new Error,on.MISSING_VALUE("key"),Zt.BAD_REQUEST);if(Dn.isEmptyOrZeroLength(e.s3.region))throw Xt(new Error,on.MISSING_VALUE("region"),Zt.BAD_REQUEST);let t=oH(e);if(!Dn.isEmpty(t))throw Xt(new Error,t,Zt.BAD_REQUEST);ts.trace(`called export_to_s3 to bucket: ${e.s3.bucket} and query ${e.search_operation.sql}`);let r;try{r=await aH(e)}catch(l){throw ts.error(l),l}let n,s=await Qne.getS3AuthObj(e.s3.aws_access_key_id,e.s3.aws_secret_access_key,e.s3.region),i,o=new Jd.PassThrough;if(e.format===sH){i=e.s3.key+".csv";let l=iH(r,r.getColumns?.());l.on("error",d=>{throw d}),l.pipe(o)}else if(e.format===nH){i=e.s3.key+".json";let l=new Jd.Readable;l.pipe(o),l.on("error",f=>{throw f}),l.push("[");let d=r.length,u="";for(let[f,E]of r.entries()){let _=f===d-1?JSON.stringify(E):JSON.stringify(E)+",";u+=_,f!==0&&f%nse===0&&(l.push(u),u="")}u.length!==0&&l.push(u),l.push("]"),l.push(null)}else throw Xt(new Error,on.INVALID_VALUE("format"),Zt.BAD_REQUEST);return new ese({client:s,params:{Bucket:e.s3.bucket,Key:i,Body:o}}).done()}a(dse,"export_to_s3");function iH(e,t){let r=Jd.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 jne(n,s);return r.pipe(i)}a(iH,"toCsvStream");function oH(e){if(ts.trace("in exportCoreValidation"),Dn.isEmpty(e.format))return"format missing";if(tH.indexOf(e.format)<0)return`format invalid. must be one of the following values: ${tH.join(", ")}`;let t=e.search_operation.operation;if(Dn.isEmpty(t))return"search_operation.operation missing";if(eH.indexOf(t)<0)return`search_operation.operation must be one of the following values: ${eH.join(", ")}`}a(oH,"exportCoreValidation");async function aH(e){ts.trace("in getRecords");let t,r;if(jd.isEmpty(e.search_operation)||jd.isEmptyOrZeroLength(e.search_operation.operation))throw Xt(new Error,on.INVALID_VALUE("Search operation"),Zt.BAD_REQUEST);switch(e.search_operation.operation){case"search_by_value":t=ise;break;case"search_by_hash":t=sse;break;case"search_by_conditions":t=db.searchByConditions;break;case"sql":t=ose;break;default:throw r=`Operation ${e.search_operation.operation} is not support by export.`,ts.error(r),Xt(new Error,r,Zt.BAD_REQUEST)}return e.search_operation.hdb_user=e.hdb_user,t(e.search_operation)}a(aH,"getRecords")});var pH={};Ze(pH,{contentTypes:()=>hb,findBestSerializer:()=>em,getDeserializer:()=>Ma,registerContentHandlers:()=>mb,serialize:()=>ef,serializeMessage:()=>wa});function fse(e){try{return e?.[0]===123?Eb(e):e}catch{return e}}function mb(e){e.register(Ese,{serializers:[{regex:/^application\/json$/,serializer:au},{regex:/^application\/cbor$/,serializer:function(t){return new Pa.EncoderStream(Zd).end(t)}},{regex:/^application\/(x-)?msgpack$/,serializer:function(t){return(t?.[Symbol.iterator]||t?.[Symbol.asyncIterator])&&!Array.isArray(t)?Zh.Readable.from((0,Xs.encodeIter)(t,Zd)):(0,Xs.pack)(t)}},{regex:/^text\/csv$/,serializer:function(t){return this.header("Content-Disposition",'attachment; filename="data.csv"'),(0,Xh.toCsvStream)(t)}}]}),e.addContentTypeParser("application/x-msgpack",{parseAs:"buffer"},(t,r,n)=>{try{n(null,(0,Xs.unpack)(r))}catch(s){s.statusCode=400,n(s)}}),e.addContentTypeParser("application/cbor",{parseAs:"buffer"},(t,r,n)=>{try{n(null,(0,Pa.decode)(r))}catch(s){s.statusCode=400,n(s)}})}function em(e){let r=(e.headers.asObject||e.headers).accept,n,s=0,i,o,c=r?r.toLowerCase().split(/\s*,\s*/):[];for(let l of c){let[d,...u]=l.split(/\s*;\s*/),f=1,E={q:1};for(let h of u){let p=h.indexOf("=");E[h.substring(0,p)]=h.substring(p+1)}f=+E.q;let _=Er.get(d);if(_){let h=(_.q||1)*f;h>s&&(n=_,i=_.type||d,s=h,o=E)}}if(!n){if(r)throw new fH.ClientError("No supported content types found in Accept header, supported types include: "+Array.from(Er.keys()).join(", "),406);n=Er.get("application/json"),i="application/json"}return{serializer:n,type:i,parameters:o}}function ef(e,t,r){let n=uH&&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)r.headers.set("Content-Type","application/octet-stream"),r.headers.set("Vary","Accept-Encoding"),s=e;else{let i=em(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[Symbol.iterator]||e[Symbol.asyncIterator])&&i.serializer.serializeStream){let o=i.serializer.serializeStream(e,r);return n&&(r.headers.set("Content-Encoding","br"),o=o.pipe((0,xi.createBrotliCompress)({params:{[xi.constants.BROTLI_PARAM_MODE]:i.type.includes("json")||i.type.includes("text")?xi.constants.BROTLI_MODE_TEXT:xi.constants.BROTLI_MODE_GENERIC,[xi.constants.BROTLI_PARAM_QUALITY]:2}}))),o}s=i.serializer.serialize(e,r)}return n&&s?.length>uH?(r.headers.set("Content-Encoding","br"),new Promise((i,o)=>(0,xi.brotliCompress)(s,(c,l)=>{c?o(c):i(l)}))):s}function wa(e,t){if(e?.contentType!=null&&e.data!=null)return e.data;if(!t)return Xd(e);let r=t.serialize;if(r)return r(e);let n=em(t);return r=t.serialize=n.serializer.serialize,r(e)}function hse(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 Ma(e,t){e||(e="");let r=e.indexOf(";"),n;r>-1&&(n=e.slice(r+1),e=e.slice(0,r));let s=Er.get(e);if(t){if(s?.deserializeStream)return s.deserializeStream;let i=Er.get(e)?.deserialize||dH(e,n);return o=>hse(o).then(i)}return e&&Er.get(e)?.deserialize||dH(e,n)}function dH(e,t){if(e.startsWith("text/")){let r=t?.match(/charset=(.+)/)?.[1]||"utf-8";return n=>({contentType:e,data:n.toString(r)})}else return e==="application/octet-stream"?r=>r:r=>{if(!e)try{if(r?.[0]===123)return Eb(r)}catch{}return{contentType:e||"application/octet-stream",data:r}}}function mse(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)}}}}}var Xh,Xs,Pa,xi,fH,Zh,_H,fb,_b,EH,hH,Xd,Eb,Zd,Er,hb,lH,mH,_se,Ese,uH,ll=Oe(()=>{fS();Xh=U(Jh()),Xs=require("msgpackr"),Pa=require("cbor-x"),xi=require("zlib"),fH=U(ce()),Zh=require("stream");Lr();_H=require("../index"),fb=U(ie()),_b=U(H()),EH=U(require("yaml")),hH=fb.default.get(_b.CONFIG_PARAMS.SERIALIZATION_BIGINT)!==!1,Xd=hH?Fo:JSON.stringify,Eb=hH?dS:JSON.parse,Zd={useRecords:!1,useToJSON:!0},Er=new Map,hb=Er;st.contentTypes=hb;(0,_H._assignPackageExport)("contentTypes",hb);Er.set("application/json",{serializeStream:au,serialize:Xd,deserialize:Eb,q:.8});lH=new Pa.Encoder(Zd);Er.set("application/cbor",{serializeStream(e){return e[Symbol.asyncIterator]&&(e[Symbol.iterator]=null),new Pa.EncoderStream(Zd).end(e)},serialize:lH.encode,deserialize:lH.decode,q:1});Er.set("application/x-msgpack",{serializeStream(e){return(e?.[Symbol.iterator]||e?.[Symbol.asyncIterator])&&!Array.isArray(e)?Zh.Readable.from((0,Xs.encodeIter)(e,Zd)):(0,Xs.pack)(e)},serialize:Xs.pack,deserialize:Xs.unpack,q:.9});Er.set("text/csv",{serializeStream(e,t){return t.headers.set("Content-Disposition",'attachment; filename="data.csv"'),(0,Xh.toCsvStream)(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]),(0,Xh.toCsvStream)(e,e?.getColumns?.())},q:.1});Er.set("text/plain",{serialize(e){return e.toString()},deserialize(e){return e.toString()},q:.2});Er.set("text/yaml",{serialize(e){return EH.stringify(e,{aliasDuplicateObjects:!1})},q:.7});Er.set("text/event-stream",{serializeStream:function(e){return Zh.Readable.from(mse(e,this.serialize))},serialize: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+`
27
+ `),e.data){let r=e.data;typeof r=="object"&&(r=Xd(r)),t+="data: "+r+`
18
28
  `}return e.id&&(t+="id: "+e.id+`
19
29
  `),e.retry&&(t+="retry: "+e.retry+`
20
30
  `),t+`
21
- `}else return typeof e=="object"?`data: ${jl(e)}
31
+ `}else return typeof e=="object"?`data: ${Xd(e)}
22
32
 
23
33
  `:`data: ${e}
24
34
 
25
- `},compressible:!1,q:.8});Ft.set("application/x-www-form-urlencoded",{deserialize(e){let t={};for(let[r,n]of new URLSearchParams(e))if(t.hasOwnProperty(r)){let s=t[r];Array.isArray(s)?s.push(n):t.key=[s,n]}else t[r]=n},serialize(e){let t=new URLSearchParams;for(let r in e)t.set(r,e);return t.toString()}});cv={type:"application/json",serializeStream:Oc,serialize:jl,deserialize:Q9,q:.5};Ft.set("*/*",cv);Ft.set("",cv);a(Q9,"tryJSONParse");a(pg,"registerContentHandlers");z9=require("fastify-plugin"),J9=z9(function(e,t,r){e.addHook("preSerialization",async(n,s)=>{if(s.raw.getHeader("content-type"))return;let{serializer:o,type:c}=wf(n.raw);s.type(c),s.serializer(function(l){return(o.serializeStream||o.serialize)(l,{headers:{set:(_,u)=>{s.header(_,u)}}})})}),r()},{name:"content-type-negotiation"});a(wf,"findBestSerializer");rv=fg.default.get(Eg.CONFIG_PARAMS.HTTP_COMPRESSIONTHRESHOLD);a(Cf,"serialize");a(fo,"serializeMessage");a(X9,"streamToBuffer");a(po,"getDeserializer");a(nv,"deserializerUnknownType");a(j9,"transformIterable")});var su={};qe(su,{addAnalyticsListener:()=>nu,recordAction:()=>wr,recordActionBinary:()=>Jr,setAnalyticsEnabled:()=>Z9});function Z9(e){Sv=e}function wr(e,t,r,n,s){if(!Sv)return;let i=t+(r?"-"+r:"");n!==void 0&&(i+="-"+n),s!==void 0&&(i+="-"+s);let o=Mf.get(i);if(o)if(typeof e=="number"){let c=o.values,l=c.index++;if(l>=c.length){let _=c;o.values=c=new Float32Array(l*2),c.set(_),c.index=l+1}c[l]=e,o.total+=e}else if(typeof e=="boolean")e&&o.total++,o.count++;else if(typeof e=="function")o.count++;else throw new TypeError("Invalid metric value type "+typeof e);else{if(typeof e=="number")o={total:e,values:new Float32Array(4)},o.values.index=1,o.values[0]=e,o.total=e;else if(typeof e=="boolean")o={},o.total=e?1:0,o.count=1;else if(typeof e=="function")o={},o.count=1,o.callback=e;else throw new TypeError("Invalid metric value type "+typeof e);o.description={metric:t,path:r,method:n,type:s},Mf.set(i,o)}Df||e7()}function Jr(e,t,r,n,s){wr(!!e,t,r,n,s)}function nu(e){Rv.push(e)}function e7(){Df=performance.now(),setTimeout(async()=>{let e=performance.now()-Df;Df=0;let t=[],r={time:Date.now(),period:e,threadId:So.threadId,metrics:t};for(let[s,i]of Mf){if(i.values){let o=i.values.subarray(0,i.values.index);o.sort();let c=o.length,l=0,_=[],u;for(let d of Av){let E=Math.floor(c*d),f=o[E-1];if(E>l){let h=E-l;if(f===u){let p=_[_.length-1];typeof p=="number"?_[_.length-1]={value:p,count:1+h}:p.count+=h}else _.push(h>1?{value:f,count:h}:f),u=f;l=E}}t.push(Object.assign(i.description,{mean:i.total/c,distribution:_,count:c}))}else i.callback?t.push(Object.assign(i.description,i.callback(i))):t.push(Object.assign(i.description,{total:i.total,count:i.count}));await Ov()}let n=process.memoryUsage();t.push({metric:"memory",threadId:So.threadId,byThread:!0,...n});for(let s of Rv)s(t);Mf=new Map,So.parentPort?So.parentPort.postMessage({type:gv,report:r}):Nv({report:r})},Tv).unref()}async function t7(e,t=6e4){let r=gg(),n=bv(),s=new Promise(p=>{let S=performance.now();setImmediate(()=>{let T=performance.now();T-S>5e3&&(0,eu.warn)("Unusually high event queue latency on the main thread of "+Math.round(T-S)+"ms"),S=performance.now()}),n.primaryStore.prefetch([1],()=>{let T=performance.now();T-S>5e3&&(0,eu.warn)("Unusually high task queue latency on the main thread of "+Math.round(T-S)+"ms"),p(T-S)})}),i;for(let p of n.primaryStore.getRange({start:1/0,end:!1,reverse:!0}))if(p.value?.time){i=p.value.time;break}if(Date.now()-t<i)return;let o,c=new Map,l=new Map,_=[],u;for(let{key:p,value:S}of r.primaryStore.getRange({start:i||!1,exclusiveStart:!0,end:1/0})){if(!S)continue;if(o){if(p>o+t)break}else o=p;u=p;let{metrics:T,threadId:R}=S;for(let b of T||[]){let{path:C,method:H,type:v,metric:q,count:M,total:Q,distribution:J,threads:X,...ae}=b;M||(M=1);let ce=q+(C?"-"+C:"");H!==void 0&&(ce+="-"+H),v!==void 0&&(ce+="-"+v);let ge=c.get(ce);if(ge){if(ge.threads){let Ne=ge.threads[R];if(Ne)ge=Ne;else{ge.threads[R]=Object.assign({},ae);continue}}ge.count||(ge.count=1);let Ge=ge.count;for(let Ne in ae){let ve=ae[Ne];typeof ve=="number"&&(ge[Ne]=(ge[Ne]*Ge+ve*M)/(Ge+M))}ge.count+=M,Q>=0&&(ge.total+=Q,ge.ratio=ge.total/ge.count)}else ge=Object.assign({period:t},b),delete ge.distribution,c.set(ce,ge),ge.byThread&&(ge.threads=[],ge.threads[R]=Object.assign({},ae),_.push(ge));if(J){J=J.map(Ne=>typeof Ne=="number"?{value:Ne,count:1}:Ne);let Ge=l.get(ce);Ge?Ge.push(...J):l.set(ce,J)}}await Ov()}for(let p of _){let{path:S,method:T,type:R,metric:b,count:C,total:H,distribution:v,threads:q,...M}=p;q=q.filter(Q=>Q);for(let Q in M){if(typeof p[Q]!="number")continue;let J=0;for(let X of q){let ae=X[Q];typeof ae=="number"&&(J+=ae)}p[Q]=J}p.count=q.length,delete p.threads,delete p.byThread}for(let[p,S]of l){let T=c.get(p);S.sort((Ne,ve)=>Ne.value>ve.value?1:-1);let R=T.count-1,b=[],C=0,H=0,v;for(let Ne of Av){let ve=R*Ne;for(;C<ve;)v=S[H++],C+=v.count,H===1&&C--;let Ku=S[H>1?H-2:0];v||(v=S[0]),b.push(v.value-(v.value-Ku.value)*(C-ve)/v.count)}let[q,M,Q,J,X,ae,ce,ge,Ge]=b;Object.assign(T,{p1:q,p10:M,p25:Q,median:J,p75:X,p90:ae,p95:ce,p99:ge,p999:Ge})}let d;for(let[p,S]of c)S.id=(0,Lf.getNextMonotonicTime)(),S.time=u,n.primaryStore.put(S.id,S,{append:!0}).then(T=>{T||n.primaryStore.put(S.id,S)}),d=!0;let E=Date.now(),{idle:f,active:h}=performance.eventLoopUtilization();if(d||h*10>f){let p=(0,Lf.getNextMonotonicTime)(),S={id:p,metric:"main-thread-utilization",idle:f-uv,active:h-_v,taskQueueLatency:await s,time:E,...process.memoryUsage()};n.primaryStore.put(p,S,{append:!0}).then(T=>{T||n.primaryStore.put(p,S)})}uv=f,_v=h}async function dv(e,t){let r=Date.now()-t;for(let n of e.primaryStore.getKeys({start:!1,end:r}))e.primaryStore.remove(n)}function gg(){return fv||(fv=ft({table:"hdb_raw_analytics",database:"system",audit:!1,trackDeletes:!1,attributes:[{name:"id",isPrimaryKey:!0},{name:"action"},{name:"metrics"}]}))}function bv(){return Ev||(Ev=ft({table:"hdb_analytics",database:"system",audit:!1,trackDeletes:!1,attributes:[{name:"id",isPrimaryKey:!0},{name:"metric"},{name:"path"},{name:"method"},{name:"type"}]}))}function s7(){yv=!0;let e=(0,ru.get)(Tg.CONFIG_PARAMS.ANALYTICS_AGGREGATEPERIOD)*1e3;e&&setInterval(async()=>{await t7(Tv,e),await dv(gg(),r7),await dv(bv(),n7)},Math.min(e/2,2147483647)).unref()}function Nv(e,t){let r=e.report;r.threadId=t?.threadId||So.threadId;for(let n of r.metrics)n.metric==="bytes-sent"&&(hv+=n.mean*n.count);r.totalBytesProcessed=hv,t&&(r.metrics.push({metric:"utilization",...t.performance.eventLoopUtilization(mv.get(t))}),mv.set(t,t.performance.eventLoopUtilization())),r.id=(0,Lf.getNextMonotonicTime)(),gg().primaryStore.put(r.id,r),yv||s7(),i7&&(Iv=a7(r))}async function a7(e){if(await Iv,!bi){let r=(0,tu.dirname)((0,eu.getLogFilePath)());try{bi=await(0,Sg.open)((0,tu.join)(r,"analytics.log"),"r+")}catch{bi=await(0,Sg.open)((0,tu.join)(r,"analytics.log"),"w+")}}let t=(await bi.stat()).size;if(t>o7){let r=Buffer.alloc(t);await bi.read(r,{position:0}),r=r.subarray(r.indexOf(10,r.length/2)+1),await bi.write(r,{position:0}),await bi.truncate(r.length),t=r.length}await bi.write(JSON.stringify(e)+`
26
- `,t)}var So,pv,eu,tu,Sg,Lf,ru,Tg,Mf,Sv,Df,Tv,gv,Rv,Av,uv,_v,Ov,r7,n7,fv,Ev,yv,hv,mv,i7,Iv,bi,o7,Bs=Re(()=>{So=require("worker_threads"),pv=B(it());Ae();eu=B(K()),tu=require("path"),Sg=require("fs/promises"),Lf=B(vr()),ru=B(te()),Tg=B(U());ur();(0,ru.initSync)();Mf=new Map,Sv=(0,ru.get)(Tg.CONFIG_PARAMS.ANALYTICS_AGGREGATEPERIOD)>-1;a(Z9,"setAnalyticsEnabled");a(wr,"recordAction");st.recordAnalytics=wr;a(Jr,"recordActionBinary");Df=0,Tv=1e3,gv="analytics-report",Rv=[];a(nu,"addAnalyticsListener");Av=[.01,.1,.25,.5,.75,.9,.95,.99,.999,1];a(e7,"sendAnalytics");a(t7,"aggregation");uv=0,_v=0,Ov=a(()=>new Promise(setImmediate),"rest");a(dv,"cleanup");r7=36e5,n7=31536e6;a(gg,"getRawAnalyticsTable");a(bv,"getAnalyticsTable");(0,pv.setChildListenerByType)(gv,Nv);a(s7,"startScheduledTasks");hv=0,mv=new Map,i7=!1;a(Nv,"recordAnalytics");o7=1e6;a(a7,"logAnalytics")});function Og(e,t,r,n,s,i,o,c){let l=e[0];if(t==="or"){let d=_(l);for(let f=1;f<e.length;f++){let h=e[f],p=_(h);d=d.concat(p)}let E=new Set;return d.filter(f=>{let h=f.key??f;return E.has(h)?!1:(E.add(h),!0)})}else{let d=_(l),E=u(e.slice(1),!0,l.estimated_count);return E.length>0?o(d,E):d}function _(d){return d.conditions?Og(d.conditions,d.operator,r,n,s,i,o,c):Ma(d,n,d.descending||s.reverse===!0,r,s.allowFullScan,c)}a(_,"executeCondition");function u(d,E,f){return d.map((h,p)=>{if(h.conditions){let R=h.operator==="or",b=u(h.conditions,!R,f);return R?(C,H)=>b.some(v=>v(C,H)):(C,H)=>b.every(v=>v(C,H))}let S=(h.attribute||h[0])===r.primaryKey,T=yg(h,r,i,c,S,f);return E&&p<d.length-1&&f&&(f=m7(r.primaryStore,h.estimated_count,f)),T}).filter(Boolean)}a(u,"mapConditionsToFilters")}function Ma(e,t,r,n,s,i){let o=e[0]??e.attribute,c=e[1]??e.value,l=e.comparator;if(Array.isArray(o)){let R=o[0],b=xs(n.attributes,R);if(b.relationship){if(o.length<2)throw new Xr.ClientError("Can not directly query a relational attribute, must query an attribute within the target table");let C=b.definition?.tableClass||b.elements?.definition?.tableClass,H=new Map,v=Ma({attribute:o.length>2?o.slice(1):o[1],value:c,comparator:l},t,r,C,s,H);if(b.relationship.to){i[o[0]]=H;let q=!!xs(C.attributes,b.relationship.to)?.elements;v=d7(v,b,C.primaryStore,q,H)}if(b.relationship.from){let q=a(M=>Ma({attribute:b.relationship.from,value:M},t,r,n,s,H),"searchEntry");b.elements?(i[o[0]]=H,v=f7(v,b,C.primaryStore,H,q)):v=v.flatMap(q)}return v}else if(o.length===1)o=o[0];else throw new Xr.ClientError("Unable to query by attribute "+JSON.stringify(o))}let _,u,d,E;c instanceof Date&&(c=c.getTime());let f;switch(bg[l]||l){case"lt":_=!0,u=c;break;case"le":_=!0,u=c,d=!0;break;case"gt":_=c,E=!0;break;case"ge":_=c;break;case"prefix":Array.isArray(c)?c[c.length-1]!=null&&(c=c.concat(null)):c=[c,null],_=c,u=c.slice(0),u[u.length-1]=ls.MAXIMUM_KEY;break;case"starts_with":_=c.toString(),u=c+"\uFFFF";break;case"between":_=c[0],_ instanceof Date&&(_=_.getTime()),u=c[1],u instanceof Date&&(u=u.getTime()),d=!0;break;case"equals":case void 0:_=c,u=c,d=!0;break;case"ne":if(c===null){_=c,E=!0;break}case"sort":case"contains":case"ends_with":_=!0,f=!0;break;default:throw new Xr.ClientError(`Unknown query comparator "${l}"`)}if(r){let R=_;_=u,u=R,R=!E,E=!d,d=R}let h=o===n.primaryKey||o==null,p=h?n.primaryStore:n.indices[o],S;if(!p||p.isIndexing||f||c===null&&!p.indexNulls){if(s===!1&&!p)throw new Xr.ClientError(`"${o}" is not indexed, can not search for this attribute`,404);if(s===!1&&f)throw new Xr.ClientError(`Can not use ${l||"equal"} operator without combining with a condition that uses an index, can not search for attribute ${o}`,403);if(p?.isIndexing)throw new Xr.ServerError(`"${o}" is not indexed yet, can not search for this attribute`,503);if(c===null&&!p.indexNulls)throw new Xr.ClientError(`"${o}" is not indexed for nulls, index needs to be rebuilt to search for nulls, can not search for this attribute`,400);if(S=yg(e),!S)throw new Xr.ClientError(`Unknown search operator ${e.comparator}`)}let T={start:_,end:u,inclusiveEnd:d,exclusiveStart:E,values:!0,versions:h,transaction:t,reverse:r};if(h){let R=p.getRange(T).map(S?function({key:b,value:C}){return this.isSync?C&&S(C)?b:yi.SKIP:new Promise((H,v)=>setImmediate(()=>{try{H(C&&S(C)?b:yi.SKIP)}catch(q){v(q)}}))}:b=>b.value==null?yi.SKIP:b);return R.hasEntries=!0,R}else return p?p.getRange(T).map(S?function({key:R,value:b}){return this.isSync?S({[o]:R})?b:yi.SKIP:new Promise((C,H)=>setImmediate(()=>{try{C(S({[o]:R})?b:yi.SKIP)}catch(v){H(v)}}))}:({value:R})=>R):n.primaryStore.getRange(r?{end:!0,transaction:t,reverse:!0}:{start:!0,transaction:t}).map(function({key:R,value:b}){return this.isSync?b&&S(b)?R:yi.SKIP:new Promise((C,H)=>setImmediate(()=>{try{C(b&&S(b)?R:yi.SKIP)}catch(v){H(v)}}))})}function xs(e,t){if(Array.isArray(t))if(t.length>1){let r=xs(e,t[0]),n=(r?.definition?.tableClass||r?.elements.definition?.tableClass)?.attributes;return n?xs(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 d7(e,t,r,n,s){return new e.constructor({[Symbol.iterator](){let i;s.hasMappings=!0;let o;return{next(){if(!i){let l=t.relationship.to,_=a((u,d)=>{let E=u;Array.isArray(u)&&(E=Bn(u),o=!0);let f=s.get(E);f?f.push(d):s.set(E,f=[d]),u!==E&&(f.key=u)},"add_entry");for(let u of e){let d=u.value??r.get(u.key??u),E=d?.[l];if(E!=null&&!s.filters?.some(f=>!f(d)))if(n)for(let f=0;f<E.length;f++)_(E[f],u);else _(E,u)}return i=(o?s:s.keys())[Symbol.iterator](),this.next()}let c=i.next();return c.done?c:{value:o?c.value[1].key||c.value[0]:c.value}}}}})}function f7(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 _=Bn(l.value);if(!c.has(_))return c.add(_),l}if(!i){let _=new Map;n.fromRecord=u=>u[t.relationship.from]?.filter?.(d=>_.has(Bn(d)));for(let u of e){if(n.filters){let d=r.get(u);if(n.filters.some(E=>!E(d)))continue}_.set(Bn(u),u)}return i=_.values()[Symbol.iterator](),this.next()}do{let _=i.next();return _.done?_:(o=s(_.value)[Symbol.iterator](),this.next())}while(!0)},return(){return o?.return?.()},throw(){return o?.throw?.()}}}})}function yg(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 u=c[0],d=xs(t.attributes,u),E=d.definition?.tableClass||d.elements.definition?.tableClass,f=n?.[u],h=yg({attribute:c.length>2?c.slice(1):c[1],value:l,comparator:o},E,r,f?.[u]?.joined,c[1]===E.primaryKey,i);if(!h)return;if(f){f.filters||(f.filters=[]),f.filters.push(h);return}let p=t.propertyResolvers?.[u],S,T=a((R,b)=>{let C,H;if(p){if(p.from&&h.idFilter){if(!S)if(h.idFilter.idSet?.size===1){for(let q of h.idFilter.idSet)e={attribute:p.from,value:q};S=_(p.from,h.idFilter,!0,!0)}else S=_(p.from,h.idFilter,!1,!0);let v=S(R);return S.idFilter&&(T.idFilter=S.idFilter),v}H=p(R,r,b),C=H?.value}else C=R[u];return C?Array.isArray(C)?C.some(h):h(C,H):!1},"recordFilter");return T}}switch(l instanceof Date&&(l=l.getTime()),bg[o]||o){case Rg.SEARCH_TYPES.EQUALS:case void 0:return _(c,u=>u===l,!0);case"contains":return _(c,u=>u?.toString().includes(l));case"ends_with":return _(c,u=>u?.toString().endsWith(l));case"starts_with":return _(c,u=>typeof u=="string"&&u.startsWith(l),!0);case"prefix":return Array.isArray(l)?l[l.length-1]==null&&(l=l.slice(0,-1)):l=[l],_(c,u=>{if(!Array.isArray(u))return!1;for(let d=0,E=l.length;d<E;d++)if(u[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()),_(c,u=>(0,ls.compareKeys)(u,l[0])>=0&&(0,ls.compareKeys)(u,l[1])<=0,!0);case"gt":return _(c,u=>(0,ls.compareKeys)(u,l)>0);case"ge":return _(c,u=>(0,ls.compareKeys)(u,l)>=0);case"lt":return _(c,u=>(0,ls.compareKeys)(u,l)<0);case"le":return _(c,u=>(0,ls.compareKeys)(u,l)<=0);case"ne":return _(c,u=>(0,ls.compareKeys)(u,l)!==0);case"sort":return()=>!0;default:throw new Xr.ClientError(`Unknown query comparator "${o}"`)}function _(u,d,E,f){let h;E=E&&!s&&t?.indices[u]&&i>3,E&&(e.estimated_count==null&&Uf(t)(e),h=e.estimated_count>>4,(isNaN(h)||h>=i)&&(E=!1));let p=0,S=3;function T(R){let b=R[u],C;if(typeof b!="object"||!b||f?C=d(b):Array.isArray(b)?C=b.some(d):b instanceof Date&&(C=d(b.getTime())),E&&(S++,!C&&!T.idFilter&&++p/S*(i-S)>h)){let H=Ma(e,r.transaction.getReadTxn(),!1,t).map(Bn),v=new Set(H);T.idFilter=q=>v.has(Bn(q)),T.idFilter.idSet=v}return C}return a(T,"recordFilter"),s&&(T.idFilter=d),T}a(_,"attributeComparator")}function Uf(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/Hs(e.primaryStore):i.estimated_count}return r.estimated_count=s,r.estimated_count}let n=r.comparator||r.search_type;if(n=bg[n]||n,n===Rg.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=xs(e.attributes,s[0]),o=i.definition?.tableClass||i.elements.definition?.tableClass,c=Uf(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*Hs(e.indices[i.relationship.from])/(Hs(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=Hs(e.primaryStore)-(i?i.getValuesCount(null):0):r.estimated_count=1/0}else n==="starts_with"||n==="prefix"?r.estimated_count=u7*Hs(e.primaryStore)+1:n==="between"?r.estimated_count=l7*Hs(e.primaryStore)+1:n==="sort"?r.estimated_count=Hs(e.primaryStore)+1:r.estimated_count=c7*Hs(e.primaryStore)+1;typeof r.descending=="boolean"&&(r.estimated_count/=2)}return r.estimated_count}return a(t,"estimateConditionForTable"),t}function vf(e){if(e)if(Ni=e,Da.lastIndex=0,E7.test(e))try{let t=iu(new La,"");if(Cr!==Ni.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 ${Cr} in '${Ni}'`,t}else{let t=new URLSearchParams(e);return t.conditions=t,t}}function iu(e,t){let r=Da,n,s,i,o,c,l=decodeURIComponent,_;for(;n=r.exec(Ni);){Cr=r.lastIndex;let[,u,d]=n;if(o){if(u)throw new SyntaxError(`expected operator, but encountered '${u}'`);o=!1,c=!1}else c=!0;let E;switch(d){case"=":if(s){if(u.length<=2)i=u;else throw new SyntaxError(`invalid FIQL operator ${u}`);l=wv}else{if(l=decodeURIComponent,i="equals",!u)throw new SyntaxError("attribute must be specified before equality comparator");s=ou(u)}break;case"==":case"!=":case"<":case"<=":case">":case">=":case"===":case"!==":if(i=_7[d],l=Ag[i]?wv:decodeURIComponent,!u)throw new SyntaxError(`attribute must be specified before comparator ${d}`);s=ou(u);break;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 h={comparator:i,attribute:s,value:l(u)};i==="eq"&&Cv(h,u),Pf(e,_),e.conditions.push(h)}d==="&"&&(_="and"),d==="|"&&(_="or"),s=void 0;break;case",":if(e.conditions)throw new SyntaxError("conditions/comparisons are not allowed in a property list");e.push(ou(u)),s=void 0;break;case"(":Da.lastIndex=Cr;let f=iu(u?[]:new La,")");switch(u){case"":Pf(e,_),e.conditions.push(f);break;case"limit":switch(f.length){case 1:e.limit=+f[0];break;case 2:e.offset=+f[0],e.limit=f[1]-e.offset;break;default:throw new SyntaxError("limit must have 1 or 2 arguments")}break;case"select":Array.isArray(f[0])&&f.length===1&&!f[0].name?(e.select=f[0],e.select.asArray=!0):f.length===1?e.select=f[0]:f.length===2&&f[1]===""?e.select=f.slice(0,1):e.select=f;break;case"group-by":throw new SyntaxError("group by is not implemented yet");case"sort":e.sort=Dv(f);break;default:throw new SyntaxError(`unknown query function call ${u}`)}Ni[Cr]===","?r.lastIndex=++Cr:o=!0,s=null;break;case"{":if(e.conditions)throw new SyntaxError("property sets are not allowed in a queries");if(!u)throw new SyntaxError("property sets must have a defined parent property name");Da.lastIndex=Cr,E=iu([],"}"),E.name=u,e.push(E),Ni[Cr]===","?r.lastIndex=++Cr:o=!0;break;case"[":Da.lastIndex=Cr,u?(E=iu(new La,"]"),E.name=u):E=iu(e.conditions?new La:[],"]"),e.conditions?(Pf(e,_),e.conditions.push(E),s=null):e.push(E),Ni[Cr]===","?r.lastIndex=++Cr:o=!0;break;case")":case"]":case"}":if(t===d[0]){if(e.conditions){if(s){let h={comparator:i||"equals",attribute:s,value:l(u)};i==="eq"&&Cv(h,u),Pf(e,_),e.conditions.push(h)}else if(u)throw new SyntaxError("no attribute or comparison specified")}else(u||e.length>0&&c)&&e.push(ou(u));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?h7:Da,r.lastIndex=Cr),Cr===Ni.length)return e}if(t)throw new SyntaxError(`expected '${t}', but encountered end of string`)}function Pf(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 ou(e){return e.indexOf(".")>-1?e.split(".").map(ou):decodeURIComponent(e)}function wv(e){if(e==="null")return null;if(e.indexOf(":")>-1){let[t,r]=e.split(":");if(t==="number")return+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 Xr.ClientError(`Unknown type ${t}`)}return decodeURIComponent(e)}function Cv(e,t){if(t.indexOf("*")>-1)if(t.endsWith("*"))e.comparator="starts_with",e.value=decodeURIComponent(t.slice(0,-1));else throw new Xr.ClientError("wildcard can only be used at the end of a string")}function Dv(e){let t=Lv(e[0]);return e.length>1&&(t.next=Dv(e.slice(1))),t}function Lv(e){if(Array.isArray(e)){let t=Lv(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 Bn(e){return Array.isArray(e)?e.join("\0"):e}function Hs(e){let t=Date.now();return(e.estimatedEntryCountExpires||0)<t&&(e.estimatedEntryCount=e.getStats().entryCount,e.estimatedEntryCountExpires=t+1e4),e.estimatedEntryCount}function m7(e,t,r){return t*r/Hs(e)}var Xr,Rg,ls,yi,c7,l7,u7,_7,Ag,bg,E7,Da,h7,Cr,Ni,La,Bf=Re(()=>{Xr=B(ne()),Rg=B(dt()),ls=require("ordered-binary"),yi=require("lmdb"),c7=.3,l7=.1,u7=.05,_7={"<":"lt","<=":"le",">":"gt",">=":"ge","!=":"ne","==":"eq","===":"equals","!==":"not_equal"},Ag={lt:!0,le:!0,gt:!0,ge:!0,ne:!0,eq:!0};a(Og,"executeConditions");a(Ma,"searchByIndex");a(xs,"findAttribute");a(d7,"joinTo");a(f7,"joinFrom");bg={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(yg,"filterByType");a(Uf,"estimateCondition");E7=/[()[\]|!<>.]|(=\w*=)/,Da=/([^?&|=<>!([{}\]),]*)([([{}\])|,&]|[=<>!]*)/g,h7=/([^&|=[\]{}]+)([[\]{}]|[&|=]*)/g;a(vf,"parseQuery");a(iu,"parseBlock");a(Pf,"assignOperator");a(ou,"decodeProperty");a(wv,"typedDecoding");a(Cv,"wildcardDecoding");a(Dv,"toSortObject");a(Lv,"toSortEntry");La=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(Bn,"flattenKey");a(Hs,"estimatedEntryCount");a(m7,"intersectionEstimate")});function Bv(e){let t={openapi:p7,info:{title:"HarperDB HTTP REST interface",version:(0,vv.version)()},paths:{},components:{schemas:{},securitySchemes:{basicAuth:{type:"http",scheme:"basic"},bearerAuth:{type:"http",scheme:"bearer",bearerFormat:"JWT"}}}},r=[{basicAuth:[],bearerAuth:[]}];for(let[,n]of e){if(!n.path)continue;let{path:s}=n,i=s.split("/").slice(-1),{attributes:o,primaryKey:c,prototype:l}=n.Resource;if(c=c??"id",!c)continue;let _={},u=[];if(o)for(let{type:b,name:C,elements:H,relationship:v,definition:q}of o){if(v)b==="array"?_[C]={type:"array",items:{$ref:Ii+H.type}}:_[C]={$ref:Ii+b};else{let M=q??H?.definition;if(M){if(!t.components.schemas[M.type]){let Q={};M.properties.forEach(J=>{Q[J.name]=new Cg(Ng[J.type],J.type)}),t.components.schemas[M.type]=new Uv(Q)}b==="array"?_[C]={type:"array",items:{$ref:Ii+M.type}}:_[C]={$ref:Ii+M.type}}else b==="array"?H.type==="Any"||H.type=="ID"?_[C]={type:"array",items:{format:H.type}}:_[C]={type:"array",items:new Cg(Ng[H.type],H.type)}:b==="Any"||b=="ID"?_[C]={format:b}:_[C]=new Cg(Ng[b],b)}u.push(new Dg(C,"query",_[C]))}let d=Object.keys(_),E=new Dg(c,"path",{format:"ID"});E.required=!0,E.description="primary key of record";let f=new Dg("property","path",{enum:d});f.required=!0,t.components.schemas[i]=new Uv(_);let h=l.post!==Resource.prototype.post||l.update,p=typeof l.put=="function",S=typeof l.get=="function",T=typeof l.delete=="function",R="/"+s+"/";h&&(t.paths[R]={},t.paths[R].post=new S7(i,r,"create a new record auto-assigning a primary key")),S&&(t.paths[R]||(t.paths[R]={}),t.paths[R].get=new Ig(u,r,{200:new wg({$ref:Ii+i})},"search for records by the specified property name and value pairs")),T&&(t.paths[R]||(t.paths[R]={}),t.paths[R].delete=new Pv(u,r,"delete all the records that match the provided query",{204:new Mv})),R="/"+s+"/{"+c+"}",S&&(t.paths[R]={},t.paths[R].get=new Ig([E],r,{200:new wg({$ref:Ii+i})},"retrieve a record by its primary key")),p&&(t.paths[R]||(t.paths[R]={}),t.paths[R].put=new T7([E],r,i,"create or update the record with the URL path that maps to the record's primary key")),T&&(t.paths[R]||(t.paths[R]={}),t.paths[R].delete=new Pv([E],r,"delete a record with the given primary key",{204:new Mv})),S&&f.schema.enum.length>0&&(R="/"+s+"/{"+c+"}.{property}",t.paths[R]={},t.paths[R].get=new Ig([E,f],r,{200:new wg({enum:d})},"used to retrieve the specified property of the specified record"))}return t}function S7(e,t,r){this.description=r,this.requestBody={content:{"application/json":{schema:{$ref:Ii+e}}}},this.security=t,this.responses={200:{description:Lg,headers:{Location:{description:"primary key of new record",schema:{type:"string",format:"ID"}}},content:{"application/json":{schema:{type:"string",format:"ID"}}}}}}function Ig(e,t,r,n){this.description=n,this.parameters=e,this.security=t,this.responses=r}function wg(e){this.description=Lg,this.content={"application/json":{schema:e}}}function Mv(){this.description="successfully processed request, no content returned to client"}function T7(e,t,r,n){this.description=n,this.parameters=e,this.security=t,this.requestBody={content:{"application/json":{schema:{$ref:Ii+r}}}},this.responses={200:{description:Lg}}}function Pv(e,t,r,n){this.description=r,this.parameters=e,this.security=t,this.responses=n}function Uv(e){this.type="object",this.properties=e}function Cg(e,t){this.type=e,this.format=t}function Dg(e,t,r){this.name=e,this.in=t,this.schema=r}var vv,p7,Ng,Ii,Lg,Hv=Re(()=>{vv=B(Cd()),p7="3.0.3",Ng={Int:"integer",Float:"number",Long:"integer",String:"string",Boolean:"boolean",Date:"string",Bytes:"string",BigInt:"integer",array:"array"},Ii="#/components/schemas/",Lg="successful operation";a(Bv,"generateJsonApi");a(S7,"Post");a(Ig,"Get");a(wg,"Response200");a(Mv,"Response204");a(T7,"Put");a(Pv,"Delete");a(Uv,"ResourceSchema");a(Cg,"Type");a(Dg,"Parameter")});var xf={};qe(xf,{start:()=>A7});async function R7(e,t){let r=e.headers.asObject,n=r.accept==="text/event-stream"?"CONNECT":e.method;e.search&&vf(e);let s=new Ri;try{e.responseHeaders=s;let i=e.url.slice(1),o,c;if(i!==xv){let h=Hf.getMatch(i);if(!h)return t(e);e.handlerPath=h.path,o={url:h.relativeURL,async:!0},c=h.Resource}let l=r["cache-control"];if(l){l=l.toLowerCase();let h=l.match(/max-age=(\d+)/)?.[1];h&&(e.expiresAt=h*1e3+Date.now()),l.includes("only-if-cached")&&(e.onlyIfCached=!0),l.includes("no-cache")&&(e.noCache=!0),l.includes("no-store")&&(e.noCacheStore=!0),l.includes("stale-if-error")&&(e.staleIfError=!0),l.includes("must-revalidate")&&(e.mustRevalidate=!0)}let _=await Je(e,()=>{if(r["content-length"]||r["transfer-encoding"])try{e.data=po(r["content-type"],!0)(e.body,e.headers)}catch(h){throw new Pa.ClientError(h,400)}if(e.authorize=!0,i===xv&&n==="GET"){if(e?.user?.role?.permission?.super_user)return Bv(Hf);throw new Pa.ServerError("Forbidden",403)}switch(n){case"GET":case"HEAD":return c.get(o,e);case"POST":return c.post(o,e.data,e);case"PUT":return c.put(o,e.data,e);case"DELETE":return c.delete(o,e);case"PATCH":return c.patch(o,e.data,e);case"OPTIONS":s.setIfNone("Allow","GET, HEAD, POST, PUT, DELETE, PATCH, OPTIONS, TRACE, QUERY, COPY, MOVE");return;case"CONNECT":return c.connect(o,null,e);case"TRACE":return"HarperDB is the terminating server";case"QUERY":return c.query(o,e.data,e);case"COPY":return c.copy(o,r.destination,e);case"MOVE":return c.move(o,r.destination,e);case"BREW":throw new Pa.ClientError("HarperDB is short and stout and can't brew coffee",418);default:throw new Pa.ServerError(`Method ${n} is not recognized`,501)}}),u=200,d;if(_==null)u=n==="GET"||n==="HEAD"?404:204,Mg.lastModified&&e.lastModified&&s.setIfNone("Last-Modified",new Date(e.lastModified).toUTCString());else if(d=e.lastModified){g7[0]=d;let h=String.fromCharCode(34,(Wt[0]&63)+62,(Wt[0]>>6)+(Wt[1]<<2&63)+62,(Wt[1]>>4)+(Wt[2]<<4&63)+62,(Wt[2]>>2)+62,(Wt[3]&63)+62,(Wt[3]>>6)+(Wt[4]<<2&63)+62,(Wt[4]>>4)+(Wt[5]<<4&63)+62,(Wt[5]>>2)+62,(Wt[6]&63)+62,(Wt[6]>>6)+(Wt[7]<<2&63)+62,34),p=r["if-none-match"];p&&h==p?(_?.onDone&&_.onDone(),u=304,_=void 0):s.setIfNone("ETag",h),Mg.lastModified&&s.setIfNone("Last-Modified",new Date(d).toUTCString())}e.createdResource&&(u=201),e.newLocation&&s.setIfNone("Location",e.newLocation);let E={status:u,headers:s,body:void 0},f=_?.wasLoadedFromSource?.();return f!==void 0&&(E.wasCacheMiss=f,!f&&d&&s.setIfNone("Age",Math.round((Date.now()-(e.lastRefreshed||d))/1e3))),_!==void 0&&(E.body=Cf(_,e,E),n==="HEAD"&&(E.body=void 0)),E}catch(i){i.statusCode?i.statusCode===500?To.warn(i):To.info(i):To.error(i),i.statusCode===405&&(i.method&&(i.message+=` to handle HTTP method ${i.method.toUpperCase()||""}`),i.allow&&(i.allow.push("trace","head","options"),s.setIfNone("Allow",i.allow.map(c=>c.toUpperCase()).join(", "))));let o={status:i.statusCode||500,headers:s,body:void 0};return o.body=Cf(i.contentType?i:i.toString(),e,o),o}}function A7(e){Mg=e,!Gv&&(Gv=!0,Hf=e.resources,e.server.http(async(t,r)=>{if(!t.isWebSocket)return R7(t,r)},e),e.server.ws(async(t,r,n)=>{au++;let s=new bn;Fv||(Fv=!0,nu(l=>{au>0&&l.push({metric:"ws-connections",connections:au,byThread:!0})}));let i;t.on("error",l=>{i=!0,To.warn(l)});let o;t.on("message",a(function(_){o||(o=po(r.headers.asObject["content-type"]));let u=o(_);s.push(u)},"message"));let c;t.on("close",()=>{au--,Jr(!i,"connection","ws","disconnect"),s.emit("close"),c&&c.return()});try{await n;let l=r.url.slice(1),_=Hf.getMatch(l);if(Jr(!!_,"connection","ws","connect"),_){r.handlerPath=_.path,wr(h=>({count:h.count,total:au}),"connections",r.handlerPath,"connect","ws"),r.authorize=!0;let u={url:_.relativeURL,async:!0},d=_.Resource;c=(await Je(r,()=>d.connect(u,s,r)))[Symbol.asyncIterator]();let f;for(;!(f=await c.next()).done;){let h=fo(f.value,r);t.send(h),wr(h.length,"bytes-sent",r.handlerPath,"message","ws")}}else return t.close(1011,`No resource was found to handle ${r.pathname}`)}catch(l){t.close(O7[l.statusCode]||1011,l.toString()),t.close("login fialed")}t.close()},e))}var To,Pa,Wt,g7,Mg,xv,Gv,Hf,Fv,au,O7,qv=Re(()=>{Oa();Bs();To=B(K()),Pa=B(ne());Bf();Rc();to();Hl();Hv();Wt=new Uint8Array(8),g7=new Float64Array(Wt.buffer,0,1),Mg={},xv="openapi";a(R7,"http");au=0;a(A7,"start");O7={401:3e3,403:3003}});var Pg=g((lhe,kv)=>{var{recordAction:Gf,recordActionBinary:b7}=(Bs(),ie(su)),y7=require("fastify-plugin"),N7=200;kv.exports=y7(function(e,t,r){e.addHook("onResponse",async(n,s)=>{let i=s.elapsedTime}),e.addHook("onSend",async(n,s,i)=>{let o=s.elapsedTime,c=performance.now(),l=s.request.routeOptions,_,u,d;l.config?.isOperation?(_=n.body?.operation,u="operation"):(_=l.url,u="fastify-route",d=l.method),Gf(o,"duration",_,d,u),b7(s.raw.statusCode<400,"success",_,d,u);let E=N7;i?.pipe?(i.on("data",S=>{E+=S.length}),i.on("end",()=>{Gf(performance.now()-c,"transfer",_,d,u),Gf(E,"bytes-sent",_,d,u)})):(E+=i?.length||0,Gf(E,"bytes-sent",_,d,u));let f=o.toFixed(3),h=s.getHeader("Server-Timing"),p=`db;dur=${f}`;s.header("Server-Timing",h?`${h}, ${p}`:p)}),r()},{name:"hdb-request-time"})});var Gg=g((dhe,Kv)=>{var Vf=require("clone"),$f=at(),I7=z(),qf=U(),uhe=K(),Ug=require("fs"),Bg=require("joi"),{string:kf}=Bg.types(),{hdb_errors:w7,handleHDBError:Ff}=ne(),{HDB_ERROR_MSGS:_he,HTTP_STATUS_CODES:vg}=w7,{common_validators:Ua}=zn(),Vv=" is required",C7=["insert","update","upsert"],Hg={database:{presence:!1,format:Ua.schema_format,length:Ua.schema_length},schema:{presence:!1,format:Ua.schema_format,length:Ua.schema_length},table:{presence:!0,format:Ua.schema_format,length:Ua.schema_length},action:{inclusion:{within:C7,message:"is required and must be either insert, update, or upsert"}},file_path:{},csv_url:{url:{allowLocal:!0}},data:{},passthrough_headers:{}},D7={schema:kf.required(),table:kf.required(),action:kf.valid("insert","update","upsert")},{AWS_ACCESS_KEY:L7,AWS_SECRET:M7,AWS_BUCKET:P7,AWS_FILE_KEY:U7,REGION:v7}=qf.S3_BUCKET_AUTH_KEYS,B7={s3:{presence:!0},[`s3.${L7}`]:{presence:!0,type:"String"},[`s3.${M7}`]:{presence:!0,type:"String"},[`s3.${P7}`]:{presence:!0,type:"String"},[`s3.${U7}`]:{presence:!0,type:"String",hasValidFileExt:[".csv",".json"]},[`s3.${v7}`]:{presence:!0,type:"String"}},$v=Vf(Hg);$v.data.presence={message:Vv};var Yv=Vf(Hg);Yv.file_path.presence={message:Vv};var H7=Object.assign(Vf(Hg),B7),xg=Vf(D7);xg.csv_url=kf.uri().messages({"string.uri":"'csv_url' must be a valid url"}).required();xg.passthrough_headers=Bg.object();function x7(e){let t=$f.validateObject(e,$v);return Yf(e,t)}a(x7,"dataObject");function G7(e){let t=$f.validateBySchema(e,Bg.object(xg));return Yf(e,t)}a(G7,"urlObject");function F7(e){let t=$f.validateObject(e,Yv);return Yf(e,t)}a(F7,"fileObject");function q7(e){let t=$f.validateObject(e,H7);return Yf(e,t)}a(q7,"s3FileObject");function Yf(e,t){if(!t){let r=I7.checkGlobalSchemaTable(e.schema,e.table);if(r)return Ff(new Error,r,vg.BAD_REQUEST);if(e.operation===qf.OPERATIONS_ENUM.CSV_FILE_LOAD)try{Ug.accessSync(e.file_path,Ug.constants.R_OK|Ug.constants.F_OK)}catch(n){return n.code===qf.NODE_ERROR_CODES.ENOENT?Ff(n,`No such file or directory ${n.path}`,vg.BAD_REQUEST):n.code===qf.NODE_ERROR_CODES.EACCES?Ff(n,`Permission denied ${n.path}`,vg.BAD_REQUEST):Ff(n)}}return t}a(Yf,"postValidateChecks");Kv.exports={dataObject:x7,urlObject:G7,fileObject:F7,s3FileObject:q7}});var Fg=g((Ehe,Wv)=>{"use strict";var cu=K(),Kf=U();async function k7(e,t,r,n=void 0){if(!e||typeof e!="function")throw new Error("Invalid function parameter");let s;try{return s=await e(t),r&&await r(t,s,n),t.operation===Kf.OPERATIONS_ENUM.INSERT||t.operation===Kf.OPERATIONS_ENUM.UPDATE||t.operation===Kf.OPERATIONS_ENUM.UPSERT?(delete s.new_attributes,delete s.txn_time):t.operation===Kf.OPERATIONS_ENUM.DELETE&&delete s.txn_time,s}catch(i){throw i.message&&typeof i.message=="string"&&i.message.includes("already exists")?(cu.info(i.message),i):i.http_resp_msg?(cu.error(`Error calling operation: ${e.name}`),cu.error(i.http_resp_msg),i):(cu.error(`Error calling operation: ${e.name}`),cu.error(i),i)}}a(k7,"callOperationFunctionAsAwait");Wv.exports={callOperationFunctionAsAwait:k7}});var zv=g((mhe,Qv)=>{"use strict";var qg=class{static{a(this,"BulkLoadFileObject")}constructor(t,r,n,s,i,o,c=null){this.op=t,this.action=r,this.schema=n,this.table=s,this.file_path=i,this.file_type=o,this.role_perms=c}},kg=class{static{a(this,"BulkLoadDataObject")}constructor(t,r,n,s){this.action=t,this.schema=r,this.table=n,this.data=s}};Qv.exports={BulkLoadFileObject:qg,BulkLoadDataObject:kg}});var Xv=g((She,Jv)=>{"use strict";var Vg=class{static{a(this,"ClusteringOriginObject")}constructor(t,r,n){this.timestamp=t,this.user=r,this.node_name=n}};Jv.exports=Vg});var zg=g((bhe,E0)=>{"use strict";var Wf=ln(),zf=Gg(),V7=require("needle"),Hn=U(),ghe=ct(),va=z(),{handleHDBError:lt,hdb_errors:o0}=ne(),{HTTP_STATUS_CODES:Qt,HDB_ERROR_MSGS:Lt,CHECK_LOGS_WRAPPER:Ro}=o0,Ba=K(),$g=require("papaparse");va.promisifyPapaParse();var xn=require("fs-extra"),$7=require("path"),{chain:jv}=require("stream-chain"),Zv=require("stream-json/streamers/StreamArray"),e0=require("stream-json/utils/Batch"),t0=require("stream-chain/utils/comp"),{finished:r0}=require("stream"),Y7=te(),a0=Fg(),K7=ug(),{BulkLoadFileObject:Kg,BulkLoadDataObject:W7}=zv(),Wg=eg(),{verifyBulkLoadAttributePerms:c0}=Af(),Rhe=Xv(),Ahe=wt(),Ohe=Rs(),{databases:Q7}=(Ae(),ie(ke)),{coerceType:z7}=(Jf(),ie(Jg)),n0="No records parsed from csv file.",go=`${Y7.get("HDB_ROOT")}/tmp`,{schema_regex:J7}=zn(),s0=1024*1024*2,i0=5e3,X7={"text/csv":!0,"application/octet-stream":!0,"text/plain":!0,"application/vnd.ms-excel":!0};E0.exports={csvDataLoad:j7,csvURLLoad:Z7,csvFileLoad:eee,importFromS3:tee};async function j7(e,t){let r=zf.dataObject(e);if(r)throw lt(r,r.message,Qt.BAD_REQUEST,void 0,void 0,!0);let n={};try{let s=_0(e.schema,e.table),i=$g.parse(e.data,{header:!0,skipEmptyLines:!0,transform:Yg.bind(null,s),dynamicTyping:!1}),o=new Wg;e.hdb_user&&e.hdb_user.role&&e.hdb_user.role.permission&&e.hdb_user.role.permission.super_user!==!0&&c0(e.hdb_user.role.permission,this.job_operation_function.name,e.action,e.schema,e.table,i.meta.fields,o);let c=o.getPermsResponse();if(c)throw lt(new Error,c,Qt.BAD_REQUEST,void 0,void 0,!0);let l=new W7(e.action,e.schema,e.table,i.data);return n=await a0.callOperationFunctionAsAwait(d0,l,null),n.message===n0?n0:f0(n.records,n.number_written)}catch(s){throw Ao(s)}}a(j7,"csvDataLoad");async function Z7(e){let t=zf.urlObject(e);if(t)throw lt(t,t.message,Qt.BAD_REQUEST,void 0,void 0,!0);let r=`${Date.now()}.csv`,n=`${go}/${r}`;try{await ree(e,r)}catch(s){throw Ba.error(Lt.DOWNLOAD_FILE_ERR(r)+" - "+s),lt(s,Ro(Lt.DOWNLOAD_FILE_ERR(r)))}try{let s=new Kg(this.job_operation_function.name,e.action,e.schema,e.table,n,Hn.VALID_S3_FILE_TYPES.CSV,e.hdb_user.role.permission),i=await Qg(s);return await Qf(n),i}catch(s){throw await Qf(n),Ao(s)}}a(Z7,"csvURLLoad");async function eee(e){let t=zf.fileObject(e);if(t)throw lt(t,t.message,Qt.BAD_REQUEST,void 0,void 0,!0);let r=new Kg(this.job_operation_function.name,e.action,e.schema,e.table,e.file_path,Hn.VALID_S3_FILE_TYPES.CSV,e.hdb_user.role.permission);try{return await Qg(r)}catch(n){throw Ao(n)}}a(eee,"csvFileLoad");async function tee(e){let t=zf.s3FileObject(e);if(t)throw lt(t,t.message,Qt.BAD_REQUEST,void 0,void 0,!0);let r;try{let n=$7.extname(e.s3.key),s=`${Date.now()}${n}`;r=`${go}/${s}`;let i=new Kg(this.job_operation_function.name,e.action,e.schema,e.table,r,n,e.hdb_user.role.permission);await nee(s,e);let o=await Qg(i);return await Qf(r),o}catch(n){throw await Qf(r),Ao(n)}}a(tee,"importFromS3");async function ree(e,t){let r;try{let n=e.passthrough_headers?{headers:e.passthrough_headers}:void 0;r=await V7("get",e.csv_url,n)}catch(n){let s=`Error downloading CSV file from ${e.csv_url}, status code: ${n.statusCode}. Check the log for more information.`;throw lt(n,s,n.statusCode,Hn.LOG_LEVELS.ERROR,"Error downloading CSV file - "+n)}iee(r,e.csv_url),await see(t,r.raw)}a(ree,"downloadCSVFile");async function nee(e,t){try{let r=`${go}/${e}`;await xn.mkdirp(go),await xn.writeFile(`${go}/${e}`,"",{flag:"a+"});let n=await xn.createWriteStream(r),s=await K7.getFileStreamFromS3(t);await new Promise((i,o)=>{s.on("error",function(c){o(c)}),s.pipe(n).on("error",function(c){o(c)}).on("close",function(){Ba.info(`${t.s3.key} successfully downloaded to ${r}`),i()})})}catch(r){throw Ba.error(Lt.S3_DOWNLOAD_ERR+" - "+r),lt(r,Ro(Lt.S3_DOWNLOAD_ERR))}}a(nee,"downloadFileFromS3");async function see(e,t){try{await xn.mkdirp(go),await xn.writeFile(`${go}/${e}`,t)}catch(r){throw Ba.error(Lt.WRITE_TEMP_FILE_ERR),lt(r,Ro(Lt.DEFAULT_BULK_LOAD_ERR))}}a(see,"writeFileToTempFolder");async function Qf(e){if(e)try{await xn.access(e),await xn.unlink(e)}catch{Ba.warn(`could not delete temp csv file at ${e}, file does not exist`)}}a(Qf,"deleteTempFile");function iee(e,t){if(e.statusCode!==o0.HTTP_STATUS_CODES.OK)throw lt(new Error,`CSV Load failed from URL: ${t}, status code: ${e.statusCode}, message: ${e.statusMessage}`,Qt.BAD_REQUEST);if(!X7[e.headers["content-type"]])throw lt(new Error,`CSV Load failed from URL: ${t}, unsupported content type: ${e.headers["content-type"]}`,Qt.BAD_REQUEST);if(!e.raw)throw lt(new Error,`CSV Load failed from URL: ${t}, no csv found at url`,Qt.BAD_REQUEST)}a(iee,"validateURLResponse");async function Qg(e){try{let t;switch(e.file_type){case Hn.VALID_S3_FILE_TYPES.CSV:t=await oee(e);break;case Hn.VALID_S3_FILE_TYPES.JSON:t=await aee(e);break;default:throw lt(new Error,Lt.DEFAULT_BULK_LOAD_ERR,Qt.BAD_REQUEST,Hn.LOG_LEVELS.ERROR,Lt.INVALID_FILE_EXT_ERR(e))}return f0(t.records,t.number_written)}catch(t){throw Ao(t)}}a(Qg,"fileLoad");async function l0(e,t,r,n,s){let i=n.data?n.data:n;if(i.length===0)return;s&&s.pause();let o={operation:e.action,schema:e.schema,table:e.table,records:i};try{let{attributes:c}=await Wf.validation(o);e.role_perms&&e.role_perms.super_user!==!0&&c0(e.role_perms,e.op,e.action,e.schema,e.table,c,t),s&&s.resume()}catch(c){let l=lt(c);r(l)}}a(l0,"validateChunk");async function u0(e,t,r,n,s){let i=n.data?n.data:n;if(i.length===0)return;va.autoCastJSONDeep(i),s&&s.pause();let o=n.meta?n.meta.fields:null;if(o)i.forEach(c=>{!va.isEmpty(c)&&!va.isEmpty(c.__parsed_extra)&&delete c.__parsed_extra});else{let c=new Set;i.forEach(l=>{Object.keys(l).forEach(_=>c.add(_))}),o=[...c]}try{let c={schema:e.schema,table:e.table,action:e.action,data:i},l=await a0.callOperationFunctionAsAwait(d0,c,null);t.records+=l.records,t.number_written+=l.number_written,s&&s.resume()}catch(c){let l=lt(c,Ro(Lt.INSERT_CSV_ERR),Qt.INTERNAL_SERVER_ERROR,Hn.LOG_LEVELS.ERROR,Lt.INSERT_CSV_ERR+" - "+c);r(l)}}a(u0,"insertChunk");async function oee(e){let t={records:0,number_written:0},r=_0(e.schema,e.table);try{let n=new Wg,s=xn.createReadStream(e.file_path,{highWaterMark:s0});s.setEncoding("utf8"),await $g.parsePromise(s,l0.bind(null,e,n),Yg.bind(null,r));let i=n.getPermsResponse();if(i)throw lt(new Error,i,Qt.BAD_REQUEST);return s=xn.createReadStream(e.file_path,{highWaterMark:s0}),s.setEncoding("utf8"),await $g.parsePromise(s,u0.bind(null,e,t),Yg.bind(null,r)),s.destroy(),t}catch(n){throw lt(n,Ro(Lt.PAPA_PARSE_ERR),Qt.INTERNAL_SERVER_ERROR,Hn.LOG_LEVELS.ERROR,Lt.PAPA_PARSE_ERR+n)}}a(oee,"callPapaParse");function _0(e,t){let r=Q7[e][t].attributes,n=new Map;for(let s of r)s.type&&n.set(s.name,i=>z7(i,s));return n}a(_0,"createTransformMap");function Yg(e,t,r){let n=e.get(r);return n?n(t):va.autoCast(t)}a(Yg,"typeFunction");async function aee(e){let t={records:0,number_written:0},r=a(n=>{throw n},"throwErr");try{let n=new Wg,s=jv([xn.createReadStream(e.file_path,{encoding:"utf-8"}),Zv.withParser(),c=>c.value,new e0({batchSize:i0}),t0(async c=>{await l0(e,n,r,c)})]);await new Promise((c,l)=>{r0(s,_=>{_?l(_):c()}),s.resume()});let i=n.getPermsResponse();if(i)throw lt(new Error,i,Qt.BAD_REQUEST);let o=jv([xn.createReadStream(e.file_path,{encoding:"utf-8"}),Zv.withParser(),c=>c.value,new e0({batchSize:i0}),t0(async c=>{await u0(e,t,r,c)})]);return await new Promise((c,l)=>{r0(o,_=>{_?l(_):c()}),o.resume()}),t}catch(n){throw lt(n,Ro(Lt.INSERT_JSON_ERR),Qt.INTERNAL_SERVER_ERROR,Hn.LOG_LEVELS.ERROR,Lt.INSERT_JSON_ERR+n)}}a(aee,"insertJson");async function d0(e){let t={};try{e.data&&e.data.length>0&&cee(e.data[0])?t=await lee(e.data,e.schema,e.table,e.action):(t.message="No records parsed from csv file.",Ba.info(t.message))}catch(r){throw Ao(r)}return t}a(d0,"callBulkFileLoad");function cee(e){let t=Object.keys(e);for(let r of t)if(!J7.test(r))throw new Error(`Invalid column name '${r}', cancelling load operation`);return!0}a(cee,"validateColumnNames");async function lee(e,t,r,n){n||(n="insert");let s={operation:n,schema:t,table:r,records:e},i;switch(n){case"insert":i=Wf.insert;break;case"update":i=Wf.update;break;case"upsert":i=Wf.upsert;break;default:throw lt(new Error,Lt.INVALID_ACTION_PARAM_ERR(n),Qt.BAD_REQUEST,Hn.LOG_LEVELS.ERROR,Lt.INVALID_ACTION_PARAM_ERR(n))}try{let o=await i(s),c;switch(n){case"insert":c=o.inserted_hashes;break;case"update":c=o.update_hashes;break;case"upsert":c=o.upserted_hashes;break;default:break}if(Array.isArray(o.skipped_hashes)&&o.skipped_hashes.length>0){let u=global.hdb_schema[t][r].hash_attribute,d=e.length;for(;d--;)o.skipped_hashes.indexOf(e[d][u])>=0&&e.splice(d,1)}let l=va.isEmptyOrZeroLength(c)?0:c.length;return{records:e.length,number_written:l,new_attributes:o.new_attributes}}catch(o){throw Ao(o)}}a(lee,"bulkFileLoad");function f0(e,t){return`successfully loaded ${t} of ${e} records`}a(f0,"buildResponseMsg");function Ao(e){return lt(e,Ro(Lt.DEFAULT_BULK_LOAD_ERR),Qt.INTERNAL_SERVER_ERROR,Hn.LOG_LEVELS.ERROR,Lt.DEFAULT_BULK_LOAD_ERR+" - "+e)}a(Ao,"buildTopLevelErrMsg")});var m0=g((Nhe,h0)=>{"use strict";var Xg=class{static{a(this,"SqlSearchObject")}constructor(t,r){this.operation="sql",this.sql=t,this.hdb_user=r}};h0.exports=Xg});var T0=g((whe,S0)=>{"use strict";var uee=U(),p0=require("moment"),_ee=require("uuid").v4,jg=class{static{a(this,"JobObject")}constructor(){this.id=_ee(),this.type=void 0,this.start_datetime=p0().valueOf(),this.created_datetime=p0().valueOf(),this.end_datetime=void 0,this.status=uee.JOB_STATUS_ENUM.CREATED,this.message=void 0,this.user=void 0,this.request=void 0}};S0.exports=jg});var Zg=g((Dhe,I0)=>{"use strict";var dee=require("uuid").v4,b0=ln(),y0=Gr(),fee=es(),Eee=ra(),hee=m0(),Xe=U(),mee=T0(),pee=IS(),pn=K(),See=Hc(),Ha=z(),{promisify:Tee}=require("util"),Oo=require("moment"),gee=bf(),Xf=Gg(),g0=Bm(),{deleteTransactionLogsBeforeValidator:Ree}=zT(),{handleHDBError:R0,hdb_errors:Aee}=ne(),{HTTP_STATUS_CODES:A0}=Aee,O0=y0.searchByValue,Oee=y0.searchByHash,bee=b0.insert,yee=Tee(gee.evaluateSQL),Nee=b0.update;I0.exports={addJob:Cee,updateJob:Lee,handleGetJob:Iee,handleGetJobsByStartDate:wee,getJobById:N0};async function Iee(e){try{let t=await N0(e.id);return Ha.isEmptyOrZeroLength(t)||(t[0]={...t[0]},t[0].request!==void 0&&delete t[0].request,delete t[0].__createdtime__,delete t[0].__updatedtime__),t}catch(t){let r=`There was an error getting job: ${t}`;throw pn.error("There was an error getting job",t),new Error(r)}}a(Iee,"handleGetJob");async function wee(e){try{let t=await Dee(e);if(pn.trace(`Searching for jobs from ${e.from_date} to ${e.to_date}`),t&&t.length>0)for(let r of t)r.start_datetime&&(r.start_datetime_converted=Oo(r.start_datetime)),r.end_datetime&&(r.end_datetime_converted=Oo(r.end_datetime)),r.request!==void 0&&delete r.request,delete r.__createdtime__,delete r.__updatedtime__;return t}catch(t){let r=`There was an error searching jobs by date: ${t}`;throw pn.error(r),new Error(r)}}a(wee,"handleGetJobsByStartDate");async function Cee(e){let t={message:"",error:"",success:!1,createdJob:void 0};if(!e||Object.keys(e).length===0||Ha.isEmptyOrZeroLength(e.operation)){let u="job parameter is invalid";return pn.info(u),t.error=u,t}if(!Xe.JOB_TYPE_ENUM[e.operation])return pn.info(`invalid job type specified: ${e.operation}.`),t;let r=e.operation,n;switch(r){case Xe.OPERATIONS_ENUM.CSV_FILE_LOAD:n=Xf.fileObject(e);break;case Xe.OPERATIONS_ENUM.CSV_URL_LOAD:n=Xf.urlObject(e);break;case Xe.OPERATIONS_ENUM.CSV_DATA_LOAD:n=Xf.dataObject(e);break;case Xe.OPERATIONS_ENUM.IMPORT_FROM_S3:n=Xf.s3FileObject(e);break;case Xe.OPERATIONS_ENUM.DELETE_FILES_BEFORE:case Xe.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE:n=g0(e,"date");break;case Xe.OPERATIONS_ENUM.DELETE_AUDIT_LOGS_BEFORE:n=g0(e,"timestamp");break;case Xe.OPERATIONS_ENUM.DELETE_TRANSACTION_LOGS_BEFORE:n=Ree(e);break;case Xe.OPERATIONS_ENUM.RESTART_SERVICE:if(Xe.PROCESS_DESCRIPTORS_VALIDATE[e.service]===void 0)throw R0(new Error,"Invalid service",A0.BAD_REQUEST,void 0,void 0,!0);break;default:break}if(n)throw R0(n,n.message,A0.BAD_REQUEST,void 0,void 0,!0);let s=new mee;s.type=e.operation===Xe.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE?Xe.OPERATIONS_ENUM.DELETE_FILES_BEFORE:e.operation,s.type=e.operation,s.user=e.hdb_user.username;let i=new fee(Xe.SYSTEM_SCHEMA_NAME,Xe.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,"id",s.id,"id",["id"]),o;try{o=Array.from(await O0(i))}catch(u){let d=`There was an error inserting a new job: ${u}`;return pn.error(d),t}let c=Array.isArray(o)?o:Object.keys(o);if(c&&c.length>0){s.id=dee();try{o=await O0(i)}catch(u){let d=`There was an error inserting a new job: ${u}`;return pn.error(d),t}if(c=Array.isArray(o)?o:Object.keys(o),c&&c.length>0)return pn.error("Error creating a job, could not find a unique job id."),t}s.request=e;let l=new See(Xe.SYSTEM_SCHEMA_NAME,Xe.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,"id",[s]),_;try{_=await bee(l)}catch(u){return pn.error(`There was an error inserting a job for job type: ${e.operation} -- ${u}`),t.success=!1,t}if(_.inserted_hashes.length===0)t.message=`Had a problem creating a job with type ${s.operation} and id ${s.id}`;else{let u=`Created a job with type ${s.type} and id ${s.id}`;t.message=u,t.createdJob=s,t.success=!0,pn.trace(u)}return t}a(Cee,"addJob");async function Dee(e){let t=Oo(e.from_date,Oo.ISO_8601),r=Oo(e.to_date,Oo.ISO_8601);if(!t.isValid())throw new Error("Invalid 'from' date, must be in ISO-8601 format (YYYY-MM-DD).");if(!r.isValid())throw new Error("Invalid 'to' date, must be in ISO-8601 format (YYYY-MM-DD)");let n=`select * from system.hdb_job where start_datetime > '${t.valueOf()}' and start_datetime < '${r.valueOf()}'`,s=new hee(n,e.hdb_user);try{return await yee(s)}catch(i){throw pn.error(`there was a problem searching for jobs from date ${e.from_date} to date ${e.to_date} ${i}`),new Error("there was an error searching for jobs. Please check the log for details.")}}a(Dee,"getJobsInDateRange");async function N0(e){if(Ha.isEmptyOrZeroLength(e))return Ha.errorizeMessage("Invalid job ID specified.");let t=new Eee(Xe.SYSTEM_SCHEMA_NAME,Xe.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,[e],["*"]);try{return await Oee(t)}catch(r){let n=`There was an error searching for a job by id: ${e} ${r}`;return pn.error(n),Ha.errorizeMessage("there was an error searching for jobs. Please check the log for details.")}}a(N0,"getJobById");async function Lee(e){if(Object.keys(e).length===0)throw new Error("invalid job object passed to updateJob");if(Ha.isEmptyOrZeroLength(e.id))throw new Error("invalid ID passed to updateJob");(e.status===Xe.JOB_STATUS_ENUM.COMPLETE||e.status===Xe.JOB_STATUS_ENUM.ERROR)&&(e.end_datetime=Oo().valueOf());let t=new pee(Xe.SYSTEM_SCHEMA_NAME,Xe.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,[e]),r;return r=await Nee(t),r}a(Lee,"updateJob")});var v0=g((Mhe,U0)=>{"use strict";var w0=z(),Mt=U(),Mee=require("moment"),jf=zg(),lu=K(),C0=Zg(),D0=yf(),L0=Yi(),M0=it(),Pee=Sf(),Uee=Ul(),{parentPort:vee,isMainThread:P0}=require("worker_threads"),{onMessageByType:Bee}=it(),eR=class{static{a(this,"RunnerMessage")}constructor(t,r){this.job=t,this.json=r}};async function Hee(e){if(!e||Object.keys(e).length===0)throw new Error("Empty runner passed to parseMessage");if(!e.json||Object.keys(e.json).length===0)throw new Error("Empty JSON passed to parseMessage");if(!e.job||Object.keys(e.job).length===0)throw new Error("Empty job passed to parseMessage");if(w0.isEmptyOrZeroLength(e.json.operation))throw new Error("Invalid operation");if(w0.isEmptyOrZeroLength(e.job.id))throw new Error("Empty job id specified");switch(e.json.operation){case Mt.JOB_TYPE_ENUM.csv_file_load:await us(e,jf.csvFileLoad);break;case Mt.JOB_TYPE_ENUM.csv_url_load:await us(e,jf.csvURLLoad);break;case Mt.JOB_TYPE_ENUM.csv_data_load:await us(e,jf.csvDataLoad);break;case Mt.JOB_TYPE_ENUM.import_from_s3:await us(e,jf.importFromS3);break;case Mt.JOB_TYPE_ENUM.empty_trash:break;case Mt.JOB_TYPE_ENUM.export_local:await us(e,D0.export_local);break;case Mt.JOB_TYPE_ENUM.export_to_s3:await us(e,D0.export_to_s3);break;case Mt.JOB_TYPE_ENUM.delete_files_before:case Mt.JOB_TYPE_ENUM.delete_records_before:await us(e,L0.deleteFilesBefore);break;case Mt.JOB_TYPE_ENUM.delete_audit_logs_before:await us(e,L0.deleteAuditLogsBefore);break;case Mt.JOB_TYPE_ENUM.delete_transaction_logs_before:await us(e,Pee.deleteTransactionLogsBefore);break;case Mt.JOB_TYPE_ENUM.restart_service:return await us(e,Uee.restartService),`Restarting ${e.json.service}`;break;default:return`Invalid operation ${e.json.operation} specified`}}a(Hee,"parseMessage");async function us(e,t){try{e.job.status=Mt.JOB_STATUS_ENUM.IN_PROGRESS,e.job.start_datetime=Mee().valueOf(),await C0.updateJob(e.job),await xee(e.job.id)}catch(r){let n=r.message!==void 0?r.message:r;typeof n=="string"?(n=`There was an error running ${t.name} job with id ${e.job.id} - ${n}`,r.message=n):lu.error(`There was an error running ${t.name} job with id ${e.job.id}`),lu.error(n),e.job.message=n,e.job.status=Mt.JOB_STATUS_ENUM.ERROR;try{await C0.updateJob(e.job)}catch(s){throw lu.error(`Unable to update job with id ${e.job.id}`),s}throw r}}a(us,"runJob");async function xee(e){lu.trace("launching job thread:",e),P0?M0.startWorker("server/jobs/jobProcess.js",{autoRestart:!1,name:"job",env:Object.assign({},process.env,{[Mt.PROCESS_NAME_ENV_PROP]:`JOB-${e}`})}):vee.postMessage({type:Mt.ITC_EVENT_TYPES.START_JOB,jobId:e})}a(xee,"launchJobThread");P0&&Bee(Mt.ITC_EVENT_TYPES.START_JOB,async(e,t)=>{try{M0.startWorker("server/jobs/jobProcess.js",{autoRestart:!1,name:"job",env:Object.assign({},process.env,{[Mt.PROCESS_NAME_ENV_PROP]:`JOB-${e.jobId}`})})}catch(r){lu.error(r)}});U0.exports={parseMessage:Hee,RunnerMessage:eR}});var H0=g((Uhe,B0)=>{"use strict";var tR=class{static{a(this,"OperationFunctionObject")}constructor(t,r=void 0){this.operation_function=t,this.job_operation_function=r}};B0.exports=tR});var eB=g((Bhe,aR)=>{"use strict";var nE=Gr(),sR=bf(),Zf=zg(),Gs=pd(),eE=ri(),_u=Yi(),Gee=dS(),uu=un(),tE=RS(),zt=QT(),rE=K(),Fee=bS(),qee=vd(),x0=sT(),kee=Hd(),Vee=oT(),$ee=aT(),Yee=uT(),Kee=dT(),rR=hT(),G0=yf(),Wee=Af(),iR=Zg(),F=U(),{hdb_errors:fu,handleHDBError:du}=ne(),{HTTP_STATUS_CODES:F0}=fu,nR=gT(),q0=Ul(),J0=require("util"),xa=ln(),Qee=ni(),zee=Ea(),k0=v0(),V0=dl(),$0=(cf(),ie(xl)),Y0=Er(),K0=Sf(),W0=ff(),{setServerUtilities:Jee}=(Jf(),ie(Jg)),{CONTEXT:Xee}=(yn(),ie(Cp)),{_assignPackageExport:jee}=require("../index"),{transformReq:Zee}=z(),{server:ete}=(ur(),ie(vi)),ir=rE.loggerWithTag("operation"),tte=Fg(),Q0=nE.searchByHash,rte=nE.searchByValue,nte=J0.promisify(nE.search),ste=J0.promisify(sR.evaluateSQL),ite={[F.OPERATIONS_ENUM.CREATE_ATTRIBUTE]:!0,[F.OPERATIONS_ENUM.CREATE_TABLE]:!0,[F.OPERATIONS_ENUM.CREATE_SCHEMA]:!0,[F.OPERATIONS_ENUM.DROP_ATTRIBUTE]:!0,[F.OPERATIONS_ENUM.DROP_TABLE]:!0,[F.OPERATIONS_ENUM.DROP_SCHEMA]:!0},$=H0();async function X0(e,t){try{if(e.body.operation!=="read_log"&&(rE.log_level===F.LOG_LEVELS.INFO||rE.log_level===F.LOG_LEVELS.DEBUG||rE.log_level===F.LOG_LEVELS.TRACE)){let{hdb_user:n,hdb_auth_header:s,password:i,...o}=e.body;ir.info(o)}}catch(n){ir.error(n)}let r=await tte.callOperationFunctionAsAwait(t,e.body,null);if(typeof r!="object"&&(r={message:r}),r instanceof Error)throw r;return ite[e.body.operation]&&Qee.setSchemaDataToGlobal(n=>{n&&ir.error(n)}),r}a(X0,"processLocalTransaction");var z0=ate();aR.exports={chooseOperation:j0,getOperationFunction:Z0,operation:oR,processLocalTransaction:X0};Jee(aR.exports);ete.operation=oR;function j0(e){let t;try{t=Z0(e)}catch(s){throw ir.error(`Error when selecting operation function - ${s}`),s}let{operation_function:r,job_operation_function:n}=t;try{if(e.operation==="sql"||e.search_operation&&e.search_operation.operation==="sql"){let s=e.operation==="sql"?e.sql:e.search_operation.sql,i=sR.convertSQLToAST(s);if(e.parsed_sql_object=i,!e.bypass_auth){let o=sR.checkASTPermissions(e,i);if(o)throw ir.error(`${F0.FORBIDDEN} from operation ${e.operation}`),ir.warn(`User '${e.hdb_user.username}' is not permitted to ${e.operation}`),du(new Error,o,fu.HTTP_STATUS_CODES.FORBIDDEN,void 0,void 0,!0)}}else if(!e.bypass_auth&&e.operation!==F.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS&&e.operation!==F.OPERATIONS_ENUM.LOGIN&&e.operation!==F.OPERATIONS_ENUM.LOGOUT){let s=n===void 0?r:n,i=e.search_operation?e.search_operation:e;i.hdb_user||(i.hdb_user=e.hdb_user);let o=Wee.verifyPerms(i,s);if(o)throw ir.error(`${F0.FORBIDDEN} from operation ${e.operation}`),ir.warn(`User '${i.hdb_user.username}' is not permitted to ${i.operation}`),du(new Error,o,fu.HTTP_STATUS_CODES.FORBIDDEN,void 0,!1,!0)}}catch(s){throw du(s,"There was an error when trying to choose an operation path")}return r}a(j0,"chooseOperation");function Z0(e){if(ir.trace(`getOperationFunction with operation: ${e.operation}`),z0.has(e.operation))return z0.get(e.operation);throw du(new Error,fu.HDB_ERROR_MSGS.OP_NOT_FOUND(e.operation),fu.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0)}a(Z0,"getOperationFunction");jee("operation",oR);function oR(e,t){e.hdb_user=this[Xee]?.user,e.bypass_auth=!t;let r=j0(e);return X0({body:e},r)}a(oR,"operation");async function ote(e){ir.trace("In serverUtils.catchup");let t=e.transaction,r=t.channel.split(":"),n=r[0],s=r[1];for(let i of t.transactions)try{i.schema=n,i.table=s,i[F.CLUSTERING_FLAG]=!0;let o;switch(i.operation){case F.OPERATIONS_ENUM.INSERT:o=await xa.insert(i);break;case F.OPERATIONS_ENUM.UPDATE:o=await xa.update(i);break;case F.OPERATIONS_ENUM.UPSERT:o=await xa.upsert(i);break;case F.OPERATIONS_ENUM.DELETE:o=await _u.deleteRecord(i);break;default:ir.warn("invalid operation in catchup");break}await transact_to_clustering_utils.postOperationHandler(i,o,e)}catch(o){ir.info("Invalid operation in transaction"),ir.error(o)}}a(ote,"catchup");async function Gn(e){Zee(e);let t,r;try{r=await iR.addJob(e),t=r.createdJob,ir.info("addJob result",r);let n=new k0.RunnerMessage(t,e);return{message:await k0.parseMessage(n)??`Starting job with id ${t.id}`,job_id:t.id}}catch(n){let s=`There was an error executing job: ${n.http_resp_msg?n.http_resp_msg:n}`;throw ir.error(s),du(n,s)}}a(Gn,"executeJob");function ate(){let e=new Map;return e.set(F.OPERATIONS_ENUM.INSERT,new $(xa.insert)),e.set(F.OPERATIONS_ENUM.UPDATE,new $(xa.update)),e.set(F.OPERATIONS_ENUM.UPSERT,new $(xa.upsert)),e.set(F.OPERATIONS_ENUM.SEARCH_BY_CONDITIONS,new $(nE.searchByConditions)),e.set(F.OPERATIONS_ENUM.SEARCH_BY_HASH,new $(Q0)),e.set(F.OPERATIONS_ENUM.SEARCH_BY_ID,new $(Q0)),e.set(F.OPERATIONS_ENUM.SEARCH_BY_VALUE,new $(rte)),e.set(F.OPERATIONS_ENUM.SEARCH,new $(nte)),e.set(F.OPERATIONS_ENUM.SQL,new $(ste)),e.set(F.OPERATIONS_ENUM.CSV_DATA_LOAD,new $(Gn,Zf.csvDataLoad)),e.set(F.OPERATIONS_ENUM.CSV_FILE_LOAD,new $(Gn,Zf.csvFileLoad)),e.set(F.OPERATIONS_ENUM.CSV_URL_LOAD,new $(Gn,Zf.csvURLLoad)),e.set(F.OPERATIONS_ENUM.IMPORT_FROM_S3,new $(Gn,Zf.importFromS3)),e.set(F.OPERATIONS_ENUM.CREATE_SCHEMA,new $(Gs.createSchema)),e.set(F.OPERATIONS_ENUM.CREATE_DATABASE,new $(Gs.createSchema)),e.set(F.OPERATIONS_ENUM.CREATE_TABLE,new $(Gs.createTable)),e.set(F.OPERATIONS_ENUM.CREATE_ATTRIBUTE,new $(Gs.createAttribute)),e.set(F.OPERATIONS_ENUM.DROP_SCHEMA,new $(Gs.dropSchema)),e.set(F.OPERATIONS_ENUM.DROP_DATABASE,new $(Gs.dropSchema)),e.set(F.OPERATIONS_ENUM.DROP_TABLE,new $(Gs.dropTable)),e.set(F.OPERATIONS_ENUM.DROP_ATTRIBUTE,new $(Gs.dropAttribute)),e.set(F.OPERATIONS_ENUM.DESCRIBE_SCHEMA,new $(eE.describeSchema)),e.set(F.OPERATIONS_ENUM.DESCRIBE_DATABASE,new $(eE.describeSchema)),e.set(F.OPERATIONS_ENUM.DESCRIBE_TABLE,new $(eE.describeTable)),e.set(F.OPERATIONS_ENUM.DESCRIBE_ALL,new $(eE.describeAll)),e.set(F.OPERATIONS_ENUM.DELETE,new $(_u.deleteRecord)),e.set(F.OPERATIONS_ENUM.ADD_USER,new $(uu.addUser)),e.set(F.OPERATIONS_ENUM.ALTER_USER,new $(uu.alterUser)),e.set(F.OPERATIONS_ENUM.DROP_USER,new $(uu.dropUser)),e.set(F.OPERATIONS_ENUM.LIST_USERS,new $(uu.listUsersExternal)),e.set(F.OPERATIONS_ENUM.LIST_ROLES,new $(tE.listRoles)),e.set(F.OPERATIONS_ENUM.ADD_ROLE,new $(tE.addRole)),e.set(F.OPERATIONS_ENUM.ALTER_ROLE,new $(tE.alterRole)),e.set(F.OPERATIONS_ENUM.DROP_ROLE,new $(tE.dropRole)),e.set(F.OPERATIONS_ENUM.USER_INFO,new $(uu.userInfo)),e.set(F.OPERATIONS_ENUM.READ_LOG,new $(Fee)),e.set(F.OPERATIONS_ENUM.ADD_NODE,new $(qee)),e.set(F.OPERATIONS_ENUM.UPDATE_NODE,new $(x0)),e.set(F.OPERATIONS_ENUM.SET_NODE_REPLICATION,new $(x0)),e.set(F.OPERATIONS_ENUM.REMOVE_NODE,new $(kee)),e.set(F.OPERATIONS_ENUM.CONFIGURE_CLUSTER,new $(Vee)),e.set(F.OPERATIONS_ENUM.PURGE_STREAM,new $($ee)),e.set(F.OPERATIONS_ENUM.SET_CONFIGURATION,new $(Y0.setConfiguration)),e.set(F.OPERATIONS_ENUM.CLUSTER_STATUS,new $(Yee.clusterStatus)),e.set(F.OPERATIONS_ENUM.CLUSTER_NETWORK,new $(Kee)),e.set(F.OPERATIONS_ENUM.CLUSTER_SET_ROUTES,new $(rR.setRoutes)),e.set(F.OPERATIONS_ENUM.CLUSTER_GET_ROUTES,new $(rR.getRoutes)),e.set(F.OPERATIONS_ENUM.CLUSTER_DELETE_ROUTES,new $(rR.deleteRoutes)),e.set(F.OPERATIONS_ENUM.EXPORT_TO_S3,new $(Gn,G0.export_to_s3)),e.set(F.OPERATIONS_ENUM.DELETE_FILES_BEFORE,new $(Gn,_u.deleteFilesBefore)),e.set(F.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE,new $(Gn,_u.deleteFilesBefore)),e.set(F.OPERATIONS_ENUM.EXPORT_LOCAL,new $(Gn,G0.export_local)),e.set(F.OPERATIONS_ENUM.SEARCH_JOBS_BY_START_DATE,new $(iR.handleGetJobsByStartDate)),e.set(F.OPERATIONS_ENUM.GET_JOB,new $(iR.handleGetJob)),e.set(F.OPERATIONS_ENUM.GET_FINGERPRINT,new $(nR.getFingerprint)),e.set(F.OPERATIONS_ENUM.SET_LICENSE,new $(nR.setLicense)),e.set(F.OPERATIONS_ENUM.GET_REGISTRATION_INFO,new $(nR.getRegistrationInfo)),e.set(F.OPERATIONS_ENUM.RESTART,new $(q0.restart)),e.set(F.OPERATIONS_ENUM.RESTART_SERVICE,new $(Gn,q0.restartService)),e.set(F.OPERATIONS_ENUM.CATCHUP,new $(ote)),e.set(F.OPERATIONS_ENUM.SYSTEM_INFORMATION,new $(zee.systemInformation)),e.set(F.OPERATIONS_ENUM.DELETE_AUDIT_LOGS_BEFORE,new $(Gn,_u.deleteAuditLogsBefore)),e.set(F.OPERATIONS_ENUM.READ_AUDIT_LOG,new $(Gee)),e.set(F.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS,new $(V0.createTokens)),e.set(F.OPERATIONS_ENUM.REFRESH_OPERATION_TOKEN,new $(V0.refreshOperationToken)),e.set(F.OPERATIONS_ENUM.LOGIN,new $($0.login)),e.set(F.OPERATIONS_ENUM.LOGOUT,new $($0.logout)),e.set(F.OPERATIONS_ENUM.GET_CONFIGURATION,new $(Y0.getConfiguration)),e.set(F.OPERATIONS_ENUM.CUSTOM_FUNCTIONS_STATUS,new $(zt.customFunctionsStatus)),e.set(F.OPERATIONS_ENUM.GET_CUSTOM_FUNCTIONS,new $(zt.getCustomFunctions)),e.set(F.OPERATIONS_ENUM.GET_COMPONENT_FILE,new $(zt.getComponentFile)),e.set(F.OPERATIONS_ENUM.GET_COMPONENTS,new $(zt.getComponents)),e.set(F.OPERATIONS_ENUM.SET_COMPONENT_FILE,new $(zt.setComponentFile)),e.set(F.OPERATIONS_ENUM.DROP_COMPONENT,new $(zt.dropComponent)),e.set(F.OPERATIONS_ENUM.GET_CUSTOM_FUNCTION,new $(zt.getCustomFunction)),e.set(F.OPERATIONS_ENUM.SET_CUSTOM_FUNCTION,new $(zt.setCustomFunction)),e.set(F.OPERATIONS_ENUM.DROP_CUSTOM_FUNCTION,new $(zt.dropCustomFunction)),e.set(F.OPERATIONS_ENUM.ADD_CUSTOM_FUNCTION_PROJECT,new $(zt.addComponent)),e.set(F.OPERATIONS_ENUM.ADD_COMPONENT,new $(zt.addComponent)),e.set(F.OPERATIONS_ENUM.DROP_CUSTOM_FUNCTION_PROJECT,new $(zt.dropCustomFunctionProject)),e.set(F.OPERATIONS_ENUM.PACKAGE_CUSTOM_FUNCTION_PROJECT,new $(zt.packageComponent)),e.set(F.OPERATIONS_ENUM.PACKAGE_COMPONENT,new $(zt.packageComponent)),e.set(F.OPERATIONS_ENUM.DEPLOY_CUSTOM_FUNCTION_PROJECT,new $(zt.deployComponent)),e.set(F.OPERATIONS_ENUM.DEPLOY_COMPONENT,new $(zt.deployComponent)),e.set(F.OPERATIONS_ENUM.READ_TRANSACTION_LOG,new $(K0.readTransactionLog)),e.set(F.OPERATIONS_ENUM.DELETE_TRANSACTION_LOGS_BEFORE,new $(Gn,K0.deleteTransactionLogsBefore)),e.set(F.OPERATIONS_ENUM.INSTALL_NODE_MODULES,new $(W0.installModules)),e.set(F.OPERATIONS_ENUM.AUDIT_NODE_MODULES,new $(W0.auditModules)),e.set(F.OPERATIONS_ENUM.GET_BACKUP,new $(Gs.getBackup)),e}a(ate,"initializeOperationFunctionMap")});var iE=g((xhe,nB)=>{"use strict";var cR=U(),cte=z(),Eu=K(),{handleHDBError:lR,hdb_errors:sE}=ne(),{isMainThread:lte}=require("worker_threads"),{Readable:ute}=require("stream"),tB=require("os"),_te=require("util"),dte=vS(),fte=_te.promisify(dte.authorize),rB=eB(),{createGzip:Ete,constants:hte}=require("zlib");function mte(e){let t=`Found an uncaught exception with message: ${e.message}. ${tB.EOL}Stack: ${e.stack} ${tB.EOL}Terminating ${lte?"HDB":"thread"}.`;console.error(t),Eu.fatal(t),process.exit(1)}a(mte,"handleServerUncaughtException");function pte(e,t,r){if(Eu[e.logLevel||"error"](e),e.statusCode)return typeof e.http_resp_msg!="object"?r.code(e.statusCode).send({error:e.http_resp_msg||e.message}):r.code(e.statusCode).send(e.http_resp_msg);let n=e.statusCode?e.statusCode:sE.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR;return typeof e=="string"?r.code(n).send({error:e}):r.code(n).send(e.message?{error:e.message}:e)}a(pte,"serverErrorHandler");function Ste(e,t,r){if(!e.body||Object.keys(e.body).length===0||typeof e.body!="object"){let n=lR(new Error,"Invalid JSON.",sE.HTTP_STATUS_CODES.BAD_REQUEST);r(n,null)}if(cte.isEmpty(e.body.operation)){let n=lR(new Error,"Request body must include an 'operation' property.",sE.HTTP_STATUS_CODES.BAD_REQUEST);r(n,null)}r()}a(Ste,"reqBodyValidationHandler");function Tte(e,t,r){let n;e.body.operation!==cR.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS&&e.body.operation!==cR.OPERATIONS_ENUM.LOGIN&&e.body.operation!==cR.OPERATIONS_ENUM.LOGOUT?fte(e,t).then(s=>{n=s,e.body.hdb_user=n,e.body.hdb_auth_header=e.headers.authorization,r()}).catch(s=>{Eu.warn(s),Eu.warn(`{"ip":"${e.socket.remoteAddress}", "error":"${s.stack}"`);let i=typeof s=="string"?{error:s}:{error:s.message};r(lR(s,i,sE.HTTP_STATUS_CODES.UNAUTHORIZED),null)}):(e.body.hdb_user=null,e.body.hdb_auth_header=e.headers.authorization,e.body.baseRequest=e.raw?.baseRequest,e.body.baseResponse=t.raw?.baseResponse,e.body.fastifyResponse=t,r())}a(Tte,"authHandler");async function gte(e,t,r=!1){let n;try{r&&(e.body.operation!=="configure_cluster"||e.body.operation!=="set_configuration")&&(e.body.bypass_auth=r),n=rB.chooseOperation(e.body);let s=await rB.processLocalTransaction(e,n);if(s instanceof ute&&s.headers){for(let[i,o]of s.headers)t.header(i,o);e.headers["accept-encoding"]?.includes("gzip")&&(t.header("content-encoding","gzip"),s=s.pipe(Ete({level:hte.Z_BEST_SPEED})))}return s}catch(s){throw Eu.error(s),s}}a(gte,"handlePostRequest");nB.exports={authHandler:Tte,handlePostRequest:gte,handleServerUncaughtException:mte,serverErrorHandler:pte,reqBodyValidationHandler:Ste}});var aB=g((Fhe,oB)=>{"use strict";var Rte=require("fastify-plugin"),{handlePostRequest:sB,authHandler:Ate,reqBodyValidationHandler:Ote}=iE();async function bte(e){e.decorate("hdbCore",{preValidation:[Ote,Ate],request:t=>iB(sB(t,response)),requestWithoutAuthentication:(t,r)=>iB(sB(t,r,!0))})}a(bte,"hdbCore");async function iB(e){if(e=await e,e?.[Symbol.asyncIterator]&&!e[Symbol.iterator]){let t=[];for await(let r of e)t.push(r);return t}return e}a(iB,"convertAsyncIterators");oB.exports=Rte(bte)});var uB=g((Vhe,lB)=>{"use strict";var khe=require("fs"),uR=te();uR.initSync();var{CONFIG_PARAMS:cB}=U(),yte=1024*1024*1024;function Nte(e){let t=uR.get(cB.HTTP_TIMEOUT),r=uR.get(cB.HTTP_KEEPALIVETIMEOUT);return{bodyLimit:yte,connectionTimeout:t,keepAliveTimeout:r,return503OnClosing:!1,forceCloseConnections:!0,ignoreTrailingSlash:!0,https:e}}a(Nte,"getServerOptions");lB.exports=Nte});var fB=g((Yhe,dB)=>{"use strict";var _R=te();_R.initSync();var{CONFIG_PARAMS:_B}=U();function Ite(){let e=_R.get(_B.HTTP_CORSACCESSLIST),t=_R.get(_B.HTTP_CORS),r;return t&&(r={origin:!0,allowedHeaders:["Content-Type","Authorization","Accept"],credentials:!1},e&&e.length>0&&e[0]!==null&&e[0]!=="*"&&(r.origin=(n,s)=>s(null,e.indexOf(n)!==-1))),r}a(Ite,"getCORSOptions");dB.exports=Ite});var mB=g((Whe,hB)=>{"use strict";var EB=te();EB.initSync();var wte=U();function Cte(){return EB.get(wte.CONFIG_PARAMS.HTTP_HEADERSTIMEOUT)??6e4}a(Cte,"getHeaderTimeoutConfig");hB.exports=Cte});var fR={};qe(fR,{customFunctionsServer:()=>Mte,ready:()=>LB,start:()=>Lte});function Lte(e){let t=e.securePort>0;return{async handleFile(r,n,s,i){Fs||(Fs=DB(t),st.http((await Fs).server));let o=await Fs,c=(0,dR.dirname)(s),l=(0,dR.dirname)(n);if(l.startsWith("/")&&(l=l.slice(1)),!pB.has(c)){pB.add(c);try{o.register(Ute(c,l))}catch(_){if(_.message==="Root plugin has already booted")$e.warn(`Could not load root fastify route for ${s}, this may require a restart to install properly`);else throw _}}},ready:LB}}async function Mte(){try{$e.info("In Custom Functions Fastify server"+process.cwd()),$e.info(`Custom Functions Running with NODE_ENV set as: ${process.env.NODE_ENV}`),$e.debug(`Custom Functions server process ${process.pid} starting up.`),await Pte();let e=OB.get(bB.CONFIG_PARAMS.HTTP_SECUREPORT)>0,t;try{t=Fs=await DB(e)}catch(r){throw $e.error(`Custom Functions buildServer error: ${r}`),r}try{await t.ready()}catch(r){throw $e.error(`Custom Functions server.ready() error: ${r}`),r}t.server.cantCleanupProperly=!0}catch(e){$e.error(`Custom Functions ${process.pid} Error: ${e}`),$e.error(e),process.exit(1)}}async function Pte(){try{$e.info("Custom Functions starting configuration."),await yB.setUsersToGlobal(),$e.info("Custom Functions completed configuration.")}catch(e){$e.error(e)}}function Ute(e,t){return async function(r){try{$e.info("Custom Functions starting buildRoutes"),$e.trace("Loading fastify routes folder "+e),(0,SB.existsSync)(e)&&r.register(AB.default,s=>({dir:e,dirNameRoutePrefix:!1,options:{hdbCore:s.hdbCore,logger:$e.loggerWithTag("custom-function"),prefix:`/${t}`}})).after((s,i,o)=>{s?.message?$e.error(s.message):s&&$e.error(s),o()})}catch(n){$e.error(`Custom Functions errored buildRoutes: ${n}`)}}}async function DB(e){$e.info("Custom Functions starting buildServer.");let t=(0,NB.default)(e),r=(0,TB.default)(t);r.server.headersTimeout=(0,wB.default)(),r.setErrorHandler(CB.serverErrorHandler);let n=(0,IB.default)();return n&&r.register(gB.default,n),r.register(function(s,i,o){s.setNotFoundHandler(function(c,l){r.server.emit("unhandled",c.raw,l.raw)}),o()}),r.register(RB.default),await r.register(Dte),await r.after(),pg(r),$e.info("Custom Functions completed buildServer."),r}function LB(){if(Fs)return Fs.then?Fs.then(e=>e.ready()):Fs.ready()}var dR,SB,TB,gB,RB,AB,OB,bB,$e,Dte,yB,NB,IB,wB,CB,Fs,pB,MB=Re(()=>{dR=require("path"),SB=require("fs"),TB=B(require("fastify")),gB=B(require("@fastify/cors")),RB=B(Pg()),AB=B(require("@fastify/autoload")),OB=B(te()),bB=B(U()),$e=B(K()),Dte=B(aB()),yB=B(un()),NB=B(uB()),IB=B(fB()),wB=B(mB()),CB=B(iE());Oa();ur();pB=new Set;a(Lte,"start");a(Mte,"customFunctionsServer");a(Pte,"setUp");a(Ute,"buildRouteFolder");a(DB,"buildServer");a(LB,"ready")});var ER={};qe(ER,{start:()=>vte});function vte(e){return{handleDirectory(t,r){if(t==="/"){let n=(0,HB.default)(r,e);return e.server.http(async(s,i)=>{if(!s.isWebSocket)return new Promise(o=>n(s._nodeRequest,s._nodeResponse,()=>{o(i(s))}))}),!0}},handleFile(t,r,n){UB||(UB=!0,e.server.http(async(s,i)=>{if(!s.isWebSocket){let o=PB.get(s.pathname);if(o)return{handlesHeaders:!0,body:(0,vB.default)(s,(0,BB.realpathSync)(o))}}return i(s)},{runFirst:!0})),PB.set(r,n)}}}var vB,BB,HB,PB,UB,xB=Re(()=>{vB=B(require("send")),BB=require("fs"),HB=B(require("serve-static")),PB=new Map;a(vte,"start")});function xte(){let e=(0,kB.checkMemoryLimit)();e&&!process.env.DEV_MODE&&(console.error(e),mR=setInterval(()=>{cE.notify(e)},Hte).unref())}function Gte(e,t=1,r){if(hR++,(0,qs.startWorker)("server/threads/threadServer.js",{name:Va.THREAD_TYPES.HTTP,workerIndex:e,threadCount:t,async onStarted(n){let s=new Promise((o,c)=>{function l(_){_.type===Va.CLUSTER_MESSAGE_TYPE_ENUM.CHILD_STARTED&&(n.removeListener("message",l),o(n))}a(l,"onMessage"),n.on("message",l),n.on("error",c)});Bte.push(s),await s,Ga.push(n),n.expectedIdle=1,n.lastIdle=0,n.requests=1,n.on("message",o=>{if(o.requestId){let c=aE.get(o.requestId);c&&c(o)}}),n.on("exit",i),n.on("shutdown",i);function i(){let o=Ga.indexOf(n);o>-1&&Ga.splice(o,1)}if(a(i,"removeWorker"),Fa){let o=Fa;Fa=[];for(let c of o)VB[c.localPort](null,c)}}}),r){let n=setInterval(()=>{pR?pR=!1:(clearInterval(n),console.log("shut down dynamic thread due to inactivity"),(0,qs.shutdownWorkers)(),hR=0,setTimeout(()=>{global.gc?.()},5e3))},1e4)}}function $B(e=0,t){if(typeof e=="string")try{(0,lE.existsSync)(e)&&(0,lE.unlinkSync)(e)}catch{}let r;t?t==="ip"?r=Fte:r=qte(t):r=SR;let n=(0,qa.createServer)({allowHalfOpen:!0,pauseOnConnect:!r.readsData}).listen(e);if(n._handle){n._handle.onconnection=VB[e]=function(i,o){r.readsData||(o.reading=!1,o.readStop()),pR=!0,r(o,(c,l)=>{if(!c){if(GB){let u=o._socket||new qa.Socket({handle:o,writable:!0,readable:!0});GB.deliverSocket(u,e,l),u.resume()}else hR>0?(Fa.length===0&&setTimeout(()=>{Fa.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(),o.localPort=e,Fa.push(o)):(console.log("start up a dynamic thread to handle request"),Gte(0));wr(!1,"socket-routed");return}c.requests++;let _=o.fd;if(_>=0)c.postMessage({port:e,fd:_,data:l});else{let u=o._socket||new qa.Socket({handle:o,writable:!0,readable:!0});Yte(u,c,e)}wr(!0,"socket-routed")})};let s=El();cE.info(`HarperDB ${s.version} Server running on port ${e}`)}return n.on("error",s=>{console.error("Error in socket server",s)}),process.env._UNREF_SERVER&&n.unref(),n}function SR(e,t){let r,n=0;for(let s of Ga){if(s.threadId===-1)continue;let i=s.expectedIdle/s.requests;if(i>n)r=s;else if(n>=oE)return oE=i,t(r);n=i}oE=0,t(r)}function Fte(e,t){let r={};e.getpeername(r);let n=r.address,s=ka.get(n),i=Date.now();if(s&&s.worker.threadId!==-1)return s.lastUsed=i,t(s.worker);SR(e,o=>{ka.set(n,{worker:o,lastUsed:i}),t(o)})}function qte(e){let t=new RegExp(`${e}:\\s*(.+)`,"i");return r.readsData=!0,r;function r(n,s){let i=new qa.Socket({handle:n,readable:!0,writable:!0});n._socket=i,i.on("data",o=>{n.readStop();let l=o.toString("latin1").match(t)?.[1],_=ka.get(l),u=Date.now();if(_&&_.worker.threadId!==-1)return _.lastUsed=u,s(_.worker);SR(n,d=>{ka.set(l,{worker:d,lastUsed:u}),s(d,o)})})}a(r,"findByHeaderAffinity")}function Vte(){oE=0;for(let e of Ga)e.expectedIdle=e.recentELU.idle+kte,e.requests=1;Ga.sort((e,t)=>e.expectedIdle>t.expectedIdle?-1:1)}function Yte(e,t,r){let n=$te++;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(),aE.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")),aE.delete(n)),s.event=="destroy"&&(e.destroy(),aE.delete(n))})}var qs,qa,Va,cE,lE,qB,kB,Ga,Fa,VB,GB,hR,Bte,mR,Hte,pR,oE,FB,ka,kte,aE,$te,YB=Re(()=>{qs=B(it()),qa=require("net"),Va=B(U()),cE=B(K()),lE=require("fs");Bs();qB=require("worker_threads"),kB=B(zi()),Ga=[],Fa=[],VB=[],hR=0,Bte=[];qB.isMainThread&&(process.on("uncaughtException",e=>{e.code!=="ECONNRESET"&&e.message!=="write EIO"&&console.error("uncaughtException",e)}),(0,qs.onMessageFromWorkers)(e=>{e.type===Va.ITC_EVENT_TYPES.RESTART&&mR&&(clearInterval(mR),xte())}));Hte=6e5;a(xte,"licenseWarning");a(Gte,"startHTTPWorker");a($B,"startSocketServer");oE=0;a(SR,"findMostIdleWorker");FB=36e5,ka=new Map;a(Fte,"findByRemoteAddressAffinity");a(qte,"makeFindByHeaderAffinity");setInterval(()=>{let e=Date.now();for(let[t,r]of ka)r.lastUsed+FB<e&&ka.delete(t)},FB).unref();kte=1e3;a(Vte,"updateWorkerIdleness");(0,qs.setMonitorListener)(Vte);aE=new Map,$te=1;a(Yte,"proxySocket")});var AR={};qe(AR,{Request:()=>TR,createReuseportFd:()=>uE});var KB,TR,gR,RR,uE,_E=Re(()=>{KB=require("os"),TR=class{static{a(this,"Request")}#e;constructor(t,r){this.method=t.method;let n=t.url;this._nodeRequest=t,this._nodeResponse=r,this.url=n,this.headers=new RR(t.headers)}get absoluteURL(){return this.protocol+"://"+this.host+this.url}get pathname(){let t=this.url.indexOf("?");return t>-1?this.url.slice(0,t):this.url}set pathname(t){let r=this.url.indexOf("?");r>-1?this.url=t+this.url.slice(r):this.url=t}get protocol(){return this._nodeRequest.socket.encrypted?"https":"http"}get ip(){return this._nodeRequest.socket.remoteAddress}get authorized(){return this._nodeRequest.socket.authorized}get peerCertificate(){return this._nodeRequest.socket.getPeerCertificate()}get mtlsConfig(){return this._nodeRequest.socket.server.mtlsConfig}get body(){return this.#e||(this.#e=new gR(this._nodeRequest))}get host(){return this._nodeRequest.authority||this._nodeRequest.headers.host}get isAborted(){return!1}},gR=class{static{a(this,"RequestBody")}#e;constructor(t){this.#e=t}on(t,r){return this.#e.on(t,r),this}pipe(t,r){return this.#e.pipe(t,r)}},RR=class{constructor(t){this.asObject=t}static{a(this,"Headers")}set(t,r){this.asObject[t.toLowerCase()]=r}get(t){return this.asObject[t.toLowerCase()]}has(t){return this.asObject.hasOwnProperty(t.toLowerCase())}[Symbol.iterator](){return Object.entries(this.asObject)[Symbol.iterator]()}keys(){return Object.keys(this.asObject)}values(){return Object.values(this.asObject)}forEach(t){for(let[r,n]of this)t(n,r,this)}};(0,KB.platform)()!="win32"&&(uE=require("node-unix-socket").createReuseportFd)});var JB=g((cme,zB)=>{"use strict";var Kte=require("cluster"),bo=te();bo.initSync();var QB=U(),nme=require("util"),ks=K(),sme=require("fs"),Wte=require("fastify"),ime=El(),Qte=require("@fastify/cors"),zte=require("@fastify/compress"),Jte=require("@fastify/static"),Xte=Pg(),jte=require("path"),{PACKAGE_ROOT:Zte}=U(),ere=ni(),tre=z(),rre=un(),nre=zi(),{server:sre}=(ur(),ie(vi)),{node_request_key:ome}=(_E(),ie(AR)),{authHandler:ire,handlePostRequest:ore,serverErrorHandler:are,reqBodyValidationHandler:cre}=iE(),ame=require("net"),{registerContentHandlers:lre}=(Oa(),ie(lv)),ure=6e4,_re=1024*1024*1024,dre="TRUE",{CONFIG_PARAMS:hu}=QB,$a;zB.exports={hdbServer:WB,start:WB};async function WB(e){try{ks.info("In Fastify server"+process.cwd()),ks.info(`Running with NODE_ENV set as: ${process.env.NODE_ENV}`),ks.debug(`HarperDB server process ${process.pid} starting up.`),global.clustering_on=!1,global.isMaster=Kte.isMaster,await fre();let t=e.securePort>0;$a=Ere(t),await $a.ready(),e||(e={}),e.isOperationsServer=!0;try{sre.http($a.server,e),$a.server.closeIdleConnections||await $a.listen({port:0,host:"::"})}catch(r){throw $a.close(),ks.error(r),ks.error("Error configuring operations server"),r}}catch(t){console.error(`Failed to build server on ${process.pid}`,t),ks.fatal(t),process.exit(1)}}a(WB,"operationsServer");async function fre(){ks.trace("Configuring HarperDB process."),ere.setSchemaDataToGlobal(),await rre.setUsersToGlobal(),await nre.getLicense()}a(fre,"setUp");function Ere(e){ks.debug(`HarperDB process starting to build ${e?"HTTPS":"HTTP"} server.`);let t=hre(e),r=Wte(t);r.server.headersTimeout=pre(),r.setErrorHandler(are);let n=mre();n&&r.register(Qte,n),r.register(function(i,o,c){i.setNotFoundHandler(function(l,_){r.server.emit("unhandled",l.raw,_.raw)}),c()}),r.register(Xte),r.register(zte),r.register(Jte,{root:jte.join(Zte,"studio/build-local")}),lre(r);let s=bo.get(QB.HDB_SETTINGS_NAMES.LOCAL_STUDIO_ON);return r.get("/",function(i,o){return!tre.isEmpty(s)&&s.toString().toLowerCase()==="true"?o.sendFile("index.html"):o.sendFile("running.html")}),r.post("/",{preValidation:[cre,ire],config:{isOperation:!0}},async function(i,o){return i.body?.operation?.startsWith("restart")&&o.header("Connection","close"),ore(i,o)}),r.get("/health",()=>"HarperDB is running."),ks.debug(`HarperDB process starting up ${e?"HTTPS":"HTTP"} server listener.`),r}a(Ere,"buildServer");function hre(e){let t=bo.get(hu.OPERATIONSAPI_NETWORK_TIMEOUT),r=bo.get(hu.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT);return{bodyLimit:_re,connectionTimeout:t,keepAliveTimeout:r,forceCloseConnections:!0,return503OnClosing:!1,https:e}}a(hre,"getServerOptions");function mre(){let e=bo.get(hu.OPERATIONSAPI_NETWORK_CORS),t=bo.get(hu.OPERATIONSAPI_NETWORK_CORSACCESSLIST),r;return e&&(e===!0||e.toUpperCase()===dre)&&(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(mre,"getCORSOpts");function pre(){return bo.get(hu.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT)??ure}a(pre,"getHeaderTimeoutConfig")});var wR={};qe(wR,{disableNATS:()=>Tre,publishToStream:()=>EE,setNATSReplicator:()=>OR,setPublishToStream:()=>gre,setSubscription:()=>IR,start:()=>Sre});function Sre(){mu.default.get(pu.default.CONFIG_PARAMS.CLUSTERING_ENABLED)&&Are()}function Tre(e=!0){tH=e}function gre(e,t){EE=e,IR=t}function Are(){if(tH||process.env._DISABLE_NATS)return;let e=mr(),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];OR(s,r,i)}}CR((r,n)=>{OR(r.tableName,r.databaseName,r),n&&nH(r)}),!XB&&(XB=!0)}function OR(e,t,r){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 $t{static{a(this,"NATSReplicator")}put(i){return n(this.getContext()).addWrite(t,{operation:"put",table:e,id:this[Le],record:i})}delete(){return n(this.getContext()).addWrite(t,{operation:"delete",table:e,id:this[Le]})}publish(i){return n(this.getContext()).addWrite(t,{operation:"publish",table:e,id:this[Le],record:i})}patch(i){return n(this.getContext()).addWrite(t,{operation:"patch",table:e,id:this[Le],record:i})}invalidate(){n(this.getContext()).addWrite(t,{operation:"invalidate",table:e,id:this[Le]})}static defineSchema(i){nH(i)}static subscribe(){let i=new bn;return IR(t,e,i),i}static subscribeOnThisThread(i){return i<(mu.default.get(pu.default.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXINGESTTHREADS)??Rre)}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 dE(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=rH;return i}a(n,"getNATSTransaction")}function nH(e){let t=mu.default.get(pu.default.CONFIG_PARAMS.CLUSTERING_NODENAME);EE(`${yR.SUBJECT_PREFIXES.TXN}.${e.databaseName}.${e.tableName}`,(0,NR.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 jB,yR,NR,ZB,eH,mu,pu,fE,tH,EE,IR,Rre,rH,XB,dE,bR,sH=Re(()=>{Ae();yn();jB=B(wt()),yR=B(ct()),NR=B(Rs());Rc();ZB=B(hE()),eH=B(vr()),mu=B(te()),pu=B(U()),fE=B(K());a(Sre,"start");a(Tre,"disableNATS");EE=jB.publishToStream,IR=ZB.setSubscription;a(gre,"setPublishToStream");Rre=2;a(Are,"assignReplicationSource");a(OR,"setNATSReplicator");a(nH,"publishSchema");dE=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=mu.default.get(pu.default.CONFIG_PARAMS.CLUSTERING_NODENAME),n=[];for(let[s,i]of this.writes_by_db){let o=[],c=[],l,_;for(let u of i){let d=u.table,E=u.operation=="put"?"upsert":u.operation;l||(fE.trace(`Sending transaction event ${E}`),_=l={operation:E,schema:s,table:d,__origin:{user:this.user?.username,timestamp:t,node_name:r}},l.hash_values=c,E!=="delete"&&E!=="invalidate"&&(l.records=o)),l.table===d&&l.operation===E?(o.push(u.record),c.push(u.id)):_=_.next={operation:E,table:d,id:u.id,record:u.record},u.expiresAt&&(_.expiresAt=u.expiresAt)}l&&n.push(EE(`${yR.SUBJECT_PREFIXES.TXN}.${s}.${l.table}`,(0,NR.createNatsTableStreamName)(s,l.table),void 0,l)?.catch(u=>{throw fE.error("An error has occurred trying to replicate transaction",l,u),u.statusCode=504,u}))}return Promise.all(n)}},bR=class extends dE{static{a(this,"ImmmediateNATSTransaction")}constructor(){super({get timestamp(){return(0,eH.getNextMonotonicTime)()}})}addWrite(t,r){super.addWrite(t,r),this.commit({})}};rH=new bR});var SH=g(wi=>{"use strict";var{isMainThread:MR,parentPort:Tu,threadId:mE}=require("worker_threads"),{Socket:Ore,createServer:bre}=require("net"),{createServer:yre,IncomingMessage:Nre}=require("http"),{createServer:Ire}=require("https"),{readFileSync:wre,unlinkSync:iH,existsSync:Cre}=require("fs"),Pt=K(),xe=te(),ut=U(),{server:TE}=(ur(),ie(vi)),{WebSocketServer:Dre}=require("ws"),{createSecureContext:Lre,createServer:Mre}=require("node:tls"),{getTicketKeys:lH,restartNumber:Pre,getWorkerIndex:gu}=it(),{Headers:uH,appendHeader:Ure}=(Hl(),ie(MP)),{recordAction:Su,recordActionBinary:vre}=(Bs(),ie(su)),{Request:_H,createReuseportFd:oH}=(_E(),ie(AR)),{checkMemoryLimit:Bre}=zi(),{X509Certificate:Hre}=require("crypto"),dH=require("tls"),xre=dH.createSecureContext,Ya;dH.createSecureContext=function(e){return Ya||xre(e)};var fH=xe.get(ut.CONFIG_PARAMS.THREADS_DEBUG);if(fH){let e;if(MR)e=xe.get(ut.CONFIG_PARAMS.THREADS_DEBUG_PORT)??9229,process.on(["SIGINT","SIGTERM","SIGQUIT","exit"],()=>{try{require("inspector").close()}catch(t){Pt.info("Could not close debugger",t)}});else{let t=xe.get(ut.CONFIG_PARAMS.THREADS_DEBUG_STARTINGPORT);t&&gu()>=0&&(e=t+gu())}if(e){let t=xe.get(ut.CONFIG_PARAMS.THREADS_DEBUG_HOST),r=xe.get(ut.CONFIG_PARAMS.THREADS_DEBUG_WAITFORDEBUGGER);try{require("inspector").open(e,t,r)}catch(n){Pt.trace(`Could not start debugging on port ${e}, you may already be debugging:`,n.message)}}}else if(process.env.DEV_MODE&&MR)try{require("inspector").open(9229)}catch(e){Pre<=1&&Pt.trace("Could not start debugging on port 9229, you may already be debugging:",e.message)}process.on("uncaughtException",e=>{e.code!=="ECONNRESET"&&e.message!=="write EIO"&&console.error("uncaughtException",e)});var{HDB_SETTINGS_NAMES:hme,CONFIG_PARAMS:Gre}=ut;xe.initSync();var Fre=xe.get(Gre.HTTP_SESSIONAFFINITY),_s={};wi.registerServer=BR;wi.httpServer=HR;wi.deliverSocket=vR;wi.startServers=EH;wi.when_components_loaded=null;wi.createSNICallback=xR;TE.http=HR;TE.request=$re;TE.socket=Yre;TE.ws=Kre;var DR={},pE={},qre,Vs={},SE={},kre=[],PR=[];function EH(){return wi.when_components_loaded=GR().loadRootComponents(!0).then(()=>{Tu?.on("message",t=>{let{port:r,fd:n,data:s}=t;if(n)vR(n,r,s);else if(t.requestId)Vre(t);else if(t.type===ut.ITC_EVENT_TYPES.SHUTDOWN){Pt.trace("received shutdown request",mE);for(let i in _s){let o=_s[i],c;if(o.closeIdleConnections){let _=Object.getOwnPropertySymbols(o).find(E=>E.description.includes("connections")),u=0,d=setInterval(()=>{u++;let E=u>=100,f=o[_][E?"all":"idle"]();if(f.length===0){E&&clearInterval(d);return}u===1?Pt.info(`Closing ${f.length} idle connections`):E&&Pt.warn(`Forcefully closing ${f.length} active connections`);for(let h=0,p=f.length;h<p;h++){let S=f[h].socket;S._httpMessage&&!S._httpMessage.finished&&!E||(E?S.destroySoon():S.end(`HTTP/1.1 408 Request Timeout\r
35
+ `},compressible:!1,q:.8});Er.set("application/x-www-form-urlencoded",{deserialize(e){let t={};for(let[r,n]of new URLSearchParams(e))if(t.hasOwnProperty(r)){let s=t[r];Array.isArray(s)?s.push(n):t.key=[s,n]}else t[r]=n},serialize(e){let t=new URLSearchParams;for(let r in e)t.set(r,e);return t.toString()}});mH={type:"application/json",serializeStream:au,serialize:Xd,deserialize:fse,q:.5};Er.set("*/*",mH);Er.set("",mH);a(fse,"tryJSONParse");a(mb,"registerContentHandlers");_se=require("fastify-plugin"),Ese=_se(function(e,t,r){e.addHook("preSerialization",async(n,s)=>{if(s.raw.getHeader("content-type"))return;let{serializer:o,type:c}=em(n.raw);s.type(c),s.serializer(function(l){return(o.serializeStream||o.serialize)(l,{headers:{set:(d,u)=>{s.header(d,u)}}})})}),r()},{name:"content-type-negotiation"});a(em,"findBestSerializer");uH=fb.default.get(_b.CONFIG_PARAMS.HTTP_COMPRESSIONTHRESHOLD);a(ef,"serialize");a(wa,"serializeMessage");a(hse,"streamToBuffer");a(Ma,"getDeserializer");a(dH,"deserializerUnknownType");a(mse,"transformIterable")});var of={};Ze(of,{addAnalyticsListener:()=>sf,recordAction:()=>an,recordActionBinary:()=>Ln,setAnalyticsEnabled:()=>pse});function pse(e){NH=e}function an(e,t,r,n,s){if(!NH)return;let i=t+(r?"-"+r:"");n!==void 0&&(i+="-"+n),s!==void 0&&(i+="-"+s);let o=nm.get(i);if(o)if(typeof e=="number"){let c=o.values,l=c.index++;if(l>=c.length){let d=c;o.values=c=new Float32Array(l*2),c.set(d),c.index=l+1}c[l]=e,o.total+=e}else if(typeof e=="boolean")e&&o.total++,o.count++;else if(typeof e=="function")o.count++;else throw new TypeError("Invalid metric value type "+typeof e);else{if(typeof e=="number")o={total:e,values:new Float32Array(4)},o.values.index=1,o.values[0]=e,o.total=e;else if(typeof e=="boolean")o={},o.total=e?1:0,o.count=1;else if(typeof e=="function")o={},o.count=1,o.callback=e;else throw new TypeError("Invalid metric value type "+typeof e);o.description={metric:t,path:r,method:n,type:s},nm.set(i,o)}tm||Sse()}function Ln(e,t,r,n,s){an(!!e,t,r,n,s)}function sf(e){CH.push(e)}function Sse(){tm=performance.now(),setTimeout(async()=>{let e=performance.now()-tm;tm=0;let t=[],r={time:Date.now(),period:e,threadId:Ua.threadId,metrics:t};for(let[s,i]of nm){if(i.values){let o=i.values.subarray(0,i.values.index);o.sort();let c=o.length,l=0,d=[],u;for(let f of DH){let E=Math.floor(c*f),_=o[E-1];if(E>l){let h=E-l;if(_===u){let p=d[d.length-1];typeof p=="number"?d[d.length-1]={value:p,count:1+h}:p.count+=h}else d.push(h>1?{value:_,count:h}:_),u=_;l=E}}t.push(Object.assign(i.description,{mean:i.total/c,distribution:d,count:c}))}else i.callback?t.push(Object.assign(i.description,i.callback(i))):t.push(Object.assign(i.description,{total:i.total,count:i.count}));await LH()}let n=process.memoryUsage();t.push({metric:"memory",threadId:Ua.threadId,byThread:!0,...n});for(let s of CH)s(t);nm=new Map,Ua.parentPort?Ua.parentPort.postMessage({type:wH,report:r}):UH({report:r})},IH).unref()}async function Tse(e,t=6e4){let r=Tb(),n=PH(),s=new Promise(p=>{let S=performance.now();setImmediate(()=>{let g=performance.now();g-S>5e3&&(0,tf.warn)("Unusually high event queue latency on the main thread of "+Math.round(g-S)+"ms"),S=performance.now()}),n.primaryStore.prefetch([1],()=>{let g=performance.now();g-S>5e3&&(0,tf.warn)("Unusually high task queue latency on the main thread of "+Math.round(g-S)+"ms"),p(g-S)})}),i;for(let p of n.primaryStore.getRange({start:1/0,end:!1,reverse:!0}))if(p.value?.time){i=p.value.time;break}if(Date.now()-t<i)return;let o,c=new Map,l=new Map,d=[],u;for(let{key:p,value:S}of r.primaryStore.getRange({start:i||!1,exclusiveStart:!0,end:1/0})){if(!S)continue;if(o){if(p>o+t)break}else o=p;u=p;let{metrics:g,threadId:T}=S;for(let A of g||[]){let{path:N,method:V,type:v,metric:J,count:$,total:F,distribution:ne,threads:ee,...Z}=A;$||($=1);let le=J+(N?"-"+N:"");V!==void 0&&(le+="-"+V),v!==void 0&&(le+="-"+v);let fe=c.get(le);if(fe){if(fe.threads){let ye=fe.threads[T];if(ye)fe=ye;else{fe.threads[T]=Object.assign({},Z);continue}}fe.count||(fe.count=1);let je=fe.count;for(let ye in Z){let Ht=Z[ye];typeof Ht=="number"&&(fe[ye]=(fe[ye]*je+Ht*$)/(je+$))}fe.count+=$,F>=0&&(fe.total+=F,fe.ratio=fe.total/fe.count)}else fe=Object.assign({period:t},A),delete fe.distribution,c.set(le,fe),fe.byThread&&(fe.threads=[],fe.threads[T]=Object.assign({},Z),d.push(fe));if(ne){ne=ne.map(ye=>typeof ye=="number"?{value:ye,count:1}:ye);let je=l.get(le);je?je.push(...ne):l.set(le,ne)}}await LH()}for(let p of d){let{path:S,method:g,type:T,metric:A,count:N,total:V,distribution:v,threads:J,...$}=p;J=J.filter(F=>F);for(let F in $){if(typeof p[F]!="number")continue;let ne=0;for(let ee of J){let Z=ee[F];typeof Z=="number"&&(ne+=Z)}p[F]=ne}p.count=J.length,delete p.threads,delete p.byThread}for(let[p,S]of l){let g=c.get(p);S.sort((ye,Ht)=>ye.value>Ht.value?1:-1);let T=g.count-1,A=[],N=0,V=0,v;for(let ye of DH){let Ht=T*ye;for(;N<Ht;)v=S[V++],N+=v.count,V===1&&N--;let Bo=S[V>1?V-2:0];v||(v=S[0]),A.push(v.value-(v.value-Bo.value)*(N-Ht)/v.count)}let[J,$,F,ne,ee,Z,le,fe,je]=A;Object.assign(g,{p1:J,p10:$,p25:F,median:ne,p75:ee,p90:Z,p95:le,p99:fe,p999:je})}let f;for(let[p,S]of c)S.id=(0,rm.getNextMonotonicTime)(),S.time=u,n.primaryStore.put(S.id,S,{append:!0}).then(g=>{g||n.primaryStore.put(S.id,S)}),f=!0;let E=Date.now(),{idle:_,active:h}=performance.eventLoopUtilization();if(f||h*10>_){let p=(0,rm.getNextMonotonicTime)(),S={id:p,metric:"main-thread-utilization",idle:_-SH,active:h-TH,taskQueueLatency:await s,time:E,...process.memoryUsage()};n.primaryStore.put(p,S,{append:!0}).then(g=>{g||n.primaryStore.put(p,S)})}SH=_,TH=h}async function gH(e,t){let r=Date.now()-t;for(let n of e.primaryStore.getKeys({start:!1,end:r}))e.primaryStore.remove(n)}function Tb(){return RH||(RH=dt({table:"hdb_raw_analytics",database:"system",audit:!1,trackDeletes:!1,attributes:[{name:"id",isPrimaryKey:!0},{name:"action"},{name:"metrics"}]}))}function PH(){return AH||(AH=dt({table:"hdb_analytics",database:"system",audit:!1,trackDeletes:!1,attributes:[{name:"id",isPrimaryKey:!0},{name:"metric"},{name:"path"},{name:"method"},{name:"type"}]}))}function Ase(){MH=!0;let e=(0,nf.get)(Sb.CONFIG_PARAMS.ANALYTICS_AGGREGATEPERIOD)*1e3;e&&setInterval(async()=>{await Tse(IH,e),await gH(Tb(),gse),await gH(PH(),Rse)},Math.min(e/2,2147483647)).unref()}function UH(e,t){let r=e.report;r.threadId=t?.threadId||Ua.threadId;for(let n of r.metrics)n.metric==="bytes-sent"&&(bH+=n.mean*n.count);r.totalBytesProcessed=bH,t&&(r.metrics.push({metric:"utilization",...t.performance.eventLoopUtilization(yH.get(t))}),yH.set(t,t.performance.eventLoopUtilization())),r.id=(0,rm.getNextMonotonicTime)(),Tb().primaryStore.put(r.id,r),MH||Ase(),bse&&(vH=Ose(r))}async function Ose(e){if(await vH,!Io){let r=(0,rf.dirname)((0,tf.getLogFilePath)());try{Io=await(0,pb.open)((0,rf.join)(r,"analytics.log"),"r+")}catch{Io=await(0,pb.open)((0,rf.join)(r,"analytics.log"),"w+")}}let t=(await Io.stat()).size;if(t>yse){let r=Buffer.alloc(t);await Io.read(r,{position:0}),r=r.subarray(r.indexOf(10,r.length/2)+1),await Io.write(r,{position:0}),await Io.truncate(r.length),t=r.length}await Io.write(JSON.stringify(e)+`
36
+ `,t)}var Ua,OH,tf,rf,pb,rm,nf,Sb,nm,NH,tm,IH,wH,CH,DH,SH,TH,LH,gse,Rse,RH,AH,MH,bH,yH,bse,vH,Io,yse,Bi=Oe(()=>{Ua=require("worker_threads"),OH=U(at());Ne();tf=U(X()),rf=require("path"),pb=require("fs/promises"),rm=U(hn()),nf=U(ie()),Sb=U(H());Lr();(0,nf.initSync)();nm=new Map,NH=(0,nf.get)(Sb.CONFIG_PARAMS.ANALYTICS_AGGREGATEPERIOD)>-1;a(pse,"setAnalyticsEnabled");a(an,"recordAction");st.recordAnalytics=an;a(Ln,"recordActionBinary");tm=0,IH=1e3,wH="analytics-report",CH=[];a(sf,"addAnalyticsListener");DH=[.01,.1,.25,.5,.75,.9,.95,.99,.999,1];a(Sse,"sendAnalytics");a(Tse,"aggregation");SH=0,TH=0,LH=a(()=>new Promise(setImmediate),"rest");a(gH,"cleanup");gse=36e5,Rse=31536e6;a(Tb,"getRawAnalyticsTable");a(PH,"getAnalyticsTable");(0,OH.setChildListenerByType)(wH,UH);a(Ase,"startScheduledTasks");bH=0,yH=new Map,bse=!1;a(UH,"recordAnalytics");yse=1e6;a(Ose,"logAnalytics")});function Ab(e,t,r,n,s,i,o,c){let l=e[0];if(t==="or"){let f=d(l);for(let _=1;_<e.length;_++){let h=e[_],p=d(h);f=f.concat(p)}let E=new Set;return f.filter(_=>{let h=_.key??_;return E.has(h)?!1:(E.add(h),!0)})}else{let f=d(l),E=u(e.slice(1),!0,l.estimated_count);return E.length>0?o(f,E):f}function d(f){return f.conditions?Ab(f.conditions,f.operator,r,n,s,i,o,c):Sl(f,n,f.descending||s.reverse===!0,r,s.allowFullScan,c)}a(d,"executeCondition");function u(f,E,_){return f.map((h,p)=>{if(h.conditions){let T=h.operator==="or",A=u(h.conditions,!T,_);return T?(N,V)=>A.some(v=>v(N,V)):(N,V)=>A.every(v=>v(N,V))}let S=(h.attribute||h[0])===r.primaryKey,g=yb(h,r,i,c,S,_);return E&&p<f.length-1&&_&&(_=Use(r.primaryStore,h.estimated_count,_)),g}).filter(Boolean)}a(u,"mapConditionsToFilters")}function Sl(e,t,r,n,s,i){let o=e[0]??e.attribute,c=e[1]??e.value,l=e.comparator;if(Array.isArray(o)){let T=o[0],A=ei(n.attributes,T);if(A.relationship){if(o.length<2)throw new Pn.ClientError("Can not directly query a relational attribute, must query an attribute within the target table");let N=A.definition?.tableClass||A.elements?.definition?.tableClass,V=new Map,v=Sl({attribute:o.length>2?o.slice(1):o[1],value:c,comparator:l},t,r,N,s,V);if(A.relationship.to){i[o[0]]=V;let J=!!ei(N.attributes,A.relationship.to)?.elements;v=Dse(v,A,N.primaryStore,J,V)}if(A.relationship.from){let J=a($=>Sl({attribute:A.relationship.from,value:$},t,r,n,s,V),"searchEntry");A.elements?(i[o[0]]=V,v=Lse(v,A,N.primaryStore,V,J)):v=v.flatMap(J)}return v}else if(o.length===1)o=o[0];else throw new Pn.ClientError("Unable to query by attribute "+JSON.stringify(o))}let d,u,f,E;c instanceof Date&&(c=c.getTime());let _;switch(bb[l]||l){case"lt":d=!0,u=c;break;case"le":d=!0,u=c,f=!0;break;case"gt":d=c,E=!0;break;case"ge":d=c;break;case"prefix":Array.isArray(c)?c[c.length-1]!=null&&(c=c.concat(null)):c=[c,null],d=c,u=c.slice(0),u[u.length-1]=Zs.MAXIMUM_KEY;break;case"starts_with":d=c.toString(),u=c+"\uFFFF";break;case"between":d=c[0],d instanceof Date&&(d=d.getTime()),u=c[1],u instanceof Date&&(u=u.getTime()),f=!0;break;case"equals":case void 0:d=c,u=c,f=!0;break;case"ne":if(c===null){d=c,E=!0;break}case"sort":case"contains":case"ends_with":d=!0,_=!0;break;default:throw new Pn.ClientError(`Unknown query comparator "${l}"`)}if(r){let T=d;d=u,u=T,T=!E,E=!f,f=T}let h=o===n.primaryKey||o==null,p=h?n.primaryStore:n.indices[o],S;if(!p||p.isIndexing||_||c===null&&!p.indexNulls){if(s===!1&&!p)throw new Pn.ClientError(`"${o}" is not indexed, can not search for this attribute`,404);if(s===!1&&_)throw new Pn.ClientError(`Can not use ${l||"equal"} operator without combining with a condition that uses an index, can not search for attribute ${o}`,403);if(p?.isIndexing)throw new Pn.ServerError(`"${o}" is not indexed yet, can not search for this attribute`,503);if(c===null&&!p.indexNulls)throw new Pn.ClientError(`"${o}" is not indexed for nulls, index needs to be rebuilt to search for nulls, can not search for this attribute`,400);if(S=yb(e),!S)throw new Pn.ClientError(`Unknown search operator ${e.comparator}`)}let g={start:d,end:u,inclusiveEnd:f,exclusiveStart:E,values:!0,versions:h,transaction:t,reverse:r};if(h){let T=p.getRange(g).map(S?function({key:A,value:N}){return this.isSync?N&&S(N)?A:wo.SKIP:new Promise((V,v)=>setImmediate(()=>{try{V(N&&S(N)?A:wo.SKIP)}catch(J){v(J)}}))}:A=>A.value==null?wo.SKIP:A);return T.hasEntries=!0,T}else return p?p.getRange(g).map(S?function({key:T,value:A}){return this.isSync?S({[o]:T})?A:wo.SKIP:new Promise((N,V)=>setImmediate(()=>{try{N(S({[o]:T})?A:wo.SKIP)}catch(v){V(v)}}))}:({value:T})=>T):n.primaryStore.getRange(r?{end:!0,transaction:t,reverse:!0}:{start:!0,transaction:t}).map(function({key:T,value:A}){return this.isSync?A&&S(A)?T:wo.SKIP:new Promise((N,V)=>setImmediate(()=>{try{N(A&&S(A)?T:wo.SKIP)}catch(v){V(v)}}))})}function ei(e,t){if(Array.isArray(t))if(t.length>1){let r=ei(e,t[0]),n=(r?.definition?.tableClass||r?.elements.definition?.tableClass)?.attributes;return n?ei(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 Dse(e,t,r,n,s){return new e.constructor({[Symbol.iterator](){let i;s.hasMappings=!0;let o;return{next(){if(!i){let l=t.relationship.to,d=a((u,f)=>{let E=u;Array.isArray(u)&&(E=Rs(u),o=!0);let _=s.get(E);_?_.push(f):s.set(E,_=[f]),u!==E&&(_.key=u)},"add_entry");for(let u of e){let f=u.value??r.get(u.key??u),E=f?.[l];if(E!=null&&!s.filters?.some(_=>!_(f)))if(n)for(let _=0;_<E.length;_++)d(E[_],u);else d(E,u)}return i=(o?s:s.keys())[Symbol.iterator](),this.next()}let c=i.next();return c.done?c:{value:o?c.value[1].key||c.value[0]:c.value}},return(){if(i?.return)return i.return()}}}})}function Lse(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 d=Rs(l.value);if(!c.has(d))return c.add(d),l}if(!i){let d=new Map;n.fromRecord=u=>u[t.relationship.from]?.filter?.(f=>d.has(Rs(f)));for(let u of e){if(n.filters){let f=r.get(u);if(n.filters.some(E=>!E(f)))continue}d.set(Rs(u),u)}return i=d.values()[Symbol.iterator](),this.next()}do{let d=i.next();return d.done?d:(o=s(d.value)[Symbol.iterator](),this.next())}while(!0)},return(){return o?.return?.()},throw(){return o?.throw?.()}}}})}function yb(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 u=c[0],f=ei(t.attributes,u),E=f.definition?.tableClass||f.elements.definition?.tableClass,_=n?.[u],h=yb({attribute:c.length>2?c.slice(1):c[1],value:l,comparator:o},E,r,_?.[u]?.joined,c[1]===E.primaryKey,i);if(!h)return;if(_){_.filters||(_.filters=[]),_.filters.push(h);return}let p=t.propertyResolvers?.[u],S,g=a((T,A)=>{let N,V;if(p){if(p.from&&h.idFilter){if(!S)if(h.idFilter.idSet?.size===1){for(let J of h.idFilter.idSet)e={attribute:p.from,value:J};S=d(p.from,h.idFilter,!0,!0)}else S=d(p.from,h.idFilter,!1,!0);let v=S(T);return S.idFilter&&(g.idFilter=S.idFilter),v}V=p(T,r,A),N=V?.value}else N=T[u];return N?Array.isArray(N)?N.some(h):h(N,V):!1},"recordFilter");return g}}switch(l instanceof Date&&(l=l.getTime()),bb[o]||o){case gb.SEARCH_TYPES.EQUALS:case void 0:return d(c,u=>u===l,!0);case"contains":return d(c,u=>u?.toString().includes(l));case"ends_with":return d(c,u=>u?.toString().endsWith(l));case"starts_with":return d(c,u=>typeof u=="string"&&u.startsWith(l),!0);case"prefix":return Array.isArray(l)?l[l.length-1]==null&&(l=l.slice(0,-1)):l=[l],d(c,u=>{if(!Array.isArray(u))return!1;for(let f=0,E=l.length;f<E;f++)if(u[f]!==l[f])return!1;return!0},!0);case"between":return l[0]instanceof Date&&(l[0]=l[0].getTime()),l[1]instanceof Date&&(l[1]=l[1].getTime()),d(c,u=>(0,Zs.compareKeys)(u,l[0])>=0&&(0,Zs.compareKeys)(u,l[1])<=0,!0);case"gt":return d(c,u=>(0,Zs.compareKeys)(u,l)>0);case"ge":return d(c,u=>(0,Zs.compareKeys)(u,l)>=0);case"lt":return d(c,u=>(0,Zs.compareKeys)(u,l)<0);case"le":return d(c,u=>(0,Zs.compareKeys)(u,l)<=0);case"ne":return d(c,u=>(0,Zs.compareKeys)(u,l)!==0);case"sort":return()=>!0;default:throw new Pn.ClientError(`Unknown query comparator "${o}"`)}function d(u,f,E,_){let h;E=E&&!s&&t?.indices[u]&&i>3,E&&(e.estimated_count==null&&im(t)(e),h=e.estimated_count>>4,(isNaN(h)||h>=i)&&(E=!1));let p=0,S=3;function g(T){let A=T[u],N;if(typeof A!="object"||!A||_?N=f(A):Array.isArray(A)?N=A.some(f):A instanceof Date&&(N=f(A.getTime())),E&&(S++,!N&&!g.idFilter&&++p/S*(i-S)>h)){let V=Sl(e,r.transaction.getReadTxn(),!1,t).map(Rs),v=new Set(V);g.idFilter=J=>v.has(Rs(J)),g.idFilter.idSet=v}return N}return a(g,"recordFilter"),s&&(g.idFilter=f),g}a(d,"attributeComparator")}function im(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/Hi(e.primaryStore):i.estimated_count}return r.estimated_count=s,r.estimated_count}let n=r.comparator||r.search_type;if(n=bb[n]||n,n===gb.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=ei(e.attributes,s[0]),o=i.definition?.tableClass||i.elements.definition?.tableClass,c=im(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*Hi(e.indices[i.relationship.from])/(Hi(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=Hi(e.primaryStore)-(i?i.getValuesCount(null):0):r.estimated_count=1/0}else n==="starts_with"||n==="prefix"?r.estimated_count=wse*Hi(e.primaryStore)+1:n==="between"?r.estimated_count=Ise*Hi(e.primaryStore)+1:n==="sort"?r.estimated_count=Hi(e.primaryStore)+1:r.estimated_count=Nse*Hi(e.primaryStore)+1;typeof r.descending=="boolean"&&(r.estimated_count/=2)}return r.estimated_count}return a(t,"estimateConditionForTable"),t}function om(e){if(e)if(Co=e,ml.lastIndex=0,Pse.test(e))try{let t=af(new pl,"");if(cn!==Co.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 ${cn} in '${Co}'`,t}else return new URLSearchParams(e)}function af(e,t){let r=ml,n,s,i,o,c,l=decodeURIComponent,d;for(;n=r.exec(Co);){cn=r.lastIndex;let[,u,f]=n;if(o){if(u)throw new SyntaxError(`expected operator, but encountered '${u}'`);o=!1,c=!1}else c=!0;let E;switch(f){case"=":if(s){if(u.length<=2)i=u;else throw new SyntaxError(`invalid FIQL operator ${u}`);l=xH}else{if(l=decodeURIComponent,i="equals",!u)throw new SyntaxError("attribute must be specified before equality comparator");s=cf(u)}break;case"==":case"!=":case"<":case"<=":case">":case">=":case"===":case"!==":if(i=Cse[f],l=Rb[i]?xH:decodeURIComponent,!u)throw new SyntaxError(`attribute must be specified before comparator ${f}`);s=cf(u);break;case"|":case"&":case"":case void 0:if(s==null){if(s===void 0)throw t?new SyntaxError(`expected '${t}', but encountered ${f[0]?"'"+f[0]+"'":"end of string"}}`):new SyntaxError(`no comparison specified before ${f?"'"+f+"'":"end of string"}`)}else{if(!e.conditions)throw new SyntaxError("conditions/comparisons are not allowed in a property list");let h={comparator:i,attribute:s,value:l(u)};i==="eq"&&BH(h,u),sm(e,d),e.conditions.push(h)}f==="&"&&(d="and"),f==="|"&&(d="or"),s=void 0;break;case",":if(e.conditions)throw new SyntaxError("conditions/comparisons are not allowed in a property list");e.push(cf(u)),s=void 0;break;case"(":ml.lastIndex=cn;let _=af(u?[]:new pl,")");switch(u){case"":sm(e,d),e.conditions.push(_);break;case"limit":switch(_.length){case 1:e.limit=+_[0];break;case 2:e.offset=+_[0],e.limit=_[1]-e.offset;break;default:throw new SyntaxError("limit must have 1 or 2 arguments")}break;case"select":Array.isArray(_[0])&&_.length===1&&!_[0].name?(e.select=_[0],e.select.asArray=!0):_.length===1?e.select=_[0]:_.length===2&&_[1]===""?e.select=_.slice(0,1):e.select=_;break;case"group-by":throw new SyntaxError("group by is not implemented yet");case"sort":e.sort=HH(_);break;default:throw new SyntaxError(`unknown query function call ${u}`)}Co[cn]===","?r.lastIndex=++cn:o=!0,s=null;break;case"{":if(e.conditions)throw new SyntaxError("property sets are not allowed in a queries");if(!u)throw new SyntaxError("property sets must have a defined parent property name");ml.lastIndex=cn,E=af([],"}"),E.name=u,e.push(E),Co[cn]===","?r.lastIndex=++cn:o=!0;break;case"[":ml.lastIndex=cn,u?(E=af(new pl,"]"),E.name=u):E=af(e.conditions?new pl:[],"]"),e.conditions?(sm(e,d),e.conditions.push(E),s=null):e.push(E),Co[cn]===","?r.lastIndex=++cn:o=!0;break;case")":case"]":case"}":if(t===f[0]){if(e.conditions){if(s){let h={comparator:i||"equals",attribute:s,value:l(u)};i==="eq"&&BH(h,u),sm(e,d),e.conditions.push(h)}else if(u)throw new SyntaxError("no attribute or comparison specified")}else(u||e.length>0&&c)&&e.push(cf(u));return e}else throw t?new SyntaxError(`expected '${t}', but encountered '${f[0]}'`):new SyntaxError(`unexpected token '${f[0]}'`);default:throw new SyntaxError(`unexpected operator '${f}'`)}if(t!==")"&&(r=s?Mse:ml,r.lastIndex=cn),cn===Co.length)return e}if(t)throw new SyntaxError(`expected '${t}', but encountered end of string`)}function sm(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 cf(e){return e.indexOf(".")>-1?e.split(".").map(cf):decodeURIComponent(e)}function xH(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 Pn.ClientError(`Unknown type ${t}`)}return decodeURIComponent(e)}function BH(e,t){if(t.indexOf("*")>-1)if(t.endsWith("*"))e.comparator="starts_with",e.value=decodeURIComponent(t.slice(0,-1));else throw new Pn.ClientError("wildcard can only be used at the end of a string")}function HH(e){let t=kH(e[0]);return e.length>1&&(t.next=HH(e.slice(1))),t}function kH(e){if(Array.isArray(e)){let t=kH(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 Rs(e){return Array.isArray(e)?e.join("\0"):e}function Hi(e){let t=Date.now();return(e.estimatedEntryCountExpires||0)<t&&(e.estimatedEntryCount=e.getStats().entryCount,e.estimatedEntryCountExpires=t+1e4),e.estimatedEntryCount}function Use(e,t,r){return t*r/Hi(e)}var Pn,gb,Zs,wo,Nse,Ise,wse,Cse,Rb,bb,Pse,ml,Mse,cn,Co,pl,va,lf=Oe(()=>{Pn=U(ce()),gb=U(Ft()),Zs=require("ordered-binary"),wo=require("lmdb"),Nse=.3,Ise=.1,wse=.05,Cse={"<":"lt","<=":"le",">":"gt",">=":"ge","!=":"ne","==":"eq","===":"equals","!==":"not_equal"},Rb={lt:!0,le:!0,gt:!0,ge:!0,ne:!0,eq:!0};a(Ab,"executeConditions");a(Sl,"searchByIndex");a(ei,"findAttribute");a(Dse,"joinTo");a(Lse,"joinFrom");bb={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(yb,"filterByType");a(im,"estimateCondition");Pse=/[()[\]|!<>.]|(=\w*=)/,ml=/([^?&|=<>!([{}\]),]*)([([{}\])|,&]|[=<>!]*)/g,Mse=/([^&|=[\]{}]+)([[\]{}]|[&|=]*)/g;a(om,"parseQuery");a(af,"parseBlock");a(sm,"assignOperator");a(cf,"decodeProperty");a(xH,"typedDecoding");a(BH,"wildcardDecoding");a(HH,"toSortObject");a(kH,"toSortEntry");pl=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(Rs,"flattenKey");a(Hi,"estimatedEntryCount");a(Use,"intersectionEstimate");va=class{constructor(t){this.url=t}static{a(this,"SimpleURLQuery")}get(){}[Symbol.iterator](){return[][Symbol.iterator]()}}});function $H(e){let t={openapi:vse,info:{title:"HarperDB HTTP REST interface",version:(0,VH.version)()},paths:{},components:{schemas:{},securitySchemes:{basicAuth:{type:"http",scheme:"basic"},bearerAuth:{type:"http",scheme:"bearer",bearerFormat:"JWT"}}}},r=[{basicAuth:[],bearerAuth:[]}];for(let[,n]of e){if(!n.path)continue;let{path:s}=n,i=s.split("/").slice(-1),{attributes:o,primaryKey:c,prototype:l}=n.Resource;if(c=c??"id",!c)continue;let d={},u=[];if(o)for(let{type:A,name:N,elements:V,relationship:v,definition:J}of o){if(v)A==="array"?d[N]={type:"array",items:{$ref:Do+V.type}}:d[N]={$ref:Do+A};else{let $=J??V?.definition;if($){if(!t.components.schemas[$.type]){let F={};$.properties.forEach(ne=>{F[ne.name]=new wb(Ob[ne.type],ne.type)}),t.components.schemas[$.type]=new qH(F)}A==="array"?d[N]={type:"array",items:{$ref:Do+$.type}}:d[N]={$ref:Do+$.type}}else A==="array"?V.type==="Any"||V.type=="ID"?d[N]={type:"array",items:{format:V.type}}:d[N]={type:"array",items:new wb(Ob[V.type],V.type)}:A==="Any"||A=="ID"?d[N]={format:A}:d[N]=new wb(Ob[A],A)}u.push(new Cb(N,"query",d[N]))}let f=Object.keys(d),E=new Cb(c,"path",{format:"ID"});E.required=!0,E.description="primary key of record";let _=new Cb("property","path",{enum:f});_.required=!0,t.components.schemas[i]=new qH(d);let h=l.post!==Resource.prototype.post||l.update,p=typeof l.put=="function",S=typeof l.get=="function",g=typeof l.delete=="function",T="/"+s+"/";h&&(t.paths[T]={},t.paths[T].post=new xse(i,r,"create a new record auto-assigning a primary key")),S&&(t.paths[T]||(t.paths[T]={}),t.paths[T].get=new Nb(u,r,{200:new Ib({$ref:Do+i})},"search for records by the specified property name and value pairs")),g&&(t.paths[T]||(t.paths[T]={}),t.paths[T].delete=new GH(u,r,"delete all the records that match the provided query",{204:new FH})),T="/"+s+"/{"+c+"}",S&&(t.paths[T]={},t.paths[T].get=new Nb([E],r,{200:new Ib({$ref:Do+i})},"retrieve a record by its primary key")),p&&(t.paths[T]||(t.paths[T]={}),t.paths[T].put=new Bse([E],r,i,"create or update the record with the URL path that maps to the record's primary key")),g&&(t.paths[T]||(t.paths[T]={}),t.paths[T].delete=new GH([E],r,"delete a record with the given primary key",{204:new FH})),S&&_.schema.enum.length>0&&(T="/"+s+"/{"+c+"}.{property}",t.paths[T]={},t.paths[T].get=new Nb([E,_],r,{200:new Ib({enum:f})},"used to retrieve the specified property of the specified record"))}return t}function xse(e,t,r){this.description=r,this.requestBody={content:{"application/json":{schema:{$ref:Do+e}}}},this.security=t,this.responses={200:{description:Db,headers:{Location:{description:"primary key of new record",schema:{type:"string",format:"ID"}}},content:{"application/json":{schema:{type:"string",format:"ID"}}}}}}function Nb(e,t,r,n){this.description=n,this.parameters=e,this.security=t,this.responses=r}function Ib(e){this.description=Db,this.content={"application/json":{schema:e}}}function FH(){this.description="successfully processed request, no content returned to client"}function Bse(e,t,r,n){this.description=n,this.parameters=e,this.security=t,this.requestBody={content:{"application/json":{schema:{$ref:Do+r}}}},this.responses={200:{description:Db}}}function GH(e,t,r,n){this.description=r,this.parameters=e,this.security=t,this.responses=n}function qH(e){this.type="object",this.properties=e}function wb(e,t){this.type=e,this.format=t}function Cb(e,t,r){this.name=e,this.in=t,this.schema=r}var VH,vse,Ob,Do,Db,YH=Oe(()=>{VH=U(vE()),vse="3.0.3",Ob={Int:"integer",Float:"number",Long:"integer",String:"string",Boolean:"boolean",Date:"string",Bytes:"string",BigInt:"integer",array:"array"},Do="#/components/schemas/",Db="successful operation";a($H,"generateJsonApi");a(xse,"Post");a(Nb,"Get");a(Ib,"Response200");a(FH,"Response204");a(Bse,"Put");a(GH,"Delete");a(qH,"ResourceSchema");a(wb,"Type");a(Cb,"Parameter")});var cm={};Ze(cm,{start:()=>Fse});async function kse(e,t){let r=e.headers.asObject,n=r.accept==="text/event-stream",s=n?"CONNECT":e.method;e.search&&om(e);let i=new Li;try{e.responseHeaders=i;let o=e.url.slice(1),c,l;if(o!==KH){let S=am.getMatch(o,n?"sse":"rest");if(!S)return t(e);e.handlerPath=S.path,c=new va(S.relativeURL),c.async=!0,l=S.Resource}let d=r["cache-control"];if(d){let S=zH(d);for(let g of S)switch(g.name){case"max-age":e.expiresAt=g.value*1e3+Date.now();break;case"only-if-cached":e.onlyIfCached=!0;break;case"no-cache":e.noCache=!0;break;case"no-store":e.noCacheStore=!0;break;case"stale-if-error":e.staleIfError=!0;break;case"must-revalidate":e.mustRevalidate=!0;break}}let u=r["x-replicate-to"];if(u){let S=zH(u).map(g=>(g.next?.name==="confirm"&&g.next.value>=0&&(e.replicatedConfirmation=+g.next.value),g.name));e.replicateTo=S.length===1&&+S[0]>=0?+S[0]:S[0]==="*"?void 0:S}let f=await Tt(e,()=>{if(r["content-length"]||r["transfer-encoding"])try{e.data=Ma(r["content-type"],!0)(e.body,e.headers)}catch(S){throw new Tl.ClientError(S,400)}if(e.authorize=!0,o===KH&&s==="GET"){if(e?.user?.role?.permission?.super_user)return $H(am);throw new Tl.ServerError("Forbidden",403)}switch(s){case"GET":case"HEAD":return l.get(c,e);case"POST":return l.post(c,e.data,e);case"PUT":return l.put(c,e.data,e);case"DELETE":return l.delete(c,e);case"PATCH":return l.patch(c,e.data,e);case"OPTIONS":i.setIfNone("Allow","GET, HEAD, POST, PUT, DELETE, PATCH, OPTIONS, TRACE, QUERY, COPY, MOVE");return;case"CONNECT":return l.connect(c,null,e);case"TRACE":return"HarperDB is the terminating server";case"QUERY":return l.query(c,e.data,e);case"COPY":return l.copy(c,r.destination,e);case"MOVE":return l.move(c,r.destination,e);case"BREW":throw new Tl.ClientError("HarperDB is short and stout and can't brew coffee",418);default:throw new Tl.ServerError(`Method ${s} is not recognized`,501)}}),E=200,_;if(f==null)E=s==="GET"||s==="HEAD"?404:204,Lb.lastModified&&e.lastModified&&i.setIfNone("Last-Modified",new Date(e.lastModified).toUTCString());else{if(f.status>0&&f.headers)return f.headers=FA(f.headers,i),f.data!==void 0&&(f.body=ef(f.data,e,f)),f;if(_=e.lastModified){Hse[0]=_;let S=String.fromCharCode(34,(br[0]&63)+62,(br[0]>>6)+(br[1]<<2&63)+62,(br[1]>>4)+(br[2]<<4&63)+62,(br[2]>>2)+62,(br[3]&63)+62,(br[3]>>6)+(br[4]<<2&63)+62,(br[4]>>4)+(br[5]<<4&63)+62,(br[5]>>2)+62,(br[6]&63)+62,(br[6]>>6)+(br[7]<<2&63)+62,34),g=r["if-none-match"];g&&S==g?(f?.onDone&&f.onDone(),E=304,f=void 0):i.setIfNone("ETag",S),Lb.lastModified&&i.setIfNone("Last-Modified",new Date(_).toUTCString())}}e.createdResource&&(E=201),e.newLocation&&i.setIfNone("Location",e.newLocation);let h={status:E,headers:i,body:void 0},p=f?.wasLoadedFromSource?.();return p!==void 0&&(h.wasCacheMiss=p,!p&&_&&i.setIfNone("Age",Math.round((Date.now()-(e.lastRefreshed||_))/1e3))),f!==void 0&&(h.body=ef(f,e,h),s==="HEAD"&&(h.body=void 0)),h}catch(o){o.statusCode?o.statusCode===500?xa.warn(o):xa.info(o):xa.error(o),o.statusCode===405&&(o.method&&(o.message+=` to handle HTTP method ${o.method.toUpperCase()||""}`),o.allow&&(o.allow.push("trace","head","options"),i.setIfNone("Allow",o.allow.map(l=>l.toUpperCase()).join(", "))));let c={status:o.statusCode||500,headers:i,body:void 0};return c.body=ef(o.contentType?o:o.toString(),e,c),c}}function Fse(e){Lb=e,!WH&&(WH=!0,am=e.resources,e.server.http(async(t,r)=>{if(!t.isWebSocket)return kse(t,r)},e),e.server.ws(async(t,r,n)=>{uf++;let s=new mn;QH||(QH=!0,sf(l=>{uf>0&&l.push({metric:"ws-connections",connections:uf,byThread:!0})}));let i;t.on("error",l=>{i=!0,xa.warn(l)});let o;t.on("message",a(function(d){o||(o=Ma(r.headers.asObject["content-type"]));let u=o(d);s.push(u)},"message"));let c;t.on("close",()=>{uf--,Ln(!i,"connection","ws","disconnect"),s.emit("close"),c&&c.return()});try{await n;let l=r.url.slice(1),d=am.getMatch(l,"ws");if(Ln(!!d,"connection","ws","connect"),d){r.handlerPath=d.path,an(h=>({count:h.count,total:uf}),"connections",r.handlerPath,"connect","ws"),r.authorize=!0;let u=new va(d.relativeURL),f=d.Resource;c=(await Tt(r,()=>f.connect(u,s,r)))[Symbol.asyncIterator]();let _;for(;!(_=await c.next()).done;){let h=wa(_.value,r);t.send(h),an(h.length,"bytes-sent",r.handlerPath,"message","ws")}}else return t.close(1011,`No resource was found to handle ${r.pathname}`)}catch(l){t.close(Gse[l.statusCode]||1011,l.toString())}t.close()},e))}function zH(e){return e.split(/\s*,\s*/).map(r=>{let n,s=r.split(/\s*;\s*/),i;for(;i=s.pop();)if(i.includes("=")){let[o,c]=i.split(/\s*=\s*/);n={name:o.toLowerCase(),value:c,next:n}}else n={name:i.toLowerCase(),next:n};return n})}var xa,Tl,br,Hse,Lb,KH,WH,am,QH,uf,Gse,jH=Oe(()=>{ll();Bi();xa=U(X()),Tl=U(ce());lf();ic();oa();Hd();YH();lf();br=new Uint8Array(8),Hse=new Float64Array(br.buffer,0,1),Lb={},KH="openapi";a(kse,"http");uf=0;a(Fse,"start");Gse={401:3e3,403:3003};a(zH,"parseHeaderValue")});var Pb=I((URe,JH)=>{var{recordAction:lm,recordActionBinary:qse}=(Bi(),ae(of)),Vse=require("fastify-plugin"),$se=200;JH.exports=Vse(function(e,t,r){e.addHook("onResponse",async(n,s)=>{let i=s.elapsedTime}),e.addHook("onSend",async(n,s,i)=>{let o=s.elapsedTime,c=performance.now(),l=s.request.routeOptions,d,u,f;l.config?.isOperation?(d=n.body?.operation,u="operation"):(d=l.url,u="fastify-route",f=l.method),lm(o,"duration",d,f,u),qse(s.raw.statusCode<400,"success",d,f,u);let E=$se;i?.pipe?(i.on("data",S=>{E+=S.length}),i.on("end",()=>{lm(performance.now()-c,"transfer",d,f,u),lm(E,"bytes-sent",d,f,u)})):(E+=i?.length||0,lm(E,"bytes-sent",d,f,u));let _=o.toFixed(3),h=s.getHeader("Server-Timing"),p=`db;dur=${_}`;s.header("Server-Timing",h?`${h}, ${p}`:p)}),r()},{name:"hdb-request-time"})});var Hb=I((BRe,tk)=>{var _m=require("clone"),Em=mt(),Yse=re(),dm=H(),vRe=X(),Mb=require("fs"),vb=require("joi"),{string:fm}=vb.types(),{hdb_errors:Kse,handleHDBError:um}=ce(),{HDB_ERROR_MSGS:xRe,HTTP_STATUS_CODES:Ub}=Kse,{common_validators:gl}=xs(),XH=" is required",Wse=["insert","update","upsert"],xb={database:{presence:!1,format:gl.schema_format,length:gl.schema_length},schema:{presence:!1,format:gl.schema_format,length:gl.schema_length},table:{presence:!0,format:gl.schema_format,length:gl.schema_length},action:{inclusion:{within:Wse,message:"is required and must be either insert, update, or upsert"}},file_path:{},csv_url:{url:{allowLocal:!0}},data:{},passthrough_headers:{}},Qse={schema:fm.required(),table:fm.required(),action:fm.valid("insert","update","upsert")},{AWS_ACCESS_KEY:zse,AWS_SECRET:jse,AWS_BUCKET:Jse,AWS_FILE_KEY:Xse,REGION:Zse}=dm.S3_BUCKET_AUTH_KEYS,eie={s3:{presence:!0},[`s3.${zse}`]:{presence:!0,type:"String"},[`s3.${jse}`]:{presence:!0,type:"String"},[`s3.${Jse}`]:{presence:!0,type:"String"},[`s3.${Xse}`]:{presence:!0,type:"String",hasValidFileExt:[".csv",".json"]},[`s3.${Zse}`]:{presence:!0,type:"String"}},ZH=_m(xb);ZH.data.presence={message:XH};var ek=_m(xb);ek.file_path.presence={message:XH};var tie=Object.assign(_m(xb),eie),Bb=_m(Qse);Bb.csv_url=fm.uri().messages({"string.uri":"'csv_url' must be a valid url"}).required();Bb.passthrough_headers=vb.object();function rie(e){let t=Em.validateObject(e,ZH);return hm(e,t)}a(rie,"dataObject");function nie(e){let t=Em.validateBySchema(e,vb.object(Bb));return hm(e,t)}a(nie,"urlObject");function sie(e){let t=Em.validateObject(e,ek);return hm(e,t)}a(sie,"fileObject");function iie(e){let t=Em.validateObject(e,tie);return hm(e,t)}a(iie,"s3FileObject");function hm(e,t){if(!t){let r=Yse.checkGlobalSchemaTable(e.schema,e.table);if(r)return um(new Error,r,Ub.BAD_REQUEST);if(e.operation===dm.OPERATIONS_ENUM.CSV_FILE_LOAD)try{Mb.accessSync(e.file_path,Mb.constants.R_OK|Mb.constants.F_OK)}catch(n){return n.code===dm.NODE_ERROR_CODES.ENOENT?um(n,`No such file or directory ${n.path}`,Ub.BAD_REQUEST):n.code===dm.NODE_ERROR_CODES.EACCES?um(n,`Permission denied ${n.path}`,Ub.BAD_REQUEST):um(n)}}return t}a(hm,"postValidateChecks");tk.exports={dataObject:rie,urlObject:nie,fileObject:sie,s3FileObject:iie}});var kb=I((kRe,rk)=>{"use strict";var df=X(),mm=H();async function oie(e,t,r,n=void 0){if(!e||typeof e!="function")throw new Error("Invalid function parameter");let s;try{return s=await e(t),r&&await r(t,s,n),t.operation===mm.OPERATIONS_ENUM.INSERT||t.operation===mm.OPERATIONS_ENUM.UPDATE||t.operation===mm.OPERATIONS_ENUM.UPSERT?(delete s.new_attributes,delete s.txn_time):t.operation===mm.OPERATIONS_ENUM.DELETE&&delete s.txn_time,s}catch(i){throw i.message&&typeof i.message=="string"&&i.message.includes("already exists")?(df.info(i.message),i):i.http_resp_msg?(df.error(`Error calling operation: ${e.name}`),df.error(i.http_resp_msg),i):(df.error(`Error calling operation: ${e.name}`),df.error(i),i)}}a(oie,"callOperationFunctionAsAwait");rk.exports={callOperationFunctionAsAwait:oie}});var sk=I((GRe,nk)=>{"use strict";var Fb=class{static{a(this,"BulkLoadFileObject")}constructor(t,r,n,s,i,o,c=null){this.op=t,this.action=r,this.schema=n,this.table=s,this.file_path=i,this.file_type=o,this.role_perms=c}},Gb=class{static{a(this,"BulkLoadDataObject")}constructor(t,r,n,s){this.action=t,this.schema=r,this.table=n,this.data=s}};nk.exports={BulkLoadFileObject:Fb,BulkLoadDataObject:Gb}});var ok=I((VRe,ik)=>{"use strict";var qb=class{static{a(this,"ClusteringOriginObject")}constructor(t,r,n){this.timestamp=t,this.user=r,this.node_name=n}};ik.exports=qb});var Qb=I((zRe,bk)=>{"use strict";var pm=qn(),Tm=Hb(),aie=require("needle"),As=H(),YRe=Pt(),Rl=re(),{handleHDBError:xt,hdb_errors:hk}=ce(),{HTTP_STATUS_CODES:yr,HDB_ERROR_MSGS:cr,CHECK_LOGS_WRAPPER:Ha}=hk,Al=X(),Vb=require("papaparse");Rl.promisifyPapaParse();var bs=require("fs-extra"),cie=require("path"),{chain:ak}=require("stream-chain"),ck=require("stream-json/streamers/StreamArray"),lk=require("stream-json/utils/Batch"),uk=require("stream-chain/utils/comp"),{finished:dk}=require("stream"),lie=ie(),mk=kb(),uie=lb(),{BulkLoadFileObject:Yb,BulkLoadDataObject:die}=sk(),Kb=ZA(),{verifyBulkLoadAttributePerms:pk}=Qh(),KRe=ok(),WRe=or(),QRe=mi(),{databases:fie}=(Ne(),ae(it)),{coerceType:_ie}=(gm(),ae(zb)),fk="No records parsed from csv file.",Ba=`${lie.get("HDB_ROOT")}/tmp`,{schema_regex:Eie}=xs(),_k=1024*1024*2,Ek=5e3,hie={"text/csv":!0,"application/octet-stream":!0,"text/plain":!0,"application/vnd.ms-excel":!0};bk.exports={csvDataLoad:mie,csvURLLoad:pie,csvFileLoad:Sie,importFromS3:Tie};async function mie(e,t){let r=Tm.dataObject(e);if(r)throw xt(r,r.message,yr.BAD_REQUEST,void 0,void 0,!0);let n={};try{let s=gk(e.schema,e.table),i=Vb.parse(e.data,{header:!0,skipEmptyLines:!0,transform:$b.bind(null,s),dynamicTyping:!1}),o=new Kb;e.hdb_user&&e.hdb_user.role&&e.hdb_user.role.permission&&e.hdb_user.role.permission.super_user!==!0&&pk(e.hdb_user.role.permission,this.job_operation_function.name,e.action,e.schema,e.table,i.meta.fields,o);let c=o.getPermsResponse();if(c)throw xt(new Error,c,yr.BAD_REQUEST,void 0,void 0,!0);let l=new die(e.action,e.schema,e.table,i.data);return n=await mk.callOperationFunctionAsAwait(Rk,l,null),n.message===fk?fk:Ak(n.records,n.number_written)}catch(s){throw ka(s)}}a(mie,"csvDataLoad");async function pie(e){let t=Tm.urlObject(e);if(t)throw xt(t,t.message,yr.BAD_REQUEST,void 0,void 0,!0);let r=`${Date.now()}.csv`,n=`${Ba}/${r}`;try{await gie(e,r)}catch(s){throw Al.error(cr.DOWNLOAD_FILE_ERR(r)+" - "+s),xt(s,Ha(cr.DOWNLOAD_FILE_ERR(r)))}try{let s=new Yb(this.job_operation_function.name,e.action,e.schema,e.table,n,As.VALID_S3_FILE_TYPES.CSV,e.hdb_user.role.permission),i=await Wb(s);return await Sm(n),i}catch(s){throw await Sm(n),ka(s)}}a(pie,"csvURLLoad");async function Sie(e){let t=Tm.fileObject(e);if(t)throw xt(t,t.message,yr.BAD_REQUEST,void 0,void 0,!0);let r=new Yb(this.job_operation_function.name,e.action,e.schema,e.table,e.file_path,As.VALID_S3_FILE_TYPES.CSV,e.hdb_user.role.permission);try{return await Wb(r)}catch(n){throw ka(n)}}a(Sie,"csvFileLoad");async function Tie(e){let t=Tm.s3FileObject(e);if(t)throw xt(t,t.message,yr.BAD_REQUEST,void 0,void 0,!0);let r;try{let n=cie.extname(e.s3.key),s=`${Date.now()}${n}`;r=`${Ba}/${s}`;let i=new Yb(this.job_operation_function.name,e.action,e.schema,e.table,r,n,e.hdb_user.role.permission);await Rie(s,e);let o=await Wb(i);return await Sm(r),o}catch(n){throw await Sm(r),ka(n)}}a(Tie,"importFromS3");async function gie(e,t){let r;try{let n=e.passthrough_headers?{headers:e.passthrough_headers}:void 0;r=await aie("get",e.csv_url,n)}catch(n){let s=`Error downloading CSV file from ${e.csv_url}, status code: ${n.statusCode}. Check the log for more information.`;throw xt(n,s,n.statusCode,As.LOG_LEVELS.ERROR,"Error downloading CSV file - "+n)}bie(r,e.csv_url),await Aie(t,r.raw)}a(gie,"downloadCSVFile");async function Rie(e,t){try{let r=`${Ba}/${e}`;await bs.mkdirp(Ba),await bs.writeFile(`${Ba}/${e}`,"",{flag:"a+"});let n=await bs.createWriteStream(r),s=await uie.getFileStreamFromS3(t);await new Promise((i,o)=>{s.on("error",function(c){o(c)}),s.pipe(n).on("error",function(c){o(c)}).on("close",function(){Al.info(`${t.s3.key} successfully downloaded to ${r}`),i()})})}catch(r){throw Al.error(cr.S3_DOWNLOAD_ERR+" - "+r),xt(r,Ha(cr.S3_DOWNLOAD_ERR))}}a(Rie,"downloadFileFromS3");async function Aie(e,t){try{await bs.mkdirp(Ba),await bs.writeFile(`${Ba}/${e}`,t)}catch(r){throw Al.error(cr.WRITE_TEMP_FILE_ERR),xt(r,Ha(cr.DEFAULT_BULK_LOAD_ERR))}}a(Aie,"writeFileToTempFolder");async function Sm(e){if(e)try{await bs.access(e),await bs.unlink(e)}catch{Al.warn(`could not delete temp csv file at ${e}, file does not exist`)}}a(Sm,"deleteTempFile");function bie(e,t){if(e.statusCode!==hk.HTTP_STATUS_CODES.OK)throw xt(new Error,`CSV Load failed from URL: ${t}, status code: ${e.statusCode}, message: ${e.statusMessage}`,yr.BAD_REQUEST);if(!hie[e.headers["content-type"]])throw xt(new Error,`CSV Load failed from URL: ${t}, unsupported content type: ${e.headers["content-type"]}`,yr.BAD_REQUEST);if(!e.raw)throw xt(new Error,`CSV Load failed from URL: ${t}, no csv found at url`,yr.BAD_REQUEST)}a(bie,"validateURLResponse");async function Wb(e){try{let t;switch(e.file_type){case As.VALID_S3_FILE_TYPES.CSV:t=await yie(e);break;case As.VALID_S3_FILE_TYPES.JSON:t=await Oie(e);break;default:throw xt(new Error,cr.DEFAULT_BULK_LOAD_ERR,yr.BAD_REQUEST,As.LOG_LEVELS.ERROR,cr.INVALID_FILE_EXT_ERR(e))}return Ak(t.records,t.number_written)}catch(t){throw ka(t)}}a(Wb,"fileLoad");async function Sk(e,t,r,n,s){let i=n.data?n.data:n;if(i.length===0)return;s&&s.pause();let o={operation:e.action,schema:e.schema,table:e.table,records:i};try{let{attributes:c}=await pm.validation(o);e.role_perms&&e.role_perms.super_user!==!0&&pk(e.role_perms,e.op,e.action,e.schema,e.table,c,t),s&&s.resume()}catch(c){let l=xt(c);r(l)}}a(Sk,"validateChunk");async function Tk(e,t,r,n,s){let i=n.data?n.data:n;if(i.length===0)return;Rl.autoCastJSONDeep(i),s&&s.pause();let o=n.meta?n.meta.fields:null;if(o)i.forEach(c=>{!Rl.isEmpty(c)&&!Rl.isEmpty(c.__parsed_extra)&&delete c.__parsed_extra});else{let c=new Set;i.forEach(l=>{Object.keys(l).forEach(d=>c.add(d))}),o=[...c]}try{let c={schema:e.schema,table:e.table,action:e.action,data:i},l=await mk.callOperationFunctionAsAwait(Rk,c,null);t.records+=l.records,t.number_written+=l.number_written,s&&s.resume()}catch(c){let l=xt(c,Ha(cr.INSERT_CSV_ERR),yr.INTERNAL_SERVER_ERROR,As.LOG_LEVELS.ERROR,cr.INSERT_CSV_ERR+" - "+c);r(l)}}a(Tk,"insertChunk");async function yie(e){let t={records:0,number_written:0},r=gk(e.schema,e.table);try{let n=new Kb,s=bs.createReadStream(e.file_path,{highWaterMark:_k});s.setEncoding("utf8"),await Vb.parsePromise(s,Sk.bind(null,e,n),$b.bind(null,r));let i=n.getPermsResponse();if(i)throw xt(new Error,i,yr.BAD_REQUEST);return s=bs.createReadStream(e.file_path,{highWaterMark:_k}),s.setEncoding("utf8"),await Vb.parsePromise(s,Tk.bind(null,e,t),$b.bind(null,r)),s.destroy(),t}catch(n){throw xt(n,Ha(cr.PAPA_PARSE_ERR),yr.INTERNAL_SERVER_ERROR,As.LOG_LEVELS.ERROR,cr.PAPA_PARSE_ERR+n)}}a(yie,"callPapaParse");function gk(e,t){let r=fie[e][t].attributes,n=new Map;for(let s of r)s.type&&!s.computed&&!s.relationship&&n.set(s.name,i=>_ie(i,s));return n}a(gk,"createTransformMap");function $b(e,t,r){let n=e.get(r);return n?n(t):Rl.autoCast(t)}a($b,"typeFunction");async function Oie(e){let t={records:0,number_written:0},r=a(n=>{throw n},"throwErr");try{let n=new Kb,s=ak([bs.createReadStream(e.file_path,{encoding:"utf-8"}),ck.withParser(),c=>c.value,new lk({batchSize:Ek}),uk(async c=>{await Sk(e,n,r,c)})]);await new Promise((c,l)=>{dk(s,d=>{d?l(d):c()}),s.resume()});let i=n.getPermsResponse();if(i)throw xt(new Error,i,yr.BAD_REQUEST);let o=ak([bs.createReadStream(e.file_path,{encoding:"utf-8"}),ck.withParser(),c=>c.value,new lk({batchSize:Ek}),uk(async c=>{await Tk(e,t,r,c)})]);return await new Promise((c,l)=>{dk(o,d=>{d?l(d):c()}),o.resume()}),t}catch(n){throw xt(n,Ha(cr.INSERT_JSON_ERR),yr.INTERNAL_SERVER_ERROR,As.LOG_LEVELS.ERROR,cr.INSERT_JSON_ERR+n)}}a(Oie,"insertJson");async function Rk(e){let t={};try{e.data&&e.data.length>0&&Nie(e.data[0])?t=await Iie(e.data,e.schema,e.table,e.action):(t.message="No records parsed from csv file.",Al.info(t.message))}catch(r){throw ka(r)}return t}a(Rk,"callBulkFileLoad");function Nie(e){let t=Object.keys(e);for(let r of t)if(!Eie.test(r))throw new Error(`Invalid column name '${r}', cancelling load operation`);return!0}a(Nie,"validateColumnNames");async function Iie(e,t,r,n){n||(n="insert");let s={operation:n,schema:t,table:r,records:e},i;switch(n){case"insert":i=pm.insert;break;case"update":i=pm.update;break;case"upsert":i=pm.upsert;break;default:throw xt(new Error,cr.INVALID_ACTION_PARAM_ERR(n),yr.BAD_REQUEST,As.LOG_LEVELS.ERROR,cr.INVALID_ACTION_PARAM_ERR(n))}try{let o=await i(s),c;switch(n){case"insert":c=o.inserted_hashes;break;case"update":c=o.update_hashes;break;case"upsert":c=o.upserted_hashes;break;default:break}if(Array.isArray(o.skipped_hashes)&&o.skipped_hashes.length>0){let u=global.hdb_schema[t][r].hash_attribute,f=e.length;for(;f--;)o.skipped_hashes.indexOf(e[f][u])>=0&&e.splice(f,1)}let l=Rl.isEmptyOrZeroLength(c)?0:c.length;return{records:e.length,number_written:l,new_attributes:o.new_attributes}}catch(o){throw ka(o)}}a(Iie,"bulkFileLoad");function Ak(e,t){return`successfully loaded ${t} of ${e} records`}a(Ak,"buildResponseMsg");function ka(e){return xt(e,Ha(cr.DEFAULT_BULK_LOAD_ERR),yr.INTERNAL_SERVER_ERROR,As.LOG_LEVELS.ERROR,cr.DEFAULT_BULK_LOAD_ERR+" - "+e)}a(ka,"buildTopLevelErrMsg")});var Ok=I((JRe,yk)=>{"use strict";var jb=class{static{a(this,"SqlSearchObject")}constructor(t,r){this.operation="sql",this.sql=t,this.hdb_user=r}};yk.exports=jb});var wk=I((ZRe,Ik)=>{"use strict";var wie=H(),Nk=require("moment"),Cie=require("uuid").v4,Jb=class{static{a(this,"JobObject")}constructor(){this.id=Cie(),this.type=void 0,this.start_datetime=Nk().valueOf(),this.created_datetime=Nk().valueOf(),this.end_datetime=void 0,this.status=wie.JOB_STATUS_ENUM.CREATED,this.message=void 0,this.user=void 0,this.request=void 0}};Ik.exports=Jb});var Xb=I((tAe,xk)=>{"use strict";var Die=require("uuid").v4,Mk=qn(),Uk=gn(),Lie=Gs(),Pie=yc(),Mie=Ok(),gt=H(),Uie=wk(),vie=jg(),rs=X(),xie=bu(),bl=re(),{promisify:Bie}=require("util"),Fa=require("moment"),Hie=jh(),Rm=Hb(),Ck=nT(),{deleteTransactionLogsBeforeValidator:kie}=QA(),{handleHDBError:Dk,hdb_errors:Fie}=ce(),{HTTP_STATUS_CODES:Lk}=Fie,Pk=Uk.searchByValue,Gie=Uk.searchByHash,qie=Mk.insert,Vie=Bie(Hie.evaluateSQL),$ie=Mk.update;xk.exports={addJob:Wie,updateJob:zie,handleGetJob:Yie,handleGetJobsByStartDate:Kie,getJobById:vk};async function Yie(e){try{let t=await vk(e.id);return bl.isEmptyOrZeroLength(t)||(t[0]={...t[0]},t[0].request!==void 0&&delete t[0].request,delete t[0].__createdtime__,delete t[0].__updatedtime__),t}catch(t){let r=`There was an error getting job: ${t}`;throw rs.error("There was an error getting job",t),new Error(r)}}a(Yie,"handleGetJob");async function Kie(e){try{let t=await Qie(e);if(rs.trace(`Searching for jobs from ${e.from_date} to ${e.to_date}`),t&&t.length>0)for(let r of t)r.start_datetime&&(r.start_datetime_converted=Fa(r.start_datetime)),r.end_datetime&&(r.end_datetime_converted=Fa(r.end_datetime)),r.request!==void 0&&delete r.request,delete r.__createdtime__,delete r.__updatedtime__;return t}catch(t){let r=`There was an error searching jobs by date: ${t}`;throw rs.error(r),new Error(r)}}a(Kie,"handleGetJobsByStartDate");async function Wie(e){let t={message:"",error:"",success:!1,createdJob:void 0};if(!e||Object.keys(e).length===0||bl.isEmptyOrZeroLength(e.operation)){let u="job parameter is invalid";return rs.info(u),t.error=u,t}if(!gt.JOB_TYPE_ENUM[e.operation])return rs.info(`invalid job type specified: ${e.operation}.`),t;let r=e.operation,n;switch(r){case gt.OPERATIONS_ENUM.CSV_FILE_LOAD:n=Rm.fileObject(e);break;case gt.OPERATIONS_ENUM.CSV_URL_LOAD:n=Rm.urlObject(e);break;case gt.OPERATIONS_ENUM.CSV_DATA_LOAD:n=Rm.dataObject(e);break;case gt.OPERATIONS_ENUM.IMPORT_FROM_S3:n=Rm.s3FileObject(e);break;case gt.OPERATIONS_ENUM.DELETE_FILES_BEFORE:case gt.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE:n=Ck(e,"date");break;case gt.OPERATIONS_ENUM.DELETE_AUDIT_LOGS_BEFORE:n=Ck(e,"timestamp");break;case gt.OPERATIONS_ENUM.DELETE_TRANSACTION_LOGS_BEFORE:n=kie(e);break;case gt.OPERATIONS_ENUM.RESTART_SERVICE:if(gt.PROCESS_DESCRIPTORS_VALIDATE[e.service]===void 0)throw Dk(new Error,"Invalid service",Lk.BAD_REQUEST,void 0,void 0,!0);break;default:break}if(n)throw Dk(n,n.message,Lk.BAD_REQUEST,void 0,void 0,!0);let s=new Uie;s.type=e.operation===gt.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE?gt.OPERATIONS_ENUM.DELETE_FILES_BEFORE:e.operation,s.type=e.operation,s.user=e.hdb_user.username;let i=new Lie(gt.SYSTEM_SCHEMA_NAME,gt.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,"id",s.id,"id",["id"]),o;try{o=Array.from(await Pk(i))}catch(u){let f=`There was an error inserting a new job: ${u}`;return rs.error(f),t}let c=Array.isArray(o)?o:Object.keys(o);if(c&&c.length>0){s.id=Die();try{o=await Pk(i)}catch(u){let f=`There was an error inserting a new job: ${u}`;return rs.error(f),t}if(c=Array.isArray(o)?o:Object.keys(o),c&&c.length>0)return rs.error("Error creating a job, could not find a unique job id."),t}s.request=e;let l=new xie(gt.SYSTEM_SCHEMA_NAME,gt.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,"id",[s]),d;try{d=await qie(l)}catch(u){return rs.error(`There was an error inserting a job for job type: ${e.operation} -- ${u}`),t.success=!1,t}if(d.inserted_hashes.length===0)t.message=`Had a problem creating a job with type ${s.operation} and id ${s.id}`;else{let u=`Created a job with type ${s.type} and id ${s.id}`;t.message=u,t.createdJob=s,t.success=!0,rs.trace(u)}return t}a(Wie,"addJob");async function Qie(e){let t=Fa(e.from_date,Fa.ISO_8601),r=Fa(e.to_date,Fa.ISO_8601);if(!t.isValid())throw new Error("Invalid 'from' date, must be in ISO-8601 format (YYYY-MM-DD).");if(!r.isValid())throw new Error("Invalid 'to' date, must be in ISO-8601 format (YYYY-MM-DD)");let n=`select * from system.hdb_job where start_datetime > '${t.valueOf()}' and start_datetime < '${r.valueOf()}'`,s=new Mie(n,e.hdb_user);try{return await Vie(s)}catch(i){throw rs.error(`there was a problem searching for jobs from date ${e.from_date} to date ${e.to_date} ${i}`),new Error("there was an error searching for jobs. Please check the log for details.")}}a(Qie,"getJobsInDateRange");async function vk(e){if(bl.isEmptyOrZeroLength(e))return bl.errorizeMessage("Invalid job ID specified.");let t=new Pie(gt.SYSTEM_SCHEMA_NAME,gt.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,[e],["*"]);try{return await Gie(t)}catch(r){let n=`There was an error searching for a job by id: ${e} ${r}`;return rs.error(n),bl.errorizeMessage("there was an error searching for jobs. Please check the log for details.")}}a(vk,"getJobById");async function zie(e){if(Object.keys(e).length===0)throw new Error("invalid job object passed to updateJob");if(bl.isEmptyOrZeroLength(e.id))throw new Error("invalid ID passed to updateJob");(e.status===gt.JOB_STATUS_ENUM.COMPLETE||e.status===gt.JOB_STATUS_ENUM.ERROR)&&(e.end_datetime=Fa().valueOf());let t=new vie(gt.SYSTEM_SCHEMA_NAME,gt.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,[e]),r;return r=await $ie(t),r}a(zie,"updateJob")});var $k=I((nAe,Vk)=>{"use strict";var Bk=re(),lr=H(),jie=require("moment"),Am=Qb(),ff=X(),Hk=Xb(),kk=Jh(),Fk=Jo(),Gk=at(),Jie=$h(),Xie=xd(),{parentPort:Zie,isMainThread:qk}=require("worker_threads"),{onMessageByType:eoe}=at(),Zb=class{static{a(this,"RunnerMessage")}constructor(t,r){this.job=t,this.json=r}};async function toe(e){if(!e||Object.keys(e).length===0)throw new Error("Empty runner passed to parseMessage");if(!e.json||Object.keys(e.json).length===0)throw new Error("Empty JSON passed to parseMessage");if(!e.job||Object.keys(e.job).length===0)throw new Error("Empty job passed to parseMessage");if(Bk.isEmptyOrZeroLength(e.json.operation))throw new Error("Invalid operation");if(Bk.isEmptyOrZeroLength(e.job.id))throw new Error("Empty job id specified");switch(e.json.operation){case lr.JOB_TYPE_ENUM.csv_file_load:await ti(e,Am.csvFileLoad);break;case lr.JOB_TYPE_ENUM.csv_url_load:await ti(e,Am.csvURLLoad);break;case lr.JOB_TYPE_ENUM.csv_data_load:await ti(e,Am.csvDataLoad);break;case lr.JOB_TYPE_ENUM.import_from_s3:await ti(e,Am.importFromS3);break;case lr.JOB_TYPE_ENUM.empty_trash:break;case lr.JOB_TYPE_ENUM.export_local:await ti(e,kk.export_local);break;case lr.JOB_TYPE_ENUM.export_to_s3:await ti(e,kk.export_to_s3);break;case lr.JOB_TYPE_ENUM.delete_files_before:case lr.JOB_TYPE_ENUM.delete_records_before:await ti(e,Fk.deleteFilesBefore);break;case lr.JOB_TYPE_ENUM.delete_audit_logs_before:await ti(e,Fk.deleteAuditLogsBefore);break;case lr.JOB_TYPE_ENUM.delete_transaction_logs_before:await ti(e,Jie.deleteTransactionLogsBefore);break;case lr.JOB_TYPE_ENUM.restart_service:return await ti(e,Xie.restartService),`Restarting ${e.json.service}`;break;default:return`Invalid operation ${e.json.operation} specified`}}a(toe,"parseMessage");async function ti(e,t){try{e.job.status=lr.JOB_STATUS_ENUM.IN_PROGRESS,e.job.start_datetime=jie().valueOf(),await Hk.updateJob(e.job),await roe(e.job.id)}catch(r){let n=r.message!==void 0?r.message:r;typeof n=="string"?(n=`There was an error running ${t.name} job with id ${e.job.id} - ${n}`,r.message=n):ff.error(`There was an error running ${t.name} job with id ${e.job.id}`),ff.error(n),e.job.message=n,e.job.status=lr.JOB_STATUS_ENUM.ERROR;try{await Hk.updateJob(e.job)}catch(s){throw ff.error(`Unable to update job with id ${e.job.id}`),s}throw r}}a(ti,"runJob");async function roe(e){ff.trace("launching job thread:",e),qk?Gk.startWorker("server/jobs/jobProcess.js",{autoRestart:!1,name:"job",env:Object.assign({},process.env,{[lr.PROCESS_NAME_ENV_PROP]:`JOB-${e}`})}):Zie.postMessage({type:lr.ITC_EVENT_TYPES.START_JOB,jobId:e})}a(roe,"launchJobThread");qk&&eoe(lr.ITC_EVENT_TYPES.START_JOB,async(e,t)=>{try{Gk.startWorker("server/jobs/jobProcess.js",{autoRestart:!1,name:"job",env:Object.assign({},process.env,{[lr.PROCESS_NAME_ENV_PROP]:`JOB-${e.jobId}`})})}catch(r){ff.error(r)}});Vk.exports={parseMessage:toe,RunnerMessage:Zb}});var Kk=I((iAe,Yk)=>{"use strict";var ey=class{static{a(this,"OperationFunctionObject")}constructor(t,r=void 0){this.operation_function=t,this.job_operation_function=r}};Yk.exports=ey});var uF=I((cAe,oy)=>{"use strict";var Im=gn(),ny=jh(),bm=Qb(),ki=bE(),ym=Zi(),hf=Jo(),noe=vg(),_f=$n(),Om=$g(),Nt=WA(),Nm=X(),soe=Wg(),ioe=lh(),Wk=tA(),ooe=dh(),aoe=sA(),coe=iA(),loe=cA(),uoe=uA(),ty=_A(),Qk=Jh(),doe=Qh(),sy=Xb(),G=H(),{hdb_errors:pf,handleHDBError:mf}=ce(),{HTTP_STATUS_CODES:zk}=pf,ry=SA(),jk=xd(),oF=require("util"),yl=qn(),foe=eo(),_oe=Bc(),Jk=$k(),Xk=Xu(),Zk=(Lh(),ae(kd)),eF=dr(),tF=$h(),rF=Bh(),{setServerUtilities:Eoe}=(gm(),ae(zb)),{CONTEXT:aAe}=(ls(),ae(ZT)),{_assignPackageExport:hoe}=require("../index"),{transformReq:moe}=re(),{server:poe}=(Lr(),ae(ko)),Hr=Nm.loggerWithTag("operation"),Ef=To(),nF=(Ra(),ae(ga)),Soe=kb(),sF=Im.searchByHash,Toe=Im.searchByValue,goe=oF.promisify(Im.search),Roe=oF.promisify(ny.evaluateSQL),Aoe={[G.OPERATIONS_ENUM.CREATE_ATTRIBUTE]:!0,[G.OPERATIONS_ENUM.CREATE_TABLE]:!0,[G.OPERATIONS_ENUM.CREATE_SCHEMA]:!0,[G.OPERATIONS_ENUM.DROP_ATTRIBUTE]:!0,[G.OPERATIONS_ENUM.DROP_TABLE]:!0,[G.OPERATIONS_ENUM.DROP_SCHEMA]:!0},Q=Kk();async function aF(e,t){try{if(e.body.operation!=="read_log"&&(Nm.log_level===G.LOG_LEVELS.INFO||Nm.log_level===G.LOG_LEVELS.DEBUG||Nm.log_level===G.LOG_LEVELS.TRACE)){let{hdb_user:n,hdb_auth_header:s,password:i,...o}=e.body;Hr.info(o)}}catch(n){Hr.error(n)}let r=await Soe.callOperationFunctionAsAwait(t,e.body,null);if(typeof r!="object"&&(r={message:r}),r instanceof Error)throw r;return Aoe[e.body.operation]&&foe.setSchemaDataToGlobal(n=>{n&&Hr.error(n)}),r}a(aF,"processLocalTransaction");var iF=yoe();oy.exports={chooseOperation:cF,getOperationFunction:lF,operation:iy,processLocalTransaction:aF};Eoe(oy.exports);poe.operation=iy;function cF(e){let t;try{t=lF(e)}catch(s){throw Hr.error(`Error when selecting operation function - ${s}`),s}let{operation_function:r,job_operation_function:n}=t;try{if(e.operation==="sql"||e.search_operation&&e.search_operation.operation==="sql"){let s=e.operation==="sql"?e.sql:e.search_operation.sql,i=ny.convertSQLToAST(s);if(e.parsed_sql_object=i,!e.bypass_auth){let o=ny.checkASTPermissions(e,i);if(o)throw Hr.error(`${zk.FORBIDDEN} from operation ${e.operation}`),Hr.warn(`User '${e.hdb_user.username}' is not permitted to ${e.operation}`),mf(new Error,o,pf.HTTP_STATUS_CODES.FORBIDDEN,void 0,void 0,!0)}}else if(!e.bypass_auth&&e.operation!==G.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS&&e.operation!==G.OPERATIONS_ENUM.LOGIN&&e.operation!==G.OPERATIONS_ENUM.LOGOUT){let s=n===void 0?r:n,i=e.search_operation?e.search_operation:e;i.hdb_user||(i.hdb_user=e.hdb_user);let o=doe.verifyPerms(i,s);if(o)throw Hr.error(`${zk.FORBIDDEN} from operation ${e.operation}`),Hr.warn(`User '${i.hdb_user.username}' is not permitted to ${i.operation}`),mf(new Error,o,pf.HTTP_STATUS_CODES.FORBIDDEN,void 0,!1,!0)}}catch(s){throw mf(s,"There was an error when trying to choose an operation path")}return r}a(cF,"chooseOperation");function lF(e){if(Hr.trace(`getOperationFunction with operation: ${e.operation}`),iF.has(e.operation))return iF.get(e.operation);throw mf(new Error,pf.HDB_ERROR_MSGS.OP_NOT_FOUND(e.operation),pf.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0)}a(lF,"getOperationFunction");hoe("operation",iy);function iy(e,t,r){e.hdb_user=t?.user,e.bypass_auth=!r;let n=cF(e);return aF({body:e},n)}a(iy,"operation");async function boe(e){Hr.trace("In serverUtils.catchup");let t=e.transaction,r=t.channel.split(":"),n=r[0],s=r[1];for(let i of t.transactions)try{i.schema=n,i.table=s,i[G.CLUSTERING_FLAG]=!0;let o;switch(i.operation){case G.OPERATIONS_ENUM.INSERT:o=await yl.insert(i);break;case G.OPERATIONS_ENUM.UPDATE:o=await yl.update(i);break;case G.OPERATIONS_ENUM.UPSERT:o=await yl.upsert(i);break;case G.OPERATIONS_ENUM.DELETE:o=await hf.deleteRecord(i);break;default:Hr.warn("invalid operation in catchup");break}await transact_to_clustering_utils.postOperationHandler(i,o,e)}catch(o){Hr.info("Invalid operation in transaction"),Hr.error(o)}}a(boe,"catchup");async function ys(e){moe(e);let t,r;try{r=await sy.addJob(e),t=r.createdJob,Hr.info("addJob result",r);let n=new Jk.RunnerMessage(t,e);return{message:await Jk.parseMessage(n)??`Starting job with id ${t.id}`,job_id:t.id}}catch(n){let s=`There was an error executing job: ${n.http_resp_msg?n.http_resp_msg:n}`;throw Hr.error(s),mf(n,s)}}a(ys,"executeJob");function yoe(){let e=new Map;return e.set(G.OPERATIONS_ENUM.INSERT,new Q(yl.insert)),e.set(G.OPERATIONS_ENUM.UPDATE,new Q(yl.update)),e.set(G.OPERATIONS_ENUM.UPSERT,new Q(yl.upsert)),e.set(G.OPERATIONS_ENUM.SEARCH_BY_CONDITIONS,new Q(Im.searchByConditions)),e.set(G.OPERATIONS_ENUM.SEARCH_BY_HASH,new Q(sF)),e.set(G.OPERATIONS_ENUM.SEARCH_BY_ID,new Q(sF)),e.set(G.OPERATIONS_ENUM.SEARCH_BY_VALUE,new Q(Toe)),e.set(G.OPERATIONS_ENUM.SEARCH,new Q(goe)),e.set(G.OPERATIONS_ENUM.SQL,new Q(Roe)),e.set(G.OPERATIONS_ENUM.CSV_DATA_LOAD,new Q(ys,bm.csvDataLoad)),e.set(G.OPERATIONS_ENUM.CSV_FILE_LOAD,new Q(ys,bm.csvFileLoad)),e.set(G.OPERATIONS_ENUM.CSV_URL_LOAD,new Q(ys,bm.csvURLLoad)),e.set(G.OPERATIONS_ENUM.IMPORT_FROM_S3,new Q(ys,bm.importFromS3)),e.set(G.OPERATIONS_ENUM.CREATE_SCHEMA,new Q(ki.createSchema)),e.set(G.OPERATIONS_ENUM.CREATE_DATABASE,new Q(ki.createSchema)),e.set(G.OPERATIONS_ENUM.CREATE_TABLE,new Q(ki.createTable)),e.set(G.OPERATIONS_ENUM.CREATE_ATTRIBUTE,new Q(ki.createAttribute)),e.set(G.OPERATIONS_ENUM.DROP_SCHEMA,new Q(ki.dropSchema)),e.set(G.OPERATIONS_ENUM.DROP_DATABASE,new Q(ki.dropSchema)),e.set(G.OPERATIONS_ENUM.DROP_TABLE,new Q(ki.dropTable)),e.set(G.OPERATIONS_ENUM.DROP_ATTRIBUTE,new Q(ki.dropAttribute)),e.set(G.OPERATIONS_ENUM.DESCRIBE_SCHEMA,new Q(ym.describeSchema)),e.set(G.OPERATIONS_ENUM.DESCRIBE_DATABASE,new Q(ym.describeSchema)),e.set(G.OPERATIONS_ENUM.DESCRIBE_TABLE,new Q(ym.describeTable)),e.set(G.OPERATIONS_ENUM.DESCRIBE_ALL,new Q(ym.describeAll)),e.set(G.OPERATIONS_ENUM.DELETE,new Q(hf.deleteRecord)),e.set(G.OPERATIONS_ENUM.ADD_USER,new Q(_f.addUser)),e.set(G.OPERATIONS_ENUM.ALTER_USER,new Q(_f.alterUser)),e.set(G.OPERATIONS_ENUM.DROP_USER,new Q(_f.dropUser)),e.set(G.OPERATIONS_ENUM.LIST_USERS,new Q(_f.listUsersExternal)),e.set(G.OPERATIONS_ENUM.LIST_ROLES,new Q(Om.listRoles)),e.set(G.OPERATIONS_ENUM.ADD_ROLE,new Q(Om.addRole)),e.set(G.OPERATIONS_ENUM.ALTER_ROLE,new Q(Om.alterRole)),e.set(G.OPERATIONS_ENUM.DROP_ROLE,new Q(Om.dropRole)),e.set(G.OPERATIONS_ENUM.USER_INFO,new Q(_f.userInfo)),e.set(G.OPERATIONS_ENUM.READ_LOG,new Q(soe)),e.set(G.OPERATIONS_ENUM.ADD_NODE,new Q(ioe)),e.set(G.OPERATIONS_ENUM.UPDATE_NODE,new Q(Wk)),e.set(G.OPERATIONS_ENUM.SET_NODE_REPLICATION,new Q(Wk)),e.set(G.OPERATIONS_ENUM.REMOVE_NODE,new Q(ooe)),e.set(G.OPERATIONS_ENUM.CONFIGURE_CLUSTER,new Q(aoe)),e.set(G.OPERATIONS_ENUM.PURGE_STREAM,new Q(coe)),e.set(G.OPERATIONS_ENUM.SET_CONFIGURATION,new Q(eF.setConfiguration)),e.set(G.OPERATIONS_ENUM.CLUSTER_STATUS,new Q(loe.clusterStatus)),e.set(G.OPERATIONS_ENUM.CLUSTER_NETWORK,new Q(uoe)),e.set(G.OPERATIONS_ENUM.CLUSTER_SET_ROUTES,new Q(ty.setRoutes)),e.set(G.OPERATIONS_ENUM.CLUSTER_GET_ROUTES,new Q(ty.getRoutes)),e.set(G.OPERATIONS_ENUM.CLUSTER_DELETE_ROUTES,new Q(ty.deleteRoutes)),e.set(G.OPERATIONS_ENUM.EXPORT_TO_S3,new Q(ys,Qk.export_to_s3)),e.set(G.OPERATIONS_ENUM.CREATE_CSR,new Q(Ef.createCsr)),e.set(G.OPERATIONS_ENUM.SIGN_CERTIFICATE,new Q(Ef.signCertificate)),e.set(G.OPERATIONS_ENUM.LIST_CERTIFICATES,new Q(Ef.listCertificates)),e.set(G.OPERATIONS_ENUM.ADD_CERTIFICATES,new Q(Ef.addCertificate)),e.set(G.OPERATIONS_ENUM.REMOVE_CERTIFICATE,new Q(Ef.removeCertificate)),e.set(G.OPERATIONS_ENUM.ADD_NODE_BACK,new Q(nF.addNodeBack)),e.set(G.OPERATIONS_ENUM.REMOVE_NODE_BACK,new Q(nF.removeNodeBack)),e.set(G.OPERATIONS_ENUM.DELETE_FILES_BEFORE,new Q(ys,hf.deleteFilesBefore)),e.set(G.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE,new Q(ys,hf.deleteFilesBefore)),e.set(G.OPERATIONS_ENUM.EXPORT_LOCAL,new Q(ys,Qk.export_local)),e.set(G.OPERATIONS_ENUM.SEARCH_JOBS_BY_START_DATE,new Q(sy.handleGetJobsByStartDate)),e.set(G.OPERATIONS_ENUM.GET_JOB,new Q(sy.handleGetJob)),e.set(G.OPERATIONS_ENUM.GET_FINGERPRINT,new Q(ry.getFingerprint)),e.set(G.OPERATIONS_ENUM.SET_LICENSE,new Q(ry.setLicense)),e.set(G.OPERATIONS_ENUM.GET_REGISTRATION_INFO,new Q(ry.getRegistrationInfo)),e.set(G.OPERATIONS_ENUM.RESTART,new Q(jk.restart)),e.set(G.OPERATIONS_ENUM.RESTART_SERVICE,new Q(ys,jk.restartService)),e.set(G.OPERATIONS_ENUM.CATCHUP,new Q(boe)),e.set(G.OPERATIONS_ENUM.SYSTEM_INFORMATION,new Q(_oe.systemInformation)),e.set(G.OPERATIONS_ENUM.DELETE_AUDIT_LOGS_BEFORE,new Q(ys,hf.deleteAuditLogsBefore)),e.set(G.OPERATIONS_ENUM.READ_AUDIT_LOG,new Q(noe)),e.set(G.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS,new Q(Xk.createTokens)),e.set(G.OPERATIONS_ENUM.REFRESH_OPERATION_TOKEN,new Q(Xk.refreshOperationToken)),e.set(G.OPERATIONS_ENUM.LOGIN,new Q(Zk.login)),e.set(G.OPERATIONS_ENUM.LOGOUT,new Q(Zk.logout)),e.set(G.OPERATIONS_ENUM.GET_CONFIGURATION,new Q(eF.getConfiguration)),e.set(G.OPERATIONS_ENUM.CUSTOM_FUNCTIONS_STATUS,new Q(Nt.customFunctionsStatus)),e.set(G.OPERATIONS_ENUM.GET_CUSTOM_FUNCTIONS,new Q(Nt.getCustomFunctions)),e.set(G.OPERATIONS_ENUM.GET_COMPONENT_FILE,new Q(Nt.getComponentFile)),e.set(G.OPERATIONS_ENUM.GET_COMPONENTS,new Q(Nt.getComponents)),e.set(G.OPERATIONS_ENUM.SET_COMPONENT_FILE,new Q(Nt.setComponentFile)),e.set(G.OPERATIONS_ENUM.DROP_COMPONENT,new Q(Nt.dropComponent)),e.set(G.OPERATIONS_ENUM.GET_CUSTOM_FUNCTION,new Q(Nt.getCustomFunction)),e.set(G.OPERATIONS_ENUM.SET_CUSTOM_FUNCTION,new Q(Nt.setCustomFunction)),e.set(G.OPERATIONS_ENUM.DROP_CUSTOM_FUNCTION,new Q(Nt.dropCustomFunction)),e.set(G.OPERATIONS_ENUM.ADD_CUSTOM_FUNCTION_PROJECT,new Q(Nt.addComponent)),e.set(G.OPERATIONS_ENUM.ADD_COMPONENT,new Q(Nt.addComponent)),e.set(G.OPERATIONS_ENUM.DROP_CUSTOM_FUNCTION_PROJECT,new Q(Nt.dropCustomFunctionProject)),e.set(G.OPERATIONS_ENUM.PACKAGE_CUSTOM_FUNCTION_PROJECT,new Q(Nt.packageComponent)),e.set(G.OPERATIONS_ENUM.PACKAGE_COMPONENT,new Q(Nt.packageComponent)),e.set(G.OPERATIONS_ENUM.DEPLOY_CUSTOM_FUNCTION_PROJECT,new Q(Nt.deployComponent)),e.set(G.OPERATIONS_ENUM.DEPLOY_COMPONENT,new Q(Nt.deployComponent)),e.set(G.OPERATIONS_ENUM.READ_TRANSACTION_LOG,new Q(tF.readTransactionLog)),e.set(G.OPERATIONS_ENUM.DELETE_TRANSACTION_LOGS_BEFORE,new Q(ys,tF.deleteTransactionLogsBefore)),e.set(G.OPERATIONS_ENUM.INSTALL_NODE_MODULES,new Q(rF.installModules)),e.set(G.OPERATIONS_ENUM.AUDIT_NODE_MODULES,new Q(rF.auditModules)),e.set(G.OPERATIONS_ENUM.GET_BACKUP,new Q(ki.getBackup)),e.set(G.OPERATIONS_ENUM.ADD_SSH_KEY,new Q(Nt.addSSHKey)),e.set(G.OPERATIONS_ENUM.UPDATE_SSH_KEY,new Q(Nt.updateSSHKey)),e.set(G.OPERATIONS_ENUM.DELETE_SSH_KEY,new Q(Nt.deleteSSHKey)),e.set(G.OPERATIONS_ENUM.LIST_SSH_KEYS,new Q(Nt.listSSHKeys)),e.set(G.OPERATIONS_ENUM.SET_SSH_KNOWN_HOSTS,new Q(Nt.setSSHKnownHosts)),e.set(G.OPERATIONS_ENUM.GET_SSH_KNOWN_HOSTS,new Q(Nt.getSSHKnownHosts)),e}a(yoe,"initializeOperationFunctionMap")});var Cm=I((uAe,_F)=>{"use strict";var ay=H(),Ooe=re(),Sf=X(),{handleHDBError:cy,hdb_errors:wm}=ce(),{isMainThread:Noe}=require("worker_threads"),{Readable:Ioe}=require("stream"),dF=require("os"),woe=require("util"),Coe=sR(),Doe=woe.promisify(Coe.authorize),fF=uF(),{createGzip:Loe,constants:Poe}=require("zlib");function Moe(e){let t=`Found an uncaught exception with message: ${e.message}. ${dF.EOL}Stack: ${e.stack} ${dF.EOL}Terminating ${Noe?"HDB":"thread"}.`;console.error(t),Sf.fatal(t),process.exit(1)}a(Moe,"handleServerUncaughtException");function Uoe(e,t,r){if(Sf[e.logLevel||"error"](e),e.statusCode)return typeof e.http_resp_msg!="object"?r.code(e.statusCode).send({error:e.http_resp_msg||e.message}):r.code(e.statusCode).send(e.http_resp_msg);let n=e.statusCode?e.statusCode:wm.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR;return typeof e=="string"?r.code(n).send({error:e}):r.code(n).send(e.message?{error:e.message}:e)}a(Uoe,"serverErrorHandler");function voe(e,t,r){if(!e.body||Object.keys(e.body).length===0||typeof e.body!="object"){let n=cy(new Error,"Invalid JSON.",wm.HTTP_STATUS_CODES.BAD_REQUEST);r(n,null)}if(Ooe.isEmpty(e.body.operation)){let n=cy(new Error,"Request body must include an 'operation' property.",wm.HTTP_STATUS_CODES.BAD_REQUEST);r(n,null)}r()}a(voe,"reqBodyValidationHandler");function xoe(e,t,r){let n;e.body.operation!==ay.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS&&e.body.operation!==ay.OPERATIONS_ENUM.LOGIN&&e.body.operation!==ay.OPERATIONS_ENUM.LOGOUT?Doe(e,t).then(s=>{n=s,e.body.hdb_user=n,e.body.hdb_auth_header=e.headers.authorization,r()}).catch(s=>{Sf.warn(s),Sf.warn(`{"ip":"${e.socket.remoteAddress}", "error":"${s.stack}"`);let i=typeof s=="string"?{error:s}:{error:s.message};r(cy(s,i,wm.HTTP_STATUS_CODES.UNAUTHORIZED),null)}):(e.body.hdb_user=null,e.body.hdb_auth_header=e.headers.authorization,e.body.baseRequest=e.raw?.baseRequest,e.body.baseResponse=t.raw?.baseResponse,e.body.fastifyResponse=t,r())}a(xoe,"authHandler");async function Boe(e,t,r=!1){let n;try{r&&(e.body.operation!=="configure_cluster"||e.body.operation!=="set_configuration")&&(e.body.bypass_auth=r),n=fF.chooseOperation(e.body);let s=await fF.processLocalTransaction(e,n);if(s instanceof Ioe&&s.headers){for(let[i,o]of s.headers)t.header(i,o);e.headers["accept-encoding"]?.includes("gzip")&&(t.header("content-encoding","gzip"),s=s.pipe(Loe({level:Poe.Z_BEST_SPEED})))}return s}catch(s){throw Sf.error(s),s}}a(Boe,"handlePostRequest");_F.exports={authHandler:xoe,handlePostRequest:Boe,handleServerUncaughtException:Moe,serverErrorHandler:Uoe,reqBodyValidationHandler:voe}});var pF=I((fAe,mF)=>{"use strict";var Hoe=require("fastify-plugin"),{handlePostRequest:EF,authHandler:koe,reqBodyValidationHandler:Foe}=Cm();async function Goe(e){e.decorate("hdbCore",{preValidation:[Foe,koe],request:t=>hF(EF(t,response)),requestWithoutAuthentication:(t,r)=>hF(EF(t,r,!0))})}a(Goe,"hdbCore");async function hF(e){if(e=await e,e?.[Symbol.asyncIterator]&&!e[Symbol.iterator]){let t=[];for await(let r of e)t.push(r);return t}return e}a(hF,"convertAsyncIterators");mF.exports=Hoe(Goe)});var gF=I((hAe,TF)=>{"use strict";var EAe=require("fs"),ly=ie();ly.initSync();var{CONFIG_PARAMS:SF}=H(),qoe=1024*1024*1024;function Voe(e){let t=ly.get(SF.HTTP_TIMEOUT),r=ly.get(SF.HTTP_KEEPALIVETIMEOUT);return{bodyLimit:qoe,connectionTimeout:t,keepAliveTimeout:r,return503OnClosing:!1,forceCloseConnections:!0,ignoreTrailingSlash:!0,https:e}}a(Voe,"getServerOptions");TF.exports=Voe});var bF=I((pAe,AF)=>{"use strict";var uy=ie();uy.initSync();var{CONFIG_PARAMS:RF}=H();function $oe(){let e=uy.get(RF.HTTP_CORSACCESSLIST),t=uy.get(RF.HTTP_CORS),r;return t&&(r={origin:!0,allowedHeaders:["Content-Type","Authorization","Accept"],credentials:!1},e&&e.length>0&&e[0]!==null&&e[0]!=="*"&&(r.origin=(n,s)=>s(null,e.indexOf(n)!==-1))),r}a($oe,"getCORSOptions");AF.exports=$oe});var NF=I((TAe,OF)=>{"use strict";var yF=ie();yF.initSync();var Yoe=H();function Koe(){return yF.get(Yoe.CONFIG_PARAMS.HTTP_HEADERSTIMEOUT)??6e4}a(Koe,"getHeaderTimeoutConfig");OF.exports=Koe});var fy={};Ze(fy,{customFunctionsServer:()=>zoe,ready:()=>GF,start:()=>Qoe});function Qoe(e){let t=e.securePort>0;return{async handleFile(r,n,s,i){Fi||(Fi=FF(t),st.http((await Fi).server));let o=await Fi,c=(0,dy.dirname)(s),l=(0,dy.dirname)(n);if(l.startsWith("/")&&(l=l.slice(1)),!IF.has(c)){IF.add(c);try{o.register(Joe(c,l))}catch(d){if(d.message==="Root plugin has already booted")ut.warn(`Could not load root fastify route for ${s}, this may require a restart to install properly`);else throw d}}},ready:GF}}async function zoe(){try{ut.info("In Custom Functions Fastify server"+process.cwd()),ut.info(`Custom Functions Running with NODE_ENV set as: ${process.env.NODE_ENV}`),ut.debug(`Custom Functions server process ${process.pid} starting up.`),await joe();let e=MF.get(UF.CONFIG_PARAMS.HTTP_SECUREPORT)>0,t;try{t=Fi=await FF(e)}catch(r){throw ut.error(`Custom Functions buildServer error: ${r}`),r}try{await t.ready()}catch(r){throw ut.error(`Custom Functions server.ready() error: ${r}`),r}t.server.cantCleanupProperly=!0}catch(e){ut.error(`Custom Functions ${process.pid} Error: ${e}`),ut.error(e),process.exit(1)}}async function joe(){try{ut.info("Custom Functions starting configuration."),await vF.setUsersToGlobal(),ut.info("Custom Functions completed configuration.")}catch(e){ut.error(e)}}function Joe(e,t){return async function(r){try{ut.info("Custom Functions starting buildRoutes"),ut.trace("Loading fastify routes folder "+e),(0,wF.existsSync)(e)&&r.register(PF.default,s=>({dir:e,dirNameRoutePrefix:!1,options:{hdbCore:s.hdbCore,logger:ut.loggerWithTag("custom-function"),prefix:`/${t}`}})).after((s,i,o)=>{s?.message?ut.error(s.message):s&&ut.error(s),o()})}catch(n){ut.error(`Custom Functions errored buildRoutes: ${n}`)}}}async function FF(e){ut.info("Custom Functions starting buildServer.");let t=(0,xF.default)(e),r=(0,CF.default)(t);r.server.headersTimeout=(0,HF.default)(),r.setErrorHandler(kF.serverErrorHandler);let n=(0,BF.default)();return n&&r.register(DF.default,n),r.register(function(s,i,o){s.setNotFoundHandler(function(c,l){r.server.emit("unhandled",c.raw,l.raw)}),o()}),r.register(LF.default),await r.register(Woe),await r.after(),mb(r),ut.info("Custom Functions completed buildServer."),r}function GF(){if(Fi)return Fi.then?Fi.then(e=>e.ready()):Fi.ready()}var dy,wF,CF,DF,LF,PF,MF,UF,ut,Woe,vF,xF,BF,HF,kF,Fi,IF,qF=Oe(()=>{dy=require("path"),wF=require("fs"),CF=U(require("fastify")),DF=U(require("@fastify/cors")),LF=U(Pb()),PF=U(require("@fastify/autoload")),MF=U(ie()),UF=U(H()),ut=U(X()),Woe=U(pF()),vF=U($n()),xF=U(gF()),BF=U(bF()),HF=U(NF()),kF=U(Cm());ll();Lr();IF=new Set;a(Qoe,"start");a(zoe,"customFunctionsServer");a(joe,"setUp");a(Joe,"buildRouteFolder");a(FF,"buildServer");a(GF,"ready")});var _y={};Ze(_y,{start:()=>Xoe});function Xoe(e){return{handleDirectory(t,r){if(t==="/"){let n=(0,WF.default)(r,e);return e.server.http(async(s,i)=>{if(!s.isWebSocket)return new Promise(o=>n(s._nodeRequest,s._nodeResponse,()=>{o(i(s))}))}),!0}},handleFile(t,r,n){$F||($F=!0,e.server.http(async(s,i)=>{if(!s.isWebSocket){let o=VF.get(s.pathname);if(o)return{handlesHeaders:!0,body:(0,YF.default)(s,(0,KF.realpathSync)(o))}}return i(s)},{runFirst:!0})),VF.set(r,n)}}}var YF,KF,WF,VF,$F,QF=Oe(()=>{YF=U(require("send")),KF=require("fs"),WF=U(require("serve-static")),VF=new Map;a(Xoe,"start")});function tae(){let e=(0,XF.checkMemoryLimit)();e&&!process.env.DEV_MODE&&(console.error(e),hy=setInterval(()=>{Pm.notify(e)},eae).unref())}function rae(e,t=1,r){if(Ey++,(0,ri.startWorker)("server/threads/threadServer.js",{name:Cl.THREAD_TYPES.HTTP,workerIndex:e,threadCount:t,async onStarted(n){let s=new Promise((o,c)=>{function l(d){d.type===Cl.CLUSTER_MESSAGE_TYPE_ENUM.CHILD_STARTED&&(n.removeListener("message",l),o(n))}a(l,"onMessage"),n.on("message",l),n.on("error",c)});Zoe.push(s),await s,Ol.push(n),n.expectedIdle=1,n.lastIdle=0,n.requests=1,n.on("message",o=>{if(o.requestId){let c=Lm.get(o.requestId);c&&c(o)}}),n.on("exit",i),n.on("shutdown",i);function i(){let o=Ol.indexOf(n);o>-1&&Ol.splice(o,1)}if(a(i,"removeWorker"),Nl){let o=Nl;Nl=[];for(let c of o)ZF[c.localPort](null,c)}}}),r){let n=setInterval(()=>{my?my=!1:(clearInterval(n),console.log("shut down dynamic thread due to inactivity"),(0,ri.shutdownWorkers)(),Ey=0,setTimeout(()=>{global.gc?.()},5e3))},1e4)}}function eG(e=0,t){if(typeof e=="string")try{(0,Mm.existsSync)(e)&&(0,Mm.unlinkSync)(e)}catch{}let r;t?t==="ip"?r=nae:r=sae(t):r=py;let n=(0,Il.createServer)({allowHalfOpen:!0,pauseOnConnect:!r.readsData}).listen(e);if(n._handle){n._handle.onconnection=ZF[e]=function(i,o){r.readsData||(o.reading=!1,o.readStop()),my=!0,r(o,(c,l)=>{if(!c){if(zF){let u=o._socket||new Il.Socket({handle:o,writable:!0,readable:!0});zF.deliverSocket(u,e,l),u.resume()}else Ey>0?(Nl.length===0&&setTimeout(()=>{Nl.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(),o.localPort=e,Nl.push(o)):(console.log("start up a dynamic thread to handle request"),rae(0));an(!1,"socket-routed");return}c.requests++;let d=o.fd;if(d>=0)c.postMessage({port:e,fd:d,data:l});else{let u=o._socket||new Il.Socket({handle:o,writable:!0,readable:!0});cae(u,c,e)}an(!0,"socket-routed")})};let s=ed();Pm.info(`HarperDB ${s.version} Server running on port ${e}`)}return n.on("error",s=>{console.error("Error in socket server",s)}),process.env._UNREF_SERVER&&n.unref(),n}function py(e,t){let r,n=0;for(let s of Ol){if(s.threadId===-1)continue;let i=s.expectedIdle/s.requests;if(i>n)r=s;else if(n>=Dm)return Dm=i,t(r);n=i}Dm=0,t(r)}function nae(e,t){let r={};e.getpeername(r);let n=r.address,s=wl.get(n),i=Date.now();if(s&&s.worker.threadId!==-1)return s.lastUsed=i,t(s.worker);py(e,o=>{wl.set(n,{worker:o,lastUsed:i}),t(o)})}function sae(e){let t=new RegExp(`${e}:\\s*(.+)`,"i");return r.readsData=!0,r;function r(n,s){let i=new Il.Socket({handle:n,readable:!0,writable:!0});n._socket=i,i.on("data",o=>{n.readStop();let l=o.toString("latin1").match(t)?.[1],d=wl.get(l),u=Date.now();if(d&&d.worker.threadId!==-1)return d.lastUsed=u,s(d.worker);py(n,f=>{wl.set(l,{worker:f,lastUsed:u}),s(f,o)})})}a(r,"findByHeaderAffinity")}function oae(){Dm=0;for(let e of Ol)e.expectedIdle=e.recentELU.idle+iae,e.requests=1;Ol.sort((e,t)=>e.expectedIdle>t.expectedIdle?-1:1)}function cae(e,t,r){let n=aae++;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(),Lm.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")),Lm.delete(n)),s.event=="destroy"&&(e.destroy(),Lm.delete(n))})}var ri,Il,Cl,Pm,Mm,JF,XF,Ol,Nl,ZF,zF,Ey,Zoe,hy,eae,my,Dm,jF,wl,iae,Lm,aae,tG=Oe(()=>{ri=U(at()),Il=require("net"),Cl=U(H()),Pm=U(X()),Mm=require("fs");Bi();JF=require("worker_threads"),XF=U(ea()),Ol=[],Nl=[],ZF=[],Ey=0,Zoe=[];JF.isMainThread&&(process.on("uncaughtException",e=>{e.code!=="ECONNRESET"&&e.message!=="write EIO"&&console.error("uncaughtException",e)}),(0,ri.onMessageFromWorkers)(e=>{e.type===Cl.ITC_EVENT_TYPES.RESTART&&hy&&(clearInterval(hy),tae())}));eae=6e5;a(tae,"licenseWarning");a(rae,"startHTTPWorker");a(eG,"startSocketServer");Dm=0;a(py,"findMostIdleWorker");jF=36e5,wl=new Map;a(nae,"findByRemoteAddressAffinity");a(sae,"makeFindByHeaderAffinity");setInterval(()=>{let e=Date.now();for(let[t,r]of wl)r.lastUsed+jF<e&&wl.delete(t)},jF).unref();iae=1e3;a(oae,"updateWorkerIdleness");(0,ri.setMonitorListener)(oae);Lm=new Map,aae=1;a(cae,"proxySocket")});var Ry={};Ze(Ry,{Request:()=>Sy,createReuseportFd:()=>Um});var rG,Sy,Ty,gy,Um,vm=Oe(()=>{rG=require("os"),Sy=class{static{a(this,"Request")}#e;constructor(t,r){this.method=t.method;let n=t.url;this._nodeRequest=t,this._nodeResponse=r,this.url=n,this.headers=new gy(t.headers)}get absoluteURL(){return this.protocol+"://"+this.host+this.url}get pathname(){let t=this.url.indexOf("?");return t>-1?this.url.slice(0,t):this.url}set pathname(t){let r=this.url.indexOf("?");r>-1?this.url=t+this.url.slice(r):this.url=t}get protocol(){return this._nodeRequest.socket.encrypted?"https":"http"}get ip(){return this._nodeRequest.socket.remoteAddress}get authorized(){return this._nodeRequest.socket.authorized}get peerCertificate(){return this._nodeRequest.socket.getPeerCertificate()}get mtlsConfig(){return this._nodeRequest.socket.server.mtlsConfig}get body(){return this.#e||(this.#e=new Ty(this._nodeRequest))}get host(){return this._nodeRequest.authority||this._nodeRequest.headers.host}get isAborted(){return!1}},Ty=class{static{a(this,"RequestBody")}#e;constructor(t){this.#e=t}on(t,r){return this.#e.on(t,r),this}pipe(t,r){return this.#e.pipe(t,r)}},gy=class{constructor(t){this.asObject=t}static{a(this,"Headers")}set(t,r){this.asObject[t.toLowerCase()]=r}get(t){return this.asObject[t.toLowerCase()]}has(t){return this.asObject.hasOwnProperty(t.toLowerCase())}[Symbol.iterator](){return Object.entries(this.asObject)[Symbol.iterator]()}keys(){return Object.keys(this.asObject)}values(){return Object.values(this.asObject)}forEach(t){for(let[r,n]of this)t(n,r,this)}};(0,rG.platform)()!="win32"&&(Um=require("node-unix-socket").createReuseportFd)});var oG=I((UAe,iG)=>{"use strict";var lae=require("cluster"),Ga=ie();Ga.initSync();var sG=H(),CAe=require("util"),Gi=X(),DAe=require("fs"),uae=require("fastify"),LAe=ed(),dae=require("@fastify/cors"),fae=require("@fastify/compress"),_ae=require("@fastify/static"),Eae=Pb(),hae=require("path"),{PACKAGE_ROOT:mae}=H(),pae=eo(),Sae=re(),Tae=$n(),gae=ea(),{server:Rae}=(Lr(),ae(ko)),{node_request_key:PAe}=(vm(),ae(Ry)),{authHandler:Aae,handlePostRequest:bae,serverErrorHandler:yae,reqBodyValidationHandler:Oae}=Cm(),MAe=require("net"),{registerContentHandlers:Nae}=(ll(),ae(pH)),Iae=6e4,wae=1024*1024*1024,Cae="TRUE",{CONFIG_PARAMS:Tf}=sG,Dl;iG.exports={hdbServer:nG,start:nG};async function nG(e){try{Gi.debug("In Fastify server"+process.cwd()),Gi.debug(`Running with NODE_ENV set as: ${process.env.NODE_ENV}`),Gi.debug(`HarperDB server process ${process.pid} starting up.`),global.clustering_on=!1,global.isMaster=lae.isMaster,await Dae();let t=e.securePort>0;Dl=Lae(t),await Dl.ready(),e||(e={}),e.isOperationsServer=!0;try{Rae.http(Dl.server,e),Dl.server.closeIdleConnections||await Dl.listen({port:0,host:"::"})}catch(r){throw Dl.close(),Gi.error(r),Gi.error("Error configuring operations server"),r}}catch(t){console.error(`Failed to build server on ${process.pid}`,t),Gi.fatal(t),process.exit(1)}}a(nG,"operationsServer");async function Dae(){Gi.trace("Configuring HarperDB process."),pae.setSchemaDataToGlobal(),await Tae.setUsersToGlobal(),await gae.getLicense()}a(Dae,"setUp");function Lae(e){Gi.debug(`HarperDB process starting to build ${e?"HTTPS":"HTTP"} server.`);let t=Pae(e),r=uae(t);r.server.headersTimeout=Uae(),r.setErrorHandler(yae);let n=Mae();n&&r.register(dae,n),r.register(function(i,o,c){i.setNotFoundHandler(function(l,d){r.server.emit("unhandled",l.raw,d.raw)}),c()}),r.register(Eae),r.register(fae),r.register(_ae,{root:hae.join(mae,"studio/build-local")}),Nae(r);let s=Ga.get(sG.HDB_SETTINGS_NAMES.LOCAL_STUDIO_ON);return r.get("/",function(i,o){return!Sae.isEmpty(s)&&s.toString().toLowerCase()==="true"?o.sendFile("index.html"):o.sendFile("running.html")}),r.post("/",{preValidation:[Oae,Aae],config:{isOperation:!0}},async function(i,o){return i.body?.operation?.startsWith("restart")&&o.header("Connection","close"),bae(i,o)}),r.get("/health",()=>"HarperDB is running."),Gi.debug(`HarperDB process starting up ${e?"HTTPS":"HTTP"} server listener.`),r}a(Lae,"buildServer");function Pae(e){let t=Ga.get(Tf.OPERATIONSAPI_NETWORK_TIMEOUT),r=Ga.get(Tf.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT);return{bodyLimit:wae,connectionTimeout:t,keepAliveTimeout:r,forceCloseConnections:!0,return503OnClosing:!1,https:e}}a(Pae,"getServerOptions");function Mae(){let e=Ga.get(Tf.OPERATIONSAPI_NETWORK_CORS),t=Ga.get(Tf.OPERATIONSAPI_NETWORK_CORSACCESSLIST),r;return e&&(e===!0||e.toUpperCase()===Cae)&&(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(Mae,"getCORSOpts");function Uae(){return Ga.get(Tf.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT)??Iae}a(Uae,"getHeaderTimeoutConfig")});var Iy={};Ze(Iy,{disableNATS:()=>xae,publishToStream:()=>Hm,setNATSReplicator:()=>Ay,setPublishToStream:()=>Bae,setSubscription:()=>Ny,start:()=>vae});function vae(){gf.default.get(Rf.default.CONFIG_PARAMS.CLUSTERING_ENABLED)&&kae()}function xae(e=!0){dG=e}function Bae(e,t){Hm=e,Ny=t}function kae(){if(dG||process.env._DISABLE_NATS)return;let e=ct(),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];Ay(s,r,i)}}ha((r,n)=>{Ay(r.tableName,r.databaseName,r),n&&_G(r)}),!aG&&(aG=!0)}function Ay(e,t,r){if(t==="system"&&Fae.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 pr{static{a(this,"NATSReplicator")}put(i){return n(this.getContext()).addWrite(t,{operation:"put",table:e,id:this[Ye],record:i})}delete(){return n(this.getContext()).addWrite(t,{operation:"delete",table:e,id:this[Ye]})}publish(i){return n(this.getContext()).addWrite(t,{operation:"publish",table:e,id:this[Ye],record:i})}patch(i){return n(this.getContext()).addWrite(t,{operation:"patch",table:e,id:this[Ye],record:i})}invalidate(){n(this.getContext()).addWrite(t,{operation:"invalidate",table:e,id:this[Ye]})}static defineSchema(i){_G(i)}static subscribe(){let i=new mn;return Ny(t,e,i),i}static subscribeOnThisThread(i){return i<(gf.default.get(Rf.default.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXINGESTTHREADS)??Hae)}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 xm(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=fG;return i}a(n,"getNATSTransaction")}function _G(e){let t=gf.default.get(Rf.default.CONFIG_PARAMS.CLUSTERING_NODENAME);Hm(`${yy.SUBJECT_PREFIXES.TXN}.${e.databaseName}.${e.tableName}`,(0,Oy.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 cG,yy,Oy,lG,uG,gf,Rf,Bm,dG,Hm,Ny,Hae,fG,aG,Fae,xm,by,EG=Oe(()=>{Ne();ls();cG=U(or()),yy=U(Pt()),Oy=U(mi());ic();lG=U(km()),uG=U(hn()),gf=U(ie()),Rf=U(H()),Bm=U(X());a(vae,"start");a(xae,"disableNATS");Hm=cG.publishToStream,Ny=lG.setSubscription;a(Bae,"setPublishToStream");Hae=2;a(kae,"assignReplicationSource");Fae=["hdb_job","hdb_analytics","hdb_raw_analytics","hdb_info","hdb_license"];a(Ay,"setNATSReplicator");a(_G,"publishSchema");xm=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=gf.default.get(Rf.default.CONFIG_PARAMS.CLUSTERING_NODENAME),n=[];for(let[s,i]of this.writes_by_db){let o=[],c=[],l,d;for(let u of i){let f=u.table,E=u.operation=="put"?"upsert":u.operation;l||(Bm.trace(`Sending transaction event ${E}`),d=l={operation:E,schema:s,table:f,__origin:{user:this.user?.username,timestamp:t,node_name:r}},l.hash_values=c,E!=="delete"&&E!=="invalidate"&&(l.records=o)),l.table===f&&l.operation===E?(o.push(u.record),c.push(u.id)):d=d.next={operation:E,table:f,id:u.id,record:u.record},u.expiresAt&&(d.expiresAt=u.expiresAt)}l&&n.push(Hm(`${yy.SUBJECT_PREFIXES.TXN}.${s}.${l.table}`,(0,Oy.createNatsTableStreamName)(s,l.table),void 0,l)?.catch(u=>{throw Bm.error("An error has occurred trying to replicate transaction",l,u),u.statusCode=504,u}))}return Promise.all(n)}},by=class extends xm{static{a(this,"ImmmediateNATSTransaction")}constructor(){super({get timestamp(){return(0,uG.getNextMonotonicTime)()}})}addWrite(t,r){super.addWrite(t,r),this.commit({})}};fG=new by});var IG=I(Lo=>{"use strict";var{isMainThread:Cy,parentPort:Of,threadId:Gm,workerData:Gae}=require("worker_threads"),{Socket:qae,createServer:Vae}=require("net"),{createServer:$ae,IncomingMessage:Yae}=require("http"),{createServer:Kae}=require("https"),{unlinkSync:pG,existsSync:Wae}=require("fs"),kr=X(),Et=ie(),Yt=H(),{server:Vm}=(Lr(),ae(ko)),{WebSocketServer:Qae}=require("ws"),{createServer:zae}=require("node:tls"),{getTicketKeys:jae,restartNumber:Jae,getWorkerIndex:Nf}=at(),{Headers:Dy,appendHeader:Xae}=(Hd(),ae(Fx)),{recordAction:Af,recordActionBinary:Zae}=(Bi(),ae(of)),{Request:SG,createReuseportFd:yf}=(vm(),ae(Ry)),{checkMemoryLimit:ece}=ea(),{createTLSSelector:TG}=To(),{resolvePath:gG}=dr(),RG=Et.get(Yt.CONFIG_PARAMS.THREADS_DEBUG);if(RG){let e;if(Cy)e=Et.get(Yt.CONFIG_PARAMS.THREADS_DEBUG_PORT)??9229,process.on(["SIGINT","SIGTERM","SIGQUIT","exit"],()=>{try{require("inspector").close()}catch(t){kr.info("Could not close debugger",t)}});else{let t=Et.get(Yt.CONFIG_PARAMS.THREADS_DEBUG_STARTINGPORT);t&&Nf()>=0&&(e=t+Nf())}if(e){let t=Et.get(Yt.CONFIG_PARAMS.THREADS_DEBUG_HOST),r=Et.get(Yt.CONFIG_PARAMS.THREADS_DEBUG_WAITFORDEBUGGER);try{require("inspector").open(e,t,r)}catch(n){kr.trace(`Could not start debugging on port ${e}, you may already be debugging:`,n.message)}}}else if(process.env.DEV_MODE&&Cy)try{require("inspector").open(9229)}catch(e){Jae<=1&&kr.trace("Could not start debugging on port 9229, you may already be debugging:",e.message)}process.on("uncaughtException",e=>{e.isHandled||e.code==="ECONNRESET"||e.code==="ECONNREFUSED"||e.message!=="write EIO"&&console.error("uncaughtException",e)});var{HDB_SETTINGS_NAMES:GAe,CONFIG_PARAMS:tce}=Yt;Et.initSync();var rce=Et.get(tce.HTTP_SESSIONAFFINITY),ni={};Lo.registerServer=Uy;Lo.httpServer=vy;Lo.deliverSocket=My;Lo.startServers=AG;Lo.listenOnPorts=bG;Lo.when_components_loaded=null;Vm.http=vy;Vm.request=oce;Vm.socket=ace;Vm.ws=cce;var wy={},bf={},nce,Fm={},qm={},sce=[],Ly=[];function AG(){return Lo.when_components_loaded=xy().loadRootComponents(!0).then(()=>{Of?.on("message",t=>{let{port:r,fd:n,data:s}=t;if(n)My(n,r,s);else if(t.requestId)ice(t);else if(t.type===Yt.ITC_EVENT_TYPES.SHUTDOWN){kr.trace("received shutdown request",Gm);for(let i in ni){let o=ni[i],c;if(o.closeIdleConnections){let d=Object.getOwnPropertySymbols(o).find(E=>E.description.includes("connections")),u=0,f=setInterval(()=>{u++;let E=u>=100,_=o[d][E?"all":"idle"]();if(_.length===0){E&&clearInterval(f);return}u===1?kr.info(`Closing ${_.length} idle connections`):E&&kr.warn(`Forcefully closing ${_.length} active connections`);for(let h=0,p=_.length;h<p;h++){let S=_[h].socket;S._httpMessage&&!S._httpMessage.finished&&!E||(E?S.destroySoon():S.end(`HTTP/1.1 408 Request Timeout\r
27
37
  Connection: close\r
28
38
  \r
29
- `))}},25).unref()}o.close?.(()=>{if(xe.get(ut.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET)&&gu()==0)try{iH(xe.get(ut.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET))}catch{}clearInterval(c),setTimeout(()=>{console.log("forced close server",i,mE),o.cantCleanupProperly||Pt.warn("Had to forcefully exit the thread",mE),process.exit(0)},5e3).unref()})}if(fH||process.env.DEV_MODE)try{require("inspector").close()}catch(i){Pt.info("Could not close debugger",i)}}}).ref();let e=[];if(oH&&!Fre)for(let t in _s){let r=_s[t];if(isNaN(t)&&gu()==0){Cre(t)&&iH(t),e.push(new Promise((i,o)=>{r.listen({path:t},()=>{i(),Pt.info("Domain socket listening on "+t)}).on("error",o)}));continue}let n=xe.get(ut.CONFIG_PARAMS.HTTP_THREADRANGE);if(n){let i=typeof n=="string"?n.split("-"):n,o=gu();if(o<i[0]||o>i[1])continue}let s;try{s=oH(+t,"::")}catch(i){console.error(`Unable to bind to port ${t}`,i);continue}e.push(new Promise((i,o)=>{r.listen({fd:s},()=>{i(),Pt.trace("Listening on port "+t,mE)}).on("error",o)}))}Promise.all(e).then(()=>{Tu?.postMessage({type:ut.ITC_EVENT_TYPES.CHILD_STARTED})})})}a(EH,"startServers");MR||EH();function vR(e,t,r){let n=e?.read?e:new Ore({fd:e,readable:!0,writable:!0,allowHalfOpen:!0}),s=_s[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=_s[t];c?(typeof c=="function"?c(n):c.emit("connection",n),r&&n.emit("data",r)):o<5?i(o+1):(Pt.error(`Server on port ${t} was not registered`),n.destroy())},1e3)},"retry");i(1)}return n}a(vR,"deliverSocket");var aH=new Map;function Vre(e){let{port:t,event:r,data:n,requestId:s}=e,i;switch(i=aH.get(s),r){case"connection":i=vR(void 0,t),aH.set(s,i),i.write=(c,l,_)=>(Tu.postMessage({requestId:s,event:"data",data:c.toString("latin1")}),_&&_(),!0),i.end=(c,l,_)=>(Tu.postMessage({requestId:s,event:"end",data:c?.toString("latin1")}),_&&_(),!0);let o=i.destroy;i.destroy=()=>{o.call(i),Tu.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(Vre,"proxyRequest");function BR(e,t,r=!0){!+t&&t!==xe.get(ut.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET)&&(t=parseInt(xe.get(ut.CONFIG_PARAMS.HTTP_PORT),10));let n=_s[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",cH),s.on("unhandled",(i,o)=>{e.cantCleanupProperly&&(n.cantCleanupProperly=!0),e.emit("request",i,o)}),n.lastServer=e}else _s[t]=e;e.on("unhandled",cH)}a(BR,"registerServer");function hH(e){let t=[],r=parseInt(e?.securePort);return r&&t.push({port:r,secure:!0}),r=parseInt(e?.port),r&&t.push({port:r,secure:!1}),t.length===0&&(t=[],xe.get(ut.CONFIG_PARAMS.HTTP_PORT)!=null&&t.push({port:xe.get(ut.CONFIG_PARAMS.HTTP_PORT),secure:xe.get(ut.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HTTPS)}),xe.get(ut.CONFIG_PARAMS.HTTP_SECUREPORT)!=null&&t.push({port:xe.get(ut.CONFIG_PARAMS.HTTP_SECUREPORT),secure:!0})),e?.isOperationsServer&&xe.get(ut.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET)&&t.push({port:xe.get(ut.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET),secure:!1}),t}a(hH,"getPorts");function HR(e,t){for(let{port:r,secure:n}of hH(t))mH(r,n,t?.isOperationsServer),typeof e=="function"?PR[t?.runFirst?"unshift":"push"]({listener:e,port:t?.port||r}):(e.isSecure=n,BR(e,r,!1)),SE[r]=UR(PR,r),qre=UR(kre,r)}a(HR,"httpServer");function mH(e,t,r){if(!Vs[e]){let n=r?"operationsApi_network":"http",s={noDelay:!0,keepAliveTimeout:xe.get(n+"_keepAliveTimeout"),headersTimeout:xe.get(n+"_headersTimeout"),requestTimeout:xe.get(n+"_timeout")},i=xe.get(n+"_mtls"),o=xe.get(n+"_mtls_required");if(t){n=r?"operationsApi_":"";let l=xe.get(n+"tls");Object.assign(s,{allowHTTP1:!0,rejectUnauthorized:!!o,requestCert:!!i,ticketKeys:lH(),maxHeaderSize:xe.get(ut.CONFIG_PARAMS.HTTP_MAXHEADERSIZE),SNICallback:xR(l)})}let c=Bre();Vs[e]=(t?Ire:yre)(s,async(l,_)=>{try{let d=performance.now(),E=new _H(l,_);r&&(E.isOperationsServer=!0);let f=await SE[e](E);if(!f){if(E._nodeResponse.statusCode)return;f=pH(E)}if(c?f.headers?.set?.("Server","Unlicensed HarperDB, this should only be used for educational and development purposes"):f.headers?.set?.("Server","HarperDB"),f.status===-1){for(let H of f.headers||[])_.setHeader(H[0],H[1]);return l.baseRequest=E,_.baseResponse=f,Vs[e].emit("unhandled",l,_)}let h=f.status||200,p=performance.now(),S=p-d,T=f.body,R;if(!f.handlesHeaders){let H=f.headers||new uH;T?T.length>=0&&(typeof T=="string"?H.set("Content-Length",Buffer.byteLength(T)):H.set("Content-Length",T.length),R=!0):(H.set("Content-Length","0"),R=!0);let v=`hdb;dur=${S.toFixed(2)}`;f.wasCacheMiss&&(v+=", miss"),Ure(H,"Server-Timing",v,!0),_.writeHead(h,H&&(H[Symbol.iterator]?Array.from(H):H)),R&&_.end(T)}let b=E.handlerPath,C=E.method;if(Su(S,"duration",b,C,f.wasCacheMiss==null?void 0:f.wasCacheMiss?"cache-miss":"cache-hit"),vre(h<400,"success",b,C),!R)if(T?.pipe){T.pipe(_),T.destroy&&_.on("close",()=>{T.destroy()});let H=0;T.on("data",v=>{H+=v.length}),T.on("end",()=>{Su(performance.now()-p,"transfer",b,C),Su(H,"bytes-sent",b,C)})}else T?.then?T.then(H=>{_.end(H)},u):_.end(T)}catch(d){u(d)}function u(d){let E=d.headers;_.writeHead(d.statusCode||500,E&&(E[Symbol.iterator]?Array.from(E):E)),_.end(d.toString()),d.statusCode?d.statusCode===500?Pt.warn(d):Pt.info(d):Pt.error(d)}a(u,"onError")}),i&&(Vs[e].mtlsConfig=i),t&&(Vs[e].on("secureConnection",l=>{l._parent.startTime&&Su(performance.now()-l._parent.startTime,"tls-handshake",e),Su(l.isSessionReused(),"tls-reused",e)}),Vs[e].isSecure=!0,s.SNICallback(null,(l,_)=>{try{Ya=_,_&&Vs[e].setSecureContext(_.options)}finally{Ya=null}})),BR(Vs[e],e)}return Vs[e]}a(mH,"getHTTPServer");function UR(e,t){let r=pH;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(UR,"makeCallbackChain");function pH(e){return e.user&&(e._nodeRequest.user=e.user),{status:-1,body:"Not found",headers:new uH}}a(pH,"unhandled");function $re(e,t){HR(e,{requestOnly:!0,...t})}a($re,"onRequest");function Yre(e,t){let r;if(t.securePort){let n=Object.assign({},xe.get("tls"));t.mtls?.certificateAuthority&&(n.certificateAuthority=t.mtls.certificateAuthority);let s={noDelay:!0,rejectUnauthorized:!!t.mtls?.required,requestCert:!!t.mtls,SNICallback:xR(n)};r=Mre(s,e),s.SNICallback(null,(i,o)=>{try{Ya=o,o&&r.setSecureContext(o.options)}finally{Ya=null}}),_s[t.securePort]=r}return t.port&&(r=bre({noDelay:!0},e),_s[t.port]=r),r}a(Yre,"onSocket");Object.defineProperty(Nre.prototype,"upgrade",{get(){return"connection"in this.headers&&"upgrade"in this.headers&&this.headers.connection.startsWith("Upgrade")&&this.headers.upgrade.toLowerCase()=="websocket"},set(e){}});function Kre(e,t){let r;for(let{port:n,secure:s}of hH(t)){pE[n]||(pE[n]=new Dre({server:r=mH(n,s)}),pE[n].on("connection",async(c,l)=>{try{let _=new _H(l);_.isWebSocket=!0;let u=SE[n](_),d=l.headers["sec-websocket-protocol"]||"",E=DR[n];if(d){let f;for(let h=0;h<E.length;h++){let p=E[h];p.protocol===d&&(f=!0,p.listener(c,_,u))}if(f)return}for(let f=0;f<E.length;f++){let h=E[f];h.protocol||h.listener(c,_,u)}}catch(_){Pt.warn("Error handling WebSocket connection",_)}}),pE[n].on("error",c=>{console.log("Error in setting up WebSocket server",c)}));let i=t?.subProtocol||"",o=DR[n];o||(o=DR[n]=[]),o.push({listener:e,protocol:i}),SE[n]=UR(PR,n)}return r}a(Kre,"onWebSocket");function cH(e,t){t.writeHead(404),t.end(`Not found
30
- `)}a(cH,"defaultNotFound");function LR(e){return e.startsWith("-----BEGIN")?e:wre(e)}a(LR,"readPEM");function xR(e){let t=[];for(let o=0;e[o];o++)t.push(e[o]);t.length||t.push(e);let r=new Map,n,s,i=!1;for(let o of t){let c=LR(o.privateKey),l=LR(o.certificate),_=o.certificateAuthority&&LR(o.certificateAuthority);if(!c||!l)throw new Error("Missing private key or certificate for secure server");let u={ciphers:o.ciphers,ca:_,ticketKeys:lH()},d=Lre(u);d.options=u,u.instantiatedContext=d,d.context.setCert(l),d.context.setKey(c,void 0),u.cert=l,u.key=c,d.certStart=l.slice(0,100).toString(),n||(n=d);let E=new Hre(l);d.subject=E.subject;let f=o.hostname??o.host??o.hostnames??o.hosts??(E.subjectAltName?E.subjectAltName.split(",").map(h=>{let p=h.indexOf(":");return h.slice(p+1)}):[E.subject.match(/CN=(.*)/)?.[1]]);Array.isArray(f)||(f=[f]);for(let h of f)h?(h[0]==="*"&&(i=!0,h=h.slice(1)),r.has(h)||r.set(h,d),!s&&h.match(/\d+\.\d+\.\d+\.\d+/)&&(s=d)):Pt.error("No hostname found for certificate at",o.certificate)}return(o,c)=>{let l=o;for(;;){let _=r.get(l);if(_)return Pt.debug("Found certificate for",o,_.certStart),c(null,_);if(i&&l){let u=l.indexOf(".",1);u<0?l="":l=l.slice(u)}else break}Pt.debug("No certificate found to match",o,"using the first certificate"),o?c(null,n):c(null,s)}}a(xR,"createSNICallback")});async function AH({clientId:e,user:t,clean:r,will:n,keepalive:s}){let i;if(e&&!r){let o=await FR.get(e,{returnNonexistent:!0});i=new VR(e,t,o),o&&(i.sessionWasPresent=!0)}else{if(e){let o=await FR.get(e);o&&o.delete()}i=new RE(e,t)}return n&&(n.id=e,n.user={username:t?.username},Ru.put(n)),s&&(i.keepalive=s,i.receivedPacket()),i}function qR(){return gE++,gE>65500&&(gE=1),gE}function kR(e,t,r){let{topic:n,retain:s}=e;e.data=t,e.async=!0,r.authorize=!0;let i=gi.getMatch(n);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 Je(r,()=>s?t===void 0?o.delete(e,r):o.put(e,e.data,r):o.publish(e,e.data,r))}var TH,Ci,gH,RH,FR,Ru,gE,RE,VR,OH=Re(()=>{Ae();Bl();TH=B(vr()),Ci=B(K());to();gH=B(it()),RH=B(SH());ur();FR=ft({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"}]}}]}),Ru=ft({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,gH.getWorkerIndex)()===0&&(async()=>{await RH.when_components_loaded,await new Promise(e=>setTimeout(e,2e3));for await(let e of Ru.search({})){let t=e.data,r=Object.assign({},e);r.user?.username&&(r.user=await st.getUser(r.user.username)),Je(r,()=>{try{kR(r,t,r)}catch{(0,Ci.warn)("Failed to publish will",t)}Ru.delete(e.id,r)})}})();a(AH,"getSession");gE=1;a(qR,"getNextMessageId");RE=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,_;if(c>-1?(l=s.slice(c),_=s.slice(0,c)):_=s,!_)throw new Error("No topic provided");if(_.indexOf(".")>-1)throw new Error("Dots are not allowed in topic names");let u=this.subscriptions.find(T=>T.topic===s),d;u?(d=i>0,u.end(),this.subscriptions.splice(this.subscriptions.indexOf(u),1)):d=i===2;let E={search:l,async:!0,user:this.user,startTime:o,omitCurrent:d,url:""};o&&(0,Ci.trace)("Resuming subscription from",s,"from",o);let f=gi.getMatch(_);if(!f){let T=new Error(`The topic ${s} does not exist, no resource has been defined to handle this topic`);throw T.statusCode=404,T}if(E.url=f.relativeURL,E.url.indexOf("+")>-1||E.url.indexOf("#")>-1){let T=E.url.slice(1);if(T.indexOf("#")>-1&&T.indexOf("#")!==T.length-1)throw new Error("Multi-level wildcards can only be used at the end of a topic");if(E.isCollection=!0,T.indexOf("+")===T.length-1)E.onlyChildren=!0,E.url="/"+T.slice(0,T.length-1);else{let R=T.split("/"),b;for(let v=0;v<R.length;v++)if(R[v].indexOf("+")>-1)if(R[v]==="+")b=!0;else throw new Error("Single-level wildcards can only be used as a topic level (between or after slashes)");if(n&&b)throw new Error("Filters can not be combined");let C=!0;R[R.length-1]==="#"&&(R.length--,C=!1),b&&(n=a(v=>{let q=v.id;if(!Array.isArray(q)||C&&q.length!==R.length)return!1;for(let M=0;M<R.length;M++)if(R[M]!=="+"&&R[M]!==q[M])return!1;return!0},"filter"));let H=R.indexOf("+");E.url="/"+(H>-1?R.slice(0,H):R).concat("").join("/")}}let h=f.path,p=f.Resource,S=await Je(E,async()=>{let T=this.createContext();T.topic=s,T.retainHandling=i;let R=await p.subscribe(E,T);if(!R)throw new Error(`No subscription was returned from subscribe for topic ${s}`);if(!R[Symbol.asyncIterator])throw new Error(`Subscription is not (async) iterable for topic ${s}`);return(async()=>{for await(let b of R)try{let C;if(b.type&&b.type!=="put"&&b.type!=="delete"&&b.type!=="message"&&b.type!=="patch"||n&&!n(b))continue;r?(b.topic=s,C=this.needsAcknowledge(b)):(b.acknowledge?.(),C=qR());let H=b.id;Array.isArray(H)&&(H=Ra(H)),H==null&&(H=""),this.listener(h+"/"+H,b.value,C,t)}catch(C){(0,Ci.warn)(C)}})(),R});return S.topic=s,S.qos=t.qos,this.subscriptions.push(S),S}resume(){}needsAcknowledge(t){let r=qR();return t.acknowledge&&(this.awaitingAcks||(this.awaitingAcks=new Map),this.awaitingAcks.set(r,t.acknowledge)),r}acknowledge(t){let r=this.awaitingAcks?.get(t);r&&(this.awaitingAcks.delete(t),r())}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 kR(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();Je(r,async()=>{try{if(!t){let n=await Ru.get(this.sessionId);n?.doesExist()&&await kR(n,n.data,r)}}finally{await Ru.delete(this.sessionId)}}).catch(n=>{(0,Ci.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(kR,"publish");VR=class extends RE{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.timestamp):null)}resumeSubscription(t,r,n){return super.addSubscription(t,r,n)}needsAcknowledge(t){this.awaitingAcks||(this.awaitingAcks=new Map);let r=qR(),n={topic:t.topic,timestamp:t.timestamp};return t.acknowledge&&(n.acknowledge=t.acknowledge),this.awaitingAcks.set(r,n),r}acknowledge(t){let r=this.awaitingAcks.get(t);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,Ci.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,TH.getNextMonotonicTime)()),(0,Ci.trace)("Added durable subscription",t.topic,r),{qos:t.qos,topic:t.topic,startTime:r}}),FR.put(this.sessionRecord)}}});var YR={};qe(YR,{bypassAuth:()=>Wre,start:()=>Qre});function Wre(){wH=!0}function Qre({server:e,port:t,network:r,webSocket:n,securePort:s,requireAuthentication:i}){e.mqtt||(e.mqtt={requireAuthentication:i,sessions:new Set,events:new IH.EventEmitter},e.mqtt.events.on("error",()=>{}));let o=e.mqtt,c,l=r?.mtls;return n&&(c=e.ws((_,u,d)=>{if(_.protocol==="mqtt"){o.events.emit("connection",_),Jt.debug("Received WebSocket connection for MQTT from",_._socket.remoteAddress);let{onMessage:E,onClose:f}=yH(_,(h,p)=>{if(_.send(h),p&&_._socket.writableNeedDrain)return new Promise(S=>this._socket.once("drain",S))},u,Promise.resolve(d).then(()=>u?.user),o);_.on("message",E),_.on("close",f),_.on("error",h=>{Jt.info("WebSocket error",h)})}},Object.assign({subProtocol:"mqtt"},n))),(t||s)&&(c=e.socket(async _=>{let u;if(o.events.emit("connection",_),Jt.debug(`Received ${_.getCertificate?"SSL":"TCP"} connection for MQTT from ${_.remoteAddress}`),l){if(_.authorized)try{let f=l.user;if(f!==null){(f===void 0||f==="Common Name"||f==="CN")&&(f=_.getPeerCertificate().subject.CN);try{u=await e.getUser(f,null,null),(0,Ka.get)(Xt.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)&&OE.notify({username:u?.username,status:Xt.AUTH_AUDIT_STATUS.SUCCESS,type:Xt.AUTH_AUDIT_TYPES.AUTHENTICATION,auth_strategy:"MQTT mTLS",remote_address:_.remoteAddress})}catch(h){throw(0,Ka.get)(Xt.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGFAILED)&&OE.error({username:f,status:Xt.AUTH_AUDIT_STATUS.FAILURE,type:Xt.AUTH_AUDIT_TYPES.AUTHENTICATION,auth_strategy:"mqtt",remote_address:_.remoteAddress}),h}}else Jt.debug("MQTT mTLS authorized connection (mTLS did not authorize a user)","from",_.remoteAddress)}catch(f){o.events.emit("error",f,_),Jt.error(f)}else if(l.required)return Jt.info(`Unauthorized connection attempt, no authorized client certificate provided, error: ${_.authorizationError}`),_.end()}!u&&wH&&_.remoteAddress.includes("127.0.0.1")&&(u=await(0,NH.getSuperUser)(),Jt.debug("Auto-authorizing local connection",u?.username));let{onMessage:d,onClose:E}=yH(_,f=>_.write(f),null,u,o);_.on("data",d),_.on("close",E),_.on("error",f=>{Jt.info("Socket error",f)})},{port:t,securePort:s,mtls:l})),c}function yH(e,t,r,n,s){bH||(bH=!0,nu(d=>{AE>0&&d.push({metric:"mqtt-connections",connections:AE,byThread:!0})}));let i;AE++;let o,c={protocolVersion:4},l=(0,bE.parser)({protocolVersion:5});function _(d){l.parse(d)}a(_,"onMessage");function u(){AE--,i||(i=!0,o?.disconnect?.(),s.events.emit("disconnected",o,e),s.sessions.delete(o),Jr(!1,"connection","mqtt","disconnect"),Jt.debug("MQTT connection was closed",e.remoteAddress))}return a(u,"onClose"),l.on("packet",async d=>{n?.then&&(n=await n),o?.then&&await o;let E=d.topic,f=E?.indexOf("/",1),h=f>0?E.slice(0,f):E;wr(d.length,"bytes-received",h,S(d),"mqtt");try{switch(o?.receivedPacket?.(),d.cmd){case"connect":if(c.protocolVersion=d.protocolVersion,d.username)try{n=await st.getUser(d.username,d.password.toString(),r),(0,Ka.get)(Xt.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)&&OE.notify({username:n?.username,status:Xt.AUTH_AUDIT_STATUS.SUCCESS,type:Xt.AUTH_AUDIT_TYPES.AUTHENTICATION,auth_strategy:"MQTT",remote_address:e.remoteAddress})}catch(M){return(0,Ka.get)(Xt.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGFAILED)&&OE.error({username:d.username,status:Xt.AUTH_AUDIT_STATUS.FAILURE,type:Xt.AUTH_AUDIT_TYPES.AUTHENTICATION,auth_strategy:"mqtt",remote_address:e.remoteAddress}),s.events.emit("auth-failed",d,e,M),Jr(!1,"connection","mqtt","connect"),p({cmd:"connack",reasonCode:4,returnCode:134})}if(!n&&s.requireAuthentication)return s.events.emit("auth-failed",d,e),Jr(!1,"connection","mqtt","connect"),p({cmd:"connack",reasonCode:4,returnCode:134});try{if(s.authorizeClient?.(d,n),d.will){let M=e.deserialize||(e.deserialize=po(r?.headers.get?.("content-type")));d.will.data=d.will.payload?.length>0?M(d.will.payload):void 0,delete d.will.payload}o=AH({user:n,...d}),o=await o,o.socket=e,r&&(o.request=r),s.sessions.add(o)}catch(M){return Jt.error(M),s.events.emit("auth-failed",d,e,M),Jr(!1,"connection","mqtt","connect"),p({cmd:"connack",reasonCode:M.code||5,returnCode:M.code||128})}s.events.emit("connected",o,e),Jr(!0,"connection","mqtt","connect"),p({cmd:"connack",sessionPresent:o.sessionWasPresent,reasonCode:0,returnCode:0}),o.setListener((M,Q,J,X)=>{try{let ae=M.indexOf("/",1),ce=ae>0?M.slice(0,ae):M;p({cmd:"publish",topic:M,payload:T(Q),messageId:J||Math.floor(Math.random()*1e8),qos:X.qos},ce)}catch(ae){Jt.error(ae),o?.disconnect(),s.sessions.delete(o)}}),o.sessionWasPresent&&await o.resume();break;case"subscribe":let R=[];for(let M of d.subscriptions){let Q;try{Q=(await o.addSubscription(M,M.qos>=1)).qos||0}catch(J){s.events.emit("error",J,e,M,o),Jt.error(J),Q=c.protocolVersion<5?128:J.statusCode===403?135:J.statusCode===404?143:128}R.push(Q)}await o.committed,p({cmd:"suback",granted:R,messageId:d.messageId});break;case"unsubscribe":{let M=[];for(let Q of d.unsubscriptions)M.push(o.removeSubscription(Q)?0:17);p({cmd:"unsuback",granted:M,messageId:d.messageId});break}case"pubrel":p({cmd:"pubcomp",messageId:d.messageId,reasonCode:0});return;case"publish":let b=d.qos===2?"pubrec":"puback",C=e.deserialize||(e.deserialize=po(r?.headers.get?.("content-type"))),v=(d.payload?.length||0)>0?C(d.payload):void 0,q;try{q=await o.publish(d,v)}catch(M){s.events.emit("error",M,e,d,o),Jt.warn(M),d.qos>0&&p({cmd:b,messageId:d.messageId,reasonCode:128},d.topic);break}d.qos>0&&p({cmd:b,messageId:d.messageId,reasonCode:q===!1?144:0},d.topic);break;case"pubrec":p({cmd:"pubrel",messageId:d.messageId,reasonCode:0});break;case"pubcomp":case"puback":o.acknowledge(d.messageId);break;case"pingreq":p({cmd:"pingresp"});break;case"disconnect":i=!0,o?.disconnect(!0),s.events.emit("disconnected",o,e),s.sessions.delete(o),Jr(!0,"connection","mqtt","disconnect"),Jt.debug("Received disconnect command, closing MQTT session",e.remoteAddress),e.close?e.close():e.end();break}}catch(R){s.events.emit("error",R,e,d,o),Jt.error(R),p({cmd:"disconnect"})}function p(R,b){let C=(0,bE.generate)(R,c);t(C),wr(C.length,"bytes-sent",b,S(R),"mqtt")}a(p,"sendPacket");function S(R){return R.qos>0?R.cmd+",qos="+R.qos:R.cmd}a(S,"packetMethodName");function T(R){return fo(R,r)}a(T,"serialize")}),l.on("error",d=>{Jt.warn("MQTT parsing error, closing connection:",d.message),e?.destroy?e.destroy():e?.terminate()}),{onMessage:_,onClose:u}}var bE,NH,Ka,Xt,$R,IH,OE,Jt,wH,bH,AE,CH=Re(()=>{bE=require("mqtt-packet");OH();NH=B(un());Oa();Bs();ur();Ka=B(te()),Xt=B(U()),$R=B(K()),IH=require("events"),OE=(0,$R.loggerWithTag)("auth-event"),Jt=(0,$R.loggerWithTag)("mqtt"),wH=(0,Ka.get)(Xt.CONFIG_PARAMS.AUTHENTICATION_AUTHORIZELOCAL)??process.env.DEV_MODE;a(Wre,"bypassAuth");a(Qre,"start");AE=0;a(yH,"onSocket")});var mf={};qe(mf,{component_errors:()=>Qa,loadComponent:()=>yE,loadComponentDirectories:()=>xH,setErrorReporter:()=>jre});function xH(e,t){t&&(WR=t),e&&(QR=e);let r=[];if((0,je.existsSync)(KR)){let s=(0,je.readdirSync)(KR,{withFileTypes:!0});for(let i of s){if(!i.isDirectory()&&!i.isSymbolicLink())continue;let o=i.name,c=(0,tt.join)(KR,o);r.push(yE(c,WR,"hdb",!1))}}let n=process.env.RUN_HDB_APP;return n&&r.push(yE(n,WR,n,!1,null,process.env.DEV_MODE)),Promise.all(r).then(()=>{HH=!0})}function jre(e){Au=e}async function yE(e,t,r,n,s,i){let o=(0,je.realpathSync)(e);if(!LH.has(o)){LH.set(o,!0),s&&(QR=s);try{let c;n&&(Qa=new Map);let l=(0,tt.join)(e,n?"harperdb-config.yaml":"config.yaml");(0,je.existsSync)(l)?c=n?(0,BH.getConfigObj)():(0,MH.parseDocument)((0,je.readFileSync)(l,"utf8"),{simpleKeys:!0}).toJSON():c=zR;let _=(0,tt.join)(e,"node_modules","harperdb");try{yo.isMainThread&&(n||(0,je.existsSync)(_)&&(0,je.realpathSync)(Ja.PACKAGE_ROOT)!==(0,je.realpathSync)(_))&&((0,je.rmSync)(_,{recursive:!0,force:!0}),(0,je.existsSync)((0,tt.join)(e,"node_modules"))||(0,je.mkdirSync)((0,tt.join)(e,"node_modules")),(0,je.symlinkSync)(Ja.PACKAGE_ROOT,_,"dir"))}catch(E){Wa.default.error("Error symlinking harperdb module",E)}let u=[],d=n;for(let E in c){let f=c[E];if(Qa.set(n?E:(0,tt.basename)(e),!1),!f)continue;let h,p=f.package;try{if(p){let C=e,H;for(;!(0,je.existsSync)(H=(0,tt.join)(C,"node_modules",E));)if(C=(0,tt.dirname)(C),C.length<(0,vH.getHdbBasePath)().length){H=null;break}if(H)h=await yE(H,t,r,!1),d=!0;else throw new Error(`Unable to find package ${E}:${p}`)}else h=Xre[E];if(!h)continue;u.push(h);let S=a(C=>(C.origin=r,ft(C)),"ensureTable"),T=f.network||(f.port||f.securePort)&&f,R=T?.securePort||T?.https&&T.port,b=!T?.https&&T?.port;if(yo.isMainThread&&(h=await h.startOnMainThread?.({server:st,ensureTable:S,port:b,securePort:R,resources:t,...f})||h,n&&T))for(let C of[b,R])try{if(+C&&!DH.includes(C)){let H=JR.get(Ja.CONFIG_PARAMS.HTTP_SESSIONAFFINITY);H&&Wa.default.warn("Session affinity is not recommended and may cause memory leaks"),(H||!uE)&&(DH.push(C),$B(C,H))}}catch(H){console.error("Error listening on socket",C,H,E)}if(t.isWorker&&(h=await h.start?.({server:st,ensureTable:S,port:b,securePort:R,resources:t,...f})||h),QR.set(h,!0),(h.handleFile||h.handleDirectory)&&f.files){if(f.files.includes(".."))throw(0,UH.handleHDBError)("Can not reference parent directories");let C=(0,tt.join)(e,f.files).replace(/\\/g,"/"),H=C.indexOf("/*");if(H>-1&&f.files!==zR[E]?.files&&!(0,je.existsSync)(C.slice(0,H)))throw new Error(`The path '${C.slice(0,H)}' does not exist and cannot be used as the base of the resolved 'files' path value '${f.files}'`);let v=(0,tt.basename)(e),q=f.path||"/";q=q.startsWith("/")?q:q.startsWith("./")?"/"+v+q.slice(2):q==="."?"/"+v:"/"+v+"/"+q;let M,Q,J;if(f.root){let ae=f.root;ae.startsWith("/")&&(ae=ae.slice(1)),ae.endsWith("/")&&(ae=ae.slice(0,-1)),ae+="/",Q=(0,tt.join)(e,ae)}else(J=C.indexOf("/*"))>-1&&(Q=C.slice(0,J+1),M=(0,tt.relative)(e,Q));let X=!1;if(yo.isMainThread&&h.setupDirectory&&(X=await h.setupDirectory?.(q,Q,t)),t.isWorker&&h.handleDirectory&&(X=await h.handleDirectory?.(q,Q,t)),X)continue;for(let ae of await(0,PH.default)(C,{onlyFiles:!1,objectMode:!0})){let{path:ce,dirent:ge}=ae;d=!0;let Ge=(0,tt.relative)(e,ce).replace(/\\/g,"/");if(M)if(Ge.startsWith(M))Ge=Ge.slice(M.length+1);else throw new Error(`The root path '${f.root}' does not reference a valid part of the file path '${Ge}'.The root path should be used to indicate the relative path/part of the file path for determining the exported web path.`);let Ne=q+(q.endsWith("/")?"":"/")+Ge;try{if(ge.isFile()){let ve=await Jre(ce);yo.isMainThread&&await h.setupFile?.(ve,Ne,ce,t),t.isWorker&&await h.handleFile?.(ve,Ne,ce,t)}else yo.isMainThread&&await h.setupDirectory?.(Ne,ce,t),t.isWorker&&await h.handleDirectory?.(Ne,ce,t)}catch(ve){ve.message=`Could not load ${ge.isFile()?"file":"directory"} '${ce}'${f.module?" using '"+f.module+"'":""} for application '${e}' due to: ${ve.message}`,Au?.(ve),((0,za.getWorkerIndex)()===0?console:Wa.default).error(ve),t.set(f.path||"/",new Ou(ve)),Qa.set(n?E:(0,tt.basename)(e),ve.message)}}}}catch(S){S.message=`Could not load component '${E}' for application '${(0,tt.basename)(e)}' due to: ${S.message}`,Au?.(S),((0,za.getWorkerIndex)()===0?console:Wa.default).error(S),t.set(f.path||"/",new Ou(S),null,!0),Qa.set(n?E:(0,tt.basename)(e),S.message)}}if(yo.isMainThread&&!HH&&i&&(0,za.watchDir)(e,async()=>xH()),c.extensionModule)return await c_((0,tt.join)(e,c.extensionModule));if(!d&&t.isWorker){let E=`${e} did not load any modules, resources, or files, is this a valid component?`;Au?.(new Error(E)),((0,za.getWorkerIndex)()===0?console:Wa.default).error(E),Qa.set((0,tt.basename)(e),E)}}catch(c){console.error(`Could not load application directory ${e}`,c),c.message=`Could not load application due to ${c.message}`,Au?.(c),t.set("",new Ou(c))}}}var je,tt,yo,MH,JR,Ja,PH,za,Wa,UH,vH,zre,BH,Jre,KR,QR,HH,WR,Qa,Xre,zR,DH,LH,Au,Ou,pf=Re(()=>{je=require("fs"),tt=require("path"),yo=require("worker_threads"),MH=require("yaml"),JR=B(te()),Ja=B(U());tb();ib();ob();qv();MB();xB();PH=B(require("fast-glob")),za=B(it()),Wa=B(K());xh();ur();UH=B(ne());yn();Ae();YB();vH=B(te()),zre=B(JB());cf();sH();CH();BH=B(Er());_E();({readFile:Jre}=je.promises),KR=JR.get(Ja.CONFIG_PARAMS.COMPONENTSROOT),QR=new Map,Qa=new Map;a(xH,"loadComponentDirectories");Xre={REST:xf,rest:xf,graphqlSchema:Hh,jsResource:Fh,fastifyRoutes:fR,login:kh,static:ER,operationsApi:zre,customFunctions:{},http:{},clustering:wR,authentication:xl,mqtt:YR},zR={rest:!0,graphqlSchema:{files:"*.graphql"},jsResource:{files:"resources.js"},fastifyRoutes:{files:"routes/*.js",path:"."}};Object.defineProperty(zR,"static",{value:{files:"web/**"}});DH=[],LH=new Map;a(jre,"setErrorReporter");a(yE,"loadComponent");Ou=class extends $t{constructor(r){super();this.error=r}static{a(this,"ErrorResource")}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 GR=g((xme,FH)=>{var{isMainThread:GH}=require("worker_threads"),{getTables:Zre}=(Ae(),ie(ke)),{loadComponentDirectories:ene,loadComponent:tne}=(pf(),ie(mf)),{resetResources:rne}=(Bl(),ie(LP)),nne=YT(),sne=Er(),{dirname:ine}=require("path"),{getConnection:one}=wt(),ane=te(),cne=U(),XR=new Map;async function lne(e=!1){!GH&&ane.get(cne.CONFIG_PARAMS.CLUSTERING_ENABLED)&&one();try{GH&&await nne()}catch(n){console.error(n)}let t=rne();Zre(),t.isWorker=e,await tne(ine(sne.getConfigFilePath()),t,"hdb",!0,XR),await ene(XR,t);let r=[];for(let[n]of XR)n.ready&&r.push(n.ready());r.length>0&&await Promise.all(r)}a(lne,"loadRootComponents");FH.exports.loadRootComponents=lne});var it=g((Fme,Li)=>{"use strict";var{Worker:une,MessageChannel:_ne,parentPort:ds,isMainThread:rA,threadId:dne,workerData:$s}=require("worker_threads"),{PACKAGE_ROOT:fne}=U(),{join:$H,isAbsolute:Ene,extname:hne}=require("path"),{server:YH}=(ur(),ie(vi)),{watch:mne,readdir:pne}=require("fs/promises"),{totalmem:qH}=require("os"),bu=U(),KH=te(),Ys=K(),{randomBytes:Sne}=require("crypto"),{_assignPackageExport:Tne}=require("../index"),gne=U(),kH=1024*1024,Di=[],Sn=[],Rne=50,nA=1e4,Ane="restart",WH="request_thread_info",QH="resource_report",zH="thread_info",JH="added-port",One="ack",jR;Tne("threads",Sn);Li.exports={startWorker:ZR,restartWorkers:iA,shutdownWorkers:wne,workers:Di,setMonitorListener:Bne,onMessageFromWorkers:Cne,onMessageByType:nx,broadcast:Lne,broadcastWithAcknowledgement:Pne,setChildListenerByType:Ine,getWorkerIndex:XH,getWorkerCount:jH,getTicketKeys:ex,setMainIsWorker:yne,setTerminateTimeout:bne,restartNumber:$s?.restartNumber||1};Sn.onMessageByType=nx;Sn.sendToThread=function(e,t){if(!t?.type)throw new Error("A message with a type must be provided");let r=Sn.find(n=>n.threadId===e);if(r)return r.postMessage(t),!0};var sA;function bne(e){nA=e}a(bne,"setTerminateTimeout");function XH(){return $s?$s.workerIndex:sA?0:void 0}a(XH,"getWorkerIndex");function jH(){return $s?$s.workerCount:sA?1:void 0}a(jH,"getWorkerCount");function yne(e){sA=e}a(yne,"setMainIsWorker");var ZH=1,NE;function ex(){return NE||(NE=rA?Sne(48):$s.ticketKeys,NE)}a(ex,"getTicketKeys");Object.defineProperty(YH,"workerIndex",{get(){return XH()}});Object.defineProperty(YH,"workerCount",{get(){return jH()}});var tx={[WH](e,t){Une(t)},[QH](e,t){vne(t,e)}};function ZR(e,t={}){let r=process.constrainedMemory?.()||qH();r=Math.min(r,qH(),2e4*kH);let n=KH.get(bu.CONFIG_PARAMS.THREADS_MAXHEAPMEMORY)??Math.max(Math.floor(r/kH/(10+(t.threadCount||1)/4)),512),s=Math.min(Math.max(n>>6,16),64),i=[],o=[];for(let l of Sn){let _=new _ne;_.existingPort=l,i.push(_),o.push(_.port2)}hne(e)||(e+=".js");let c=new une(Ene(e)?e:$H(fne,e),Object.assign({resourceLimits:{maxOldGenerationSizeMb:n,maxYoungGenerationSizeMb:s},execArgv:["--enable-source-maps"],argv:process.argv.slice(2),workerData:{addPorts:o,addThreadIds:i.map(l=>l.existingPort.threadId),workerIndex:t.workerIndex,workerCount:ZH=t.threadCount,name:t.name,restartNumber:Li.exports.restartNumber,ticketKeys:ex()},transferList:o},t));for(let{port1:l,existingPort:_}of i)_.postMessage({type:JH,port:l,threadId:c.threadId},[l]);return wE(c,!0),c.unexpectedRestarts=t.unexpectedRestarts||0,c.startCopy=()=>ZR(e,t),c.on("error",l=>{Ys.error(`Worker index ${t.workerIndex} error:`,l)}),c.on("exit",l=>{Di.splice(Di.indexOf(c),1),!c.wasShutdown&&t.autoRestart!==!1&&(c.unexpectedRestarts<Rne?(t.unexpectedRestarts=c.unexpectedRestarts+1,ZR(e,t)):Ys.error(`Thread has been restarted ${c.restarts} times and will not be restarted`))}),c.on("message",l=>{tx[l.type]?.(l,c)}),Di.push(c),xne(),t.onStarted&&t.onStarted(c),c.name=t.name,c}a(ZR,"startWorker");var Nne=[bu.THREAD_TYPES.HTTP];async function iA(e=null,t=Math.max(ZH>3,1),r=!0){if(rA){if(r){let{loadRootComponents:o}=GR();await o()}Li.exports.restartNumber++,t<1&&(t=t*Di.length);let n=[],s=[];for(let o of Di.slice(0)){if(e&&o.name!==e||o.wasShutdown)continue;Ys.trace("sending shutdown request to ",o.threadId),o.postMessage({restartNumber:Li.exports.restartNumber,type:bu.ITC_EVENT_TYPES.SHUTDOWN}),o.wasShutdown=!0,o.emit("shutdown",{});let c=Nne.indexOf(o.name)>-1,l=new Promise(_=>{let u=setTimeout(()=>o.terminate(),nA*2).unref();o.on("exit",()=>{clearTimeout(u),n.splice(n.indexOf(l)),!c&&r&&o.startCopy(),_()})});if(n.push(l),c&&r){let _=o.startCopy(),u=new Promise(d=>{let E=a(f=>{f.type===gne.ITC_EVENT_TYPES.CHILD_STARTED&&(Ys.trace("Worker has started",_.threadId),d(),s.splice(s.indexOf(u)),_.off("message",E))},"startListener");Ys.trace("Waiting for worker to start",_.threadId),_.on("message",E)});s.push(u),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}=Ul();r&&(e==="http"||!e)&&KH.get(bu.CONFIG_PARAMS.CLUSTERING_ENABLED)&&await i({service:"clustering"})}else ds.postMessage({type:Ane,workerType:e})}a(iA,"restartWorkers");function Ine(e,t){tx[e]=t}a(Ine,"setChildListenerByType");function wne(e){return iA(e,1/0,!1)}a(wne,"shutdownWorkers");var rx=[];function Cne(e){rx.push(e)}a(Cne,"onMessageFromWorkers");var eA=new Map;function nx(e,t){let r=eA.get(e);r||eA.set(e,r=[]),r.push(t)}a(nx,"onMessageByType");var Dne=10;async function Lne(e){let t=0;for(let r of Sn)try{r.postMessage(e),t++>Dne&&(t=0,await new Promise(setImmediate))}catch(n){Ys.error("Unable to send message to worker",n)}}a(Lne,"broadcast");var IE=new Map,Mne=1;function Pne(e){return new Promise(t=>{let r=0;for(let n of Sn)try{let s=Mne++,i=a(()=>{IE.delete(s),--r===0&&t(),n!==ds&&--n.refCount===0&&n.unref()},"ack_handler");i.port=n,n.ref(),n.refCount=(n.refCount||0)+1,IE.set(e.requestId=s,i),n.hasAckCloseListener||(n.hasAckCloseListener=!0,n.on(n.close?"close":"exit",()=>{for(let[,o]of IE)o.port===n&&o()})),n.postMessage(e),r++}catch(s){Ys.error("Unable to send message to worker",s)}r===0&&t()})}a(Pne,"broadcastWithAcknowledgement");function Une(e){e.postMessage({type:zH,workers:sx()})}a(Une,"sendThreadInfo");function sx(){let e=Date.now();return Di.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(sx,"getChildWorkerInfo");function vne(e,t){e.resources=t,e.resources.updated=Date.now()}a(vne,"recordResourceReport");var tA;function Bne(e){tA=e}a(Bne,"setMonitorListener");var Hne=1e3,VH=!1;function xne(){VH||(VH=!0,setInterval(()=>{for(let e of Di){let t=e.performance.eventLoopUtilization(),r;e.lastTotalELU?r=e.performance.eventLoopUtilization(t,e.lastTotalELU):r=t,e.lastTotalELU=t,e.recentELU=r}tA&&tA()},Hne).unref())}a(xne,"startMonitoring");var Gne=1e3;if(ds){wE(ds);for(let e=0,t=$s.addPorts.length;e<t;e++){let r=$s.addPorts[e];r.threadId=$s.addThreadIds[e],wE(r)}setInterval(()=>{let e=process.memoryUsage();ds.postMessage({type:QH,heapTotal:e.heapTotal,heapUsed:e.heapUsed,external:e.external,arrayBuffers:e.arrayBuffers})},Gne).unref(),jR=a(()=>new Promise((e,t)=>{ds.on("message",r),ds.postMessage({type:WH});function r(n){n.type===zH&&(ds.off("message",r),e(n.workers))}a(r,"receiveThreadInfo")}),"getThreadInfo")}else jR=sx;Li.exports.getThreadInfo=jR;function wE(e,t){Sn.push(e),e.on("message",r=>{if(r.type===JH)r.port.threadId=r.threadId,wE(r.port);else if(r.type===One){let n=IE.get(r.id);n&&n()}else{for(let s of rx)s(r,e);let n=eA.get(r.type);if(n)for(let s of n)try{s(r,e)}catch(i){Ys.error(i)}}}).on("close",()=>{Sn.splice(Sn.indexOf(e),1)}).on("exit",()=>{Sn.splice(Sn.indexOf(e),1)}),t?e.refCount=100:e.unref()}a(wE,"addPort");if(rA){let e,t,r=new Set,n=a(async(s,i)=>{i&&(e=i);for(let o of await pne(s,{withFileTypes:!0}))o.isDirectory()&&o.name!=="node_modules"&&n($H(s,o.name));try{for await(let{filename:o}of mne(s,{persistent:!1}))r.add(o),t&&clearTimeout(t),t=setTimeout(async()=>{e&&await e(),await iA(),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");Li.exports.watchDir=n,process.env.WATCH_DIR&&n(process.env.WATCH_DIR)}else ds.on("message",async e=>{let{type:t}=e;t===bu.ITC_EVENT_TYPES.SHUTDOWN&&(Li.exports.restartNumber=e.restartNumber,ds.unref(),setTimeout(()=>{Ys.warn("Thread did not voluntarily terminate",dne),process.exit(0)},nA).unref())})});var fC={};qe(fC,{AUDIT_STORE_OPTIONS:()=>Zd,createAuditEntry:()=>f_,openAuditStore:()=>ME,readAuditEntry:()=>vt,setAuditRetention:()=>qne,transactionKeyEncoder:()=>fx});function ME(e){let t=e.auditStore=e.openDB(ux.AUDIT_STORE_NAME,Zd);t.rootStore=e;let r=[];t.addDeleteRemovalCallback=function(i,o){return r[i]=o,{remove(){delete r[i]}}};let n=null;function s(i=CE){clearTimeout(n),n=setTimeout(async()=>{if(t.rootStore.status==="closed"||t.rootStore.status==="closing")return;let o=0,c;try{for(let{key:l,value:_}of t.getRange({start:0,snapshot:!1,end:Date.now()-oA})){if((_[0]&15)===lA){let u=vt(_),d=u.tableId;r[d]?.(u.recordId)}if(c=t.remove(l),await new Promise(setImmediate),++o>=Fne){i=10;break}}await c}finally{o===0&&(i=Math.min(i<<1,oA/10)),s(i)}},i).unref()}return a(s,"scheduleAuditCleanup"),t.scheduleAuditCleanup=s,(0,LE.getWorkerIndex)()===(0,LE.getWorkerCount)()-1&&s(CE),t}function qne(e,t=CE){oA=e,CE=t}function f_(e,t,r,n,s,i,o){let c=Ex[i];if(!c)throw new Error(`Invalid audit entry type ${i}`);let l=1;n&&(n>1?Xa.setFloat64(0,n):Tn.set(sm),l=9),E(0),E(t),d(r),Xa.setFloat64(l,e),l+=8,s?d(s):Tn[l++]=0,Tn[n?8:0]=c;let u=Tn.subarray(0,l);if(o)return Buffer.concat([u,o]);return u;function d(f){let h=l;l+=1,l=(0,ja.writeKey)(f,Tn,l);let p=l-h-1;p>127?p>16383?(_A.error("Key or username was too large for audit entry",f),l=h+1,Tn[h]=0):(Tn.copyWithin(h+2,h+1,l),Xa.setUint16(h,p|32768),l++):Tn[h]=p}function E(f){f<128?Tn[l++]=f:f<16384?(Xa.setUint16(l,f|32768),l+=2):f<1056964608?(Xa.setUint32(l,f|3221225472),l+=4):(Tn[l]=255,Xa.setUint32(l+1,f),l+=5)}}function vt(e){try{let t=e.dataView||(e.dataView=new uA(e.buffer,e.byteOffset,e.byteLength)),r;e[0]==66&&(r=t.readFloat64());let n=t.readInt(),s=t.readInt(),i=t.readInt(),o=t.readInt(),c=t.position,l=t.position+=o,_=t.readFloat64();o=t.readInt();let u=t.position,d=t.position+=o;return{type:Ex[n&7],tableId:i,get recordId(){return lx(e,c,l)},version:_,previousLocalTime:r,get user(){return d>u?lx(e,u,d):void 0},getValue(E,f,h){if(n&aA||n&cA&&!f)return E.decoder.decode(e.subarray(t.position));if(n&cA&&h)return dA(E.getEntry(this.recordId),h,E)}}}catch(t){return _A.error("Reading audit entry error",t,e),{}}}function lx(e,t,r){let n=e.subarray(t,r);return(0,ja.readKey)(n,0,r-t)}var ja,DE,ux,_x,LE,dx,_A,Tn,Xa,fx,Zd,oA,Fne,CE,aA,cA,ix,lA,ox,ax,cx,Ex,uA,Zs=Re(()=>{ja=require("ordered-binary"),DE=B(te()),ux=B(dt()),_x=B(U()),LE=B(it()),dx=B(z());wc();_A=B(K());PE();(0,DE.initSync)();Tn=Buffer.alloc(1024),Xa=new DataView(Tn.buffer,Tn.byteOffset,1024),fx={writeKey(e,t,r){return e===Ic?(t.set(Ic,r),r+8):typeof e=="number"?((t.dataView||(t.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength))).setFloat64(r,e),r+8):(0,ja.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,ja.readKey)(e,t,r)}},Zd={encoding:"binary",keyEncoder:fx},oA=(0,dx.convertToMS)((0,DE.get)(_x.CONFIG_PARAMS.LOGGING_AUDITRETENTION))||86400*3,Fne=1e3,CE=1e4;a(ME,"openAuditStore");a(qne,"setAuditRetention");aA=16,cA=32,ix=1,lA=2,ox=3,ax=4,cx=5,Ex={put:ix|aA,[ix]:"put",delete:lA,[lA]:"delete",message:ox|aA,[ox]:"message",invalidate:ax,[ax]:"invalidate",patch:cx|cA,[cx]:"patch"};a(f_,"createAuditEntry");a(vt,"readAuditEntry");uA=class extends DataView{static{a(this,"Decoder")}position=0;readInt(){let t=this.getUint8(this.position++);return 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{debugger}}};a(lx,"readKeySafely")});var fA={};qe(fA,{add:()=>UE,applyReverse:()=>hx,getRecordAtTime:()=>dA,rebuildUpdateBefore:()=>vE});function UE(e,t,r){let n=e[t];typeof n=="bigint"?e[t]=n+BigInt(r.value):isNaN(e[t])?e[t]=r.value:e[t]=n+r.value}function vE(e,t){let r=null;for(let n in e)if(n in t){let s=t[n];if(s?.__op__){let i=e[n];if(i?.__op__)if(i.__op__===s.__op__)r||(r={}),r[n]=i;else throw new Error("Can not merge updates with different operations");else r||(r={}),r[n]=i,UE(r,n,s)}}else r||(r={}),r[n]=e[n];return r}function hx(e,t){for(let r in t){let n=t[r];if(n?.__op__){let s=kne[n.__op__]?.reverse;if(s)s(e,r,{value:n.value});else throw new Error(`Unsupported operation ${n.__op__}`)}else e[r]=mx}}function dA(e,t,r){let n=r.rootStore.auditStore,s=Object.assign({},e.value),i=e.localTime;for(;i>t;){let l=n.get(i),_=vt(l);switch(_.type){case"put":s=_.getValue(r);break;case"patch":hx(s,_.getValue(r));break;case"delete":s=null}i=_.previousLocalTime}let o={},c=0;for(let l in s)s[l]===mx&&(o[l]=!0,c++);for(;c>0&&i>0;){let l=n.get(i),_=vt(l),u;switch(_.type){case"put":u=_.getValue(r);break;case"patch":u=_.getValue(r);break}for(let d in u)o[d]&&(s[d]=u[d],o[d]=!1,c--);i=_.previousLocalTime}if(c>0)for(let l in o)s[l]=null;return s}var kne,mx,PE=Re(()=>{Zs();a(UE,"add");UE.reverse=function(e,t,r){let n=e[t];typeof n=="bigint"?e[t]=n-BigInt(r.value):isNaN(e[t])||(e[t]=n-r.value)};kne={add:UE};a(vE,"rebuildUpdateBefore");a(hx,"applyReverse");mx={};a(dA,"getRecordAtTime")});function jr(e){return e[yt]||(e[yt]=Object.create(null))}function FE(e,t){let r=e.prototype,n={},s=t.attributes||t.properties||[];for(let o of s){let c=o.name,l,_;if(o.resolve)_={get(){return o.resolve(this,this[ye])},set(u){return o.set(this,u)},configurable:!0};else{switch(o.type){case"String":l=a(function(u){if(!(typeof u=="string"||u==null&&o.nullable!==!1))throw new gn.ClientError(`${c} must be a string, attempt to assign ${u}`);jr(this)[c]=u},"set");break;case"ID":l=a(function(u){if(!(typeof u=="string"||u?.length>0&&u.every?.(d=>typeof d=="string")||u==null&&o.nullable!==!1))throw new gn.ClientError(`${c} must be a string, attempt to assign ${u}`);jr(this)[c]=u},"set");break;case"Float":case"Number":l=a(function(u){let d=u?.__op__?u.value:u;if(!(typeof d=="number"||u==null&&o.nullable!==!1))throw new gn.ClientError(`${c} must be a number, attempt to assign ${d}`);jr(this)[c]=u},"set");break;case"Int":l=a(function(u){let d=u?.__op__?u.value:u;if(!(d>>0===d||u==null&&o.nullable!==!1))if(typeof d=="number"&&Math.abs((d>>0)-d)<=1)d=Math.round(d),u?.__op__?u.value=d:u=d;else throw new gn.ClientError(`${c} must be an integer between -2147483648 and 2147483647, attempt to assign ${u}`);jr(this)[c]=u},"set");break;case"Long":l=a(function(u){let d=u?.__op__?u.value:u;if(!(Math.round(d)===u&&Math.abs(d)<=9007199254740992||u==null&&o.nullable!==!1))if(typeof d=="number"&&Math.abs(d)<=9007199254740992)d=Math.round(d),u?.__op__?u.value=d:u=d;else throw new gn.ClientError(`${c} must be an integer between -9007199254740992 and 9007199254740992, attempt to assign ${u}`);jr(this)[c]=u},"set");break;case"BigInt":l=a(function(u){let d=u?.__op__?u.value:u;if(!(typeof d=="bigint"||u==null&&o.nullable!==!1))if(typeof d=="string"||typeof d=="number")d=BigInt(d),u?.__op__?u.value=d:u=d;else throw new gn.ClientError(`${c} must be a number, attempt to assign ${u}`);jr(this)[c]=u},"set");break;case"Boolean":l=a(function(u){if(!(typeof u=="boolean"||u==null&&o.nullable!==!1))throw new gn.ClientError(`${c} must be a boolean, attempt to assign ${u}`);jr(this)[c]=u},"set");break;case"Date":l=a(function(u){if(!(u instanceof Date||u==null&&o.nullable!==!1))if(typeof u=="string"||typeof u=="number")u=new Date(u);else throw new gn.ClientError(`${c} must be a Date, attempt to assign ${u}`);jr(this)[c]=u},"set");break;case"Bytes":l=a(function(u){if(!(u instanceof Uint8Array||u==null&&o.nullable!==!1))throw new gn.ClientError(`${c} must be a Buffer or Uint8Array, attempt to assign ${u}`);jr(this)[c]=u},"set");break;case"Any":case void 0:l=a(function(u){jr(this)[c]=u},"set");break;default:l=a(function(u){if(!(typeof u=="object"||u==null&&o.nullable!==!1))throw new gn.ClientError(`${c} must be an object, attempt to assign ${u}`);jr(this)[c]=u},"set")}_={get(){let u=this[yt];if(u&&c in u){let E=u[c];if(E?.__op__){let f=this[de]?.[c];return E.update(f)}return E}let d=this[de]?.[c];if(d&&typeof d=="object"){let E=Sx(d,o);if(E)return u||(u=this[yt]=Object.create(null)),u[c]=E}return d},set:l,enumerable:!0,configurable:!0}}_.get.isAttribute=!0,n[c]=_,(!(c in r)||Object.getOwnPropertyDescriptor(r,c)?.get?.isAttribute)&&Object.defineProperty(r,c,_)}i("getProperty",function(o){let c=n[o];if(c)return c.get.call(this);let l=this[yt];return l?.[o]!==void 0?l[o]:this[de]?.[o]}),i("set",function(o,c){let l=n[o];if(l)return l.set.call(this,c);if(t.sealed)throw new gn.ClientError("Can not add a property to a sealed table schema");jr(this)[o]=c}),i("deleteProperty",function(o){jr(this)[o]=void 0}),i("toJSON",function(){let o=this[yt],c;for(let _ in o){c||(c=Object.assign({},this[de]));let u=o[_];if(u?.__op__){let d=c[_];u=u.update(d)}c[_]=u}return Object.keys(this).length>0&&(c||(c=Object.assign({},this[de])),Object.assign(c,this)),c||this[de]}),r.get||i("get",r.getProperty),r.delete||i("delete",r.deleteProperty);function i(o,c){Object.defineProperty(r,o,{value:c,configurable:!0})}a(i,"setMethod")}function Sx(e,t){let r;switch(e.constructor){case Object:return t?((r=t.TrackedObject)||(t.TrackedObject=r=class{static{a(this,"TrackedObject")}constructor(s){if(s?.[de])throw new Error("Can not track an already tracked object, check for circular references");this[de]=s}},FE(r,t)),new r(e)):new BE(e);case Array:let n=new xE(e.length);n[de]=e;for(let s=0,i=e.length;s<i;s++){let o=e[s];o&&typeof o=="object"&&(o=Sx(o,t?.elements)),n[s]=o}return n;default:return e}}function cd(e){let t=e[yt],r;for(let s in t){r||(r=Object.assign({},e[de]));let i=t[s];if(i&&typeof i=="object")if(i.__op__){let o=r[s];i=i.update(o)}else i=cd(i);r[s]=i}return Object.keys(e).length>0&&(r||(r=Object.assign({},e[de])),Object.assign(r,e)),r||e[de]}function Io(e,t=e[yt]){let r;if(px.call(e,de)&&e.constructor===Array&&!Object.isFrozen(e)){r=e;for(let n=0,s=e.length;n<s;n++){let i=e[n];if(i&&typeof i=="object"){let o=Io(i);o!==i&&r===e&&(r=e.slice(0)),i=o}r[n]=i}return Object.freeze(r)}for(let n in t){r||(r=Object.assign({},e[de]));let s=t[n];if(s&&typeof s=="object")if(s.__op__){let i=fA[s?.__op__];if(i)i(r,n,s);else throw new Error("Invalid CRDT operation "+s.__op__);continue}else s=Io(s);r[n]=s}return r?Object.freeze(r):px.call(e,de)?e[de]:e}function HE(e){let t=e[de];if(t===void 0)return!0;if(e.constructor===Array){if(!t||e[No]||e.length!==t.length)return!0;for(let r=0,n=e.length;r<n;r++){let s=t[r],i=e[r];if(s&&i?.[de]===s){if(HE(i))return!0}else return!0}}else{let r=e[yt];if(r&&!t)return!0;for(let n in r){let s=r[n];if(s&&typeof s=="object"){let i=t[n];if(i&&s[de]===i){if(HE(s))return!0}else return!0}else return!0}}return!1}var gn,yt,BE,px,No,xE,GE,ld=Re(()=>{yn();gn=B(ne());PE();yt=Symbol("own-data");a(jr,"getChanges");a(FE,"assignTrackedAccessors");a(Sx,"trackObject");BE=class{static{a(this,"GenericTrackedObject")}constructor(t){if(t?.[de])throw new Error("Can not track an already tracked object, check for circular references");this[de]=t}};FE(BE,{});a(cd,"collapseData");px=Object.prototype.hasOwnProperty;a(Io,"deepFreeze");a(HE,"hasChanges");No=Symbol.for("has-array-changes"),xE=class extends Array{static{a(this,"TrackedArray")}[No];constructor(t){super(t)}splice(...t){return this[No]=!0,super.splice(...t)}push(...t){return this[No]=!0,super.push(...t)}pop(){return this[No]=!0,super.pop()}unshift(...t){return this[No]=!0,super.unshift(...t)}shift(){return this[No]=!0,super.shift()}};xE.prototype.constructor=Array;GE=class{constructor(t){this.value=t}static{a(this,"Addition")}__op__="add";update(t){return(+t||0)+this.value}}});var Cp={};qe(Cp,{CONTEXT:()=>ye,ID_PROPERTY:()=>Le,IS_COLLECTION:()=>Fn,RECORD_PROPERTY:()=>de,Resource:()=>$t,snake_case:()=>$ne,transformForSelect:()=>kE});function $ne(e){return e[0].toLowerCase()+e.slice(1).replace(/[a-z][A-Z][a-z]/g,t=>t[0]+"_"+t.slice(1))}function Tx(e,t){if(yu=!1,e==="")return null;if(e=e.slice(1),e.indexOf("/")===-1)return e===""?(yu=!0,null):(e.startsWith("$")&&(e=parseInt(e,36)),t.coerceId(decodeURIComponent(e)));let r=e.split("/"),n=new hA;for(let s=0;s<r.length;s++){let i=r[s];if(!i&&s===r.length-1){yu=!0;break}n[s]=t.coerceId(decodeURIComponent(i))}return n}function Zr(e,t){n.reliesOnPrototype=!0;let r=t.hasContent;return n;function n(s,i,o){let c,l,_,u;if(r?(o?(u=i,o=o[ye]||o):i?typeof s=="object"&&s&&(!Array.isArray(s)||typeof s[0]=="object")?(u=s,c=u[this.primaryKey]??null,o=i[ye]||i):u=i:(u=s,c=u[Le]??u[this.primaryKey]??null),c==null&&(_=!0)):i?o=i[ye]||i:s&&typeof s=="object"&&!Array.isArray(s)&&(o=s),c===void 0)if(typeof s=="string")c=s;else if(typeof s=="object"&&s)if(l=s,s[Symbol.iterator]){c=[],_=!0;for(let f of s){if(typeof f=="object"&&f)break;c.push(f)}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,_=!1)))}else{if(typeof(c=s.url)=="string"){let f=c.indexOf("?");if(f>-1){let p=this.parseQuery(c.slice(f+1));l?l=Object.assign(p,l):l=p,c=c.slice(0,f)}let h=this.parsePath(c,o,l);h?.id!==void 0?(h.query&&(l?l=Object.assign(h.query,l):l=h.query),_=h.isCollection,c=h.id):c=h}c===void 0&&(c=s.id??null,c==null&&(_=!0))}else c=s??null,c==null&&(_=!0);o||(o={});let d;if(l?.ensureLoaded!=null||l?.async||_?(d=Object.assign({},t),l?.ensureLoaded!=null&&(d.ensureLoaded=l.ensureLoaded),l?.async&&(d.async=l.async),_&&(d.isCollection=!0)):d=t,o.transaction){let f=this.getResource(c,o,d);return f.then?f.then(E):E(f)}else return Je(o,()=>{let f=this.getResource(c,o,d);return f.then?f.then(E):E(f)},d);function E(f){if(o.authorize){o.authorize=!1;let h=t.type==="read"?f.allowRead(o.user,l,o):t.type==="update"?f.doesExist?.()===!1?f.allowCreate(o.user,u,o):f.allowUpdate(o.user,u,o):t.type==="create"?f.allowCreate(o.user,u,o):f.allowDelete(o.user,l,o);if(h?.then)return h.then(p=>{if(!p)throw new qE(o.user);return typeof u?.then=="function"?u.then(S=>e(f,l,o,S)):e(f,l,o,u)});if(!h)throw new qE(o.user)}return typeof u?.then=="function"?u.then(h=>e(f,l,o,h)):e(f,l,o,u)}a(E,"authorizeActionOnResource")}}function en(e,t){let r=new Ax.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 EA(e,t,r){let n=e[de];if(n){let s=e[yt];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 kE(e,t){let r=t?.propertyResolvers,n=t[ye],s;if(typeof e=="string")return a(function o(c){return c.then?c.then(o):Array.isArray(c)?c.map(o):EA(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=i(EA(l,r,n));for(let d of e)_.push(u(d));return _},"transform");let o=e.forceNulls;return a(function c(l){if(l.then)return l.then(c);if(Array.isArray(l))return l.map(E=>E&&typeof E=="object"?c(E):E);let _={},u=i(EA(l,r,n)),d;for(let E of e){let f=u(E);f===void 0&&o&&(f=null),f?.then?(d||(d=[]),d.push(f.then(h=>_[E.name||E]=h))):_[E.name||E]=f}return d?Promise.all(d).then(()=>_):_},"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 u=r[c.name]?.definition?.tableClass;l=s[c.name]=kE(c.select||c,u)}let _=o(c.name);return l(_)}else return o(c);else return c}}a(i,"handleProperty")}var gx,Rx,Ax,ye,Le,Fn,de,Vne,$t,qE,yu,hA,yn=Re(()=>{gx=require("crypto");Rc();Rx=require("../index"),Ax=B(ne());ld();to();Bf();ye=Symbol.for("context"),Le=Symbol.for("primary-key"),Fn=Symbol("is-collection"),de=Symbol("stored-record"),Vne={json:"application/json",cbor:"application/cbor",msgpack:"application/x-msgpack",csv:"text/csv"},$t=class{static{a(this,"Resource")}static transactions;constructor(t,r){this[Le]=t;let n=r?.[ye];this[ye]=n!==void 0?n:r||null}static get=Zr(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 _=kE(l,t.constructor);return typeof c?.map=="function"?c.map(_):_(c)}return c}},{type:"read",letItLinger:!0,ensureLoaded:!0,async:!0});static put=Zr(function(t,r,n,s){if(Array.isArray(s)&&t[Fn]){let i=[],o=n.authorize;for(let c of s){let l=t.constructor,_=l.getResource(c[l.primaryKey],n,{async:!0});_.then?i.push(_.then(u=>u.put(c,n))):i.push(_.put(c,n))}return Promise.all(i)}return t.put?t.put(s,r):en(t,"put")},{hasContent:!0,type:"update"});static patch=Zr(function(t,r,n,s){return t.patch?t.patch(s,r):en(t,"patch")},{hasContent:!0,type:"update"});static delete=Zr(function(t,r,n,s){return t.delete?t.delete(r):en(t,"delete")},{hasContent:!1,type:"delete"});static getNewId(){return(0,gx.randomUUID)()}static create(t,r,n){let s;return t==null?s=this.getNewId():Array.isArray(t)&&typeof t[0]!="object"?s=[...t,this.getNewId()]:typeof t!="object"?s=[t,this.getNewId()]:(s=this.getNewId(),n=r,r=t),n||(n={}),Je(n,()=>{let i=new this(s,n),o=i.update?i.update(r,!0):en(i,"update");return n.newLocation=s,n.createdResource=!0,o?.then?o.then(()=>s):s})}static invalidate=Zr(function(t,r,n,s){return t.invalidate?t.invalidate(r):en(t,"delete")},{hasContent:!1,type:"update"});static post=Zr(function(t,r,n,s){return t[Le]!=null&&t.update?.(),t.post(s,r)},{hasContent:!0,type:"create"});static connect=Zr(function(t,r,n,s){return t.connect?t.connect(s,r):en(t,"connect")},{hasContent:!0,type:"read"});static subscribe=Zr(function(t,r,n,s){return t.subscribe?t.subscribe(r):en(t,"subscribe")},{type:"read"});static publish=Zr(function(t,r,n,s){return t[Le]!=null&&t.update?.(),t.publish?t.publish(s,r):en(t,"publish")},{hasContent:!0,type:"create"});static search=Zr(function(t,r,n,s){let i=t.search?t.search(r):en(t,"search"),o=n.select;if(o&&n.hasOwnProperty("select")&&i!=null&&!i.selectApplied){let c=kE(o,t.constructor);return i.map(c)}return i},{type:"read"});static query=Zr(function(t,r,n,s){return t.search?t.search(s,r):en(t,"search")},{hasContent:!0,type:"read"});static copy=Zr(function(t,r,n,s){return t.copy?t.copy(s,r):en(t,"copy")},{type:"create"});static move=Zr(function(t,r,n,s){return t.move?t.move(s,r):en(t,"move")},{type:"delete"});post(t){if(this[Fn])return this.constructor.create(this[Le],t,this[ye]);en(this,"post")}static isCollection(t){return t?.[Fn]}static coerceId(t){return t}static parseQuery(t){return vf(t)}static parsePath(t,r,n){let s=t.indexOf(".");if(s>-1){let o=t.slice(s+1);t=t.slice(0,s);let c=r?.headers&&Vne[o];if(c)r.headers.set("accept",c);else if(n)n.property=o;else return{query:{property:o},id:Tx(t,this),isCollection:yu}}let i=Tx(t,this);return yu?{id:i,isCollection:!0}:i}static getResource(t,r,n){let s,i=r[ye],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 _=l.asMap.get(t);if(s=_?.find(u=>u.constructor===c),s)return s;_||l.asMap.set(t,_=[]),_.push(s=new c(t,i))}else{if(s=l.find(_=>_[Le]===t&&_.constructor===c),s)return s;if(l.push(s=new c(t,i)),l.length>10){let _=new Map;for(let u of l){let d=u[Le],E=_.get(d);E?E.push(u):_.set(d,[u])}i.resourceCache.length=0,i.resourceCache.asMap=_}}}else s=new c(t,i);return o&&(s[Fn]=!0),s}subscribe(t){return new bn}connect(t){return t?.subscribe!==!1?this.subscribe?.(t):new bn}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[Le]}getContext(){return this[ye]}};$t.prototype[ye]=null;(0,Rx._assignPackageExport)("Resource",$t);a($ne,"snake_case");qE=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(Tx,"pathToId");hA=class extends Array{static{a(this,"MulitPartId")}toString(){return this.join("/")}};a(Zr,"transactional");a(en,"missingMethod");a(EA,"selectFromObject");a(kE,"transformForSelect")});function yx(e,t,r,n,s){let i=e.primaryStore.env.path,o=e.primaryStore.tableId,c;s?.crossThreads===!1?(c=bx,Yne(e.primaryStore,e.auditStore)):(c=Ox,e.primaryStore.env.hasSubscriptionCommitListener||(e.primaryStore.env.hasSubscriptionCommitListener=!0,e.primaryStore.on("committed",()=>{Nx(Ox[i])})));let l=c[i]||(c[i]=[]);l.auditStore=e.auditStore,l.lastTxnTime==null&&(l.lastTxnTime=Date.now());let _=l[o];_||(_=l[o]=new Map,_.envs=l,_.tableId=o,_.store=e.primaryStore),t=Ra(t);let u=new pA(r);u.startTime=n;let d=_.get(t);return d?d.push(u):(_.set(t,d=[u]),d.tables=_,d.key=t),u.subscriptions=d,u}function Nx(e){if(!e)return;let t=e.auditStore;try{t.resetReadTxn()}catch(n){throw n.message+=" in "+path,n}let r;for(let{key:n,value:s}of t.getRange({start:e.lastTxnTime,exclusiveStart:!0})){e.lastTxnTime=n;let i=vt(s),o=e[i.tableId];if(!o)continue;let c=i.recordId,l,_=Ra(i.recordId),u=0;do{let d=o.get(_);if(d){for(let f of d)if(!(u>0&&!(f.includeDescendants&&!(f.onlyChildren&&u>1)))){if(f.startTime>=n){(0,mA.info)("omitting",c,f.startTime,n);continue}try{let h;f.supportsTransactions&&f.txnInProgress!==i.version&&(h=!0,f.txnInProgress||(r?r.push(f):r=[f]),f.txnInProgress=i.version),f.listener(c,i,n,h)}catch(h){console.error(h),(0,mA.info)(h)}}}if(_==null)break;let E=_.lastIndexOf?.("/",_.length-2);E>-1?_=_.slice(0,E):_=null,u++}while(!0)}if(r)for(let n of r)n.txnInProgress=null,n.listener(null,{type:"end_txn"},e.lastTxnTime,!0)}function Yne(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=bx[s];if(!l)return;let _=a(()=>{r.threadLocalWrites||(r.threadLocalWrites=new Float64Array(r.getUserSharedBuffer("last-thread-local-write",new ArrayBuffer(8)))),l.txnTime=r.threadLocalWrites[0]||Date.now(),Nx(l),r.threadLocalWrites[0]=l.lastTxnTime,r.unlock("thread-local-writes")},"acquiredLock");r.attemptLock("thread-local-writes",_)&&_()})}}var mA,Ox,bx,pA,Ix=Re(()=>{mA=B(K());Rc();Bl();Zs();Ox=Object.create(null),bx=Object.create(null);a(yx,"addSubscription");pA=class extends bn{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,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(Nx,"notifyFromTransactionData");a(Yne,"listenToCommits")});var Jg={};qe(Jg,{coerceType:()=>VE,makeTable:()=>KE,setServerUtilities:()=>ese,updateResource:()=>$E});function KE(e){let{primaryKey:t,indices:r,tableId:n,tableName:s,primaryStore:i,databasePath:o,databaseName:c,auditStore:l,schemaDefined:_,dbisDB:u,sealed:d}=e,{expirationMS:E,evictionMS:f,audit:h,trackDeletes:p}=e,{attributes:S}=e;S||(S=[]);let T=am(i,n,l),R=0,b,C,H={},v=Promise.resolve(),q,M,Q;for(let Y of S)(Y.assignCreatedTime||Y.name==="__createdtime__")&&(q=Y),(Y.assignUpdatedTime||Y.name==="__updatedtime__")&&(M=Y),Y.expiresAt&&(Q=Y),Y.isPrimaryKey&&(H=Y);let J,X=[],ae=[],ce=1,ge=2,Ge={},Ne={},ve=864e5,Ku,Wu,Ws,VA=!1,fh,Eh,UG=i.getRange({start:!1,end:!1}).constructor,vG=10,BG=6;h&&KA();class Qe extends $t{static name=s;static primaryStore=i;static auditStore=l;static primaryKey=t;static tableName=s;static indices=r;static audit=h;static databasePath=o;static databaseName=c;static attributes=S;static expirationTimer;static createdTimeProperty=q;static updatedTimeProperty=M;static propertyResolvers;static sources=[];static get expirationMS(){return E}static dbisDB=u;static schemaDefined=_;static sourcedFrom(m,A){A&&(this.sourceOptions=A,(A.expiration||A.eviction||A.scanInterval)&&this.setTTLExpiration(A)),A?.intermediateSource?(m.intermediateSource=!0,this.sources.unshift(m)):this.sources.push(m),C=m.get&&(!m.get.reliesOnPrototype||m.prototype.get);let w=a(L=>{let N=this.sources.slice(0,-1);if(N=N.filter(P=>P[L]&&(!P[L].reliesOnPrototype||P.prototype[L])),N.length>0)if(N.length===1){let P=N[0];return(k,D,x)=>{if(k?.source!==P)return P[L](D,x,k)}}else return(P,k,D)=>{let x=[];for(let G of N){if(P?.source===G)break;x.push(G[L](k,D,P))}return Promise.all(x)}},"getApplyToIntermediateSource"),y=this.sources[this.sources.length-1],O=a(L=>{if(y[L]&&(!y[L].reliesOnPrototype||y.prototype[L]))return(N,P,k)=>{if(!N?.source)return y[L](P,k,N)}},"getApplyToCanonicalSource");return Ge={put:O("put"),patch:O("patch"),delete:O("delete"),publish:O("publish")},Ne={put:w("put"),patch:w("patch"),delete:w("delete"),publish:w("publish"),invalidate:w("invalidate")},(async()=>{let L=!1,N=a(async(P,k)=>{let D=P.value,x=P.table?ot[c][P.table]:Qe;if(c===kn.SYSTEM_SCHEMA_NAME&&(P.table===kn.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME||P.table===kn.SYSTEM_TABLE_NAMES.USER_TABLE_NAME)&&(L=!0),P.id===void 0&&(P.id=D[x.primaryKey],P.id===void 0))throw new Error("Replication message without an id "+JSON.stringify(P));P.source=m;let G=await x.getResource(P.id,k,Za);switch(P.type){case"put":return G._writeUpdate(D,!0,Za);case"patch":return G._writeUpdate(D,!1,Za);case"delete":return G._writeDelete(Za);case"publish":return G._writePublish(D,Za);case"invalidate":return G.invalidate(Za);default:rt.error("Unknown operation",P.type,P.id)}},"writeUpdate");try{let P=m.subscribe;P&&p==null&&(p=!0);let k=m.subscribeOnThisThread?m.subscribeOnThisThread((0,Co.getWorkerIndex)()):(0,Co.getWorkerIndex)()===0,D=P&&k&&await m.subscribe?.({crossThreads:!1,inTransactionUpdates:!0,supportsTransactions:!0,omitCurrent:!0});if(D){let x;for await(let G of D)try{if(!(G.type==="transaction"?G.writes[0]:G)){rt.error("Bad subscription event",G);continue}if(G.source=m,x)if(G.beginTxn)x.resolve();else{N(G,x);continue}if(G.type==="end_txn")continue;let me=Je(G,()=>{if(G.type==="transaction"){let ee=[];for(let Pe of G.writes)try{ee.push(N(Pe,G))}catch(le){throw le.message+=" writing "+JSON.stringify(Pe)+" of event "+JSON.stringify(G),le}return Promise.all(ee)}else if(G.type==="define_schema"){let ee=this.attributes.slice(0),Pe;for(let le of G.attributes)ee.find(Fe=>Fe.name===le.name)||(ee.push(le),Pe=!0);Pe&&(ft({table:s,database:c,attributes:ee,origin:"cluster"}),Mu.signalSchemaChange(new Pu.SchemaEventMsg(process.pid,kn.OPERATIONS_ENUM.CREATE_TABLE,c,s)))}else return G.beginTxn?(x=G,N(G,G),new Promise(ee=>{x.resolve=ee})):N(G,G)});L&&(await me,Mu.signalUserChange(new Pu.UserEventMsg(process.pid))),G.onCommit&&(me?.then?me.then(G.onCommit):G.onCommit())}catch(se){rt.error("error in subscription handler",se)}}}catch(P){rt.error(P)}})(),this}static getResource(m,A,w){let y=super.getResource(m,A,w);if(m!=null){oc(m);try{if(y.hasOwnProperty(de))return y;if(typeof m=="object"&&m&&!Array.isArray(m))throw new Error(`Invalid id ${JSON.stringify(m)}`);let O=!w?.async||i.cache?.get(m),L=An(A),N=L.getReadTxn();if(N?.isDone)throw new Error("You can not read from a transaction that has already been committed/aborted");return hh(m,A,{transaction:N},O,P=>{if(P?$E(y,P):y[de]=null,A.onlyIfCached&&A.noCacheStore){if(!y.doesExist())throw new tn.ServerError("Entry is not cached",504)}else if(w?.ensureLoaded){let k=mh(m,P,A,y);if(k)return L?.disregardReadTxn(),y[SA]=!0,gA(k,D=>($E(y,D),y))}return y})}catch(O){throw O.message.includes("Unable to serialize object")&&(O.message+=": "+JSON.stringify(m)),O}}return y}ensureLoaded(){let m=mh(this[Le],this[Dr],this[ye]);if(m)return this[SA]=!0,gA(m,A=>{this[Dr]=A,this[de]=A.value,this[Du]=A.version})}static setTTLExpiration(m){if(typeof m=="number")E=m*1e3,f||(f=0);else if(m&&typeof m=="object")E=m.expiration*1e3,f=(m.eviction||0)*1e3,ve=m.scanInterval*1e3;else throw new Error("Invalid expiration value type");if(E<0)throw new Error("Expiration can not be negative");ve=ve||(E+f)/4,Sh()}static enableAuditing(m=!0){h=m,m&&KA(),Qe.audit=m}static coerceId(m){return m===""?null:VE(m,H)}static async dropTable(){if(delete ot[c][s],c===o){for(let m of S)u.remove(Qe.tableName+"/"+m.name),r[m.name]?.drop();u.remove(Qe.tableName+"/"),i.drop(),await u.committed}else console.log("legacy dropTable"),await i.close(),await fs.remove(data_path),await fs.remove(data_path===standard_path?data_path+MDB_LOCK_FILE_SUFFIX:path.join(path.dirname(data_path),MDB_LEGACY_LOCK_FILE_NAME));Mu.signalSchemaChange(new Pu.SchemaEventMsg(process.pid,kn.OPERATIONS_ENUM.DROP_TABLE,c,s))}get(m){if(typeof m=="string")return this.getProperty(m);if(this[Fn])return this.search(m);if(this[Le]===null){if(m?.conditions)return this.search(m);let A=Qe.getRecordCount();return{recordCount:A.recordCount,estimatedRecordRange:A.estimatedRange,records:"./",name:s,database:c,attributes:S}}if(m?.property)return this.getProperty(m.property);if(this.doesExist()||m?.ensureLoaded===!1||this[ye]?.returnNonexistent)return this}allowRead(m,A){let w=zu(m);if(w?.read){if(w.isSuperUser)return!0;let y=w.attribute_permissions,O=A?.select;if(y?.length>0||VA&&O){if(A||(A={}),O){let L=y?.length>0&&TA(y,"read");A.select=O.map(N=>{let P=N.name||N;if(!L||L[P]){let k=Ws[P]?.definition?.tableClass;if(k){if(N.name||(N={name:N}),!k.prototype.allowRead.call(null,m,N))return!1;if(!N.select)return N.name}return N}}).filter(Boolean)}else A.select=y.filter(L=>L.read&&!Ws[L.attribute_name]).map(L=>L.attribute_name);return A}else return!0}}allowUpdate(m,A){let w=zu(m);if(w?.update){let y=w.attribute_permissions;if(y?.length>0){let O=TA(y,"update");for(let L in A)if(!O[L])return!1;for(let L of y){let N=L.attribute_name;!L.update&&!(N in A)&&(A[N]=this.getProperty(N))}}return!0}}allowCreate(m,A){if(this[Fn]){let w=zu(m);if(w?.insert){let y=w.attribute_permissions;if(y?.length>0){let O=TA(y,"insert");for(let L in A)if(!O[L])return!1}else return!0}}else return this.allowUpdate(m,{})}allowDelete(m){return zu(m)?.delete}update(m,A){if(!An(this[ye]))throw new Error("Can not update a table resource outside of a transaction");if(m===!1)return this;let y;return typeof m=="object"&&m&&(A?(Object.isFrozen(m)&&(m=Object.assign({},m)),this[de]={},this[yt]=m):(y=this[yt],y&&(m=Object.assign(y,m)),this[yt]=y=m)),this._writeUpdate(this[yt],A),this}addTo(m,A){if(typeof A=="number"||typeof A=="bigint")this[Nu]===Cx?this.set(m,(+this.getProperty(m)||0)+A):(this[Nu]||this.update(),this.set(m,new GE(A)));else throw new Error("Can not add a non-numeric value")}subtractFrom(m,A){if(typeof A=="number")return this.addTo(m,-A);throw new Error("Can not subtract a non-numeric value")}getMetadata(){return this[Dr]}invalidate(m){let A=this[ye],w=this[Le];oc(w),An(this[ye]).addWrite({key:w,store:i,invalidated:!0,entry:this[Dr],nodeName:this[ye]?.nodeName,before:Ge.invalidate?.bind(this,A,w),beforeIntermediate:Ne.invalidate?.bind(this,A,w),commit:(O,L)=>{if(L?.version>O)return;let N=null;for(let P in r)N||(N={}),N[P]=this.getProperty(P);T(w,N,this[Dr],O,Iu,h,this[ye],0,"invalidate")}})}static evict(m,A,w){let y=this.Source,O;if(!((C||h)&&(!A||(O=i.getEntry(m),!O||!A)||O.version!==w))){if(C){if(i.hasLock(m,O.version))return;let L;for(let N in r)L||(L={}),L[N]=A[N];if(L)return T(m,L,O,w,wu,null,null,0,null,!0)}return i.ifVersion(m,w,()=>{Qu(m,A,null)}),h?T(m,null,O,w,wu,null,null,0,null,!0):i.remove(m,w)}}lock(){throw new Error("Not yet implemented")}static operation(m,A){return m.table||=s,m.schema||=c,vx.operation(m,A)}put(m){this.update(m,!0)}patch(m){this.update(m,!1)}_writeUpdate(m,A,w){let y=this[ye],O=An(y),L=this[Le];oc(L);let N=this[Dr];this[Nu]=A?Cx:Xne;let P={key:L,store:i,entry:N,nodeName:y?.nodeName,validate:k=>{m||(m=this[yt]),A||m&&HE(this[yt]===m?this:m)?y?.source||(O.checkOverloaded(),this.validate(m,!A),M&&(m[M.name]=M.type==="Date"?new Date(k):M.type==="String"?new Date(k).toISOString():k),A&&(t&&m[t]!==L&&(m[t]=L),q&&(N?.value?m[q.name]=N?.value[q.name]:m[q.name]=q.type==="Date"?new Date(k):q.type==="String"?new Date(k).toISOString():k),m=Io(m))):O.removeWrite(P)},before:A?Ge.put?()=>Ge.put(y,L,m):null:Ge.patch?()=>Ge.patch(y,L,m):Ge.put?()=>Ge.put(y,L,Io(this)):null,beforeIntermediate:A?Ne.put?()=>Ne.put(y,L,m):null:Ne.patch?()=>Ne.patch(y,L,m):Ne.put?()=>Ne.put(y,L,Io(this)):null,commit:(k,D,x)=>{if(x){if(y&&D?.version>(y.lastModified||0)&&(y.lastModified=D.version),this[Dr]=D,D?.value?.[de])throw new Error("Can not assign a record to a record, check for circular references");A||(this[de]=D?.value??null)}this[yt]=void 0,this[Du]=k;let G=D?.value,se=m;if(this[Nu]=0,D?.version>=k)if(h){let le=D.localTime,Fe=D.version;for(;se&&(le>k||Fe>=k&&le>0);){let re=l.get(le);if(!re)break;let j=vt(re);if(Fe=j.version,Fe>k){if(j.type==="patch"){let pe=j.getValue(i);se=vE(se,pe)}else if(j.type==="put"||j.type==="delete")return}else if(Fe===k)return;le=j.previousLocalTime}}else{if(A)return;se=vE(se,G)}let me;if(A?me=se:(this[de]=G,me=A?se:Io(this,se)),this[de]=me,me?.[de])throw new Error("Can not assign a record to a record, check for circular references");let ee;A||(ee=m),Qu(L,G,me);let Pe=A?"put":"patch";T(L,me,D,k,0,h,y,y.expiresAt||(E?E+Date.now():0),Pe,!1,ee)}};O.addWrite(P)}async delete(m){if(typeof m=="string")return this.deleteProperty(m);if(this[Fn]){for await(let A of this.search(m))(await Qe.getResource(A[t],this.getContext(),{ensureLoaded:!1}))._writeDelete(m);return}return this[de]?this._writeDelete(m):!1}_writeDelete(m){let A=An(this[ye]),w=this[Le];oc(w);let y=this[ye];return A.addWrite({key:w,store:i,resource:this,nodeName:y?.nodeName,before:Ge.delete?.bind(this,y,w),beforeIntermediate:Ne.delete?.bind(this,y,w),commit:(O,L,N)=>{let P=L?.value;N&&(y&&L?.version>(y.lastModified||0)&&(y.lastModified=L.version),$E(this,L)),!(L?.version>O)&&(Qu(this[Le],P),rt.trace("Write delete entry",w,O),h||p?(T(w,null,this[Dr],O,0,h,this[ye],0,"delete"),h||Sh()):i.remove(this[Le]))}}),!0}search(m){let A=this[ye],w=An(A);if(!m)throw new Error("No query provided");let y=m.conditions;y?y.length===void 0&&(y=y[Symbol.iterator]?Array.from(y):[y]):y=Array.isArray(m)?m:m[Symbol.iterator]?Array.from(m):[],this[Le]&&(y=[{attribute:null,comparator:"prefix",value:this[Le]}].concat(y));let O,L={};function N(j,pe){let Be;switch(pe){case"and":case void 0:if(j.length<1)throw new Error('An "and" operator requires at least one condition');Be=!0;break;case"or":if(j.length<2)throw new Error('An "or" operator requires at least two conditions');break;default:throw new Error("Invalid operator "+pe)}let $n=Be&&{},Qs;for(let Ye of j){if(Ye.conditions){Ye.conditions=N(Ye.conditions,Ye.operator);continue}let kt=Ye[0]??Ye.attribute,sn=kt==null?H:xs(S,kt);if(sn){if(Be){let Yn=Bn(kt),Vt=$n[Yn];Vt?(Vt.push(Ye),Qs=!0):$n[Yn]=[Ye]}(sn.type||Ag[Ye.comparator])&&(Ye[1]===void 0?Ye.value=k(Ye.value,sn):Ye[1]=k(Ye[1],sn))}else if(kt!=null)throw(0,tn.handleHDBError)(new Error,`${kt} is not a defined attribute`,404)}if(m.enforceExecutionOrder)return j;if(Qs)for(let Ye in $n){let kt=$n[Ye],sn=kt.length;if(sn>1)for(let Yn=0;Yn<sn;Yn++){let Vt=kt[Yn];if(Vt.comparator==="ge"||Vt.comparator==="greater_than_equal")for(let zs=0;zs<sn;zs++){let Ho=kt[zs];(Ho.comparator==="le"||Ho.comparator==="less_than_equal")&&(Vt.comparator="between",Vt.value=[Vt.value,Ho.value],j.splice(j.indexOf(Ho),1))}if(Vt.comparator==="equals"||!Vt.comparator){for(let zs=0;zs<sn;zs++)if(zs!==Yn){let Ho=kt[zs];j.splice(j.indexOf(Ho),1)}break}}}return j}a(N,"prepareConditions");function P(j,pe){if(m.enforceExecutionOrder)return j;for(let Be of j)Be.conditions&&(Be.conditions=P(Be.conditions,Be.operator));return j.length>1&&pe!=="or"?(0,Ux.sortBy)(j,Uf(Qe)):j}a(P,"orderConditions");function k(j,pe){return Array.isArray(j)?j.map(Be=>VE(Be,pe)):VE(j,pe)}a(k,"coerceTypedValues");let D=m.operator;(y.length>0||D)&&(y=N(y,D));let x=typeof m.sort=="object"&&m.sort,G;if(x&&D!=="or"){let j=x.attribute;if(O=y.find(pe=>Bn(pe.attribute)===Bn(j)),!O){let pe=xs(S,j);if(!pe)throw(0,tn.handleHDBError)(new Error,`${Array.isArray(j)?j.join("."):j} is not a defined attribute`,404);if(pe.indexed)O={attribute:j,comparator:"sort"},y.push(O);else if(y.length===0&&!m.allowFullScan)throw(0,tn.handleHDBError)(new Error,`${Array.isArray(j)?j.join("."):j} is not indexed and not combined with any other conditions`,404)}O&&(O.descending=!!x.descending)}y=P(y,D),x&&(O&&y[0]===O?x.next&&(G={dbOrderedAttribute:x.attribute,attribute:x.next.attribute,descending:x.next.descending,next:x.next.next}):(O&&y.splice(y.indexOf(O),1),G=x));let se=m.select;if(y.length===0&&(y=[{attribute:t,comparator:"greater_than",value:!0}]),m.explain)return{conditions:y,operator:D,postOrdering:G,selectApplied:!!se};let me=w.useReadTxn(),ee=Og(y,D,Qe,me,m,A,(j,pe)=>$A(j,se,A,me,pe),L),Pe=m.ensureLoaded!==!1;G||(ee=re(ee));let le=Qe.transformEntryForSelect(se,A,me,L,Pe,!0),Fe=Qe.transformToOrderedSelect(ee,se,G,me,A,le);function re(j){return m.offset||m.limit!==void 0?j.slice(m.offset,m.limit!==void 0?(m.offset||0)+m.limit:void 0):j}return a(re,"applyOffset"),G&&(Fe=re(Fe)),Fe.onDone=()=>{Fe.onDone=null,w.doneReadTxn()},Fe.selectApplied=!0,Fe.getColumns=()=>{if(se){let j=[];for(let pe of se)pe==="*"?j.push(...S.map(Be=>Be.name)):j.push(pe.name||pe);return j}return S.map(j=>j.name)},Fe}static transformToOrderedSelect(m,A,w,y,O,L){let N=new UG;if(w){m=$A(m,A,y,O,null);let P;N.iterate=function(){let D,x=m[Symbol.asyncIterator]?m[Symbol.asyncIterator]():m[Symbol.iterator](),G,se=w.dbOrderedAttribute,me,ee,Pe=!0;function le(re){let j=re.next&&le(re.next),pe=re.descending;return(Be,$n)=>{let Qs=ph(Be,re.attribute,y),Ye=ph($n,re.attribute,y),kt=pe?(0,Do.compareKeys)(Ye,Qs):(0,Do.compareKeys)(Qs,Ye);return kt===0?j?.(Be,$n)||0:kt}}a(le,"createComparator");let Fe=le(w);return{async next(){let re;if(D)if(re=D.next(),re.done){if(G)return N.onDone&&N.onDone(),re}else return{value:await L.call(this,re.value)};P=[],me&&P.push(me);do if(re=await x.next(),re.done){if(G=!0,P.length)break;return N.onDone&&N.onDone(),re}else{let j=re.value;if(j?.then&&(j=await j),se){let pe=ph(j,se,y);if(Pe)Pe=!1,ee=pe;else if(pe!==ee){ee=pe,me=j;break}}P.push(j)}while(!0);return w.isGrouped,P.sort(Fe),D=P[Symbol.iterator](),re=D.next(),re.done?(N.onDone&&N.onDone(),re):{value:await L.call(this,re.value)}},return(){N.onDone&&N.onDone(),x.return()},throw(){N.onDone&&N.onDone(),x.throw()}}};let k=a(D=>{if(typeof A=="object"&&Array.isArray(D.attribute))for(let x=0;x<A.length;x++){let G=A[x],se;if(G.name===D.attribute[0]){for(se=G.sort||(G.sort={});se.next;)se=se.next;se.attribute=D.attribute.slice(1),se.descending=D.descending}else G===D.attribute[0]&&(A[x]=se={name:G,sort:{attribute:D.attribute.slice(1),descending:D.descending}})}D.next&&k(D.next)},"applySortingOnSelect");k(w)}else N.iterate=(m[Symbol.asyncIterator]||m[Symbol.iterator]).bind(m),N=N.map(L);return N}static transformEntryForSelect(m,A,w,y,O,L){if(m&&(m===t||m?.length===1&&m[0]===t)){let D=a(x=>(A?.transaction?.stale&&(A.transaction.stale=!1),x?.key??x),"transform");return m===t?D:m.asArray?x=>[D(x)]:x=>({[t]:D(x)})}let N;O&&C&&!m?.every(D=>{let x;return typeof D=="object"?x=D.name:x=D,r[x]||x===t})&&(N=!0);let P,k=a(function(D){let x;if(A?.transaction?.stale&&(A.transaction.stale=!1),D!=null){if(fh=D,x=D.value||D.deref?.(),!x&&(D.key===void 0||D.deref)){if(D=hh(D.key??D,A,{transaction:w,lazy:m?.length<4},this.isSync,G=>G),D?.then)return D.then(k.bind(this));x=D?.value}if(N&&(D.metadataFlags&(Iu|wu)||D.expiresAt&&D.expiresAt<Date.now())){let G=mh(D.key??D,D,A);if(G?.then)return G.then(k)}}if(x==null)return L?wo.SKIP:x;if(m&&!(m[0]==="*"&&m.length===1)){let G,se=a((ee,Pe)=>{let le;typeof ee=="object"?le=ee.name:le=ee;let Fe=Ws?.[le],re;if(Fe){let j=y?.[le];if(j)if(j.hasMappings){let Be=Fe.from?x[Fe.from]:Bn(D.key);re=j.get(Be),re||(re=[])}else re=j.fromRecord?.(x);else re=Fe(x,A,D);let pe=a(Be=>{if(Be&&typeof Be=="object"){let $n=Fe.definition?.tableClass||Qe;P||(P={});let Qs=P[le]||(P[le]=$n.transformEntryForSelect(le===ee?null:ee.select||(Array.isArray(ee)?ee:null),A,w,j,O));if(Array.isArray(Be)){let Ye=[],kt=$n.transformToOrderedSelect(Be,ee.select,typeof ee.sort=="object"&&ee.sort,A,w,Qs)[this.isSync?Symbol.iterator:Symbol.asyncIterator](),sn=a(Vt=>{for(;!Vt.done;){if(Vt?.then)return Vt.then(sn);Ye.push(Vt.value),Vt=kt.next()}Pe(Ye,le)},"nextValue"),Yn=sn(kt.next());Yn&&(G||(G=[]),G.push(Yn));return}else if(Be=Qs.call(this,Be),Be?.then){G||(G=[]),G.push(Be.then(Ye=>Pe(Ye,le)));return}}Pe(Be,le)},"handleResolvedValue");re?.then?(G||(G=[]),G.push(re.then(pe))):pe(re);return}else re=x[le],re&&typeof re=="object"&&le!==ee&&(re=Qe.transformEntryForSelect(ee.select||ee,A,w,null)({value:re}));Pe(re,le)},"selectAttribute"),me;if(typeof m=="string")se(m,ee=>{me=ee});else if(Array.isArray(m))if(m.asArray)me=[],m.forEach((ee,Pe)=>{ee==="*"?m[Pe]=x:se(ee,le=>me[Pe]=le)});else{me={};let ee=m.forceNulls;for(let Pe of m)if(Pe==="*")for(let le in x)me[le]=x[le];else se(Pe,(le,Fe)=>{le===void 0&&ee&&(le=null),me[Fe]=le})}else throw new tn.ClientError("Invalid select"+m);return G?Promise.all(G).then(()=>me):me}return x},"transform");return k}async subscribe(m){if(!l)throw new Error("Can not subscribe to a table without an audit log");h||ft({table:s,database:c,schemaDefined:_,attributes:S,audit:!0}),m||(m={});let A=!m.rawEvents,w=yx(Qe,this[Le]??null,function(N,P,k,D){try{let x=P.getValue?.(i,A);if(!x&&P.type==="patch"&&A){let G=i.getEntry(N);G?.version===P.version?x=G.value:x=P.getValue?.(i,!0,k),P.type="put"}this.send({id:N,timestamp:k,value:x,version:P.version,type:P.type,beginTxn:D})}catch(x){rt.error(x)}},m.startTime||0,m);this[Fn]&&(w.includeDescendants=!0,m.onlyChildren&&(w.onlyChildren=!0)),m.supportsTransactions&&(w.supportsTransactions=!0);let y=this[Le],O=m.previousCount;O>1e3&&(O=1e3);let L=m.startTime;if(this[Fn]){if(L){if(O)throw new tn.ClientError("startTime and previousCount can not be combined for a table level subscription");for(let{key:N,value:P}of l.getRange({start:L,exclusiveStart:!0})){let k=vt(P);if(k.tableId!==n)continue;let D=k.recordId;if(y==null||Mx(y,D)){let x=k.getValue(i,A,N);w.send({id:D,timestamp:N,value:x,version:k.version,type:k.type})}w.startTime=N}}else if(O){let N=[];for(let{key:P,value:k}of l.getRange({start:"z",end:!1,reverse:!0}))try{let D=vt(k);if(D.tableId!==n)continue;let x=D.recordId;if(y==null||Mx(y,x)){let G=D.getValue(i,A,P);if(N.push({id:x,timestamp:P,value:G,version:D.version,type:D.type}),--O<=0)break}}catch(D){rt.error("Error getting history entry",P,D)}for(let P=N.length;P>0;)w.send(N[--P]);N[0]&&(w.startTime=N[0].timestamp)}else if(!m.omitCurrent)for(let{key:N,value:P,version:k,localTime:D}of i.getRange({start:y??!1,end:y==null?void 0:[y,Do.MAXIMUM_KEY],versions:!0}))P&&w.send({id:N,timestamp:D,value:P,version:k,type:"put"})}else{O&&!L&&(L=0);let N=this[Dr]?.localTime;if(N===om&&(i.cache?.delete(y),this[Dr]=i.getEntry(y),rt.trace("re-retrieved record",N,this[Dr]?.localTime),N=this[Dr]?.localTime),rt.trace("Subscription from",L,"from",y,N),L<N){let P=[],k=N;do{let D=l.get(k);if(D){m.omitCurrent=!0;let x=vt(D),G=x.getValue(i,A,k);A&&(x.type="put"),P.push({id:y,value:G,timestamp:k,...x}),k=x.previousLocalTime}else break;O&&O--}while(k>L&&O!==0);for(let D=P.length;D>0;)w.send(P[--D]);w.startTime=N}!m.omitCurrent&&this.doesExist()&&w.send({id:y,timestamp:N,value:this[de],version:this[Du],type:"put"})}return m.listener&&w.on("data",m.listener),w}doesExist(){return!!(this[de]||this[Nu])}publish(m,A){this._writePublish(m,A)}_writePublish(m,A){let w=An(this[ye]),y=this[Le]||null;oc(y);let O=this[ye];w.addWrite({key:y,store:i,entry:this[Dr],nodeName:O?.nodeName,validate:()=>{O?.source||(w.checkOverloaded(),this.validate(m))},before:Ge.publish?.bind(this,O,y,m),beforeIntermediate:Ne.publish?.bind(this,O,y,m),commit:(L,N,P)=>{N===void 0&&p&&!h&&Sh(),T(y,N?.value??null,N,N?.version||L,0,!0,O,N?.expiresAt,"message",!1,m)}})}validate(m,A){let w,y=a((O,L,N)=>{if(L.type&&O!=null)if(A&&O.__op__&&(O=O.value),L.properties){typeof O!="object"&&(w||(w=[])).push(`Value ${qn(O)} in property ${N} must be an object${L.type?" ("+L.type+")":""}`);let P=L.properties;for(let k=0,D=P.length;k<D;k++){let x=P[k],G=y(O[x.name],x,N+"."+x.name);G&&(O[x.name]=G)}if(L.sealed&&O!=null&&typeof O=="object")for(let k in O)P.find(D=>D.name===k)||(w||(w=[])).push(`Property ${k} is not allowed within object in property ${N}`)}else switch(L.type){case"Int":(typeof O!="number"||O>>0!==O)&&(w||(w=[])).push(`Value ${qn(O)} in property ${N} must be an integer (from -2147483648 to 2147483647)`);break;case"Long":(typeof O!="number"||!(Math.floor(O)===O&&Math.abs(O)<=9007199254740992))&&(w||(w=[])).push(`Value ${qn(O)} in property ${N} must be an integer (from -9007199254740992 to 9007199254740992)`);break;case"Float":typeof O!="number"&&(w||(w=[])).push(`Value ${qn(O)} in property ${N} must be a number`);break;case"ID":typeof O=="string"||O?.length>0&&O.every?.(P=>typeof P=="string")||(w||(w=[])).push(`Value ${qn(O)} in property ${N} must be a string, or an array of strings`);break;case"String":typeof O!="string"&&(w||(w=[])).push(`Value ${qn(O)} in property ${N} must be a string`);break;case"Boolean":typeof O!="boolean"&&(w||(w=[])).push(`Value ${qn(O)} in property ${N} must be a boolean`);break;case"Date":if(!(O instanceof Date)){if(typeof O=="string"||typeof O=="number")return new Date(O);(w||(w=[])).push(`Value ${qn(O)} in property ${N} must be a Date`)}break;case"BigInt":if(typeof O!="bigint"){if(typeof O=="string"||typeof O=="number")return BigInt(O);(w||(w=[])).push(`Value ${qn(O)} in property ${N} must be a bigint`)}break;case"Bytes":O instanceof Uint8Array||(w||(w=[])).push(`Value ${qn(O)} in property ${N} must be a Buffer or Uint8Array`);break;case"array":if(Array.isArray(O)){if(L.elements)for(let P=0,k=O.length;P<k;P++){let D=O[P],x=y(D,L.elements,N+"[*]");x&&(O[P]=x)}}else(w||(w=[])).push(`Value ${qn(O)} in property ${N} must be a Buffer or Uint8Array`);break}L.nullable===!1&&O==null&&(w||(w=[])).push(`Property ${N} is required (and not does not allow null values)`)},"validateValue");for(let O=0,L=S.length;O<L;O++){let N=S[O];if(!N.relationship&&(!A||N.name in m)){let P=y(m[N.name],N,N.name);P&&(m[N.name]=P)}}if(d)for(let O in m)S.find(L=>L.name===O)||(w||(w=[])).push(`Property ${O} is not allowed`);if(w)throw new tn.ClientError(w.join(". "))}getUpdatedTime(){return this[Du]}wasLoadedFromSource(){return C?!!this[SA]:void 0}static async addAttributes(m){let A=S.slice(0);for(let w of m){if(!w.name)throw new tn.ClientError("Attribute name is required");if(w.name.match(/[`/]/))throw new tn.ClientError("Attribute names cannot include backticks or forward slashes");A.push(w)}return ft({table:s,database:c,schemaDefined:_,attributes:A}),Qe.indexingOperation}static async removeAttributes(m){let A=S.filter(w=>!m.includes(w.name));return ft({table:s,database:c,schemaDefined:_,attributes:A}),Qe.indexingOperation}static getRecordCount(m){let A=i.getStats().entryCount,w=5e3,y=1e3,O;A>w&&!m?.exactCount&&(O=y);let L=0;for(let{value:N}of i.getRange({start:!0,lazy:!0,limit:O}))N!=null&&L++;if(O){let N=L;L=0;for(let{value:Pe}of i.getRange({start:"\uFFFF",reverse:!0,lazy:!0,limit:O}))Pe!=null&&L++;let P=O*2,k=(L+N)/P,D=Math.pow((L-N+1)/O/2,2)+k*(1-k)/P,x=Math.max(Math.sqrt(D)*A,1),G=Math.round(k*A),se=Math.max(G-1.96*x,0),me=Math.min(G+1.96*x,A),ee=Math.pow(10,Math.round(Math.log10(x)));return ee>G&&(ee=ee/10),L=Math.round(G/ee)*ee,{recordCount:L,estimatedRange:[Math.round(se),Math.round(me)]}}return{recordCount:L}}static updatedAttributes(){Ws=this.propertyResolvers={$id:(m,A,w)=>({value:w.key}),$updatedtime:(m,A,w)=>w.version,$record:(m,A,w)=>w?{value:m}:m};for(let m of this.attributes){m.resolve=null;let A=m.relationship;if(A)if(m.indexed&&console.error("A relationship property can not be directly indexed, (but you may want to index the foreign key attribute)"),VA=!0,A.to)m.elements?.definition?(Ws[m.name]=m.resolve=(w,y,O)=>{let L=w[A.from?A.from:t],N=m.elements.definition.tableClass;return O?Ma({attribute:A.to,value:L},An(y).getReadTxn(),!1,N,!1).asArray:N.search([{attribute:A.to,value:L}],y).asArray},m.set=()=>{throw new Error("Setting a one-to-many relationship property is not supported")},m.resolve.definition=m.elements.definition,A.from&&(m.resolve.from=A.from)):console.error(`The one-to-many/many-to-many relationship property "${m.name}" in table "${s}" must have an array type referencing a table as the elements`);else if(A.from){let w=m.definition||m.elements?.definition;w?(Ws[m.name]=m.resolve=(y,O,L)=>{let N=y[A.from];if(N!==void 0){if(m.elements){let P,k=N.map(D=>{let x=L?w.tableClass.primaryStore.getEntry(D,{transaction:An(O).getReadTxn()}):w.tableClass.get(D,O);return x?.then&&(P=!0),x});return A.filterMissing?P?Promise.all(k).then(D=>D.filter(Px)):k.filter(Px):P?Promise.all(k):k}return L?w.tableClass.primaryStore.getEntry(N,{transaction:An(O).getReadTxn()}):w.tableClass.get(N,O)}},m.set=(y,O)=>{if(Array.isArray(O)){let L=O.map(N=>N[Le]||N[w.tableClass.primaryKey]);y[A.from]=L}else{let L=O[Le]||O[w.tableClass.primaryKey];y[A.from]=L}},m.resolve.definition=m.definition||m.elements?.definition,m.resolve.from=A.from):console.error(`The relationship property "${m.name}" in table "${s}" must be a type that references a table`)}else console.error(`The relationship directive on "${m.name}" in table "${s}" must use either "from" or "to" arguments`)}FE(this,this)}static async deleteHistory(m=0){let A;for(let{key:w,value:y}of l.getRange({start:0,end:m}))await Cu(),vt(y).tableId===n&&(A=l.remove(w));await A}static async*getHistory(m=0,A=1/0){for(let{key:w,value:y}of l.getRange({start:m,end:A})){await Cu();let O=vt(y);O.tableId===n&&(yield{id:O.recordId,localTime:w,version:O.version,type:O.type,value:O.getValue(i,!0,w),user:O.user})}}static async getHistoryOfRecord(m){let A=[];if(m==null)throw new Error("An id is required");let w=i.getEntry(m);if(!w)return A;let y=w.localTime;if(!y)throw new Error("The entry does not have a local audit time");let O=0;do{await Cu();let L=l.get(y);if(L){let N=vt(L);A.push({id:N.recordId,localTime:y,version:N.version,type:N.type,value:N.getValue(i,!0,y),user:N.user}),y=N.previousLocalTime}else break}while(O<1e3&&y);return A.reverse()}static cleanup(){J?.remove()}}Qe.updatedAttributes();let HG=Qe.prototype;return HG[Jne]=!0,E&&Qe.setTTLExpiration(E/1e3),Q&&xG(),Qe;function Qu(Y,m,A){let w;for(let y in r){let O=r[y],L=O.isIndexing,N=A?.[y],P=m?.[y];if(N===P&&!L)continue;w=!0;let k=O.indexNulls,D=(0,Lu.getIndexedValues)(N,k),x=(0,Lu.getIndexedValues)(P,k);if(x?.length>0){let G=new Set(x);if(D=D?D.filter(se=>{if(G.has(se))G.delete(se);else return!0}):[],x=Array.from(G),(x.length>0||D.length>0)&&wx){let se=x.concat(D).map(me=>({key:me,value:Y}));O.prefetch(se,Lx)}for(let se=0,me=x.length;se<me;se++)O.remove(x[se],Y)}else D?.length>0&&wx&&O.prefetch(D.map(G=>({key:G,value:Y})),Lx);if(D)for(let G=0,se=D.length;G<se;G++)O.put(D[G],Y)}return w}a(Qu,"updateIndices");function oc(Y){switch(typeof Y){case"number":return!0;case"string":if(Y.length<659)return!0;if(Y.length>Dx)throw new Error("Primary key size is too large: "+Y.length);break;case"object":if(Y===null)return!0;break;case"bigint":if(Y<2n**64n&&Y>-(2n**64n))return!0;break;default:throw new Error("Invalid primary key type: "+typeof Y)}if((0,Do.writeKey)(Y,jne,0)>Dx)throw new Error("Primary key size is too large: "+Y.length);return!0}a(oc,"checkValidId");function hh(Y,m,A,w,y){let O=a(()=>{if(m?.transaction?.stale&&(m.transaction.stale=!1),A.transaction?.isDone)return y(null,Y);let L=i.getEntry(Y,A);return L&&m&&(L?.version>(m.lastModified||0)&&(m.lastModified=L.version),L?.localTime&&!m.lastRefreshed&&(m.lastRefreshed=L.localTime)),y(L,Y)},"whenPrefetched");return w?O():ce>0?(ce--,O()):new Promise((L,N)=>{ce===0?(ce--,i.prefetch([Y],()=>{P(),k()})):(X.push(Y),ae.push(k),X.length>BG&&(ce--,P()));function P(){if(X.length>0){let D=ae;i.prefetch(X,()=>{ce===-1?P():ce++;for(let x of D)x()}),X=[],ae=[],ge>2&&ge--}else ce=ge,ge<vG&&ge++}a(P,"prefetch");function k(){try{L(O())}catch(D){N(D)}}a(k,"load")})}a(hh,"loadLocalRecord");function zu(Y){if(!Y?.role)return;let m=Y.role.permission;if(m.super_user)return Zne;let A=m[c],w,y=A?.tables;if(y)return y[s];if(c==="data"&&(w=m[s])&&!w.tables)return w}a(zu,"getTablePermissions");function mh(Y,m,A,w){if(C){let y;if(A.noCache?y=!0:(m?(!m.value||m.metadataFlags&(Iu|wu)||m.expiresAt&&m.expiresAt<Date.now())&&(y=!0):y=!0,Jr(!y,"cache-hit",s)),y){let O=YA(Y,m,A).then(L=>(L?.value?.[de]&&rt.error("Can not assign a record with a record property"),A&&(L?.version>(A.lastModified||0)&&(A.lastModified=L.version),A.lastRefreshed=Date.now()),L));if(A?.onlyIfCached||m?.value&&w?.allowStaleWhileRevalidate?.(m,Y)){if(O.catch(L=>rt.warn(L)),A?.onlyIfCached&&!w.doesExist())throw new tn.ServerError("Entry is not cached",504);return}else return O}}}a(mh,"ensureLoadedFromSource");function An(Y){let m=Y?.transaction;if(m){if(!m.lmdbDb)return m.lmdbDb=i,m;do{if(m.lmdbDb?.path===i.path)return m;let A=m.next;if(!A)return m=m.next=new eo,m.lmdbDb=i,m;m=A}while(!0)}else return new od}a(An,"txnForContext");function ph(Y,m,A){if(!Y)return;fh=Y;let w=Y.value||Y.deref?.()||(fh=i.getEntry(Y.key))?.value;if(typeof m=="object"){let O=Ws,L=w;for(let N=0,P=m.length;N<P;N++){let k=m[N],D=O?.[k];L=D&&L?D(L,A,!0)?.value:L?.[k],O=D?.definition?.tableClass?.propertyResolvers}return L}let y=Ws[m];return y?y(w,A):w[m]}a(ph,"getAttributeValue");function $A(Y,m,A,w,y){let O=y?.length,L={transaction:w,lazy:O>0||typeof m=="string"||m?.length<4,alwaysPrefetch:!0},N;function P(k,D){let x=k?.value;if(!x)return wo.SKIP;for(let G=0;G<O;G++)if(!N?.includes(G)&&!y[G](x,k))return wo.SKIP;return D!==void 0&&(k.key=D),k}if(a(P,"processEntry"),O>0||!Y.hasEntries){let k=Y.map(D=>{if(N=null,typeof D=="object"&&D?.key!==void 0)return O>0?P(D):D;if(D==null)return wo.SKIP;for(let x=0;x<O;x++){let se=y[x].idFilter;if(se){if(!se(D))return wo.SKIP;N||(N=[]),N.push(x)}}return hh(D,A,L,!1,P)});return Array.isArray(Y)&&(k=k.filter(D=>D!==wo.SKIP)),k.hasEntries=!0,k}return Y}a($A,"transformToEntries");async function YA(Y,m,A){let w=m?.metadataFlags,y=m?.version,O,L;if(!i.attemptLock(Y,y,()=>{clearTimeout(L);let D=i.getEntry(Y);!D||!D.value||D.metadataFlags&(Iu|wu)?O(YA(Y,i.getEntry(Y),A)):O(D)}))return new Promise(D=>{O=D,L=setTimeout(()=>{i.unlock(Y,y)},zne)});let N=m?.value,P={requestContext:A,replacingRecord:N,replacingVersion:y,noCacheStore:!1,source:null,resourceCache:A?.resourceCache},k=A?.responseHeaders;return new Promise((D,x)=>{let G;gA(Je(P,async se=>{let me=performance.now(),ee,Pe,le;try{for(let pe of Qe.sources)if(pe.get&&(!pe.get.reliesOnPrototype||pe.prototype.get)&&(P.source=pe,ee=await pe.get(Y,P),ee))break;le=w&Iu;let re=P.lastModified||le&&y;Pe=le||re>y||!N,re||(re=(0,Lu.getNextMonotonicTime)());let j=performance.now()-me;if(wr(j,"cache-resolution",s),k&&kT(k,"Server-Timing",`cache-resolve;dur=${j.toFixed(2)}`,!0),se.timestamp=re,E&&!P.expiresAt&&(P.expiresAt=Date.now()+E),ee){if(typeof ee!="object")throw new Error("Only objects can be cached and stored in tables");typeof ee.toJSON=="function"&&(ee=ee.toJSON()),t&&ee[t]!==Y&&(ee[t]=Y)}G=!0,D({version:re,value:ee})}catch(re){re.message+=` while resolving record ${Y} for ${s}`,N&&((re.code==="ECONNRESET"||re.code==="ECONNREFUSED"||re.code==="EAI_AGAIN")&&!A?.mustRevalidate||A?.staleIfError&&(re.statusCode===500||re.statusCode===502||re.statusCode===503||re.statusCode===504))?(D({version:y,value:N}),rt.trace(re.message,"(returned stale record)")):x(re),P.transaction.abort();return}if(A?.noCacheStore||P.noCacheStore){P.transaction.abort();return}An(P).addWrite({key:Y,store:i,entry:m,nodeName:"source",commit:(re,j)=>{if(j?.version!==y)return;let pe=Qu(Y,N,ee);ee?(Ne.put?.(P,Y,ee),T(Y,ee,j,re,0,h&&Pe||null,P,P.expiresAt,"put",!!le)):(Ne.delete?.(P,Y),h||p?T(Y,null,j,re,0,h&&Pe||null,P,0,"delete",!!le):i.remove(Y,y))}})}),()=>{i.unlock(Y,y)},se=>{i.unlock(Y,y),G&&rt.error("Error committing cache update",se)})})}a(YA,"getFromSource");function Sh(){if(ve!==Ku&&(Ku=ve,(0,Co.getWorkerIndex)()===(0,Co.getWorkerCount)()-1)){if(Wu&&clearTimeout(Wu),!ve)return;let Y=new Date;Y.setMonth(0),Y.setDate(1),Y.setHours(0),Y.setMinutes(0),Y.setSeconds(0);let m=Math.ceil((Date.now()-Y.getTime())/ve)*ve+Y.getTime(),A=a(w=>{rt.trace(`Scheduled next cleanup scan at ${new Date(w)}ms`),Wu=setTimeout(()=>v=v.then(async()=>{if(A(Math.max(w+ve,Date.now())),i.rootStore.status!=="open"){clearTimeout(Wu);return}let y=50,O=new Array(y),L=0;rt.trace(`Starting cleanup scan for ${s}`);try{let N=0;for(let{key:P,value:k,version:D,expiresAt:x}of i.getRange({start:!1,snapshot:!1,versions:!0,lazy:!0})){let G;k===null&&!h&&D+Qne<Date.now()?G=i.remove(P,D):x&&x+f<Date.now()&&(G=Qe.evict(P,k,D),N++),G&&(await O[L],O[L]=G.catch(se=>{rt.error("Cleanup error",se)}),++L>=y&&(L=0)),await Cu()}rt.trace(`Finished cleanup scan for ${s}, evicted ${N} entries`)}catch(N){rt.trace(`Error in cleanup scan for ${s}:`,N)}}),Math.min(w-Date.now(),2147483647)).unref()},"startNextTimer");A(m)}}a(Sh,"scheduleCleanup");function KA(){J=l?.addDeleteRemovalCallback(n,Y=>{let m=i.getEntry(Y);m?.value===null&&i.remove(Y,m.version)})}a(KA,"addDeleteRemoval");function xG(){(0,Co.getWorkerIndex)()===0&&setInterval(async()=>{if(!Eh){Eh=!0;try{let Y=Q.name,m=r[Y];if(!m)throw new Error(`expiresAt attribute ${Q} must be indexed`);for(let A of m.getRange({start:!0,values:!1,end:Date.now(),snapshot:!1})){for(let w of m.getValues(A)){let y=i.getEntry(w);y?.value?y.value[Y]<Date.now()&&Qe.evict(w,y.value,y.version):i.ifVersion(w,y?.version,()=>m.remove(A,w))}await Cu()}}catch(Y){rt.error("Error in evicting old records",Y)}finally{Eh=!1}}},Wne).unref()}a(xG,"runRecordExpirationEviction")}function TA(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 Lx(){}function ese(e){vx=e}function VE(e,t){let r=t?.type;return e===null?e:e===""&&r&&r!=="String"&&r!=="Any"?null:r==="Int"||r==="Long"?e==="null"?null:parseInt(e):r==="Float"?e==="null"?null:parseFloat(e):r==="BigInt"?e==="null"?null:BigInt(e):r==="Boolean"?e==="true"?!0:e==="false"?!1:e:r==="Date"?isNaN(e)?e==="null"?null:(tse.test(e)||(e+="Z"),new Date(e)):new Date(+e):!r||r==="Any"?(0,YE.autoCast)(e):e}function Mx(e,t){if(e==null)return!0;if(!Array.isArray(t))return e===t;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 gA(e,t,r){return e?.then?e.then(t,r):t(e)}function $E(e,t){e[Dr]=t,e[de]=t?.value??null,e[Du]=t?.version}function Px(e){return e!=null}function qn(e){try{return JSON.stringify(e)}catch{return e}}var kn,wo,Lu,Ux,Uu,tn,Mu,Pu,rt,Do,Co,YE,Kne,vx,Wne,Qne,wx,zne,Du,Jne,Dr,Nu,Cx,Xne,SA,Za,Iu,wu,jne,Dx,Zne,bpe,tse,Cu,Jf=Re(()=>{kn=B(U()),wo=require("lmdb"),Lu=B(vr()),Ux=require("lodash");yn();Xp();Uu=B(te());Ix();tn=B(ne()),Mu=B(As()),Pu=B(Ln());Ae();Bf();rt=B(K());ld();to();Do=require("ordered-binary"),Co=B(it());Zs();YE=B(z());wc();Bs();PE();Hl();Kne=new Uint8Array(9);Kne[8]=192;Wne=6e4,Qne=864e5;Uu.initSync();wx=Uu.get(kn.CONFIG_PARAMS.STORAGE_PREFETCHWRITES),zne=1e4,Du=Symbol.for("version"),Jne=Symbol.for("incremental-update"),Dr=Symbol("entry"),Nu=Symbol("is-saving"),Cx=1,Xne=2,SA=Symbol("loaded-from-source"),Za={isNotification:!0,ensureLoaded:!1},Iu=1,wu=8,jne=Buffer.allocUnsafeSlow(8192),Dx=1978,Zne={read:!0,insert:!0,update:!0,delete:!0,isSuperUser:!0},bpe=(0,YE.convertToMS)(Uu.get(kn.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE))||864e5;a(KE,"makeTable");a(TA,"attributesAsObject");a(Lx,"noop");a(ese,"setServerUtilities");tse=/[+-][0-9]{2}:[0-9]{2}|[a-zA-Z]$/;a(VE,"coerceType");a(Mx,"isDescendantId");Cu=a(()=>new Promise(setImmediate),"rest");a(gA,"when");a($E,"updateResource");a(Px,"exists");a(qn,"stringify")});var ke={};qe(ke,{database:()=>sa,databases:()=>ot,dropDatabase:()=>rS,dropTableMeta:()=>ose,getDatabases:()=>mr,getDefaultCompression:()=>ef,getTables:()=>rse,onUpdatedTable:()=>CR,readMetaDb:()=>vu,resetDatabases:()=>Cl,table:()=>ft,tables:()=>Br});function rse(){return XE||mr(),Br||{}}function mr(){if(XE)return ot;XE=!0,rc=new Map;let e=(0,pt.getHdbBasePath)()&&(0,nt.join)((0,pt.getHdbBasePath)(),Ut.DATABASES_DIR_NAME),t=(0,pt.get)(Ut.CONFIG_PARAMS.DATABASES)||{};if(process.env.SCHEMAS_DATA_PATH&&(t.data={path:process.env.SCHEMAS_DATA_PATH}),e=process.env.STORAGE_PATH||(0,pt.get)(Ut.CONFIG_PARAMS.STORAGE_PATH)||e&&((0,rn.existsSync)(e)?e:(0,nt.join)((0,pt.getHdbBasePath)(),Ut.LEGACY_DATABASES_DIR_NAME)),!!e){if((0,rn.existsSync)(e))for(let r of(0,rn.readdirSync)(e,{withFileTypes:!0})){let n=(0,nt.basename)(r.name,".mdb");r.isFile()&&(0,nt.extname)(r.name).toLowerCase()===".mdb"&&!t[n]?.path&&vu((0,nt.join)(e,r.name),null,n)}if((0,rn.existsSync)((0,tc.getBaseSchemaPath)())){for(let r of(0,rn.readdirSync)((0,tc.getBaseSchemaPath)(),{withFileTypes:!0}))if(!r.isFile()){let n=(0,nt.join)((0,tc.getBaseSchemaPath)(),r.name),s=(0,nt.join)((0,tc.getTransactionAuditStoreBasePath)(),r.name);for(let i of(0,rn.readdirSync)(n,{withFileTypes:!0}))if(i.isFile()&&(0,nt.extname)(i.name).toLowerCase()===".mdb"){let o=(0,nt.join)(s,i.name);vu((0,nt.join)(n,i.name),(0,nt.basename)(i.name,".mdb"),r.name,o,!0)}}}if(t)for(let r in t){let n=t[r],s=n.path;if((0,rn.existsSync)(s))for(let o of(0,rn.readdirSync)(s,{withFileTypes:!0}))o.isFile()&&(0,nt.extname)(o.name).toLowerCase()===".mdb"&&vu((0,nt.join)(s,o.name),(0,nt.basename)(o.name,".mdb"),r);let i=n.tables;if(i)for(let o in i){let c=i[o],l=(0,nt.join)(c.path,(0,nt.basename)(o+".mdb"));(0,rn.existsSync)(l)&&vu(l,o,r,null,!0)}}for(let r in ot){let n=rc.get(r);if(n){let s=ot[r];r.includes("delete")&&Rn.trace(`defined tables ${Array.from(n.keys())}`);for(let i in s)n.has(i)||(Rn.trace(`delete table class ${i}`),delete s[i])}else if(delete ot[r],r==="data"){for(let s in Br)delete Br[s];delete Br[jE]}}return rc=null,ot}}function Cl(){XE=!1;for(let[,e]of Mi)e.needsDeletion=!0;mr();for(let[e,t]of Mi)t.needsDeletion&&!e.endsWith("system.mdb")&&(t.close(),Mi.delete(e));return ot}function vu(e,t,r=OA,n,s){let i=new RA.default(e,!1);try{let o=Mi.get(e);o?o.needsDeletion=!1:(o=(0,QE.open)(i),Mi.set(e,o));let c=new Lo.default(!1),l=o.dbisDb||(o.dbisDb=o.openDB(WE.INTERNAL_DBIS_NAME,c)),_=o.auditStore;_||(n?(0,rn.existsSync)(n)&&(i.path=n,_=(0,QE.open)(i),_.isLegacy=!0):_=ME(o));let u=Gx(r),d=u[jE],E=new Map;for(let{key:f,value:h}of l.getRange({start:!1})){let[p,S]=f.toString().split("/");S===""?S=h.name:S||(S=p,p=t,h.name||(h.name=S,h.indexed=!h.is_hash_attribute)),d?.add(p);let T=E.get(p);T||E.set(p,T={attributes:[]}),(S==null||h.is_hash_attribute)&&(T.primary=h),S!=null&&T.attributes.push(h),Object.defineProperty(h,"key",{value:f,configurable:!0})}for(let[f,h]of E){let{attributes:p,primary:S}=h;if(!S){for(let X of p)if(X.is_hash_attribute||X.isPrimaryKey){S=X;break}if(!S){Rn.fatal(`Unable to find a primary key attribute on table ${f}, with attributes: ${JSON.stringify(p)}`);continue}}let T=u[f],R={},b=[],C,H,v=typeof S.audit=="boolean"?S.audit:(0,pt.get)(Ut.CONFIG_PARAMS.LOGGING_AUDITLOG),q=S.trackDeletes,M=S.expiration,Q=S.eviction,J=S.sealed;if(T)R=T.indices,b=T.attributes,T.schemaVersion++;else{C=S.tableId,C?C>=(l.get(ec)||0)&&l.putSync(ec,C+1):(S.tableId=C=l.get(ec),C||(C=1),l.putSync(ec,C+1),l.putSync(S.key,S));let X=new Lo.default(!S.is_hash_attribute,S.is_hash_attribute);if(X.compression=S.compression,X.compression){let ae=(0,pt.get)(Ut.CONFIG_PARAMS.STORAGE_COMPRESSION_THRESHOLD)||xx;X.compression.threshold=ae}H=E_(o.openDB(S.key,X)),H.rootStore=o,H.tableId=C}for(let X of p){X.attribute=X.name;try{if(!X.is_hash_attribute&&(X.indexed||X.attribute&&!X.name)){if(!R[X.name]){let ce=new Lo.default(!X.is_hash_attribute,X.is_hash_attribute);R[X.name]=o.openDB(X.key,ce),R[X.name].indexNulls=X.indexNulls}let ae=b.find(ce=>ce.name===X.name);ae?b.splice(b.indexOf(ae),1,X):b.push(X)}}catch(ae){Rn.error("Error trying to update attribute",X,b,R,ae)}}if(!T){T=Fx(u,f,KE({primaryStore:H,auditStore:_,audit:v,sealed:J,expirationMS:M&&M*1e3,evictionMS:Q&&Q*1e3,trackDeletes:q,tableName:f,tableId:C,primaryKey:S.name,databasePath:s?r+"/"+f:r,databaseName:r,indices:R,attributes:p,schemaDefined:S.schemaDefined,dbisDB:l})),T.schemaVersion=1;for(let X of bA)X(T)}}return o}catch(o){throw o.message+=` opening database ${e}`,o}}function Gx(e){let t=ot[e];if(t||(e==="data"?t=ot[e]=Br:e==="system"?Object.defineProperty(ot,"system",{value:t=Object.create(null),configurable:!0}):t=ot[e]=Object.create(null)),rc&&!rc.has(e)){let r=new Set;t[jE]=r,rc.set(e,r)}return t}function Fx(e,t,r){return e[t]=r,r}function sa({database:e,table:t}){e||(e=OA),mr();let r=Gx(e),n=(0,nt.join)((0,pt.getHdbBasePath)(),Ut.DATABASES_DIR_NAME),s=(0,pt.get)(Ut.CONFIG_PARAMS.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,pt.get)(Ut.CONFIG_PARAMS.STORAGE_PATH)||((0,rn.existsSync)(n)?n:(0,nt.join)((0,pt.getHdbBasePath)(),Ut.LEGACY_DATABASES_DIR_NAME));let o=(0,nt.join)(n,(i?t:e)+".mdb"),c=Mi.get(o);if(!c){let l=new RA.default(o,!1);c=(0,QE.open)(l),Mi.set(o,c)}return c}async function rS(e){if(!ot[e])throw new Error("Schema does not exist");let t=ot[e],r;for(let n in t)r=t[n].primaryStore.rootStore,Mi.delete(r.path),r.status==="open"&&(await r.close(),await Bu.remove(r.path));if(r||(r=sa({database:e,table:null}),r.status==="open"&&(await r.close(),await Bu.remove(r.path))),e==="data"){for(let n in Br)delete Br[n];delete Br[jE]}delete ot[e]}function ft({table:e,database:t,expiration:r,eviction:n,scanInterval:s,attributes:i,audit:o,sealed:c,trackDeletes:l,schemaDefined:_,origin:u}){t||(t=OA);let d=sa({database:t,table:e}),E=ot[t],f=E?.[e];if(d.status==="closed")throw new Error(`Can not use a closed data store for ${e}`);let h,p,S,T;_==null&&(_=!0);let R=new Lo.default(!1);for(let M of i)M.attribute&&!M.name?(M.name=M.attribute,M.indexed=!0):M.attribute=M.name,M.expiresAt&&(M.indexed=!0);let b,C;if(f){if(h=f.primaryKey,f.primaryStore.rootStore.status==="closed")throw new Error(`Can not use a closed data store from ${e} class`);f.attributes.splice(0,f.attributes.length,...i)}else{let M=d.auditStore;M||(M=ME(d)),p=i.find(ae=>ae.isPrimaryKey)||{},h=p.name,p.is_hash_attribute=!0,p.schemaDefined=_,p.compression=ef(),l&&(p.trackDeletes=!0),o=p.audit=typeof o=="boolean"?o:(0,pt.get)(Ut.CONFIG_PARAMS.LOGGING_AUDITLOG),r&&(p.expiration=r),n&&(p.eviction=n),typeof c=="boolean"&&(p.sealed=c),u&&(p.origins?p.origins.includes(u)||p.origins.push(u):p.origins=[u]),Rn.trace(`${e} table loading, opening primary store`);let Q=new Lo.default(!1,!0);Q.compression=p.compression;let J=e+"/",X=E_(d.openDB(J,Q));X.rootStore=d,T=d.dbisDb=d.openDB(WE.INTERNAL_DBIS_NAME,R),X.tableId=T.get(ec),X.tableId||(X.tableId=1),T.putSync(ec,X.tableId+1),p.tableId=X.tableId,f=Fx(E,e,KE({primaryStore:X,auditStore:M,audit:o,sealed:c,trackDeletes:l,expirationMS:r&&r*1e3,evictionMS:n&&n*1e3,primaryKey:h,tableName:e,tableId:X.tableId,databasePath:t,databaseName:t,indices:{},attributes:i,schemaDefined:_,dbisDB:T})),f.schemaVersion=1,b=!0,q(),T.put(J,p)}S=f.indices,T=T||(d.dbisDb=d.openDB(WE.INTERNAL_DBIS_NAME,R)),f.dbisDB=T;let H=[];for(let{key:M,value:Q}of T.getRange({start:!0})){let[J,X]=M.toString().split("/");if(X===""&&(X=Q.name),X){if(J!==e)continue}else X=J;if(!i.find(ce=>ce.name===X)?.indexed&&Q.indexed&&!Q.isPrimaryKey){q(),b=!0,T.remove(M);let ce=f.indices[J];ce&&H.push(ce)}}let v=[];try{for(let M of i||[]){if(M.relationship)continue;let Q=e+"/"+(M.name||"");Object.defineProperty(M,"key",{value:Q,configurable:!0});let J=T.get(Q);if(M.isPrimaryKey){if(J=J||T.get(Q=e+"/")||{},o!==f.audit||c!==c||(+r||void 0)!==(+J.expiration||void 0)||(+n||void 0)!==(+J.eviction||void 0)){let ae=Object.assign({},J);typeof o=="boolean"&&(o&&f.enableAuditing(o),ae.audit=o),r&&(ae.expiration=+r),n&&(ae.eviction=+n),c!==void 0&&(ae.sealed=c),b=!0,q(),T.put(Q,ae)}continue}J?.attribute&&!J.name&&(J.indexed=!0);let X=!J||J.type!==M.type||J.indexed!==M.indexed||J.nullable!==M.nullable||JSON.stringify(J.attributes)!==JSON.stringify(M.attributes)||JSON.stringify(J.elements)!==JSON.stringify(M.elements);if(M.indexed){let ae=new Lo.default(!0,!1),ce=d.openDB(Q,ae);(X||J.indexingPID&&J.indexingPID!==process.pid||J.restartNumber<Hu.workerData?.restartNumber)&&(b=!0,q(),J=T.get(Q),(X||J.indexingPID&&J.indexingPID!==process.pid||J.restartNumber<Hu.workerData?.restartNumber)&&(b=!0,M.indexNulls===void 0&&(M.indexNulls=!0),f.primaryStore.getStats().entryCount>0&&(M.lastIndexedKey=J?.lastIndexedKey||!1,M.indexingPID=process.pid,ce.isIndexing=!0,Object.defineProperty(M,"dbi",{value:ce}),v.push(M))),T.put(Q,M)),J?.indexNulls&&M.indexNulls===void 0&&(M.indexNulls=!0),ce.indexNulls=M.indexNulls,S[M.name]=ce}else X&&(b=!0,q(),T.put(Q,M))}}finally{C&&C()}if(b&&(f.schemaVersion++,f.updatedAttributes()),Rn.trace(`${e} table loading, running index`),v.length>0||H.length>0?f.indexingOperation=ise(f,v,H):b&&zE.signalSchemaChange(new JE.SchemaEventMsg(process.pid,"schema-change",f.databaseName,f.tableName)),f.origin=u,b)for(let M of bA)M(f,u!=="cluster");return(r||n||s)&&f.setTTLExpiration({expiration:r,eviction:n,scanInterval:s}),Rn.trace(`${e} table loaded`),f;function q(){C||d.transactionSync(()=>({then(M){C=M}}))}a(q,"startTxn")}async function ise(e,t,r){try{let n=e.schemaVersion;await zE.signalSchemaChange(new JE.SchemaEventMsg(process.pid,"schema-change",e.databaseName,e.tableName));let s;for(let l of r)s=l.drop();let i,o=0,c=t.length;if(await new Promise(l=>setImmediate(l)),c>0){let l=0;for(let{key:_,value:u,version:d}of e.primaryStore.getRange({start:t[0].lastIndexedKey,lazy:c<4,versions:!0,snapshot:!1}))if(u){if(l++,s=e.primaryStore.ifVersion(_,d,()=>{for(let E=0;E<c;E++){let f=t[E],h=f.name,p=(0,Bx.getIndexedValues)(u[h]);if(p)for(let S=0,T=p.length;S<T;S++)f.dbi.put(p[S],_)}}),s.then(()=>l--,E=>{l--,Rn.error(E)}),Hu.workerData&&Hu.workerData.restartNumber!==Hx.restartNumber&&(i=!0),++o%100===0||i){for(let E of t)E.lastIndexedKey=_,e.dbisDB.put(E.key,E);if(i)return}l>nse?await s:l>sse&&await new Promise(E=>setImmediate(E))}for(let _ of t)delete _.lastIndexedKey,delete _.indexingPID,_.dbi.isIndexing=!1,s=e.dbisDB.put(_.key,_)}await s,await zE.signalSchemaChange(new JE.SchemaEventMsg(process.pid,"indexing-finished",e.databaseName,e.tableName))}catch(n){Rn.error("Error in indexing",n)}}function ose({table:e,database:t}){let r=sa({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 CR(e){bA.push(e)}function ef(){let e=(0,pt.get)(Ut.CONFIG_PARAMS.STORAGE_COMPRESSION),t=(0,pt.get)(Ut.CONFIG_PARAMS.STORAGE_COMPRESSION_DICTIONARY),r=(0,pt.get)(Ut.CONFIG_PARAMS.STORAGE_COMPRESSION_THRESHOLD)||xx,n={startingOffset:32};return t&&(n.dictionary=Bu.readFileSync(t)),r&&(n.threshold=r),e&&n}var pt,WE,QE,nt,rn,tc,Lo,RA,Ut,Bu,AA,Bx,zE,JE,Hu,Rn,Hx,OA,jE,xx,Br,ot,ec,bA,XE,Mi,rc,nse,sse,Ae=Re(()=>{pt=B(te()),WE=B(dt()),QE=require("lmdb"),nt=require("path"),rn=require("fs"),tc=B(ze());Jf();Lo=B(Cc()),RA=B(Dc()),Ut=B(U()),Bu=B(require("fs-extra")),AA=require("../index"),Bx=B(vr()),zE=B(As()),JE=B(Ln()),Hu=require("worker_threads"),Rn=B(K()),Hx=B(it());Zs();wc();OA="data",jE=Symbol("defined-tables"),xx=((0,pt.get)(Ut.CONFIG_PARAMS.STORAGE_PAGESIZE)||4096)-60;(0,pt.initSync)();Br=Object.create(null),ot=Object.create(null);(0,AA._assignPackageExport)("databases",ot);(0,AA._assignPackageExport)("tables",Br);ec=Symbol.for("next-table-id"),bA=[],Mi=new Map;a(rse,"getTables");a(mr,"getDatabases");a(Cl,"resetDatabases");a(vu,"readMetaDb");a(Gx,"ensureDB");a(Fx,"setTable");a(sa,"database");a(rS,"dropDatabase");a(ft,"table");nse=1e3,sse=10;a(ise,"runIndexing");a(ose,"dropTableMeta");a(CR,"onUpdatedTable");a(ef,"getDefaultCompression")});var z=g((Ppe,eG)=>{"use strict";var Pi=require("path"),Yx=require("fs-extra"),Lr=K(),qx=require("fs-extra"),ZE=require("os"),ase=require("net"),cse=require("recursive-iterator"),_t=U(),lse=yO(),kx=require("papaparse"),eh=require("moment"),{inspect:use}=require("util"),Vx=require("is-number"),Mpe=require("lodash"),_se=require("minimist"),dse=require("https"),fse=require("http"),{hdb_errors:th}=ne(),Ese=/^((\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)))$/,Kx=require("util").promisify(setTimeout),hse=100,mse=5,pse="",Sse=4,$x={true:!0,TRUE:!0,FALSE:!1,false:!1,undefined:null,null:null,NULL:null,NaN:NaN};eG.exports={isEmpty:nn,isEmptyOrZeroLength:Es,arrayHasEmptyValues:Rse,arrayHasEmptyOrZeroLengthValues:Ase,buildFolderPath:Ose,isBoolean:Wx,errorizeMessage:Tse,stripFileExtension:yse,autoCast:Nse,autoCastJSON:Qx,autoCastJSONDeep:NA,removeDir:Ise,compareVersions:wse,isCompatibleDataVersion:Cse,escapeRawValue:Dse,unescapeValue:Lse,stringifyProps:Mse,timeoutPromise:Use,isClusterOperation:Bse,getClusterUser:xse,checkGlobalSchemaTable:Hse,getHomeDir:Jx,getPropsFilePath:Pse,promisifyPapaParse:Gse,removeBOM:Xx,createEventPromise:Fse,checkProcessRunning:qse,checkSchemaTableExist:kse,checkSchemaExists:jx,checkTableExists:Zx,getStartOfTomorrowInSeconds:Vse,getLimitKey:$se,isObject:bse,isNotEmptyAndHasValue:gse,autoCasterIsNumberCheck:zx,backtickASTSchemaItems:Yse,isPortTaken:vse,createForkArgs:Kse,autoCastBoolean:Wse,async_set_timeout:Kx,getTableHashAttribute:Qse,doesSchemaExist:zse,doesTableExist:Jse,stringifyObj:Xse,ms_to_time:jse,changeExtension:Zse,getEnvCliRootPath:IA,noBootFile:eie,httpRequest:tie,transformReq:rie,convertToMS:nie,PACKAGE_ROOT:_t.PACKAGE_ROOT};function Tse(e){return e instanceof Error?e:new Error(e)}a(Tse,"errorizeMessage");function nn(e){return e==null}a(nn,"isEmpty");function gse(e){return!nn(e)&&(e||e===0||e===""||Wx(e))}a(gse,"isNotEmptyAndHasValue");function Es(e){return nn(e)||e.length===0||e.size===0}a(Es,"isEmptyOrZeroLength");function Rse(e){if(nn(e))return!0;for(let t=0;t<e.length;t++)if(nn(e[t]))return!0;return!1}a(Rse,"arrayHasEmptyValues");function Ase(e){if(Es(e))return!0;for(let t=0;t<e.length;t++)if(Es(e[t]))return!0;return!1}a(Ase,"arrayHasEmptyOrZeroLengthValues");function Ose(...e){try{return e.join(Pi.sep)}catch{console.error(e)}}a(Ose,"buildFolderPath");function Wx(e){return nn(e)?!1:e===!0||e===!1}a(Wx,"isBoolean");function bse(e){return nn(e)?!1:typeof e=="object"}a(bse,"isObject");function yse(e){return Es(e)?pse:e.slice(0,-Sse)}a(yse,"stripFileExtension");function Nse(e){return nn(e)||e===""||typeof e!="string"?e:$x[e]!==void 0?$x[e]:zx(e)===!0?Number(e):Ese.test(e)?new Date(e):e}a(Nse,"autoCast");function Qx(e){if(typeof e=="string"&&(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")))try{return JSON.parse(e)}catch{}return e}a(Qx,"autoCastJSON");function NA(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=NA(n);s!==n&&(e[t]=s)}else for(let t in e){let r=e[t],n=NA(r);n!==r&&(e[t]=n)}return e}else return Qx(e)}a(NA,"autoCastJSONDeep");function zx(e){if(e.startsWith("0.")&&Vx(e))return!0;let t=e.toUpperCase().includes("E");return!!((e!=="0"&&e.startsWith("0"))===!1&&t===!1&&Vx(e))}a(zx,"autoCasterIsNumberCheck");async function Ise(e){if(Es(e))throw new Error(`Directory path: ${e} does not exist`);try{await qx.emptyDir(e),await qx.remove(e)}catch(t){throw Lr.error(`Error removing files in ${e} -- ${t}`),t}}a(Ise,"removeDir");function wse(e,t){if(Es(e)){Lr.info("Invalid current version sent as parameter.");return}if(Es(t)){Lr.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 _=0;_<l;_++)if(r=parseInt(o[_],10)-parseInt(c[_],10),r)return r;return o.length-c.length}a(wse,"compareVersions");function Cse(e,t,r=!1){let n=e.toString().split("."),s=t.toString().split(".");return n[0]===s[0]&&(!r||n[1]===s[1])}a(Cse,"isCompatibleDataVersion");function Dse(e){if(nn(e))return e;let t=String(e);return t==="."?_t.UNICODE_PERIOD:t===".."?_t.UNICODE_PERIOD+_t.UNICODE_PERIOD:t.replace(_t.FORWARD_SLASH_REGEX,_t.UNICODE_FORWARD_SLASH)}a(Dse,"escapeRawValue");function Lse(e){if(nn(e))return e;let t=String(e);return t===_t.UNICODE_PERIOD?".":t===_t.UNICODE_PERIOD+_t.UNICODE_PERIOD?"..":String(e).replace(_t.ESCAPED_FORWARD_SLASH_REGEX,"/")}a(Lse,"unescapeValue");function Mse(e,t){if(nn(e))return Lr.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+ZE.EOL}!Es(n)&&n[0]===";"?r+=" "+n+s+ZE.EOL:Es(n)||(r+=n+"="+s+ZE.EOL)}catch{Lr.error(`Found bad property during upgrade with key ${n} and value: ${s}`)}}),r}a(Mse,"stringifyProps");function Jx(){let e;try{e=ZE.homedir()}catch{e=process.env.HOME}return e||(e="~/"),e}a(Jx,"getHomeDir");function Pse(){let e=Pi.join(Jx(),_t.HDB_HOME_DIR_NAME,_t.BOOT_PROPS_FILE_NAME);return Yx.existsSync(e)||(e=Pi.join(__dirname,"../","hdb_boot_properties.file")),e}a(Pse,"getPropsFilePath");function Use(e,t){let r,n;return n=new Promise(function(s){r=setTimeout(function(){s(t)},e)}),{promise:n,cancel:function(){clearTimeout(r)}}}a(Use,"timeoutPromise");async function vse(e){if(!e)throw new Error("Invalid port passed as parameter");return new Promise((t,r)=>{let n=ase.createServer().once("error",s=>{s.code==="EADDRINUSE"?t(!0):r(s)}).once("listening",()=>n.once("close",()=>t(!1)).close()).listen(e)})}a(vse,"isPortTaken");function Bse(e){try{return _t.CLUSTER_OPERATIONS[e.toLowerCase()]!==void 0}catch(t){Lr.error(`Error checking operation against cluster ops ${t}`)}return!1}a(Bse,"isClusterOperation");function Hse(e,t){let r=(Ae(),ie(ke)).getDatabases();if(!r[e])return th.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e);if(!r[e][t])return th.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(Hse,"checkGlobalSchemaTable");function xse(e,t){if(nn(t)){Lr.warn("No CLUSTERING_USER defined, clustering disabled");return}if(nn(e)||Es(e)){Lr.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){Lr.error(`unable to find cluster_user due to: ${n.message}`);return}if(r===void 0){Lr.warn(`CLUSTERING_USER: ${t} not found or is not active.`);return}return r}a(xse,"getClusterUser");function Gse(){kx.parsePromise=function(e,t,r){return new Promise(function(n,s){kx.parse(e,{header:!0,transformHeader:Xx,chunk:t.bind(null,s),skipEmptyLines:!0,transform:r,dynamicTyping:!1,error:s,complete:n})})}}a(Gse,"promisifyPapaParse");function Xx(e){if(typeof e!="string")throw new TypeError(`Expected a string, got ${typeof e}`);return e.charCodeAt(0)===65279?e.slice(1):e}a(Xx,"removeBOM");function Fse(e,t,r){return new Promise(n=>{t.once(e,s=>{let i=r;Lr.info(`Got cluster status event response: ${use(s)}`);try{i.cancel()}catch{Lr.error("Error trying to cancel timeout.")}n(s)})})}a(Fse,"createEventPromise");async function qse(e){let t=!0,r=0;do await Kx(hse*r++),(await lse.findPs(e)).length>0&&(t=!1);while(t&&r<mse);if(t)throw new Error(`process ${e} was not started`)}a(qse,"checkProcessRunning");function kse(e,t){let r=jx(e);if(r)return r;let n=Zx(e,t);if(n)return n}a(kse,"checkSchemaTableExist");function jx(e){let{getDatabases:t}=(Ae(),ie(ke));if(!t()[e])return th.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}a(jx,"checkSchemaExists");function Zx(e,t){let{getDatabases:r}=(Ae(),ie(ke));if(!r()[e][t])return th.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(Zx,"checkTableExists");function Vse(){let e=eh().utc().add(1,_t.MOMENT_DAYS_TAG).startOf(_t.MOMENT_DAYS_TAG).unix(),t=eh().utc().unix();return e-t}a(Vse,"getStartOfTomorrowInSeconds");function $se(){return eh().utc().format("DD-MM-YYYY")}a($se,"getLimitKey");function Yse(e){try{let t=new cse(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){Lr.error("Got an error back ticking items."),Lr.error(t)}}a(Yse,"backtickASTSchemaItems");function Kse(e){return[e]}a(Kse,"createForkArgs");function Wse(e){return e===!0||typeof e=="string"&&e.toLowerCase()==="true"}a(Wse,"autoCastBoolean");function Qse(e,t){let{getDatabases:r}=(Ae(),ie(ke)),n=r()[e]?.[t];return n?.primaryKey||n?.hash_attribute}a(Qse,"getTableHashAttribute");function zse(e){let{getDatabases:t}=(Ae(),ie(ke));return t()[e]!==void 0}a(zse,"doesSchemaExist");function Jse(e,t){let{getDatabases:r}=(Ae(),ie(ke));return r()[e]?.[t]!==void 0}a(Jse,"doesTableExist");function Xse(e){try{return JSON.stringify(e)}catch{return e}}a(Xse,"stringifyObj");function jse(e){let t=eh.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(jse,"ms_to_time");function Zse(e,t){let r=Pi.basename(e,Pi.extname(e));return Pi.join(Pi.dirname(e),r+t)}a(Zse,"changeExtension");function IA(){if(process.env[_t.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return process.env[_t.CONFIG_PARAMS.ROOTPATH.toUpperCase()];let e=_se(process.argv);if(e[_t.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return e[_t.CONFIG_PARAMS.ROOTPATH.toUpperCase()]}a(IA,"getEnvCliRootPath");var yA;function eie(){if(yA)return yA;let e=IA();if(IA()&&Yx.pathExistsSync(Pi.join(e,_t.HDB_CONFIG_FILE)))return yA=!0,!0}a(eie,"noBootFile");function tie(e,t){let r;return e.protocol==="http:"?r=fse:r=dse,new Promise((n,s)=>{let i=r.request(e,o=>{o.setEncoding("utf8");let c={body:"",headers:o.headers};o.on("data",l=>{c.body+=l}),o.on("end",()=>{n(c)})});i.on("error",o=>{s(o)}),i.write(JSON.stringify(t)),i.end()})}a(tie,"httpRequest");function rie(e){if(!e.schema&&!e.database){e.schema=_t.DEFAULT_DATABASE_NAME;return}e.database&&(e.schema=e.database)}a(rie,"transformReq");function nie(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(nie,"convertToMS")});var te=g((vpe,iG)=>{"use strict";var wA=require("fs-extra"),Mo=require("path"),tG=require("os"),sie=require("properties-reader"),Gu=K(),xu=z(),ue=U(),rh=Er(),iie="Error initializing environment manager",nh="BOOT_PROPS_FILE_PATH",rG=!1,oie={[ue.HDB_SETTINGS_NAMES.INSTALL_USER]:!0,[ue.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY]:!0,[ue.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]:!0,BOOT_PROPS_FILE_PATH:!0},Ks={};iG.exports={BOOT_PROPS_FILE_PATH:nh,getHdbBasePath:aie,setHdbBasePath:cie,get:nG,initSync:uie,setProperty:Me,initTestEnvironment:die,setCloneVar:_ie};function aie(){return Ks[ue.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]}a(aie,"getHdbBasePath");function cie(e){Ks[ue.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=e}a(cie,"setHdbBasePath");function nG(e){let t=rh.getConfigValue(e);return t===void 0?Ks[e]:t}a(nG,"get");function Me(e,t){oie[e]&&(Ks[e]=t),rh.updateConfigObject(e,t)}a(Me,"setProperty");function lie(){let e;try{e=xu.getPropsFilePath(),wA.accessSync(e,wA.constants.F_OK|wA.constants.R_OK),rG=!0;let t=sie(e);return Ks[ue.HDB_SETTINGS_NAMES.INSTALL_USER]=t.get(ue.HDB_SETTINGS_NAMES.INSTALL_USER),Ks[ue.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY]=t.get(ue.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY),Ks[nh]=e,!0}catch{return Gu.trace(`Environment manager found no properties file at ${e}`),!1}}a(lie,"doesPropFileExist");function uie(e=!1){try{(rG||lie()||xu.noBootFile())&&!sG&&(rh.initConfig(e),Ks[ue.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=rh.getConfigValue(ue.HDB_SETTINGS_NAMES.HDB_ROOT_KEY))}catch(t){Gu.error(iie),Gu.error(t),console.error(t),process.exit(1)}}a(uie,"initSync");var sG=!1;function _ie(e){sG=e}a(_ie,"setCloneVar");function die(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=Mo.join(__dirname,"../../","unitTests");Ks[nh]=Mo.join(l,"hdb_boot_properties.file"),Me(ue.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY,Mo.join(l,"settings.test")),Me(ue.HDB_SETTINGS_NAMES.INSTALL_USER,tG.userInfo()?tG.userInfo().username:void 0),Me(ue.HDB_SETTINGS_NAMES.LOG_LEVEL_KEY,"debug"),Me(ue.HDB_SETTINGS_NAMES.LOG_PATH_KEY,Mo.join(l,"envDir","log")),Me(ue.HDB_SETTINGS_NAMES.LOG_DAILY_ROTATE_KEY,!1),Me(ue.HDB_SETTINGS_NAMES.CLUSTERING_ENABLED_KEY,!0),Me(ue.HDB_SETTINGS_NAMES.CLUSTERING_NODE_NAME_KEY,"1231412de213"),Me(ue.HDB_SETTINGS_NAMES.HDB_ROOT_KEY,Mo.join(l,"envDir")),Me(ue.CONFIG_PARAMS.STORAGE_PATH,Mo.join(l,"envDir")),s&&(Me(ue.CONFIG_PARAMS.HTTP_SECUREPORT,nG(ue.CONFIG_PARAMS.HTTP_PORT)),Me(ue.CONFIG_PARAMS.HTTP_PORT,null)),Me(ue.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HTTPS,!!s),Me(ue.HDB_SETTINGS_NAMES.SERVER_PORT_KEY,9925),Me(ue.HDB_SETTINGS_NAMES.CORS_ENABLED_KEY,xu.isEmpty(i)?!1:i),Me(ue.CONFIG_PARAMS.HTTP_CORS,xu.isEmpty(i)?!1:i),Me(ue.HDB_SETTINGS_NAMES.MAX_CUSTOM_FUNCTION_PROCESSES,2),Me(ue.HDB_SETTINGS_NAMES.MAX_HDB_PROCESSES,4),Me(ue.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_PORT_KEY,9926),Me(ue.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_ENABLED_KEY,!0),Me(ue.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY,Mo.resolve(__dirname,"../../unitTests/server/fastifyRoutes/custom_functions")),Me(ue.HDB_SETTINGS_NAMES.LOCAL_STUDIO_ON,xu.isEmpty(c)?!1:c),o&&(Me("CORS_ACCESSLIST",o),Me(ue.CONFIG_PARAMS.HTTP_CORSACCESSLIST,o)),n&&(Me(ue.HDB_SETTINGS_NAMES.SERVER_TIMEOUT_KEY,n),Me(ue.CONFIG_PARAMS.HTTP_TIMEOUT,n)),t&&(Me(ue.HDB_SETTINGS_NAMES.SERVER_KEEP_ALIVE_TIMEOUT_KEY,t),Me(ue.CONFIG_PARAMS.HTTP_KEEPALIVETIMEOUT,t)),r&&(Me(ue.HDB_SETTINGS_NAMES.SERVER_HEADERS_TIMEOUT_KEY,r),Me(ue.CONFIG_PARAMS.HTTP_HEADERSTIMEOUT,r))}catch(t){let r=`Error reading in HDB environment variables from path ${nh}. Please check your boot props and settings files`;Gu.fatal(r),Gu.error(t)}}a(die,"initTestEnvironment")});var wt=g((kpe,AG)=>{"use strict";var qt=te();qt.initSync();var fie=require("fs-extra"),Eie=require("semver"),ku=require("path"),{monotonicFactory:hie}=require("ulidx"),aG=hie(),mie=require("util"),cG=require("child_process"),pie=mie.promisify(cG.exec),Sie=cG.spawn,jt=ct(),Ce=U(),sh=z(),Vn=K(),ih=Rs(),Tie=fd(),Fu=Er(),{broadcast:gie,onMessageByType:Rie,getWorkerIndex:Aie}=it(),{isMainThread:lG}=require("worker_threads"),{Encoder:Oie,decode:MA}=require("msgpackr"),uG=new Oie,{isEmpty:Bo}=sh,_G=un(),Hpe=48*36e11;lG&&Rie(Ce.ITC_EVENT_TYPES.RESTART,()=>{Mr=void 0,vo=void 0});var{connect:bie,StorageType:yie,RetentionPolicy:Nie,AckPolicy:PA,DeliverPolicy:UA,DiscardPolicy:Iie,NatsConnection:xpe,JetStreamManager:Gpe,JetStreamClient:Fpe,StringCodec:qpe,JSONCodec:wie,createInbox:vA,headers:Cie,ErrorCode:oG}=require("nats"),{PACKAGE_ROOT:Die}=U(),Lie=El(),{recordAction:Mie}=(Bs(),ie(su)),dG=wie(),Pie="clustering",Uie=Lie.engines[jt.NATS_SERVER_NAME],vie=ku.join(Die,"dependencies"),LA=ku.join(vie,`${process.platform}-${process.arch}`,jt.NATS_BINARY_NAME),CA,DA,qu,Po,Uo;AG.exports={runCommand:fG,checkNATSServerInstalled:Bie,createConnection:BA,getConnection:Vu,getJetStreamManager:$u,getJetStream:hG,getNATSReferences:hs,getServerList:xie,createLocalStream:HA,listStreams:mG,deleteLocalStream:Gie,getServerConfig:nc,listRemoteStreams:Fie,viewStream:qie,viewStreamIterator:kie,publishToStream:Vie,request:Kie,reloadNATS:xA,reloadNATSHub:Wie,reloadNATSLeaf:Qie,extractServerName:Yie,requestErrorHandler:zie,createLocalTableStream:gG,createTableStreams:jie,purgeTableStream:RG,purgeSchemaTableStreams:Zie,getStreamInfo:eoe,updateLocalStreams:roe,closeConnection:Hie,getJsmServerName:oh,addNatsMsgHeader:pG,clearClientCache:EG,updateRemoteConsumer:Jie,createConsumer:SG,updateConsumerIterator:Xie};async function fG(e,t=void 0){let{stdout:r,stderr:n}=await pie(e,{cwd:t});if(n)throw new Error(n.replace(`
39
+ `))}},25).unref()}o.close?.(()=>{if(Et.get(Yt.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET)&&Nf()==0)try{pG(gG(Et.get(Yt.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET)))}catch{}clearInterval(c),setTimeout(()=>{console.log("forced close server",i,Gm),o.cantCleanupProperly||kr.warn("Had to forcefully exit the thread",Gm),process.exit(0)},5e3).unref()})}if(RG||process.env.DEV_MODE)try{require("inspector").close()}catch(i){kr.info("Could not close debugger",i)}}}).ref();let e;yf&&!rce&&(e=bG()),Promise.resolve(e).then(()=>{Of?.postMessage({type:Yt.ITC_EVENT_TYPES.CHILD_STARTED})})})}a(AG,"startServers");function bG(){let e=[];for(let t in ni){let r=ni[t];if(t.includes?.("/")&&Nf()==0){Wae(t)&&pG(t),e.push(new Promise((o,c)=>{r.listen({path:t},()=>{o(),kr.info("Domain socket listening on "+t)}).on("error",c)}));continue}let n,s=Et.get(Yt.CONFIG_PARAMS.HTTP_THREADRANGE);if(s){let o=typeof s=="string"?s.split("-"):s,c=Nf();if(c<o[0]||c>o[1])continue}let i;try{let o=t.lastIndexOf(":");o>0?yf?n={fd:yf(+t.slice(o+1).replace(/[\[\]]/g,""),t.slice(0,o))}:n={host:+t.slice(o+1).replace(/[\[\]]/g,""),port:t.slice(0,o)}:yf?n={fd:yf(+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(),kr.trace("Listening on port "+t,Gm)}).on("error",c)}))}return Promise.all(e)}a(bG,"listenOnPorts");!Cy&&!Gae.noServerStart&&AG();function My(e,t,r){let n=e?.read?e:new qae({fd:e,readable:!0,writable:!0,allowHalfOpen:!0}),s=ni[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=ni[t];c?(typeof c=="function"?c(n):c.emit("connection",n),r&&n.emit("data",r)):o<5?i(o+1):(kr.error(`Server on port ${t} was not registered`),n.destroy())},1e3)},"retry");i(1)}return n}a(My,"deliverSocket");var hG=new Map;function ice(e){let{port:t,event:r,data:n,requestId:s}=e,i;switch(i=hG.get(s),r){case"connection":i=My(void 0,t),hG.set(s,i),i.write=(c,l,d)=>(Of.postMessage({requestId:s,event:"data",data:c.toString("latin1")}),d&&d(),!0),i.end=(c,l,d)=>(Of.postMessage({requestId:s,event:"end",data:c?.toString("latin1")}),d&&d(),!0);let o=i.destroy;i.destroy=()=>{o.call(i),Of.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(ice,"proxyRequest");function Uy(e,t,r=!0){t||(t=Et.get(Yt.CONFIG_PARAMS.HTTP_PORT));let n=ni[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",mG),s.on("unhandled",(i,o)=>{e.cantCleanupProperly&&(n.cantCleanupProperly=!0),e.emit("request",i,o)}),n.lastServer=e}else ni[t]=e;e.on("unhandled",mG)}a(Uy,"registerServer");function yG(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=[],Et.get(Yt.CONFIG_PARAMS.HTTP_PORT)!=null&&t.push({port:Et.get(Yt.CONFIG_PARAMS.HTTP_PORT),secure:Et.get(Yt.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HTTPS)}),Et.get(Yt.CONFIG_PARAMS.HTTP_SECUREPORT)!=null&&t.push({port:Et.get(Yt.CONFIG_PARAMS.HTTP_SECUREPORT),secure:!0})),e?.isOperationsServer&&Et.get(Yt.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET)&&t.push({port:gG(Et.get(Yt.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET)),secure:!1}),t}a(yG,"getPorts");function vy(e,t){for(let{port:r,secure:n}of yG(t))OG(r,n,t?.isOperationsServer),typeof e=="function"?Ly[t?.runFirst?"unshift":"push"]({listener:e,port:t?.port||r}):(e.isSecure=n,Uy(e,r,!1)),qm[r]=Py(Ly,r),nce=Py(sce,r)}a(vy,"httpServer");function OG(e,t,r){if(!Fm[e]){let n=r?"operationsApi_network":"http",s={noDelay:!0,keepAliveTimeout:Et.get(n+"_keepAliveTimeout"),headersTimeout:Et.get(n+"_headersTimeout"),requestTimeout:Et.get(n+"_timeout"),highWaterMark:128*1024,noDelay:!0,keepAlive:!0,keepAliveInitialDelay:600},i=Et.get(n+"_mtls"),o=Et.get(n+"_mtls_required");t&&Object.assign(s,{allowHTTP1:!0,rejectUnauthorized:!!o,requestCert:!!(i||r),ticketKeys:jae(),maxHeaderSize:Et.get(Yt.CONFIG_PARAMS.HTTP_MAXHEADERSIZE),SNICallback:TG(r?"operations-api":"server",i),ALPNCallback:function(d){return d.protocols.includes("harperdb-replication")&&(this.isReplicationConnection=!0),"http/1.1"},ALPNProtocols:null});let c=ece(),l=Fm[e]=(t?Kae:$ae)(s,async(d,u)=>{try{let E=performance.now(),_=new SG(d,u);r&&(_.isOperationsServer=!0);let h=await qm[e](_);if(!h){if(_._nodeResponse.statusCode)return;h=NG(_)}if(h.headers?.set||(h.headers=new Dy(h.headers)),c?h.headers?.set?.("Server","Unlicensed HarperDB, this should only be used for educational and development purposes"):h.headers?.set?.("Server","HarperDB"),h.status===-1){for(let v of h.headers||[])u.setHeader(v[0],v[1]);return d.baseRequest=_,u.baseResponse=h,Fm[e].emit("unhandled",d,u)}let p=h.status||200,S=performance.now(),g=S-E,T=h.body,A;if(!h.handlesHeaders){let v=h.headers||new Dy;T?T.length>=0&&(typeof T=="string"?v.set("Content-Length",Buffer.byteLength(T)):v.set("Content-Length",T.length),A=!0):(v.set("Content-Length","0"),A=!0);let J=`hdb;dur=${g.toFixed(2)}`;h.wasCacheMiss&&(J+=", miss"),Xae(v,"Server-Timing",J,!0),u.writeHead(p,v&&(v[Symbol.iterator]?Array.from(v):v)),A&&u.end(T)}let N=_.handlerPath,V=_.method;if(Af(g,"duration",N,V,h.wasCacheMiss==null?void 0:h.wasCacheMiss?"cache-miss":"cache-hit"),Zae(p<400,"success",N,V),!A)if(T?.pipe){T.pipe(u),T.destroy&&u.on("close",()=>{T.destroy()});let v=0;T.on("data",J=>{v+=J.length}),T.on("end",()=>{Af(performance.now()-S,"transfer",N,V),Af(v,"bytes-sent",N,V)})}else T?.then?T.then(v=>{u.end(v)},f):u.end(T)}catch(E){f(E)}function f(E){let _=E.headers;u.writeHead(E.statusCode||500,_&&(_[Symbol.iterator]?Array.from(_):_)),u.end(E.toString()),E.statusCode?E.statusCode===500?kr.warn(E):kr.info(E):kr.error(E)}a(f,"onError")});t&&(l.ports||(l.ports=[]),l.ports.push(e),s.SNICallback.initialize(l),i&&(l.mtlsConfig=i),l.on("secureConnection",d=>{d._parent.startTime&&Af(performance.now()-d._parent.startTime,"tls-handshake",e),Af(d.isSessionReused(),"tls-reused",e)}),l.isSecure=!0),Uy(l,e)}return Fm[e]}a(OG,"getHTTPServer");function Py(e,t){let r=NG;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(Py,"makeCallbackChain");function NG(e){return e.user&&(e._nodeRequest.user=e.user),{status:-1,body:"Not found",headers:new Dy}}a(NG,"unhandled");function oce(e,t){vy(e,{requestOnly:!0,...t})}a(oce,"onRequest");function ace(e,t){let r;if(t.securePort){let n=TG("server",t.mtls);r=zae({rejectUnauthorized:!!t.mtls?.required,requestCert:!!t.mtls,noDelay:!0,keepAlive:!0,keepAliveInitialDelay:600,SNICallback:n},e),n.initialize(r),ni[t.securePort]=r}return t.port&&(r=Vae(e,{noDelay:!0,keepAlive:!0,keepAliveInitialDelay:600}),ni[t.port]=r),r}a(ace,"onSocket");Object.defineProperty(Yae.prototype,"upgrade",{get(){return"connection"in this.headers&&"upgrade"in this.headers&&this.headers.connection.startsWith("Upgrade")&&this.headers.upgrade.toLowerCase()=="websocket"},set(e){}});function cce(e,t){let r=[];for(let{port:n,secure:s}of yG(t)){if(!bf[n]){let c;bf[n]=new Qae({server:c=OG(n,s,t?.isOperationsServer)}),c._ws=bf[n],r.push(c),bf[n].on("connection",async(l,d)=>{try{let u=new SG(d);u.isWebSocket=!0;let f=qm[n](u),E=d.headers["sec-websocket-protocol"],_=wy[n],h;if(E){for(let p=0;p<_.length;p++){let S=_[p];S.protocol===E&&(h=!0,S.listener(l,u,f))}if(h)return}for(let p=0;p<_.length;p++){let S=_[p];S.protocol||(S.listener(l,u,f),h=!0)}h||l.close(1008,"No handler for protocol")}catch(u){kr.warn("Error handling WebSocket connection",u)}}),bf[n].on("error",l=>{console.log("Error in setting up WebSocket server",l)})}let i=t?.subProtocol||"",o=wy[n];o||(o=wy[n]=[]),o.push({listener:e,protocol:i}),qm[n]=Py(Ly,n)}return r}a(cce,"onWebSocket");function mG(e,t){t.writeHead(404),t.end(`Not found
40
+ `)}a(mG,"defaultNotFound")});async function LG({clientId:e,user:t,clean:r,will:n,keepalive:s}){let i;if(e&&!r){let o=await By.get(e,{returnNonexistent:!0});i=new Fy(e,t,o),o&&(i.sessionWasPresent=!0)}else{if(e){let o=await By.get(e);o&&o.delete()}i=new Ym(e,t)}return n&&(n.id=e,n.user={username:t?.username},If.put(n)),s&&(i.keepalive=s,i.receivedPacket()),i}function Hy(){return $m++,$m>65500&&($m=1),$m}function ky(e,t,r){let{topic:n,retain:s}=e;e.data=t,e.async=!0,r.authorize=!0;let i=ho.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 Tt(r,()=>s?t===void 0?o.delete(e,r):o.put(e,e.data,r):o.publish(e,e.data,r))}var wG,Po,CG,DG,By,If,$m,Ym,Fy,PG=Oe(()=>{Ne();nd();wG=U(hn()),Po=U(X());oa();CG=U(at()),DG=U(IG());Lr();By=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"}]}}]}),If=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,CG.getWorkerIndex)()===0&&(async()=>{await DG.when_components_loaded,await new Promise(e=>setTimeout(e,2e3));for await(let e of If.search({})){let t=e.data,r=Object.assign({},e);r.user?.username&&(r.user=await st.getUser(r.user.username)),Tt(r,()=>{try{ky(r,t,r)}catch{(0,Po.warn)("Failed to publish will",t)}If.delete(e.id,r)})}})();a(LG,"getSession");$m=1;a(Hy,"getNextMessageId");Ym=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,d;if(c>-1?(l=s.slice(c),d=s.slice(0,c)):d=s,!d)throw new Error("No topic provided");if(d.indexOf(".")>-1)throw new Error("Dots are not allowed in topic names");let u=this.subscriptions.find(g=>g.topic===s),f;u?(f=i>0,u.end(),this.subscriptions.splice(this.subscriptions.indexOf(u),1)):f=i===2;let E={search:l,async:!0,user:this.user,startTime:o,omitCurrent:f,url:""};o&&(0,Po.trace)("Resuming subscription from",s,"from",o);let _=ho.getMatch(d,"mqtt");if(!_){let g=new Error(`The topic ${s} does not exist, no resource has been defined to handle this topic`);throw g.statusCode=404,g}if(E.url=_.relativeURL,E.url.indexOf("+")>-1||E.url.indexOf("#")>-1){let g=E.url.slice(1);if(g.indexOf("#")>-1&&g.indexOf("#")!==g.length-1)throw new Error("Multi-level wildcards can only be used at the end of a topic");if(E.isCollection=!0,g.indexOf("+")===g.length-1)E.onlyChildren=!0,E.url="/"+g.slice(0,g.length-1);else{let T=g.split("/"),A;for(let v=0;v<T.length;v++)if(T[v].indexOf("+")>-1)if(T[v]==="+")A=!0;else throw new Error("Single-level wildcards can only be used as a topic level (between or after slashes)");if(n&&A)throw new Error("Filters can not be combined");let N=!0;T[T.length-1]==="#"&&(T.length--,N=!1),A&&(n=a(v=>{let J=v.id;if(!Array.isArray(J)||N&&J.length!==T.length)return!1;for(let $=0;$<T.length;$++)if(T[$]!=="+"&&T[$]!==J[$])return!1;return!0},"filter"));let V=T.indexOf("+");E.url="/"+(V>-1?T.slice(0,V):T).concat("").join("/")}}let h=_.path,p=_.Resource,S=await Tt(E,async()=>{let g=this.createContext();g.topic=s,g.retainHandling=i;let T=await p.subscribe(E,g);if(!T)throw new Error(`No subscription was returned from subscribe for topic ${s}`);if(!T[Symbol.asyncIterator])throw new Error(`Subscription is not (async) iterable for topic ${s}`);return(async()=>{for await(let A of T)try{let N;if(A.type&&A.type!=="put"&&A.type!=="delete"&&A.type!=="message"&&A.type!=="patch"||n&&!n(A))continue;r?(A.topic=s,N=this.needsAcknowledge(A)):(A.acknowledge?.(),N=Hy());let V=A.id;Array.isArray(V)&&(V=kc(V)),V==null&&(V=""),this.listener(h+"/"+V,A.value,N,t)}catch(N){(0,Po.warn)(N)}})(),T});return S.topic=s,S.qos=t.qos,this.subscriptions.push(S),S}resume(){}needsAcknowledge(t){let r=Hy();return t.acknowledge&&(this.awaitingAcks||(this.awaitingAcks=new Map),this.awaitingAcks.set(r,t.acknowledge)),r}acknowledge(t){let r=this.awaitingAcks?.get(t);r&&(this.awaitingAcks.delete(t),r())}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 ky(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();Tt(r,async()=>{try{if(!t){let n=await If.get(this.sessionId);n?.doesExist()&&await ky(n,n.data,r)}}finally{await If.delete(this.sessionId)}}).catch(n=>{(0,Po.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(ky,"publish");Fy=class extends Ym{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.timestamp):null)}resumeSubscription(t,r,n){return super.addSubscription(t,r,n)}needsAcknowledge(t){this.awaitingAcks||(this.awaitingAcks=new Map);let r=Hy(),n={topic:t.topic,timestamp:t.timestamp};return t.acknowledge&&(n.acknowledge=t.acknowledge),this.awaitingAcks.set(r,n),r}acknowledge(t){let r=this.awaitingAcks.get(t);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,Po.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,wG.getNextMonotonicTime)()),(0,Po.trace)("Added durable subscription",t.topic,r),{qos:t.qos,topic:t.topic,startTime:r}}),By.put(this.sessionRecord)}}});var qy={};Ze(qy,{bypassAuth:()=>lce,start:()=>uce});function lce(){BG=!0}function uce({server:e,port:t,network:r,webSocket:n,securePort:s,requireAuthentication:i}){e.mqtt||(e.mqtt={requireAuthentication:i,sessions:new Set,events:new xG.EventEmitter},e.mqtt.events.on("error",()=>{}));let o=e.mqtt,c=[],l=r?.mtls;return n&&(c=e.ws((d,u,f)=>{if(d.protocol==="mqtt"){o.events.emit("connection",d),Or.debug?.("Received WebSocket connection for MQTT from",d._socket.remoteAddress);let{onMessage:E,onClose:_}=UG(d,(h,p)=>{if(d.send(h),p&&d._socket.writableNeedDrain)return new Promise(S=>this._socket.once("drain",S))},u,Promise.resolve(f).then(()=>u?.user),o);d.on("message",E),d.on("close",_),d.on("error",h=>{Or.info?.("WebSocket error",h)})}},Object.assign({subProtocol:"mqtt"},n))),(t||s)&&c.push(e.socket(async d=>{let u;if(o.events.emit("connection",d),Or.debug?.(`Received ${d.getCertificate?"SSL":"TCP"} connection for MQTT from ${d.remoteAddress}`),l){if(d.authorized)try{let _=l.user;if(_!==null){(_===void 0||_==="Common Name"||_==="CN")&&(_=d.getPeerCertificate().subject.CN);try{u=await e.getUser(_,null,null),(0,Ll.get)(Nr.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)&&Wm.notify({username:u?.username,status:Nr.AUTH_AUDIT_STATUS.SUCCESS,type:Nr.AUTH_AUDIT_TYPES.AUTHENTICATION,auth_strategy:"MQTT mTLS",remote_address:d.remoteAddress})}catch(h){throw(0,Ll.get)(Nr.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGFAILED)&&Wm.error?.({username:_,status:Nr.AUTH_AUDIT_STATUS.FAILURE,type:Nr.AUTH_AUDIT_TYPES.AUTHENTICATION,auth_strategy:"mqtt",remote_address:d.remoteAddress}),h}}else Or.debug?.("MQTT mTLS authorized connection (mTLS did not authorize a user)","from",d.remoteAddress)}catch(_){o.events.emit("error",_,d),Or.error?.(_)}else if(l.required)return Or.info?.(`Unauthorized connection attempt, no authorized client certificate provided, error: ${d.authorizationError}`),d.end()}!u&&BG&&d.remoteAddress.includes("127.0.0.1")&&(u=await(0,vG.getSuperUser)(),Or.debug?.("Auto-authorizing local connection",u?.username));let{onMessage:f,onClose:E}=UG(d,_=>d.write(_),null,u,o);d.on("data",f),d.on("close",E),d.on("error",_=>{Or.info?.("Socket error",_)})},{port:t,securePort:s,mtls:l})),c}function UG(e,t,r,n,s){MG||(MG=!0,sf(f=>{Km>0&&f.push({metric:"mqtt-connections",connections:Km,byThread:!0})}));let i;Km++;let o,c={protocolVersion:4},l=(0,Qm.parser)({protocolVersion:5});function d(f){l.parse(f)}a(d,"onMessage");function u(){Km--,i||(i=!0,o?.disconnect?.(),s.events.emit("disconnected",o,e),s.sessions.delete(o),Ln(!1,"connection","mqtt","disconnect"),Or.debug?.("MQTT connection was closed",e.remoteAddress))}return a(u,"onClose"),l.on("packet",async f=>{n?.then&&(n=await n),o?.then&&await o;let E=f.topic,_=E?.indexOf("/",1),h=_>0?E.slice(0,_):E;an(f.length,"bytes-received",h,S(f),"mqtt");try{switch(o?.receivedPacket?.(),f.cmd){case"connect":if(c.protocolVersion=f.protocolVersion,f.username)try{n=await st.getUser(f.username,f.password.toString(),r),(0,Ll.get)(Nr.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)&&Wm.notify({username:n?.username,status:Nr.AUTH_AUDIT_STATUS.SUCCESS,type:Nr.AUTH_AUDIT_TYPES.AUTHENTICATION,auth_strategy:"MQTT",remote_address:e.remoteAddress})}catch($){return(0,Ll.get)(Nr.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGFAILED)&&Wm.error?.({username:f.username,status:Nr.AUTH_AUDIT_STATUS.FAILURE,type:Nr.AUTH_AUDIT_TYPES.AUTHENTICATION,auth_strategy:"mqtt",remote_address:e.remoteAddress}),s.events.emit("auth-failed",f,e,$),Ln(!1,"connection","mqtt","connect"),p({cmd:"connack",reasonCode:4,returnCode:134})}if(!n&&s.requireAuthentication)return s.events.emit("auth-failed",f,e),Ln(!1,"connection","mqtt","connect"),p({cmd:"connack",reasonCode:4,returnCode:134});try{if(s.authorizeClient?.(f,n),f.will){let $=e.deserialize||(e.deserialize=Ma(r?.headers.get?.("content-type")));f.will.data=f.will.payload?.length>0?$(f.will.payload):void 0,delete f.will.payload}o=LG({user:n,...f}),o=await o,o.socket=e,r&&(o.request=r),s.sessions.add(o)}catch($){return Or.error?.($),s.events.emit("auth-failed",f,e,$),Ln(!1,"connection","mqtt","connect"),p({cmd:"connack",reasonCode:$.code||5,returnCode:$.code||128})}s.events.emit("connected",o,e),Ln(!0,"connection","mqtt","connect"),p({cmd:"connack",sessionPresent:o.sessionWasPresent,reasonCode:0,returnCode:0}),o.setListener(($,F,ne,ee)=>{try{let Z=$.indexOf("/",1),le=Z>0?$.slice(0,Z):$;p({cmd:"publish",topic:$,payload:g(F),messageId:ne||Math.floor(Math.random()*1e8),qos:ee.qos},le)}catch(Z){Or.error?.(Z),o?.disconnect(),s.sessions.delete(o)}}),o.sessionWasPresent&&await o.resume();break;case"subscribe":let T=[];for(let $ of f.subscriptions){let F;try{F=(await o.addSubscription($,$.qos>=1)).qos||0}catch(ne){s.events.emit("error",ne,e,$,o),Or.error?.(ne),F=c.protocolVersion<5?128:ne.statusCode===403?135:ne.statusCode===404?143:128}T.push(F)}await o.committed,p({cmd:"suback",granted:T,messageId:f.messageId});break;case"unsubscribe":{let $=[];for(let F of f.unsubscriptions)$.push(o.removeSubscription(F)?0:17);p({cmd:"unsuback",granted:$,messageId:f.messageId});break}case"pubrel":p({cmd:"pubcomp",messageId:f.messageId,reasonCode:0});return;case"publish":let A=f.qos===2?"pubrec":"puback",N=e.deserialize||(e.deserialize=Ma(r?.headers.get?.("content-type"))),v=(f.payload?.length||0)>0?N(f.payload):void 0,J;try{J=await o.publish(f,v)}catch($){s.events.emit("error",$,e,f,o),Or.warn?.($),f.qos>0&&p({cmd:A,messageId:f.messageId,reasonCode:128},f.topic);break}f.qos>0&&p({cmd:A,messageId:f.messageId,reasonCode:J===!1?144:0},f.topic);break;case"pubrec":p({cmd:"pubrel",messageId:f.messageId,reasonCode:0});break;case"pubcomp":case"puback":o.acknowledge(f.messageId);break;case"pingreq":p({cmd:"pingresp"});break;case"disconnect":i=!0,o?.disconnect(!0),s.events.emit("disconnected",o,e),s.sessions.delete(o),Ln(!0,"connection","mqtt","disconnect"),Or.debug?.("Received disconnect command, closing MQTT session",e.remoteAddress),e.close?e.close():e.end();break}}catch(T){s.events.emit("error",T,e,f,o),Or.error?.(T),p({cmd:"disconnect"})}function p(T,A){let N=(0,Qm.generate)(T,c);t(N),an(N.length,"bytes-sent",A,S(T),"mqtt")}a(p,"sendPacket");function S(T){return T.qos>0?T.cmd+",qos="+T.qos:T.cmd}a(S,"packetMethodName");function g(T){return wa(T,r)}a(g,"serialize")}),l.on("error",f=>{Or.warn("MQTT parsing error, closing connection:",f.message),e?.destroy?e.destroy():e?.terminate()}),{onMessage:d,onClose:u}}var Qm,vG,Ll,Nr,Gy,xG,Wm,Or,BG,MG,Km,HG=Oe(()=>{Qm=require("mqtt-packet");PG();vG=U($n());ll();Bi();Lr();Ll=U(ie()),Nr=U(H()),Gy=U(td()),xG=require("events"),Wm=(0,Gy.loggerWithTag)("auth-event"),Or=(0,Gy.loggerWithTag)("mqtt"),BG=(0,Ll.get)(Nr.CONFIG_PARAMS.AUTHENTICATION_AUTHORIZELOCAL)??process.env.DEV_MODE;a(lce,"bypassAuth");a(uce,"start");Km=0;a(UG,"onSocket")});var Fh={};Ze(Fh,{component_errors:()=>Ml,loadComponent:()=>zm,loadComponentDirectories:()=>KG,setErrorReporter:()=>Ece});function KG(e,t){t&&($y=t),e&&(Yy=e);let r=[];if((0,Rt.existsSync)(Vy)){let s=(0,Rt.readdirSync)(Vy,{withFileTypes:!0});for(let i of s){if(!i.isDirectory()&&!i.isSymbolicLink())continue;let o=i.name,c=(0,It.join)(Vy,o);r.push(zm(c,$y,"hdb",!1))}}let n=process.env.RUN_HDB_APP;return n&&r.push(zm(n,$y,n,!1,null,!!process.env.DEV_MODE)),Promise.all(r).then(()=>{YG=!0})}function Ece(e){wf=e}async function zm(e,t,r,n,s,i){let o=(0,Rt.realpathSync)(e);if(!FG.has(o)){FG.set(o,!0),s&&(Yy=s);try{let c;n&&(Ml=new Map);let l=(0,It.join)(e,n?"harperdb-config.yaml":"config.yaml");(0,Rt.existsSync)(l)?c=n?(0,jm.getConfigObj)():(0,GG.parseDocument)((0,Rt.readFileSync)(l,"utf8")).toJSON():c=Ky;let d=(0,It.join)(e,"node_modules","harperdb");try{qa.isMainThread&&(n||(0,Rt.existsSync)(d)&&(0,Rt.realpathSync)(vl.PACKAGE_ROOT)!==(0,Rt.realpathSync)(d))&&((0,Rt.rmSync)(d,{recursive:!0,force:!0}),(0,Rt.existsSync)((0,It.join)(e,"node_modules"))||(0,Rt.mkdirSync)((0,It.join)(e,"node_modules")),(0,Rt.symlinkSync)(vl.PACKAGE_ROOT,d,"dir"))}catch(f){Pl.default.error("Error symlinking harperdb module",f)}let u=n;for(let f in c){let E=c[f];if(Ml.set(n?f:(0,It.basename)(e),!1),!E)continue;let _,h=E.package;try{if(h){let A=e,N;for(;!(0,Rt.existsSync)(N=(0,It.join)(A,"node_modules",f));)if(A=(0,It.dirname)(A),A.length<(0,$G.getHdbBasePath)().length){N=null;break}if(N)_=await zm(N,t,r,!1),u=!0;else throw new Error(`Unable to find package ${f}:${h}`)}else _=_ce[f];if(!_)continue;let p=a(A=>(A.origin=r,dt(A)),"ensureTable"),S=E.network||(E.port||E.securePort)&&E,g=S?.securePort||S?.https&&S.port,T=!S?.https&&S?.port;if(qa.isMainThread&&(_=await _.startOnMainThread?.({server:st,ensureTable:p,port:T,securePort:g,resources:t,...E})||_,n&&S))for(let A of[T,g])try{if(+A&&!kG.includes(A)){let N=Wy.get(vl.CONFIG_PARAMS.HTTP_SESSIONAFFINITY);N&&Pl.default.warn("Session affinity is not recommended and may cause memory leaks"),(N||!Um)&&(kG.push(A),eG(A,N))}}catch(N){console.error("Error listening on socket",A,N,f)}if(t.isWorker&&(_=await _.start?.({server:st,ensureTable:p,port:T,securePort:g,resources:t,...E})||_),Yy.set(_,!0),(_.handleFile||_.handleDirectory||_.setupFile||_.setupDirectory)&&E.files!=null){if(E.files.includes(".."))throw(0,VG.handleHDBError)("Can not reference parent directories");let A=(0,It.join)(e,E.files).replace(/\\/g,"/"),N=A.indexOf("/*");if(N>-1&&E.files!==Ky[f]?.files&&!(0,Rt.existsSync)(A.slice(0,N)))throw new Error(`The path '${A.slice(0,N)}' does not exist and cannot be used as the base of the resolved 'files' path value '${E.files}'`);let V=(0,It.basename)(e),v=E.path||"/";v=v.startsWith("/")?v:v.startsWith("./")?"/"+V+v.slice(2):v==="."?"/"+V:"/"+V+"/"+v;let J,$,F;if(E.root){let ee=E.root;ee.startsWith("/")&&(ee=ee.slice(1)),ee.endsWith("/")&&(ee=ee.slice(0,-1)),ee+="/",$=(0,It.join)(e,ee)}else(F=A.indexOf("/*"))>-1&&($=A.slice(0,F+1),J=(0,It.relative)(e,$));let ne=!1;if(qa.isMainThread&&_.setupDirectory&&(ne=await _.setupDirectory?.(v,$,t)),t.isWorker&&_.handleDirectory&&(ne=await _.handleDirectory?.(v,$,t)),ne)continue;for(let ee of await(0,qG.default)(A,{onlyFiles:!1,objectMode:!0})){let{path:Z,dirent:le}=ee;u=!0;let fe=(0,It.relative)(e,Z).replace(/\\/g,"/");if(J)if(fe.startsWith(J))fe=fe.slice(J.length+1);else throw new Error(`The root path '${E.root}' does not reference a valid part of the file path '${fe}'.The root path should be used to indicate the relative path/part of the file path for determining the exported web path.`);let je=v+(v.endsWith("/")?"":"/")+fe;try{if(le.isFile()){let ye=await fce(Z);qa.isMainThread&&await _.setupFile?.(ye,je,Z,t),t.isWorker&&await _.handleFile?.(ye,je,Z,t)}else qa.isMainThread&&await _.setupDirectory?.(je,Z,t),t.isWorker&&await _.handleDirectory?.(je,Z,t)}catch(ye){ye.message=`Could not load ${le.isFile()?"file":"directory"} '${Z}'${E.module?" using '"+E.module+"'":""} for application '${e}' due to: ${ye.message}`,wf?.(ye),((0,Ul.getWorkerIndex)()===0?console:Pl.default).error(ye),t.set(E.path||"/",new Cf(ye)),Ml.set(n?f:(0,It.basename)(e),ye.message)}}}}catch(p){p.message=`Could not load component '${f}' for application '${(0,It.basename)(e)}' due to: ${p.message}`,wf?.(p),((0,Ul.getWorkerIndex)()===0?console:Pl.default).error(p),t.set(E.path||"/",new Cf(p),null,!0),Ml.set(n?f:(0,It.basename)(e),p.message)}}if(qa.isMainThread&&!YG&&i&&(0,Ul.watchDir)(e,async()=>KG()),c.extensionModule)return await m_((0,It.join)(e,c.extensionModule));if(!u&&t.isWorker){let f=`${e} did not load any modules, resources, or files, is this a valid component?`;wf?.(new Error(f)),((0,Ul.getWorkerIndex)()===0?console:Pl.default).error(f),Ml.set((0,It.basename)(e),f)}}catch(c){console.error(`Could not load application directory ${e}`,c),c.message=`Could not load application due to ${c.message}`,wf?.(c),t.set("",new Cf(c))}}}var Rt,It,qa,GG,Wy,vl,qG,Ul,Pl,VG,$G,dce,jm,fce,Vy,Yy,YG,$y,Ml,_ce,Ky,kG,FG,wf,Cf,Gh=Oe(()=>{Rt=require("fs"),It=require("path"),qa=require("worker_threads"),GG=require("yaml"),Wy=U(ie()),vl=U(H());JN();tI();rI();jH();qF();QF();qG=U(require("fast-glob")),Ul=U(at()),Pl=U(X());iS();Lr();VG=U(ce());Ne();tG();$G=U(ie()),dce=U(oG());Lh();EG();Ai();HG();jm=U(dr());vm();({readFile:fce}=Rt.promises),Vy=(0,jm.resolvePath)(Wy.get(vl.CONFIG_PARAMS.COMPONENTSROOT)),Yy=new Map,Ml=new Map;a(KG,"loadComponentDirectories");_ce={REST:cm,rest:cm,graphqlSchema:sS,jsResource:aS,fastifyRoutes:fy,login:lS,static:_y,operationsApi:dce,customFunctions:{},http:{},clustering:Iy,replication:dd,authentication:kd,mqtt:qy},Ky={rest:!0,graphqlSchema:{files:"*.graphql"},jsResource:{files:"resources.js"},fastifyRoutes:{files:"routes/*.js",path:"."}};Object.defineProperty(Ky,"static",{value:{files:"web/**"}});kG=[],FG=new Map;a(Ece,"setErrorReporter");a(zm,"loadComponent");Cf=class{constructor(t){this.error=t}static{a(this,"ErrorResource")}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 xy=I((ube,QG)=>{var{isMainThread:WG}=require("worker_threads"),{getTables:hce,getDatabases:cbe,table:lbe}=(Ne(),ae(it)),{loadComponentDirectories:mce,loadComponent:pce}=(Gh(),ae(Fh)),{resetResources:Sce}=(nd(),ae(CU)),Tce=$A(),gce=dr(),{dirname:Rce}=require("path"),{getConnection:Ace}=or(),bce=ie(),{CONFIG_PARAMS:yce}=H(),{loadCertificates:Oce}=To(),Qy=new Map;async function Nce(e=!1){!WG&&bce.get(yce.CLUSTERING_ENABLED)&&Ace();try{WG&&await Tce()}catch(n){console.error(n)}let t=Sce();hce(),t.isWorker=e,await Oce(),await pce(Rce(gce.getConfigFilePath()),t,"hdb",!0,Qy),await mce(Qy,t);let r=[];for(let[n]of Qy)n.ready&&r.push(n.ready());r.length>0&&await Promise.all(r)}a(Nce,"loadRootComponents");QG.exports.loadRootComponents=Nce});var at=I((fbe,Os)=>{"use strict";var{Worker:Ice,MessageChannel:wce,parentPort:si,isMainThread:Zy,threadId:Cce,workerData:ii}=require("worker_threads"),{PACKAGE_ROOT:Dce}=H(),{join:XG,isAbsolute:Lce,extname:Pce}=require("path"),{server:ZG}=(Lr(),ae(ko)),{watch:Mce,readdir:Uce}=require("fs/promises"),{totalmem:zG}=require("os"),Df=H(),eq=ie(),oi=X(),{randomBytes:vce}=require("crypto"),{_assignPackageExport:xce}=require("../index"),Bce=H(),jG=1024*1024,Mo=[],ns=[],Hce=50,eO=1e4,kce="restart",tq="request_thread_info",rq="resource_report",nq="thread_info",sq="added-port",Fce="ack",zy;xce("threads",ns);Os.exports={startWorker:jy,restartWorkers:rO,shutdownWorkers:Yce,workers:Mo,setMonitorListener:Zce,onMessageFromWorkers:Kce,onMessageByType:dq,broadcast:Qce,broadcastWithAcknowledgement:jce,setChildListenerByType:$ce,getWorkerIndex:iq,getWorkerCount:oq,getTicketKeys:cq,setMainIsWorker:qce,setTerminateTimeout:Gce,restartNumber:ii?.restartNumber||1};ns.onMessageByType=dq;ns.sendToThread=function(e,t){if(!t?.type)throw new Error("A message with a type must be provided");let r=ns.find(n=>n.threadId===e);if(r)return r.postMessage(t),!0};Os.exports.whenThreadsStarted=new Promise(e=>{Os.exports.threadsHaveStarted=e});var tO;function Gce(e){eO=e}a(Gce,"setTerminateTimeout");function iq(){return ii?ii.workerIndex:tO?0:void 0}a(iq,"getWorkerIndex");function oq(){return ii?ii.workerCount:tO?1:void 0}a(oq,"getWorkerCount");function qce(e){tO=e,Os.exports.threadsHaveStarted()}a(qce,"setMainIsWorker");var aq=1,Jm;function cq(){return Jm||(Jm=Zy?vce(48):ii.ticketKeys,Jm)}a(cq,"getTicketKeys");Object.defineProperty(ZG,"workerIndex",{get(){return iq()}});Object.defineProperty(ZG,"workerCount",{get(){return oq()}});var lq={[tq](e,t){Jce(t)},[rq](e,t){Xce(t,e)}};function jy(e,t={}){let r=process.constrainedMemory?.()||zG();r=Math.min(r,zG(),2e4*jG);let n=eq.get(Df.CONFIG_PARAMS.THREADS_MAXHEAPMEMORY)??Math.max(Math.floor(r/jG/(10+(t.threadCount||1)/4)),512),s=Math.min(Math.max(n>>6,16),64),i=[],o=[];for(let l of ns){let d=new wce;d.existingPort=l,i.push(d),o.push(d.port2)}Pce(e)||(e+=".js");let c=new Ice(Lce(e)?e:XG(Dce,e),Object.assign({resourceLimits:{maxOldGenerationSizeMb:n,maxYoungGenerationSizeMb:s},execArgv:["--enable-source-maps"],argv:process.argv.slice(2),workerData:{addPorts:o,addThreadIds:i.map(l=>l.existingPort.threadId),workerIndex:t.workerIndex,workerCount:aq=t.threadCount,name:t.name,restartNumber:Os.exports.restartNumber,ticketKeys:cq()},transferList:o},t));for(let{port1:l,existingPort:d}of i)d.postMessage({type:sq,port:l,threadId:c.threadId},[l]);return Zm(c,!0),c.unexpectedRestarts=t.unexpectedRestarts||0,c.startCopy=()=>jy(e,t),c.on("error",l=>{oi.error(`Worker index ${t.workerIndex} error:`,l)}),c.on("exit",l=>{Mo.splice(Mo.indexOf(c),1),!c.wasShutdown&&t.autoRestart!==!1&&(c.unexpectedRestarts<Hce?(t.unexpectedRestarts=c.unexpectedRestarts+1,jy(e,t)):oi.error(`Thread has been restarted ${c.restarts} times and will not be restarted`))}),c.on("message",l=>{lq[l.type]?.(l,c)}),Mo.push(c),tle(),t.onStarted&&t.onStarted(c),c.name=t.name,c}a(jy,"startWorker");var Vce=[Df.THREAD_TYPES.HTTP];async function rO(e=null,t=Math.max(aq>3,1),r=!0){if(Zy){if(r){let{loadRootComponents:o}=xy();await o()}Os.exports.restartNumber++,t<1&&(t=t*Mo.length);let n=[],s=[];for(let o of Mo.slice(0)){if(e&&o.name!==e||o.wasShutdown)continue;oi.trace("sending shutdown request to ",o.threadId),o.postMessage({restartNumber:Os.exports.restartNumber,type:Df.ITC_EVENT_TYPES.SHUTDOWN}),o.wasShutdown=!0,o.emit("shutdown",{});let c=Vce.indexOf(o.name)>-1,l=new Promise(d=>{let u=setTimeout(()=>{oi.warn("Thread did not voluntarily terminate, terminating from the outside",o.threadId),o.terminate()},eO*2).unref();o.on("exit",()=>{clearTimeout(u),n.splice(n.indexOf(l)),!c&&r&&o.startCopy(),d()})});if(n.push(l),c&&r){let d=o.startCopy(),u=new Promise(f=>{let E=a(_=>{_.type===Bce.ITC_EVENT_TYPES.CHILD_STARTED&&(oi.trace("Worker has started",d.threadId),f(),s.splice(s.indexOf(u)),d.off("message",E))},"startListener");oi.trace("Waiting for worker to start",d.threadId),d.on("message",E)});s.push(u),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}=xd();r&&(e==="http"||!e)&&eq.get(Df.CONFIG_PARAMS.CLUSTERING_ENABLED)&&await i({service:"clustering"})}else si.postMessage({type:kce,workerType:e})}a(rO,"restartWorkers");function $ce(e,t){lq[e]=t}a($ce,"setChildListenerByType");function Yce(e){return rO(e,1/0,!1)}a(Yce,"shutdownWorkers");var uq=[];function Kce(e){uq.push(e)}a(Kce,"onMessageFromWorkers");var Jy=new Map;function dq(e,t){let r=Jy.get(e);r||Jy.set(e,r=[]),r.push(t)}a(dq,"onMessageByType");var Wce=10;async function Qce(e,t){let r=0;for(let n of ns)try{n.postMessage(e),r++>Wce&&(r=0,await new Promise(setImmediate))}catch(s){oi.error("Unable to send message to worker",s)}t&&_q(e,null)}a(Qce,"broadcast");var Xm=new Map,zce=1;function jce(e){return new Promise(t=>{let r=0;for(let n of ns)try{let s=zce++,i=a(()=>{Xm.delete(s),--r===0&&t(),n!==si&&--n.refCount===0&&n.unref()},"ack_handler");i.port=n,n.ref(),n.refCount=(n.refCount||0)+1,Xm.set(e.requestId=s,i),n.hasAckCloseListener||(n.hasAckCloseListener=!0,n.on(n.close?"close":"exit",()=>{for(let[,o]of Xm)o.port===n&&o()})),n.postMessage(e),r++}catch(s){oi.error("Unable to send message to worker",s)}r===0&&t()})}a(jce,"broadcastWithAcknowledgement");function Jce(e){e.postMessage({type:nq,workers:fq()})}a(Jce,"sendThreadInfo");function fq(){let e=Date.now();return Mo.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(fq,"getChildWorkerInfo");function Xce(e,t){e.resources=t,e.resources.updated=Date.now()}a(Xce,"recordResourceReport");var Xy;function Zce(e){Xy=e}a(Zce,"setMonitorListener");var ele=1e3,JG=!1;function tle(){JG||(JG=!0,setInterval(()=>{for(let e of Mo){let t=e.performance.eventLoopUtilization(),r;e.lastTotalELU?r=e.performance.eventLoopUtilization(t,e.lastTotalELU):r=t,e.lastTotalELU=t,e.recentELU=r}Xy&&Xy()},ele).unref())}a(tle,"startMonitoring");var rle=1e3;if(si&&ii.addPorts){Zm(si);for(let e=0,t=ii.addPorts.length;e<t;e++){let r=ii.addPorts[e];r.threadId=ii.addThreadIds[e],Zm(r)}setInterval(()=>{let e=process.memoryUsage();si.postMessage({type:rq,heapTotal:e.heapTotal,heapUsed:e.heapUsed,external:e.external,arrayBuffers:e.arrayBuffers})},rle).unref(),zy=a(()=>new Promise((e,t)=>{si.on("message",r),si.postMessage({type:tq});function r(n){n.type===nq&&(si.off("message",r),e(n.workers))}a(r,"receiveThreadInfo")}),"getThreadInfo")}else zy=fq;Os.exports.getThreadInfo=zy;function Zm(e,t){ns.push(e),e.on("message",r=>{if(r.type===sq)r.port.threadId=r.threadId,Zm(r.port);else if(r.type===Fce){let n=Xm.get(r.id);n&&n()}else _q(r,e)}).on("close",()=>{ns.splice(ns.indexOf(e),1)}).on("exit",()=>{ns.splice(ns.indexOf(e),1)}),t?e.refCount=100:e.unref()}a(Zm,"addPort");function _q(e,t){for(let n of uq)n(e,t);let r=Jy.get(e.type);if(r)for(let n of r)try{n(e,t)}catch(s){oi.error(s)}}a(_q,"notifyMessageListeners");if(Zy){let e,t,r=new Set,n=a(async(s,i)=>{i&&(e=i);for(let o of await Uce(s,{withFileTypes:!0}))o.isDirectory()&&o.name!=="node_modules"&&n(XG(s,o.name));try{for await(let{filename:o}of Mce(s,{persistent:!1}))r.add(o),t&&clearTimeout(t),t=setTimeout(async()=>{e&&await e(),await rO(),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");Os.exports.watchDir=n,process.env.WATCH_DIR&&n(process.env.WATCH_DIR)}else si.on("message",async e=>{let{type:t}=e;t===Df.ITC_EVENT_TYPES.SHUTDOWN&&(Os.exports.restartNumber=e.restartNumber,si.unref(),setTimeout(()=>{oi.warn("Thread did not voluntarily terminate",Cce),process.exit(0)},eO).unref())})});var cP={};Ze(cP,{AUDIT_STORE_OPTIONS:()=>Pd,Decoder:()=>Yc,HAS_CURRENT_RESIDENCY_ID:()=>qo,HAS_EXPIRATION_EXTENDED_TYPE:()=>Eu,HAS_ORIGINATING_OPERATION:()=>_u,HAS_PREVIOUS_RESIDENCY_ID:()=>Vo,REMOTE_SEQUENCE_UPDATE:()=>zE,createAuditEntry:()=>ac,getLastRemoved:()=>FR,openAuditStore:()=>sp,readAuditEntry:()=>Lt,setAuditRetention:()=>sle,transactionKeyEncoder:()=>yq});function sp(e){let t=e.auditStore=e.openDB(nO.AUDIT_STORE_NAME,Object.assign({create:!1},Pd));t||(t=e.auditStore=e.openDB(nO.AUDIT_STORE_NAME,Pd),hq(t,1)),t.rootStore=e;let r=[];t.addDeleteRemovalCallback=function(i,o){return r[i]=o,{remove(){delete r[i]}}};let n=null;function s(i=ep){clearTimeout(n),n=setTimeout(async()=>{if(t.rootStore.status==="closed"||t.rootStore.status==="closing")return;let o=0,c,l;try{for(let{key:d,value:u}of t.getRange({start:1,snapshot:!1,end:Date.now()-sO})){if((u[0]&15)===iO){let f=Lt(u),E=f.tableId;r[E]?.(f.recordId)}if(c=t.remove(d),l=d,await new Promise(setImmediate),++o>=nle){i=10;break}}await c}finally{o===0?i=Math.min(i<<1,sO/10):hq(t,l),s(i)}},i).unref()}if(a(s,"scheduleAuditCleanup"),t.scheduleAuditCleanup=s,(0,Pf.getWorkerIndex)()===(0,Pf.getWorkerCount)()-1&&s(ep),(0,Pf.getWorkerIndex)()===0&&!Eq)for(let i of t.getKeys({reverse:!0,limit:1}))i>Date.now()&&(Eq=!0,np.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 hq(e,t){oO[0]=t,e.put(Symbol.for("last-removed"),Oq)}function FR(e){let t=e.get(Symbol.for("last-removed"));if(t)return Oq.set(t),oO[0]}function sle(e,t=ep){sO=e,ep=t}function ac(e,t,r,n,s,i,o,c,l,d,u,f,E){let _=Nq[o];if(!_)throw new Error(`Invalid audit entry type ${o}`);let h=1;if(n&&(n>1?Uo.setFloat64(0,n):ss.set(NS),h=9),l){if(l&16761087)throw new Error("Illegal extended type");h++}g(s),g(t),S(r),Uo.setFloat64(h,e),h+=8,l&qo&&g(d),l&Vo&&g(u),l&Eu&&(Uo.setFloat64(h,f),h+=8),l&_u&&g(Iq[E]),i?S(i):ss[h++]=0,l?Uo.setUint16(n?8:0,_|l|32768):ss[n?8:0]=_;let p=ss.subarray(0,h);if(c)return Buffer.concat([p,c]);return p;function S(T){let A=h;h+=1,h=(0,xl.writeKey)(T,ss,h);let N=h-A-1;N>127?N>16383?(np.error("Key or username was too large for audit entry",T),h=A+1,ss[A]=0):(ss.copyWithin(A+2,A+1,h),Uo.setUint16(A,N|32768),h++):ss[A]=N}function g(T){T<128?ss[h++]=T:T<16384?(Uo.setUint16(h,T|32768),h+=2):T<1056964608?(Uo.setUint32(h,T|3221225472),h+=4):(ss[h]=255,Uo.setUint32(h+1,T),h+=5)}}function Lt(e){try{let t=e.dataView||(e.dataView=new Yc(e.buffer,e.byteOffset,e.byteLength)),r;e[t.position]==66&&(r=t.readFloat64());let n=t.readInt(),s=t.readInt(),i=t.readInt(),o=t.readInt(),c=t.position,l=t.position+=o,d=t.readFloat64(),u,f,E,_;if(n&qo&&(u=t.readInt()),n&Vo&&(f=t.readInt()),n&Eu&&(E=t.readFloat64()),n&_u){let S=t.readInt();_=Iq[S]}o=t.readInt();let h=t.position,p=t.position+=o;return{type:Nq[n&7],tableId:i,nodeId:s,get recordId(){return Rq(e,c,l)},getBinaryRecordId(){return e.subarray(c,l)},version:d,previousLocalTime:r,get user(){return p>h?Rq(e,h,p):void 0},encoded:e,getValue(S,g,T){if(n&tp||n&Lf&&!g)return S.decoder.decode(e.subarray(t.position));if(n&Lf&&T)return aO(S.getEntry(this.recordId),T,S)},getBinaryValue(){return n&(tp|Lf)?e.subarray(t.position):void 0},extendedType:n,residencyId:u,previousResidencyId:f,expiresAt:E,originatingOperation:_}}catch(t){return np.error("Reading audit entry error",t,e),{}}}function Rq(e,t,r){let n=e.subarray(t,r);return(0,xl.readKey)(n,0,r-t)}var xl,rp,nO,Aq,Pf,bq,np,ss,Uo,yq,Pd,sO,nle,oO,Oq,ep,Eq,tp,Lf,mq,iO,pq,Sq,Tq,gq,zE,qo,Vo,_u,Eu,Nq,Iq,Yc,_i=Oe(()=>{xl=require("ordered-binary"),rp=U(ie()),nO=U(Ft()),Aq=U(H()),Pf=U(at()),bq=U(re());cc();np=U(X());ip();(0,rp.initSync)();ss=Buffer.alloc(1024),Uo=new DataView(ss.buffer,ss.byteOffset,1024),yq={writeKey(e,t,r){return e===fu?(t.set(fu,r),r+8):typeof e=="number"?((t.dataView||(t.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength))).setFloat64(r,e),r+8):(0,xl.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,xl.readKey)(e,t,r)}},Pd={encoding:"binary",keyEncoder:yq},sO=(0,bq.convertToMS)((0,rp.get)(Aq.CONFIG_PARAMS.LOGGING_AUDITRETENTION))||86400*3,nle=1e3,oO=new Float64Array(1),Oq=new Uint8Array(oO.buffer),ep=1e4,Eq=!1;a(sp,"openAuditStore");a(hq,"updateLastRemoved");a(FR,"getLastRemoved");a(sle,"setAuditRetention");tp=16,Lf=32,mq=1,iO=2,pq=3,Sq=4,Tq=5,gq=6,zE=11,qo=512,Vo=1024,_u=2048,Eu=4096,Nq={put:mq|tp,[mq]:"put",delete:iO,[iO]:"delete",message:pq|tp,[pq]:"message",invalidate:Sq|Lf,[Sq]:"invalidate",patch:Tq|Lf,[Tq]:"patch",relocate:gq,[gq]:"relocate"},Iq={insert:1,update:2,upsert:3,1:"insert",2:"update",3:"upsert"};a(ac,"createAuditEntry");a(Lt,"readAuditEntry");Yc=class extends DataView{static{a(this,"Decoder")}position=0;readInt(){let t;try{t=this.getUint8(this.position++)}catch(r){throw r}return 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{debugger}}};a(Rq,"readKeySafely")});var cO={};Ze(cO,{add:()=>op,applyReverse:()=>wq,getRecordAtTime:()=>aO,rebuildUpdateBefore:()=>ap});function op(e,t,r){let n=e[t];typeof n=="bigint"?e[t]=n+BigInt(r.value):isNaN(e[t])?e[t]=r.value:e[t]=n+r.value}function ap(e,t){let r=null;for(let n in e)if(n in t){let s=t[n];if(s?.__op__){let i=e[n];if(i?.__op__)if(i.__op__===s.__op__)r||(r={}),r[n]=i;else throw new Error("Can not merge updates with different operations");else r||(r={}),r[n]=i,op(r,n,s)}}else r||(r={}),r[n]=e[n];return r}function wq(e,t){for(let r in t){let n=t[r];if(n?.__op__){let s=ile[n.__op__]?.reverse;if(s)s(e,r,{value:n.value});else throw new Error(`Unsupported operation ${n.__op__}`)}else e[r]=Cq}}function aO(e,t,r){let n=r.rootStore.auditStore,s=Object.assign({},e.value),i=e.localTime;for(;i>t;){let l=n.get(i),d=Lt(l);switch(d.type){case"put":s=d.getValue(r);break;case"patch":wq(s,d.getValue(r));break;case"delete":s=null}i=d.previousLocalTime}let o={},c=0;for(let l in s)s[l]===Cq&&(o[l]=!0,c++);for(;c>0&&i>0;){let l=n.get(i),d=Lt(l),u;switch(d.type){case"put":u=d.getValue(r);break;case"patch":u=d.getValue(r);break}for(let f in u)o[f]&&(s[f]=u[f],o[f]=!1,c--);i=d.previousLocalTime}if(c>0)for(let l in o)s[l]=null;return s}var ile,Cq,ip=Oe(()=>{_i();a(op,"add");op.reverse=function(e,t,r){let n=e[t];typeof n=="bigint"?e[t]=n-BigInt(r.value):isNaN(e[t])||(e[t]=n-r.value)};ile={add:op};a(ap,"rebuildUpdateBefore");a(wq,"applyReverse");Cq={};a(aO,"getRecordAtTime")});function Mn(e){return e[er]||(e[er]=Object.create(null))}function fp(e,t){let r=e.prototype,n={},s=t.attributes||t.properties||[];for(let o of s){let c=o.name,l,d;if(o.resolve)d={get(){return o.resolve(this,this[Me])},set(u){return o.set(this,u)},configurable:!0};else{switch(o.type){case"String":l=a(function(u){if(!(typeof u=="string"||u==null&&o.nullable!==!1))throw new is.ClientError(`${c} must be a string, attempt to assign ${u}`);Mn(this)[c]=u},"set");break;case"ID":l=a(function(u){if(!(typeof u=="string"||u?.length>0&&u.every?.(f=>typeof f=="string")||u==null&&o.nullable!==!1))throw new is.ClientError(`${c} must be a string, attempt to assign ${u}`);Mn(this)[c]=u},"set");break;case"Float":case"Number":l=a(function(u){let f=u?.__op__?u.value:u;if(!(typeof f=="number"||u==null&&o.nullable!==!1))throw new is.ClientError(`${c} must be a number, attempt to assign ${f}`);Mn(this)[c]=u},"set");break;case"Int":l=a(function(u){let f=u?.__op__?u.value:u;if(!(f>>0===f||u==null&&o.nullable!==!1))if(typeof f=="number"&&Math.abs((f>>0)-f)<=1)f=Math.round(f),u?.__op__?u.value=f:u=f;else throw new is.ClientError(`${c} must be an integer between -2147483648 and 2147483647, attempt to assign ${u}`);Mn(this)[c]=u},"set");break;case"Long":l=a(function(u){let f=u?.__op__?u.value:u;if(!(Math.round(f)===u&&Math.abs(f)<=9007199254740992||u==null&&o.nullable!==!1))if(typeof f=="number"&&Math.abs(f)<=9007199254740992)f=Math.round(f),u?.__op__?u.value=f:u=f;else throw new is.ClientError(`${c} must be an integer between -9007199254740992 and 9007199254740992, attempt to assign ${u}`);Mn(this)[c]=u},"set");break;case"BigInt":l=a(function(u){let f=u?.__op__?u.value:u;if(!(typeof f=="bigint"||u==null&&o.nullable!==!1))if(typeof f=="string"||typeof f=="number")f=BigInt(f),u?.__op__?u.value=f:u=f;else throw new is.ClientError(`${c} must be a number, attempt to assign ${u}`);Mn(this)[c]=u},"set");break;case"Boolean":l=a(function(u){if(!(typeof u=="boolean"||u==null&&o.nullable!==!1))throw new is.ClientError(`${c} must be a boolean, attempt to assign ${u}`);Mn(this)[c]=u},"set");break;case"Date":l=a(function(u){if(!(u instanceof Date||u==null&&o.nullable!==!1))if(typeof u=="string"||typeof u=="number")u=new Date(u);else throw new is.ClientError(`${c} must be a Date, attempt to assign ${u}`);Mn(this)[c]=u},"set");break;case"Bytes":l=a(function(u){if(!(u instanceof Uint8Array||u==null&&o.nullable!==!1))throw new is.ClientError(`${c} must be a Buffer or Uint8Array, attempt to assign ${u}`);Mn(this)[c]=u},"set");break;case"Any":case void 0:l=a(function(u){Mn(this)[c]=u},"set");break;default:l=a(function(u){if(!(typeof u=="object"||u==null&&o.nullable!==!1))throw new is.ClientError(`${c} must be an object, attempt to assign ${u}`);Mn(this)[c]=u},"set")}d={get(){let u=this[er];if(u&&c in u){let E=u[c];if(E?.__op__){let _=this[Ce]?.[c];return E.update(_)}return E}let f=this[Ce]?.[c];if(f&&typeof f=="object"){let E=Lq(f,o);if(E)return u||(u=this[er]=Object.create(null)),u[c]=E}return f},set:l,enumerable:!0,configurable:!0}}d.get.isAttribute=!0,n[c]=d,(!(c in r)||Object.getOwnPropertyDescriptor(r,c)?.get?.isAttribute)&&Object.defineProperty(r,c,d)}i("getProperty",function(o){let c=n[o];if(c)return c.get.call(this);let l=this[er];return l?.[o]!==void 0?l[o]:this[Ce]?.[o]}),i("set",function(o,c){let l=n[o];if(l)return l.set.call(this,c);if(t.sealed)throw new is.ClientError("Can not add a property to a sealed table schema");Mn(this)[o]=c}),i("deleteProperty",function(o){Mn(this)[o]=void 0}),i("toJSON",function(){let o=this[er],c;for(let d in o){c||(c=Object.assign({},this[Ce]));let u=o[d];if(u?.__op__){let f=c[d];u=u.update(f)}c[d]=u}return Object.keys(this).length>0&&(c||(c=Object.assign({},this[Ce])),Object.assign(c,this)),c||this[Ce]}),r.get||i("get",r.getProperty),r.delete||i("delete",r.deleteProperty);function i(o,c){Object.defineProperty(r,o,{value:c,configurable:!0})}a(i,"setMethod")}function Lq(e,t){let r;switch(e.constructor){case Object:return t?((r=t.TrackedObject)||(t.TrackedObject=r=class{static{a(this,"TrackedObject")}constructor(s){if(s?.[Ce])throw new Error("Can not track an already tracked object, check for circular references");this[Ce]=s}},fp(r,t)),new r(e)):new cp(e);case Array:let n=new up(e.length);n[Ce]=e;for(let s=0,i=e.length;s<i;s++){let o=e[s];o&&typeof o=="object"&&(o=Lq(o,t?.elements)),n[s]=o}return n;default:return e}}function EE(e){let t=e[er],r;for(let s in t){r||(r=Object.assign({},e[Ce]));let i=t[s];if(i&&typeof i=="object")if(i.__op__){let o=r[s];i=i.update(o)}else i=EE(i);r[s]=i}return Object.keys(e).length>0&&(r||(r=Object.assign({},e[Ce])),Object.assign(r,e)),r||e[Ce]}function $a(e,t=e[er]){let r;if(Dq.call(e,Ce)&&e.constructor===Array&&!Object.isFrozen(e)){r=e;for(let n=0,s=e.length;n<s;n++){let i=e[n];if(i&&typeof i=="object"){let o=$a(i);o!==i&&r===e&&(r=e.slice(0)),i=o}r[n]=i}return Object.freeze(r)}for(let n in t){r||(r=Object.assign({},e[Ce]));let s=t[n];if(s&&typeof s=="object")if(s.__op__){let i=cO[s?.__op__];if(i)i(r,n,s);else throw new Error("Invalid CRDT operation "+s.__op__);continue}else s=$a(s);r[n]=s}return r?Object.freeze(r):Dq.call(e,Ce)?e[Ce]:e}function lp(e){let t=e[Ce];if(t===void 0)return!0;if(e.constructor===Array){if(!t||e[Va]||e.length!==t.length)return!0;for(let r=0,n=e.length;r<n;r++){let s=t[r],i=e[r];if(s&&i?.[Ce]===s){if(lp(i))return!0}else return!0}}else{let r=e[er];if(r&&!t)return!0;for(let n in r){let s=r[n];if(s&&typeof s=="object"){let i=t[n];if(i&&s[Ce]===i){if(lp(s))return!0}else return!0}else return!0}}return!1}var is,er,cp,Dq,Va,up,dp,hE=Oe(()=>{ls();is=U(ce());ip();er=Symbol("own-data");a(Mn,"getChanges");a(fp,"assignTrackedAccessors");a(Lq,"trackObject");cp=class{static{a(this,"GenericTrackedObject")}constructor(t){if(t?.[Ce])throw new Error("Can not track an already tracked object, check for circular references");this[Ce]=t}};fp(cp,{});a(EE,"collapseData");Dq=Object.prototype.hasOwnProperty;a($a,"deepFreeze");a(lp,"hasChanges");Va=Symbol.for("has-array-changes"),up=class extends Array{static{a(this,"TrackedArray")}[Va];constructor(t){super(t)}splice(...t){return this[Va]=!0,super.splice(...t)}push(...t){return this[Va]=!0,super.push(...t)}pop(){return this[Va]=!0,super.pop()}unshift(...t){return this[Va]=!0,super.unshift(...t)}shift(){return this[Va]=!0,super.shift()}};up.prototype.constructor=Array;dp=class{constructor(t){this.value=t}static{a(this,"Addition")}__op__="add";update(t){return(+t||0)+this.value}}});var ZT={};Ze(ZT,{CONTEXT:()=>Me,ID_PROPERTY:()=>Ye,IS_COLLECTION:()=>Ns,RECORD_PROPERTY:()=>Ce,Resource:()=>pr,snake_case:()=>ale,transformForSelect:()=>Ep});function ale(e){return e[0].toLowerCase()+e.slice(1).replace(/[a-z][A-Z][a-z]/g,t=>t[0]+"_"+t.slice(1))}function Pq(e,t){if(Mf=!1,e==="")return null;if(e=e.slice(1),e.indexOf("/")===-1)return e===""?(Mf=!0,null):t.coerceId(decodeURIComponent(e));let r=e.split("/"),n=new uO;for(let s=0;s<r.length;s++){let i=r[s];if(!i&&s===r.length-1){Mf=!0;break}n[s]=t.coerceId(decodeURIComponent(i))}return n}function Un(e,t){n.reliesOnPrototype=!0;let r=t.hasContent;return n;function n(s,i,o){let c,l,d,u;if(r?(o?(u=i,o=o[Me]||o):i?typeof s=="object"&&s&&(!Array.isArray(s)||typeof s[0]=="object")?(u=s,c=u[this.primaryKey]??null,o=i[Me]||i):u=i:(u=s,s=void 0,c=u[Ye]??u[this.primaryKey]),c===null&&(d=!0)):i?o=i[Me]||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"){let _=c.indexOf("?");if(_>-1){let p=this.parseQuery(c.slice(_+1));l?l=Object.assign(p,l):l=p,c=c.slice(0,_)}let h=this.parsePath(c,o,l);h?.id!==void 0?(h.query&&(l?l=Object.assign(h.query,l):l=h.query),d=h.isCollection,c=h.id):c=h}else if(s[Symbol.iterator]){c=[],d=!0;for(let _ of s){if(typeof _=="object"&&_)break;c.push(_)}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,d=!1)))}c===void 0&&(c=s.id??null,c==null&&(d=!0))}else c=s,l=new va(c),c===null&&(d=!0);o||(o={});let f;if(l?.ensureLoaded!=null||l?.async||d?(f=Object.assign({},t),l?.ensureLoaded!=null&&(f.ensureLoaded=l.ensureLoaded),l?.async&&(f.async=l.async),d&&(f.isCollection=!0)):f=t,o.transaction){let _=this.getResource(c,o,f);return _.then?_.then(E):E(_)}else return Tt(o,()=>{let _=this.getResource(c,o,f);return _.then?_.then(E):E(_)},f);function E(_){if(o.authorize){o.authorize=!1;let h=t.type==="read"?_.allowRead(o.user,l,o):t.type==="update"?_.doesExist?.()===!1?_.allowCreate(o.user,u,o):_.allowUpdate(o.user,u,o):t.type==="create"?_.allowCreate(o.user,u,o):_.allowDelete(o.user,l,o);if(h?.then)return h.then(p=>{if(!p)throw new _p(o.user);return typeof u?.then=="function"?u.then(S=>e(_,l,o,S)):e(_,l,o,u)});if(!h)throw new _p(o.user)}return typeof u?.then=="function"?u.then(h=>e(_,l,o,h)):e(_,l,o,u)}a(E,"authorizeActionOnResource")}}function vn(e,t){let r=new vq.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 lO(e,t,r){let n=e[Ce];if(n){let s=e[er];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[Me],s;if(typeof e=="string")return a(function o(c){return c.then?c.then(o):Array.isArray(c)?c.map(o):lO(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 d=[],u=i(lO(l,r,n));for(let f of e)d.push(u(f));return d},"transform");let o=e.forceNulls;return a(function c(l){if(l.then)return l.then(c);if(Array.isArray(l))return l.map(E=>E&&typeof E=="object"?c(E):E);let d={},u=i(lO(l,r,n)),f;for(let E of e){let _=u(E);_===void 0&&o&&(_=null),_?.then?(f||(f=[]),f.push(_.then(h=>d[E.name||E]=h))):d[E.name||E]=_}return f?Promise.all(f).then(()=>d):d},"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 u=r[c.name]?.definition?.tableClass;l=s[c.name]=Ep(c.select||c,u)}let d=o(c.name);return l(d)}else return o(c);else return c}}a(i,"handleProperty")}var Mq,Uq,vq,Me,Ye,Ns,Ce,ole,pr,_p,Mf,uO,ls=Oe(()=>{Mq=require("crypto");ic();Uq=require("../index"),vq=U(ce());hE();oa();lf();Me=Symbol.for("context"),Ye=Symbol.for("primary-key"),Ns=Symbol("is-collection"),Ce=Symbol("stored-record"),ole={json:"application/json",cbor:"application/cbor",msgpack:"application/x-msgpack",csv:"text/csv"},pr=class{static{a(this,"Resource")}static transactions;constructor(t,r){this[Ye]=t;let n=r?.[Me];this[Me]=n!==void 0?n:r||null}static get=Un(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 d=Ep(l,t.constructor);return typeof c?.map=="function"?c.map(d):d(c)}return c}},{type:"read",letItLinger:!0,ensureLoaded:!0,async:!0});static put=Un(function(t,r,n,s){if(Array.isArray(s)&&t[Ns]){let i=[],o=n.authorize;for(let c of s){let l=t.constructor,d=l.getResource(c[l.primaryKey],n,{async:!0});d.then?i.push(d.then(u=>u.put(c,n))):i.push(d.put(c,n))}return Promise.all(i)}return t.put?t.put(s,r):vn(t,"put")},{hasContent:!0,type:"update"});static patch=Un(function(t,r,n,s){return t.patch?t.patch(s,r):vn(t,"patch")},{hasContent:!0,type:"update"});static delete=Un(function(t,r,n,s){return t.delete?t.delete(r):vn(t,"delete")},{hasContent:!1,type:"delete"});static getNewId(){return(0,Mq.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={}),Tt(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=Un(function(t,r,n,s){return t.invalidate?t.invalidate(r):vn(t,"delete")},{hasContent:!1,type:"update"});static post=Un(function(t,r,n,s){return t[Ye]!=null&&t.update?.(),t.post(s,r)},{hasContent:!0,type:"create"});static connect=Un(function(t,r,n,s){return t.connect?t.connect(s,r):vn(t,"connect")},{hasContent:!0,type:"read"});static subscribe=Un(function(t,r,n,s){return t.subscribe?t.subscribe(r):vn(t,"subscribe")},{type:"read"});static publish=Un(function(t,r,n,s){return t[Ye]!=null&&t.update?.(),t.publish?t.publish(s,r):vn(t,"publish")},{hasContent:!0,type:"create"});static search=Un(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=Un(function(t,r,n,s){return t.search?t.search(s,r):vn(t,"search")},{hasContent:!0,type:"read"});static copy=Un(function(t,r,n,s){return t.copy?t.copy(s,r):vn(t,"copy")},{hasContent:!0,type:"create"});static move=Un(function(t,r,n,s){return t.move?t.move(s,r):vn(t,"move")},{hasContent:!0,type:"delete"});async post(t){if(this[Ns])return(await this.constructor.create(this[Ye],t,this[Me]))[Ye];vn(this,"post")}static isCollection(t){return t?.[Ns]}static coerceId(t){return t}static parseQuery(t){return om(t)}static parsePath(t,r,n){let s=t.indexOf(".");if(s>-1){let o=t.slice(s+1);t=t.slice(0,s);let c=r?.headers&&ole[o];if(c)r.headers.set("accept",c);else if(n)n.property=o;else return{query:{property:o},id:Pq(t,this),isCollection:Mf}}let i=Pq(t,this);return Mf?{id:i,isCollection:!0}:i}static getResource(t,r,n){let s,i=r[Me],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 d=l.asMap.get(t);if(s=d?.find(u=>u.constructor===c),s)return s;d||l.asMap.set(t,d=[]),d.push(s=new c(t,i))}else{if(s=l.find(d=>d[Ye]===t&&d.constructor===c),s)return s;if(l.push(s=new c(t,i)),l.length>10){let d=new Map;for(let u of l){let f=u[Ye],E=d.get(f);E?E.push(u):d.set(f,[u])}i.resourceCache.length=0,i.resourceCache.asMap=d}}}else s=new c(t,i);return o&&(s[Ns]=!0),s}subscribe(t){return new mn}connect(t){return t?.subscribe!==!1?this.subscribe?.(t):new mn}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[Ye]}getContext(){return this[Me]}};pr.prototype[Me]=null;(0,Uq._assignPackageExport)("Resource",pr);a(ale,"snake_case");_p=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(Pq,"pathToId");uO=class extends Array{static{a(this,"MulitPartId")}toString(){return this.join("/")}};a(Un,"transactional");a(vn,"missingMethod");a(lO,"selectFromObject");a(Ep,"transformForSelect")});var zb={};Ze(zb,{coerceType:()=>hp,makeTable:()=>Sp,setServerUtilities:()=>mle,updateResource:()=>mp});function Sp(e){let{primaryKey:t,indices:r,tableId:n,tableName:s,primaryStore:i,databasePath:o,databaseName:c,auditStore:l,schemaDefined:d,dbisDB:u,sealed:f,replicate:E}=e,{expirationMS:_,evictionMS:h,audit:p,trackDeletes:S}=e,{attributes:g}=e;g||(g=[]);let T=CS(i,n,l),A,N,V={},v=Promise.resolve(),J,$,F;for(let q of g)(q.assignCreatedTime||q.name==="__createdtime__")&&(J=q),(q.assignUpdatedTime||q.name==="__updatedtime__")&&($=q),q.expiresAt&&(F=q),q.isPrimaryKey&&(V=q);let ne,ee=[],Z=[],le=1,fe=2,je={},ye={},Ht=864e5,Bo,tc,Gr,Yl=!1,Vi,$i,Cs=new Map,Ds=new Map,Ct,Hp,dn=Bl.get(os.CONFIG_PARAMS.REPLICATION_DATABASES);if(Array.isArray(dn)){for(let q of dn)if(q.name===c&&q.replicateTo>=0){Hp=q.replicateTo;break}}let e_=i.getRange({start:!1,end:!1}).constructor,t_=10,Kl=6;p&&tt();class ve extends pr{static name=s;static primaryStore=i;static auditStore=l;static primaryKey=t;static tableName=s;static tableId=n;static indices=r;static audit=p;static databasePath=o;static databaseName=c;static attributes=g;static replicate=E;static sealed=f;static createdTimeProperty=J;static updatedTimeProperty=$;static propertyResolvers;static userResolvers={};static sources=[];static get expirationMS(){return _}static dbisDB=u;static schemaDefined=d;static sourcedFrom(m,R){if(R&&(this.sourceOptions=R,(R.expiration||R.eviction||R.scanInterval)&&this.setTTLExpiration(R)),R?.intermediateSource)m.intermediateSource=!0,this.sources.unshift(m);else{if(this.sources.some(C=>!C.intermediateSource))throw new Error("Can not have multiple canonical (non-intermediate) sources");this.sources.push(m)}N=N||m.get&&(!m.get.reliesOnPrototype||m.prototype.get),A=A||m.load;let w=a(C=>{let O=this.sources;if(O=O.filter(P=>P.intermediateSource&&P[C]&&(!P[C].reliesOnPrototype||P.prototype[C])),O.length>0)if(O.length===1){let P=O[0];return(M,L,B)=>{if(M?.source!==P)return P[C](L,B,M)}}else return(P,M,L)=>{let B=[];for(let Y of O){if(P?.source===Y)break;B.push(Y[C](M,L,P))}return Promise.all(B)}},"getApplyToIntermediateSource"),b=this.sources[this.sources.length-1];b.intermediateSource&&(b={});let y=a(C=>{if(b[C]&&(!b[C].reliesOnPrototype||b.prototype[C]))return(O,P,M)=>{if(!O?.source)return b[C](P,M,O)}},"getApplyToCanonicalSource");return je={put:y("put"),patch:y("patch"),delete:y("delete"),publish:y("publish")},ye={put:w("put"),patch:w("patch"),delete:w("delete"),publish:w("publish"),invalidate:w("invalidate")},(async()=>{let C=!1,O,P=a(async(M,L)=>{let B=M.value,Y=M.table?Ve[c][M.table]:ve;if(c===os.SYSTEM_SCHEMA_NAME&&(M.table===os.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME||M.table===os.SYSTEM_TABLE_NAMES.USER_TABLE_NAME)&&(C=!0),M.id===void 0&&(M.id=B[Y.primaryKey],M.id===void 0))throw new Error("Replication message without an id "+JSON.stringify(M));M.source=m;let K={residencyId:Dt(M.residencyList),isNotification:!0,ensureLoaded:!1,nodeId:M.nodeId},Te=await Y.getResource(M.id,L,K);switch(M.type){case"put":return Te._writeUpdate(B,!0,K);case"patch":return Te._writeUpdate(B,!1,K);case"delete":return Te._writeDelete(K);case"publish":return Te._writePublish(B,K);case"invalidate":return Te._writeInvalidate(K);case"relocate":return Te._writeRelocate(K);default:qe.default.error?.("Unknown operation",M.type,M.id)}},"writeUpdate");try{let M=m.subscribe;M&&S==null&&(S=!0);let L=m.subscribeOnThisThread?m.subscribeOnThisThread((0,Wa.getWorkerIndex)()):(0,Wa.getWorkerIndex)()===0,B=M&&L&&await m.subscribe?.({crossThreads:!1,inTransactionUpdates:!0,supportsTransactions:!0,omitCurrent:!0});if(B){let Y;for await(let K of B)try{if(!(K.type==="transaction"?K.writes[0]:K)){qe.default.error?.("Bad subscription event",K);continue}if(K.source=m,K.type==="end_txn"){if(Y?.resolve(),K.localTime&&O!==K.localTime){if(K.remoteNodeIds?.length>0){let Ie=[Symbol.for("seq"),K.remoteNodeIds[0]],he=u.get(Ie),De=he?.nodes;De||(De=[]);for(let k of K.remoteNodeIds.slice(1)){let se=De.find(ue=>ue.name===k);se||(se={id:k,seqId:0},De.push(se)),se.seqId=Math.max(he?.seqId??1,K.localTime),k===K.nodeId&&(se.lastTxnTime=K.timestamp)}let x=Math.max(he?.seqId??1,K.localTime);u.put(Ie,{seqId:x,nodes:De})}O=K.localTime}K.onCommit&&Y?.committed.then(K.onCommit);continue}if(Y)if(K.beginTxn)Y.resolve();else{Y.write_promises.push(P(K,Y));continue}let j=Tt(K,()=>{if(K.type==="transaction"){let Ie=[];for(let he of K.writes)try{Ie.push(P(he,K))}catch(De){throw De.message+=" writing "+JSON.stringify(he)+" of event "+JSON.stringify(K),De}return Promise.all(Ie)}else if(K.type==="define_schema"){let Ie=this.attributes.slice(0),he;for(let De of K.attributes)Ie.find(x=>x.name===De.name)||(Ie.push(De),he=!0);he&&(dt({table:s,database:c,attributes:Ie,origin:"cluster"}),kf.signalSchemaChange(new Ff.SchemaEventMsg(process.pid,os.OPERATIONS_ENUM.CREATE_TABLE,c,s)))}else return K.beginTxn?(Y=K,Y.write_promises=[P(K,K)],new Promise(Ie=>{Y.resolve=()=>Ie(Promise.all(Y.write_promises))})):P(K,K)});Y&&(Y.committed=j),C&&j&&!j?.waitingForUserChange&&(j.then(()=>kf.signalUserChange(new Ff.UserEventMsg(process.pid))),j.waitingForUserChange=!0),K.onCommit&&(j?j.then(K.onCommit):K.onCommit())}catch(Te){qe.default.error?.("error in subscription handler",Te)}}}catch(M){qe.default.error?.(M)}})(),this}static getResource(m,R,w){let b=super.getResource(m,R,w);if(m!=null){li(m);try{if(b.hasOwnProperty(Ce))return b;if(typeof m=="object"&&m&&!Array.isArray(m))throw new Error(`Invalid id ${JSON.stringify(m)}`);let y=!w?.async||i.cache?.get(m),C=Dr(R),O=C.getReadTxn();if(O?.isDone)throw new Error("You can not read from a transaction that has already been committed/aborted");return rc(m,R,{transaction:O,ensureLoaded:w?.ensureLoaded},y,P=>{if(P?mp(b,P):b[Ce]=null,R.onlyIfCached&&R.noCacheStore){if(!b.doesExist())throw new wr.ServerError("Entry is not cached",504)}else if(w?.ensureLoaded){let M=nc(m,P,R,b);if(M)return C?.disregardReadTxn(),b[dO]=!0,_O(M,L=>(mp(b,L),b))}return b})}catch(y){throw y.message.includes("Unable to serialize object")&&(y.message+=": "+JSON.stringify(m)),y}}return b}ensureLoaded(){let m=nc(this[Ye],this[Ir],this[Me]);if(m)return this[dO]=!0,_O(m,R=>{this[Ir]=R,this[Ce]=R.value,this[Bf]=R.version})}static getNewId(){let m=V?.type;if(m==="String"||m==="ID")return super.getNewId();if(!Ct){let y=i.getEntry(Symbol.for("id_allocation")),C=y?.value,O;if(C&&C.nodeName===server.hostname&&(!Sle(i)||C.pid===process.pid)){let P=C.start,M=C.end;O=P;for(let L of i.getKeys({start:M,end:P,limit:1,reverse:!0}))O=L}else C=b(y?.version??null),O=C.start;Ct=new BigInt64Array([BigInt(O)+1n]),Ct=new BigInt64Array(i.getUserSharedBuffer("id",Ct.buffer)),Ct.maxSafeId=C.end}let R=Number(Atomics.add(Ct,0,1n)),w=m==="Int"?512:1048576;if(R+w>=Ct.maxSafeId){let y=a(C=>{Ct.maxSafeId=R+(m==="Int"?1023:4194303);let O=(m==="Int"?Math.pow(2,31):Math.pow(2,49))-1,P=C?void 0:i.useReadTransaction(),M=Number(Ct[0]);for(let Y of i.getKeys({start:M+1,end:O,limit:1,transaction:P}))O=Y;P?.done();let{value:L,version:B}=i.getEntry(Symbol.for("id_allocation"));if(Ct.maxSafeId<O){if(L.end>Ct.maxSafeId-100)return;qe.default.info?.("New id allocation",R,Ct.maxSafeId,B),i.put(Symbol.for("id_allocation"),{start:L.start,end:Ct.maxSafeId,nodeName:server.hostname,pid:process.pid},Date.now(),B)}else{qe.default.warn?.(`Id conflict detected, starting new id allocation range, attempting to allocate to ${Ct.maxSafeId}, but id of ${O} detected`);let Y=b(B);Y.alreadyUpdated||Atomics.store(Ct,0,BigInt(Y.start+1)),Ct.maxSafeId=Y.end}},"updateEnd");R+w===Ct.maxSafeId?setImmediate(y):R+100>=Ct.maxSafeId&&(qe.default.warn?.(`Synchronous id allocation required on table ${s}${m=="Int"?", it is highly recommended that you use Long or Float as the type for auto-incremented primary keys":""}`),i.transactionSync(()=>y(!0)))}return R;function b(y){let C=(m==="Int"?Math.pow(2,31):Math.pow(2,49))-1,O=C/4,P,M,L=!1,B,Y;do{B=Math.floor(Math.random()*C),Y={start:B,end:B+(m==="Int"?1024:4194304),nodeName:server.hostname,pid:process.pid},P=0;for(let K of i.getKeys({start:B,limit:1,reverse:!0}))P=K;M=C;for(let K of i.getKeys({start:B+1,end:C,limit:1}))M=K;O*=.875,O<1e3&&!L&&(L=!0,qe.default.error?.(`Id allocation in table ${s} is very dense, limited safe range of numbers to allocate ids in${m==="Int"?", it is highly recommended that you use Long or Float as the type for auto-incremented primary keys":""}`,B,P,M,O))}while(!(O<M-B&&(O<B-P||P===0)));return i.transactionSync(()=>{let K=i.getEntry(Symbol.for("id_allocation"));return(K?.version??null)==y?(qe.default.info?.("Allocated new id range",Y),i.put(Symbol.for("id_allocation"),Y,Date.now()),Y):(qe.default.debug?.("Looks like ids were already allocated"),Object.assign({alreadyUpdated:!0},K.value))})}}static setTTLExpiration(m){if(typeof m=="number")_=m*1e3,h||(h=0);else if(m&&typeof m=="object")_=m.expiration*1e3,h=(m.eviction||0)*1e3,Ht=m.scanInterval*1e3;else throw new Error("Invalid expiration value type");if(_<0)throw new Error("Expiration can not be negative");Ht=Ht||(_+h)/4,Fe()}static getResidencyRecord(m){return u.get([Symbol.for("residency_by_id"),m])}static setResidency(m){ve.getResidency=m}static setResidencyById(m){ve.getResidencyById=m}static getResidency(m,R,w){if(ve.getResidencyById)return ve.getResidencyById(m[t]);let b=Hp;if(R.replicateTo!=null){if(Array.isArray(R.replicateTo))return R.replicateTo.includes(server.hostname)?R.replicateTo:[server.hostname,...R.replicateTo];R.replicateTo>=0&&(b=R.replicateTo)}if(b>=0&&server.nodes){let y=[server.hostname];if(w)y.push(...w.slice(0,b));else{let C=Math.floor(server.nodes.length*Math.random());y.push(...server.nodes.slice(C,C+b));let O=C+b-server.nodes.length;O>0&&y.push(...server.nodes.slice(0,O))}return y}}static enableAuditing(m=!0){p=m,m&&tt(),ve.audit=m}static coerceId(m){return m===""?null:hp(m,V)}static async dropTable(){if(delete Ve[c][s],c===o){for(let m of g)u.remove(ve.tableName+"/"+m.name),r[m.name]?.drop();u.remove(ve.tableName+"/"),i.drop(),await u.committed}else console.log("legacy dropTable"),await i.close(),await fs.remove(data_path),await fs.remove(data_path===standard_path?data_path+MDB_LOCK_FILE_SUFFIX:path.join(path.dirname(data_path),MDB_LEGACY_LOCK_FILE_NAME));kf.signalSchemaChange(new Ff.SchemaEventMsg(process.pid,os.OPERATIONS_ENUM.DROP_TABLE,c,s))}get(m){if(typeof m=="string")return this.getProperty(m);if(this[Ns])return this.search(m);if(this[Ye]===null){if(m?.conditions)return this.search(m);let R=ve.getRecordCount();return{recordCount:R.recordCount,estimatedRecordRange:R.estimatedRange,records:"./",name:s,database:c,auditSize:l?.getStats().entryCount,attributes:g}}if(m?.property)return this.getProperty(m.property);if(this.doesExist()||m?.ensureLoaded===!1||this[Me]?.returnNonexistent)return this}allowRead(m,R){let w=ui(m);if(w?.read){if(w.isSuperUser)return!0;let b=w.attribute_permissions,y=R?.select;if(b?.length>0||Yl&&y){if(R||(R={}),y){let C=b?.length>0&&fO(b,"read");R.select=y.map(O=>{let P=O.name||O;if(!C||C[P]){let M=Gr[P]?.definition?.tableClass;if(M){if(O.name||(O={name:O}),!M.prototype.allowRead.call(null,m,O))return!1;if(!O.select)return O.name}return O}}).filter(Boolean)}else R.select=b.filter(C=>C.read&&!Gr[C.attribute_name]).map(C=>C.attribute_name);return R}else return!0}}allowUpdate(m,R){let w=ui(m);if(w?.update){let b=w.attribute_permissions;if(b?.length>0){let y=fO(b,"update");for(let C in R)if(!y[C])return!1;for(let C of b){let O=C.attribute_name;!C.update&&!(O in R)&&(R[O]=this.getProperty(O))}}return Ae(this[Me])}}allowCreate(m,R){if(this[Ns]){let w=ui(m);if(w?.insert){let b=w.attribute_permissions;if(b?.length>0){let y=fO(b,"insert");for(let C in R)if(!y[C])return!1;return Ae(this[Me])}else return Ae(this[Me])}}else return this.allowUpdate(m,{})}allowDelete(m){return ui(m)?.delete&&Ae(this[Me])}update(m,R){if(!Dr(this[Me]))throw new Error("Can not update a table resource outside of a transaction");if(m===!1)return this;let b;return typeof m=="object"&&m&&(R?(Object.isFrozen(m)&&(m=Object.assign({},m)),this[Ce]={},this[er]=m):(b=this[er],b&&(m=Object.assign(b,m)),this[er]=b=m)),this._writeUpdate(this[er],R),this}addTo(m,R){if(typeof R=="number"||typeof R=="bigint")this[Uf]===Bq?this.set(m,(+this.getProperty(m)||0)+R):(this[Uf]||this.update(),this.set(m,new dp(R)));else throw new Error("Can not add a non-numeric value")}subtractFrom(m,R){if(typeof R=="number")return this.addTo(m,-R);throw new Error("Can not subtract a non-numeric value")}getMetadata(){return this[Ir]}invalidate(){this._writeInvalidate()}_writeInvalidate(m){let R=this[Me],w=this[Ye];li(w),Dr(this[Me]).addWrite({key:w,store:i,invalidated:!0,entry:this[Ir],before:je.invalidate?.bind(this,R,w),beforeIntermediate:ye.invalidate?.bind(this,R,w),commit:(y,C)=>{if(me(y,C,m?.nodeId))return;let O=null;for(let P in r)O||(O={}),O[P]=this.getProperty(P);qe.default.trace?.(`Invalidating entry id: ${w}, timestamp: ${new Date(y).toISOString()}`),T(w,O,this[Ir],y,Ya,p,{user:R?.user,residencyId:m?.residencyId,nodeId:m?.nodeId},"invalidate")}})}_writeRelocate(m){let R=this[Me],w=this[Ye];li(w),Dr(this[Me]).addWrite({key:w,store:i,invalidated:!0,entry:this[Ir],before:je.relocate?.bind(this,R,w),beforeIntermediate:ye.relocate?.bind(this,R,w),commit:(y,C)=>{if(me(y,C,m?.nodeId))return;let O=ve.getResidencyRecord(m.residencyId),P=0,M=null,L=C?.value;if(O&&!O.includes(server.hostname)){for(let B in r)M||(M={}),M[B]=L(B);P=Ya}else M=L;qe.default.trace?.(`Relocating entry id: ${w}, timestamp: ${new Date(y).toISOString()}`),T(w,M,this[Ir],y,P,p,{user:R.user,residencyId:m.residencyId,nodeId:m.nodeId,expiresAt:m.expiresAt},"relocate",!1,null)}})}static _recordRelocate(m,R){let w={previousResidency:this.getResidencyRecord(m.residencyId),isRelocation:!0},b=this.getResidency(R.value,w),y;if(b){if(!Array.isArray(b))throw new Error("Residency must be an array, but was: "+b);if(!b.includes(server.hostname))return;y=Dt(b)}let O=T(m.key,R.value,m,m.version,0,!0,{residencyId:y,expiresAt:R.expiresAt},"relocate",!1,null)}static evict(m,R,w){let b=this.Source,y;if(!((N||p)&&(!R||(y=i.getEntry(m),!y||!R)||y.version!==w))){if(N){if(i.hasLock(m,y.version))return;let C;for(let O in r)C||(C={}),C[O]=R[O];if(C)return T(m,C,y,w,vf,null,null,null,!0)}return i.ifVersion(m,w,()=>{Yi(m,R,null)}),p?T(m,null,y,w,vf,null,null,null,!0):i.remove(m,w)}}lock(){throw new Error("Not yet implemented")}static operation(m,R){return m.table||=s,m.schema||=c,Vq.operation(m,R)}put(m){this.update(m,!0)}patch(m){this.update(m,!1)}_writeUpdate(m,R,w){let b=this[Me],y=Dr(b),C=this[Ye];li(C);let O=this[Ir];this[Uf]=R?Bq:_le;let P={key:C,store:i,entry:O,nodeName:b?.nodeName,validate:M=>{m||(m=this[er]),R||m&&lp(this[er]===m?this:m)?b?.source||(y.checkOverloaded(),this.validate(m,!R),$&&(m[$.name]=$.type==="Date"?new Date(M):$.type==="String"?new Date(M).toISOString():M),R&&(t&&m[t]!==C&&(m[t]=C),J&&(O?.value?m[J.name]=O?.value[J.name]:m[J.name]=J.type==="Date"?new Date(M):J.type==="String"?new Date(M).toISOString():M),m=$a(m))):y.removeWrite(P)},before:R?je.put?()=>je.put(b,C,m):null:je.patch?()=>je.patch(b,C,m):je.put?()=>je.put(b,C,$a(this)):null,beforeIntermediate:R?ye.put?()=>ye.put(b,C,m):null:ye.patch?()=>ye.patch(b,C,m):ye.put?()=>ye.put(b,C,$a(this)):null,commit:(M,L,B)=>{if(B){if(b&&L?.version>(b.lastModified||0)&&(b.lastModified=L.version),this[Ir]=L,L?.value?.[Ce])throw new Error("Can not assign a record to a record, check for circular references");R||(this[Ce]=L?.value??null)}this[er]=void 0,this[Bf]=M;let Y=L?.value,K=m;if(this[Uf]=0,me(M,L,w?.nodeId))if(p){let k=L.localTime,se=L.version;for(;K&&(k>M||se>=M&&k>0);){let ue=l.get(k);if(!ue)break;let pe=Lt(ue);if(se=pe.version,se>M){if(pe.type==="patch"){let rt=pe.getValue(i);K=ap(K,rt)}else if(pe.type==="put"||pe.type==="delete")return}else if(se===M)return;k=pe.previousLocalTime}}else{if(R)return;K=ap(K,Y)}let j;if(R?j=K:(this[Ce]=Y,j=R?K:$a(this,K)),this[Ce]=j,j?.[Ce])throw new Error("Can not assign a record to a record, check for circular references");let Ie,he;if(w?.residencyId!=null)he=w.residencyId;else{O?.residencyId&&(b.previousResidency=ve.getResidencyRecord(O.residencyId));let k=ve.getResidency(j,b);if(k){if(!Array.isArray(k))throw new Error("Residency must be an array, got: "+k);k.includes(server.hostname)||k.push(server.hostname)}he=Dt(k)}R||(Ie=m);let De=b?.expiresAt||(_?_+Date.now():0);qe.default.trace?.(`Saving record with id: ${C}, timestamp: ${new Date(M).toISOString()}${De?", expires at: "+new Date(De).toISOString():""}${L?", replaces entry from: "+new Date(L.version).toISOString():", new entry"}`),Yi(C,Y,j);let x=R?"put":"patch";T(C,j,L,M,0,p,{user:b?.user,residencyId:he,expiresAt:De,nodeId:w?.nodeId,originatingOperation:b?.originatingOperation},x,!1,Ie),b.expiresAt&&Fe()}};y.addWrite(P)}async delete(m){if(typeof m=="string")return this.deleteProperty(m);if(this[Ns]){for await(let R of this.search(m))(await ve.getResource(R[t],this.getContext(),{ensureLoaded:!1}))._writeDelete(m);return}return this[Ce]?this._writeDelete(m):!1}_writeDelete(m){let R=Dr(this[Me]),w=this[Ye];li(w);let b=this[Me];return R.addWrite({key:w,store:i,resource:this,nodeName:b?.nodeName,before:je.delete?.bind(this,b,w),beforeIntermediate:ye.delete?.bind(this,b,w),commit:(y,C,O)=>{let P=C?.value;O&&(b&&C?.version>(b.lastModified||0)&&(b.lastModified=C.version),mp(this,C)),!me(y,C,m?.nodeId)&&(Yi(this[Ye],P),qe.default.trace?.(`Deleting record with id: ${w}, txn timestamp: ${new Date(y).toISOString()}`),p||S?(T(w,null,this[Ir],y,0,p,{user:b?.user,nodeId:m?.nodeId},"delete"),p||Fe()):i.remove(this[Ye]))}}),!0}search(m){let R=this[Me],w=Dr(R);if(!m)throw new Error("No query provided");let b=m.conditions;b?b.length===void 0&&(b=b[Symbol.iterator]?Array.from(b):[b]):b=Array.isArray(m)?m:m[Symbol.iterator]?Array.from(m):[],this[Ye]&&(b=[{attribute:null,comparator:"prefix",value:this[Ye]}].concat(b));let y,C={};function O(k,se){let ue;switch(se){case"and":case void 0:if(k.length<1)throw new Error('An "and" operator requires at least one condition');ue=!0;break;case"or":if(k.length<2)throw new Error('An "or" operator requires at least two conditions');break;default:throw new Error("Invalid operator "+se)}let pe=ue&&{},rt;for(let xe of k){if(xe.conditions){xe.conditions=O(xe.conditions,xe.operator);continue}let He=xe[0]??xe.attribute,nt=He==null?V:ei(g,He);if(nt){if(ue){let tr=Rs(He),kt=pe[tr];kt?(kt.push(xe),rt=!0):pe[tr]=[xe]}(nt.type||Rb[xe.comparator])&&(xe[1]===void 0?xe.value=M(xe.value,nt):xe[1]=M(xe[1],nt))}else if(He!=null)throw(0,wr.handleHDBError)(new Error,`${He} is not a defined attribute`,404)}if(m.enforceExecutionOrder)return k;if(rt)for(let xe in pe){let He=pe[xe],nt=He.length;if(nt>1)for(let tr=0;tr<nt;tr++){let kt=He[tr];if(kt.comparator==="ge"||kt.comparator==="greater_than_equal")for(let fn=0;fn<nt;fn++){let di=He[fn];(di.comparator==="le"||di.comparator==="less_than_equal")&&(kt.comparator="between",kt.value=[kt.value,di.value],k.splice(k.indexOf(di),1))}if(kt.comparator==="equals"||!kt.comparator){for(let fn=0;fn<nt;fn++)if(fn!==tr){let di=He[fn];k.splice(k.indexOf(di),1)}break}}}return k}a(O,"prepareConditions");function P(k,se){if(m.enforceExecutionOrder)return k;for(let ue of k)ue.conditions&&(ue.conditions=P(ue.conditions,ue.operator));return k.length>1&&se!=="or"?(0,qq.sortBy)(k,im(ve)):k}a(P,"orderConditions");function M(k,se){return Array.isArray(k)?k.map(ue=>hp(ue,se)):hp(k,se)}a(M,"coerceTypedValues");let L=m.operator;(b.length>0||L)&&(b=O(b,L));let B=typeof m.sort=="object"&&m.sort,Y;if(B&&L!=="or"){let k=B.attribute;if(y=b.find(se=>Rs(se.attribute)===Rs(k)),!y){let se=ei(g,k);if(!se)throw(0,wr.handleHDBError)(new Error,`${Array.isArray(k)?k.join("."):k} is not a defined attribute`,404);if(se.indexed)y={attribute:k,comparator:"sort"},b.push(y);else if(b.length===0&&!m.allowFullScan)throw(0,wr.handleHDBError)(new Error,`${Array.isArray(k)?k.join("."):k} is not indexed and not combined with any other conditions`,404)}y&&(y.descending=!!B.descending)}b=P(b,L),B&&(y&&b[0]===y?B.next&&(Y={dbOrderedAttribute:B.attribute,attribute:B.next.attribute,descending:B.next.descending,next:B.next.next}):(y&&b.splice(b.indexOf(y),1),Y=B));let K=m.select;if(b.length===0&&(b=[{attribute:t,comparator:"greater_than",value:!0}]),m.explain)return{conditions:b,operator:L,postOrdering:Y,selectApplied:!!K};let Te=w.useReadTxn(),j=Ab(b,L,ve,Te,m,R,(k,se)=>te(k,K,R,Te,se),C),Ie=m.ensureLoaded!==!1;Y||(j=x(j));let he=ve.transformEntryForSelect(K,R,Te,C,Ie,!0),De=ve.transformToOrderedSelect(j,K,Y,Te,R,he);function x(k){return m.offset||m.limit!==void 0?k.slice(m.offset,m.limit!==void 0?(m.offset||0)+m.limit:void 0):k}return a(x,"applyOffset"),Y&&(De=x(De)),De.onDone=()=>{De.onDone=null,w.doneReadTxn()},De.selectApplied=!0,De.getColumns=()=>{if(K){let k=[];for(let se of K)se==="*"?k.push(...g.map(ue=>ue.name)):k.push(se.name||se);return k}return g.filter(k=>!k.computed&&!k.relationship).map(k=>k.name)},De}static transformToOrderedSelect(m,R,w,b,y,C){let O=new e_;if(w){m=te(m,R,b,y,null);let P;O.iterate=function(){let L,B=m[Symbol.asyncIterator]?m[Symbol.asyncIterator]():m[Symbol.iterator](),Y,K=w.dbOrderedAttribute,Te,j,Ie=!0;function he(x){let k=x.next&&he(x.next),se=x.descending;return(ue,pe)=>{let rt=Ho(ue,x.attribute,b),xe=Ho(pe,x.attribute,b),He=se?(0,Qa.compareKeys)(xe,rt):(0,Qa.compareKeys)(rt,xe);return He===0?k?.(ue,pe)||0:He}}a(he,"createComparator");let De=he(w);return{async next(){let x;if(L)if(x=L.next(),x.done){if(Y)return O.onDone&&O.onDone(),x}else return{value:await C.call(this,x.value)};P=[],Te&&P.push(Te);do if(x=await B.next(),x.done){if(Y=!0,P.length)break;return O.onDone&&O.onDone(),x}else{let k=x.value;if(k?.then&&(k=await k),K){let se=Ho(k,K,b);if(Ie)Ie=!1,j=se;else if(se!==j){j=se,Te=k;break}}P.push(k)}while(!0);return w.isGrouped,P.sort(De),L=P[Symbol.iterator](),x=L.next(),x.done?(O.onDone&&O.onDone(),x):{value:await C.call(this,x.value)}},return(){O.onDone&&O.onDone(),B.return()},throw(){O.onDone&&O.onDone(),B.throw()}}};let M=a(L=>{if(typeof R=="object"&&Array.isArray(L.attribute))for(let B=0;B<R.length;B++){let Y=R[B],K;if(Y.name===L.attribute[0]){for(K=Y.sort||(Y.sort={});K.next;)K=K.next;K.attribute=L.attribute.slice(1),K.descending=L.descending}else Y===L.attribute[0]&&(R[B]=K={name:Y,sort:{attribute:L.attribute.slice(1),descending:L.descending}})}L.next&&M(L.next)},"applySortingOnSelect");M(w)}else O.iterate=(m[Symbol.asyncIterator]||m[Symbol.iterator]).bind(m),O=O.map(C);return O}static transformEntryForSelect(m,R,w,b,y,C){if(m&&(m===t||m?.length===1&&m[0]===t&&Array.isArray(m))){let L=a(B=>(R?.transaction?.stale&&(R.transaction.stale=!1),B?.key??B),"transform");return m===t?L:m.asArray?B=>[L(B)]:B=>({[t]:L(B)})}let O;y&&N&&!(typeof m=="string"?[m]:m)?.every(L=>{let B;return typeof L=="object"?B=L.name:B=L,r[B]||B===t})&&(O=!0);let P,M=a(function(L){let B;if(R?.transaction?.stale&&(R.transaction.stale=!1),L!=null){if(Vi=L,B=L.value||L.deref?.(),!B&&(L.key===void 0||L.deref)){if(L=rc(L.key??L,R,{transaction:w,lazy:m?.length<4},this?.isSync,Y=>Y),L?.then)return L.then(M.bind(this));B=L?.value}if(O&&L?.metadataFlags&(Ya|vf)||L?.expiresAt&&L?.expiresAt<Date.now()){let Y=nc(L.key??L,L,R);if(Y?.then)return Y.then(M)}}if(B==null)return C?Ka.SKIP:B;if(m&&!(m[0]==="*"&&m.length===1)){let Y,K=a((j,Ie)=>{let he;typeof j=="object"?he=j.name:he=j;let De=Gr?.[he],x;if(De){let k=b?.[he];if(k)if(k.hasMappings){let ue=De.from?B[De.from]:Rs(L.key);x=k.get(ue),x||(x=[])}else x=k.fromRecord?.(B);else x=De(B,R,L);let se=a(ue=>{if(ue&&typeof ue=="object"){let pe=De.definition?.tableClass||ve;P||(P={});let rt=P[he]||(P[he]=pe.transformEntryForSelect(he===j?null:j.select||(Array.isArray(j)?j:null),R,w,k,y));if(Array.isArray(ue)){let xe=[],He=pe.transformToOrderedSelect(ue,j.select,typeof j.sort=="object"&&j.sort,R,w,rt)[this.isSync?Symbol.iterator:Symbol.asyncIterator](),nt=a(kt=>{for(;!kt.done;){if(kt?.then)return kt.then(nt);xe.push(kt.value),kt=He.next()}Ie(xe,he)},"nextValue"),tr=nt(He.next());tr&&(Y||(Y=[]),Y.push(tr));return}else if(ue=rt.call(this,ue),ue?.then){Y||(Y=[]),Y.push(ue.then(xe=>Ie(xe,he)));return}}Ie(ue,he)},"handleResolvedValue");x?.then?(Y||(Y=[]),Y.push(x.then(se))):se(x);return}else x=B[he],x&&typeof x=="object"&&he!==j&&(x=ve.transformEntryForSelect(j.select||j,R,w,null)({value:x}));Ie(x,he)},"selectAttribute"),Te;if(typeof m=="string")K(m,j=>{Te=j});else if(Array.isArray(m))if(m.asArray)Te=[],m.forEach((j,Ie)=>{j==="*"?m[Ie]=B:K(j,he=>Te[Ie]=he)});else{Te={};let j=m.forceNulls;for(let Ie of m)if(Ie==="*")for(let he in B)Te[he]=B[he];else K(Ie,(he,De)=>{he===void 0&&j&&(he=null),Te[De]=he})}else throw new wr.ClientError("Invalid select"+m);return Y?Promise.all(Y).then(()=>Te):Te}return B},"transform");return M}async subscribe(m){if(!l)throw new Error("Can not subscribe to a table without an audit log");p||dt({table:s,database:c,schemaDefined:d,attributes:g,audit:!0}),m||(m={});let R=!m.rawEvents,w=DR(ve,this[Ye]??null,function(O,P,M,L){try{let B=P.getValue?.(i,R),Y=P.type;if(!B&&P.type==="patch"&&R){let K=i.getEntry(O);K?.version===P.version?B=K.value:B=P.getValue?.(i,!0,M),Y="put"}this.send({id:O,timestamp:M,value:B,version:P.version,type:Y,beginTxn:L})}catch(B){qe.default.error?.(B)}},m.startTime||0,m);this[Ns]&&(w.includeDescendants=!0,m.onlyChildren&&(w.onlyChildren=!0)),m.supportsTransactions&&(w.supportsTransactions=!0);let b=this[Ye],y=m.previousCount;y>1e3&&(y=1e3);let C=m.startTime;if(this[Ns]){if(C){if(y)throw new wr.ClientError("startTime and previousCount can not be combined for a table level subscription");for(let{key:O,value:P}of l.getRange({start:C,exclusiveStart:!0})){let M=Lt(P);if(M.tableId!==n)continue;let L=M.recordId;if(b==null||Fq(b,L)){let B=M.getValue(i,R,O);w.send({id:L,timestamp:O,value:B,version:M.version,type:M.type})}w.startTime=O}}else if(y){let O=[];for(let{key:P,value:M}of l.getRange({start:"z",end:!1,reverse:!0}))try{let L=Lt(M);if(L.tableId!==n)continue;let B=L.recordId;if(b==null||Fq(b,B)){let Y=L.getValue(i,R,P);if(O.push({id:B,timestamp:P,value:Y,version:L.version,type:L.type}),--y<=0)break}}catch(L){qe.default.error?.("Error getting history entry",P,L)}for(let P=O.length;P>0;)w.send(O[--P]);O[0]&&(w.startTime=O[0].timestamp)}else if(!m.omitCurrent)for(let{key:O,value:P,version:M,localTime:L}of i.getRange({start:b??!1,end:b==null?void 0:[b,Qa.MAXIMUM_KEY],versions:!0}))P&&w.send({id:O,timestamp:L,value:P,version:M,type:"put"})}else{y&&!C&&(C=0);let O=this[Ir]?.localTime;if(O===wS&&(i.cache?.delete(b),this[Ir]=i.getEntry(b),qe.default.trace?.("re-retrieved record",O,this[Ir]?.localTime),O=this[Ir]?.localTime),qe.default.trace?.("Subscription from",C,"from",b,O),C<O){let P=[],M=O;do{let L=l.get(M);if(L){m.omitCurrent=!0;let B=Lt(L),Y=B.getValue(i,R,M);R&&(B.type="put"),P.push({id:b,value:Y,timestamp:M,...B}),M=B.previousLocalTime}else break;y&&y--}while(M>C&&y!==0);for(let L=P.length;L>0;)w.send(P[--L]);w.startTime=O}!m.omitCurrent&&this.doesExist()&&w.send({id:b,timestamp:O,value:this[Ce],version:this[Bf],type:"put"})}return m.listener&&w.on("data",m.listener),w}doesExist(){return!!(this[Ce]||this[Uf])}publish(m,R){this._writePublish(m,R)}_writePublish(m,R){let w=Dr(this[Me]),b=this[Ye]||null;b!=null&&li(b);let y=this[Me];w.addWrite({key:b,store:i,entry:this[Ir],nodeName:y?.nodeName,validate:()=>{y?.source||(w.checkOverloaded(),this.validate(m))},before:je.publish?.bind(this,y,b,m),beforeIntermediate:ye.publish?.bind(this,y,b,m),commit:(C,O,P)=>{O===void 0&&S&&!p&&Fe(),qe.default.trace?.(`Publishing message to id: ${b}, timestamp: ${new Date(C).toISOString()}`),T(b,O?.value??null,O,O?.version||C,0,!0,{user:y?.user,residencyId:R?.residencyId,expiresAt:y?.expiresAt,nodeId:R?.nodeId},"message",!1,m)}})}validate(m,R){let w,b=a((y,C,O)=>{if(C.type&&y!=null)if(R&&y.__op__&&(y=y.value),C.properties){typeof y!="object"&&(w||(w=[])).push(`Value ${Is(y)} in property ${O} must be an object${C.type?" ("+C.type+")":""}`);let P=C.properties;for(let M=0,L=P.length;M<L;M++){let B=P[M],Y=b(y[B.name],B,O+"."+B.name);Y&&(y[B.name]=Y)}if(C.sealed&&y!=null&&typeof y=="object")for(let M in y)P.find(L=>L.name===M)||(w||(w=[])).push(`Property ${M} is not allowed within object in property ${O}`)}else switch(C.type){case"Int":(typeof y!="number"||y>>0!==y)&&(w||(w=[])).push(`Value ${Is(y)} in property ${O} must be an integer (from -2147483648 to 2147483647)`);break;case"Long":(typeof y!="number"||!(Math.floor(y)===y&&Math.abs(y)<=9007199254740992))&&(w||(w=[])).push(`Value ${Is(y)} in property ${O} must be an integer (from -9007199254740992 to 9007199254740992)`);break;case"Float":typeof y!="number"&&(w||(w=[])).push(`Value ${Is(y)} in property ${O} must be a number`);break;case"ID":typeof y=="string"||y?.length>0&&y.every?.(P=>typeof P=="string")||(w||(w=[])).push(`Value ${Is(y)} in property ${O} must be a string, or an array of strings`);break;case"String":typeof y!="string"&&(w||(w=[])).push(`Value ${Is(y)} in property ${O} must be a string`);break;case"Boolean":typeof y!="boolean"&&(w||(w=[])).push(`Value ${Is(y)} in property ${O} must be a boolean`);break;case"Date":if(!(y instanceof Date)){if(typeof y=="string"||typeof y=="number")return new Date(y);(w||(w=[])).push(`Value ${Is(y)} in property ${O} must be a Date`)}break;case"BigInt":if(typeof y!="bigint"){if(typeof y=="string"||typeof y=="number")return BigInt(y);(w||(w=[])).push(`Value ${Is(y)} in property ${O} must be a bigint`)}break;case"Bytes":y instanceof Uint8Array||(w||(w=[])).push(`Value ${Is(y)} in property ${O} must be a Buffer or Uint8Array`);break;case"array":if(Array.isArray(y)){if(C.elements)for(let P=0,M=y.length;P<M;P++){let L=y[P],B=b(L,C.elements,O+"[*]");B&&(y[P]=B)}}else(w||(w=[])).push(`Value ${Is(y)} in property ${O} must be a Buffer or Uint8Array`);break}C.nullable===!1&&y==null&&(w||(w=[])).push(`Property ${O} is required (and not does not allow null values)`)},"validateValue");for(let y=0,C=g.length;y<C;y++){let O=g[y];if(!(O.relationship||O.computed)&&(!R||O.name in m)){let P=b(m[O.name],O,O.name);P&&(m[O.name]=P)}}if(f)for(let y in m)g.find(C=>C.name===y)||(w||(w=[])).push(`Property ${y} is not allowed`);if(w)throw new wr.ClientError(w.join(". "))}getUpdatedTime(){return this[Bf]}wasLoadedFromSource(){return N?!!this[dO]:void 0}static async addAttributes(m){let R=g.slice(0);for(let w of m){if(!w.name)throw new wr.ClientError("Attribute name is required");if(w.name.match(/[`/]/))throw new wr.ClientError("Attribute names cannot include backticks or forward slashes");R.push(w)}return dt({table:s,database:c,schemaDefined:d,attributes:R}),ve.indexingOperation}static async removeAttributes(m){let R=g.filter(w=>!m.includes(w.name));return dt({table:s,database:c,schemaDefined:d,attributes:R}),ve.indexingOperation}static getRecordCount(m){let R=i.getStats().entryCount,w=5e3,b=1e3,y;R>w&&!m?.exactCount&&(y=b);let C=0;for(let{value:O}of i.getRange({start:!0,lazy:!0,limit:y}))O!=null&&C++;if(y){let O=C;C=0;for(let{value:Ie}of i.getRange({start:"\uFFFF",reverse:!0,lazy:!0,limit:y}))Ie!=null&&C++;let P=y*2,M=(C+O)/P,L=Math.pow((C-O+1)/y/2,2)+M*(1-M)/P,B=Math.max(Math.sqrt(L)*R,1),Y=Math.round(M*R),K=Math.max(Y-1.96*B,0),Te=Math.min(Y+1.96*B,R),j=Math.pow(10,Math.round(Math.log10(B)));return j>Y&&(j=j/10),C=Math.round(Y/j)*j,{recordCount:C,estimatedRange:[Math.round(K),Math.round(Te)]}}return{recordCount:C}}static updatedAttributes(){Gr=this.propertyResolvers={$id:(m,R,w)=>({value:w.key}),$updatedtime:(m,R,w)=>w.version,$record:(m,R,w)=>w?{value:m}:m};for(let m of this.attributes){m.resolve=null;let R=m.relationship,w=m.computed;if(R)if(m.indexed&&console.error("A relationship property can not be directly indexed, (but you may want to index the foreign key attribute)"),w&&console.error("A relationship property is already computed and can not be combined with a computed function (the relationship will be given precedence)"),Yl=!0,R.to)m.elements?.definition?(Gr[m.name]=m.resolve=(b,y,C)=>{let O=b[R.from?R.from:t],P=m.elements.definition.tableClass;return C?Sl({attribute:R.to,value:O},Dr(y).getReadTxn(),!1,P,!1).asArray:P.search([{attribute:R.to,value:O}],y).asArray},m.set=()=>{throw new Error("Setting a one-to-many relationship property is not supported")},m.resolve.definition=m.elements.definition,R.from&&(m.resolve.from=R.from)):console.error(`The one-to-many/many-to-many relationship property "${m.name}" in table "${s}" must have an array type referencing a table as the elements`);else if(R.from){let b=m.definition||m.elements?.definition;b?(Gr[m.name]=m.resolve=(y,C,O)=>{let P=y[R.from];if(P!==void 0){if(m.elements){let M,L=P.map(B=>{let Y=O?b.tableClass.primaryStore.getEntry(B,{transaction:Dr(C).getReadTxn()}):b.tableClass.get(B,C);return Y?.then&&(M=!0),Y});return R.filterMissing?M?Promise.all(L).then(B=>B.filter(Gq)):L.filter(Gq):M?Promise.all(L):L}return O?b.tableClass.primaryStore.getEntry(P,{transaction:Dr(C).getReadTxn()}):b.tableClass.get(P,C)}},m.set=(y,C)=>{if(Array.isArray(C)){let O=C.map(P=>P[Ye]||P[b.tableClass.primaryKey]);y[R.from]=O}else{let O=C[Ye]||C[b.tableClass.primaryKey];y[R.from]=O}},m.resolve.definition=m.definition||m.elements?.definition,m.resolve.from=R.from):console.error(`The relationship property "${m.name}" in table "${s}" must be a type that references a table`)}else console.error(`The relationship directive on "${m.name}" in table "${s}" must use either "from" or "to" arguments`);else w&&(typeof w.from=="function"&&this.setComputedAttribute(m.name,w.from),Gr[m.name]=m.resolve=(b,y,C)=>{let O=typeof w.from=="string"?b[w.from]:b,P=this.userResolvers[m.name];if(P)return P(O,y,C);qe.default.warn(`Computed attribute "${m.name}" does not have a function assigned to it. Please use setComputedAttribute('${m.name}', resolver) to assign a resolver function.`),this.userResolvers[m.name]=()=>{}})}fp(this,this)}static setComputedAttribute(m,R){let w=ei(g,m);if(!w){console.error(`The attribute "${m}" does not exist in the table "${s}"`);return}if(!w.computed){console.error(`The attribute "${m}" is not defined as computed in the table "${s}"`);return}this.userResolvers[m]=R}static async deleteHistory(m=0){let R;for(let{key:w,value:b}of l.getRange({start:0,end:m}))await xf(),Lt(b).tableId===n&&(R=l.remove(w));await R}static async*getHistory(m=0,R=1/0){for(let{key:w,value:b}of l.getRange({start:m,end:R})){await xf();let y=Lt(b);y.tableId===n&&(yield{id:y.recordId,localTime:w,version:y.version,type:y.type,value:y.getValue(i,!0,w),user:y.user,operation:y.originatingOperation})}}static async getHistoryOfRecord(m){let R=[];if(m==null)throw new Error("An id is required");let w=i.getEntry(m);if(!w)return R;let b=w.localTime;if(!b)throw new Error("The entry does not have a local audit time");let y=0;do{await xf();let C=l.get(b);if(C){let O=Lt(C);R.push({id:O.recordId,localTime:b,version:O.version,type:O.type,value:O.getValue(i,!0,b),user:O.user}),b=O.previousLocalTime}else break}while(y<1e3&&b);return R.reverse()}static cleanup(){ne?.remove()}}ve.updatedAttributes();let kp=ve.prototype;return kp[fle]=!0,_&&ve.setTTLExpiration(_/1e3),F&&Ee(),ve;function Yi(q,m,R){let w;for(let b in r){let y=r[b],C=y.isIndexing,O=Gr[b],P=R&&(O?O(R):R[b]),M=m&&(O?O(m):m[b]);if(P===M&&!C)continue;w=!0;let L=y.indexNulls,B=(0,Hf.getIndexedValues)(P,L),Y=(0,Hf.getIndexedValues)(M,L);if(Y?.length>0){let K=new Set(Y);if(B=B?B.filter(Te=>{if(K.has(Te))K.delete(Te);else return!0}):[],Y=Array.from(K),(Y.length>0||B.length>0)&&xq){let Te=Y.concat(B).map(j=>({key:j,value:q}));y.prefetch(Te,kq)}for(let Te=0,j=Y.length;Te<j;Te++)y.remove(Y[Te],q)}else B?.length>0&&xq&&y.prefetch(B.map(K=>({key:K,value:q})),kq);if(B)for(let K=0,Te=B.length;K<Te;K++)y.put(B[K],q)}return w}a(Yi,"updateIndices");function li(q){switch(typeof q){case"number":return!0;case"string":if(q.length<659)return!0;if(q.length>Hq)throw new Error("Primary key size is too large: "+q.length);break;case"object":if(q===null)throw new Error("Invalid primary key of null");break;case"bigint":if(q<2n**64n&&q>-(2n**64n))return!0;break;default:throw new Error("Invalid primary key type: "+typeof q)}if((0,Qa.writeKey)(q,Ele,0)>Hq)throw new Error("Primary key size is too large: "+q.length);return!0}a(li,"checkValidId");function rc(q,m,R,w,b){if(ve.getResidencyById&&R.ensureLoaded){let C=ve.getResidencyById(q);if(C&&!C.includes(server.hostname))return A({key:q,residency:C}).then(b,O=>{qe.default.error?.("Unable to retrieve data",O)})}let y=a(()=>{if(m?.transaction?.stale&&(m.transaction.stale=!1),R.transaction?.isDone)return b(null,q);let C=i.getEntry(q,R);return C?.residencyId&&C.metadataFlags&Ya&&A&&R.ensureLoaded?A(C).then(O=>b(O,q)):(C&&m&&(C?.version>(m.lastModified||0)&&(m.lastModified=C.version),C?.localTime&&!m.lastRefreshed&&(m.lastRefreshed=C.localTime)),b(C,q))},"whenPrefetched");return w?y():le>0?(le--,y()):new Promise((C,O)=>{le===0?(le--,i.prefetch([q],()=>{P(),M()})):(ee.push(q),Z.push(M),ee.length>Kl&&(le--,P()));function P(){if(ee.length>0){let L=Z;i.prefetch(ee,()=>{le===-1?P():le++;for(let B of L)B()}),ee=[],Z=[],fe>2&&fe--}else le=fe,fe<t_&&fe++}a(P,"prefetch");function M(){try{C(y())}catch(L){O(L)}}a(M,"load")})}a(rc,"loadLocalRecord");function ui(q){if(!q?.role)return;let m=q.role.permission;if(m.super_user)return hle;let R=m[c],w,b=R?.tables;if(b)return b[s];if(c==="data"&&(w=m[s])&&!w.tables)return w}a(ui,"getTablePermissions");function nc(q,m,R,w){if(N){let b=!1;if(R.noCache?b=!0:(m?(!m.value||m.metadataFlags&(Ya|vf)||m.expiresAt&&m.expiresAt<Date.now())&&(b=!0):b=!0,Ln(!b,"cache-hit",s)),b){let y=Je(q,m,R).then(C=>(C?.value?.[Ce]&&qe.default.error?.("Can not assign a record with a record property"),R&&(C?.version>(R.lastModified||0)&&(R.lastModified=C.version),R.lastRefreshed=Date.now()),C));if(R?.onlyIfCached||m?.value&&w?.allowStaleWhileRevalidate?.(m,q)){if(y.catch(C=>qe.default.warn?.(C)),R?.onlyIfCached&&!w.doesExist())throw new wr.ServerError("Entry is not cached",504);return}else return y}}else if(m?.value&&m.expiresAt&&m.expiresAt<Date.now())return ve.evict(m.key,m.value,m.version),m.value=null,{then(b){return b(m)}}}a(nc,"ensureLoadedFromSource");function Dr(q){let m=q?.transaction;if(m){if(!m.lmdbDb)return m.lmdbDb=i,m;do{if(m.lmdbDb?.path===i.path)return m;let R=m.next;if(!R)return m=m.next=new ia,m.lmdbDb=i,m;m=R}while(!0)}else return new dE}a(Dr,"txnForContext");function Ho(q,m,R){if(!q)return;Vi=q;let w=q.value||q.deref?.()||(Vi=i.getEntry(q.key))?.value;if(typeof m=="object"){let y=Gr,C=w;for(let O=0,P=m.length;O<P;O++){let M=m[O],L=y?.[M];C=L&&C?L(C,R,!0)?.value:C?.[M],y=L?.definition?.tableClass?.propertyResolvers}return C}let b=Gr[m];return b?b(w,R):w[m]}a(Ho,"getAttributeValue");function te(q,m,R,w,b){let y=b?.length,C={transaction:w,lazy:y>0||typeof m=="string"||m?.length<4,alwaysPrefetch:!0},O;function P(M,L){let B=M?.value;if(!B)return Ka.SKIP;for(let Y=0;Y<y;Y++)if(!O?.includes(Y)&&!b[Y](B,M))return Ka.SKIP;return L!==void 0&&(M.key=L),M}if(a(P,"processEntry"),y>0||!q.hasEntries){let M=q.map(L=>{if(O=null,typeof L=="object"&&L?.key!==void 0)return y>0?P(L):L;if(L==null)return Ka.SKIP;for(let B=0;B<y;B++){let K=b[B].idFilter;if(K){if(!K(L))return Ka.SKIP;O||(O=[]),O.push(B)}}return rc(L,R,C,!1,P)});return Array.isArray(q)&&(M=M.filter(L=>L!==Ka.SKIP)),M.hasEntries=!0,M}return q}a(te,"transformToEntries");function me(q,m,R=server.replication?.getThisNodeId(l)){if(q<=m?.version){if(m?.version===q&&R!==void 0){let w=server.replication?.exportIdMapping(l),b=m.localTime,y=l.get(b);if(y){let C,O,P=Lt(y);for(let M in w)w[M]===R&&(C=M),w[M]===P.nodeId&&(O=M);if(C>O)return!1}}return!0}return!1}a(me,"precedesExistingVersion");async function Je(q,m,R){let w=m?.metadataFlags,b=m?.version,y,C;if(!i.attemptLock(q,b,()=>{clearTimeout(C);let L=i.getEntry(q);!L||!L.value||L.metadataFlags&(Ya|vf)?y(Je(q,i.getEntry(q),R)):y(L)}))return new Promise(L=>{y=L,C=setTimeout(()=>{i.unlock(q,b)},dle)});let O=m?.value,P={requestContext:R,replacingRecord:O,replacingEntry:m,replacingVersion:b,noCacheStore:!1,source:null,resourceCache:R?.resourceCache},M=R?.responseHeaders;return new Promise((L,B)=>{let Y;_O(Tt(P,async K=>{let Te=performance.now(),j,Ie,he;try{for(let se of ve.sources)if(se.get&&(!se.get.reliesOnPrototype||se.prototype.get)){if(se.available?.(m)===!1)continue;if(P.source=se,j=await se.get(q,P),j)break}he=w&Ya;let x=P.lastModified||he&&b;Ie=he||x>b||!O,x||(x=(0,Hf.getNextMonotonicTime)());let k=performance.now()-Te;if(an(k,"cache-resolution",s),M&&kA(M,"Server-Timing",`cache-resolve;dur=${k.toFixed(2)}`,!0),K.timestamp=x,_&&!P.expiresAt&&(P.expiresAt=Date.now()+_),j){if(typeof j!="object")throw new Error("Only objects can be cached and stored in tables");if(j.status>0&&j.headers)if(j.status>=300)if(j.status===304)j=O,x=b;else throw new wr.ServerError(j.body||"Error from source",j.status);else j=j.body;typeof j.toJSON=="function"&&(j=j.toJSON()),t&&j[t]!==q&&(j[t]=q)}Y=!0,L({key:q,version:x,value:j})}catch(x){x.message+=` while resolving record ${q} for ${s}`,O&&((x.code==="ECONNRESET"||x.code==="ECONNREFUSED"||x.code==="EAI_AGAIN")&&!R?.mustRevalidate||R?.staleIfError&&(x.statusCode===500||x.statusCode===502||x.statusCode===503||x.statusCode===504))?(L({key:q,version:b,value:O}),qe.default.trace?.(x.message,"(returned stale record)")):B(x),P.transaction.abort();return}if(R?.noCacheStore||P.noCacheStore){P.transaction.abort();return}Dr(P).addWrite({key:q,store:i,entry:m,nodeName:"source",commit:(x,k)=>{if(k?.version!==b)return;let se=Yi(q,O,j);j?(ye.put?.(P,q,j),qe.default.trace?.(`Writing resolved record from source with id: ${q}, timestamp: ${new Date(x).toISOString()}`),T(q,j,k,x,0,p&&Ie||null,{user:P?.user,expiresAt:P.expiresAt},"put",!!he)):k&&(ye.delete?.(P,q),qe.default.trace?.(`Deleting resolved record from source with id: ${q}, timestamp: ${new Date(x).toISOString()}`),p||S?T(q,null,k,x,0,p&&Ie||null,{user:P?.user},"delete",!!he):i.remove(q,b))}})}),()=>{i.unlock(q,b)},K=>{i.unlock(q,b),Y&&qe.default.error?.("Error committing cache update",K)})})}a(Je,"getFromSource");function Ae(q){if(!q||q.user?.role?.permission?.super_user)return!0;if(q.replicateTo)throw new wr.ClientError("Can not specify replication parameters without super user permissions",403);if(q.replicatedConfirmation)throw new wr.ClientError("Can not specify replication confirmation without super user permissions",403);return!0}a(Ae,"checkContextPermissions");function Fe(){if(Ht!==Bo&&(Bo=Ht,(0,Wa.getWorkerIndex)()===(0,Wa.getWorkerCount)()-1)){if(tc&&clearTimeout(tc),!Ht)return;let q=new Date;q.setMonth(0),q.setDate(1),q.setHours(0),q.setMinutes(0),q.setSeconds(0);let m=Math.ceil((Date.now()-q.getTime())/Ht)*Ht+q.getTime(),R=a(w=>{qe.default.trace?.(`Scheduled next cleanup scan at ${new Date(w)}ms`),tc=setTimeout(()=>v=v.then(async()=>{if(R(Math.max(w+Ht,Date.now())),i.rootStore.status!=="open"){clearTimeout(tc);return}let b=50,y=new Array(b),C=0;qe.default.info?.(`Starting cleanup scan for ${s}`);try{let O=0;for(let{key:P,value:M,version:L,expiresAt:B}of i.getRange({start:!1,snapshot:!1,versions:!0,lazy:!0})){let Y;M===null&&!p&&L+ule<Date.now()?Y=i.remove(P,L):B&&B+h<Date.now()&&(Y=ve.evict(P,M,L),O++),Y&&(await y[C],y[C]=Y.catch(K=>{qe.default.error?.("Cleanup error",K)}),++C>=b&&(C=0)),await xf()}qe.default.info?.(`Finished cleanup scan for ${s}, evicted ${O} entries`)}catch(O){qe.default.warn?.(`Error in cleanup scan for ${s}:`,O)}}),Math.min(w-Date.now(),2147483647)).unref()},"startNextTimer");R(m)}}a(Fe,"scheduleCleanup");function tt(){ne=l?.addDeleteRemovalCallback(n,q=>{let m=i.getEntry(q);m?.value===null&&i.remove(q,m.version)})}a(tt,"addDeleteRemoval");function Ee(){(0,Wa.getWorkerIndex)()===0&&setInterval(async()=>{if(!$i){$i=!0;try{let q=F.name,m=r[q];if(!m)throw new Error(`expiresAt attribute ${F} must be indexed`);for(let R of m.getRange({start:!0,values:!1,end:Date.now(),snapshot:!1})){for(let w of m.getValues(R)){let b=i.getEntry(w);b?.value?b.value[q]<Date.now()&&ve.evict(w,b.value,b.version):i.ifVersion(w,b?.version,()=>m.remove(R,w))}await xf()}}catch(q){qe.default.error?.("Error in evicting old records",q)}finally{$i=!1}}},lle).unref()}a(Ee,"runRecordExpirationEviction");function Dt(q){if(q){let m=q.join(","),R=u.get([Symbol.for("residency_by_set"),m]);return R||(u.put([Symbol.for("residency_by_set"),m],R=Math.floor(Math.random()*2147483647)),u.put([Symbol.for("residency_by_id"),R],q),R)}}a(Dt,"getResidencyId")}function fO(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 kq(){}function mle(e){Vq=e}function hp(e,t){let r=t?.type;return e===null?e:e===""&&r&&r!=="String"&&r!=="Any"?null:r==="Int"||r==="Long"?e[0]==="$"?parseInt(e.slice(1),36):e==="null"?null:parseInt(e):r==="Float"?e==="null"?null:+e:r==="BigInt"?e==="null"?null:BigInt(e):r==="Boolean"?e==="true"?!0:e==="false"?!1:e:r==="Date"?isNaN(e)?e==="null"?null:(ple.test(e)||(e+="Z"),new Date(e)):new Date(+e):!r||r==="Any"?(0,pp.autoCast)(e):e}function Fq(e,t){if(e==null)return!0;if(!Array.isArray(t))return e===t;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 _O(e,t,r){return e?.then?e.then(t,r):t(e)}function mp(e,t){e[Ir]=t,e[Ce]=t?.value??null,e[Bf]=t?.version}function Gq(e){return e!=null}function Is(e){try{return JSON.stringify(e)}catch{return e}}function Sle(e){let t=process.pid;return e.env.readerList().slice(1).some(r=>+r.match(/\d+/)?.[0]!=t)}var os,Ka,Hf,qq,Bl,wr,kf,Ff,qe,Qa,Wa,pp,cle,Vq,lle,ule,xq,dle,Bf,fle,Ir,Uf,Bq,_le,dO,Ya,vf,Ele,Hq,hle,qbe,ple,xf,gm=Oe(()=>{os=U(H()),Ka=require("lmdb"),Hf=U(hn()),qq=require("lodash");ls();fE();Bl=U(ie());LR();wr=U(ce()),kf=U(pi()),Ff=U(Es());Ne();lf();qe=U(td());hE();oa();Qa=require("ordered-binary"),Wa=U(at());_i();pp=U(re());cc();Bi();ip();Hd();cle=new Uint8Array(9);cle[8]=192;lle=6e4,ule=864e5;Bl.initSync();xq=Bl.get(os.CONFIG_PARAMS.STORAGE_PREFETCHWRITES),dle=1e4,Bf=Symbol.for("version"),fle=Symbol.for("incremental-update"),Ir=Symbol("entry"),Uf=Symbol("is-saving"),Bq=1,_le=2,dO=Symbol("loaded-from-source"),Ya=1,vf=8,Ele=Buffer.allocUnsafeSlow(8192),Hq=1978,hle={read:!0,insert:!0,update:!0,delete:!0,isSuperUser:!0},qbe=(0,pp.convertToMS)(Bl.get(os.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE))||864e5;a(Sp,"makeTable");a(fO,"attributesAsObject");a(kq,"noop");a(mle,"setServerUtilities");ple=/[+-][0-9]{2}:[0-9]{2}|[a-zA-Z]$/;a(hp,"coerceType");a(Fq,"isDescendantId");xf=a(()=>new Promise(setImmediate),"rest");a(_O,"when");a(mp,"updateResource");a(Gq,"exists");a(Is,"stringify");a(Sle,"hasOtherProcesses")});var it={};Ze(it,{database:()=>Nc,databases:()=>Ve,dropDatabase:()=>Og,dropTableMeta:()=>ble,getDatabases:()=>ct,getDefaultCompression:()=>Oh,getTables:()=>Tle,onRemovedDB:()=>ld,onUpdatedTable:()=>ha,readMetaDb:()=>Gf,resetDatabases:()=>Dd,table:()=>dt,tables:()=>pn});function Tle(){return Ap||ct(),pn||{}}function ct(){if(Ap)return Ve;Ap=!0,Fl=new Map;let e=(0,Kt.getHdbBasePath)()&&(0,wt.join)((0,Kt.getHdbBasePath)(),ur.DATABASES_DIR_NAME),t=(0,Kt.get)(ur.CONFIG_PARAMS.DATABASES)||{};if(process.env.SCHEMAS_DATA_PATH&&(t.data={path:process.env.SCHEMAS_DATA_PATH}),e=process.env.STORAGE_PATH||(0,Kt.get)(ur.CONFIG_PARAMS.STORAGE_PATH)||e&&((0,xn.existsSync)(e)?e:(0,wt.join)((0,Kt.getHdbBasePath)(),ur.LEGACY_DATABASES_DIR_NAME)),!e)return;if((0,xn.existsSync)(e))for(let n of(0,xn.readdirSync)(e,{withFileTypes:!0})){let s=(0,wt.basename)(n.name,".mdb");n.isFile()&&(0,wt.extname)(n.name).toLowerCase()===".mdb"&&!t[s]?.path&&Gf((0,wt.join)(e,n.name),null,s)}if((0,xn.existsSync)((0,kl.getBaseSchemaPath)())){for(let n of(0,xn.readdirSync)((0,kl.getBaseSchemaPath)(),{withFileTypes:!0}))if(!n.isFile()){let s=(0,wt.join)((0,kl.getBaseSchemaPath)(),n.name),i=(0,wt.join)((0,kl.getTransactionAuditStoreBasePath)(),n.name);for(let o of(0,xn.readdirSync)(s,{withFileTypes:!0}))if(o.isFile()&&(0,wt.extname)(o.name).toLowerCase()===".mdb"){let c=(0,wt.join)(i,o.name);Gf((0,wt.join)(s,o.name),(0,wt.basename)(o.name,".mdb"),n.name,c,!0)}}}if(t)for(let n in t){let s=t[n],i=s.path;if((0,xn.existsSync)(i))for(let c of(0,xn.readdirSync)(i,{withFileTypes:!0}))c.isFile()&&(0,wt.extname)(c.name).toLowerCase()===".mdb"&&Gf((0,wt.join)(i,c.name),(0,wt.basename)(c.name,".mdb"),n);let o=s.tables;if(o)for(let c in o){let l=o[c],d=(0,wt.join)(l.path,(0,wt.basename)(c+".mdb"));(0,xn.existsSync)(d)&&Gf(d,c,n,null,!0)}}for(let n in Ve){let s=Fl.get(n);if(s){let i=Ve[n];n.includes("delete")&&hr.trace(`defined tables ${Array.from(s.keys())}`);for(let o in i)s.has(o)||(hr.trace(`delete table class ${o}`),delete i[o])}else if(delete Ve[n],n==="data"){for(let i in pn)delete pn[i];delete pn[bp]}}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 Fl=null,Ve}function Dd(){Ap=!1;for(let[,e]of vo)e.needsDeletion=!0;ct();for(let[e,t]of vo)t.needsDeletion&&!e.endsWith("system.mdb")&&(t.close(),vo.delete(e),delete Ve[t.databaseName],Vf.forEach(r=>r(t.databaseName)));return Ve}function Gf(e,t,r=mO,n,s){let i=new EO.default(e,!1);try{let o=vo.get(e);o?o.needsDeletion=!1:(o=(0,Gl.open)(i),vo.set(e,o));let c=new za.default(!1),l=o.dbisDb||(o.dbisDb=o.openDB(Tp.INTERNAL_DBIS_NAME,c)),d=o.auditStore;d||(n?(0,xn.existsSync)(n)&&(i.path=n,d=(0,Gl.open)(i),d.isLegacy=!0):d=sp(o));let u=Wq(r),f=u[bp],E=new Map;for(let{key:_,value:h}of l.getRange({start:!1})){let[p,S]=_.toString().split("/");S===""?S=h.name:S||(S=p,p=t,h.name||(h.name=S,h.indexed=!h.is_hash_attribute)),f?.add(p);let g=E.get(p);g||E.set(p,g={attributes:[]}),(S==null||h.is_hash_attribute)&&(g.primary=h),S!=null&&g.attributes.push(h),Object.defineProperty(h,"key",{value:_,configurable:!0})}for(let[_,h]of E){let{attributes:p,primary:S}=h;if(!S){for(let Z of p)if(Z.is_hash_attribute||Z.isPrimaryKey){S=Z;break}if(!S){hr.fatal(`Unable to find a primary key attribute on table ${_}, with attributes: ${JSON.stringify(p)}`);continue}}let g=u[_],T={},A=[],N,V,v=typeof S.audit=="boolean"?S.audit:(0,Kt.get)(ur.CONFIG_PARAMS.LOGGING_AUDITLOG),J=S.trackDeletes,$=S.expiration,F=S.eviction,ne=S.sealed,ee=S.replicate;if(g)T=g.indices,A=g.attributes,g.schemaVersion++;else{N=S.tableId,N?N>=(l.get(Hl)||0)&&l.putSync(Hl,N+1):(S.tableId=N=l.get(Hl),N||(N=1),l.putSync(Hl,N+1),l.putSync(S.key,S));let Z=new za.default(!S.is_hash_attribute,S.is_hash_attribute);if(Z.compression=S.compression,Z.compression){let le=(0,Kt.get)(ur.CONFIG_PARAMS.STORAGE_COMPRESSION_THRESHOLD)||Kq;Z.compression.threshold=le}V=A_(o.openDB(S.key,Z)),o.databaseName=r,V.rootStore=o,V.tableId=N}for(let Z of p){Z.attribute=Z.name;try{if(!Z.is_hash_attribute&&(Z.indexed||Z.attribute&&!Z.name)){if(!T[Z.name]){let fe=new za.default(!Z.is_hash_attribute,Z.is_hash_attribute);T[Z.name]=o.openDB(Z.key,fe),T[Z.name].indexNulls=Z.indexNulls}let le=A.find(fe=>fe.name===Z.name);le?A.splice(A.indexOf(le),1,Z):A.push(Z)}}catch(le){hr.error("Error trying to update attribute",Z,A,T,le)}}if(!g){g=Qq(u,_,Sp({primaryStore:V,auditStore:d,audit:v,sealed:ne,replicate:ee,expirationMS:$&&$*1e3,evictionMS:F&&F*1e3,trackDeletes:J,tableName:_,tableId:N,primaryKey:S.name,databasePath:s?r+"/"+_:r,databaseName:r,indices:T,attributes:p,schemaDefined:S.schemaDefined,dbisDB:l})),g.schemaVersion=1;for(let Z of qf)Z(g)}}return o}catch(o){throw o.message+=` opening database ${e}`,o}}function Wq(e){let t=Ve[e];if(t||(e==="data"?t=Ve[e]=pn:e==="system"?Object.defineProperty(Ve,"system",{value:t=Object.create(null),configurable:!0}):t=Ve[e]=Object.create(null)),Fl&&!Fl.has(e)){let r=new Set;t[bp]=r,Fl.set(e,r)}return t}function Qq(e,t,r){return e[t]=r,r}function Nc({database:e,table:t}){e||(e=mO),ct();let r=Wq(e),n=(0,wt.join)((0,Kt.getHdbBasePath)(),ur.DATABASES_DIR_NAME),s=(0,Kt.get)(ur.CONFIG_PARAMS.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,Kt.get)(ur.CONFIG_PARAMS.STORAGE_PATH)||((0,xn.existsSync)(n)?n:(0,wt.join)((0,Kt.getHdbBasePath)(),ur.LEGACY_DATABASES_DIR_NAME));let o=(0,wt.join)(n,(i?t:e)+".mdb"),c=vo.get(o);if(!c||c.status==="closed"){let l=new EO.default(o,!1);c=(0,Gl.open)(l),vo.set(o,c)}return c.auditStore||(c.auditStore=sp(c)),c}async function Og(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,vo.delete(r.path),r.status==="open"&&(await r.close(),await $f.remove(r.path));if(r||(r=Nc({database:e,table:null}),r.status==="open"&&(await r.close(),await $f.remove(r.path))),e==="data"){for(let n in pn)delete pn[n];delete pn[bp]}delete Ve[e],Vf.forEach(n=>n(e))}function dt({table:e,database:t,expiration:r,eviction:n,scanInterval:s,attributes:i,audit:o,sealed:c,replicate:l,trackDeletes:d,schemaDefined:u,origin:f}){t||(t=mO);let E=Nc({database:t,table:e}),_=Ve[t];hr.trace(`Defining ${e} in ${t}`);let h=_?.[e];if(E.status==="closed")throw new Error(`Can not use a closed data store for ${e}`);let p,S,g,T;u==null&&(u=!0);let A=new za.default(!1);for(let F of i)F.attribute&&!F.name?(F.name=F.attribute,F.indexed=!0):F.attribute=F.name,F.expiresAt&&(F.indexed=!0);let N,V;if(h){if(p=h.primaryKey,h.primaryStore.rootStore.status==="closed")throw new Error(`Can not use a closed data store from ${e} class`);h.attributes.splice(0,h.attributes.length,...i)}else{let F=E.auditStore;S=i.find(le=>le.isPrimaryKey)||{},p=S.name,S.is_hash_attribute=!0,S.schemaDefined=u,S.compression=Oh(),d&&(S.trackDeletes=!0),o=S.audit=typeof o=="boolean"?o:(0,Kt.get)(ur.CONFIG_PARAMS.LOGGING_AUDITLOG),r&&(S.expiration=r),n&&(S.eviction=n),typeof c=="boolean"&&(S.sealed=c),typeof l=="boolean"&&(S.replicate=l),f&&(S.origins?S.origins.includes(f)||S.origins.push(f):S.origins=[f]),hr.trace(`${e} table loading, opening primary store`);let ne=new za.default(!1,!0);ne.compression=S.compression;let ee=e+"/",Z=A_(E.openDB(ee,ne));E.databaseName=t,Z.rootStore=E,T=E.dbisDb=E.openDB(Tp.INTERNAL_DBIS_NAME,A),Z.tableId=T.get(Hl),Z.tableId||(Z.tableId=1),T.putSync(Hl,Z.tableId+1),S.tableId=Z.tableId,h=Qq(_,e,Sp({primaryStore:Z,auditStore:F,audit:o,sealed:c,replicate:l,trackDeletes:d,expirationMS:r&&r*1e3,evictionMS:n&&n*1e3,primaryKey:p,tableName:e,tableId:Z.tableId,databasePath:t,databaseName:t,indices:{},attributes:i,schemaDefined:u,dbisDB:T})),h.schemaVersion=1,N=!0,$(),T.put(ee,S)}g=h.indices,T=T||(E.dbisDb=E.openDB(Tp.INTERNAL_DBIS_NAME,A)),h.dbisDB=T;let v=[];for(let{key:F,value:ne}of T.getRange({start:!0})){let[ee,Z]=F.toString().split("/");if(Z===""&&(Z=ne.name),Z){if(ee!==e)continue}else Z=ee;if(!i.find(fe=>fe.name===Z)?.indexed&&ne.indexed&&!ne.isPrimaryKey){$(),N=!0,T.remove(F);let fe=h.indices[ee];fe&&v.push(fe)}}let J=[];try{for(let F of i||[]){if(F.relationship)continue;let ne=e+"/"+(F.name||"");Object.defineProperty(F,"key",{value:ne,configurable:!0});let ee=T.get(ne);if(F.isPrimaryKey){if(ee=ee||T.get(ne=e+"/")||{},o!==void 0&&o!==h.audit||c!==void 0&&c!==h.sealed||l!==void 0&&l!==h.replicate||(+r||void 0)!==(+ee.expiration||void 0)||(+n||void 0)!==(+ee.eviction||void 0)){let le=Object.assign({},ee);typeof o=="boolean"&&(o&&h.enableAuditing(o),le.audit=o),r&&(le.expiration=+r),n&&(le.eviction=+n),c!==void 0&&(le.sealed=c),l!==void 0&&(le.replicate=l),N=!0,$(),T.put(ne,le)}continue}ee?.attribute&&!ee.name&&(ee.indexed=!0);let Z=!ee||ee.type!==F.type||ee.indexed!==F.indexed||ee.nullable!==F.nullable||ee.version!==F.version||JSON.stringify(ee.attributes)!==JSON.stringify(F.attributes)||JSON.stringify(ee.elements)!==JSON.stringify(F.elements);if(F.indexed){let le=new za.default(!0,!1),fe=E.openDB(ne,le);(Z||ee.indexingPID&&ee.indexingPID!==process.pid||ee.restartNumber<Yf.workerData?.restartNumber)&&(N=!0,$(),ee=T.get(ne),(Z||ee.indexingPID&&ee.indexingPID!==process.pid||ee.restartNumber<Yf.workerData?.restartNumber)&&(N=!0,F.indexNulls===void 0&&(F.indexNulls=!0),h.primaryStore.getStats().entryCount>0&&(F.lastIndexedKey=ee?.lastIndexedKey??void 0,F.indexingPID=process.pid,fe.isIndexing=!0,Object.defineProperty(F,"dbi",{value:fe}),J.push(F))),T.put(ne,F)),ee?.indexNulls&&F.indexNulls===void 0&&(F.indexNulls=!0),fe.indexNulls=F.indexNulls,g[F.name]=fe}else Z&&(N=!0,$(),T.put(ne,F))}}finally{V&&V()}if(N&&(E.auditStore,h.schemaVersion++,h.updatedAttributes()),hr.trace(`${e} table loading, running index`),J.length>0||v.length>0?h.indexingOperation=Ale(h,J,v):N&&gp.signalSchemaChange(new Rp.SchemaEventMsg(process.pid,"schema-change",h.databaseName,h.tableName)),h.origin=f,N)for(let F of qf)F(h,f!=="cluster");return(r||n||s)&&h.setTTLExpiration({expiration:r,eviction:n,scanInterval:s}),hr.trace(`${e} table loaded`),h;function $(){V||E.transactionSync(()=>({then(F){V=F}}))}a($,"startTxn")}async function Ale(e,t,r){try{hr.info(`Indexing ${e.tableName} attributes`,t);let n=e.schemaVersion;await gp.signalSchemaChange(new Rp.SchemaEventMsg(process.pid,"schema-change",e.databaseName,e.tableName));let s;for(let d of r)s=d.drop();let i,o={},c=0,l=t.length;if(await new Promise(d=>setImmediate(d)),l>0){let d;for(let f of t)(0,Gl.compareKeys)(f.lastIndexedKey,d)<0&&(d=f.lastIndexedKey),f.lastIndexedKey==null&&f.dbi.clearAsync();let u=0;for(let{key:f,value:E,version:_}of e.primaryStore.getRange({start:d,lazy:l<4,versions:!0,snapshot:!1}))if(E){if(u++,s=e.primaryStore.ifVersion(f,_,()=>{for(let h=0;h<l;h++){let p=t[h],S=p.name;try{let g=p.resolve,T=E&&(g?g(E):E[S]),A=(0,$q.getIndexedValues)(T);if(A)for(let N=0,V=A.length;N<V;N++)p.dbi.put(A[N],f)}catch(g){o[S]||(o[S]=!0,hr.error(`Error indexing attribute ${S}`,g))}}}),s.then(()=>u--,h=>{u--,hr.error(h)}),Yf.workerData&&Yf.workerData.restartNumber!==Yq.restartNumber&&(i=!0),++c%100===0||i){for(let h of t)h.lastIndexedKey=f,e.dbisDB.put(h.key,h);if(i)return}u>gle?await s:u>Rle&&await new Promise(h=>setImmediate(h))}for(let f of t)delete f.lastIndexedKey,delete f.indexingPID,f.dbi.isIndexing=!1,s=e.dbisDB.put(f.key,f)}await s,await gp.signalSchemaChange(new Rp.SchemaEventMsg(process.pid,"indexing-finished",e.databaseName,e.tableName)),hr.info(`Finished indexing ${e.tableName} attributes`,t)}catch(n){hr.error("Error in indexing",n)}}function ble({table:e,database:t}){let r=Nc({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 ha(e){return qf.push(e),{remove(){let t=qf.indexOf(e);t>-1&&qf.splice(t,1)}}}function ld(e){return Vf.push(e),{remove(){let t=Vf.indexOf(e);t>-1&&Vf.splice(t,1)}}}function Oh(){let e=(0,Kt.get)(ur.CONFIG_PARAMS.STORAGE_COMPRESSION),t=(0,Kt.get)(ur.CONFIG_PARAMS.STORAGE_COMPRESSION_DICTIONARY),r=(0,Kt.get)(ur.CONFIG_PARAMS.STORAGE_COMPRESSION_THRESHOLD)||Kq,n={startingOffset:32};return t&&(n.dictionary=$f.readFileSync(t)),r&&(n.threshold=r),e&&n}var Kt,Tp,Gl,wt,xn,kl,za,EO,ur,$f,hO,$q,gp,Rp,Yf,hr,Yq,mO,bp,Kq,pn,Ve,Hl,qf,Vf,Ap,vo,Fl,gle,Rle,Ne=Oe(()=>{Kt=U(ie()),Tp=U(Ft()),Gl=require("lmdb"),wt=require("path"),xn=require("fs"),kl=U(ht());gm();za=U(hu()),EO=U(mu()),ur=U(H()),$f=U(require("fs-extra")),hO=require("../index"),$q=U(hn()),gp=U(pi()),Rp=U(Es()),Yf=require("worker_threads"),hr=U(X()),Yq=U(at());_i();cc();mO="data",bp=Symbol("defined-tables"),Kq=((0,Kt.get)(ur.CONFIG_PARAMS.STORAGE_PAGESIZE)||4096)-60;(0,Kt.initSync)();pn=Object.create(null),Ve=Object.create(null);(0,hO._assignPackageExport)("databases",Ve);(0,hO._assignPackageExport)("tables",pn);Hl=Symbol.for("next-table-id"),qf=[],Vf=[],vo=new Map;a(Tle,"getTables");a(ct,"getDatabases");a(Dd,"resetDatabases");a(Gf,"readMetaDb");a(Wq,"ensureDB");a(Qq,"setTable");a(Nc,"database");a(Og,"dropDatabase");a(dt,"table");gle=1e3,Rle=10;a(Ale,"runIndexing");a(ble,"dropTableMeta");a(ha,"onUpdatedTable");a(ld,"onRemovedDB");a(Oh,"getDefaultCompression")});var re=I((Jbe,cV)=>{"use strict";var xo=require("path"),Zq=require("fs-extra"),ln=X(),zq=require("fs-extra"),yp=require("os"),yle=require("net"),Ole=require("recursive-iterator"),Bt=H(),Nle=gN(),jq=require("papaparse"),Op=require("moment"),{inspect:Ile}=require("util"),Jq=require("is-number"),jbe=require("lodash"),wle=require("minimist"),Cle=require("https"),Dle=require("http"),{hdb_errors:Np}=ce(),Lle=/^((\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)))$/,eV=require("util").promisify(setTimeout),Ple=100,Mle=5,Ule="",vle=4,Xq={true:!0,TRUE:!0,FALSE:!1,false:!1,undefined:null,null:null,NULL:null,NaN:NaN};cV.exports={isEmpty:Bn,isEmptyOrZeroLength:ai,arrayHasEmptyValues:Hle,arrayHasEmptyOrZeroLengthValues:kle,buildFolderPath:Fle,isBoolean:tV,errorizeMessage:xle,stripFileExtension:qle,autoCast:Vle,autoCastJSON:rV,autoCastJSONDeep:SO,removeDir:$le,compareVersions:Yle,isCompatibleDataVersion:Kle,escapeRawValue:Wle,unescapeValue:Qle,stringifyProps:zle,timeoutPromise:Jle,isClusterOperation:Zle,getClusterUser:tue,checkGlobalSchemaTable:eue,getHomeDir:sV,getPropsFilePath:jle,promisifyPapaParse:rue,removeBOM:iV,createEventPromise:nue,checkProcessRunning:sue,checkSchemaTableExist:iue,checkSchemaExists:oV,checkTableExists:aV,getStartOfTomorrowInSeconds:oue,getLimitKey:aue,isObject:Gle,isNotEmptyAndHasValue:Ble,autoCasterIsNumberCheck:nV,backtickASTSchemaItems:cue,isPortTaken:Xle,createForkArgs:lue,autoCastBoolean:uue,async_set_timeout:eV,getTableHashAttribute:due,doesSchemaExist:fue,doesTableExist:_ue,stringifyObj:Eue,ms_to_time:hue,changeExtension:mue,getEnvCliRootPath:TO,noBootFile:pue,httpRequest:Sue,transformReq:Tue,convertToMS:gue,PACKAGE_ROOT:Bt.PACKAGE_ROOT};function xle(e){return e instanceof Error?e:new Error(e)}a(xle,"errorizeMessage");function Bn(e){return e==null}a(Bn,"isEmpty");function Ble(e){return!Bn(e)&&(e||e===0||e===""||tV(e))}a(Ble,"isNotEmptyAndHasValue");function ai(e){return Bn(e)||e.length===0||e.size===0}a(ai,"isEmptyOrZeroLength");function Hle(e){if(Bn(e))return!0;for(let t=0;t<e.length;t++)if(Bn(e[t]))return!0;return!1}a(Hle,"arrayHasEmptyValues");function kle(e){if(ai(e))return!0;for(let t=0;t<e.length;t++)if(ai(e[t]))return!0;return!1}a(kle,"arrayHasEmptyOrZeroLengthValues");function Fle(...e){try{return e.join(xo.sep)}catch{console.error(e)}}a(Fle,"buildFolderPath");function tV(e){return Bn(e)?!1:e===!0||e===!1}a(tV,"isBoolean");function Gle(e){return Bn(e)?!1:typeof e=="object"}a(Gle,"isObject");function qle(e){return ai(e)?Ule:e.slice(0,-vle)}a(qle,"stripFileExtension");function Vle(e){return Bn(e)||e===""||typeof e!="string"?e:Xq[e]!==void 0?Xq[e]:nV(e)===!0?Number(e):Lle.test(e)?new Date(e):e}a(Vle,"autoCast");function rV(e){if(typeof e=="string"&&(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")))try{return JSON.parse(e)}catch{}return e}a(rV,"autoCastJSON");function SO(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=SO(n);s!==n&&(e[t]=s)}else for(let t in e){let r=e[t],n=SO(r);n!==r&&(e[t]=n)}return e}else return rV(e)}a(SO,"autoCastJSONDeep");function nV(e){if(e.startsWith("0.")&&Jq(e))return!0;let t=e.toUpperCase().includes("E");return!!((e!=="0"&&e.startsWith("0"))===!1&&t===!1&&Jq(e))}a(nV,"autoCasterIsNumberCheck");async function $le(e){if(ai(e))throw new Error(`Directory path: ${e} does not exist`);try{await zq.emptyDir(e),await zq.remove(e)}catch(t){throw ln.error(`Error removing files in ${e} -- ${t}`),t}}a($le,"removeDir");function Yle(e,t){if(ai(e)){ln.info("Invalid current version sent as parameter.");return}if(ai(t)){ln.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 d=0;d<l;d++)if(r=parseInt(o[d],10)-parseInt(c[d],10),r)return r;return o.length-c.length}a(Yle,"compareVersions");function Kle(e,t,r=!1){let n=e.toString().split("."),s=t.toString().split(".");return n[0]===s[0]&&(!r||n[1]===s[1])}a(Kle,"isCompatibleDataVersion");function Wle(e){if(Bn(e))return e;let t=String(e);return t==="."?Bt.UNICODE_PERIOD:t===".."?Bt.UNICODE_PERIOD+Bt.UNICODE_PERIOD:t.replace(Bt.FORWARD_SLASH_REGEX,Bt.UNICODE_FORWARD_SLASH)}a(Wle,"escapeRawValue");function Qle(e){if(Bn(e))return e;let t=String(e);return t===Bt.UNICODE_PERIOD?".":t===Bt.UNICODE_PERIOD+Bt.UNICODE_PERIOD?"..":String(e).replace(Bt.ESCAPED_FORWARD_SLASH_REGEX,"/")}a(Qle,"unescapeValue");function zle(e,t){if(Bn(e))return ln.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+yp.EOL}!ai(n)&&n[0]===";"?r+=" "+n+s+yp.EOL:ai(n)||(r+=n+"="+s+yp.EOL)}catch{ln.error(`Found bad property during upgrade with key ${n} and value: ${s}`)}}),r}a(zle,"stringifyProps");function sV(){let e;try{e=yp.homedir()}catch{e=process.env.HOME}return e}a(sV,"getHomeDir");function jle(){let e=xo.join(sV(),Bt.HDB_HOME_DIR_NAME,Bt.BOOT_PROPS_FILE_NAME);return Zq.existsSync(e)||(e=xo.join(__dirname,"../","hdb_boot_properties.file")),e}a(jle,"getPropsFilePath");function Jle(e,t){let r,n;return n=new Promise(function(s){r=setTimeout(function(){s(t)},e)}),{promise:n,cancel:function(){clearTimeout(r)}}}a(Jle,"timeoutPromise");async function Xle(e){if(!e)throw new Error("Invalid port passed as parameter");return new Promise((t,r)=>{let n=yle.createServer().once("error",s=>{s.code==="EADDRINUSE"?t(!0):r(s)}).once("listening",()=>n.once("close",()=>t(!1)).close()).listen(e)})}a(Xle,"isPortTaken");function Zle(e){try{return Bt.CLUSTER_OPERATIONS[e.toLowerCase()]!==void 0}catch(t){ln.error(`Error checking operation against cluster ops ${t}`)}return!1}a(Zle,"isClusterOperation");function eue(e,t){let r=(Ne(),ae(it)).getDatabases();if(!r[e])return Np.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e);if(!r[e][t])return Np.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(eue,"checkGlobalSchemaTable");function tue(e,t){if(Bn(t)){ln.warn("No CLUSTERING_USER defined, clustering disabled");return}if(Bn(e)||ai(e)){ln.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){ln.error(`unable to find cluster_user due to: ${n.message}`);return}if(r===void 0){ln.warn(`CLUSTERING_USER: ${t} not found or is not active.`);return}return r}a(tue,"getClusterUser");function rue(){jq.parsePromise=function(e,t,r){return new Promise(function(n,s){jq.parse(e,{header:!0,transformHeader:iV,chunk:t.bind(null,s),skipEmptyLines:!0,transform:r,dynamicTyping:!1,error:s,complete:n})})}}a(rue,"promisifyPapaParse");function iV(e){if(typeof e!="string")throw new TypeError(`Expected a string, got ${typeof e}`);return e.charCodeAt(0)===65279?e.slice(1):e}a(iV,"removeBOM");function nue(e,t,r){return new Promise(n=>{t.once(e,s=>{let i=r;ln.info(`Got cluster status event response: ${Ile(s)}`);try{i.cancel()}catch{ln.error("Error trying to cancel timeout.")}n(s)})})}a(nue,"createEventPromise");async function sue(e){let t=!0,r=0;do await eV(Ple*r++),(await Nle.findPs(e)).length>0&&(t=!1);while(t&&r<Mle);if(t)throw new Error(`process ${e} was not started`)}a(sue,"checkProcessRunning");function iue(e,t){let r=oV(e);if(r)return r;let n=aV(e,t);if(n)return n}a(iue,"checkSchemaTableExist");function oV(e){let{getDatabases:t}=(Ne(),ae(it));if(!t()[e])return Np.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}a(oV,"checkSchemaExists");function aV(e,t){let{getDatabases:r}=(Ne(),ae(it));if(!r()[e][t])return Np.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(aV,"checkTableExists");function oue(){let e=Op().utc().add(1,Bt.MOMENT_DAYS_TAG).startOf(Bt.MOMENT_DAYS_TAG).unix(),t=Op().utc().unix();return e-t}a(oue,"getStartOfTomorrowInSeconds");function aue(){return Op().utc().format("DD-MM-YYYY")}a(aue,"getLimitKey");function cue(e){try{let t=new Ole(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){ln.error("Got an error back ticking items."),ln.error(t)}}a(cue,"backtickASTSchemaItems");function lue(e){return[e]}a(lue,"createForkArgs");function uue(e){return e===!0||typeof e=="string"&&e.toLowerCase()==="true"}a(uue,"autoCastBoolean");function due(e,t){let{getDatabases:r}=(Ne(),ae(it)),n=r()[e]?.[t];return n?.primaryKey||n?.hash_attribute}a(due,"getTableHashAttribute");function fue(e){let{getDatabases:t}=(Ne(),ae(it));return t()[e]!==void 0}a(fue,"doesSchemaExist");function _ue(e,t){let{getDatabases:r}=(Ne(),ae(it));return r()[e]?.[t]!==void 0}a(_ue,"doesTableExist");function Eue(e){try{return JSON.stringify(e)}catch{return e}}a(Eue,"stringifyObj");function hue(e){let t=Op.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(hue,"ms_to_time");function mue(e,t){let r=xo.basename(e,xo.extname(e));return xo.join(xo.dirname(e),r+t)}a(mue,"changeExtension");function TO(){if(process.env[Bt.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return process.env[Bt.CONFIG_PARAMS.ROOTPATH.toUpperCase()];let e=wle(process.argv);if(e[Bt.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return e[Bt.CONFIG_PARAMS.ROOTPATH.toUpperCase()]}a(TO,"getEnvCliRootPath");var pO;function pue(){if(pO)return pO;let e=TO();if(TO()&&Zq.pathExistsSync(xo.join(e,Bt.HDB_CONFIG_FILE)))return pO=!0,!0}a(pue,"noBootFile");function Sue(e,t){let r;return e.protocol==="http:"?r=Dle:r=Cle,new Promise((n,s)=>{let i=r.request(e,o=>{o.setEncoding("utf8");let c={body:"",headers:o.headers};o.on("data",l=>{c.body+=l}),o.on("end",()=>{n(c)})});i.on("error",o=>{s(o)}),i.write(JSON.stringify(t)),i.end()})}a(Sue,"httpRequest");function Tue(e){if(!e.schema&&!e.database){e.schema=Bt.DEFAULT_DATABASE_NAME;return}e.database&&(e.schema=e.database)}a(Tue,"transformReq");function gue(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(gue,"convertToMS")});var ie=I((_V,EV)=>{"use strict";var gO=require("fs-extra"),ja=require("path"),lV=require("os"),Rue=require("properties-reader"),Wf=X(),Kf=re(),be=H(),Ip=dr(),Aue="Error initializing environment manager",wp="BOOT_PROPS_FILE_PATH",uV=!1,bue={[be.HDB_SETTINGS_NAMES.INSTALL_USER]:!0,[be.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY]:!0,[be.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]:!0,BOOT_PROPS_FILE_PATH:!0},qi={};Object.assign(_V,EV.exports={BOOT_PROPS_FILE_PATH:wp,getHdbBasePath:yue,setHdbBasePath:Oue,get:dV,initSync:Iue,setProperty:Ke,initTestEnvironment:Cue,setCloneVar:wue});function yue(){return qi[be.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]}a(yue,"getHdbBasePath");function Oue(e){qi[be.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=e}a(Oue,"setHdbBasePath");function dV(e){let t=Ip.getConfigValue(e);return t===void 0?qi[e]:t}a(dV,"get");function Ke(e,t){bue[e]&&(qi[e]=t),Ip.updateConfigObject(e,t)}a(Ke,"setProperty");function Nue(){let e;try{e=Kf.getPropsFilePath(),gO.accessSync(e,gO.constants.F_OK|gO.constants.R_OK),uV=!0;let t=Rue(e);return qi[be.HDB_SETTINGS_NAMES.INSTALL_USER]=t.get(be.HDB_SETTINGS_NAMES.INSTALL_USER),qi[be.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY]=t.get(be.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY),qi[wp]=e,!0}catch{return Wf.trace(`Environment manager found no properties file at ${e}`),!1}}a(Nue,"doesPropFileExist");function Iue(e=!1){try{(uV||Nue()||Kf.noBootFile())&&!fV&&(Ip.initConfig(e),qi[be.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=Ip.getConfigValue(be.HDB_SETTINGS_NAMES.HDB_ROOT_KEY))}catch(t){Wf.error(Aue),Wf.error(t),console.error(t),process.exit(1)}}a(Iue,"initSync");var fV=!1;function wue(e){fV=e}a(wue,"setCloneVar");function Cue(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=ja.join(__dirname,"../../","unitTests");qi[wp]=ja.join(l,"hdb_boot_properties.file"),Ke(be.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY,ja.join(l,"settings.test")),Ke(be.HDB_SETTINGS_NAMES.INSTALL_USER,lV.userInfo()?lV.userInfo().username:void 0),Ke(be.HDB_SETTINGS_NAMES.LOG_LEVEL_KEY,"debug"),Ke(be.HDB_SETTINGS_NAMES.LOG_PATH_KEY,ja.join(l,"envDir","log")),Ke(be.HDB_SETTINGS_NAMES.LOG_DAILY_ROTATE_KEY,!1),Ke(be.HDB_SETTINGS_NAMES.CLUSTERING_ENABLED_KEY,!0),Ke(be.HDB_SETTINGS_NAMES.CLUSTERING_NODE_NAME_KEY,"1231412de213"),Ke(be.HDB_SETTINGS_NAMES.HDB_ROOT_KEY,ja.join(l,"envDir")),Ke(be.CONFIG_PARAMS.STORAGE_PATH,ja.join(l,"envDir")),s&&(Ke(be.CONFIG_PARAMS.HTTP_SECUREPORT,dV(be.CONFIG_PARAMS.HTTP_PORT)),Ke(be.CONFIG_PARAMS.HTTP_PORT,null)),Ke(be.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HTTPS,!!s),Ke(be.CONFIG_PARAMS.HTTP_PORT,9926),Ke(be.HDB_SETTINGS_NAMES.SERVER_PORT_KEY,9925),Ke(be.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_PORT,9925),Ke(be.HDB_SETTINGS_NAMES.CORS_ENABLED_KEY,Kf.isEmpty(i)?!1:i),Ke(be.CONFIG_PARAMS.HTTP_CORS,Kf.isEmpty(i)?!1:i),Ke(be.HDB_SETTINGS_NAMES.MAX_CUSTOM_FUNCTION_PROCESSES,2),Ke(be.HDB_SETTINGS_NAMES.MAX_HDB_PROCESSES,4),Ke(be.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_PORT_KEY,9926),Ke(be.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_ENABLED_KEY,!0),Ke(be.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY,ja.resolve(__dirname,"../../unitTests/server/fastifyRoutes/custom_functions")),Ke(be.HDB_SETTINGS_NAMES.LOCAL_STUDIO_ON,Kf.isEmpty(c)?!1:c),o&&(Ke("CORS_ACCESSLIST",o),Ke(be.CONFIG_PARAMS.HTTP_CORSACCESSLIST,o)),n&&(Ke(be.HDB_SETTINGS_NAMES.SERVER_TIMEOUT_KEY,n),Ke(be.CONFIG_PARAMS.HTTP_TIMEOUT,n)),t&&(Ke(be.HDB_SETTINGS_NAMES.SERVER_KEEP_ALIVE_TIMEOUT_KEY,t),Ke(be.CONFIG_PARAMS.HTTP_KEEPALIVETIMEOUT,t)),r&&(Ke(be.HDB_SETTINGS_NAMES.SERVER_HEADERS_TIMEOUT_KEY,r),Ke(be.CONFIG_PARAMS.HTTP_HEADERSTIMEOUT,r))}catch(t){let r=`Error reading in HDB environment variables from path ${wp}. Please check your boot props and settings files`;Wf.fatal(r),Wf.error(t)}}a(Cue,"initTestEnvironment")});var or=I((iye,LV)=>{"use strict";var mr=ie();mr.initSync();var Due=require("fs-extra"),Lue=require("semver"),jf=require("path"),{monotonicFactory:Pue}=require("ulidx"),mV=Pue(),Mue=require("util"),pV=require("child_process"),Uue=Mue.promisify(pV.exec),vue=pV.spawn,Cr=Pt(),We=H(),Cp=re(),ws=X(),Dp=mi(),xue=TE(),Qf=dr(),{broadcast:Bue,onMessageByType:Hue,getWorkerIndex:kue}=at(),{isMainThread:SV}=require("worker_threads"),{Encoder:Fue,decode:yO}=require("msgpackr"),TV=new Fue,{isEmpty:ec}=Cp,gV=$n(),eye=48*36e11;SV&&Hue(We.ITC_EVENT_TYPES.RESTART,()=>{un=void 0,Za=void 0});var{connect:Gue,StorageType:que,RetentionPolicy:Vue,AckPolicy:OO,DeliverPolicy:NO,DiscardPolicy:$ue,NatsConnection:tye,JetStreamManager:rye,JetStreamClient:nye,StringCodec:sye,JSONCodec:Yue,createInbox:IO,headers:Kue,ErrorCode:hV}=require("nats"),{PACKAGE_ROOT:Wue}=H(),Que=ed(),{recordAction:zue}=(Bi(),ae(of)),RV=Yue(),jue="clustering",Jue=Que.engines[Cr.NATS_SERVER_NAME],Xue=jf.join(Wue,"dependencies"),bO=jf.join(Xue,`${process.platform}-${process.arch}`,Cr.NATS_BINARY_NAME),RO,AO,zf,Ja,Xa;LV.exports={runCommand:AV,checkNATSServerInstalled:Zue,createConnection:wO,getConnection:Jf,getJetStreamManager:Xf,getJetStream:yV,getNATSReferences:ci,getServerList:tde,createLocalStream:CO,listStreams:OV,deleteLocalStream:rde,getServerConfig:ql,listRemoteStreams:nde,viewStream:sde,viewStreamIterator:ide,publishToStream:ode,request:lde,reloadNATS:DO,reloadNATSHub:ude,reloadNATSLeaf:dde,extractServerName:cde,requestErrorHandler:fde,createLocalTableStream:CV,createTableStreams:hde,purgeTableStream:DV,purgeSchemaTableStreams:mde,getStreamInfo:pde,updateLocalStreams:Tde,closeConnection:ede,getJsmServerName:Lp,addNatsMsgHeader:NV,clearClientCache:bV,updateRemoteConsumer:_de,createConsumer:IV,updateConsumerIterator:Ede};async function AV(e,t=void 0){let{stdout:r,stderr:n}=await Uue(e,{cwd:t});if(n)throw new Error(n.replace(`
31
41
  `,""));return r.replace(`
32
- `,"")}a(fG,"runCommand");async function Bie(){try{await fie.access(LA)}catch{return!1}let e=await fG(`${LA} --version`,void 0),t=e.substring(e.lastIndexOf("v")+1,e.length);return Eie.eq(t,Uie)}a(Bie,"checkNATSServerInstalled");async function BA(e,t,r,n=!0,s="127.0.0.1"){if(!t&&!r){let o=await _G.getClusterUser();if(Bo(o))throw new Error("Unable to get nats connection. Cluster user is undefined.");t=o.username,r=o.decrypt_hash}Vn.trace("create nats connection called");let i=await bie({name:s,port:e,user:t,pass:r,maxReconnectAttempts:-1,waitOnFirstConnect:n,timeout:2e5,tls:{keyFile:qt.get(Ce.CONFIG_PARAMS.CLUSTERING_TLS_PRIVATEKEY),certFile:qt.get(Ce.CONFIG_PARAMS.CLUSTERING_TLS_CERTIFICATE),caFile:qt.get(Ce.CONFIG_PARAMS.CLUSTERING_TLS_CERT_AUTH),rejectUnauthorized:!1}});return i.protocol.transport.socket.unref(),Vn.trace("create connection established a nats client connection with id",i?.info?.client_id),i.closed().then(o=>{o&&Vn.error("Error with Nats client connection, connection closed",o),EG()}),i}a(BA,"createConnection");function EG(){Mr=void 0,Po=void 0,Uo=void 0,vo=void 0}a(EG,"clearClientCache");async function Hie(){Mr&&(await Mr.drain(),Mr=void 0,Po=void 0,Uo=void 0,vo=void 0)}a(Hie,"closeConnection");var Mr,vo;async function Vu(){return vo||(vo=BA(qt.get(Ce.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),void 0,void 0),Mr=await vo),Mr||vo}a(Vu,"getConnection");async function $u(){if(Po)return Po;Bo(Mr)&&await Vu();let{domain:e}=nc(Ce.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);if(Bo(e))throw new Error("Error getting JetStream domain. Unable to get JetStream manager.");return Po=await Mr.jetstreamManager({domain:e,timeout:6e4}),Po}a($u,"getJetStreamManager");async function hG(){if(Uo)return Uo;Bo(Mr)&&await Vu();let{domain:e}=nc(Ce.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);if(Bo(e))throw new Error("Error getting JetStream domain. Unable to get JetStream manager.");return Uo=Mr.jetstream({domain:e,timeout:6e4}),Uo}a(hG,"getJetStream");async function hs(){let e=Mr||await Vu(),t=Po||await $u(),r=Uo||await hG();return{connection:e,jsm:t,js:r}}a(hs,"getNATSReferences");async function xie(e){let t=qt.get(Ce.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),{sys_name:r,decrypt_hash:n}=await _G.getClusterUser(),s=await BA(t,r,n),i=vA(),o=s.subscribe(i),c=[],l,_=(async()=>{for await(let u of o){let d=dG.decode(u.data);d.response_time=Date.now()-l,c.push(d)}})();return l=Date.now(),await s.publish("$SYS.REQ.SERVER.PING.VARZ",void 0,{reply:i}),await s.publish("$SYS.REQ.SERVER.PING",void 0,{reply:i}),await s.flush(),await sh.async_set_timeout(e),await o.drain(),await s.close(),await _,c}a(xie,"getServerList");async function HA(e,t){let{jsm:r}=await hs(),n=qt.get(Ce.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE);n=n===null?0:n*1e9;let s=qt.get(Ce.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS);s=s===null?-1:s;let i=qt.get(Ce.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES);i=i===null?-1:i,await r.streams.add({name:e,storage:yie.File,retention:Nie.Limits,subjects:t,discard:Iie.Old,max_msgs:s,max_bytes:i,max_age:n})}a(HA,"createLocalStream");async function mG(){let{jsm:e}=await hs(),t=await e.streams.list().next(),r=[];return t.forEach(n=>{r.push(n)}),r}a(mG,"listStreams");async function Gie(e){let{jsm:t}=await hs();await t.streams.delete(e)}a(Gie,"deleteLocalStream");async function Fie(e){let{connection:t}=await hs(),r=[],n=vA(),s=t.subscribe(n),i=(async()=>{for await(let o of s)r.push(dG.decode(o.data))})();return await t.publish(`$JS.${e}.API.STREAM.LIST`,void 0,{reply:n}),await t.flush(),await s.drain(),await i,r}a(Fie,"listRemoteStreams");async function qie(e,t=void 0,r=void 0){let{jsm:n,js:s}=await hs(),i=aG(),o={durable_name:i,ack_policy:PA.Explicit};t&&(o.deliver_policy=UA.StartTime,o.opt_start_time=new Date(t).toISOString()),await n.consumers.add(e,o);let c=await s.consumers.get(e,i),l=r?await c.fetch({max_messages:r,expires:2e3}):await c.consume();if(c._info.num_pending===0)return[];let _=[];for await(let u of l){let d=MA(u.data),E={nats_timestamp:u.info.timestampNanos,nats_sequence:u.info.streamSequence,entry:d};if(u.headers&&(E.origin=u.headers.get(jt.MSG_HEADERS.ORIGIN)),_.push(E),u.ack(),u.info.pending===0)break}return await c.delete(),_}a(qie,"viewStream");async function*kie(e,t=void 0,r=void 0){let{jsm:n,js:s}=await hs(),i=aG(),o={durable_name:i,ack_policy:PA.Explicit};t&&(o.deliver_policy=UA.StartTime,o.opt_start_time=new Date(t).toISOString()),await n.consumers.add(e,o);let c=await s.consumers.get(e,i),l=r?await c.fetch({max_messages:r,expires:2e3}):await c.consume();if(c._info.num_pending===0)return[];for await(let _ of l){let u=MA(_.data);u[0]||(u=[u]);for(let d of u){let E={nats_timestamp:_.info.timestampNanos,nats_sequence:_.info.streamSequence,entry:d};_.headers&&(E.origin=_.headers.get(jt.MSG_HEADERS.ORIGIN)),yield E}if(_.ack(),_.info.pending===0)break}await c.delete()}a(kie,"viewStreamIterator");async function Vie(e,t,r,n){Vn.trace(`publishToStream called with subject: ${e}, stream: ${t}, entries:`,n.operation),r=pG(n,r);let{js:s}=await hs(),i=await oh(),o=`${e}.${i}`,c=n instanceof Uint8Array?n:uG.encode(n);try{Vn.trace(`publishToStream publishing to subject: ${o}`),Mie(c.length,"bytes-sent",e,n.operation,"replication"),await s.publish(o,c,{headers:r})}catch(l){if(l.code&&l.code.toString()==="503")return TG(async()=>{try{await s.publish(o,c,{headers:r})}catch{if(l.code&&l.code.toString()==="503"){Vn.trace(`publishToStream creating stream: ${t}`);let u=o.split(".");u[2]="*",await HA(t,[o]),await s.publish(o,c,{headers:r})}else throw l}});throw l}}a(Vie,"publishToStream");function pG(e,t){t===void 0&&(t=Cie());let r=qt.get(Ce.CONFIG_PARAMS.CLUSTERING_NODENAME);return!t.has(jt.MSG_HEADERS.ORIGIN)&&r&&t.append(jt.MSG_HEADERS.ORIGIN,r),t}a(pG,"addNatsMsgHeader");function nc(e){e=e.toLowerCase();let t=ku.join(qt.get(Ce.CONFIG_PARAMS.ROOTPATH),Pie);if(e===Ce.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase())return Bo(DA)&&(DA={port:Fu.getConfigFromFile(Ce.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),server_name:Fu.getConfigFromFile(Ce.CONFIG_PARAMS.CLUSTERING_NODENAME)+jt.SERVER_SUFFIX.HUB,config_file:jt.NATS_CONFIG_FILES.HUB_SERVER,pid_file_path:ku.join(t,jt.PID_FILES.HUB),hdb_nats_path:t}),DA;if(e===Ce.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())return Bo(CA)&&(CA={port:Fu.getConfigFromFile(Ce.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),server_name:Fu.getConfigFromFile(Ce.CONFIG_PARAMS.CLUSTERING_NODENAME)+jt.SERVER_SUFFIX.LEAF,config_file:jt.NATS_CONFIG_FILES.LEAF_SERVER,domain:Fu.getConfigFromFile(Ce.CONFIG_PARAMS.CLUSTERING_NODENAME)+jt.SERVER_SUFFIX.LEAF,pid_file_path:ku.join(t,jt.PID_FILES.LEAF),hdb_nats_path:t}),CA;Vn.error(`Unable to get Nats server config. Unrecognized process: ${e}`)}a(nc,"getServerConfig");async function SG(e,t,r,n){try{await e.consumers.add(t,{ack_policy:PA.Explicit,durable_name:r,deliver_policy:UA.StartTime,opt_start_time:n})}catch(s){if(s.message!=="consumer already exists")throw s}}a(SG,"createConsumer");async function $ie(e,t,r){await e.consumers.delete(t,r)}a($ie,"removeConsumer");function Yie(e){return e.split(".")[1]}a(Yie,"extractServerName");async function Kie(e,t,r=6e4,n=vA()){if(!sh.isObject(t))throw new Error("data param must be an object");let s=uG.encode(t),{connection:i}=await hs(),o={timeout:r};n&&(o.reply=n,o.noMux=!0);let c=await i.request(e,s,o);return MA(c.data)}a(Kie,"request");function xA(e){return new Promise(async(t,r)=>{let n=Sie(LA,["--signal",`reload=${e}`],{cwd:__dirname}),s,i;n.on("error",o=>{r(o)}),n.stdout.on("data",o=>{i+=o.toString()}),n.stderr.on("data",o=>{s+=o.toString()}),n.stderr.on("close",o=>{s&&r(s),t(i)})})}a(xA,"reloadNATS");async function Wie(){let{pid_file_path:e}=nc(Ce.PROCESS_DESCRIPTORS.CLUSTERING_HUB);await xA(e)}a(Wie,"reloadNATSHub");async function Qie(){let{pid_file_path:e}=nc(Ce.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);await xA(e)}a(Qie,"reloadNATSLeaf");function zie(e,t,r){let n;switch(e.code){case oG.NoResponders:n=`Unable to ${t}, node '${r}' is not listening.`;break;case oG.Timeout:n=`Unable to ${t}, node '${r}' is listening but did not respond.`;break;default:n=e.message;break}return n}a(zie,"requestErrorHandler");async function Jie(e,t){let r=t+jt.SERVER_SUFFIX.LEAF,{connection:n}=await hs(),{jsm:s}=await soe(r),{schema:i,table:o}=e,c=ih.createNatsTableStreamName(i,o),l=e.start_time?e.start_time:new Date(Date.now()).toISOString();await TG(async()=>{if(e.subscribe===!0)await SG(s,c,n.info.server_name,l);else try{await $ie(s,c,n.info.server_name)}catch(_){Vn.trace(_)}})}a(Jie,"updateRemoteConsumer");async function Xie(e,t,r,n){let s=ih.createNatsTableStreamName(e,t),i=r+jt.SERVER_SUFFIX.LEAF,o={type:Ce.ITC_EVENT_TYPES.NATS_CONSUMER_UPDATE,status:n,stream_name:s,node_domain_name:i};if(!lG&&Aie()<qt.get(Ce.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXINGESTTHREADS)){let{updateConsumer:c}=hE();await c(o)}await gie(o),n==="stop"&&await sh.async_set_timeout(1e3)}a(Xie,"updateConsumerIterator");function TG(e){return Tie.writeTransaction(Ce.SYSTEM_SCHEMA_NAME,Ce.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,e)}a(TG,"exclusiveLock");async function gG(e,t){let r=ih.createNatsTableStreamName(e,t),n=await oh(),s=toe(e,t,n);await HA(r,[s])}a(gG,"createLocalTableStream");async function jie(e){for(let t=0,r=e.length;t<r;t++){let n=e[t].schema,s=e[t].table;await gG(n,s)}}a(jie,"createTableStreams");async function RG(e,t,r=void 0){if(qt.get(Ce.CONFIG_PARAMS.CLUSTERING_ENABLED))try{let n=ih.createNatsTableStreamName(e,t),{domain:s}=nc(Ce.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);await(await(await Vu()).jetstreamManager({domain:s,timeout:24e4})).streams.purge(n,r)}catch(n){if(n.message==="stream not found")Vn.warn(n);else throw n}}a(RG,"purgeTableStream");async function Zie(e,t){if(qt.get(Ce.CONFIG_PARAMS.CLUSTERING_ENABLED))for(let r=0,n=t.length;r<n;r++)await RG(e,t[r])}a(Zie,"purgeSchemaTableStreams");async function eoe(e){return(await $u()).streams.info(e)}a(eoe,"getStreamInfo");function toe(e,t,r){return`${jt.SUBJECT_PREFIXES.TXN}.${e}${t?"."+t:""}.${r}`}a(toe,"createSubjectName");async function oh(){if(qu)return qu;if(qu=(await $u())?.nc?.info?.server_name,qu===void 0)throw new Error("Unable to get jetstream manager server name");return qu}a(oh,"getJsmServerName");async function roe(){let e=await $u(),t=await oh(),r=await mG();for(let n of r){let s=n.config,i=s.subjects[0];if(!i)continue;let o=noe(n),c=i.split(".");if(c[c.length-1]===t&&!o||s.name==="__HARPERDB_WORK_QUEUE__")continue;let _=i.split(".");_[_.length-1]=t;let u=_.join(".");Vn.trace(`Updating stream subject name from: ${i} to: ${u}`),s.subjects[0]=u,await e.streams.update(s.name,s)}}a(roe,"updateLocalStreams");function noe(e){let{config:t}=e,r=!1,n=qt.get(Ce.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE);n=n===null?0:n*1e9;let s=qt.get(Ce.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES);s=s===null?-1:s;let i=qt.get(Ce.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS);return i=i===null?-1:i,n!==t.max_age&&(t.max_age=n,r=!0),s!==t.max_bytes&&(t.max_bytes=s,r=!0),i!==t.max_msgs&&(t.max_msgs=i,r=!0),r}a(noe,"updateStreamLimits");async function soe(e){let t,r;try{t=await Mr.jetstream({domain:e}),r=await Mr.jetstreamManager({domain:e,checkAPI:!1})}catch(n){throw Vn.error("Unable to connect to:",e),n}return{js:t,jsm:r}}a(soe,"connectToRemoteJS")});var hE=g((Wpe,PG)=>{"use strict";var{decode:ioe}=require("msgpackr"),{isMainThread:$pe,parentPort:Ype,threadId:Kpe}=require("worker_threads"),lh=wt(),sc=ct(),qA=U(),or=K(),FA=te(),ooe=U(),{onMessageByType:aoe}=it(),yG=Rs(),{recordAction:coe,recordActionBinary:loe}=(Bs(),ie(su)),{publishToStream:uoe}=lh,{ConsumerEvents:OG}=require("nats"),_oe=Gr(),{promisify:doe}=require("util"),NG=doe(setTimeout),uh=1e4,_h,ch,foe,Eoe,IG,Yu=new Map,ic=new Map;PG.exports={initialize:wG,ingestConsumer:kA,setSubscription:hoe,setIgnoreOrigin:Soe,getDatabaseSubscriptions:poe,updateConsumer:CG};async function wG(){aoe(qA.ITC_EVENT_TYPES.NATS_CONSUMER_UPDATE,async n=>{await CG(n)}),IG=!0,or.notify("Initializing clustering ingest service.");let{connection:e,jsm:t,js:r}=await lh.getNATSReferences();_h=e,ch=e.info.server_name,foe=t,Eoe=r}a(wG,"initialize");async function CG(e){if(e.status==="start"){let{js:t,jsm:r}=await DG(e.node_domain_name);kA(e.stream_name,t,r,e.node_domain_name)}else if(e.status==="stop"){let t=Yu.get(e.stream_name+e.node_domain_name);t&&(or.notify("Closing ingest consumer for node:",e.node_domain_name,"stream:",e.stream_name),await t.close?.(),Yu.set(e.stream_name+e.node_domain_name,"close")),ic.get(e.node_domain_name)==="failed"&&ic.set(e.node_domain_name,"close")}}a(CG,"updateConsumer");var dh=new Map;function hoe(e,t,r){let n=dh.get(e);n||dh.set(e,n=new Map),n.set(t,r),IG||wG().then(moe)}a(hoe,"setSubscription");async function moe(){let e=await _oe.searchByValue({database:"system",table:"hdb_nodes",search_attribute:"name",search_value:"*"});for await(let t of e){let r=t.name+sc.SERVER_SUFFIX.LEAF,n,s;for(let i of t.subscriptions)if(i.subscribe===!0){if(!n&&({js:n,jsm:s}=await DG(r),!n))break;let{schema:o,table:c}=i,l=yG.createNatsTableStreamName(o,c);kA(l,n,s,r)}}}a(moe,"accessConsumers");async function DG(e){let t,r,n=1;for(;!r;)try{t=await _h.jetstream({domain:e}),r=await _h.jetstreamManager({domain:e,checkAPI:!1})}catch(s){if(ic.get(e)==="close")break;ic.set(e,"failed"),n%10===1&&or.warn("Nats ingest attempting to connect to:",e,"Nats error:",s.message);let i=n++*100<uh?n++*100:uh;await NG(i)}return{js:t,jsm:r}}a(DG,"connectToRemoteJS");function poe(){return dh}a(poe,"getDatabaseSubscriptions");var LG;function Soe(e){LG=e}a(Soe,"setIgnoreOrigin");var MG=100,bG=new Array(MG),ah=0;async function kA(e,t,r,n){let{connection:s}=await lh.getNATSReferences();_h=s,ch=s.info.server_name;let i,o=1;for(;!i;)try{i=await t.consumers.get(e,ch),or.notify("Initializing ingest consumer for node:",n,"stream:",e)}catch(_){if(ic.get(n)==="close")break;o%10===1&&or.warn("Nats ingest error getting consumer:",n,"stream:",e,"Nats error:",_.message),_.code==="404"&&(or.notify("Nats ingest creating consumer for node:",n,"stream:",e),i=await lh.createConsumer(r,e,ch,new Date(Date.now()).toISOString()));let u=o++*100<uh?o++*100:uh;await NG(u)}let c=!1,l;for(;!c;){if(Yu.get(e+n)==="close"||ic.get(n)==="close"){Yu.delete(e+n),c=!0;continue}l=await i.consume({max_messages:FA.get(qA.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXCONSUMEMSGS)??100,bind:!0}),Yu.set(e+n,l);let _=!1;(async()=>{for await(let u of await l.status())if(u.type===OG.ConsumerDeleted&&(await l.close(),c=!0),u.type===OG.HeartbeatsMissed){let d=u.data;or.trace(`${d} clustering ingest consumer heartbeats missed, node: ${n} stream: ${l.consumer.stream}`),d===100&&(or.warn(`Restarting clustering ingest consumer due to missed heartbeat threshold being met, node: ${n} stream: ${l.consumer.stream}`),l.stop(),_=!0)}})();try{for await(let u of l)await bG[ah],bG[ah]=Toe(u).catch(d=>{or.error(d)}),++ah>=MG&&(ah=0)}catch(u){u.message==="consumer deleted"?(or.notify("Nats consumer deleted, closing messages for node:",n,"stream:",l.consumer.stream),await l.close(),c=!0):or.error("Error consuming clustering ingest, restarting consumer",u)}}}a(kA,"ingestConsumer");async function Toe(e){let t=ioe(e.data);coe(e.data.length,"bytes-received",e.subject,t.operation,"ingest"),or.trace("Nats message processor message size:",e?.msg?._msg?.size,"bytes");let r=e.headers,n=!1,s=FA.get(qA.CONFIG_PARAMS.CLUSTERING_NODENAME);r.has(sc.MSG_HEADERS.TRANSACTED_NODES)&&r.values(sc.MSG_HEADERS.TRANSACTED_NODES).indexOf(s)>-1&&(n=!0);let i=r.get(sc.MSG_HEADERS.ORIGIN);if(n||(n=i===s&&!LG),loe(n,"echo",e.subject,t.operation,"ingest"),n){e.ack();return}r.append(sc.MSG_HEADERS.TRANSACTED_NODES,s);try{let{operation:o,schema:c,next:l,table:_,records:u,hash_values:d,__origin:E,expiresAt:f}=t;or.trace("processing message:",o,c,_,(u?"records: "+u.map(C=>C?.id):"")+(d?"ids: "+d:""),"with sequence:",e.seq),or.trace(`messageProcessor nats msg id: ${e.headers.get(sc.MSG_HEADERS.NATS_MSG_ID)}`);let h;u||(u=d);let p=new Promise(C=>h=C),{timestamp:S,user:T,node_name:R}=E||{},b=dh.get(c)?.get(_);if(!b)throw new Error("Missing table for replication message",_);if(o==="define_schema")t.type=o,t.onCommit=h,b.send(t);else if(u.length===1&&!l)b.send({type:GA(o),value:u[0],id:d?.[0],expiresAt:f,timestamp:S,table:_,onCommit:h,user:T,nodeName:R});else{let C=u.map((H,v)=>({type:GA(o),value:H,expiresAt:f,id:d?.[v],table:_}));for(;l;)C.push({type:GA(l.operation),value:l.record,expiresAt:l.expiresAt,id:l.id,table:l.table}),l=l.next;b.send({type:"transaction",writes:C,table:_,timestamp:S,onCommit:h,user:T,nodeName:R})}FA.get(ooe.CONFIG_PARAMS.CLUSTERING_REPUBLISHMESSAGES)!==!1&&uoe(e.subject.split(".").slice(0,-1).join("."),yG.createNatsTableStreamName(c,_),e.headers,e.data),await p}catch(o){or.error(o)}e.ack()}a(Toe,"messageProcessor");function GA(e){switch(e){case"insert":case"upsert":case"update":return"put"}return e}a(GA,"convertOperation")});var goe=hE();(async()=>{try{await goe.initialize()}catch(e){console.error("Error launching Nats ingest service."),console.error(e)}})();
42
+ `,"")}a(AV,"runCommand");async function Zue(){try{await Due.access(bO)}catch{return!1}let e=await AV(`${bO} --version`,void 0),t=e.substring(e.lastIndexOf("v")+1,e.length);return Lue.eq(t,Jue)}a(Zue,"checkNATSServerInstalled");async function wO(e,t,r,n=!0,s="127.0.0.1"){if(!t&&!r){let o=await gV.getClusterUser();if(ec(o))throw new Error("Unable to get nats connection. Cluster user is undefined.");t=o.username,r=o.decrypt_hash}ws.trace("create nats connection called");let i=await Gue({name:s,port:e,user:t,pass:r,maxReconnectAttempts:-1,waitOnFirstConnect:n,timeout:2e5,tls:{keyFile:mr.get(We.CONFIG_PARAMS.CLUSTERING_TLS_PRIVATEKEY),certFile:mr.get(We.CONFIG_PARAMS.CLUSTERING_TLS_CERTIFICATE),caFile:mr.get(We.CONFIG_PARAMS.CLUSTERING_TLS_CERT_AUTH),rejectUnauthorized:!1}});return i.protocol.transport.socket.unref(),ws.trace("create connection established a nats client connection with id",i?.info?.client_id),i.closed().then(o=>{o&&ws.error("Error with Nats client connection, connection closed",o),bV()}),i}a(wO,"createConnection");function bV(){un=void 0,Ja=void 0,Xa=void 0,Za=void 0}a(bV,"clearClientCache");async function ede(){un&&(await un.drain(),un=void 0,Ja=void 0,Xa=void 0,Za=void 0)}a(ede,"closeConnection");var un,Za;async function Jf(){return Za||(Za=wO(mr.get(We.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),void 0,void 0),un=await Za),un||Za}a(Jf,"getConnection");async function Xf(){if(Ja)return Ja;ec(un)&&await Jf();let{domain:e}=ql(We.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);if(ec(e))throw new Error("Error getting JetStream domain. Unable to get JetStream manager.");return Ja=await un.jetstreamManager({domain:e,timeout:6e4}),Ja}a(Xf,"getJetStreamManager");async function yV(){if(Xa)return Xa;ec(un)&&await Jf();let{domain:e}=ql(We.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);if(ec(e))throw new Error("Error getting JetStream domain. Unable to get JetStream manager.");return Xa=un.jetstream({domain:e,timeout:6e4}),Xa}a(yV,"getJetStream");async function ci(){let e=un||await Jf(),t=Ja||await Xf(),r=Xa||await yV();return{connection:e,jsm:t,js:r}}a(ci,"getNATSReferences");async function tde(e){let t=mr.get(We.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),{sys_name:r,decrypt_hash:n}=await gV.getClusterUser(),s=await wO(t,r,n),i=IO(),o=s.subscribe(i),c=[],l,d=(async()=>{for await(let u of o){let f=RV.decode(u.data);f.response_time=Date.now()-l,c.push(f)}})();return l=Date.now(),await s.publish("$SYS.REQ.SERVER.PING.VARZ",void 0,{reply:i}),await s.publish("$SYS.REQ.SERVER.PING",void 0,{reply:i}),await s.flush(),await Cp.async_set_timeout(e),await o.drain(),await s.close(),await d,c}a(tde,"getServerList");async function CO(e,t){let{jsm:r}=await ci(),n=mr.get(We.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE);n=n===null?0:n*1e9;let s=mr.get(We.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS);s=s===null?-1:s;let i=mr.get(We.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES);i=i===null?-1:i,await r.streams.add({name:e,storage:que.File,retention:Vue.Limits,subjects:t,discard:$ue.Old,max_msgs:s,max_bytes:i,max_age:n})}a(CO,"createLocalStream");async function OV(){let{jsm:e}=await ci(),t=await e.streams.list().next(),r=[];return t.forEach(n=>{r.push(n)}),r}a(OV,"listStreams");async function rde(e){let{jsm:t}=await ci();await t.streams.delete(e)}a(rde,"deleteLocalStream");async function nde(e){let{connection:t}=await ci(),r=[],n=IO(),s=t.subscribe(n),i=(async()=>{for await(let o of s)r.push(RV.decode(o.data))})();return await t.publish(`$JS.${e}.API.STREAM.LIST`,void 0,{reply:n}),await t.flush(),await s.drain(),await i,r}a(nde,"listRemoteStreams");async function sde(e,t=void 0,r=void 0){let{jsm:n,js:s}=await ci(),i=mV(),o={durable_name:i,ack_policy:OO.Explicit};t&&(o.deliver_policy=NO.StartTime,o.opt_start_time=new Date(t).toISOString()),await n.consumers.add(e,o);let c=await s.consumers.get(e,i),l=r?await c.fetch({max_messages:r,expires:2e3}):await c.consume();if(c._info.num_pending===0)return[];let d=[];for await(let u of l){let f=yO(u.data),E={nats_timestamp:u.info.timestampNanos,nats_sequence:u.info.streamSequence,entry:f};if(u.headers&&(E.origin=u.headers.get(Cr.MSG_HEADERS.ORIGIN)),d.push(E),u.ack(),u.info.pending===0)break}return await c.delete(),d}a(sde,"viewStream");async function*ide(e,t=void 0,r=void 0){let{jsm:n,js:s}=await ci(),i=mV(),o={durable_name:i,ack_policy:OO.Explicit};t&&(o.deliver_policy=NO.StartTime,o.opt_start_time=new Date(t).toISOString()),await n.consumers.add(e,o);let c=await s.consumers.get(e,i),l=r?await c.fetch({max_messages:r,expires:2e3}):await c.consume();if(c._info.num_pending===0)return[];for await(let d of l){let u=yO(d.data);u[0]||(u=[u]);for(let f of u){let E={nats_timestamp:d.info.timestampNanos,nats_sequence:d.info.streamSequence,entry:f};d.headers&&(E.origin=d.headers.get(Cr.MSG_HEADERS.ORIGIN)),yield E}if(d.ack(),d.info.pending===0)break}await c.delete()}a(ide,"viewStreamIterator");async function ode(e,t,r,n){ws.trace(`publishToStream called with subject: ${e}, stream: ${t}, entries:`,n.operation),r=NV(n,r);let{js:s}=await ci(),i=await Lp(),o=`${e}.${i}`,c=n instanceof Uint8Array?n:TV.encode(n);try{ws.trace(`publishToStream publishing to subject: ${o}`),zue(c.length,"bytes-sent",e,n.operation,"replication"),await s.publish(o,c,{headers:r})}catch(l){if(l.code&&l.code.toString()==="503")return wV(async()=>{try{await s.publish(o,c,{headers:r})}catch{if(l.code&&l.code.toString()==="503"){ws.trace(`publishToStream creating stream: ${t}`);let u=o.split(".");u[2]="*",await CO(t,[o]),await s.publish(o,c,{headers:r})}else throw l}});throw l}}a(ode,"publishToStream");function NV(e,t){t===void 0&&(t=Kue());let r=mr.get(We.CONFIG_PARAMS.CLUSTERING_NODENAME);return!t.has(Cr.MSG_HEADERS.ORIGIN)&&r&&t.append(Cr.MSG_HEADERS.ORIGIN,r),t}a(NV,"addNatsMsgHeader");function ql(e){e=e.toLowerCase();let t=jf.join(mr.get(We.CONFIG_PARAMS.ROOTPATH),jue);if(e===We.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase())return ec(AO)&&(AO={port:Qf.getConfigFromFile(We.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),server_name:Qf.getConfigFromFile(We.CONFIG_PARAMS.CLUSTERING_NODENAME)+Cr.SERVER_SUFFIX.HUB,config_file:Cr.NATS_CONFIG_FILES.HUB_SERVER,pid_file_path:jf.join(t,Cr.PID_FILES.HUB),hdb_nats_path:t}),AO;if(e===We.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())return ec(RO)&&(RO={port:Qf.getConfigFromFile(We.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),server_name:Qf.getConfigFromFile(We.CONFIG_PARAMS.CLUSTERING_NODENAME)+Cr.SERVER_SUFFIX.LEAF,config_file:Cr.NATS_CONFIG_FILES.LEAF_SERVER,domain:Qf.getConfigFromFile(We.CONFIG_PARAMS.CLUSTERING_NODENAME)+Cr.SERVER_SUFFIX.LEAF,pid_file_path:jf.join(t,Cr.PID_FILES.LEAF),hdb_nats_path:t}),RO;ws.error(`Unable to get Nats server config. Unrecognized process: ${e}`)}a(ql,"getServerConfig");async function IV(e,t,r,n){try{await e.consumers.add(t,{ack_policy:OO.Explicit,durable_name:r,deliver_policy:NO.StartTime,opt_start_time:n})}catch(s){if(s.message!=="consumer already exists")throw s}}a(IV,"createConsumer");async function ade(e,t,r){await e.consumers.delete(t,r)}a(ade,"removeConsumer");function cde(e){return e.split(".")[1]}a(cde,"extractServerName");async function lde(e,t,r=6e4,n=IO()){if(!Cp.isObject(t))throw new Error("data param must be an object");let s=TV.encode(t),{connection:i}=await ci(),o={timeout:r};n&&(o.reply=n,o.noMux=!0);let c=await i.request(e,s,o);return yO(c.data)}a(lde,"request");function DO(e){return new Promise(async(t,r)=>{let n=vue(bO,["--signal",`reload=${e}`],{cwd:__dirname}),s,i;n.on("error",o=>{r(o)}),n.stdout.on("data",o=>{i+=o.toString()}),n.stderr.on("data",o=>{s+=o.toString()}),n.stderr.on("close",o=>{s&&r(s),t(i)})})}a(DO,"reloadNATS");async function ude(){let{pid_file_path:e}=ql(We.PROCESS_DESCRIPTORS.CLUSTERING_HUB);await DO(e)}a(ude,"reloadNATSHub");async function dde(){let{pid_file_path:e}=ql(We.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);await DO(e)}a(dde,"reloadNATSLeaf");function fde(e,t,r){let n;switch(e.code){case hV.NoResponders:n=`Unable to ${t}, node '${r}' is not listening.`;break;case hV.Timeout:n=`Unable to ${t}, node '${r}' is listening but did not respond.`;break;default:n=e.message;break}return n}a(fde,"requestErrorHandler");async function _de(e,t){let r=t+Cr.SERVER_SUFFIX.LEAF,{connection:n}=await ci(),{jsm:s}=await Rde(r),{schema:i,table:o}=e,c=Dp.createNatsTableStreamName(i,o),l=e.start_time?e.start_time:new Date(Date.now()).toISOString();await wV(async()=>{if(e.subscribe===!0)await IV(s,c,n.info.server_name,l);else try{await ade(s,c,n.info.server_name)}catch(d){ws.trace(d)}})}a(_de,"updateRemoteConsumer");async function Ede(e,t,r,n){let s=Dp.createNatsTableStreamName(e,t),i=r+Cr.SERVER_SUFFIX.LEAF,o={type:We.ITC_EVENT_TYPES.NATS_CONSUMER_UPDATE,status:n,stream_name:s,node_domain_name:i};if(!SV&&kue()<mr.get(We.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXINGESTTHREADS)){let{updateConsumer:c}=km();await c(o)}await Bue(o),n==="stop"&&await Cp.async_set_timeout(1e3)}a(Ede,"updateConsumerIterator");function wV(e){return xue.writeTransaction(We.SYSTEM_SCHEMA_NAME,We.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,e)}a(wV,"exclusiveLock");async function CV(e,t){let r=Dp.createNatsTableStreamName(e,t),n=await Lp(),s=Sde(e,t,n);await CO(r,[s])}a(CV,"createLocalTableStream");async function hde(e){for(let t=0,r=e.length;t<r;t++){let n=e[t].schema,s=e[t].table;await CV(n,s)}}a(hde,"createTableStreams");async function DV(e,t,r=void 0){if(mr.get(We.CONFIG_PARAMS.CLUSTERING_ENABLED))try{let n=Dp.createNatsTableStreamName(e,t),{domain:s}=ql(We.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);await(await(await Jf()).jetstreamManager({domain:s,timeout:24e4})).streams.purge(n,r)}catch(n){if(n.message==="stream not found")ws.warn(n);else throw n}}a(DV,"purgeTableStream");async function mde(e,t){if(mr.get(We.CONFIG_PARAMS.CLUSTERING_ENABLED))for(let r=0,n=t.length;r<n;r++)await DV(e,t[r])}a(mde,"purgeSchemaTableStreams");async function pde(e){return(await Xf()).streams.info(e)}a(pde,"getStreamInfo");function Sde(e,t,r){return`${Cr.SUBJECT_PREFIXES.TXN}.${e}${t?"."+t:""}.${r}`}a(Sde,"createSubjectName");async function Lp(){if(zf)return zf;if(zf=(await Xf())?.nc?.info?.server_name,zf===void 0)throw new Error("Unable to get jetstream manager server name");return zf}a(Lp,"getJsmServerName");async function Tde(){let e=await Xf(),t=await Lp(),r=await OV();for(let n of r){let s=n.config,i=s.subjects[0];if(!i)continue;let o=gde(n),c=i.split(".");if(c[c.length-1]===t&&!o||s.name==="__HARPERDB_WORK_QUEUE__")continue;let d=i.split(".");d[d.length-1]=t;let u=d.join(".");ws.trace(`Updating stream subject name from: ${i} to: ${u}`),s.subjects[0]=u,await e.streams.update(s.name,s)}}a(Tde,"updateLocalStreams");function gde(e){let{config:t}=e,r=!1,n=mr.get(We.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE);n=n===null?0:n*1e9;let s=mr.get(We.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES);s=s===null?-1:s;let i=mr.get(We.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS);return i=i===null?-1:i,n!==t.max_age&&(t.max_age=n,r=!0),s!==t.max_bytes&&(t.max_bytes=s,r=!0),i!==t.max_msgs&&(t.max_msgs=i,r=!0),r}a(gde,"updateStreamLimits");async function Rde(e){let t,r;try{t=await un.jetstream({domain:e}),r=await un.jetstreamManager({domain:e,checkAPI:!1})}catch(n){throw ws.error("Unable to connect to:",e),n}return{js:t,jsm:r}}a(Rde,"connectToRemoteJS")});var km=I((uye,qV)=>{"use strict";var{decode:Ade}=require("msgpackr"),{isMainThread:aye,parentPort:cye,threadId:lye}=require("worker_threads"),Up=or(),Vl=Pt(),MO=H(),Fr=X(),PO=ie(),bde=H(),{onMessageByType:yde}=at(),UV=mi(),{recordAction:Ode,recordActionBinary:Nde}=(Bi(),ae(of)),{publishToStream:Ide}=Up,{ConsumerEvents:PV}=require("nats"),wde=gn(),{promisify:Cde}=require("util"),vV=Cde(setTimeout),vp=1e4,xp,Mp,Dde,Lde,xV,Zf=new Map,$l=new Map;qV.exports={initialize:BV,ingestConsumer:UO,setSubscription:Pde,setIgnoreOrigin:vde,getDatabaseSubscriptions:Ude,updateConsumer:HV};async function BV(){yde(MO.ITC_EVENT_TYPES.NATS_CONSUMER_UPDATE,async n=>{await HV(n)}),xV=!0,Fr.notify("Initializing clustering ingest service.");let{connection:e,jsm:t,js:r}=await Up.getNATSReferences();xp=e,Mp=e.info.server_name,Dde=t,Lde=r}a(BV,"initialize");async function HV(e){if(e.status==="start"){let{js:t,jsm:r}=await kV(e.node_domain_name);UO(e.stream_name,t,r,e.node_domain_name)}else if(e.status==="stop"){let t=Zf.get(e.stream_name+e.node_domain_name);t&&(Fr.notify("Closing ingest consumer for node:",e.node_domain_name,"stream:",e.stream_name),await t.close?.(),Zf.set(e.stream_name+e.node_domain_name,"close")),$l.get(e.node_domain_name)==="failed"&&$l.set(e.node_domain_name,"close")}}a(HV,"updateConsumer");var Bp=new Map;function Pde(e,t,r){let n=Bp.get(e);n||Bp.set(e,n=new Map),n.set(t,r),xV||BV().then(Mde)}a(Pde,"setSubscription");async function Mde(){let e=await wde.searchByValue({database:"system",table:"hdb_nodes",search_attribute:"name",search_value:"*"});for await(let t of e){let r=t.name+Vl.SERVER_SUFFIX.LEAF,n,s;for(let i of t.subscriptions)if(i.subscribe===!0){if(!n&&({js:n,jsm:s}=await kV(r),!n))break;let{schema:o,table:c}=i,l=UV.createNatsTableStreamName(o,c);UO(l,n,s,r)}}}a(Mde,"accessConsumers");async function kV(e){let t,r,n=1;for(;!r;)try{t=await xp.jetstream({domain:e}),r=await xp.jetstreamManager({domain:e,checkAPI:!1})}catch(s){if($l.get(e)==="close")break;$l.set(e,"failed"),n%10===1&&Fr.warn("Nats ingest attempting to connect to:",e,"Nats error:",s.message);let i=n++*100<vp?n++*100:vp;await vV(i)}return{js:t,jsm:r}}a(kV,"connectToRemoteJS");function Ude(){return Bp}a(Ude,"getDatabaseSubscriptions");var FV;function vde(e){FV=e}a(vde,"setIgnoreOrigin");var GV=100,MV=new Array(GV),Pp=0;async function UO(e,t,r,n){let{connection:s}=await Up.getNATSReferences();xp=s,Mp=s.info.server_name;let i,o=1;for(;!i;)try{i=await t.consumers.get(e,Mp),Fr.notify("Initializing ingest consumer for node:",n,"stream:",e)}catch(d){if($l.get(n)==="close")break;o%10===1&&Fr.warn("Nats ingest error getting consumer:",n,"stream:",e,"Nats error:",d.message),d.code==="404"&&(Fr.notify("Nats ingest creating consumer for node:",n,"stream:",e),i=await Up.createConsumer(r,e,Mp,new Date(Date.now()).toISOString()));let u=o++*100<vp?o++*100:vp;await vV(u)}let c=!1,l;for(;!c;){if(Zf.get(e+n)==="close"||$l.get(n)==="close"){Zf.delete(e+n),c=!0;continue}l=await i.consume({max_messages:PO.get(MO.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXCONSUMEMSGS)??100,bind:!0}),Zf.set(e+n,l);let d=!1;(async()=>{for await(let u of await l.status())if(u.type===PV.ConsumerDeleted&&(await l.close(),c=!0),u.type===PV.HeartbeatsMissed){let f=u.data;Fr.trace(`${f} clustering ingest consumer heartbeats missed, node: ${n} stream: ${l.consumer.stream}`),f===100&&(Fr.warn(`Restarting clustering ingest consumer due to missed heartbeat threshold being met, node: ${n} stream: ${l.consumer.stream}`),l.stop(),d=!0)}})();try{for await(let u of l)await MV[Pp],MV[Pp]=xde(u).catch(f=>{Fr.error(f)}),++Pp>=GV&&(Pp=0)}catch(u){u.message==="consumer deleted"?(Fr.notify("Nats consumer deleted, closing messages for node:",n,"stream:",l.consumer.stream),await l.close(),c=!0):Fr.error("Error consuming clustering ingest, restarting consumer",u)}}}a(UO,"ingestConsumer");async function xde(e){let t=Ade(e.data);Ode(e.data.length,"bytes-received",e.subject,t.operation,"ingest"),Fr.trace("Nats message processor message size:",e?.msg?._msg?.size,"bytes");let r=e.headers,n=!1,s=PO.get(MO.CONFIG_PARAMS.CLUSTERING_NODENAME);r.has(Vl.MSG_HEADERS.TRANSACTED_NODES)&&r.values(Vl.MSG_HEADERS.TRANSACTED_NODES).indexOf(s)>-1&&(n=!0);let i=r.get(Vl.MSG_HEADERS.ORIGIN);if(n||(n=i===s&&!FV),Nde(n,"echo",e.subject,t.operation,"ingest"),n){e.ack();return}r.append(Vl.MSG_HEADERS.TRANSACTED_NODES,s);try{let{operation:o,schema:c,next:l,table:d,records:u,hash_values:f,__origin:E,expiresAt:_}=t;Fr.trace("processing message:",o,c,d,(u?"records: "+u.map(N=>N?.id):"")+(f?"ids: "+f:""),"with sequence:",e.seq),Fr.trace(`messageProcessor nats msg id: ${e.headers.get(Vl.MSG_HEADERS.NATS_MSG_ID)}`);let h;u||(u=f);let p=new Promise(N=>h=N),{timestamp:S,user:g,node_name:T}=E||{},A=Bp.get(c)?.get(d);if(!A)throw new Error("Missing table for replication message",d);if(o==="define_schema")t.type=o,t.onCommit=h,A.send(t);else if(u.length===1&&!l)A.send({type:LO(o),value:u[0],id:f?.[0],expiresAt:_,timestamp:S,table:d,onCommit:h,user:g,nodeName:T});else{let N=u.map((V,v)=>({type:LO(o),value:V,expiresAt:_,id:f?.[v],table:d}));for(;l;)N.push({type:LO(l.operation),value:l.record,expiresAt:l.expiresAt,id:l.id,table:l.table}),l=l.next;A.send({type:"transaction",writes:N,table:d,timestamp:S,onCommit:h,user:g,nodeName:T})}PO.get(bde.CONFIG_PARAMS.CLUSTERING_REPUBLISHMESSAGES)!==!1&&Ide(e.subject.split(".").slice(0,-1).join("."),UV.createNatsTableStreamName(c,d),e.headers,e.data),await p}catch(o){Fr.error(o)}e.ack()}a(xde,"messageProcessor");function LO(e){switch(e){case"insert":case"upsert":case"update":return"put"}return e}a(LO,"convertOperation")});var Bde=km();(async()=>{try{await Bde.initialize()}catch(e){console.error("Error launching Nats ingest service."),console.error(e)}})();