harperdb 4.3.18 → 4.3.20
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -3
- package/bin/harperdb.js +51 -51
- package/bin/lite.js +20 -20
- package/launchServiceScripts/launchInstallNATSServer.js +2 -2
- package/launchServiceScripts/launchNatsIngestService.js +20 -20
- package/launchServiceScripts/launchNatsReplyService.js +20 -20
- package/launchServiceScripts/launchUpdateNodes4-0-0.js +20 -20
- package/npm-shrinkwrap.json +93 -276
- package/package.json +3 -3
- package/resources/IterableEventQueue.d.ts +0 -1
- package/resources/Resource.d.ts +16 -16
- package/resources/ResourceInterface.d.ts +56 -13
- package/resources/auditStore.d.ts +0 -1
- package/resources/transaction.d.ts +7 -0
- package/server/Server.d.ts +0 -2
- package/server/jobs/jobProcess.js +20 -20
- package/server/threads/threadServer.js +20 -20
- package/studio/build-local/asset-manifest.json +2 -2
- package/studio/build-local/index.html +1 -1
- package/studio/build-local/static/js/{main.3213e963.js → main.35352915.js} +2 -2
- package/utility/scripts/restartHdb.js +20 -20
- package/resources/Table.d.ts +0 -589
- package/resources/databases.d.ts +0 -419
- /package/studio/build-local/static/js/{main.3213e963.js.LICENSE.txt → main.35352915.js.LICENSE.txt} +0 -0
|
@@ -1,32 +1,32 @@
|
|
|
1
|
-
"use strict";var Oq=Object.create;var cc=Object.defineProperty;var bq=Object.getOwnPropertyDescriptor;var yq=Object.getOwnPropertyNames;var Nq=Object.getPrototypeOf,Iq=Object.prototype.hasOwnProperty;var a=(e,t)=>cc(e,"name",{value:t,configurable:!0});var Ae=(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)cc(e,r,{get:t[r],enumerable:!0})},_O=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of yq(t))!Iq.call(e,s)&&s!==r&&cc(e,s,{get:()=>t[s],enumerable:!(n=bq(t,s))||n.enumerable});return e};var B=(e,t,r)=>(r=e!=null?Oq(Nq(e)):{},_O(t||!e||!e.__esModule?cc(r,"default",{value:e,enumerable:!0}):r,e)),ie=e=>_O(cc({},"__esModule",{value:!0}),e);var EO=g((jae,fO)=>{var wq=require("fast-glob"),{statSync:Dh,existsSync:Lh,readFileSync:Cq,writeFileSync:Dq}=require("fs"),{spawnSync:Lq,spawn:Mq,execFileSync:Jae}=require("child_process"),{isMainThread:Pq}=require("worker_threads"),{join:Xs,relative:dO}=require("path"),{PACKAGE_ROOT:bn}=P(),{tmpdir:Uq,platform:vq}=require("os");require("source-map-support").install();var Bq=["resources","server","dataLayer","components"],uc="ts-build",Mh,Hq=__filename.endsWith("tsBuild.js");if(Hq){if(Pq){let r;try{Dh(Xs(bn,uc)),r=!0}catch{}if(r)for(let n of wq.sync(Bq.map(s=>s+"/**/*.ts"),{cwd:bn})){let s=0,i=0;try{s=Dh(Xs(bn,n)).mtimeMs-5e3,i=Dh(Xs(bn,uc,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."),Mh=!0;break}}else console.log("TypeScript modules are not compiled, compiling now"),Mh=!0;if(Mh){let n=Xs(bn,"node_modules/.bin/tsc");vq()==="win32"&&(n+=".cmd");let s=Lq(n,{cwd:bn});if(s.stdout?.length&&console.log(s.stdout.toString()),s.stderr?.length&&console.log(s.stderr.toString()),r){let i=Xs(Uq(),"harperdb-tsc.pid"),o;if(Lh(i))try{process.kill(+Cq(i,{encoding:"utf8"}),0),o=!0}catch{}if(!o){console.log("starting tsc background process");let c=Mq(n,["--watch"],{cwd:bn,detached:!0,stdio:"ignore"});Dq(i,c.pid.toString()),c.unref()}}}}let e=fO.constructor,t=e._findPath;e._findPath=function(r,n,s){if(r.startsWith(".")&&!s&&n.length===1&&n[0].startsWith(bn)&&!n[0].includes("node_modules")){let i=dO(bn,n[0]),o;i.startsWith(uc)?o=Xs(bn,dO(uc,i)):o=Xs(bn,uc,i);let c=Xs(o,r),u=c+".js";if(Lh(u))return u;if(c.includes(".")&&Lh(c))return c}return t(r,n,s)}}});var P=g((ece,wO)=>{"use strict";var an=require("path"),xq=require("fs"),{relative:Xae,join:Zae}=an,{existsSync:Gq}=xq;function qq(){let e=__dirname;for(;!Gq(an.join(e,"package.json"));){let t=an.dirname(e);if(t===e)throw new Error("Could not find package root");e=t}return e}a(qq,"getHDBPackageRoot");var Zs=qq(),hO="js",e_=hO,Fq="harperdb-config.yaml",kq="defaultConfig.yaml",Vq="hdb",mO=`harperdb.${e_}`,pO=`customFunctionsServer.${e_}`,$q=`restartHdb.${e_}`,Uh="HarperDB",Zl="Custom Functions",t_="Clustering Hub",r_="Clustering Leaf",Yq="Clustering Ingest Service",Kq="Clustering Reply Service",Wq="foreground.pid",Qq="hdb.pid",zq="data",Jq={HDB:Uh,CLUSTERING_HUB:t_,CLUSTERING_LEAF:r_,CLUSTERING_INGEST_SERVICE:Yq,CLUSTERING_REPLY_SERVICE:Kq,CUSTOM_FUNCTIONS:Zl,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"},jq={HDB:"hdb.log",INSTALL:"install.log",CLUSTERING_HUB:"clustering_hub.log",CLUSTERING_LEAF:"clustering_leaf.log"},Xq={NOTIFY:"notify",FATAL:"fatal",ERROR:"error",WARN:"warn",INFO:"info",DEBUG:"debug",TRACE:"trace"},Zq={harperdb:Uh,"clustering hub":t_,"clustering leaf":r_,"custom functions":Zl,custom_functions:Zl,clustering:"clustering","clustering config":"clustering config",clustering_config:"clustering_config",http_workers:"http_workers"},eF={CLUSTERING_HUB_PROC_DESCRIPTOR:t_,CLUSTERING_LEAF_PROC_DESCRIPTOR:r_},Ph={HDB:an.join(Zs,"server/harperdb"),CUSTOM_FUNCTIONS:an.join(Zs,"server/customFunctions"),CLUSTERING_HUB:an.join(Zs,"server/nats"),CLUSTERING_LEAF:an.join(Zs,"server/nats")},tF={HDB:an.join(Ph.HDB,mO),CUSTOM_FUNCTIONS:an.join(Ph.CUSTOM_FUNCTIONS,pO)},rF={MAIN:"bin/harperdb.js",NATS_INGEST_SERVICE:an.join(Zs,"launchServiceScripts/launchNatsIngestService.js"),NATS_REPLY_SERVICE:an.join(Zs,"launchServiceScripts/launchNatsReplyService.js"),NODES_UPGRADE_4_0_0:an.join(Zs,"launchServiceScripts/launchUpdateNodes4-0-0.js")},nF={SUPER_USER:"super_user",CLUSTER_USER:"cluster_user"},SO="support@harperdb.io",sF="customer-success@harperdb.io",TO=1,iF=4141,gO="https://harperdbhelp.zendesk.com/hc/en-us/requests/new",oF="https://www.harperdb.io/product",aF=`For support, please submit a request at ${gO} or contact ${SO}`,RO=`For license support, please contact ${sF}`,cF="None of the specified records were found.",uF="hash attribute not found",lF=`Your current license only supports ${TO} role. ${RO}`,_F="Your current license only supports 3 connections to a node.",dF="127.0.0.1",fF=1,EF=/^\.$/,hF=/^\.\.$/,mF="U+002E",pF=/\//g,SF="U+002F",TF=/U\+002F/g,gF=/^U\+002E$/,RF=/^U\+002EU\+002E$/,AF="d",OF=999999,bF="*",yF="--max-old-space-size=",NF="system",IF="__hdb_hash",wF=".harperdb",CF=".hdb",DF="keys",LF="hdb_boot_properties.file",MF=".updateConfig.json",PF="SIGTSTP",UF=24,vF=6e4,BF=448,HF="blob",xF="trash",GF="database",qF="schema",FF="transactions",kF=".count",VF="id",$F="PROCESS_NAME",AO={SETTINGS_PATH_KEY:"settings_path"},OO=require("lodash"),YF={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"},KF={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},WF={DATA_VERSION:"data_version",UPGRADE_VERSION:"upgrade_version"},QF={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"},zF={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:",JF={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"},jF={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"},XF="060493.ks",ZF=".license",ek={CREATED:"CREATED",IN_PROGRESS:"IN_PROGRESS",COMPLETE:"COMPLETE",ERROR:"ERROR"},ee={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"},tk={CSV:".csv",JSON:".json"},rk={AWS_ACCESS_KEY:"aws_access_key_id",AWS_SECRET:"aws_secret_access_key",AWS_BUCKET:"bucket",AWS_FILE_KEY:"key",REGION:"region"},nk={SELECT:"select",INSERT:"insert",UPDATE:"update",DELETE:"delete"},lc={};lc[ee.INSERT]=ee.INSERT;lc[ee.UPDATE]=ee.UPDATE;lc[ee.UPSERT]=ee.UPSERT;lc[ee.DELETE]=ee.DELETE;var Be=Object.create(null);Be[ee.DESCRIBE_ALL]=ee.DESCRIBE_ALL;Be[ee.DESCRIBE_TABLE]=ee.DESCRIBE_TABLE;Be[ee.DESCRIBE_SCHEMA]=ee.DESCRIBE_SCHEMA;Be[ee.READ_LOG]=ee.READ_LOG;Be[ee.ADD_NODE]=ee.ADD_NODE;Be[ee.LIST_USERS]=ee.LIST_USERS;Be[ee.LIST_ROLES]=ee.LIST_ROLES;Be[ee.USER_INFO]=ee.USER_INFO;Be[ee.SQL]=ee.SQL;Be[ee.GET_JOB]=ee.GET_JOB;Be[ee.SEARCH_JOBS_BY_START_DATE]=ee.SEARCH_JOBS_BY_START_DATE;Be[ee.DELETE_FILES_BEFORE]=ee.DELETE_FILES_BEFORE;Be[ee.EXPORT_LOCAL]=ee.EXPORT_LOCAL;Be[ee.EXPORT_TO_S3]=ee.EXPORT_TO_S3;Be[ee.CLUSTER_STATUS]=ee.CLUSTER_STATUS;Be[ee.REMOVE_NODE]=ee.REMOVE_NODE;Be[ee.RESTART]=ee.RESTART;Be[ee.CUSTOM_FUNCTIONS_STATUS]=ee.CUSTOM_FUNCTIONS_STATUS;Be[ee.GET_CUSTOM_FUNCTIONS]=ee.GET_CUSTOM_FUNCTIONS;Be[ee.GET_CUSTOM_FUNCTION]=ee.GET_CUSTOM_FUNCTION;Be[ee.SET_CUSTOM_FUNCTION]=ee.SET_CUSTOM_FUNCTION;Be[ee.DROP_CUSTOM_FUNCTION]=ee.DROP_CUSTOM_FUNCTION;Be[ee.ADD_CUSTOM_FUNCTION_PROJECT]=ee.ADD_CUSTOM_FUNCTION_PROJECT;Be[ee.DROP_CUSTOM_FUNCTION_PROJECT]=ee.DROP_CUSTOM_FUNCTION_PROJECT;Be[ee.PACKAGE_CUSTOM_FUNCTION_PROJECT]=ee.PACKAGE_CUSTOM_FUNCTION_PROJECT;Be[ee.DEPLOY_CUSTOM_FUNCTION_PROJECT]=ee.DEPLOY_CUSTOM_FUNCTION_PROJECT;var sk={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"},ik={point:"point",lineString:"lineString",multiLineString:"multiLineString",multiPoint:"multiPoint",multiPolygon:"multiPolygon",polygon:"polygon"},bO={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"},ok=OO.invert(bO),ak={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"},yO={settings_path:AO.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];yO[t.toLowerCase()]=t}var ck={TABLES:"tables",PATH:"path",AUDIT_PATH:"auditPath"},uk={csv_file_load:"csv_file_load",csv_data_load:ee.CSV_DATA_LOAD,csv_url_load:ee.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"},lk={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"},_k={BIDIRECTIONAL:"BIDIRECTIONAL",OUTBOUND:"OUTBOUND",INBOUND:"INBOUND"},dk={VERSION_DEFAULT:"2.2.0"},fk={DEVELOPMENT:8192,DEFAULT:512},Ek={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"},hk={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"},mk={ENOENT:"ENOENT",EACCES:"EACCES",EEXIST:"EEXIST",ERR_INVALID_ARG_TYPE:"ERR_INVALID_ARG_TYPE"},NO={CREATED_TIME:"__createdtime__",UPDATED_TIME:"__updatedtime__"},pk=Symbol("metadata"),Sk="__clustering__",Tk=Object.values(NO),gk=15984864e5,IO={LESS:"<",LESS_OR_EQ:"<=",GREATER:">",GREATER_OR_EQ:">=",BETWEEN:"..."},Rk=OO.invert(IO),Ak={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"},Ok=111,bk=`\r
|
|
2
|
-
`,
|
|
3
|
-
`}a(
|
|
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:nV.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(aV,"findPs")});var _t=g((cce,YO)=>{"use strict";var cV="__dbis__",uV="__txns__",lV="__environment_name__",_V="__dbi_defintion__",dV={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"},fV=["__createdtime__","__updatedtime__"],EV="\uFFFF",$O={TIMESTAMP:"timestamp",HASH_VALUE:"hash_value",USER_NAME:"user_name"},hV=Object.values($O);YO.exports={AUDIT_STORE_NAME:uV,INTERNAL_DBIS_NAME:cV,DBI_DEFINITION_NAME:_V,SEARCH_TYPES:dV,TIMESTAMP_NAMES:fV,MAX_SEARCH_KEY_LENGTH:256,ENVIRONMENT_NAME_KEY:lV,TRANSACTIONS_DBI_NAMES_ENUM:$O,TRANSACTIONS_DBIS:hV,OVERFLOW_MARKER:EV}});var Ur=g((uce,eb)=>{"use strict";var KO=P(),WO=_t(),QO={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},zO=a(e=>`${e} Check logs and try again.`,"CHECK_LOGS_WRAPPER"),JO={500:zO("There was an error processing your request."),400:"Invalid request"},mV=JO[QO.INTERNAL_SERVER_ERROR],pV={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.`},SV={CONFIG_VALIDATION:e=>`HarperDB config file validation error: ${e}`},TV={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"},gV={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 ${WO.INTERNAL_DBIS_NAME}`,CANNOT_DROP_INTERNAL_DBIS_NAME:`cannot drop a dbi named ${WO.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"},RV={ATTR_NAME_LENGTH_ERR:e=>`transaction aborted due to attribute name ${e} being too long. Attribute names cannot be longer than ${KO.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 ${KO.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"},jO={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"},AV={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."},OV={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`},bV={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"},yV={OUTER_JOIN_TRANSLATION_ERROR:"There was an error translating the final SQL outer join data."},NV={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`},XO={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.`},ZO={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}`},IV={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."},wV={CLUSTERING_NOT_ENABLED:"Clustering must be enabled to perform this operation."},CV={...jO,...TV,...pV,...AV,...OV,...bV,...yV,...NV,...RV,...XO,...ZO,...IV,...wV,...SV};eb.exports={CHECK_LOGS_WRAPPER:zO,HDB_ERROR_MSGS:CV,DEFAULT_ERROR_MSGS:JO,DEFAULT_ERROR_RESP:mV,HTTP_STATUS_CODES:QO,LMDB_ERRORS_ENUM:gV,AUTHENTICATION_ERROR_MSGS:jO,VALIDATION_ERROR_MSGS:XO,ITC_ERRORS:ZO}});var ne=g((_ce,nb)=>{"use strict";var Vo=Ur(),DV=$(),LV=P(),a_=class extends Error{static{a(this,"HdbError")}constructor(t,r,n,s,i){super(),Error.captureStackTrace(this,tb),this.statusCode=n||Vo.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR,this.http_resp_msg=r||(Vo.DEFAULT_ERROR_MSGS[n]?Vo.DEFAULT_ERROR_MSGS[n]:Vo.DEFAULT_ERROR_MSGS[Vo.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&&DV[s](i)}},Vh=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}},$h=class extends Error{static{a(this,"ServerError")}constructor(t,r){super(t),this.statusCode=r||500}};function tb(e,t,r,n=LV.LOG_LEVELS.ERROR,s=null,i=!1){if(rb(e))return e;let o=new a_(e,t,r,n,s);return i&&delete o.stack,o}a(tb,"handleHDBError");function rb(e){return e.__proto__.constructor.name===a_.name}a(rb,"isHDBError");nb.exports={isHDBError:rb,handleHDBError:tb,ClientError:Vh,ServerError:$h,hdb_errors:Vo}});var ze=g((fce,lb)=>{"use strict";var gc=P(),MV=J(),cr=Z(),Rc=require("path"),PV=require("minimist"),sb=require("fs-extra"),ib=require("lodash");cr.initSync();var{CONFIG_PARAMS:ei,DATABASES_PARAM_CONFIG:mc,SYSTEM_SCHEMA_NAME:c_}=gc,pc,Sc,Tc;function ob(){if(pc!==void 0)return pc;if(cr.getHdbBasePath()!==void 0)return pc=cr.get(ei.STORAGE_PATH)||Rc.join(cr.getHdbBasePath(),gc.DATABASES_DIR_NAME),pc}a(ob,"getBaseSchemaPath");function ab(){if(Sc!==void 0)return Sc;if(cr.getHdbBasePath()!==void 0)return Sc=ub(c_),Sc}a(ab,"getSystemSchemaPath");function cb(){if(Tc!==void 0)return Tc;if(cr.getHdbBasePath()!==void 0)return Tc=cr.get(gc.CONFIG_PARAMS.STORAGE_AUDIT_PATH)||Rc.join(cr.getHdbBasePath(),gc.TRANSACTIONS_DIR_NAME),Tc}a(cb,"getTransactionAuditStoreBasePath");function UV(e,t){let r=cr.get(ei.DATABASES)?.[e];return t&&r?.tables?.[t]?.auditPath||r?.auditPath||Rc.join(cb(),e.toString())}a(UV,"getTransactionAuditStorePath");function ub(e,t){e=e.toString(),t=t&&t.toString();let r=cr.get(gc.CONFIG_PARAMS.DATABASES)?.[e];return t&&r?.tables?.[t]?.path||r?.path||Rc.join(ob(),e)}a(ub,"getSchemaPath");function vV(e,t){e=e.toString(),t=t.toString();let r=process.env;Object.assign(r,PV(process.argv));let n=r[ei.DATABASES.toUpperCase()];if(n){let i;try{i=JSON.parse(n)}catch(o){if(!MV.isObject(n))throw o;i=n}for(let o of i){let c=o[c_];if(!c)continue;let u=cr.get(ei.DATABASES);u=u??{};let _=c?.tables?.[t]?.[mc.PATH];if(_)return ib.set(u,[c_,mc.TABLES,t,mc.PATH],_),cr.setProperty(ei.DATABASES,u),_;let l=c?.[mc.PATH];if(l)return ib.set(u,[c_,mc.PATH],l),cr.setProperty(ei.DATABASES,u),l}}let s=r[ei.STORAGE_PATH.toUpperCase()];if(s){if(!sb.pathExistsSync(s))throw new Error(s+" does not exist");let i=Rc.join(s,e);return sb.mkdirsSync(i),cr.setProperty(ei.STORAGE_PATH,s),i}return ab()}a(vV,"initSystemSchemaPaths");function BV(){pc=void 0,Sc=void 0,Tc=void 0}a(BV,"resetPaths");lb.exports={getBaseSchemaPath:ob,getSystemSchemaPath:ab,getTransactionAuditStorePath:UV,getTransactionAuditStoreBasePath:cb,getSchemaPath:ub,initSystemSchemaPaths:vV,resetPaths:BV}});var vr=g((pce,hb)=>{"use strict";var HV=Ur().LMDB_ERRORS_ENUM,hce=require("lmdb"),xV=_t(),mce=require("buffer").Buffer,{OVERFLOW_MARKER:_b,MAX_SEARCH_KEY_LENGTH:u_}=xV,db=["number","string","symbol","boolean","bigint"];function GV(e){if(e=e?.primaryStore||e,!e)throw new Error(HV.ENV_REQUIRED)}a(GV,"validateEnv");function qV(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(qV,"stringifyData");function FV(e){return e instanceof Date?e.valueOf():e}a(FV,"convertKeyValueToWrite");function kV(e,t){if(e===null)return t?[null]:void 0;if(e===void 0)return;if(db.includes(typeof e))return e.length>u_?[e.slice(0,u_)+_b]:[e];let r;if(Array.isArray(e)){r=[];for(let n=0,s=e.length;n<s;n++){let i=e[n];if(db.includes(typeof i))i.length>u_?r.push(i.slice(0,u_)+_b):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(kV,"getIndexedValues");var l_=0,fb=0;function Eb(){fb=Date.now()-performance.now()}a(Eb,"adjustStartTime");Eb();var VV=6e4;setInterval(Eb,VV).unref();function $V(){let e=performance.now()+fb;return e>l_?(l_=e,e):(l_+=488e-6,l_)}a($V,"getNextMonotonicTime");hb.exports={validateEnv:GV,stringifyData:qV,convertKeyValueToWrite:FV,getNextMonotonicTime:$V,getIndexedValues:kV}});var mb,yn,Yh,Ac=Ae(()=>{mb=require("events"),yn=class extends mb.EventEmitter{static{a(this,"IterableEventQueue")}resolveNext;queue;hasDataListeners;[Symbol.asyncIterator](){let t=new Yh;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)}},Yh=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 Hi={};qe(Hi,{server:()=>st});var pb,st,ur=Ae(()=>{pb=require("../index"),st={};(0,pb._assignPackageExport)("server",st)});var Qh={};qe(Qh,{loadGQLSchema:()=>WV,start:()=>Wh,startOnMainThread:()=>KV});function Wh({ensureTable:e}){return{handleFile:t,setupFile:t};async function t(r,n,s,i){let{parse:o,Source:c,Kind:u,NamedTypeNode:_,StringValueNode:l}=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 u.OBJECT_TYPE_DEFINITION:let x=function(v){if(v.kind==="NonNullType"){let Q=x(v.type);return Q.nullable=!1,Q}if(v.kind==="ListType")return{type:"array",elements:x(v.type)};let M={type:v.name?.value};return Object.defineProperty(M,"location",{value:v.loc.startToken}),M};a(x,"getProperty");let T=S.name.value,A=[],R={table:null,database:null,properties:A};E.set(T,R);for(let v of S.directives){if(v.name.value==="table"){for(let k of v.arguments)R[k.name.value]=k.value.value;R.schema&&(R.database=R.schema),R.table||(R.table=T),R.audit&&(R.audit=R.audit!=="false"),R.attributes=R.properties,f.push(R)}if(v.name.value==="sealed"&&(R.sealed=!0),v.name.value==="export"){R.export=!0;for(let k of v.arguments)k.name.value==="name"&&(R.export={name:k.value.value})}}let C=!1;for(let v of S.fields){let k=x(v.type);k.name=v.name.value,A.push(k);for(let M of v.directives)if(M.name.value==="primaryKey")C?console.warn("Can not define two attributes as a primary key"):(k.isPrimaryKey=!0,C=!0);else if(M.name.value==="indexed")k.indexed=!0;else if(M.name.value==="relationship"){let Q={};for(let j of M.arguments)Q[j.name.value]=j.value.value;k.relationship=Q}else if(M.name.value==="createdTime")k.assignCreatedTime=!0;else if(M.name.value==="updatedTime")k.assignUpdatedTime=!0;else if(M.name.value==="expiresAt")k.expiresAt=!0;else if(M.name.value==="allow"){let Q=k.authorizedRoles=[];for(let j of M.arguments)j.name.value==="role"&&Q.push(j.value.value)}}R.type=T,T==="Query"&&(h=R)}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):YV.includes(S.type)||(0,Sb.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,Kh.dirname)(n),S.tableClass):i.set((0,Kh.dirname)(n)+"/"+(S.export.name||S.type),S.tableClass))}}var Kh,Sb,YV,KV,WV,Tb=Ae(()=>{Kh=require("path");Oe();Sb=B(Je()),YV=["ID","Int","Float","Long","String","Boolean","Date","Bytes","Any","BigInt"];a(Wh,"start");KV=Wh,WV=Wh({ensureTable:dt}).handleFile});async function __(e){let t=(0,Ab.pathToFileURL)(e).toString();return QV?(Oc||(Oc=zV(jV)),(await(await Oc).import(t)).namespace):import(t)}async function zV(e){let{StaticModuleRecord:t}=await import("@endo/static-module-record");return require("ses"),lockdown({domainTaming:"unsafe",consoleTaming:"unsafe",errorTaming:"unsafe",errorTrapping:"none",stackFiltering:"verbose"}),Oc=new Compartment({console,Math,Date,fetch:JV,...e()},{},{name:"h-dapp",resolveHook(r,n){return r==="harperdb"?"harperdb":(r=new URL(r,n).toString(),(0,Rb.extname)(r)||(r+=".js"),r)},importHook:async r=>{if(r==="harperdb")return{imports:[],exports:["Resource","tables","databases"],execute(s){Object.assign(s,{Resource:Vt,tables:Br,databases:it})}};let n=await(0,gb.readFile)(new URL(r),{encoding:"utf-8"});return new t(n,r)}}),Oc}function JV(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 jV(){return{Resource:Vt,tables:Br}}var gb,Rb,Ab,QV,Oc,zh=Ae(()=>{Nn();Oe();gb=require("fs/promises"),Rb=require("path"),Ab=require("url"),QV=!1;a(__,"secureImport");a(zV,"getCompartment");a(JV,"secureOnlyFetch");a(jV,"getGlobalVars")});var jh={};qe(jh,{handleFile:()=>XV});async function XV(e,t,r,n){let s=new Map,i=await __(r);c(i.default)&&n.set((0,Jh.dirname)(t),i.default),o(i,(0,Jh.dirname)(t));function o(u,_){for(let l in u){let d=u[l];c(d)?n.set(_+"/"+l,d):typeof d=="object"&&o(d,_+"/"+l)}}a(o,"recurseForResources");function c(u){return typeof u=="function"&&(u.get||u.put||u.post||u.delete)}return a(c,"isResource"),s}var Jh,Ob=Ae(()=>{zh();Jh=require("path");a(XV,"handleFile")});var Zh={};qe(Zh,{start:()=>ZV});function ZV({resources:e}){e.set("login",Xh),e.loginPath=t=>"/login?redirect="+encodeURIComponent(t.url)}var Xh,bb=Ae(()=>{Nn();a(ZV,"start");Xh=class extends Vt{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 Lb={};qe(Lb,{parse:()=>tm,streamAsJSON:()=>bc,stringify:()=>xi});function bc(e){return new em({value:e})}function yb(e){return console.error(e),JSON.stringify(e.toString())}function Nb(e,t,r){return e?.then?r?e.then(t,r):e.then(t):t(e)}function xi(e){try{return JSON.stringify(e)??"null"}catch(t){if(t===Cb)return Db(e);if(t.resolution)return t.resolution.then(()=>xi(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)+":"+xi(e[s]);return r+"}"}}else{if(t==="string")return JSON.stringify(e);if(t==="undefined")return"null"}return e.toString()}function tm(e){return r$.test(e)?e$.parse(e):JSON.parse(e)}var Ib,wb,e$,t$,Cb,em,r$,rm=Ae(()=>{Ib=require("stream"),wb=B(require("json-bigint-fixes")),e$=(0,wb.default)({useNativeBigInt:!0}),t$=1e4,Cb={};BigInt.prototype.toJSON=function(){throw Cb};a(bc,"streamAsJSON");em=class extends Ib.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),yb)}catch(s){yield yb(s)}else yield xi(t)}else yield xi(t)}_read(){if(!this._amReading){if(this._amReading=!0,this.done)return this.push(null);Nb(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>t$?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 Nb(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(yb,"handleError");a(Nb,"when");a(xi,"stringify");a(Db,"jsStringify");r$=/[[,:]\s*-?\d{16,}/;a(tm,"parse")});var $b=g((Pce,Vb)=>{"use strict";var nm=require("recursive-iterator"),n$=require("alasql"),sm=require("clone"),Mb=J(),{handleHDBError:Pb,hdb_errors:s$}=ne(),{HDB_ERROR_MSGS:Ub,HTTP_STATUS_CODES:vb}=s$,{getDatabases:i$}=(Oe(),ie(Fe)),o$=["DISTINCT_ARRAY"],Bb=Symbol("validateTables"),im=Symbol("validateTable"),Mce=Symbol("getAllColumns"),Hb=Symbol("validateAllColumns"),d_=Symbol("findColumn"),xb=Symbol("validateOrderBy"),yc=Symbol("validateSegment"),om=Symbol("validateColumn"),Gb=Symbol("setColumnsForTable"),qb=Symbol("checkColumnsForAsterisk"),Fb=Symbol("validateGroupBy"),kb=Symbol("hasColumns"),am=class{static{a(this,"SelectValidator")}constructor(t){this.statement=t,this.attributes=[]}validate(){if(!this.statement)throw new Error("invalid sql statement");this[Bb](),this[qb](),this[Hb]()}[Bb](){if(this[kb]()){if(!this.statement.from||this.statement.from.length===0)throw"no from clause";this.statement.from.forEach(t=>{this[im](t)}),this.statement.joins&&this.statement.joins.forEach(t=>{t.table.as=t.as,this[im](t.table)})}}[kb](){let t=!1,r=new nm(this.statement);for(let{node:n,path:s}of r)if(n&&n.columnid){t=!0;break}return t}[im](t){if(!t.databaseid)throw`schema not defined for table ${t.tableid}`;let r=i$();if(!r[t.databaseid])throw Pb(new Error,Ub.SCHEMA_NOT_FOUND(t.databaseid),vb.NOT_FOUND);if(!r[t.databaseid][t.tableid])throw Pb(new Error,Ub.TABLE_NOT_FOUND(t.databaseid,t.tableid),vb.NOT_FOUND);r[t.databaseid][t.tableid].attributes.forEach(s=>{let i=sm(s);i.table=sm(t),this.attributes.push(i)})}[d_](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)}[qb](){let t=new nm(this.statement.columns);for(let{node:r,path:n}of t)r&&r.columnid==="*"&&n.indexOf("expression")<0&&this[Gb](r.tableid)}[Gb](t){this.attributes.forEach(r=>{(!t||t&&(r.table.tableid===t||r.table.as===t))&&!r.relation&&this.statement.columns.push(new n$.yy.Column({columnid:r.attribute,tableid:r.table.as?r.table.as:r.table.tableid}))})}[Hb](){this[yc](this.statement.columns,!1),this[yc](this.statement.joins,!1),this[yc](this.statement.where,!1),this[Fb](this.statement.group,!1),this[yc](this.statement.order,!0)}[yc](t,r){if(!t)return;let n=new nm(t),s=[];for(let{node:i,path:o}of n)!Mb.isEmpty(i)&&!Mb.isEmpty(i.columnid)&&i.columnid!=="*"&&(r?this[xb](i):s.push(this[om](i)));return s}[Fb](t){if(!t)return;let r=[];if(this.statement.columns.forEach(n=>{if(!(n.funcid&&o$.indexOf(n.funcid.toUpperCase())>=0)){if(!n.aggregatorid&&!n.columnid){let s=sm(n);delete s.as,r.push(s)}else if(n.columnid){let s=this[d_](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[d_](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`}[xb](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[om](t)}[om](t){let r=this[d_](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]}};Vb.exports=am});var Kb=g((vce,Yb)=>{"use strict";var cm=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")}};Yb.exports=cm});var Qb=g((Hce,Wb)=>{"use strict";var um=class{static{a(this,"DBIDefinition")}constructor(t=!1,r=!1){this.dup_sort=t,this.is_hash_attribute=r,this.useVersions=r}};Wb.exports=um});var Xb={};qe(Xb,{HAS_EXPIRATION:()=>mm,LAST_TIMESTAMP_PLACEHOLDER:()=>wc,LOCAL_TIMESTAMP:()=>a$,METADATA:()=>Nc,NO_TIMESTAMP:()=>_m,PENDING_LOCAL_TIME:()=>pm,PREVIOUS_TIMESTAMP_PLACEHOLDER:()=>hm,RecordEncoder:()=>Em,TIMESTAMP_ASSIGN_LAST:()=>u$,TIMESTAMP_ASSIGN_NEW:()=>Jb,TIMESTAMP_ASSIGN_PREVIOUS:()=>jb,TIMESTAMP_PLACEHOLDER:()=>f_,TIMESTAMP_RECORD_PREVIOUS:()=>dm,getUpdateRecord:()=>Sm,handleLocalTimeForGets:()=>p_});function _$(){return Ic[0]=Ic[0]^64,c$.getFloat64(0)}function p_(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),u=c?.value,_=u?.[Nc];return _>=0&&(c.metadataFlags=_,c.localTime=u.localTime,c.value=u.value,u.expiresAt>0&&(c.expiresAt=u.expiresAt)),c&&(c.key=i),c};let r=e.get;e.get=function(i,o){let c=r.call(this,i,o);return c?.[Nc]>=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 u=c.value,_=u[Nc];return _>=0&&(c.metadataFlags=_,c.localTime=u.localTime,c.value=u.value,u.expiresAt>0&&(c.expiresAt=u.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,Gi.push(new WeakRef(this))),o.call(this)},i.prototype.done=function(){if(c.call(this),this.isDone)for(let u=0;u<Gi.length;u++){let _=Gi[u].deref();(!_||_.isDone||_.isCommitted)&&Gi.splice(u--,1)}},i.prototype.done.isTracked=!0}return e}function Sm(e,t,r){return function(n,s,i,o,c=-1,u,_,l,d="put",E,f){if(E||u==null?$o=i?.localTime?dm|jb:_m:$o=u?i?.localTime?dm|16384:Jb|16384:_m,l>0&&(c|=mm),h_=c,fm=l,i?.version===o&&u===!1)throw new Error("Must retain local time if version is not changed");let h={version:o,instructedWrite:$o>0},p;try{E&&(h.ifVersion=p=i?.version??null);let S=e.put(n,s,h);if(u){let T=_?.user?.username;if(f&&(E_=e.encoder.encode(f)),E&&i?.localTime){let A=i?.localTime,R=r.get(A);if(R){let C=Ut(R).previousLocalTime;return r.put(A,m_(o,t,n,C,T,d,E_),{ifVersion:p}),S}}r.put(wc,m_(o,t,n,i?.localTime?1:0,T,d,E_),{append:d!=="invalidate",instructedWrite:!0,ifVersion:p})}return S}catch(S){throw S.message+=" id: "+n+" options: "+h,S}}}var zb,lm,f_,wc,hm,a$,Nc,Ic,c$,_m,Jb,u$,jb,dm,mm,pm,l$,E_,$o,h_,fm,Em,Gi,Cc=Ae(()=>{zb=require("msgpackr");ti();lm=B($()),f_=new Uint8Array([1,1,1,1,4,64,0,0]),wc=new Uint8Array([1,1,1,1,1,0,0,0]),hm=new Uint8Array([1,1,1,1,3,64,0,0]),a$=Symbol("local-timestamp"),Nc=Symbol("metadata"),Ic=new Uint8Array(8),c$=new DataView(Ic.buffer,0,8),_m=0,Jb=0,u$=1,jb=3,dm=4,mm=16,pm=1,$o=0,h_=-1,fm=0,Em=class extends zb.Encoder{static{a(this,"RecordEncoder")}constructor(t){t.useBigIntExtension=!0,super(t);let r=this.encode;this.encode=function(n,s){if($o||h_>=0){let i=0,o=$o;o&&(i+=8,$o=0);let c=h_,u=fm;c>=0&&(i+=2,h_=-1,u&&(i+=8,fm=0));let _=l$=r.call(this,n,s|2048|i);E_=_.subarray((_.start||0)+i,_.end);let l=_.start||0;return o&&(f_[4]=o,f_[5]=o>>8,_.set(f_,l),l+=8),c>=0&&(_[l++]=c,_[l++]=0,u&&(_.dataView||(_.dataView=new DataView(_.buffer,_.byteOffset,_.byteLength))).setFloat64(l,u)),_}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,u;if(i===2){if(t.copy)t.copy(Ic,0,c),c+=8;else for(let d=0;d<8;d++)Ic[d]=t[c++];u=_$(),i=t[c]}let _;i<32&&(o=i,c+=2,o&mm&&(_=(t.dataView||(t.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength))).getFloat64(c),c+=8));let l=super.decode(t.subarray(c,s),s-c);return{localTime:u,value:l,[Nc]:o,expiresAt:_}}return super.decode(t,r)}catch(c){throw c.message+=", data: "+t.slice(0,40).toString("hex"),c}}};a(_$,"getTimestamp");a(p_,"handleLocalTimeForGets");Gi=[];setInterval(()=>{for(let e=0;e<Gi.length;e++){let t=Gi[e].deref();!t||t.isDone||t.isCommitted?Gi.splice(e--,1):t.notCurrent&&(t.openTimer?(t.openTimer>3&&(t.openTimer>60?(lm.error("Read transaction detected that has been open too long (over 15 minutes), ending transaction",t),t.done()):lm.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(Sm,"getUpdateRecord")});var Dc=g((kce,ey)=>{"use strict";var Zb=Z(),d$=P(),{RecordEncoder:f$}=(Cc(),ie(Xb)),Fce=require("fs");Zb.initSync();var E$=Zb.get(d$.CONFIG_PARAMS.STORAGE_CACHING)!==!1,Tm=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=E$&&{validated:!0},this.randomAccessStructure=!0,this.freezeData=!0,this.encoder={Encoder:f$})}};ey.exports=Tm});var Lc=g(($ce,ty)=>{"use strict";var Hr=Z(),cn=P();Hr.initSync();var S_=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(cn.CONFIG_PARAMS.STORAGE_WRITEASYNC)===!0||Hr.get(cn.CONFIG_PARAMS.STORAGE_WRITEASYNC)==="true"||Hr.get(cn.CONFIG_PARAMS.STORAGE_WRITEASYNC)==="TRUE",Hr.get(cn.CONFIG_PARAMS.STORAGE_OVERLAPPINGSYNC)!==void 0&&(this.overlappingSync=Hr.get(cn.CONFIG_PARAMS.STORAGE_OVERLAPPINGSYNC)),Hr.get(cn.CONFIG_PARAMS.STORAGE_MAXFREESPACETOLOAD)&&(this.maxFreeSpaceToLoad=Hr.get(cn.CONFIG_PARAMS.STORAGE_MAXFREESPACETOLOAD)),Hr.get(cn.CONFIG_PARAMS.STORAGE_MAXFREESPACETORETAIN)&&(this.maxFreeSpaceToRetain=Hr.get(cn.CONFIG_PARAMS.STORAGE_MAXFREESPACETORETAIN)),Hr.get(cn.CONFIG_PARAMS.STORAGE_PAGESIZE)&&(this.pageSize=Hr.get(cn.CONFIG_PARAMS.STORAGE_PAGESIZE)),this.noReadAhead=Hr.get(cn.CONFIG_PARAMS.STORAGE_NOREADAHEAD)}};ty.exports=S_;S_.MAX_DBS=1e4});var Ke=g((Kce,_y)=>{"use strict";var Rm=require("lmdb"),In=require("fs-extra"),xr=require("path"),T_=vr(),sy=$(),lr=Ur().LMDB_ERRORS_ENUM,g_=Qb(),Am=Dc(),iy=Lc(),ri=_t(),ry=P(),{table:h$,resetDatabases:m$}=(Oe(),ie(Fe)),ny=Z(),wn=ri.INTERNAL_DBIS_NAME,oy=ri.DBI_DEFINITION_NAME,p$="data.mdb",S$="lock.mdb",Mc=".mdb",T$="-lock",gm=class{static{a(this,"TransactionCursor")}constructor(t,r,n=!1){this.dbi=un(t,r),this.key_type=this.dbi[ri.DBI_DEFINITION_NAME].key_type,this.is_hash_attribute=this.dbi[ri.DBI_DEFINITION_NAME].is_hash_attribute,this.txn=t.beginTxn({readOnly:n===!1}),this.cursor=new Rm.Cursor(this.txn,this.dbi)}close(){this.cursor.close(),this.txn.abort()}commit(){this.cursor.close(),this.txn.commit()}};function R_(e,t){if(e===void 0)throw new Error(lr.BASE_PATH_REQUIRED);if(t===void 0)throw new Error(lr.ENV_NAME_REQUIRED)}a(R_,"pathEnvNameValidation");async function Om(e,t,r=!0){try{await In.access(e)}catch(n){throw n.code==="ENOENT"?new Error(lr.INVALID_BASE_PATH):n}try{let n=xr.join(e,t+Mc);return await In.access(n,In.constants.R_OK|In.constants.F_OK),n}catch(n){if(n.code==="ENOENT")if(r)try{return await In.access(xr.join(e,t,p$),In.constants.R_OK|In.constants.F_OK),xr.join(e,t)}catch(s){if(s.code==="ENOENT")throw new Error(lr.INVALID_ENVIRONMENT)}else throw new Error(lr.INVALID_ENVIRONMENT);throw n}}a(Om,"validateEnvironmentPath");function A_(e,t){if(T_.validateEnv(e),t===void 0)throw new Error(lr.DBI_NAME_REQUIRED)}a(A_,"validateEnvDBIName");async function g$(e,t,r=!1,n=!1){R_(e,t);let s=xr.basename(e);t=t.toString();let i=ny.get(ry.CONFIG_PARAMS.DATABASES);i||ny.setProperty(ry.CONFIG_PARAMS.DATABASES,i={}),i[s]||(i[s]={}),i[s].path=e;try{return await Om(e,t,n),ay(e,t,r)}catch(o){if(o.message===lr.INVALID_ENVIRONMENT){let c=xr.join(e,t);await In.mkdirp(n?c:e);let u=new iy(n?c:c+Mc,!1),_=Rm.open(u);_.dbis=Object.create(null);let l=new Am(!1);_.openDB(wn,l),global.lmdb_map===void 0&&(global.lmdb_map=Object.create(null));let d=bm(e,t,r);return _[ri.ENVIRONMENT_NAME_KEY]=d,global.lmdb_map[d]=_,_}throw o}}a(g$,"createEnvironment");async function R$(e,t,r,n=!0){R_(e,t),t=t.toString();let s=xr.join(e,t);return h$({table:t,database:xr.parse(e).name,path:s,attributes:[{name:"id",isPrimaryKey:!0}]})}a(R$,"copyEnvironment");async function ay(e,t,r=!1){R_(e,t),t=t.toString();let n=bm(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 Om(e,t),i=xr.join(e,t+Mc),o=s!=i,c=new iy(s,o),u=Rm.open(c);u.dbis=Object.create(null);let _=uy(u);for(let l=0;l<_.length;l++)un(u,_[l]);return u[ri.ENVIRONMENT_NAME_KEY]=n,global.lmdb_map[n]=u,u}a(ay,"openEnvironment");async function A$(e,t,r=!1){R_(e,t),t=t.toString();let n=xr.join(e,t+Mc),s=await Om(e,t);if(global.lmdb_map!==void 0){let i=bm(e,t,r);if(global.lmdb_map[i]){let o=global.lmdb_map[i];await cy(o),delete global.lmdb_map[i]}}await In.remove(s),await In.remove(s===n?s+T$:xr.join(xr.dirname(s),S$))}a(A$,"deleteEnvironment");async function cy(e){T_.validateEnv(e);let t=e[ri.ENVIRONMENT_NAME_KEY];await e.close(),t!==void 0&&global.lmdb_map!==void 0&&delete global.lmdb_map[t]}a(cy,"closeEnvironment");function bm(e,t,r=!1){let s=`${xr.basename(e)}.${t}`;return r===!0&&(s=`txn.${s}`),s}a(bm,"getCachedEnvironmentName");function O$(e){T_.validateEnv(e);let t=Object.create(null),r=un(e,wn);for(let{key:n,value:s}of r.getRange({start:!1}))if(n!==wn)try{t[n]=Object.assign(new g_,s)}catch{sy.warn(`an internal error occurred: unable to parse DBI Definition for ${n}`)}return t}a(O$,"listDBIDefinitions");function uy(e){T_.validateEnv(e);let t=[],r=un(e,wn);for(let{key:n}of r.getRange({start:!1}))n!==wn&&t.push(n);return t}a(uy,"listDBIs");function b$(e,t){let n=un(e,wn).getEntry(t),s=new g_;if(n!==void 0){try{s=Object.assign(s,n.value)}catch{sy.warn(`an internal error occurred: unable to parse DBI Definition for ${n}`)}return s}}a(b$,"getDBIDefinition");function ly(e,t,r,n=!r){if(A_(e,t),t=t.toString(),t===wn)throw new Error(lr.CANNOT_CREATE_INTERNAL_DBIS_NAME);try{return un(e,t)}catch(s){if(s.message===lr.DBI_DOES_NOT_EXIST){let i=new Am(r,n===!0),o=e.openDB(t,i),c=new g_(r===!0,n);return o[oy]=c,un(e,wn).putSync(t,c),e.dbis[t]=o,o}throw s}}a(ly,"createDBI");function un(e,t){if(A_(e,t),t=t.toString(),e.dbis[t]!==void 0)return e.dbis[t];let r;if(t!==wn?r=b$(e,t):r=new g_,r===void 0)throw new Error(lr.DBI_DOES_NOT_EXIST);let n;try{let s=new Am(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(lr.DBI_DOES_NOT_EXIST):s}return n[oy]=r,e.dbis[t]=n,n}a(un,"openDBI");function y$(e,t){A_(e,t),t=t.toString();let r=un(e,t),n=r.getStats();return r[ri.DBI_DEFINITION_NAME].is_hash_attribute&&n.entryCount>0&&n.entryCount--,n}a(y$,"statDBI");async function N$(e,t){try{let r=xr.join(e,t+Mc);return(await In.stat(r)).size}catch{throw new Error(lr.INVALID_ENVIRONMENT)}}a(N$,"environmentDataSize");function I$(e,t){if(A_(e,t),t=t.toString(),t===wn)throw new Error(lr.CANNOT_DROP_INTERNAL_DBIS_NAME);un(e,t).dropSync(),e.dbis!==void 0&&delete e.dbis[t],un(e,wn).removeSync(t)}a(I$,"dropDBI");function w$(e,t,r){let n;for(let s=0;s<r.length;s++){let i=r[s];if(!e.dbis[i])try{un(e,i)}catch(o){if(o.message===lr.DBI_DOES_NOT_EXIST)ly(e,i,i!==t,i===t),n=!0;else throw o}}n&&m$()}a(w$,"initializeDBIs");_y.exports={openDBI:un,openEnvironment:ay,createEnvironment:g$,listDBIs:uy,listDBIDefinitions:O$,createDBI:ly,dropDBI:I$,statDBI:y$,deleteEnvironment:A$,initializeDBIs:w$,TransactionCursor:gm,environmentDataSize:N$,copyEnvironment:R$,closeEnvironment:cy}});var fy=g((Qce,dy)=>{"use strict";var ym=class{static{a(this,"InsertRecordsResponseObject")}constructor(t=[],r=[],n=void 0){this.written_hashes=t,this.skipped_hashes=r,this.txn_time=n}};dy.exports=ym});var hy=g((Jce,Ey)=>{"use strict";var Nm=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}};Ey.exports=Nm});var py=g((Xce,my)=>{"use strict";var Im=class{static{a(this,"UpsertRecordsResponseObject")}constructor(t=[],r=void 0,n=[]){this.written_hashes=t,this.txn_time=r,this.original_records=n}};my.exports=Im});var Yo=g((nue,gy)=>{"use strict";var C$=Ke(),D$=fy(),L$=hy(),M$=py(),Wn=vr(),Pc=Ur().LMDB_ERRORS_ENUM,P$=_t(),Ts=P(),U$=J(),v$=require("uuid"),eue=require("lmdb"),{handleHDBError:B$,hdb_errors:H$}=ne(),{OVERFLOW_MARKER:tue,MAX_SEARCH_KEY_LENGTH:rue}=P$,Sy=Z();Sy.initSync();var O_=Sy.get(Ts.CONFIG_PARAMS.STORAGE_PREFETCHWRITES),wm=Ts.TIME_STAMP_NAMES_ENUM.CREATED_TIME,qi=Ts.TIME_STAMP_NAMES_ENUM.UPDATED_TIME;async function x$(e,t,r,n,s=Wn.getNextMonotonicTime()){Mm(e,t,r,n),Cm(e,t,r);let i=new D$,o=[],c=[];for(let u=0;u<n.length;u++){let _=n[u];Ty(_,!0,s);let l=G$(e,t,r,_),d=_[t];o.push(l),c.push(d)}return Dm(o,c,n,i,s)}a(x$,"insertRecords");function G$(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 l=c([[{}]]);Array.isArray(l)&&(c=l[0][Ts.FUNC_VAL],n[o]=c)}let u=Wn.getIndexedValues(c),_=e.dbis[o];if(u){O_&&_.prefetch(u.map(l=>({key:l,value:s})),b_);for(let l=0,d=u.length;l<d;l++)_.put(u[l],s)}}O_&&e.dbis[t].prefetch([s],b_),e.dbis[t].put(s,n,n[qi])})}a(G$,"insertRecord");function q$(e,t=[]){let r=0;for(let n=0;n<t.length;n++){let s=t[n];e.splice(s-r,1),r++}}a(q$,"removeSkippedRecords");function Ty(e,t,r){let n=r>0;(n||!Number.isInteger(e[qi]))&&(e[qi]=r||(r=Wn.getNextMonotonicTime())),t===!0?(n||!Number.isInteger(e[wm]))&&(e[wm]=r||Wn.getNextMonotonicTime()):delete e[wm]}a(Ty,"setTimestamps");function Cm(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),C$.initializeDBIs(e,t,r)}a(Cm,"initializeTransaction");async function F$(e,t,r,n,s=Wn.getNextMonotonicTime()){Mm(e,t,r,n),Cm(e,t,r);let i=new L$,o=[],c=[],u=[];for(let _=0;_<n.length;_++){let l=n[_],d=l[t],E;try{E=Lm(e,t,l,d,i,!0,s)}catch{i.skipped_hashes.push(d),o.push(_);continue}c.push(E),u.push(d)}return Dm(c,u,n,i,s,o)}a(F$,"updateRecords");async function k$(e,t,r,n,s=Wn.getNextMonotonicTime()){try{Mm(e,t,r,n)}catch(u){throw B$(u,u.message,H$.HTTP_STATUS_CODES.BAD_REQUEST)}Cm(e,t,r);let i=new M$,o=[],c=[];for(let u=0;u<n.length;u++){let _=n[u],l;U$.isEmpty(_[t])?(l=v$.v4(),_[t]=l):l=_[t];let d=Lm(e,t,_,l,i,!1,s);o.push(d),c.push(l)}return Dm(o,c,n,i,s)}a(k$,"upsertRecords");async function Dm(e,t,r,n,s,i=[]){let o=await Promise.all(e);for(let c=0,u=o.length;c<u;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(),q$(r,i),n}a(Dm,"finalizeWrite");function Lm(e,t,r,n,s,i=!1,o){let c=e.dbis[t],u=c.getEntry(n),_=u?.value,l=_;if(!_){if(i)return!1;_={}}if(Ty(r,!l,o),Number.isInteger(r[qi])&&_[qi]>r[qi])return!1;l&&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 R=p([[_]]);Array.isArray(R)&&(p=R[0][Ts.FUNC_VAL],r[h]=p)}if(p===T)continue;let A=Wn.getIndexedValues(T);if(A){O_&&S.prefetch(A.map(R=>({key:R,value:n})),b_);for(let R=0,C=A.length;R<C;R++)S.remove(A[R],n)}if(A=Wn.getIndexedValues(p),A){O_&&S.prefetch(A.map(R=>({key:R,value:n})),b_);for(let R=0,C=A.length;R<C;R++)S.put(A[R],n)}}let f=Object.assign({},_,r);c.put(n,f,f[qi])},"do_put");return u?d=c.ifVersion(n,u.version,E):d=c.ifNoExists(n,E),d.then(f=>f?!0:Lm(e,t,r,n,s,i,o))}a(Lm,"updateUpsertRecord");function V$(e,t,r){if(Wn.validateEnv(e),t===void 0)throw new Error(Pc.HASH_ATTRIBUTE_REQUIRED);if(!Array.isArray(r))throw r===void 0?new Error(Pc.WRITE_ATTRIBUTES_REQUIRED):new Error(Pc.WRITE_ATTRIBUTES_MUST_BE_ARRAY)}a(V$,"validateBasic");function Mm(e,t,r,n){if(V$(e,t,r),!Array.isArray(n))throw n===void 0?new Error(Pc.RECORDS_REQUIRED):new Error(Pc.RECORDS_MUST_BE_ARRAY)}a(Mm,"validateWrite");function b_(){}a(b_,"noop");gy.exports={insertRecords:x$,updateRecords:F$,upsertRecords:k$}});var Fi=g((iue,$$)=>{$$.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((oue,Oy)=>{"use strict";var Ay=J(),Ry=P(),Ko=/^[\x20-\x2E|\x30-\x5F|\x61-\x7E]*$/,Qn=require("joi"),ni={schema_format:{pattern:Ko,message:"names cannot include backticks or forward slashes"},schema_length:{minimum:1,maximum:250,tooLong:"cannot exceed 250 characters"}},Y$=Qn.alternatives(Qn.string().min(1).max(ni.schema_length.maximum).pattern(Ko).messages({"string.pattern.base":"{:#label} "+ni.schema_format.message}),Qn.number(),Qn.array()).required(),K$=Qn.alternatives(Qn.string().min(1).max(ni.schema_length.maximum).pattern(Ko).messages({"string.pattern.base":"{:#label} "+ni.schema_format.message}),Qn.number()),W$=Qn.alternatives(Qn.string().min(1).max(ni.schema_length.maximum).pattern(Ko).messages({"string.pattern.base":"{:#label} "+ni.schema_format.message}),Qn.number()).required();function Q$(e,t){return t?typeof t!="string"?`'${e}' must be a string`:t.length?t.length>ni.schema_length.maximum?`'${e}' maximum of 250 characters`:Ko.test(t)?"":`'${e}' has illegal characters`:`'${e}' must be at least one character`:`'${e}' is required`}a(Q$,"checkValidTable");function z$(e,t){return Ay.doesSchemaExist(e)?e:t.message(`Database '${e}' does not exist`)}a(z$,"validateSchemaExists");function J$(e,t){let r=t.state.ancestors[0].schema;return Ay.doesTableExist(r,e)?e:t.message(`Table '${e}' does not exist`)}a(J$,"validateTableExists");function j$(e,t){return e.toLowerCase()===Ry.SYSTEM_SCHEMA_NAME?t.message(`'subscriptions[${t.state.path[1]}]' invalid database name, '${Ry.SYSTEM_SCHEMA_NAME}' name is reserved`):e}a(j$,"validateSchemaName");Oy.exports={common_validators:ni,schema_regex:Ko,hdb_schema_table:Y$,validateSchemaExists:z$,validateTableExists:J$,validateSchemaName:j$,checkValidTable:Q$,hdb_database:K$,hdb_table:W$}});var je=g((cue,by)=>{"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};by.exports={validateObject:X$,validateObjectAsync:Z$,validateBySchema:e1};function X$(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(X$,"validateObject");async function Z$(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(Z$,"validateObjectAsync");function e1(e,t){let r=t.validate(e,{allowUnknown:!0,abortEarly:!1,errors:{wrap:{label:"'"}}});if(r.error)return new Error(r.error.message)}a(e1,"validateBySchema")});var y_=g((lue,yy)=>{var{common_validators:Jn}=zn(),vc=je(),Uc="is required",St={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 Bc(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(Bc,"makeAttributesStrings");function t1(e){return e=Bc(e),St.table.presence=!1,St.attribute.presence=!1,St.hash_attribute.presence=!1,vc.validateObject(e,St)}a(t1,"schema_object");function r1(e){return e=Bc(e),St.table.presence={message:Uc},St.attribute.presence=!1,St.hash_attribute.presence=!1,vc.validateObject(e,St)}a(r1,"table_object");function n1(e){return e=Bc(e),St.table.presence={message:Uc},St.attribute.presence=!1,vc.validateObject(e,St)}a(n1,"create_table_object");function s1(e){return e=Bc(e),St.table.presence={message:Uc},St.attribute.presence={message:Uc},St.hash_attribute.presence=!1,vc.validateObject(e,St)}a(s1,"attribute_object");function i1(e){return e=Bc(e),St.table.presence={message:Uc},St.attribute.presence=!1,St.hash_attribute.presence=!1,vc.validateObject(e,St)}a(i1,"describe_table");function o1(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(o1,"validateTableResidence");yy.exports={schema_object:t1,create_table_object:n1,table_object:r1,attribute_object:s1,describe_table:i1,validateTableResidence:o1}});var Iy=g((due,Ny)=>{"use strict";var a1=require("uuid"),Pm=class{static{a(this,"CreateAttributeObject")}constructor(t,r,n,s){this.schema=t,this.table=r,this.attribute=n,this.id=s||a1.v4(),this.schema_table=`${this.schema}.${this.table}`}};Ny.exports=Pm});var N_=g((Eue,wy)=>{"use strict";var c1=Iy(),Um=class extends c1{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}};wy.exports=Um});var Dy=g((mue,Cy)=>{"use strict";Cy.exports=l1;var u1="inserted";function l1(e,t,r,n){let s={message:`${e} ${t.length} of ${r.records.length} records`,skipped_hashes:n};return e===u1?(s.inserted_hashes=t,s):(s.update_hashes=t,s)}a(l1,"returnObject")});var I_=g((Sue,vy)=>{"use strict";var _1=P(),vm=Ke(),d1=Yo(),{getSystemSchemaPath:f1,getSchemaPath:E1}=ze(),h1=Fi(),m1=y_(),p1=N_(),S1=Dy(),{handleHDBError:Ly,hdb_errors:Py}=ne(),My=J(),{HTTP_STATUS_CODES:T1}=Py,Bm=h1.hdb_attribute,Uy=[];for(let e=0;e<Bm.attributes.length;e++)Uy.push(Bm.attributes[e].attribute);var g1="inserted";vy.exports=R1;async function R1(e){let t=m1.attribute_object(e);if(t)throw Ly(new Error,t.message,Py.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0);let r=!e.skip_table_check&&My.checkGlobalSchemaTable(e.schema,e.table);if(r)throw Ly(new Error,r,T1.NOT_FOUND);e.is_hash_attribute=e.is_hash_attribute=="true",e.dup_sort=My.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 p1(e.schema,e.table,e.attribute,e.id);try{let i=await vm.openEnvironment(E1(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}`);vm.createDBI(i,e.attribute,e.dup_sort,e.is_hash_attribute);let o=await vm.openEnvironment(f1(),_1.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME),{written_hashes:c,skipped_hashes:u}=await d1.insertRecords(o,Bm.hash_attribute,Uy,[s]);return S1(g1,c,{records:[s]},u)}catch(i){throw i}}a(R1,"lmdbCreateAttribute")});var xm=g((gue,Hy)=>{var{hdb_table:A1,hdb_database:By}=zn(),O1=je(),Hm=require("joi"),b1={undefined:"undefined",null:"null"},y1=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||b1[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"),N1=Hm.object({database:By,schema:By,table:A1,records:Hm.array().items(Hm.object().custom(y1)).required()});Hy.exports=function(e){return O1.validateBySchema(e,N1)}});var Hc=g((Oue,Gy)=>{"use strict";var gs=J(),xy=$(),Aue=xm(),{getDatabases:I1}=(Oe(),ie(Fe)),{ClientError:ki}=ne();Gy.exports=w1;function w1(e){if(gs.isEmpty(e))throw new ki("invalid update parameters defined.");if(gs.isEmptyOrZeroLength(e.schema))throw new ki("invalid schema specified.");if(gs.isEmptyOrZeroLength(e.table))throw new ki("invalid table specified.");if(!Array.isArray(e.records))throw new ki("records must be an array");let t=I1()[e.schema]?.[e.table];if(gs.isEmpty(t))throw new ki(`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 xy.error("a valid hash attribute must be provided with update record:",o),new ki("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 xy.error(`a valid hash value must be provided with ${e.operation} record:`,o),new ki(`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(w1,"insertUpdateValidate")});var xc=g((yue,qy)=>{"use strict";var C1=P().OPERATIONS_ENUM,Gm=class{static{a(this,"InsertObject")}constructor(t,r,n,s,i=void 0){this.operation=C1.INSERT,this.schema=t,this.table=r,this.hash_attribute=n,this.records=s,this.__origin=i}};qy.exports=Gm});var Gc=g((wue,ky)=>{"use strict";var Iue=xc(),w_=P(),qm=J(),Fy=$(),D1=require("uuid"),{handleHDBError:C_,hdb_errors:L1}=ne(),{HDB_ERROR_MSGS:D_,HTTP_STATUS_CODES:L_}=L1;ky.exports=M1;function M1(e,t,r){for(let s=0;s<t.length;s++)P1(t[s]);let{records:n}=e;for(let s=0;s<n.length;s++){let i=n[s];U1(i,r,e.operation)}}a(M1,"processRows");function P1(e){if(Buffer.byteLength(String(e))>w_.INSERT_MODULE_ENUM.MAX_CHARACTER_SIZE)throw C_(new Error,D_.ATTR_NAME_LENGTH_ERR(e),L_.BAD_REQUEST,void 0,void 0,!0);if(qm.isEmptyOrZeroLength(e)||qm.isEmpty(e.trim()))throw C_(new Error,D_.ATTR_NAME_NULLISH_ERR,L_.BAD_REQUEST,void 0,void 0,!0)}a(P1,"validateAttribute");function U1(e,t,r){if(!e.hasOwnProperty(t)||qm.isEmptyOrZeroLength(e[t])){if(r===w_.OPERATIONS_ENUM.INSERT||r===w_.OPERATIONS_ENUM.UPSERT){e[t]=D1.v4();return}throw Fy.error("Update transaction aborted due to record with no hash value:",e),C_(new Error,D_.RECORD_MISSING_HASH_ERR,L_.BAD_REQUEST,void 0,void 0,!0)}if(Buffer.byteLength(String(e[t]))>w_.INSERT_MODULE_ENUM.MAX_CHARACTER_SIZE)throw Fy.error(e),C_(new Error,D_.HASH_VAL_LENGTH_ERR,L_.BAD_REQUEST,void 0,void 0,!0)}a(U1,"validateHash")});var $y=g((Due,Vy)=>{"use strict";var Fm=class{static{a(this,"ITCEventObject")}constructor(t,r){this.type=t,this.message=r}};Vy.exports=Fm});var Wy=g((Mue,Ky)=>{"use strict";var km=Ke(),v1=$(),Yy=Ur().LMDB_ERRORS_ENUM;Ky.exports=B1;async function B1(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 km.closeEnvironment(global.lmdb_map[o])}catch(c){if(c.message!==Yy.ENV_REQUIRED)throw c}}break;case"drop_table":let n=`${e.schema}.${e.table}`,s=`txn.${n}`;try{await km.closeEnvironment(global.lmdb_map[n]),await km.closeEnvironment(global.lmdb_map[s])}catch(i){if(i.message!==Yy.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){v1.error(t)}}a(B1,"cleanLMDBMap")});var Rs=g((Uue,jy)=>{"use strict";var qc=require("crypto"),H1=Z(),{CONFIG_PARAMS:x1}=P(),zy="aes-256-cbc",G1=32,q1=16,Vm=64,Jy=32,F1=Vm+Jy,Qy=new Map;jy.exports={encrypt:k1,decrypt:V1,createNatsTableStreamName:$1};function k1(e){let t=qc.randomBytes(G1),r=qc.randomBytes(q1),n=qc.createCipheriv(zy,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(k1,"encrypt");function V1(e){let t=e.substr(0,Vm),r=e.substr(Vm,Jy),n=e.substr(F1,e.length),s=Buffer.from(r,"hex"),i=Buffer.from(n,"hex"),o=qc.createDecipheriv(zy,Buffer.from(t,"hex"),s),c=o.update(i);return c=Buffer.concat([c,o.final()]),c.toString()}a(V1,"decrypt");function $1(e,t){let r=H1.get(x1.CLUSTERING_DATABASELEVEL)?e:`${e}.${t}`,n=Qy.get(r);return n||(n=qc.createHash("md5").update(r).digest("hex"),Qy.set(r,n)),n}a($1,"createNatsTableStreamName")});var As=g((Hue,Zy)=>{"use strict";var Bue=Gr(),M_=$(),Xy=y_(),Y1=Rs(),P_=J(),{handleHDBError:U_,hdb_errors:K1}=ne(),{HDB_ERROR_MSGS:v_,HTTP_STATUS_CODES:$m}=K1,W1=Z();W1.initSync();var{getDatabases:Ym}=(Oe(),ie(Fe));Zy.exports={describeAll:Q1,describeTable:B_,describeSchema:z1};async function Q1(e){try{let t=P_.isEmptyOrZeroLength(e),r,n;t||(r=e.hdb_user.role.permission,n=r.super_user||r.cluster_user);let s=Ym(),i={},o={},c=[],u=e?.exact_count;for(let l in s){i[l]=!0,!t&&!n&&(o[l]=e.hdb_user.role.permission[l].describe);let d=s[l];for(let E in d)try{let f;if(t||n)f=await B_({schema:l,table:E,exact_count:u});else if(r&&r[l].describe&&r[l].tables[E].describe){let h=r[l].tables[E].attribute_permissions;f=await B_({schema:l,table:E,exact_count:u},h)}f&&c.push(f)}catch(f){M_.error(f)}}let _={};for(let l in c)t||n?(_[c[l].schema]==null&&(_[c[l].schema]={}),_[c[l].schema][c[l].name]=c[l],i[c[l].schema]&&delete i[c[l].schema]):o[c[l].schema]&&(_[c[l].schema]==null&&(_[c[l].schema]={}),_[c[l].schema][c[l].name]=c[l],i[c[l].schema]&&delete i[c[l].schema]);for(let l in i)t||n?_[l]={}:o[l]&&(_[l]={});return _}catch(t){return M_.error("Got an error in describeAll"),M_.error(t),U_(new Error,v_.DESCRIBE_ALL_ERR)}}a(Q1,"describeAll");async function B_(e,t){P_.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=Xy.describe_table(e);if(i)throw i;let c=Ym()[r];if(!c)throw U_(new Error,v_.SCHEMA_NOT_FOUND(e.schema),$m.NOT_FOUND);let u=c[n];if(!u)throw U_(new Error,v_.TABLE_NOT_FOUND(e.schema,e.table),$m.NOT_FOUND);function _(E){l.push(Object.assign({},{attribute:E.attribute,type:E.type,elements:E.elements?.type,indexed:E.indexed,is_primary_key:E.isPrimaryKey,assigned_created_time:E.assignCreatedTime,assigned_updated_time:E.assignUpdatedTime,nullable:E.nullable,properties:E.properties?E.properties.map(f=>({type:f.type,name:f.name})):void 0}))}a(_,"pushAtt");let l=[];if(s){let E={};s.forEach(f=>{f.describe&&(E[f.attribute_name]=!0)}),u.attributes.forEach(f=>{E[f.name]&&_(f)})}else u.attributes?.forEach(E=>_(E));let d={schema:r,name:u.tableName,hash_attribute:u.attributes.find(E=>E.isPrimaryKey||E.is_hash_attribute)?.name,audit:u.audit,schema_defined:u.schemaDefined,attributes:l};d.clustering_stream_name=Y1.createNatsTableStreamName(d.schema,d.name);try{let E=u.getRecordCount({exactCount:e.exact_count==="true"});d.record_count=E.recordCount,d.estimated_record_range=E.estimatedRange;let f=u.auditStore;if(f)for(let h of f.getKeys({reverse:!0,limit:1}))d.last_updated_record=h[0];if(!d.last_updated_record&&u.indices.__updatedtime__)for(let h of u.indices.__updatedtime__.getKeys({reverse:!0,limit:1}))d.last_updated_record=h}catch(E){M_.warn(`unable to stat table dbi due to ${E}`)}return d}a(B_,"descTable");async function z1(e){P_.transformReq(e);let t=Xy.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=Ym()[n];if(!i)throw U_(new Error,v_.SCHEMA_NOT_FOUND(e.schema),$m.NOT_FOUND);let o={};for(let c in i){let u;if(r&&r.tables[c]&&(u=r.tables[c]),P_.isEmpty(u)||u.describe){let _=await B_({schema:e.schema,table:c,exact_count:e.exact_count},u?u.attribute_permissions:null);_&&(o[_.name]=_)}}return o}a(z1,"describeSchema")});var Os=g((Fue,sN)=>{var J1=Fi(),{callbackify:tN,promisify:j1}=require("util"),{getDatabases:rN}=(Oe(),ie(Fe));sN.exports={setSchemaDataToGlobal:eN,getTableSchema:X1,getSystemSchema:Z1,setSchemaDataToGlobalAsync:j1(eN)};var nN=As(),Gue=tN(nN.describeAll),que=tN(nN.describeTable);function eN(e){global.hdb_schema=rN(),e&&e()}a(eN,"setSchemaDataToGlobal");function X1(e,t,r){let n=rN()[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(X1,"getTableSchema");function Z1(){return J1}a(Z1,"getSystemSchema")});var qr=g((Vue,cN)=>{"use strict";var x_=xm(),$t=J(),eY=require("util"),G_=Cn(),tY=Os(),iN=$(),{handleHDBError:Vi,hdb_errors:rY}=ne(),{HTTP_STATUS_CODES:$i}=rY,nY=eY.promisify(tY.getTableSchema),sY="updated",oN="inserted",aN="upserted";cN.exports={insert:oY,update:aY,upsert:cY,validation:iY,flush:uY};async function iY(e){if($t.isEmpty(e))throw new Error("invalid update parameters defined.");if($t.isEmptyOrZeroLength(e.schema))throw new Error("invalid database specified.");if($t.isEmptyOrZeroLength(e.table))throw new Error("invalid table specified.");let t=await nY(e.schema,e.table),r=x_(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&&$t.isEmptyOrZeroLength(c[n]))throw iN.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(!$t.isEmptyOrZeroLength(c[n])&&(c[n]==="null"||c[n]==="undefined"))throw iN.error(`a valid hash value must be provided with ${e.operation} record:`,c),new Error(`"${c[n]}" is not a valid hash attribute value`);!$t.isEmpty(c[n])&&c[n]!==""&&s.has($t.autoCast(c[n]))&&(c.skip=!0),s.add($t.autoCast(c[n]));for(let u in c)i[u]=1}),i[n]=1,{schema_table:t,hashes:Array.from(s),attributes:Object.keys(i)}}a(iY,"validation");async function oY(e){if(e.operation!=="insert")throw new Error("invalid operation, must be insert");let t=x_(e);if(t)throw Vi(new Error,t.message,$i.BAD_REQUEST);$t.transformReq(e);let r=$t.checkSchemaTableExist(e.schema,e.table);if(r)throw Vi(new Error,r,$i.BAD_REQUEST);let n=await G_.createRecords(e);return H_(oN,n.written_hashes,e,n.skipped_hashes,n.new_attributes,n.txn_time)}a(oY,"insertData");async function aY(e){if(e.operation!=="update")throw new Error("invalid operation, must be update");let t=x_(e);if(t)throw Vi(new Error,t.message,$i.BAD_REQUEST);$t.transformReq(e);let r=$t.checkSchemaTableExist(e.schema,e.table);if(r)throw Vi(new Error,r,$i.BAD_REQUEST);let n=await G_.updateRecords(e);return $t.isEmpty(n.existing_rows)?H_(sY,n.written_hashes,e,n.skipped_hashes,n.new_attributes,n.txn_time):H_(n.update_action,[],e,n.hashes,void 0,n.txn_time)}a(aY,"updateData");async function cY(e){if(e.operation!=="upsert")throw Vi(new Error,"invalid operation, must be upsert",$i.INTERNAL_SERVER_ERROR);let t=x_(e);if(t)throw Vi(new Error,t.message,$i.BAD_REQUEST);$t.transformReq(e);let r=$t.checkSchemaTableExist(e.schema,e.table);if(r)throw Vi(new Error,r,$i.BAD_REQUEST);let n=await G_.upsertRecords(e);return H_(aN,n.written_hashes,e,[],n.new_attributes,n.txn_time)}a(cY,"upsertData");function H_(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===oN?(o.inserted_hashes=t,o.skipped_hashes=n,o):e===aN?(o.upserted_hashes=t,o):(o.update_hashes=t,o.skipped_hashes=n,o)}a(H_,"returnObject");function uY(e){return $t.transformReq(e),G_.flush(e.schema,e.table)}a(uY,"flush")});var Wm=g((Yue,_N)=>{var lY=je(),Km=require("joi"),{hdb_table:_Y,hdb_database:uN}=zn(),lN={schema:uN,database:uN,table:_Y},dY={date:Km.date().iso().required()},fY={timestamp:Km.date().timestamp().required().messages({"date.format":"'timestamp' is invalid"})};_N.exports=function(e,t){let r=t==="timestamp"?{...lN,...fY}:{...lN,...dY},n=Km.object(r);return lY.validateBySchema(e,n)}});var EN=g((Kue,fN)=>{var EY=je(),Qm=require("joi"),{hdb_table:hY,hdb_database:dN}=zn(),mY=Qm.object({schema:dN,database:dN,table:hY,hash_values:Qm.array().required(),ids:Qm.array()});fN.exports=function(e){return EY.validateBySchema(e,mY)}});var mN=g((Wue,hN)=>{"use strict";var zm=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}},Jm=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}},jm=class{static{a(this,"DeleteResponseObject")}constructor(){this.message=void 0,this.deleted_hashes=[],this.skipped_hashes=[]}};hN.exports={InsertObject:zm,NoSQLSeachObject:Jm,DeleteResponseObject:jm}});var oi=g((zue,RN)=>{"use strict";var SN=Wm(),pY=EN(),Yi=J(),pN=require("moment"),TN=$(),{promisify:SY,callbackify:TY}=require("util"),Ki=P(),gY=Os(),Xm=SY(gY.getTableSchema),Zm=Cn(),{DeleteResponseObject:RY}=mN(),{handleHDBError:si,hdb_errors:AY}=ne(),{HDB_ERROR_MSGS:q_,HTTP_STATUS_CODES:ii}=AY,OY="records successfully deleted",bY=TY(gN);RN.exports={delete:bY,deleteRecord:gN,deleteFilesBefore:yY,deleteAuditLogsBefore:NY};async function yY(e){let t=SN(e,"date");if(t)throw si(t,t.message,ii.BAD_REQUEST,void 0,void 0,!0);if(Yi.transformReq(e),!pN(e.date,pN.ISO_8601).isValid())throw si(new Error,q_.INVALID_DATE,ii.BAD_REQUEST,Ki.LOG_LEVELS.ERROR,q_.INVALID_DATE,!0);let n=Yi.checkSchemaTableExist(e.schema,e.table);if(n)throw si(new Error,n,ii.NOT_FOUND,Ki.LOG_LEVELS.ERROR,n,!0);let s=await Zm.deleteRecordsBefore(e);if(await Xm(e.schema,e.table),TN.info(`Finished deleting files before ${e.date}`),s&&s.message)return s.message}a(yY,"deleteFilesBefore");async function NY(e){let t=SN(e,"timestamp");if(t)throw si(t,t.message,ii.BAD_REQUEST,void 0,void 0,!0);if(Yi.transformReq(e),isNaN(e.timestamp))throw si(new Error,q_.INVALID_VALUE("Timestamp"),ii.BAD_REQUEST,Ki.LOG_LEVELS.ERROR,q_.INVALID_VALUE("Timestamp"),!0);let r=Yi.checkSchemaTableExist(e.schema,e.table);if(r)throw si(new Error,r,ii.NOT_FOUND,Ki.LOG_LEVELS.ERROR,r,!0);let n=await Zm.deleteAuditLogsBefore(e);return await Xm(e.schema,e.table),TN.info(`Finished deleting audit logs before ${e.timestamp}`),n}a(NY,"deleteAuditLogsBefore");async function gN(e){e.ids&&(e.hash_values=e.ids);let t=pY(e);if(t)throw si(t,t.message,ii.BAD_REQUEST,void 0,void 0,!0);Yi.transformReq(e);let r=Yi.checkSchemaTableExist(e.schema,e.table);if(r)throw si(new Error,r,ii.NOT_FOUND,Ki.LOG_LEVELS.ERROR,r,!0);try{await Xm(e.schema,e.table);let n=await Zm.deleteRecords(e);return Yi.isEmptyOrZeroLength(n.message)&&(n.message=`${n.deleted_hashes.length} of ${e.hash_values.length} ${OY}`),n}catch(n){if(n.message===Ki.SEARCH_NOT_FOUND_MESSAGE){let s=new RY;return s.message=Ki.SEARCH_NOT_FOUND_MESSAGE,s.skipped_hashes=e.hash_values.length,s.deleted_hashes=0,s}throw n}}a(gN,"deleteRecord")});var F_=g((jue,bN)=>{var IY=require("crypto"),AN=9;function wY(e){let t=DY(AN),r=ON(e+t);return t+r}a(wY,"createHash");function CY(e,t){let r=e?.substr(0,AN),n=r+ON(t+r);return e===n}a(CY,"validateHash");function DY(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(DY,"generateSalt");function ON(e){return IY.createHash("md5").update(e).digest("hex")}a(ON,"md5");bN.exports={hash:wY,validate:CY}});var NN=g((Zue,yN)=>{var ep=je(),jt={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 LY(e){return jt.password.presence=!0,jt.username.presence=!0,jt.role.presence=!0,jt.active.presence=!0,ep.validateObject(e,jt)}a(LY,"addUserValidation");function MY(e){return jt.password.presence=!1,jt.username.presence=!0,jt.role.presence=!1,jt.active.presence=!1,ep.validateObject(e,jt)}a(MY,"alterUserValidation");function PY(e){return jt.password.presence=!1,jt.username.presence=!0,jt.role.presence=!1,jt.active.presence=!1,ep.validateObject(e,jt)}a(PY,"dropUserValidation");yN.exports={addUserValidation:LY,alterUserValidation:MY,dropUserValidation:PY}});var ke=g((rle,wN)=>{"use strict";var{platform:tle}=require("os"),UY="nats-server.zip",tp="nats-server",vY=process.platform==="win32"?`${tp}.exe`:tp,BY=/^[^\s.,*>]+$/,IN="__request__",HY=a(e=>`${e}.${IN}`,"REQUEST_SUBJECT"),xY={NATS_MSG_ID:"Nats-Msg-Id",ORIGIN:"origin",TRANSACTED_NODES:"transacted_nodes"},GY={HUB_SERVER:"hub.json",LEAF_SERVER:"leaf.json"},qY={HUB:"hub.pid",LEAF:"leaf.pid"},FY={HUB:"-hub",LEAF:"-leaf",ADMIN:"-admin"},kY={SUCCESS:"success",ERROR:"error"},VY={OPEN:"open",CLOSED:"closed",NO_RESPONDERS:"NoResponders",TIMEOUT:"Timeout"},$Y={TXN:"txn",MSGID:"msgid"},Wo={ERR:"error",WRN:"warn",INF:"info",DBG:"debug",TRC:"trace"},YY={[Wo.ERR]:1,[Wo.WRN]:2,[Wo.INF]:3,[Wo.DBG]:4,[Wo.TRC]:5},KY={debug:"-D",trace:"-DVV"};wN.exports={NATS_SERVER_ZIP:UY,NATS_SERVER_NAME:tp,NATS_BINARY_NAME:vY,PID_FILES:qY,NATS_CONFIG_FILES:GY,SERVER_SUFFIX:FY,NATS_TERM_CONSTRAINTS_RX:BY,REQUEST_SUFFIX:IN,UPDATE_REMOTE_RESPONSE_STATUSES:kY,CLUSTER_STATUS_STATUSES:VY,REQUEST_SUBJECT:HY,SUBJECT_PREFIXES:$Y,MSG_HEADERS:xY,LOG_LEVELS:Wo,LOG_LEVEL_FLAGS:KY,LOG_LEVEL_HIERARCHY:YY}});var DN=g((sle,CN)=>{"use strict";var WY={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
|
|
1
|
+
"use strict";var Iq=Object.create;var lc=Object.defineProperty;var wq=Object.getOwnPropertyDescriptor;var Cq=Object.getOwnPropertyNames;var Dq=Object.getPrototypeOf,Lq=Object.prototype.hasOwnProperty;var a=(e,t)=>lc(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),Fe=(e,t)=>{for(var r in t)lc(e,r,{get:t[r],enumerable:!0})},dO=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Cq(t))!Lq.call(e,s)&&s!==r&&lc(e,s,{get:()=>t[s],enumerable:!(n=wq(t,s))||n.enumerable});return e};var B=(e,t,r)=>(r=e!=null?Iq(Dq(e)):{},dO(t||!e||!e.__esModule?lc(r,"default",{value:e,enumerable:!0}):r,e)),ie=e=>dO(lc({},"__esModule",{value:!0}),e);var hO=g((tce,EO)=>{var Mq=require("fast-glob"),{statSync:Dh,existsSync:Lh,readFileSync:Pq,writeFileSync:Uq}=require("fs"),{spawnSync:vq,spawn:Bq,execFileSync:ece}=require("child_process"),{isMainThread:xq}=require("worker_threads"),{join:Xs,relative:fO}=require("path"),{PACKAGE_ROOT:bn}=P(),{tmpdir:Hq,platform:Gq}=require("os");require("source-map-support").install();var qq=["resources","server","dataLayer","components"],_c="ts-build",Mh,Fq=__filename.endsWith("tsBuild.js");if(Fq){if(xq){let r;try{Dh(Xs(bn,_c)),r=!0}catch{}if(r)for(let n of Mq.sync(qq.map(s=>s+"/**/*.ts"),{cwd:bn})){let s=0,i=0;try{s=Dh(Xs(bn,n)).mtimeMs-5e3,i=Dh(Xs(bn,_c,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."),Mh=!0;break}}else console.log("TypeScript modules are not compiled, compiling now"),Mh=!0;if(Mh){let n=Xs(bn,"node_modules/.bin/tsc");Gq()==="win32"&&(n+=".cmd");let s=vq(n,{cwd:bn});if(s.stdout?.length&&console.log(s.stdout.toString()),s.stderr?.length&&console.log(s.stderr.toString()),r){let i=Xs(Hq(),"harperdb-tsc.pid"),o;if(Lh(i))try{process.kill(+Pq(i,{encoding:"utf8"}),0),o=!0}catch{}if(!o){console.log("starting tsc background process");let c=Bq(n,["--watch"],{cwd:bn,detached:!0,stdio:"ignore"});Uq(i,c.pid.toString()),c.unref()}}}}let e=EO.constructor,t=e._findPath;e._findPath=function(r,n,s){if(r.startsWith(".")&&!s&&n.length===1&&n[0].startsWith(bn)&&!n[0].includes("node_modules")){let i=fO(bn,n[0]),o;i.startsWith(_c)?o=Xs(bn,fO(_c,i)):o=Xs(bn,_c,i);let c=Xs(o,r),u=c+".js";if(Lh(u))return u;if(c.includes(".")&&Lh(c))return c}return t(r,n,s)}}});var P=g((sce,CO)=>{"use strict";var an=require("path"),kq=require("fs"),{relative:rce,join:nce}=an,{existsSync:Vq}=kq;function $q(){let e=__dirname;for(;!Vq(an.join(e,"package.json"));){let t=an.dirname(e);if(t===e)throw new Error("Could not find package root");e=t}return e}a($q,"getHDBPackageRoot");var Zs=$q(),mO="js",n_=mO,Yq="harperdb-config.yaml",Kq="defaultConfig.yaml",Wq="hdb",pO=`harperdb.${n_}`,SO=`customFunctionsServer.${n_}`,Qq=`restartHdb.${n_}`,Uh="HarperDB",r_="Custom Functions",s_="Clustering Hub",i_="Clustering Leaf",zq="Clustering Ingest Service",Jq="Clustering Reply Service",jq="foreground.pid",Xq="hdb.pid",Zq="data",eF={HDB:Uh,CLUSTERING_HUB:s_,CLUSTERING_LEAF:i_,CLUSTERING_INGEST_SERVICE:zq,CLUSTERING_REPLY_SERVICE:Jq,CUSTOM_FUNCTIONS:r_,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"},tF={HDB:"hdb.log",INSTALL:"install.log",CLUSTERING_HUB:"clustering_hub.log",CLUSTERING_LEAF:"clustering_leaf.log"},rF={NOTIFY:"notify",FATAL:"fatal",ERROR:"error",WARN:"warn",INFO:"info",DEBUG:"debug",TRACE:"trace"},nF={harperdb:Uh,"clustering hub":s_,"clustering leaf":i_,"custom functions":r_,custom_functions:r_,clustering:"clustering","clustering config":"clustering config",clustering_config:"clustering_config",http_workers:"http_workers"},sF={CLUSTERING_HUB_PROC_DESCRIPTOR:s_,CLUSTERING_LEAF_PROC_DESCRIPTOR:i_},Ph={HDB:an.join(Zs,"server/harperdb"),CUSTOM_FUNCTIONS:an.join(Zs,"server/customFunctions"),CLUSTERING_HUB:an.join(Zs,"server/nats"),CLUSTERING_LEAF:an.join(Zs,"server/nats")},iF={HDB:an.join(Ph.HDB,pO),CUSTOM_FUNCTIONS:an.join(Ph.CUSTOM_FUNCTIONS,SO)},oF={MAIN:"bin/harperdb.js",NATS_INGEST_SERVICE:an.join(Zs,"launchServiceScripts/launchNatsIngestService.js"),NATS_REPLY_SERVICE:an.join(Zs,"launchServiceScripts/launchNatsReplyService.js"),NODES_UPGRADE_4_0_0:an.join(Zs,"launchServiceScripts/launchUpdateNodes4-0-0.js")},aF={SUPER_USER:"super_user",CLUSTER_USER:"cluster_user"},TO="support@harperdb.io",cF="customer-success@harperdb.io",gO=1,uF=4141,RO="https://harperdbhelp.zendesk.com/hc/en-us/requests/new",lF="https://www.harperdb.io/product",_F=`For support, please submit a request at ${RO} or contact ${TO}`,AO=`For license support, please contact ${cF}`,dF="None of the specified records were found.",fF="hash attribute not found",EF=`Your current license only supports ${gO} role. ${AO}`,hF="Your current license only supports 3 connections to a node.",mF="127.0.0.1",pF=1,SF=/^\.$/,TF=/^\.\.$/,gF="U+002E",RF=/\//g,AF="U+002F",OF=/U\+002F/g,bF=/^U\+002E$/,yF=/^U\+002EU\+002E$/,NF="d",IF=999999,wF="*",CF="--max-old-space-size=",DF="system",LF="__hdb_hash",MF=".harperdb",PF=".hdb",UF="keys",vF="hdb_boot_properties.file",BF=".updateConfig.json",xF="SIGTSTP",HF=24,GF=6e4,qF=448,FF="blob",kF="trash",VF="database",$F="schema",YF="transactions",KF=".count",WF="id",QF="PROCESS_NAME",OO={SETTINGS_PATH_KEY:"settings_path"},bO=require("lodash"),zF={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"},JF={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},jF={DATA_VERSION:"data_version",UPGRADE_VERSION:"upgrade_version"},XF={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"},ZF={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:",ek={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"},tk={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"},rk="060493.ks",nk=".license",sk={CREATED:"CREATED",IN_PROGRESS:"IN_PROGRESS",COMPLETE:"COMPLETE",ERROR:"ERROR"},ee={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"},ik={CSV:".csv",JSON:".json"},ok={AWS_ACCESS_KEY:"aws_access_key_id",AWS_SECRET:"aws_secret_access_key",AWS_BUCKET:"bucket",AWS_FILE_KEY:"key",REGION:"region"},ak={SELECT:"select",INSERT:"insert",UPDATE:"update",DELETE:"delete"},dc={};dc[ee.INSERT]=ee.INSERT;dc[ee.UPDATE]=ee.UPDATE;dc[ee.UPSERT]=ee.UPSERT;dc[ee.DELETE]=ee.DELETE;var xe=Object.create(null);xe[ee.DESCRIBE_ALL]=ee.DESCRIBE_ALL;xe[ee.DESCRIBE_TABLE]=ee.DESCRIBE_TABLE;xe[ee.DESCRIBE_SCHEMA]=ee.DESCRIBE_SCHEMA;xe[ee.READ_LOG]=ee.READ_LOG;xe[ee.ADD_NODE]=ee.ADD_NODE;xe[ee.LIST_USERS]=ee.LIST_USERS;xe[ee.LIST_ROLES]=ee.LIST_ROLES;xe[ee.USER_INFO]=ee.USER_INFO;xe[ee.SQL]=ee.SQL;xe[ee.GET_JOB]=ee.GET_JOB;xe[ee.SEARCH_JOBS_BY_START_DATE]=ee.SEARCH_JOBS_BY_START_DATE;xe[ee.DELETE_FILES_BEFORE]=ee.DELETE_FILES_BEFORE;xe[ee.EXPORT_LOCAL]=ee.EXPORT_LOCAL;xe[ee.EXPORT_TO_S3]=ee.EXPORT_TO_S3;xe[ee.CLUSTER_STATUS]=ee.CLUSTER_STATUS;xe[ee.REMOVE_NODE]=ee.REMOVE_NODE;xe[ee.RESTART]=ee.RESTART;xe[ee.CUSTOM_FUNCTIONS_STATUS]=ee.CUSTOM_FUNCTIONS_STATUS;xe[ee.GET_CUSTOM_FUNCTIONS]=ee.GET_CUSTOM_FUNCTIONS;xe[ee.GET_CUSTOM_FUNCTION]=ee.GET_CUSTOM_FUNCTION;xe[ee.SET_CUSTOM_FUNCTION]=ee.SET_CUSTOM_FUNCTION;xe[ee.DROP_CUSTOM_FUNCTION]=ee.DROP_CUSTOM_FUNCTION;xe[ee.ADD_CUSTOM_FUNCTION_PROJECT]=ee.ADD_CUSTOM_FUNCTION_PROJECT;xe[ee.DROP_CUSTOM_FUNCTION_PROJECT]=ee.DROP_CUSTOM_FUNCTION_PROJECT;xe[ee.PACKAGE_CUSTOM_FUNCTION_PROJECT]=ee.PACKAGE_CUSTOM_FUNCTION_PROJECT;xe[ee.DEPLOY_CUSTOM_FUNCTION_PROJECT]=ee.DEPLOY_CUSTOM_FUNCTION_PROJECT;var ck={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"},uk={point:"point",lineString:"lineString",multiLineString:"multiLineString",multiPoint:"multiPoint",multiPolygon:"multiPolygon",polygon:"polygon"},yO={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"},lk=bO.invert(yO),_k={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"},NO={settings_path:OO.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];NO[t.toLowerCase()]=t}var dk={TABLES:"tables",PATH:"path",AUDIT_PATH:"auditPath"},fk={csv_file_load:"csv_file_load",csv_data_load:ee.CSV_DATA_LOAD,csv_url_load:ee.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"},Ek={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"},hk={BIDIRECTIONAL:"BIDIRECTIONAL",OUTBOUND:"OUTBOUND",INBOUND:"INBOUND"},mk={VERSION_DEFAULT:"2.2.0"},pk={DEVELOPMENT:8192,DEFAULT:512},Sk={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"},Tk={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"},gk={ENOENT:"ENOENT",EACCES:"EACCES",EEXIST:"EEXIST",ERR_INVALID_ARG_TYPE:"ERR_INVALID_ARG_TYPE"},IO={CREATED_TIME:"__createdtime__",UPDATED_TIME:"__updatedtime__"},Rk=Symbol("metadata"),Ak="__clustering__",Ok=Object.values(IO),bk=15984864e5,wO={LESS:"<",LESS_OR_EQ:"<=",GREATER:">",GREATER_OR_EQ:">=",BETWEEN:"..."},yk=bO.invert(wO),Nk={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"},Ik=111,wk=`\r
|
|
2
|
+
`,Ck={READ:"read",INSERT:"insert",UPDATE:"update",DELETE:"delete"},Dk=["*","%"],Lk="unauthorized_access",Mk="func_val",Pk={HASH_VALUE:"hash_value",TIMESTAMP:"timestamp",USERNAME:"username"},Uk={JWT_PRIVATE_KEY_NAME:".jwtPrivate.key",JWT_PUBLIC_KEY_NAME:".jwtPublic.key",JWT_PASSPHRASE_NAME:".jwtPass"},vk={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"},Bk={HDB_CORE:"hdb_core",CUSTOM_FUNCTIONS:"custom_functions"},xk={HTTP:"http"},Hk={STOPPED:"stopped",ONLINE:"online"},Gk="3.x.x",qk={SUCCESS:"success",FAILURE:"failure"},Fk={AUTHENTICATION:"authentication",AUTHORIZATION:"authorization"};CO.exports={LOCAL_HARPERDB_OPERATIONS:xe,HDB_SUPPORT_ADDRESS:TO,HDB_SUPPORT_URL:RO,HDB_PRICING_URL:lF,SUPPORT_HELP_MSG:_F,LICENSE_HELP_MSG:AO,HDB_PROC_NAME:pO,HDB_PROC_DESCRIPTOR:Uh,CLUSTERING_LEAF_PROC_DESCRIPTOR:i_,CLUSTERING_HUB_PROC_DESCRIPTOR:s_,SYSTEM_SCHEMA_NAME:DF,HASH_FOLDER_NAME:LF,HDB_HOME_DIR_NAME:MF,UPDATE_FILE_NAME:BF,LICENSE_KEY_DIR_NAME:UF,BOOT_PROPS_FILE_NAME:vF,JOB_TYPE_ENUM:fk,JOB_STATUS_ENUM:sk,SYSTEM_TABLE_NAMES:XF,SYSTEM_TABLE_HASH_ATTRIBUTES:ZF,OPERATIONS_ENUM:ee,VALID_S3_FILE_TYPES:ik,S3_BUCKET_AUTH_KEYS:ok,VALID_SQL_OPS_ENUM:ak,GEO_CONVERSION_ENUM:uk,HDB_SETTINGS_NAMES:yO,HDB_SETTINGS_NAMES_REVERSE_LOOKUP:lk,SERVICE_ACTIONS_ENUM:ck,CLUSTER_MESSAGE_TYPE_ENUM:Ek,CLUSTER_CONNECTION_DIRECTION_ENUM:hk,CLUSTER_EVENTS_DEFS_ENUM:Sk,PERIOD_REGEX:SF,DOUBLE_PERIOD_REGEX:TF,UNICODE_PERIOD:gF,FORWARD_SLASH_REGEX:RF,UNICODE_FORWARD_SLASH:AF,ESCAPED_FORWARD_SLASH_REGEX:OF,ESCAPED_PERIOD_REGEX:bF,ESCAPED_DOUBLE_PERIOD_REGEX:yF,REG_KEY_FILE_NAME:rk,RESTART_TIMEOUT_MS:GF,HDB_FILE_PERMISSIONS:qF,DATABASES_DIR_NAME:VF,LEGACY_DATABASES_DIR_NAME:$F,TRANSACTIONS_DIR_NAME:YF,LIMIT_COUNT_NAME:KF,ID_ATTRIBUTE_STRING:WF,INSERT_MODULE_ENUM:JF,UPGRADE_JSON_FIELD_NAMES_ENUM:jF,RESTART_CODE:xF,RESTART_CODE_NUM:HF,CLUSTER_OPERATIONS:dc,SYSTEM_DEFAULT_ATTRIBUTE_NAMES:tk,HDB_INTERNAL_SC_CHANNEL_PREFIX:Pr,INTERNAL_SC_CHANNELS:ek,CLUSTERING_MESSAGE_TYPES:Nk,HDB_FILE_SUFFIX:PF,BLOB_FOLDER_NAME:FF,HDB_TRASH_DIR:kF,ORIGINATOR_SET_VALUE:Ik,LICENSE_VALUES:mk,RAM_ALLOCATION_ENUM:pk,TIME_STAMP_NAMES_ENUM:IO,TIME_STAMP_NAMES:Ok,PERMS_UPDATE_RELEASE_TIMESTAMP:bk,SEARCH_NOT_FOUND_MESSAGE:dF,SEARCH_ATTRIBUTE_NOT_FOUND:fF,LICENSE_ROLE_DENIED_RESPONSE:EF,LICENSE_MAX_CONNS_REACHED:hF,BASIC_LICENSE_MAX_NON_CU_ROLES:gO,BASIC_LICENSE_CLUSTER_CONNECTION_LIMIT_WS_ERROR_CODE:uF,VALUE_SEARCH_COMPARATORS:wO,VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP:yk,LICENSE_FILE_NAME:nk,WEBSOCKET_CLOSE_CODE_DESCRIPTION_LOOKUP:Tk,NEW_LINE:wk,BASIC_LICENSE_MAX_CLUSTER_USER_ROLES:pF,MOMENT_DAYS_TAG:NF,API_TURNOVER_SEC:IF,LOOPBACK:mF,CODE_EXTENSION:n_,WILDCARD_SEARCH_VALUE:wF,NODE_ERROR_CODES:gk,JAVASCRIPT_EXTENSION:mO,PERMS_CRUD_ENUM:Ck,UNAUTHORIZED_PERMISSION_NAME:Lk,SEARCH_WILDCARDS:Dk,FUNC_VAL:Mk,READ_AUDIT_LOG_SEARCH_TYPES_ENUM:Pk,JWT_ENUM:Uk,CLUSTERING_FLAG:Ak,ITC_EVENT_TYPES:vk,CUSTOM_FUNCTION_PROC_NAME:SO,CUSTOM_FUNCTION_PROC_DESCRIPTOR:r_,SERVICES:Bk,THREAD_TYPES:xk,MEM_SETTING_KEY:CF,HDB_RESTART_SCRIPT:Qq,PROCESS_DESCRIPTORS:eF,SERVICE_SERVERS:iF,SERVICE_SERVERS_CWD:Ph,PROCESS_DESCRIPTORS_VALIDATE:nF,LAUNCH_SERVICE_SCRIPTS:oF,LOG_LEVELS:rF,PROCESS_NAME_ENV_PROP:QF,LOG_NAMES:tF,PM2_PROCESS_STATUSES:Hk,CONFIG_PARAM_MAP:NO,CONFIG_PARAMS:I,HDB_CONFIG_FILE:Yq,HDB_DEFAULT_CONFIG_FILE:Kq,ROLE_TYPES_ENUM:aF,BOOT_PROP_PARAMS:OO,INSTALL_PROMPTS:zF,HDB_ROOT_DIR_NAME:Wq,CLUSTERING_PROCESSES:sF,FOREGROUND_PID_FILE:jq,PACKAGE_ROOT:Zs,PRE_4_0_0_VERSION:Gk,DATABASES_PARAM_CONFIG:dk,METADATA_PROPERTY:Rk,AUTH_AUDIT_STATUS:qk,AUTH_AUDIT_TYPES:Fk,HDB_PID_FILE:Xq,DEFAULT_DATABASE_NAME:Zq,LEGACY_CONFIG_PARAMS:_k};hO()});var vh=g((oce,MO)=>{"use strict";var DO=require("minimist");MO.exports=kk;function kk(e=[],t=!1){if(!Array.isArray(e))return{};let r,n;t?(r=LO(process.env),n=LO(DO(process.argv))):(r=process.env,n=DO(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(kk,"assignCMDENVVariables");function LO(e){let t,r=Object.keys(e),n=r.length,s={};for(;n--;)t=r[n],s[t.toLowerCase()]=e[t];return s}a(LO,"objKeysToLowerCase")});var $=g((cce,kh)=>{"use strict";var Bi=require("fs-extra"),{workerData:Vk,threadId:$k}=require("worker_threads"),Ss=require("path"),vO=require("yaml"),BO=require("properties-reader"),Tt=P(),PO=vh(),Yk=require("os"),{PACKAGE_ROOT:xh}=P(),{_assignPackageExport:Kk}=require("../index"),Ec={};for(let e in console)Ec[e]||(Ec[e]=console[e]);var cr={notify:7,fatal:6,error:5,warn:4,info:3,debug:2,trace:1},xO={STDOUT:"stdOut",STDERR:"stdErr"},Wk=Ss.join(xh,"logs"),Qk=Ss.join(xh,"config/yaml/",Tt.HDB_DEFAULT_CONFIG_FILE),zk=1e4,ps,Wn,ar,o_,a_,hc,ko,fc;fc===void 0&&HO();kh.exports={notify:FO,fatal:kO,error:mc,warn:Fh,info:c_,debug:qh,trace:Gh,setLogLevel:rV,log_level:ar,loggerWithTag:Jk,suppressLogging:jk,initLogSettings:HO,setupConsoleLogging:GO,logCustomLevel:eV,closeLogFile:Hh,getLogFilePath:()=>hc,OUTPUTS:xO,AuthAuditLog:iV};Kk("logger",kh.exports);function HO(e=!1){try{if(fc===void 0||e){Hh();let t=tV(),r=PO(["ROOTPATH"]);try{fc=BO(t)}catch(n){if(!r.ROOTPATH||r.ROOTPATH&&!Bi.pathExistsSync(Ss.join(r.ROOTPATH,Tt.HDB_CONFIG_FILE)))throw n}({level:ar,config_log_path:a_,to_file:ps,to_stream:Wn}=nV(r.ROOTPATH?Ss.join(r.ROOTPATH,Tt.HDB_CONFIG_FILE):fc.get("settings_path"))),o_=Tt.LOG_NAMES.HDB,hc=Ss.join(a_,o_)}}catch(t){if(fc=void 0,t.code===Tt.NODE_ERROR_CODES.ENOENT||t.code===Tt.NODE_ERROR_CODES.ERR_INVALID_ARG_TYPE){let r=PO(Object.keys(Tt.CONFIG_PARAM_MAP),!0);for(let o in r){let c=Tt.CONFIG_PARAM_MAP[o];c&&c.toLowerCase();let u=r[o];if(c===Tt.CONFIG_PARAMS.LOGGING_LEVEL){ar=u;continue}if(c===Tt.CONFIG_PARAMS.LOGGING_STDSTREAMS){Wn=u;continue}c===Tt.CONFIG_PARAMS.LOGGING_FILE&&(ps=c)}let{default_level:n,default_to_file:s,default_to_stream:i}=sV();ps=ps===void 0?s:ps,ps=UO(ps),Wn=Wn===void 0?i:Wn,Wn=UO(Wn),ar=ar===void 0?n:ar,a_=Wk,o_=Tt.LOG_NAMES.INSTALL,hc=Ss.join(a_,o_);return}throw mc("Error initializing log settings"),mc(t),t}process.env.DEV_MODE&&(Wn=!0),GO()}a(HO,"initLogSettings");var Bh=!0;function GO(){Fo("error",mc),Fo("warn",Fh),Fo("log",c_),Fo("info",c_),Fo("debug",qh),Fo("trace",Gh)}a(GO,"setupConsoleLogging");function Fo(e,t){console[e]=function(...r){if(Bh&&t(...r),!/PM2 log:|App \[/.test(r[0]))return Ec[e](...r)}}a(Fo,"logConsole");function Jk(e){let t={tagName:e.replace(/ /g,"-")};return{notify:r(FO),fatal:r(kO),error:r(mc),warn:r(Fh),info:r(c_),debug:r(qh),trace:r(Gh)};function r(n){return function(...s){return n(t,...s)}}}a(Jk,"loggerWithTag");function jk(e){try{Bh=!1,e()}finally{Bh=!0}}a(jk,"suppressLogging");var Xk=Vk?.name?.replace(/ /g,"-")||"main";function Ts(e,t){let r=new Date(Date.now()).toISOString(),n="",s=t.length,i=s-1,o=[e],c=0,u;for(typeof t[0]=="object"&&(t[0]?.tagName?(o.push(t[0]?.tagName),c++):t[0]?.serviceName&&(u=t[0]?.serviceName,c++)),o.unshift(u||Xk+"/"+$k);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(Ts,"createLogRecord");function pc(e){ps&&qO(e),Wn&&process.stdout.write(e)}a(pc,"logStdOut");function u_(e){ps&&qO(e),Wn&&process.stderr.write(e)}a(u_,"logStdErr");function qO(e){Zk(),ko?Bi.appendFileSync(ko,e):Ec.log(e)}a(qO,"logToFile");function Hh(){try{Bi.closeSync(ko)}catch{}ko=null}a(Hh,"closeLogFile");function Zk(){if(!ko){try{if(!hc)debugger;ko=Bi.openSync(hc,"a")}catch(e){Ec.error(e)}setTimeout(()=>{Hh()},zk).unref()}}a(Zk,"openLogFile");function c_(...e){cr[ar]<=cr.info&&pc(Ts("info",e))}a(c_,"info");function Gh(...e){cr[ar]<=cr.trace&&pc(Ts("trace",e))}a(Gh,"trace");function mc(...e){cr[ar]<=cr.error&&u_(Ts("error",e))}a(mc,"error");function qh(...e){cr[ar]<=cr.debug&&pc(Ts("debug",e))}a(qh,"debug");function FO(...e){cr[ar]<=cr.notify&&pc(Ts("notify",e))}a(FO,"notify");function kO(...e){cr[ar]<=cr.fatal&&u_(Ts("fatal",e))}a(kO,"fatal");function Fh(...e){cr[ar]<=cr.warn&&u_(Ts("warn",e))}a(Fh,"warn");function eV(e,t,...r){t===xO.STDERR?u_(Ts(e,r)):pc(Ts(e,r))}a(eV,"logCustomLevel");function tV(){let e;try{e=Yk.homedir()}catch{e=process.env.HOME}e||(e="~/");let t=Ss.join(e,Tt.HDB_HOME_DIR_NAME,Tt.BOOT_PROPS_FILE_NAME);return Bi.existsSync(t)||(t=Ss.join(xh,"utility/hdb_boot_properties.file")),t}a(tV,"getPropsFilePath");function rV(e){ar=e}a(rV,"setLogLevel");function UO(e){return e===!0||typeof e=="string"&&e.toLowerCase()==="true"}a(UO,"autoCastBoolean");function nV(e){try{if(e.includes("config/settings.js")){let o=BO(e);return{level:o.get(Tt.HDB_SETTINGS_NAMES.LOG_LEVEL_KEY),config_log_path:Ss.dirname(o.get(Tt.HDB_SETTINGS_NAMES.LOG_PATH_KEY)),to_file:o.get(Tt.HDB_SETTINGS_NAMES.LOG_TO_FILE),to_stream:o.get(Tt.HDB_SETTINGS_NAMES.LOG_TO_STDSTREAMS)}}let t=vO.parseDocument(Bi.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===Tt.NODE_ERROR_CODES.ENOENT)throw t;console.error("Error accessing config file for logging"),console.error(t)}}a(nV,"getLogConfig");function sV(){try{let e=vO.parseDocument(Bi.readFileSync(Qk,"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(sV,"getDefaultConfig");function iV(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(iV,"AuthAuditLog")});var $O=g((lce,VO)=>{"use strict";var oV=require("util"),aV=require("path"),cV=require("child_process"),uV=oV.promisify(cV.execFile),lV=1e3*1e3*10;VO.exports={findPs:_V};async function _V(e){let t={};try{await Promise.all(["comm","args","ppid","uid","%cpu","%mem"].map(async r=>{let{stdout:n}=await uV("ps",["wwxo",`pid,${r}`],{maxBuffer:lV});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:aV.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(_V,"findPs")});var ft=g((dce,KO)=>{"use strict";var dV="__dbis__",fV="__txns__",EV="__environment_name__",hV="__dbi_defintion__",mV={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"},pV=["__createdtime__","__updatedtime__"],SV="\uFFFF",YO={TIMESTAMP:"timestamp",HASH_VALUE:"hash_value",USER_NAME:"user_name"},TV=Object.values(YO);KO.exports={AUDIT_STORE_NAME:fV,INTERNAL_DBIS_NAME:dV,DBI_DEFINITION_NAME:hV,SEARCH_TYPES:mV,TIMESTAMP_NAMES:pV,MAX_SEARCH_KEY_LENGTH:256,ENVIRONMENT_NAME_KEY:EV,TRANSACTIONS_DBI_NAMES_ENUM:YO,TRANSACTIONS_DBIS:TV,OVERFLOW_MARKER:SV}});var Ur=g((fce,tb)=>{"use strict";var WO=P(),QO=ft(),zO={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},JO=a(e=>`${e} Check logs and try again.`,"CHECK_LOGS_WRAPPER"),jO={500:JO("There was an error processing your request."),400:"Invalid request"},gV=jO[zO.INTERNAL_SERVER_ERROR],RV={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.`},AV={CONFIG_VALIDATION:e=>`HarperDB config file validation error: ${e}`},OV={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"},bV={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 ${QO.INTERNAL_DBIS_NAME}`,CANNOT_DROP_INTERNAL_DBIS_NAME:`cannot drop a dbi named ${QO.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"},yV={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"},XO={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"},NV={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."},IV={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`},wV={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"},CV={OUTER_JOIN_TRANSLATION_ERROR:"There was an error translating the final SQL outer join data."},DV={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`},ZO={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.`},eb={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}`},LV={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."},MV={CLUSTERING_NOT_ENABLED:"Clustering must be enabled to perform this operation."},PV={...XO,...OV,...RV,...NV,...IV,...wV,...CV,...DV,...yV,...ZO,...eb,...LV,...MV,...AV};tb.exports={CHECK_LOGS_WRAPPER:JO,HDB_ERROR_MSGS:PV,DEFAULT_ERROR_MSGS:jO,DEFAULT_ERROR_RESP:gV,HTTP_STATUS_CODES:zO,LMDB_ERRORS_ENUM:bV,AUTHENTICATION_ERROR_MSGS:XO,VALIDATION_ERROR_MSGS:ZO,ITC_ERRORS:eb}});var ne=g((hce,sb)=>{"use strict";var Vo=Ur(),UV=$(),vV=P(),l_=class extends Error{static{a(this,"HdbError")}constructor(t,r,n,s,i){super(),Error.captureStackTrace(this,rb),this.statusCode=n||Vo.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR,this.http_resp_msg=r||(Vo.DEFAULT_ERROR_MSGS[n]?Vo.DEFAULT_ERROR_MSGS[n]:Vo.DEFAULT_ERROR_MSGS[Vo.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&&UV[s](i)}},Vh=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}},$h=class extends Error{static{a(this,"ServerError")}constructor(t,r){super(t),this.statusCode=r||500}};function rb(e,t,r,n=vV.LOG_LEVELS.ERROR,s=null,i=!1){if(nb(e))return e;let o=new l_(e,t,r,n,s);return i&&delete o.stack,o}a(rb,"handleHDBError");function nb(e){return e.__proto__.constructor.name===l_.name}a(nb,"isHDBError");sb.exports={isHDBError:nb,handleHDBError:rb,ClientError:Vh,ServerError:$h,hdb_errors:Vo}});var je=g((pce,_b)=>{"use strict";var Ac=P(),BV=z(),ur=Z(),Oc=require("path"),xV=require("minimist"),ib=require("fs-extra"),ob=require("lodash");ur.initSync();var{CONFIG_PARAMS:ei,DATABASES_PARAM_CONFIG:Sc,SYSTEM_SCHEMA_NAME:__}=Ac,Tc,gc,Rc;function ab(){if(Tc!==void 0)return Tc;if(ur.getHdbBasePath()!==void 0)return Tc=ur.get(ei.STORAGE_PATH)||Oc.join(ur.getHdbBasePath(),Ac.DATABASES_DIR_NAME),Tc}a(ab,"getBaseSchemaPath");function cb(){if(gc!==void 0)return gc;if(ur.getHdbBasePath()!==void 0)return gc=lb(__),gc}a(cb,"getSystemSchemaPath");function ub(){if(Rc!==void 0)return Rc;if(ur.getHdbBasePath()!==void 0)return Rc=ur.get(Ac.CONFIG_PARAMS.STORAGE_AUDIT_PATH)||Oc.join(ur.getHdbBasePath(),Ac.TRANSACTIONS_DIR_NAME),Rc}a(ub,"getTransactionAuditStoreBasePath");function HV(e,t){let r=ur.get(ei.DATABASES)?.[e];return t&&r?.tables?.[t]?.auditPath||r?.auditPath||Oc.join(ub(),e.toString())}a(HV,"getTransactionAuditStorePath");function lb(e,t){e=e.toString(),t=t&&t.toString();let r=ur.get(Ac.CONFIG_PARAMS.DATABASES)?.[e];return t&&r?.tables?.[t]?.path||r?.path||Oc.join(ab(),e)}a(lb,"getSchemaPath");function GV(e,t){e=e.toString(),t=t.toString();let r=process.env;Object.assign(r,xV(process.argv));let n=r[ei.DATABASES.toUpperCase()];if(n){let i;try{i=JSON.parse(n)}catch(o){if(!BV.isObject(n))throw o;i=n}for(let o of i){let c=o[__];if(!c)continue;let u=ur.get(ei.DATABASES);u=u??{};let _=c?.tables?.[t]?.[Sc.PATH];if(_)return ob.set(u,[__,Sc.TABLES,t,Sc.PATH],_),ur.setProperty(ei.DATABASES,u),_;let l=c?.[Sc.PATH];if(l)return ob.set(u,[__,Sc.PATH],l),ur.setProperty(ei.DATABASES,u),l}}let s=r[ei.STORAGE_PATH.toUpperCase()];if(s){if(!ib.pathExistsSync(s))throw new Error(s+" does not exist");let i=Oc.join(s,e);return ib.mkdirsSync(i),ur.setProperty(ei.STORAGE_PATH,s),i}return cb()}a(GV,"initSystemSchemaPaths");function qV(){Tc=void 0,gc=void 0,Rc=void 0}a(qV,"resetPaths");_b.exports={getBaseSchemaPath:ab,getSystemSchemaPath:cb,getTransactionAuditStorePath:HV,getTransactionAuditStoreBasePath:ub,getSchemaPath:lb,initSystemSchemaPaths:GV,resetPaths:qV}});var vr=g((Rce,mb)=>{"use strict";var FV=Ur().LMDB_ERRORS_ENUM,Tce=require("lmdb"),kV=ft(),gce=require("buffer").Buffer,{OVERFLOW_MARKER:db,MAX_SEARCH_KEY_LENGTH:d_}=kV,fb=["number","string","symbol","boolean","bigint"];function VV(e){if(e=e?.primaryStore||e,!e)throw new Error(FV.ENV_REQUIRED)}a(VV,"validateEnv");function $V(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($V,"stringifyData");function YV(e){return e instanceof Date?e.valueOf():e}a(YV,"convertKeyValueToWrite");function KV(e,t){if(e===null)return t?[null]:void 0;if(e===void 0)return;if(fb.includes(typeof e))return e.length>d_?[e.slice(0,d_)+db]:[e];let r;if(Array.isArray(e)){r=[];for(let n=0,s=e.length;n<s;n++){let i=e[n];if(fb.includes(typeof i))i.length>d_?r.push(i.slice(0,d_)+db):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(KV,"getIndexedValues");var f_=0,Eb=0;function hb(){Eb=Date.now()-performance.now()}a(hb,"adjustStartTime");hb();var WV=6e4;setInterval(hb,WV).unref();function QV(){let e=performance.now()+Eb;return e>f_?(f_=e,e):(f_+=488e-6,f_)}a(QV,"getNextMonotonicTime");mb.exports={validateEnv:VV,stringifyData:$V,convertKeyValueToWrite:YV,getNextMonotonicTime:QV,getIndexedValues:KV}});var pb,yn,Yh,bc=Re(()=>{pb=require("events"),yn=class extends pb.EventEmitter{static{a(this,"IterableEventQueue")}resolveNext;queue;hasDataListeners;[Symbol.asyncIterator](){let t=new Yh;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)}},Yh=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 xi={};Fe(xi,{server:()=>at});var Sb,at,lr=Re(()=>{Sb=require("../index"),at={};(0,Sb._assignPackageExport)("server",at)});var Qh={};Fe(Qh,{loadGQLSchema:()=>jV,start:()=>Wh,startOnMainThread:()=>JV});function Wh({ensureTable:e}){return{handleFile:t,setupFile:t};async function t(r,n,s,i){let{parse:o,Source:c,Kind:u,NamedTypeNode:_,StringValueNode:l}=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 u.OBJECT_TYPE_DEFINITION:let x=function(v){if(v.kind==="NonNullType"){let Q=x(v.type);return Q.nullable=!1,Q}if(v.kind==="ListType")return{type:"array",elements:x(v.type)};let M={type:v.name?.value};return Object.defineProperty(M,"location",{value:v.loc.startToken}),M};a(x,"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 F of v.arguments)b[F.name.value]=F.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 F of v.arguments)F.name.value==="name"&&(b.export={name:F.value.value})}}let C=!1;for(let v of S.fields){let F=x(v.type);F.name=v.name.value,R.push(F);for(let M of v.directives)if(M.name.value==="primaryKey")C?console.warn("Can not define two attributes as a primary key"):(F.isPrimaryKey=!0,C=!0);else if(M.name.value==="indexed")F.indexed=!0;else if(M.name.value==="relationship"){let Q={};for(let J of M.arguments)Q[J.name.value]=J.value.value;F.relationship=Q}else if(M.name.value==="createdTime")F.assignCreatedTime=!0;else if(M.name.value==="updatedTime")F.assignUpdatedTime=!0;else if(M.name.value==="expiresAt")F.expiresAt=!0;else if(M.name.value==="allow"){let Q=F.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):zV.includes(S.type)||(0,Tb.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,Kh.dirname)(n),S.tableClass):i.set((0,Kh.dirname)(n)+"/"+(S.export.name||S.type),S.tableClass))}}var Kh,Tb,zV,JV,jV,gb=Re(()=>{Kh=require("path");Ae();Tb=B(We()),zV=["ID","Int","Float","Long","String","Boolean","Date","Bytes","Any","BigInt"];a(Wh,"start");JV=Wh,jV=Wh({ensureTable:Et}).handleFile});async function E_(e){let t=(0,Ob.pathToFileURL)(e).toString();return XV?(yc||(yc=ZV(t$)),(await(await yc).import(t)).namespace):import(t)}async function ZV(e){let{StaticModuleRecord:t}=await import("@endo/static-module-record");return require("ses"),lockdown({domainTaming:"unsafe",consoleTaming:"unsafe",errorTaming:"unsafe",errorTrapping:"none",stackFiltering:"verbose"}),yc=new Compartment({console,Math,Date,fetch:e$,...e()},{},{name:"h-dapp",resolveHook(r,n){return r==="harperdb"?"harperdb":(r=new URL(r,n).toString(),(0,Ab.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:ct})}};let n=await(0,Rb.readFile)(new URL(r),{encoding:"utf-8"});return new t(n,r)}}),yc}function e$(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 t$(){return{Resource:$t,tables:Br}}var Rb,Ab,Ob,XV,yc,zh=Re(()=>{Nn();Ae();Rb=require("fs/promises"),Ab=require("path"),Ob=require("url"),XV=!1;a(E_,"secureImport");a(ZV,"getCompartment");a(e$,"secureOnlyFetch");a(t$,"getGlobalVars")});var jh={};Fe(jh,{handleFile:()=>r$});async function r$(e,t,r,n){let s=new Map,i=await E_(r);c(i.default)&&n.set((0,Jh.dirname)(t),i.default),o(i,(0,Jh.dirname)(t));function o(u,_){for(let l in u){let d=u[l];c(d)?n.set(_+"/"+l,d):typeof d=="object"&&o(d,_+"/"+l)}}a(o,"recurseForResources");function c(u){return typeof u=="function"&&(u.get||u.put||u.post||u.delete)}return a(c,"isResource"),s}var Jh,bb=Re(()=>{zh();Jh=require("path");a(r$,"handleFile")});var Zh={};Fe(Zh,{start:()=>n$});function n$({resources:e}){e.set("login",Xh),e.loginPath=t=>"/login?redirect="+encodeURIComponent(t.url)}var Xh,yb=Re(()=>{Nn();a(n$,"start");Xh=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 Mb={};Fe(Mb,{parse:()=>tm,streamAsJSON:()=>Nc,stringify:()=>Hi});function Nc(e){return new em({value:e})}function Nb(e){return console.error(e),JSON.stringify(e.toString())}function Ib(e,t,r){return e?.then?r?e.then(t,r):e.then(t):t(e)}function Hi(e){try{return JSON.stringify(e)??"null"}catch(t){if(t===Db)return Lb(e);if(t.resolution)return t.resolution.then(()=>Hi(e));throw t}}function Lb(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+=Lb(e[n]);return r+"]"}else{r="{";let n=!0;for(let s in e)n?n=!1:r+=",",r+=JSON.stringify(s)+":"+Hi(e[s]);return r+"}"}}else{if(t==="string")return JSON.stringify(e);if(t==="undefined")return"null"}return e.toString()}function tm(e){return o$.test(e)?s$.parse(e):JSON.parse(e)}var wb,Cb,s$,i$,Db,em,o$,rm=Re(()=>{wb=require("stream"),Cb=B(require("json-bigint-fixes")),s$=(0,Cb.default)({useNativeBigInt:!0}),i$=1e4,Db={};BigInt.prototype.toJSON=function(){throw Db};a(Nc,"streamAsJSON");em=class extends wb.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),Nb)}catch(s){yield Nb(s)}else yield Hi(t)}else yield Hi(t)}_read(){if(!this._amReading){if(this._amReading=!0,this.done)return this.push(null);Ib(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>i$?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 Ib(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(Nb,"handleError");a(Ib,"when");a(Hi,"stringify");a(Lb,"jsStringify");o$=/[[,:]\s*-?\d{16,}/;a(tm,"parse")});var Yb=g((xce,$b)=>{"use strict";var nm=require("recursive-iterator"),a$=require("alasql"),sm=require("clone"),Pb=z(),{handleHDBError:Ub,hdb_errors:c$}=ne(),{HDB_ERROR_MSGS:vb,HTTP_STATUS_CODES:Bb}=c$,{getDatabases:u$}=(Ae(),ie(ke)),l$=["DISTINCT_ARRAY"],xb=Symbol("validateTables"),im=Symbol("validateTable"),Bce=Symbol("getAllColumns"),Hb=Symbol("validateAllColumns"),h_=Symbol("findColumn"),Gb=Symbol("validateOrderBy"),Ic=Symbol("validateSegment"),om=Symbol("validateColumn"),qb=Symbol("setColumnsForTable"),Fb=Symbol("checkColumnsForAsterisk"),kb=Symbol("validateGroupBy"),Vb=Symbol("hasColumns"),am=class{static{a(this,"SelectValidator")}constructor(t){this.statement=t,this.attributes=[]}validate(){if(!this.statement)throw new Error("invalid sql statement");this[xb](),this[Fb](),this[Hb]()}[xb](){if(this[Vb]()){if(!this.statement.from||this.statement.from.length===0)throw"no from clause";this.statement.from.forEach(t=>{this[im](t)}),this.statement.joins&&this.statement.joins.forEach(t=>{t.table.as=t.as,this[im](t.table)})}}[Vb](){let t=!1,r=new nm(this.statement);for(let{node:n,path:s}of r)if(n&&n.columnid){t=!0;break}return t}[im](t){if(!t.databaseid)throw`schema not defined for table ${t.tableid}`;let r=u$();if(!r[t.databaseid])throw Ub(new Error,vb.SCHEMA_NOT_FOUND(t.databaseid),Bb.NOT_FOUND);if(!r[t.databaseid][t.tableid])throw Ub(new Error,vb.TABLE_NOT_FOUND(t.databaseid,t.tableid),Bb.NOT_FOUND);r[t.databaseid][t.tableid].attributes.forEach(s=>{let i=sm(s);i.table=sm(t),this.attributes.push(i)})}[h_](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)}[Fb](){let t=new nm(this.statement.columns);for(let{node:r,path:n}of t)r&&r.columnid==="*"&&n.indexOf("expression")<0&&this[qb](r.tableid)}[qb](t){this.attributes.forEach(r=>{(!t||t&&(r.table.tableid===t||r.table.as===t))&&!r.relation&&this.statement.columns.push(new a$.yy.Column({columnid:r.attribute,tableid:r.table.as?r.table.as:r.table.tableid}))})}[Hb](){this[Ic](this.statement.columns,!1),this[Ic](this.statement.joins,!1),this[Ic](this.statement.where,!1),this[kb](this.statement.group,!1),this[Ic](this.statement.order,!0)}[Ic](t,r){if(!t)return;let n=new nm(t),s=[];for(let{node:i,path:o}of n)!Pb.isEmpty(i)&&!Pb.isEmpty(i.columnid)&&i.columnid!=="*"&&(r?this[Gb](i):s.push(this[om](i)));return s}[kb](t){if(!t)return;let r=[];if(this.statement.columns.forEach(n=>{if(!(n.funcid&&l$.indexOf(n.funcid.toUpperCase())>=0)){if(!n.aggregatorid&&!n.columnid){let s=sm(n);delete s.as,r.push(s)}else if(n.columnid){let s=this[h_](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[h_](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[om](t)}[om](t){let r=this[h_](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]}};$b.exports=am});var Wb=g((Gce,Kb)=>{"use strict";var cm=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")}};Kb.exports=cm});var zb=g((Fce,Qb)=>{"use strict";var um=class{static{a(this,"DBIDefinition")}constructor(t=!1,r=!1){this.dup_sort=t,this.is_hash_attribute=r,this.useVersions=r}};Qb.exports=um});var Zb={};Fe(Zb,{HAS_EXPIRATION:()=>mm,LAST_TIMESTAMP_PLACEHOLDER:()=>Dc,LOCAL_TIMESTAMP:()=>_$,METADATA:()=>wc,NO_TIMESTAMP:()=>_m,PENDING_LOCAL_TIME:()=>pm,PREVIOUS_TIMESTAMP_PLACEHOLDER:()=>hm,RecordEncoder:()=>Em,TIMESTAMP_ASSIGN_LAST:()=>f$,TIMESTAMP_ASSIGN_NEW:()=>jb,TIMESTAMP_ASSIGN_PREVIOUS:()=>Xb,TIMESTAMP_PLACEHOLDER:()=>m_,TIMESTAMP_RECORD_PREVIOUS:()=>dm,getUpdateRecord:()=>Sm,handleLocalTimeForGets:()=>g_});function h$(){return Cc[0]=Cc[0]^64,d$.getFloat64(0)}function g_(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),u=c?.value,_=u?.[wc];return _>=0&&(c.metadataFlags=_,c.localTime=u.localTime,c.value=u.value,u.expiresAt>0&&(c.expiresAt=u.expiresAt)),c&&(c.key=i),c};let r=e.get;e.get=function(i,o){let c=r.call(this,i,o);return c?.[wc]>=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 u=c.value,_=u[wc];return _>=0&&(c.metadataFlags=_,c.localTime=u.localTime,c.value=u.value,u.expiresAt>0&&(c.expiresAt=u.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,Gi.push(new WeakRef(this))),o.call(this)},i.prototype.done=function(){if(c.call(this),this.isDone)for(let u=0;u<Gi.length;u++){let _=Gi[u].deref();(!_||_.isDone||_.isCommitted)&&Gi.splice(u--,1)}},i.prototype.done.isTracked=!0}return e}function Sm(e,t,r){return function(n,s,i,o,c=-1,u,_,l,d="put",E,f){if(E||u==null?$o=i?.localTime?dm|Xb:_m:$o=u?i?.localTime?dm|16384:jb|16384:_m,l>0&&(c|=mm),S_=c,fm=l,i?.version===o&&u===!1)throw new Error("Must retain local time if version is not changed");let h={version:o,instructedWrite:$o>0},p;try{E&&(h.ifVersion=p=i?.version??null);let S=e.put(n,s,h);if(u){let T=_?.user?.username;if(f&&(p_=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,T_(o,t,n,C,T,d,p_),{ifVersion:p}),S}}r.put(Dc,T_(o,t,n,i?.localTime?1:0,T,d,p_),{append:d!=="invalidate",instructedWrite:!0,ifVersion:p})}return S}catch(S){throw S.message+=" id: "+n+" options: "+h,S}}}var Jb,lm,m_,Dc,hm,_$,wc,Cc,d$,_m,jb,f$,Xb,dm,mm,pm,E$,p_,$o,S_,fm,Em,Gi,Lc=Re(()=>{Jb=require("msgpackr");ti();lm=B($()),m_=new Uint8Array([1,1,1,1,4,64,0,0]),Dc=new Uint8Array([1,1,1,1,1,0,0,0]),hm=new Uint8Array([1,1,1,1,3,64,0,0]),_$=Symbol("local-timestamp"),wc=Symbol("metadata"),Cc=new Uint8Array(8),d$=new DataView(Cc.buffer,0,8),_m=0,jb=0,f$=1,Xb=3,dm=4,mm=16,pm=1,$o=0,S_=-1,fm=0,Em=class extends Jb.Encoder{static{a(this,"RecordEncoder")}constructor(t){t.useBigIntExtension=!0,super(t);let r=this.encode;this.encode=function(n,s){if($o||S_>=0){let i=0,o=$o;o&&(i+=8,$o=0);let c=S_,u=fm;c>=0&&(i+=2,S_=-1,u&&(i+=8,fm=0));let _=E$=r.call(this,n,s|2048|i);p_=_.subarray((_.start||0)+i,_.end);let l=_.start||0;return o&&(m_[4]=o,m_[5]=o>>8,_.set(m_,l),l+=8),c>=0&&(_[l++]=c,_[l++]=0,u&&(_.dataView||(_.dataView=new DataView(_.buffer,_.byteOffset,_.byteLength))).setFloat64(l,u)),_}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,u;if(i===2){if(t.copy)t.copy(Cc,0,c),c+=8;else for(let d=0;d<8;d++)Cc[d]=t[c++];u=h$(),i=t[c]}let _;i<32&&(o=i,c+=2,o&mm&&(_=(t.dataView||(t.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength))).getFloat64(c),c+=8));let l=super.decode(t.subarray(c,s),s-c);return{localTime:u,value:l,[wc]:o,expiresAt:_}}return super.decode(t,r)}catch(c){throw c.message+=", data: "+t.slice(0,40).toString("hex"),c}}};a(h$,"getTimestamp");a(g_,"handleLocalTimeForGets");Gi=[];setInterval(()=>{for(let e=0;e<Gi.length;e++){let t=Gi[e].deref();!t||t.isDone||t.isCommitted?Gi.splice(e--,1):t.notCurrent&&(t.openTimer?(t.openTimer>3&&(t.openTimer>60?(lm.error("Read transaction detected that has been open too long (over 15 minutes), ending transaction",t),t.done()):lm.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(Sm,"getUpdateRecord")});var Mc=g((Kce,ty)=>{"use strict";var ey=Z(),m$=P(),{RecordEncoder:p$}=(Lc(),ie(Zb)),Yce=require("fs");ey.initSync();var S$=ey.get(m$.CONFIG_PARAMS.STORAGE_CACHING)!==!1,Tm=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=S$&&{validated:!0},this.randomAccessStructure=!0,this.freezeData=!0,this.encoder={Encoder:p$})}};ty.exports=Tm});var Pc=g((Qce,ry)=>{"use strict";var xr=Z(),cn=P();xr.initSync();var R_=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=xr.get(cn.CONFIG_PARAMS.STORAGE_WRITEASYNC)===!0||xr.get(cn.CONFIG_PARAMS.STORAGE_WRITEASYNC)==="true"||xr.get(cn.CONFIG_PARAMS.STORAGE_WRITEASYNC)==="TRUE",xr.get(cn.CONFIG_PARAMS.STORAGE_OVERLAPPINGSYNC)!==void 0&&(this.overlappingSync=xr.get(cn.CONFIG_PARAMS.STORAGE_OVERLAPPINGSYNC)),xr.get(cn.CONFIG_PARAMS.STORAGE_MAXFREESPACETOLOAD)&&(this.maxFreeSpaceToLoad=xr.get(cn.CONFIG_PARAMS.STORAGE_MAXFREESPACETOLOAD)),xr.get(cn.CONFIG_PARAMS.STORAGE_MAXFREESPACETORETAIN)&&(this.maxFreeSpaceToRetain=xr.get(cn.CONFIG_PARAMS.STORAGE_MAXFREESPACETORETAIN)),xr.get(cn.CONFIG_PARAMS.STORAGE_PAGESIZE)&&(this.pageSize=xr.get(cn.CONFIG_PARAMS.STORAGE_PAGESIZE)),this.noReadAhead=xr.get(cn.CONFIG_PARAMS.STORAGE_NOREADAHEAD)}};ry.exports=R_;R_.MAX_DBS=1e4});var Qe=g((Jce,dy)=>{"use strict";var Rm=require("lmdb"),In=require("fs-extra"),Hr=require("path"),A_=vr(),iy=$(),_r=Ur().LMDB_ERRORS_ENUM,O_=zb(),Am=Mc(),oy=Pc(),ri=ft(),ny=P(),{table:T$,resetDatabases:g$}=(Ae(),ie(ke)),sy=Z(),wn=ri.INTERNAL_DBIS_NAME,ay=ri.DBI_DEFINITION_NAME,R$="data.mdb",A$="lock.mdb",Uc=".mdb",O$="-lock",gm=class{static{a(this,"TransactionCursor")}constructor(t,r,n=!1){this.dbi=un(t,r),this.key_type=this.dbi[ri.DBI_DEFINITION_NAME].key_type,this.is_hash_attribute=this.dbi[ri.DBI_DEFINITION_NAME].is_hash_attribute,this.txn=t.beginTxn({readOnly:n===!1}),this.cursor=new Rm.Cursor(this.txn,this.dbi)}close(){this.cursor.close(),this.txn.abort()}commit(){this.cursor.close(),this.txn.commit()}};function b_(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(b_,"pathEnvNameValidation");async function Om(e,t,r=!0){try{await In.access(e)}catch(n){throw n.code==="ENOENT"?new Error(_r.INVALID_BASE_PATH):n}try{let n=Hr.join(e,t+Uc);return await In.access(n,In.constants.R_OK|In.constants.F_OK),n}catch(n){if(n.code==="ENOENT")if(r)try{return await In.access(Hr.join(e,t,R$),In.constants.R_OK|In.constants.F_OK),Hr.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(Om,"validateEnvironmentPath");function y_(e,t){if(A_.validateEnv(e),t===void 0)throw new Error(_r.DBI_NAME_REQUIRED)}a(y_,"validateEnvDBIName");async function b$(e,t,r=!1,n=!1){b_(e,t);let s=Hr.basename(e);t=t.toString();let i=sy.get(ny.CONFIG_PARAMS.DATABASES);i||sy.setProperty(ny.CONFIG_PARAMS.DATABASES,i={}),i[s]||(i[s]={}),i[s].path=e;try{return await Om(e,t,n),cy(e,t,r)}catch(o){if(o.message===_r.INVALID_ENVIRONMENT){let c=Hr.join(e,t);await In.mkdirp(n?c:e);let u=new oy(n?c:c+Uc,!1),_=Rm.open(u);_.dbis=Object.create(null);let l=new Am(!1);_.openDB(wn,l),global.lmdb_map===void 0&&(global.lmdb_map=Object.create(null));let d=bm(e,t,r);return _[ri.ENVIRONMENT_NAME_KEY]=d,global.lmdb_map[d]=_,_}throw o}}a(b$,"createEnvironment");async function y$(e,t,r,n=!0){b_(e,t),t=t.toString();let s=Hr.join(e,t);return T$({table:t,database:Hr.parse(e).name,path:s,attributes:[{name:"id",isPrimaryKey:!0}]})}a(y$,"copyEnvironment");async function cy(e,t,r=!1){b_(e,t),t=t.toString();let n=bm(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 Om(e,t),i=Hr.join(e,t+Uc),o=s!=i,c=new oy(s,o),u=Rm.open(c);u.dbis=Object.create(null);let _=ly(u);for(let l=0;l<_.length;l++)un(u,_[l]);return u[ri.ENVIRONMENT_NAME_KEY]=n,global.lmdb_map[n]=u,u}a(cy,"openEnvironment");async function N$(e,t,r=!1){b_(e,t),t=t.toString();let n=Hr.join(e,t+Uc),s=await Om(e,t);if(global.lmdb_map!==void 0){let i=bm(e,t,r);if(global.lmdb_map[i]){let o=global.lmdb_map[i];await uy(o),delete global.lmdb_map[i]}}await In.remove(s),await In.remove(s===n?s+O$:Hr.join(Hr.dirname(s),A$))}a(N$,"deleteEnvironment");async function uy(e){A_.validateEnv(e);let t=e[ri.ENVIRONMENT_NAME_KEY];await e.close(),t!==void 0&&global.lmdb_map!==void 0&&delete global.lmdb_map[t]}a(uy,"closeEnvironment");function bm(e,t,r=!1){let s=`${Hr.basename(e)}.${t}`;return r===!0&&(s=`txn.${s}`),s}a(bm,"getCachedEnvironmentName");function I$(e){A_.validateEnv(e);let t=Object.create(null),r=un(e,wn);for(let{key:n,value:s}of r.getRange({start:!1}))if(n!==wn)try{t[n]=Object.assign(new O_,s)}catch{iy.warn(`an internal error occurred: unable to parse DBI Definition for ${n}`)}return t}a(I$,"listDBIDefinitions");function ly(e){A_.validateEnv(e);let t=[],r=un(e,wn);for(let{key:n}of r.getRange({start:!1}))n!==wn&&t.push(n);return t}a(ly,"listDBIs");function w$(e,t){let n=un(e,wn).getEntry(t),s=new O_;if(n!==void 0){try{s=Object.assign(s,n.value)}catch{iy.warn(`an internal error occurred: unable to parse DBI Definition for ${n}`)}return s}}a(w$,"getDBIDefinition");function _y(e,t,r,n=!r){if(y_(e,t),t=t.toString(),t===wn)throw new Error(_r.CANNOT_CREATE_INTERNAL_DBIS_NAME);try{return un(e,t)}catch(s){if(s.message===_r.DBI_DOES_NOT_EXIST){let i=new Am(r,n===!0),o=e.openDB(t,i),c=new O_(r===!0,n);return o[ay]=c,un(e,wn).putSync(t,c),e.dbis[t]=o,o}throw s}}a(_y,"createDBI");function un(e,t){if(y_(e,t),t=t.toString(),e.dbis[t]!==void 0)return e.dbis[t];let r;if(t!==wn?r=w$(e,t):r=new O_,r===void 0)throw new Error(_r.DBI_DOES_NOT_EXIST);let n;try{let s=new Am(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[ay]=r,e.dbis[t]=n,n}a(un,"openDBI");function C$(e,t){y_(e,t),t=t.toString();let r=un(e,t),n=r.getStats();return r[ri.DBI_DEFINITION_NAME].is_hash_attribute&&n.entryCount>0&&n.entryCount--,n}a(C$,"statDBI");async function D$(e,t){try{let r=Hr.join(e,t+Uc);return(await In.stat(r)).size}catch{throw new Error(_r.INVALID_ENVIRONMENT)}}a(D$,"environmentDataSize");function L$(e,t){if(y_(e,t),t=t.toString(),t===wn)throw new Error(_r.CANNOT_DROP_INTERNAL_DBIS_NAME);un(e,t).dropSync(),e.dbis!==void 0&&delete e.dbis[t],un(e,wn).removeSync(t)}a(L$,"dropDBI");function M$(e,t,r){let n;for(let s=0;s<r.length;s++){let i=r[s];if(!e.dbis[i])try{un(e,i)}catch(o){if(o.message===_r.DBI_DOES_NOT_EXIST)_y(e,i,i!==t,i===t),n=!0;else throw o}}n&&g$()}a(M$,"initializeDBIs");dy.exports={openDBI:un,openEnvironment:cy,createEnvironment:b$,listDBIs:ly,listDBIDefinitions:I$,createDBI:_y,dropDBI:L$,statDBI:C$,deleteEnvironment:N$,initializeDBIs:M$,TransactionCursor:gm,environmentDataSize:D$,copyEnvironment:y$,closeEnvironment:uy}});var Ey=g((Xce,fy)=>{"use strict";var ym=class{static{a(this,"InsertRecordsResponseObject")}constructor(t=[],r=[],n=void 0){this.written_hashes=t,this.skipped_hashes=r,this.txn_time=n}};fy.exports=ym});var my=g((eue,hy)=>{"use strict";var Nm=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}};hy.exports=Nm});var Sy=g((rue,py)=>{"use strict";var Im=class{static{a(this,"UpsertRecordsResponseObject")}constructor(t=[],r=void 0,n=[]){this.written_hashes=t,this.txn_time=r,this.original_records=n}};py.exports=Im});var Yo=g((aue,Ry)=>{"use strict";var P$=Qe(),U$=Ey(),v$=my(),B$=Sy(),Qn=vr(),vc=Ur().LMDB_ERRORS_ENUM,x$=ft(),gs=P(),H$=z(),G$=require("uuid"),sue=require("lmdb"),{handleHDBError:q$,hdb_errors:F$}=ne(),{OVERFLOW_MARKER:iue,MAX_SEARCH_KEY_LENGTH:oue}=x$,Ty=Z();Ty.initSync();var N_=Ty.get(gs.CONFIG_PARAMS.STORAGE_PREFETCHWRITES),wm=gs.TIME_STAMP_NAMES_ENUM.CREATED_TIME,qi=gs.TIME_STAMP_NAMES_ENUM.UPDATED_TIME;async function k$(e,t,r,n,s=Qn.getNextMonotonicTime()){Mm(e,t,r,n),Cm(e,t,r);let i=new U$,o=[],c=[];for(let u=0;u<n.length;u++){let _=n[u];gy(_,!0,s);let l=V$(e,t,r,_),d=_[t];o.push(l),c.push(d)}return Dm(o,c,n,i,s)}a(k$,"insertRecords");function V$(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 l=c([[{}]]);Array.isArray(l)&&(c=l[0][gs.FUNC_VAL],n[o]=c)}let u=Qn.getIndexedValues(c),_=e.dbis[o];if(u){N_&&_.prefetch(u.map(l=>({key:l,value:s})),I_);for(let l=0,d=u.length;l<d;l++)_.put(u[l],s)}}N_&&e.dbis[t].prefetch([s],I_),e.dbis[t].put(s,n,n[qi])})}a(V$,"insertRecord");function $$(e,t=[]){let r=0;for(let n=0;n<t.length;n++){let s=t[n];e.splice(s-r,1),r++}}a($$,"removeSkippedRecords");function gy(e,t,r){let n=r>0;(n||!Number.isInteger(e[qi]))&&(e[qi]=r||(r=Qn.getNextMonotonicTime())),t===!0?(n||!Number.isInteger(e[wm]))&&(e[wm]=r||Qn.getNextMonotonicTime()):delete e[wm]}a(gy,"setTimestamps");function Cm(e,t,r){r.indexOf(gs.TIME_STAMP_NAMES_ENUM.CREATED_TIME)<0&&r.push(gs.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.indexOf(gs.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)<0&&r.push(gs.TIME_STAMP_NAMES_ENUM.UPDATED_TIME),P$.initializeDBIs(e,t,r)}a(Cm,"initializeTransaction");async function Y$(e,t,r,n,s=Qn.getNextMonotonicTime()){Mm(e,t,r,n),Cm(e,t,r);let i=new v$,o=[],c=[],u=[];for(let _=0;_<n.length;_++){let l=n[_],d=l[t],E;try{E=Lm(e,t,l,d,i,!0,s)}catch{i.skipped_hashes.push(d),o.push(_);continue}c.push(E),u.push(d)}return Dm(c,u,n,i,s,o)}a(Y$,"updateRecords");async function K$(e,t,r,n,s=Qn.getNextMonotonicTime()){try{Mm(e,t,r,n)}catch(u){throw q$(u,u.message,F$.HTTP_STATUS_CODES.BAD_REQUEST)}Cm(e,t,r);let i=new B$,o=[],c=[];for(let u=0;u<n.length;u++){let _=n[u],l;H$.isEmpty(_[t])?(l=G$.v4(),_[t]=l):l=_[t];let d=Lm(e,t,_,l,i,!1,s);o.push(d),c.push(l)}return Dm(o,c,n,i,s)}a(K$,"upsertRecords");async function Dm(e,t,r,n,s,i=[]){let o=await Promise.all(e);for(let c=0,u=o.length;c<u;c++)o[c]===!0?n.written_hashes.push(t[c]):(n.skipped_hashes.push(t[c]),i.push(c));return n.txn_time=s||Qn.getNextMonotonicTime(),$$(r,i),n}a(Dm,"finalizeWrite");function Lm(e,t,r,n,s,i=!1,o){let c=e.dbis[t],u=c.getEntry(n),_=u?.value,l=_;if(!_){if(i)return!1;_={}}if(gy(r,!l,o),Number.isInteger(r[qi])&&_[qi]>r[qi])return!1;l&&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][gs.FUNC_VAL],r[h]=p)}if(p===T)continue;let R=Qn.getIndexedValues(T);if(R){N_&&S.prefetch(R.map(b=>({key:b,value:n})),I_);for(let b=0,C=R.length;b<C;b++)S.remove(R[b],n)}if(R=Qn.getIndexedValues(p),R){N_&&S.prefetch(R.map(b=>({key:b,value:n})),I_);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[qi])},"do_put");return u?d=c.ifVersion(n,u.version,E):d=c.ifNoExists(n,E),d.then(f=>f?!0:Lm(e,t,r,n,s,i,o))}a(Lm,"updateUpsertRecord");function W$(e,t,r){if(Qn.validateEnv(e),t===void 0)throw new Error(vc.HASH_ATTRIBUTE_REQUIRED);if(!Array.isArray(r))throw r===void 0?new Error(vc.WRITE_ATTRIBUTES_REQUIRED):new Error(vc.WRITE_ATTRIBUTES_MUST_BE_ARRAY)}a(W$,"validateBasic");function Mm(e,t,r,n){if(W$(e,t,r),!Array.isArray(n))throw n===void 0?new Error(vc.RECORDS_REQUIRED):new Error(vc.RECORDS_MUST_BE_ARRAY)}a(Mm,"validateWrite");function I_(){}a(I_,"noop");Ry.exports={insertRecords:k$,updateRecords:Y$,upsertRecords:K$}});var Fi=g((uue,Q$)=>{Q$.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 Jn=g((lue,by)=>{"use strict";var Oy=z(),Ay=P(),Ko=/^[\x20-\x2E|\x30-\x5F|\x61-\x7E]*$/,zn=require("joi"),ni={schema_format:{pattern:Ko,message:"names cannot include backticks or forward slashes"},schema_length:{minimum:1,maximum:250,tooLong:"cannot exceed 250 characters"}},z$=zn.alternatives(zn.string().min(1).max(ni.schema_length.maximum).pattern(Ko).messages({"string.pattern.base":"{:#label} "+ni.schema_format.message}),zn.number(),zn.array()).required(),J$=zn.alternatives(zn.string().min(1).max(ni.schema_length.maximum).pattern(Ko).messages({"string.pattern.base":"{:#label} "+ni.schema_format.message}),zn.number()),j$=zn.alternatives(zn.string().min(1).max(ni.schema_length.maximum).pattern(Ko).messages({"string.pattern.base":"{:#label} "+ni.schema_format.message}),zn.number()).required();function X$(e,t){return t?typeof t!="string"?`'${e}' must be a string`:t.length?t.length>ni.schema_length.maximum?`'${e}' maximum of 250 characters`:Ko.test(t)?"":`'${e}' has illegal characters`:`'${e}' must be at least one character`:`'${e}' is required`}a(X$,"checkValidTable");function Z$(e,t){return Oy.doesSchemaExist(e)?e:t.message(`Database '${e}' does not exist`)}a(Z$,"validateSchemaExists");function e1(e,t){let r=t.state.ancestors[0].schema;return Oy.doesTableExist(r,e)?e:t.message(`Table '${e}' does not exist`)}a(e1,"validateTableExists");function t1(e,t){return e.toLowerCase()===Ay.SYSTEM_SCHEMA_NAME?t.message(`'subscriptions[${t.state.path[1]}]' invalid database name, '${Ay.SYSTEM_SCHEMA_NAME}' name is reserved`):e}a(t1,"validateSchemaName");by.exports={common_validators:ni,schema_regex:Ko,hdb_schema_table:z$,validateSchemaExists:Z$,validateTableExists:e1,validateSchemaName:t1,checkValidTable:X$,hdb_database:J$,hdb_table:j$}});var Xe=g((due,yy)=>{"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};yy.exports={validateObject:r1,validateObjectAsync:n1,validateBySchema:s1};function r1(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(r1,"validateObject");async function n1(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(n1,"validateObjectAsync");function s1(e,t){let r=t.validate(e,{allowUnknown:!0,abortEarly:!1,errors:{wrap:{label:"'"}}});if(r.error)return new Error(r.error.message)}a(s1,"validateBySchema")});var w_=g((Eue,Ny)=>{var{common_validators:jn}=Jn(),xc=Xe(),Bc="is required",gt={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 Hc(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(Hc,"makeAttributesStrings");function i1(e){return e=Hc(e),gt.table.presence=!1,gt.attribute.presence=!1,gt.hash_attribute.presence=!1,xc.validateObject(e,gt)}a(i1,"schema_object");function o1(e){return e=Hc(e),gt.table.presence={message:Bc},gt.attribute.presence=!1,gt.hash_attribute.presence=!1,xc.validateObject(e,gt)}a(o1,"table_object");function a1(e){return e=Hc(e),gt.table.presence={message:Bc},gt.attribute.presence=!1,xc.validateObject(e,gt)}a(a1,"create_table_object");function c1(e){return e=Hc(e),gt.table.presence={message:Bc},gt.attribute.presence={message:Bc},gt.hash_attribute.presence=!1,xc.validateObject(e,gt)}a(c1,"attribute_object");function u1(e){return e=Hc(e),gt.table.presence={message:Bc},gt.attribute.presence=!1,gt.hash_attribute.presence=!1,xc.validateObject(e,gt)}a(u1,"describe_table");function l1(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(l1,"validateTableResidence");Ny.exports={schema_object:i1,create_table_object:a1,table_object:o1,attribute_object:c1,describe_table:u1,validateTableResidence:l1}});var wy=g((mue,Iy)=>{"use strict";var _1=require("uuid"),Pm=class{static{a(this,"CreateAttributeObject")}constructor(t,r,n,s){this.schema=t,this.table=r,this.attribute=n,this.id=s||_1.v4(),this.schema_table=`${this.schema}.${this.table}`}};Iy.exports=Pm});var C_=g((Sue,Cy)=>{"use strict";var d1=wy(),Um=class extends d1{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}};Cy.exports=Um});var Ly=g((gue,Dy)=>{"use strict";Dy.exports=E1;var f1="inserted";function E1(e,t,r,n){let s={message:`${e} ${t.length} of ${r.records.length} records`,skipped_hashes:n};return e===f1?(s.inserted_hashes=t,s):(s.update_hashes=t,s)}a(E1,"returnObject")});var D_=g((Aue,By)=>{"use strict";var h1=P(),vm=Qe(),m1=Yo(),{getSystemSchemaPath:p1,getSchemaPath:S1}=je(),T1=Fi(),g1=w_(),R1=C_(),A1=Ly(),{handleHDBError:My,hdb_errors:Uy}=ne(),Py=z(),{HTTP_STATUS_CODES:O1}=Uy,Bm=T1.hdb_attribute,vy=[];for(let e=0;e<Bm.attributes.length;e++)vy.push(Bm.attributes[e].attribute);var b1="inserted";By.exports=y1;async function y1(e){let t=g1.attribute_object(e);if(t)throw My(new Error,t.message,Uy.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0);let r=!e.skip_table_check&&Py.checkGlobalSchemaTable(e.schema,e.table);if(r)throw My(new Error,r,O1.NOT_FOUND);e.is_hash_attribute=e.is_hash_attribute=="true",e.dup_sort=Py.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 R1(e.schema,e.table,e.attribute,e.id);try{let i=await vm.openEnvironment(S1(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}`);vm.createDBI(i,e.attribute,e.dup_sort,e.is_hash_attribute);let o=await vm.openEnvironment(p1(),h1.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME),{written_hashes:c,skipped_hashes:u}=await m1.insertRecords(o,Bm.hash_attribute,vy,[s]);return A1(b1,c,{records:[s]},u)}catch(i){throw i}}a(y1,"lmdbCreateAttribute")});var Hm=g((bue,Hy)=>{var{hdb_table:N1,hdb_database:xy}=Jn(),I1=Xe(),xm=require("joi"),w1={undefined:"undefined",null:"null"},C1=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||w1[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"),D1=xm.object({database:xy,schema:xy,table:N1,records:xm.array().items(xm.object().custom(C1)).required()});Hy.exports=function(e){return I1.validateBySchema(e,D1)}});var Gc=g((Iue,qy)=>{"use strict";var Rs=z(),Gy=$(),Nue=Hm(),{getDatabases:L1}=(Ae(),ie(ke)),{ClientError:ki}=ne();qy.exports=M1;function M1(e){if(Rs.isEmpty(e))throw new ki("invalid update parameters defined.");if(Rs.isEmptyOrZeroLength(e.schema))throw new ki("invalid schema specified.");if(Rs.isEmptyOrZeroLength(e.table))throw new ki("invalid table specified.");if(!Array.isArray(e.records))throw new ki("records must be an array");let t=L1()[e.schema]?.[e.table];if(Rs.isEmpty(t))throw new ki(`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&&Rs.isEmptyOrZeroLength(o[r]))throw Gy.error("a valid hash attribute must be provided with update record:",o),new ki("a valid hash attribute must be provided with update record, check log for more info");if(!Rs.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 ki(`Invalid hash value: '${o[r]}' is not a valid hash attribute value, check log for more info`);!Rs.isEmpty(o[r])&&o[r]!==""&&n.has(Rs.autoCast(o[r]))&&(o.skip=!0),n.add(Rs.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(M1,"insertUpdateValidate")});var qc=g((Cue,Fy)=>{"use strict";var P1=P().OPERATIONS_ENUM,Gm=class{static{a(this,"InsertObject")}constructor(t,r,n,s,i=void 0){this.operation=P1.INSERT,this.schema=t,this.table=r,this.hash_attribute=n,this.records=s,this.__origin=i}};Fy.exports=Gm});var Fc=g((Mue,Vy)=>{"use strict";var Lue=qc(),L_=P(),qm=z(),ky=$(),U1=require("uuid"),{handleHDBError:M_,hdb_errors:v1}=ne(),{HDB_ERROR_MSGS:P_,HTTP_STATUS_CODES:U_}=v1;Vy.exports=B1;function B1(e,t,r){for(let s=0;s<t.length;s++)x1(t[s]);let{records:n}=e;for(let s=0;s<n.length;s++){let i=n[s];H1(i,r,e.operation)}}a(B1,"processRows");function x1(e){if(Buffer.byteLength(String(e))>L_.INSERT_MODULE_ENUM.MAX_CHARACTER_SIZE)throw M_(new Error,P_.ATTR_NAME_LENGTH_ERR(e),U_.BAD_REQUEST,void 0,void 0,!0);if(qm.isEmptyOrZeroLength(e)||qm.isEmpty(e.trim()))throw M_(new Error,P_.ATTR_NAME_NULLISH_ERR,U_.BAD_REQUEST,void 0,void 0,!0)}a(x1,"validateAttribute");function H1(e,t,r){if(!e.hasOwnProperty(t)||qm.isEmptyOrZeroLength(e[t])){if(r===L_.OPERATIONS_ENUM.INSERT||r===L_.OPERATIONS_ENUM.UPSERT){e[t]=U1.v4();return}throw ky.error("Update transaction aborted due to record with no hash value:",e),M_(new Error,P_.RECORD_MISSING_HASH_ERR,U_.BAD_REQUEST,void 0,void 0,!0)}if(Buffer.byteLength(String(e[t]))>L_.INSERT_MODULE_ENUM.MAX_CHARACTER_SIZE)throw ky.error(e),M_(new Error,P_.HASH_VAL_LENGTH_ERR,U_.BAD_REQUEST,void 0,void 0,!0)}a(H1,"validateHash")});var Yy=g((Uue,$y)=>{"use strict";var Fm=class{static{a(this,"ITCEventObject")}constructor(t,r){this.type=t,this.message=r}};$y.exports=Fm});var Qy=g((Bue,Wy)=>{"use strict";var km=Qe(),G1=$(),Ky=Ur().LMDB_ERRORS_ENUM;Wy.exports=q1;async function q1(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 km.closeEnvironment(global.lmdb_map[o])}catch(c){if(c.message!==Ky.ENV_REQUIRED)throw c}}break;case"drop_table":let n=`${e.schema}.${e.table}`,s=`txn.${n}`;try{await km.closeEnvironment(global.lmdb_map[n]),await km.closeEnvironment(global.lmdb_map[s])}catch(i){if(i.message!==Ky.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){G1.error(t)}}a(q1,"cleanLMDBMap")});var As=g((Hue,Xy)=>{"use strict";var kc=require("crypto"),F1=Z(),{CONFIG_PARAMS:k1}=P(),Jy="aes-256-cbc",V1=32,$1=16,Vm=64,jy=32,Y1=Vm+jy,zy=new Map;Xy.exports={encrypt:K1,decrypt:W1,createNatsTableStreamName:Q1};function K1(e){let t=kc.randomBytes(V1),r=kc.randomBytes($1),n=kc.createCipheriv(Jy,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(K1,"encrypt");function W1(e){let t=e.substr(0,Vm),r=e.substr(Vm,jy),n=e.substr(Y1,e.length),s=Buffer.from(r,"hex"),i=Buffer.from(n,"hex"),o=kc.createDecipheriv(Jy,Buffer.from(t,"hex"),s),c=o.update(i);return c=Buffer.concat([c,o.final()]),c.toString()}a(W1,"decrypt");function Q1(e,t){let r=F1.get(k1.CLUSTERING_DATABASELEVEL)?e:`${e}.${t}`,n=zy.get(r);return n||(n=kc.createHash("md5").update(r).digest("hex"),zy.set(r,n)),n}a(Q1,"createNatsTableStreamName")});var Os=g((Fue,eN)=>{"use strict";var que=Gr(),v_=$(),Zy=w_(),z1=As(),B_=z(),{handleHDBError:x_,hdb_errors:J1}=ne(),{HDB_ERROR_MSGS:H_,HTTP_STATUS_CODES:$m}=J1,j1=Z();j1.initSync();var{getDatabases:Ym}=(Ae(),ie(ke));eN.exports={describeAll:X1,describeTable:G_,describeSchema:Z1};async function X1(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=Ym(),i={},o={},c=[],u=e?.exact_count;for(let l in s){i[l]=!0,!t&&!n&&(o[l]=e.hdb_user.role.permission[l].describe);let d=s[l];for(let E in d)try{let f;if(t||n)f=await G_({schema:l,table:E,exact_count:u});else if(r&&r[l].describe&&r[l].tables[E].describe){let h=r[l].tables[E].attribute_permissions;f=await G_({schema:l,table:E,exact_count:u},h)}f&&c.push(f)}catch(f){v_.error(f)}}let _={};for(let l in c)t||n?(_[c[l].schema]==null&&(_[c[l].schema]={}),_[c[l].schema][c[l].name]=c[l],i[c[l].schema]&&delete i[c[l].schema]):o[c[l].schema]&&(_[c[l].schema]==null&&(_[c[l].schema]={}),_[c[l].schema][c[l].name]=c[l],i[c[l].schema]&&delete i[c[l].schema]);for(let l in i)t||n?_[l]={}:o[l]&&(_[l]={});return _}catch(t){return v_.error("Got an error in describeAll"),v_.error(t),x_(new Error,H_.DESCRIBE_ALL_ERR)}}a(X1,"describeAll");async function G_(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=Zy.describe_table(e);if(i)throw i;let c=Ym()[r];if(!c)throw x_(new Error,H_.SCHEMA_NOT_FOUND(e.schema),$m.NOT_FOUND);let u=c[n];if(!u)throw x_(new Error,H_.TABLE_NOT_FOUND(e.schema,e.table),$m.NOT_FOUND);function _(E){l.push(Object.assign({},{attribute:E.attribute,type:E.type,elements:E.elements?.type,indexed:E.indexed,is_primary_key:E.isPrimaryKey,assigned_created_time:E.assignCreatedTime,assigned_updated_time:E.assignUpdatedTime,nullable:E.nullable,properties:E.properties?E.properties.map(f=>({type:f.type,name:f.name})):void 0}))}a(_,"pushAtt");let l=[];if(s){let E={};s.forEach(f=>{f.describe&&(E[f.attribute_name]=!0)}),u.attributes.forEach(f=>{E[f.name]&&_(f)})}else u.attributes?.forEach(E=>_(E));let d={schema:r,name:u.tableName,hash_attribute:u.attributes.find(E=>E.isPrimaryKey||E.is_hash_attribute)?.name,audit:u.audit,schema_defined:u.schemaDefined,attributes:l};d.clustering_stream_name=z1.createNatsTableStreamName(d.schema,d.name);try{let E=u.getRecordCount({exactCount:e.exact_count==="true"});d.record_count=E.recordCount,d.estimated_record_range=E.estimatedRange;let f=u.auditStore;if(f)for(let h of f.getKeys({reverse:!0,limit:1}))d.last_updated_record=h[0];if(!d.last_updated_record&&u.indices.__updatedtime__)for(let h of u.indices.__updatedtime__.getKeys({reverse:!0,limit:1}))d.last_updated_record=h}catch(E){v_.warn(`unable to stat table dbi due to ${E}`)}return d}a(G_,"descTable");async function Z1(e){B_.transformReq(e);let t=Zy.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=Ym()[n];if(!i)throw x_(new Error,H_.SCHEMA_NOT_FOUND(e.schema),$m.NOT_FOUND);let o={};for(let c in i){let u;if(r&&r.tables[c]&&(u=r.tables[c]),B_.isEmpty(u)||u.describe){let _=await G_({schema:e.schema,table:c,exact_count:e.exact_count},u?u.attribute_permissions:null);_&&(o[_.name]=_)}}return o}a(Z1,"describeSchema")});var bs=g((Yue,iN)=>{var eY=Fi(),{callbackify:rN,promisify:tY}=require("util"),{getDatabases:nN}=(Ae(),ie(ke));iN.exports={setSchemaDataToGlobal:tN,getTableSchema:rY,getSystemSchema:nY,setSchemaDataToGlobalAsync:tY(tN)};var sN=Os(),Vue=rN(sN.describeAll),$ue=rN(sN.describeTable);function tN(e){global.hdb_schema=nN(),e&&e()}a(tN,"setSchemaDataToGlobal");function rY(e,t,r){let n=nN()[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(rY,"getTableSchema");function nY(){return eY}a(nY,"getSystemSchema")});var qr=g((Wue,uN)=>{"use strict";var F_=Hm(),Yt=z(),sY=require("util"),k_=Cn(),iY=bs(),oN=$(),{handleHDBError:Vi,hdb_errors:oY}=ne(),{HTTP_STATUS_CODES:$i}=oY,aY=sY.promisify(iY.getTableSchema),cY="updated",aN="inserted",cN="upserted";uN.exports={insert:lY,update:_Y,upsert:dY,validation:uY,flush:fY};async function uY(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 aY(e.schema,e.table),r=F_(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 oN.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 oN.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 u in c)i[u]=1}),i[n]=1,{schema_table:t,hashes:Array.from(s),attributes:Object.keys(i)}}a(uY,"validation");async function lY(e){if(e.operation!=="insert")throw new Error("invalid operation, must be insert");let t=F_(e);if(t)throw Vi(new Error,t.message,$i.BAD_REQUEST);Yt.transformReq(e);let r=Yt.checkSchemaTableExist(e.schema,e.table);if(r)throw Vi(new Error,r,$i.BAD_REQUEST);let n=await k_.createRecords(e);return q_(aN,n.written_hashes,e,n.skipped_hashes,n.new_attributes,n.txn_time)}a(lY,"insertData");async function _Y(e){if(e.operation!=="update")throw new Error("invalid operation, must be update");let t=F_(e);if(t)throw Vi(new Error,t.message,$i.BAD_REQUEST);Yt.transformReq(e);let r=Yt.checkSchemaTableExist(e.schema,e.table);if(r)throw Vi(new Error,r,$i.BAD_REQUEST);let n=await k_.updateRecords(e);return Yt.isEmpty(n.existing_rows)?q_(cY,n.written_hashes,e,n.skipped_hashes,n.new_attributes,n.txn_time):q_(n.update_action,[],e,n.hashes,void 0,n.txn_time)}a(_Y,"updateData");async function dY(e){if(e.operation!=="upsert")throw Vi(new Error,"invalid operation, must be upsert",$i.INTERNAL_SERVER_ERROR);let t=F_(e);if(t)throw Vi(new Error,t.message,$i.BAD_REQUEST);Yt.transformReq(e);let r=Yt.checkSchemaTableExist(e.schema,e.table);if(r)throw Vi(new Error,r,$i.BAD_REQUEST);let n=await k_.upsertRecords(e);return q_(cN,n.written_hashes,e,[],n.new_attributes,n.txn_time)}a(dY,"upsertData");function q_(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===aN?(o.inserted_hashes=t,o.skipped_hashes=n,o):e===cN?(o.upserted_hashes=t,o):(o.update_hashes=t,o.skipped_hashes=n,o)}a(q_,"returnObject");function fY(e){return Yt.transformReq(e),k_.flush(e.schema,e.table)}a(fY,"flush")});var Wm=g((zue,dN)=>{var EY=Xe(),Km=require("joi"),{hdb_table:hY,hdb_database:lN}=Jn(),_N={schema:lN,database:lN,table:hY},mY={date:Km.date().iso().required()},pY={timestamp:Km.date().timestamp().required().messages({"date.format":"'timestamp' is invalid"})};dN.exports=function(e,t){let r=t==="timestamp"?{..._N,...pY}:{..._N,...mY},n=Km.object(r);return EY.validateBySchema(e,n)}});var hN=g((Jue,EN)=>{var SY=Xe(),Qm=require("joi"),{hdb_table:TY,hdb_database:fN}=Jn(),gY=Qm.object({schema:fN,database:fN,table:TY,hash_values:Qm.array().required(),ids:Qm.array()});EN.exports=function(e){return SY.validateBySchema(e,gY)}});var pN=g((jue,mN)=>{"use strict";var zm=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}},Jm=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}},jm=class{static{a(this,"DeleteResponseObject")}constructor(){this.message=void 0,this.deleted_hashes=[],this.skipped_hashes=[]}};mN.exports={InsertObject:zm,NoSQLSeachObject:Jm,DeleteResponseObject:jm}});var oi=g((Zue,AN)=>{"use strict";var TN=Wm(),RY=hN(),Yi=z(),SN=require("moment"),gN=$(),{promisify:AY,callbackify:OY}=require("util"),Ki=P(),bY=bs(),Xm=AY(bY.getTableSchema),Zm=Cn(),{DeleteResponseObject:yY}=pN(),{handleHDBError:si,hdb_errors:NY}=ne(),{HDB_ERROR_MSGS:V_,HTTP_STATUS_CODES:ii}=NY,IY="records successfully deleted",wY=OY(RN);AN.exports={delete:wY,deleteRecord:RN,deleteFilesBefore:CY,deleteAuditLogsBefore:DY};async function CY(e){let t=TN(e,"date");if(t)throw si(t,t.message,ii.BAD_REQUEST,void 0,void 0,!0);if(Yi.transformReq(e),!SN(e.date,SN.ISO_8601).isValid())throw si(new Error,V_.INVALID_DATE,ii.BAD_REQUEST,Ki.LOG_LEVELS.ERROR,V_.INVALID_DATE,!0);let n=Yi.checkSchemaTableExist(e.schema,e.table);if(n)throw si(new Error,n,ii.NOT_FOUND,Ki.LOG_LEVELS.ERROR,n,!0);let s=await Zm.deleteRecordsBefore(e);if(await Xm(e.schema,e.table),gN.info(`Finished deleting files before ${e.date}`),s&&s.message)return s.message}a(CY,"deleteFilesBefore");async function DY(e){let t=TN(e,"timestamp");if(t)throw si(t,t.message,ii.BAD_REQUEST,void 0,void 0,!0);if(Yi.transformReq(e),isNaN(e.timestamp))throw si(new Error,V_.INVALID_VALUE("Timestamp"),ii.BAD_REQUEST,Ki.LOG_LEVELS.ERROR,V_.INVALID_VALUE("Timestamp"),!0);let r=Yi.checkSchemaTableExist(e.schema,e.table);if(r)throw si(new Error,r,ii.NOT_FOUND,Ki.LOG_LEVELS.ERROR,r,!0);let n=await Zm.deleteAuditLogsBefore(e);return await Xm(e.schema,e.table),gN.info(`Finished deleting audit logs before ${e.timestamp}`),n}a(DY,"deleteAuditLogsBefore");async function RN(e){e.ids&&(e.hash_values=e.ids);let t=RY(e);if(t)throw si(t,t.message,ii.BAD_REQUEST,void 0,void 0,!0);Yi.transformReq(e);let r=Yi.checkSchemaTableExist(e.schema,e.table);if(r)throw si(new Error,r,ii.NOT_FOUND,Ki.LOG_LEVELS.ERROR,r,!0);try{await Xm(e.schema,e.table);let n=await Zm.deleteRecords(e);return Yi.isEmptyOrZeroLength(n.message)&&(n.message=`${n.deleted_hashes.length} of ${e.hash_values.length} ${IY}`),n}catch(n){if(n.message===Ki.SEARCH_NOT_FOUND_MESSAGE){let s=new yY;return s.message=Ki.SEARCH_NOT_FOUND_MESSAGE,s.skipped_hashes=e.hash_values.length,s.deleted_hashes=0,s}throw n}}a(RN,"deleteRecord")});var $_=g((tle,yN)=>{var LY=require("crypto"),ON=9;function MY(e){let t=UY(ON),r=bN(e+t);return t+r}a(MY,"createHash");function PY(e,t){let r=e?.substr(0,ON),n=r+bN(t+r);return e===n}a(PY,"validateHash");function UY(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(UY,"generateSalt");function bN(e){return LY.createHash("md5").update(e).digest("hex")}a(bN,"md5");yN.exports={hash:MY,validate:PY}});var IN=g((nle,NN)=>{var ep=Xe(),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 vY(e){return Zt.password.presence=!0,Zt.username.presence=!0,Zt.role.presence=!0,Zt.active.presence=!0,ep.validateObject(e,Zt)}a(vY,"addUserValidation");function BY(e){return Zt.password.presence=!1,Zt.username.presence=!0,Zt.role.presence=!1,Zt.active.presence=!1,ep.validateObject(e,Zt)}a(BY,"alterUserValidation");function xY(e){return Zt.password.presence=!1,Zt.username.presence=!0,Zt.role.presence=!1,Zt.active.presence=!1,ep.validateObject(e,Zt)}a(xY,"dropUserValidation");NN.exports={addUserValidation:vY,alterUserValidation:BY,dropUserValidation:xY}});var Ve=g((ole,CN)=>{"use strict";var{platform:ile}=require("os"),HY="nats-server.zip",tp="nats-server",GY=process.platform==="win32"?`${tp}.exe`:tp,qY=/^[^\s.,*>]+$/,wN="__request__",FY=a(e=>`${e}.${wN}`,"REQUEST_SUBJECT"),kY={NATS_MSG_ID:"Nats-Msg-Id",ORIGIN:"origin",TRANSACTED_NODES:"transacted_nodes"},VY={HUB_SERVER:"hub.json",LEAF_SERVER:"leaf.json"},$Y={HUB:"hub.pid",LEAF:"leaf.pid"},YY={HUB:"-hub",LEAF:"-leaf",ADMIN:"-admin"},KY={SUCCESS:"success",ERROR:"error"},WY={OPEN:"open",CLOSED:"closed",NO_RESPONDERS:"NoResponders",TIMEOUT:"Timeout"},QY={TXN:"txn",MSGID:"msgid"},Wo={ERR:"error",WRN:"warn",INF:"info",DBG:"debug",TRC:"trace"},zY={[Wo.ERR]:1,[Wo.WRN]:2,[Wo.INF]:3,[Wo.DBG]:4,[Wo.TRC]:5},JY={debug:"-D",trace:"-DVV"};CN.exports={NATS_SERVER_ZIP:HY,NATS_SERVER_NAME:tp,NATS_BINARY_NAME:GY,PID_FILES:$Y,NATS_CONFIG_FILES:VY,SERVER_SUFFIX:YY,NATS_TERM_CONSTRAINTS_RX:qY,REQUEST_SUFFIX:wN,UPDATE_REMOTE_RESPONSE_STATUSES:KY,CLUSTER_STATUS_STATUSES:WY,REQUEST_SUBJECT:FY,SUBJECT_PREFIXES:QY,MSG_HEADERS:kY,LOG_LEVELS:Wo,LOG_LEVEL_FLAGS:JY,LOG_LEVEL_HIERARCHY:zY}});var LN=g((cle,DN)=>{"use strict";var jY={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
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
|
-
`)},QY="certificate.pem",zY="privateKey.pem",JY="ca.pem";CN.exports={CERTIFICATE_VALUES:WY,CERTIFICATE_PEM_NAME:QY,PRIVATEKEY_PEM_NAME:zY,CA_PEM_NAME:JY}});var rp=g((ole,BN)=>{"use strict";var UN=require("fs-extra"),oe=require("joi"),jY=require("os"),{boolean:ye,string:Xt,number:Ze,array:k_}=oe.types(),{totalmem:LN}=require("os"),Wi=require("path"),XY=$(),V_=J(),ile=DN(),MN=P(),ZY=je(),PN="log",eK="components",tK="Invalid logging.rotation.maxSize unit. Available units are G, M or K",rK="Invalid logging.rotation.interval unit. Available units are D, H or M (minutes)",nK="Invalid logging.rotation.maxSize value. Value should be a number followed by unit e.g. '10M'",sK="Invalid logging.rotation.interval value. Value should be a number followed by unit e.g. '10D'",iK="rootPath config parameter is undefined",oK="clustering.enabled config parameter is undefined",Qi=Ze.min(0).required(),$_=k_.items({host:Xt.required(),port:Qi}).empty(null),jn,vN=!1;BN.exports={configValidator:aK,routesValidator:fK,route_constraints:$_};function aK(e,t=!1){if(vN=t,jn=e.rootPath,V_.isEmpty(jn))throw iK;let r=ye.required(),n=Ze.min(0).max(1e3).empty(null).default(dK),s=Xt.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path").empty(null).default(Fc),i=Xt.optional().empty(null),o=Xt.pattern(/^[^\s.,*>]+$/).messages({"string.pattern.base":"{:#label} invalid, must not contain ., * or >"}).empty(null).required(),c=oe.string().empty(null).default(Fc),u=oe.custom(uK).empty(null).default(Fc),_=e.clustering?.enabled;if(V_.isEmpty(_))throw oK;let l=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:Qi,routes:$_}).required()}).required(),leafNodes:oe.object({network:oe.object({port:Qi}).required()}).required(),network:oe.object({port:Qi}).required()}).required(),leafServer:oe.object({network:oe.object({port:Qi,routes:$_}).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:ye.optional(),databaseLevel:ye.optional(),tls:oe.object({certificate:i,certificateAuthority:i,privateKey:i,insecure:ye.required(),verify:ye.optional()}),user:Xt.optional().empty(null)}).required():d=oe.object({enabled:r,tls:oe.object({certificate:i,certificateAuthority:i,privateKey:i,insecure:ye.required()})}).required(),oe.object({authentication:oe.object({authorizeLocal:ye,cacheTTL:Ze.required(),enableSessions:ye}),analytics:oe.object({aggregatePeriod:Ze}),componentsRoot:s.optional(),clustering:d,localStudio:oe.object({enabled:r}).required(),logging:oe.object({auditAuthEvents:oe.object({logFailed:ye,logSuccessful:ye}),file:ye.required(),level:oe.valid("notify","fatal","error","warn","info","debug","trace"),rotation:oe.object({enabled:ye.optional(),compress:ye.optional(),interval:Xt.custom(_K).optional().empty(null),maxSize:Xt.custom(lK).optional().empty(null),path:Xt.optional().empty(null).default(Fc)}).required(),root:s,stdStreams:ye.required(),auditLog:ye.required()}).required(),operationsApi:oe.object({network:oe.object({cors:ye.optional(),corsAccessList:k_.optional(),headersTimeout:Ze.min(1).optional(),keepAliveTimeout:Ze.min(1).optional(),port:Ze.optional().empty(null),domainSocket:oe.optional().empty("hdb/operations-server").default(Fc),securePort:Ze.optional().empty(null),timeout:Ze.min(1).optional()}).optional(),tls:oe.alternatives([oe.array().items(l),l])}).required(),rootPath:Xt.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path").required(),mqtt:oe.object({network:oe.object({port:Qi,securePort:Qi,mtls:oe.alternatives([ye.optional(),oe.object({user:Xt.optional(),certificateAuthority:i,required:ye.optional()})])}).required(),webSocket:ye.optional(),requireAuthentication:ye.optional()}),http:oe.object({compressionThreshold:Ze.optional(),cors:ye.optional(),corsAccessList:k_.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([ye.optional(),oe.object({user:Xt.optional(),certificateAuthority:i,required:ye.optional()})]),threadRange:oe.alternatives([k_.optional(),Xt.optional()])}).required(),threads:oe.alternatives(n.optional(),oe.object({count:n.optional(),debug:oe.alternatives(ye.optional(),oe.object({startingPort:Ze.min(1).optional(),host:Xt.optional(),waitForDebugger:ye.optional()})),maxHeapMemory:Ze.min(0).optional()})),storage:oe.object({writeAsync:ye.required(),overlappingSync:ye.optional(),caching:ye.optional(),compression:oe.alternatives([ye.optional(),oe.object({dictionary:Xt.optional(),threshold:Ze.optional()})]),compactOnStart:ye.optional(),compactOnStartKeepBackup:ye.optional(),noReadAhead:ye.optional(),path:u,prefetchWrites:ye.optional(),maxFreeSpaceToLoad:Ze.optional(),maxFreeSpaceToRetain:Ze.optional()}).required(),ignoreScripts:ye.optional(),tls:oe.alternatives([oe.array().items(l),l])}).validate(e,{allowUnknown:!0,abortEarly:!1,errors:{wrap:{label:"'"}}})}a(aK,"configValidator");function cK(e){return vN||UN.existsSync(e)?null:`Specified path ${e} does not exist.`}a(cK,"doesPathExist");function uK(e,t){oe.assert(e,Xt.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path"));let r=cK(e);if(r)return t.message(r)}a(uK,"validatePath");function lK(e,t){let r=e.slice(-1);if(r!=="G"&&r!=="M"&&r!=="K")return t.message(tK);let n=e.slice(0,-1);return isNaN(parseInt(n))?t.message(nK):e}a(lK,"validateRotationMaxSize");function _K(e,t){let r=e.slice(-1);if(r!=="D"&&r!=="H"&&r!=="M")return t.message(rK);let n=e.slice(0,-1);return isNaN(parseInt(n))?t.message(sK):e}a(_K,"validateRotationInterval");function dK(e,t){let r=t.state.path.join("."),n=jY.cpus().length,s=n-1;s<=2&&(s=2);let i=process.constrainedMemory?.()||LN();return i=Math.round(Math.min(i,LN())/1e6),s=Math.max(Math.min(s,Math.round((i-750)/300)),1),XY.info(`Detected ${n} cores and ${i}MB on this machine, defaulting ${r} to ${s}`),s}a(dK,"setDefaultThreads");function Fc(e,t){let r=t.state.path.join(".");if(!V_.isEmpty(t.original)&&r!=="operationsApi.network.domainSocket")return t.original;if(V_.isEmpty(jn))throw new Error(`Error setting default root for: ${r}. HDB root is not defined`);switch(r){case"componentsRoot":return Wi.join(jn,eK);case"logging.root":return Wi.join(jn,PN);case"clustering.leafServer.streams.path":return Wi.join(jn,"clustering","leaf");case"storage.path":let n=Wi.join(jn,MN.LEGACY_DATABASES_DIR_NAME);return UN.existsSync(n)?n:Wi.join(jn,MN.DATABASES_DIR_NAME);case"logging.rotation.path":return Wi.join(jn,PN);case"operationsApi.network.domainSocket":return r==null?null:Wi.join(jn,"operations-server");default:throw new Error(`Error setting default root for config parameter: ${r}. Unrecognized config parameter`)}}a(Fc,"setDefaultRoot");function fK(e){let t=oe.object({routes:$_});return ZY.validateBySchema({routes:e},t)}a(fK,"routesValidator")});var fr=g((ule,YN)=>{"use strict";var kr=P(),vt=J(),Nt=$(),{configValidator:EK,routesValidator:HN}=rp(),dr=require("fs-extra"),hK=require("yaml"),Dn=require("path"),mK=require("is-number"),GN=require("properties-reader"),pK=require("lodash"),{handleHDBError:SK}=ne(),{HTTP_STATUS_CODES:TK,HDB_ERROR_MSGS:Y_}=Ur(),cle=require("minimist"),{server:gK}=(ur(),ie(Hi)),{DATABASES_PARAM_CONFIG:kc,CONFIG_PARAMS:Fr,CONFIG_PARAM_MAP:Ln}=kr,RK="Unable to get config value because config is uninitialized",AK="Config successfully initialized",OK="Error backing up config file",bK="Empty parameter sent to getConfigValue",qN=Dn.join(kr.PACKAGE_ROOT,"config","yaml",kr.HDB_DEFAULT_CONFIG_FILE),yK="Configuration successfully set. You must restart HarperDB for new config settings to take effect.",xN={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,W_;YN.exports={createConfigFile:NK,getDefaultConfig:IK,getConfigValue:kN,initConfig:sp,flattenConfig:Qo,updateConfigValue:VN,updateConfigObject:CK,getConfiguration:MK,setConfiguration:PK,readConfigFile:op,getClusteringRoutes:UK,initOldConfig:$N,getConfigFromFile:vK,getConfigFilePath:zi,addConfig:BK,deleteConfigFromFile:HK,getConfigObj:xK};function NK(e,t=!1){let r=ai(qN);K_=Qo(r.toJSON());let n;for(let c in e){let u=Ln[c.toLowerCase()];if(u===Fr.DATABASES){Array.isArray(e[c])?n=e[c]:n=Object.keys(e[c]).map(_=>({[_]:e[c][_]}));continue}if(!u&&(c.endsWith("_package")||c.endsWith("_port"))&&(u=c),u!==void 0){let _=u.split("_"),l=np(u,e[c]);u==="rootPath"&&l?.endsWith("/")&&(l=l.slice(0,-1));try{r.setIn([..._],l)}catch(d){Nt.error(d)}}}n&&FN(r,n),ip(r,t);let s=r.toJSON();It=Qo(s);let i=r.getIn(["rootPath"]),o=Dn.join(i,kr.HDB_CONFIG_FILE);dr.createFileSync(o),dr.writeFileSync(o,String(r)),Nt.trace(`Config file written to ${o}`)}a(NK,"createConfigFile");function FN(e,t){let r;try{try{r=JSON.parse(t)}catch(n){if(!vt.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],u=[Fr.DATABASES,s,kc.TABLES,i,o];e.hasIn(u)?e.setIn(u,c):e.addIn(u,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(FN,"setSchemasConfig");function IK(e){if(K_===void 0){let r=ai(qN);K_=Qo(r.toJSON())}let t=Ln[e.toLowerCase()];if(t!==void 0)return K_[t.toLowerCase()]}a(IK,"getDefaultConfig");function kN(e){if(e==null){Nt.error(bK);return}if(It===void 0){Nt.trace(RK);return}let t=Ln[e.toLowerCase()];if(t!==void 0)return It[t.toLowerCase()]}a(kN,"getConfigValue");function zi(e=vt.getPropsFilePath()){let t=vt.getEnvCliRootPath();return t?Dn.join(t,kr.HDB_CONFIG_FILE):GN(e).get(kr.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY)}a(zi,"getConfigFilePath");function sp(e=!1){if(It===void 0||e){let t;if(!vt.noBootFile()){t=vt.getPropsFilePath();try{dr.accessSync(t,dr.constants.F_OK|dr.constants.R_OK)}catch(i){throw Nt.error(i),new Error(`HarperDB properties file at path ${t} does not exist`)}}let r=zi(t),n;if(r.includes("config/settings.js"))try{$N(r);return}catch(i){if(i.code!==kr.NODE_ERROR_CODES.ENOENT)throw i}try{n=ai(r)}catch(i){if(i.code===kr.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}`)}wK(n,r),ip(n);let s=n.toJSON();if(gK.config=s,It=Qo(s),It.logging_rotation_rotate)for(let i in xN)It[i]&&Nt.error(`Config ${xN[i]} has been deprecated. Please check https://docs.harperdb.io/docs/ for further details.`);Nt.trace(AK)}}a(sp,"initConfig");function wK(e,t){let r=e.getIn(["rootPath"]),n=!1;e.hasIn(["storage","path"])||(e.setIn(["storage","path"],Dn.join(r,"database")),n=!0),e.hasIn(["clustering","leafServer","streams","path"])||(e.setIn(["clustering","leafServer","streams","path"],Dn.join(r,"clustering","leaf")),n=!0),e.hasIn(["logging","rotation","path"])||(e.setIn(["logging","rotation","path"],Dn.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"),dr.writeFileSync(t,String(e)))}a(wK,"checkForUpdatedConfig");function ip(e,t=!1){let r=e.toJSON();r.componentsRoot=r.componentsRoot??r?.customFunctions?.root,r?.http?.threads&&(r.threads=r?.http?.threads);let n=EK(r,t);if(n.error)throw Y_.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(ip,"validateConfig");function CK(e,t){It===void 0&&(It={});let r=Ln[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(CK,"updateConfigObject");function VN(e,t,r=void 0,n=!1,s=!1,i=!1){It===void 0&&sp();let o=kN(Ln.hdb_root),c=Dn.join(o,kr.HDB_CONFIG_FILE),u=ai(c),_;if(r===void 0&&e.toLowerCase()===Fr.DATABASES)_=t;else if(r===void 0){let E;if(i)E=e;else if(E=Ln[e.toLowerCase()],E===void 0)throw new Error(`Unable to update config, unrecognized config parameter: ${e}`);let f=E.split("_"),h=np(E,t);u.setIn([...f],h)}else for(let E in r){let f=Ln[E.toLowerCase()];if(f===Fr.HTTP_SECUREPORT&&r[E]===It[Fr.HTTP_PORT]?.toString()&&u.setIn(["http","port"],null),f===Fr.OPERATIONSAPI_NETWORK_SECUREPORT&&r[E]===It[Fr.OPERATIONSAPI_NETWORK_PORT.toLowerCase()]?.toString()&&u.setIn(["operationsApi","network","port"],null),f===Fr.DATABASES){_=r[E];continue}if(f?.startsWith("threads_")){let h=u.getIn(["threads"]);h>=0&&(u.deleteIn(["threads"]),u.setIn(["threads","count"],h))}if(!f&&(E.endsWith("_package")||E.endsWith("_port"))&&(f=E),f!==void 0){let h=f.split("_"),p=kr.LEGACY_CONFIG_PARAMS[E.toUpperCase()];p&&p.startsWith("customFunctions")&&u.hasIn(p.split("_"))&&(f=p,h=p.split("_"));let S=np(f,r[E]);f==="rootPath"&&S?.endsWith("/")&&(S=S.slice(0,-1));try{h.length>1&&typeof u.getIn(h.slice(0,-1))=="boolean"&&u.deleteIn(h.slice(0,-1)),u.setIn([...h],S)}catch(T){Nt.error(T)}}}_&&FN(u,_),ip(u);let l=u.getIn(["rootPath"]),d=Dn.join(l,kr.HDB_CONFIG_FILE);n===!0&&DK(c,l),dr.writeFileSync(d,String(u)),s&&(It=Qo(u.toJSON())),Nt.trace(`Config parameter: ${e} updated with value: ${t}`)}a(VN,"updateConfigValue");function DK(e,t){try{let r=Dn.join(t,"backup",`${kr.HDB_CONFIG_FILE}.bak`);dr.copySync(e,r),Nt.trace(`Config file: ${e} backed up to: ${r}`)}catch(r){Nt.error(OK),Nt.error(r)}}a(DK,"backupConfigFile");var LK=["databases"];function Qo(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)),W_=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])&&!LK.includes(i)){let o=r(n[i]);for(let c in o){if(!o.hasOwnProperty(c))continue;c!=="package"&&(i=i.toLowerCase());let u=i+"_"+c;!Fr[u.toUpperCase()]&&Ln[u]&&(s[Ln[u].toLowerCase()]=o[c]),s[u]=o[c]}}n[i]!==void 0&&(s[i.toLowerCase()]=n[i])}return s}a(r,"squashObj")}a(Qo,"flattenConfig");function np(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(mK(t))return parseFloat(t);if(t===!0||t===!1||Array.isArray(t)||vt.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 vt.autoCast(t)}a(np,"castConfigValue");function MK(){let e=vt.getPropsFilePath(),t=zi(e);return ai(t).toJSON()}a(MK,"getConfiguration");async function PK(e){let{operation:t,hdb_user:r,hdb_auth_header:n,...s}=e;try{return VN(void 0,void 0,s,!0),yK}catch(i){throw typeof i=="string"||i instanceof String?SK(i,i,TK.BAD_REQUEST,void 0,void 0,!0):i}}a(PK,"setConfiguration");function op(){let e=vt.getPropsFilePath();try{dr.accessSync(e,dr.constants.F_OK|dr.constants.R_OK)}catch(n){if(!vt.noBootFile())throw Nt.error(n),new Error(`HarperDB properties file at path ${e} does not exist`)}let t=zi(e);return ai(t).toJSON()}a(op,"readConfigFile");function ai(e){return hK.parseDocument(dr.readFileSync(e,"utf8"),{simpleKeys:!0})}a(ai,"parseYamlDoc");function UK(){let e=op(),t=e?.clustering?.hubServer?.cluster?.network?.routes;t=vt.isEmptyOrZeroLength(t)?[]:t;let r=HN(t);if(r)throw Y_.CONFIG_VALIDATION(r.message);let n=e?.clustering?.leafServer?.network?.routes;n=vt.isEmptyOrZeroLength(n)?[]:n;let s=HN(n);if(s)throw Y_.CONFIG_VALIDATION(s.message);if(!vt.isEmptyOrZeroLength(n)&&!vt.isEmptyOrZeroLength(t)){let i=t.filter(o=>n.some(c=>c.host===o.host&&c.port===o.port));if(!vt.isEmptyOrZeroLength(i)){let o=`Duplicate hub and leaf routes found ${JSON.stringify(i)}`;throw Y_.CONFIG_VALIDATION(o)}}return{hub_routes:t,leaf_routes:n}}a(UK,"getClusteringRoutes");function $N(e){let t=GN(e);It={};for(let r in Ln){let n=t.get(r.toUpperCase());if(vt.isEmpty(n)||typeof n=="string"&&n.trim().length===0)continue;let s=Ln[r].toLowerCase();s===Fr.LOGGING_ROOT?It[s]=Dn.dirname(n):It[s]=n}return It}a($N,"initOldConfig");function vK(e){let t=op();return pK.get(t,e.replaceAll("_","."))}a(vK,"getConfigFromFile");async function BK(e,t){let r=ai(zi());r.hasIn([e])?r.setIn([e],t):r.addIn([e],t),await dr.writeFile(zi(),String(r))}a(BK,"addConfig");function HK(e){let t=zi(vt.getPropsFilePath()),r=ai(t);r.deleteIn(e);let n=r.getIn(["rootPath"]),s=Dn.join(n,kr.HDB_CONFIG_FILE);dr.writeFileSync(s,String(r))}a(HK,"deleteConfigFromFile");function xK(){return W_||(sp(),W_)}a(xK,"getConfigObj")});var WN=g((_le,KN)=>{"use strict";var Q_=P(),z_=class{static{a(this,"BaseLicense")}constructor(t=0,r=Q_.RAM_ALLOCATION_ENUM.DEFAULT,n=Q_.LICENSE_VALUES.VERSION_DEFAULT,s){this.exp_date=t,this.ram_allocation=r,this.version=n,this.fingerprint=s}},ap=class extends z_{static{a(this,"ExtendedLicense")}constructor(t=0,r=Q_.RAM_ALLOCATION_ENUM.DEFAULT,n=Q_.LICENSE_VALUES.VERSION_DEFAULT,s,i=!1){super(t,r,n,s),this.enterprise=i}};KN.exports={BaseLicense:z_,ExtendedLicense:ap}});var Ji=g((fle,ZN)=>{"use strict";var Jo=require("fs-extra"),zN=F_(),JN=require("crypto"),GK=require("moment"),qK=require("uuid").v4,Zt=$(),up=require("path"),FK=J(),ci=P(),{totalmem:QN}=require("os"),kK=WN().ExtendedLicense,zo="invalid license key format",VK="061183",$K="mofi25",YK="aes-256-cbc",KK=16,WK=32,jN=Z();jN.initSync();var cp;ZN.exports={validateLicense:XN,generateFingerPrint:zK,licenseSearch:dp,getLicense:XK,checkMemoryLimit:ZK};function lp(){return up.join(jN.getHdbBasePath(),ci.LICENSE_KEY_DIR_NAME,ci.LICENSE_FILE_NAME)}a(lp,"getLicenseDirPath");function QK(){let e=lp();return up.join(e,ci.LICENSE_FILE_NAME)}a(QK,"getLicenseFilePath");function _p(){let e=lp();return up.join(e,ci.REG_KEY_FILE_NAME)}a(_p,"getFingerPrintFilePath");async function zK(){let e=_p();try{return await Jo.readFile(e,"utf8")}catch(t){if(t.code==="ENOENT")return await JK();throw Zt.error(`Error writing fingerprint file to ${e}`),Zt.error(t),new Error("There was an error generating the fingerprint")}}a(zK,"generateFingerPrint");async function JK(){let e=qK(),t=zN.hash(e),r=_p();try{await Jo.mkdirp(lp()),await Jo.writeFile(r,t)}catch(n){if(n.code==="EEXIST")return t;throw Zt.error(`Error writing fingerprint file to ${r}`),Zt.error(n),new Error("There was an error generating the fingerprint")}return t}a(JK,"writeFingerprint");function XN(e,t){let r={valid_license:!1,valid_date:!1,valid_machine:!1,exp_date:null,ram_allocation:ci.RAM_ALLOCATION_ENUM.DEFAULT,version:ci.LICENSE_VALUES.VERSION_DEFAULT};if(!e)return Zt.error("empty license key passed to validate."),r;let n=_p(),s=!1;try{s=Jo.statSync(n)}catch(i){Zt.error(i)}if(s){let i;try{i=Jo.readFileSync(n,"utf8")}catch{Zt.error("error validating this machine in the license"),r.valid_machine=!1;return}let o=e.split($K),c=o[1];c=Buffer.concat([Buffer.from(c)],KK);let u=Buffer.concat([Buffer.from(i)],WK),_=JN.createDecipheriv(YK,u,c);r.valid_date=!0,r.valid_license=!0,r.valid_machine=!0;let l=null;try{l=_.update(o[0],"hex","utf8"),l.trim(),l+=_.final("utf8")}catch{let f=jK(o[0],i);if(f)l=f;else throw r.valid_license=!1,r.valid_machine=!1,console.error(zo),Zt.error(zo),new Error(zo)}let d;if(isNaN(l))try{d=JSON.parse(l),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(zo),Zt.error(zo),new Error(zo)}else r.exp_date=l;r.exp_date<GK().valueOf()&&(r.valid_date=!1),zN.validate(o[1],`${VK}${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||Zt.error("Invalid licence"),r}a(XN,"validateLicense");function jK(e,t){try{let r=JN.createDecipher("aes192",t),n=r.update(e,"hex","utf8");return n.trim(),n+=r.final("utf8"),n}catch{Zt.warn("Check old license failed")}}a(jK,"checkOldLicense");function dp(){let e=new kK,t=[];try{t=Jo.readFileSync(QK(),"utf-8").split(ci.NEW_LINE)}catch(r){r.code==="ENOENT"?Zt.info("no license file found"):Zt.error(`could not search for licenses due to: '${r.message}`)}for(let r=0;r<t.length;++r){let n=t[r];try{if(FK.isEmptyOrZeroLength(n))continue;let s=JSON.parse(n),i=XN(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){Zt.error("There was an error parsing the license string."),Zt.error(s),e.ram_allocation=ci.RAM_ALLOCATION_ENUM.DEFAULT,e.enterprise=!1}}return cp=e,e}a(dp,"licenseSearch");async function XK(){return cp||await dp(),cp}a(XK,"getLicense");function ZK(){let e=dp().ram_allocation,t=process.constrainedMemory?.()||QN();if(t=Math.round(Math.min(t,QN())/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(ZK,"checkMemoryLimit")});var ln=g((Sle,hI)=>{"use strict";var nI="username is required",sI="nothing to update, must supply active, role or password to update",iI="password cannot be an empty string",oI="If role is specified, it cannot be empty.",aI="active must be true or false";hI.exports={addUser:cW,alterUser:uW,dropUser:_W,getSuperUser:hW,userInfo:dW,listUsers:j_,listUsersExternal:fW,setUsersToGlobal:Xo,findAndValidateUser:fI,getClusterUser:mW,USERNAME_REQUIRED:nI,ALTERUSER_NOTHING_TO_UPDATE:sI,EMPTY_PASSWORD:iI,EMPTY_ROLE:oI,ACTIVE_BOOLEAN:aI};var cI=qr(),eW=oi(),hp=F_(),uI=NN(),lI=Gr(),mp=bs(),Vr=J(),_I=require("validate.js"),be=$(),{promisify:tW}=require("util"),pp=Rs(),eI=P(),tI=ke(),rW=fr(),hle=Z(),mle=Ji(),nW=Fi(),{table:ple}=(Oe(),ie(Fe)),{handleHDBError:Xn,hdb_errors:sW}=ne(),{HTTP_STATUS_CODES:Zn,AUTHENTICATION_ERROR_MSGS:fp,HDB_ERROR_MSGS:jo}=sW,{UserEventMsg:Sp}=Mn(),Ep=require("lodash"),{server:Tp}=(ur(),ie(Hi)),iW=$();Tp.getUser=(e,t)=>fI(e,t,t!=null);var dI={username:!0,active:!0,role:!0,password:!0},rI=new Map,J_=lI.searchByValue,oW=lI.searchByHash,aW=tW(eW.delete);async function cW(e){let t=_I.cleanAttributes(e,dI),r=uI.addUserValidation(t);if(r)throw Xn(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 J_(n),s=s&&Array.from(s)}catch(u){throw be.error("There was an error searching for a role in add user"),be.error(u),u}if(!s||s.length<1)throw Xn(new Error,jo.ROLE_NAME_NOT_FOUND(t.role),Zn.NOT_FOUND,void 0,void 0,!0);if(s.length>1)throw Xn(new Error,jo.DUP_ROLES_FOUND(t.role),Zn.CONFLICT,void 0,void 0,!0);s[0].permission.cluster_user===!0&&(t.hash=pp.encrypt(t.password)),t.password=hp.hash(t.password),t.role=s[0].id;let i={operation:"insert",schema:"system",table:"hdb_user",records:[t]},o;try{o=await cI.insert(i)}catch(u){throw be.error("There was an error searching for a user."),be.error(u),u}be.debug(o);try{await Xo()}catch(u){throw be.error("Got an error setting users to global"),be.error(u),u}if(o.skipped_hashes.length===1)throw Xn(new Error,jo.USER_ALREADY_EXISTS(t.username),Zn.CONFLICT,void 0,void 0,!0);let c=Object.assign({},t);return c.role=s[0],mp.signalUserChange(new Sp(process.pid)),`${c.username} successfully added`}a(cW,"addUser");async function uW(e){let t=_I.cleanAttributes(e,dI);if(Vr.isEmptyOrZeroLength(t.username))throw new Error(nI);if(Vr.isEmptyOrZeroLength(t.password)&&Vr.isEmptyOrZeroLength(t.role)&&Vr.isEmptyOrZeroLength(t.active))throw new Error(sI);if(!Vr.isEmpty(t.password)&&Vr.isEmptyOrZeroLength(t.password.trim()))throw new Error(iI);if(!Vr.isEmpty(t.active)&&!Vr.isBoolean(t.active))throw new Error(aI);let r=lW(t.username);if(!Vr.isEmpty(t.password)&&!Vr.isEmptyOrZeroLength(t.password.trim())&&(r&&(t.hash=pp.encrypt(t.password)),t.password=hp.hash(t.password)),t.role==="")throw new Error(oI);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 be.error("Got an error searching for a role."),be.error(c),c}if(!o||o.length===0){let c=jo.ALTER_USER_ROLE_NOT_FOUND(t.role);throw be.error(c),Xn(new Error,c,Zn.NOT_FOUND,void 0,void 0,!0)}if(o.length>1){let c=jo.ALTER_USER_DUP_ROLES(t.role);throw be.error(c),Xn(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 cI.update(n)}catch(i){throw be.error("Error during update."),be.error(i),i}try{await Xo()}catch(i){throw be.error("Got an error setting users to global"),be.error(i),i}return mp.signalUserChange(new Sp(process.pid)),s}a(uW,"alterUser");function lW(e){let t=!1,r=global.hdb_users.get(e);return r&&r.role.permission.cluster_user===!0&&(t=!0),t}a(lW,"isClusterUser");async function _W(e){try{let t=uI.dropUserValidation(e);if(t)throw new Error(t);let r={table:"hdb_user",schema:"system",hash_values:[e.username]};if(Vr.isEmpty(global.hdb_users.get(e.username)))throw Xn(new Error,jo.USER_NOT_EXIST(e.username),Zn.NOT_FOUND,void 0,void 0,!0);let n;try{n=await aW(r)}catch(s){throw be.error("Got an error deleting a user."),be.error(s),s}be.debug(n);try{await Xo()}catch(s){throw be.error("Got an error setting users to global."),be.error(s),s}return mp.signalUserChange(new Sp(process.pid)),`${e.username} successfully deleted`}catch(t){throw t}}a(_W,"dropUser");async function dW(e){let t={};try{if(!e||!e.hdb_user)return"There was no user info in the body";t=Ep.cloneDeep(e.hdb_user);let r={schema:"system",table:"hdb_role",hash_values:[t.role.id],get_attributes:["*"]},n;try{n=await oW(r)}catch(s){throw be.error("Got an error searching for a role."),be.error(s),s}t.role=n[0],delete t.password,delete t.refresh_token,delete t.hash}catch(r){throw be.error(r),r}return t}a(dW,"userInfo");async function fW(){let e;try{e=await j_()}catch(t){throw be.error("Got an error listing users."),be.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(fW,"listUsersExternal");async function j_(){try{let e={schema:"system",table:"hdb_role",search_value:"*",search_attribute:"role",get_attributes:["*"]},t;try{t=await J_(e)}catch(o){throw be.error("Got an error searching for roles."),be.error(o),o}let r={};for(let o of t)r[o.id]=Ep.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 be.error("Got an error searching for users."),be.error(o),o}let i=new Map;for(let o of s)o=Ep.cloneDeep(o),o.role=r[o.role],EW(o.role),i.set(o.username,o);return i}catch(e){throw be.error("got an error listing users"),be.error(e),Vr.errorizeMessage(e)}return null}a(j_,"listUsers");function EW(e){try{if(!e){be.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(nW)){let r={read:!!e.permission.super_user,insert:!1,update:!1,delete:!1,attribute_permissions:[]};e.permission.system.tables[t]=r}}catch(t){be.error("Got an error trying to set system permissions."),be.error(t)}}a(EW,"appendSystemTablesToRole");async function Xo(){try{let e=await j_();global.hdb_users=e}catch(e){throw be.error(e),e}}a(Xo,"setUsersToGlobal");async function fI(e,t,r=!0){global.hdb_users||await Xo();let n=global.hdb_users.get(e);if(!n){if(!r)return{username:e};throw Xn(new Error,fp.GENERIC_AUTH_FAIL,Zn.UNAUTHORIZED,void 0,void 0,!0)}if(n&&!n.active)throw Xn(new Error,fp.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(rI.get(t)===n.password)return s;if(hp.validate(n.password,t))rI.set(t,n.password);else throw Xn(new Error,fp.GENERIC_AUTH_FAIL,Zn.UNAUTHORIZED,void 0,void 0,!0)}return s}a(fI,"findAndValidateUser");async function hW(){global.hdb_users||await Xo();for(let[,e]of global.hdb_users)if(e.role.role==="super_user")return e}a(hW,"getSuperUser");async function mW(){let e=await j_(),t=rW.getConfigFromFile(eI.CONFIG_PARAMS.CLUSTERING_USER),r=e.get(t);if(!Vr.isEmpty(r)&&r?.role?.role===eI.ROLE_TYPES_ENUM.CLUSTER_USER)return r.decrypt_hash=pp.decrypt(r.hash),r.uri_encoded_d_hash=encodeURIComponent(r.decrypt_hash),r.uri_encoded_name=encodeURIComponent(r.username),r.sys_name=r.username+tI.SERVER_SUFFIX.ADMIN,r.sys_name_encoded=r.uri_encoded_name+tI.SERVER_SUFFIX.ADMIN,r}a(mW,"getClusterUser");var EI=[];Tp.invalidateUser=function(e){for(let t of EI)try{t(e)}catch(r){iW.error("Error invalidating user",r)}};Tp.onInvalidatedUser=function(e){EI.push(e)}});var $c=g((Ale,TI)=>{"use strict";var ji=$(),$r=P(),pW=Wy(),gle=Os(),Rle=As(),SW=ln(),{validateEvent:mI}=Mn(),Vc=Cn(),TW=require("process"),{resetDatabases:gW}=(Oe(),ie(Fe)),RW={[$r.ITC_EVENT_TYPES.SCHEMA]:AW,[$r.ITC_EVENT_TYPES.USER]:SI};async function AW(e){let t=mI(e);if(t){ji.error(t);return}ji.trace("ITC schemaHandler received schema event:",e),await pW(e.message),await OW(e.message)}a(AW,"schemaHandler");async function OW(e){try{Vc.resetReadTxn($r.SYSTEM_SCHEMA_NAME,$r.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME),Vc.resetReadTxn($r.SYSTEM_SCHEMA_NAME,$r.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME),Vc.resetReadTxn($r.SYSTEM_SCHEMA_NAME,$r.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME);let t=gW();e.table&&e.database&&await t[e.database][e.table].put(Symbol.for("write-verify"),null)}catch(t){ji.error(t)}}a(OW,"syncSchemaMetadata");var pI=[];async function SI(e){try{try{Vc.resetReadTxn($r.SYSTEM_SCHEMA_NAME,$r.SYSTEM_TABLE_NAMES.USER_TABLE_NAME),Vc.resetReadTxn($r.SYSTEM_SCHEMA_NAME,$r.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME)}catch(r){ji.warn(r)}let t=mI(e);if(t){ji.error(t);return}ji.trace(`ITC userHandler ${$r.HDB_ITC_CLIENT_PREFIX}${TW.pid} received user event:`,e),await SW.setUsersToGlobal();for(let r of pI)r()}catch(t){ji.error(t)}}a(SI,"userHandler");SI.addListener=function(e){pI.push(e)};TI.exports=RW});var Mn=g((wle,RI)=>{"use strict";var ble=$(),gp=J(),bW=P(),{ITC_ERRORS:Yc}=Ur(),{parentPort:yle,threadId:yW,isMainThread:NW,workerData:Nle}=require("worker_threads"),{onMessageFromWorkers:IW,broadcast:Ile,broadcastWithAcknowledgement:wW}=Je();RI.exports={sendItcEvent:CW,validateEvent:gI,SchemaEventMsg:DW,UserEventMsg:LW};var X_;IW(async(e,t)=>{X_=X_||$c(),gI(e),X_[e.type]&&await X_[e.type](e),e.requestId&&t&&t.postMessage({type:"ack",id:e.requestId})});function CW(e){return!NW&&e.message&&(e.message.originator=yW),wW(e)}a(CW,"sendItcEvent");function gI(e){if(typeof e!="object")return Yc.INVALID_ITC_DATA_TYPE;if(!e.hasOwnProperty("type")||gp.isEmpty(e.type))return Yc.MISSING_TYPE;if(!e.hasOwnProperty("message")||gp.isEmpty(e.message))return Yc.MISSING_MSG;if(!e.message.hasOwnProperty("originator")||gp.isEmpty(e.message.originator))return Yc.MISSING_ORIGIN;if(bW.ITC_EVENT_TYPES[e.type.toUpperCase()]===void 0)return Yc.INVALID_EVENT(e.type)}a(gI,"validateEvent");function DW(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(DW,"SchemaEventMsg");function LW(e){this.originator=e}a(LW,"UserEventMsg")});var bs=g((Lle,yI)=>{"use strict";var AI=P(),Dle=J(),Z_=$(),OI=$y(),Zo,{sendItcEvent:bI}=Mn();function MW(e){try{Z_.trace("signalSchemaChange called with message:",e),Zo=Zo||$c();let t=new OI(AI.ITC_EVENT_TYPES.SCHEMA,e);return Zo.schema(t),bI(t)}catch(t){Z_.error(t)}}a(MW,"signalSchemaChange");function PW(e){try{Z_.trace("signalUserChange called with message:",e),Zo=Zo||$c();let t=new OI(AI.ITC_EVENT_TYPES.USER,e);return Zo.user(t),bI(t)}catch(t){Z_.error(t)}}a(PW,"signalUserChange");yI.exports={signalSchemaChange:MW,signalUserChange:PW}});var ed=g((Ple,II)=>{"use strict";var NI=J(),UW=P(),vW=$(),BW=I_(),HW=N_(),xW=bs(),{SchemaEventMsg:GW}=Mn(),qW="already exists in";II.exports=FW;async function FW(e,t,r){if(NI.isEmptyOrZeroLength(r))return r;let n=[];NI.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 kW(e,t.schema,t.name,i)})),s}a(FW,"lmdbCheckForNewAttributes");async function kW(e,t,r,n){let s=new HW(t,r,n,void 0,!0);e&&(s.hdb_auth_header=e);try{await VW(s)}catch(i){if(typeof i=="object"&&i.message!==void 0&&i.message.includes(qW))vW.warn(`attribute ${t}.${r}.${n} already exists`);else throw i}}a(kW,"createNewAttribute");async function VW(e){let t;return t=await BW(e),xW.signalSchemaChange(new GW(process.pid,UW.OPERATIONS_ENUM.CREATE_ATTRIBUTE,e.schema,e.table,e.attribute)),t}a(VW,"createAttribute")});var ea=g((vle,wI)=>{"use strict";var Rp=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}};wI.exports=Rp});var DI=g((Hle,CI)=>{"use strict";var $W=ea(),YW=P().OPERATIONS_ENUM,Ap=class extends $W{static{a(this,"LMDBInsertTransactionObject")}constructor(t,r,n,s,i=void 0){super(YW.INSERT,r,n,s,i),this.records=t}};CI.exports=Ap});var MI=g((Gle,LI)=>{"use strict";var KW=ea(),WW=P().OPERATIONS_ENUM,Op=class extends KW{static{a(this,"LMDBUpdateTransactionObject")}constructor(t,r,n,s,i,o=void 0){super(WW.UPDATE,n,s,i,o),this.records=t,this.original_records=r}};LI.exports=Op});var UI=g((Fle,PI)=>{"use strict";var QW=ea(),zW=P().OPERATIONS_ENUM,bp=class extends QW{static{a(this,"LMDBUpsertTransactionObject")}constructor(t,r,n,s,i,o=void 0){super(zW.UPSERT,n,s,i,o),this.records=t,this.original_records=r}};PI.exports=bp});var BI=g((Vle,vI)=>{"use strict";var JW=ea(),jW=P().OPERATIONS_ENUM,yp=class extends JW{static{a(this,"LMDBDeleteTransactionObject")}constructor(t,r,n,s,i=void 0){super(jW.DELETE,n,s,t,i),this.original_records=r}};vI.exports=yp});var Kc=g((Kle,qI)=>{"use strict";var Yle=require("path"),HI=Ke(),XW=DI(),ZW=MI(),eQ=UI(),tQ=BI(),ta=_t(),xI=J(),{CONFIG_PARAMS:rQ}=P(),GI=Z();GI.initSync();var td=P().OPERATIONS_ENUM,{getTransactionAuditStorePath:nQ}=ze();qI.exports=sQ;async function sQ(e,t){if(GI.get(rQ.LOGGING_AUDITLOG)===!1)return;let r=nQ(e.schema,e.table),n=await HI.openEnvironment(r,e.table,!0),s=iQ(e,t);if(!(s===void 0||s.hash_values.length===0)&&n!==void 0){HI.initializeDBIs(n,ta.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,ta.TRANSACTIONS_DBIS);let i=s.timestamp;return await n.dbis[ta.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP].ifNoExists(i,()=>{n.dbis[ta.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP].put(i,s),xI.isEmpty(s.user_name)||n.dbis[ta.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].put(s.user_name,i);for(let o=0;o<s.hash_values.length;o++)n.dbis[ta.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE].put(s.hash_values[o],i)})}}a(sQ,"writeTransaction");function iQ(e,t){let r=xI.isEmpty(e.hdb_user)?void 0:e.hdb_user.username;if(e.operation===td.INSERT)return new XW(e.records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===td.UPDATE)return new ZW(e.records,t.original_records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===td.UPSERT)return new eQ(e.records,t.original_records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===td.DELETE)return new tQ(t.deleted,t.original_records,r,t.txn_time,e.__origin)}a(iQ,"createTransactionObject")});var Np=g((zle,FI)=>{"use strict";var oQ=Hc(),Qle=xc(),Wc=P(),aQ=Gc(),cQ=Yo().insertRecords,uQ=Ke(),lQ=$(),_Q=ed(),{getSchemaPath:dQ}=ze(),fQ=Kc();FI.exports=EQ;async function EQ(e){try{let{schema_table:t,attributes:r}=oQ(e);aQ(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 _Q(e.hdb_auth_header,t,r),s=dQ(e.schema,e.table),i=await uQ.openEnvironment(s,e.table),o=await cQ(i,t.hash_attribute,r,e.records,e.__origin?.timestamp);try{await fQ(e,o)}catch(c){lQ.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(EQ,"lmdbCreateRecords")});var $I=g((jle,VI)=>{"use strict";var kI=P(),hQ=Np(),mQ=xc(),pQ=require("fs-extra"),{getSchemaPath:SQ}=ze();VI.exports=TQ;async function TQ(e){let t=[{name:e.schema,createddate:Date.now()}],r=new mQ(kI.SYSTEM_SCHEMA_NAME,kI.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,void 0,t);await hQ(r),await pQ.mkdirp(SQ(e.schema))}a(TQ,"lmdbCreateSchema")});var KI=g((Zle,YI)=>{"use strict";var Ip=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}};YI.exports=Ip});var JI=g((s_e,zI)=>{"use strict";var WI=Ke(),wp=vr(),Cp=Ur().LMDB_ERRORS_ENUM,gQ=_t(),QI=$(),t_e=J(),RQ=require("lmdb"),AQ=KI(),OQ=P(),{OVERFLOW_MARKER:r_e,MAX_SEARCH_KEY_LENGTH:n_e}=gQ,bQ=OQ.TIME_STAMP_NAMES_ENUM.UPDATED_TIME;async function yQ(e,t,r,n){if(wp.validateEnv(e),t===void 0)throw new Error(Cp.HASH_ATTRIBUTE_REQUIRED);if(!Array.isArray(r))throw r===void 0?new Error(Cp.IDS_REQUIRED):new Error(Cp.IDS_MUST_BE_ITERABLE);try{let s=WI.listDBIs(e);WI.initializeDBIs(e,t,s);let i=new AQ,o,c=[],u=[];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[bQ]>n){i.skipped.push(o);continue}let p=e.dbis[t].ifVersion(o,RQ.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 A=e.dbis[T],R=h[T];if(R!=null)try{let C=wp.getIndexedValues(R);if(C)for(let x=0,v=C.length;x<v;x++)A.remove(C[x],o)}catch{QI.warn(`cannot delete from attribute: ${T}, ${R}:${o}`)}}});c.push(p),u.push(o),i.original_records.push(h)}catch(h){QI.warn(h),i.skipped.push(o)}let _=[],l=await Promise.all(c);for(let E=0,f=l.length;E<f;E++)l[E]===!0?i.deleted.push(u[E]):(i.skipped.push(u[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=wp.getNextMonotonicTime(),i}catch(s){throw s}}a(yQ,"deleteRecords");zI.exports={deleteRecords:yQ}});var Qc=g((o_e,XI)=>{"use strict";var ra=J(),NQ=JI(),IQ=Ke(),{getSchemaPath:wQ}=ze(),CQ=Kc(),DQ=$();XI.exports=LQ;async function LQ(e,t=!0){let n=global.hdb_schema[e.schema][e.table].hash_attribute;if(ra.isEmpty(n))throw new Error(`could not retrieve hash attribute for schema:${e.schema} and table ${e.table}`);try{if(ra.isEmptyOrZeroLength(e.hash_values)&&!ra.isEmptyOrZeroLength(e.records)){e.hash_values=[];for(let c=0;c<e.records.length;c++){let u=e.records[c][n];ra.isEmpty(u)||e.hash_values.push(u)}}if(ra.isEmptyOrZeroLength(e.hash_values))return jI([],[]);if(!Array.isArray(e.hash_values))throw new Error("hash_values must be an array");if(ra.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=wQ(e.schema,e.table),i=await IQ.openEnvironment(s,e.table),o=await NQ.deleteRecords(i,n,e.hash_values,e.__origin?.timestamp);try{t===!0&&await CQ(e,o)}catch(c){DQ.error(`unable to write transaction due to ${c.message}`)}return jI(o.deleted,o.skipped,o.txn_time)}catch(s){throw s}}a(LQ,"lmdbDeleteRecords");function jI(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(jI,"createDeleteResponse")});var Lp=g((u_e,ZI)=>{"use strict";var MQ=P(),c_e=vr();function Dp(e,t){let r=Object.create(null);if(t.length===1&&MQ.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(Dp,"parseRow");function PQ(e,t,r,n){let s=Dp(r,e);n.push(s)}a(PQ,"searchAll");function UQ(e,t,r,n){let s=Dp(r,e);n[t]=s}a(UQ,"searchAllToMap");function vQ(e,t,r){r[e]===void 0&&(r[e]=[]),r[e].push(t)}a(vQ,"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 BQ(e,t,r,n,s,i){t.toString().endsWith(e)&&Xi(t,r,n,s,i)}a(BQ,"endsWith");function HQ(e,t,r,n,s,i){t.toString().includes(e)&&Xi(t,r,n,s,i)}a(HQ,"contains");function xQ(e,t,r,n,s,i){t>e&&Xi(t,r,n,s,i)}a(xQ,"greaterThanCompare");function GQ(e,t,r,n,s,i){t>=e&&Xi(t,r,n,s,i)}a(GQ,"greaterThanEqualCompare");function qQ(e,t,r,n,s,i){t<e&&Xi(t,r,n,s,i)}a(qQ,"lessThanCompare");function FQ(e,t,r,n,s,i){t<=e&&Xi(t,r,n,s,i)}a(FQ,"lessThanEqualCompare");ZI.exports={parseRow:Dp,searchAll:PQ,searchAllToMap:UQ,iterateDBI:vQ,endsWith:BQ,contains:HQ,greaterThanCompare:xQ,greaterThanEqualCompare:GQ,lessThanCompare:qQ,lessThanEqualCompare:FQ,pushResults:Xi}});var na=g((E_e,ow)=>{"use strict";var ui=Ke(),__e=$(),Yr=vr(),rd=_t(),ft=Ur().LMDB_ERRORS_ENUM,d_e=J(),kQ=P(),nd=Lp(),{parseRow:VQ}=nd,f_e=require("lmdb"),{OVERFLOW_MARKER:ew,MAX_SEARCH_KEY_LENGTH:$Q}=rd;function tw(e,t,r,n=!1,s=void 0,i=void 0){return Zi(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(tw,"iterateFullIndex");function zc(e,t,r,n,s,i=!1,o=void 0,c=void 0,u=!1,_=!1){return Zi(e,t,r,(l,d,E,f)=>{let A={transaction:l,start:i===!0?s:n,end:i===!0?n:s,reverse:i,limit:o,offset:c,inclusiveEnd:i===!0?!u:!_,exclusiveStart:i===!0?_:u};return f===r?(A.values=!1,d.getRange(A).map(R=>({value:R}))):d.getRange(A)})}a(zc,"iterateRangeBetween");function Zi(e,t,r,n){let s=e.database||e,i=ui.openDBI(s,r);i[rd.DBI_DEFINITION_NAME].is_hash_attribute?t=r:t&&ui.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(Zi,"setupTransaction");function rw(e,t,r,n){let s;return function(i,o){if(typeof i=="string"&&i.endsWith(ew)){if(!s)if(r)s=ui.openDBI(e,r);else{let u=ui.listDBIs(e);for(let _=0,l=u.length;_<l&&(s=ui.openDBI(e,u[_]),!s[rd.DBI_DEFINITION_NAME].is_hash_attribute);_++);}i=s.get(o,{transaction:t,lazy:!0})[n]}return i}}a(rw,"getOverflowCheck");function YQ(e,t,r,n=!1,s=void 0,i=void 0){if(Yr.validateEnv(e),t===void 0)throw new Error(ft.HASH_ATTRIBUTE_REQUIRED);return Zi(e,t,t,(o,c,u)=>(sd(r),r=Jc(u,r),c.getRange({transaction:o,start:n?void 0:!1,end:n?!1:void 0,limit:s,offset:i,reverse:n}).map(_=>VQ(_.value,r))))}a(YQ,"searchAll");function KQ(e,t,r,n=!1,s=void 0,i=void 0){if(Yr.validateEnv(e),t===void 0)throw new Error(ft.HASH_ATTRIBUTE_REQUIRED);sd(r),r=Jc(e.database||e,r);let o=new Map;for(let{key:c,value:u}of tw(e,t,t,n,s,i))o.set(c,nd.parseRow(u,r));return o}a(KQ,"searchAllToMap");function WQ(e,t,r=!1,n=void 0,s=void 0){if(Yr.validateEnv(e),t===void 0)throw new Error(ft.ATTRIBUTE_REQUIRED);let i=Object.create(null),o=tw(e,void 0,t,r,n,s),c=o.transaction,u=rw(c.database,c,void 0,t);for(let{key:_,value:l}of o){let d=u(_,l);i[d]===void 0&&(i[d]=[]),i[d].push(l)}return i}a(WQ,"iterateDBI");function QQ(e,t){if(Yr.validateEnv(e),t===void 0)throw new Error(ft.HASH_ATTRIBUTE_REQUIRED);return ui.statDBI(e,t).entryCount}a(QQ,"countAll");function zQ(e,t,r,n,s=!1,i=void 0,o=void 0){return li(e,r,n),Zi(e,t,r,(c,u,_,l)=>(n=Yr.convertKeyValueToWrite(n),l===r?u.get(n,{transaction:c,lazy:!0})===void 0?[]:[{key:n,value:n}]:u.getValues(n,{transaction:c,reverse:s,limit:i,offset:o}).map(d=>({key:n,value:d}))))}a(zQ,"equals");function JQ(e,t,r){return li(e,t,r),ui.openDBI(e,t).getValuesCount(r)}a(JQ,"count");function jQ(e,t,r,n,s=!1,i=void 0,o=void 0){return li(e,r,n),Zi(e,null,r,(c,u)=>{n=Yr.convertKeyValueToWrite(n);let _=!0;typeof n=="number"&&(_=!1);let l;if(s===!0){let d;for(let E of u.getKeys({transaction:c,start:n}))if(!E.startsWith(n)){d=E;break}return d!==void 0&&(Number.isInteger(o)?o++:i++),l=u.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 l.DONE}}),l.filter(E=>E)}else return l=u.getRange({transaction:c,start:n,reverse:s,limit:i,offset:o}).map(d=>{if(d.key.toString().startsWith(n))return d;if(_===!0)return l.DONE}),_?l:l.filter(d=>d)})}a(jQ,"startsWith");function XQ(e,t,r,n,s=!1,i=void 0,o=void 0){return nw(e,t,r,n,s,i,o,!0)}a(XQ,"endsWith");function nw(e,t,r,n,s=!1,i=void 0,o=void 0,c=!1){return li(e,r,n),Zi(e,null,r,(u,_,l,d)=>{let E=rw(l,u,d,r);return o=Number.isInteger(o)?o:0,_.getKeys({transaction:u,end:s?!1:void 0,reverse:s}).flatMap(f=>{let h=f.toString();return h.endsWith(ew)?_.getValues(f,{transaction:u}).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))?_[rd.DBI_DEFINITION_NAME].is_hash_attribute?{key:f,value:f}:_.getValues(f,{transaction:u}).map(p=>({key:f,value:p})):[]}).slice(o,i===void 0?void 0:i+(o||0))})}a(nw,"contains");function ZQ(e,t,r,n,s=!1,i=void 0,o=void 0){li(e,r,n);let c=typeof n,u;return c==="string"?u="\uFFFF":c==="number"?u=1/0:c==="boolean"&&(u=!0),zc(e,t,r,n,u,s,i,o,!0,!1)}a(ZQ,"greaterThan");function ez(e,t,r,n,s=!1,i=void 0,o=void 0){li(e,r,n);let c=typeof n,u;return c==="string"?u="\uFFFF":c==="number"?u=1/0:c==="boolean"&&(u=!0),zc(e,t,r,n,u,s,i,o,!1,!1)}a(ez,"greaterThanEqual");function tz(e,t,r,n,s=!1,i=void 0,o=void 0){li(e,r,n);let c=typeof n,u;return c==="string"?u="\0":c==="number"?u=-1/0:c==="boolean"&&(u=!1),zc(e,t,r,u,n,s,i,o,!1,!0)}a(tz,"lessThan");function rz(e,t,r,n,s=!1,i=void 0,o=void 0){li(e,r,n);let c=typeof n,u;return c==="string"?u="\0":c==="number"?u=-1/0:c==="boolean"&&(u=!1),zc(e,t,r,u,n,s,i,o,!1,!1)}a(rz,"lessThanEqual");function nz(e,t,r,n,s,i=!1,o=void 0,c=void 0){if(Yr.validateEnv(e),r===void 0)throw new Error(ft.ATTRIBUTE_REQUIRED);if(n===void 0)throw new Error(ft.START_VALUE_REQUIRED);if(s===void 0)throw new Error(ft.END_VALUE_REQUIRED);if(n=Yr.convertKeyValueToWrite(n),s=Yr.convertKeyValueToWrite(s),n>s)throw new Error(ft.END_VALUE_MUST_BE_GREATER_THAN_START_VALUE);return zc(e,t,r,n,s,i,o,c)}a(nz,"between");function sz(e,t,r,n){Yr.validateEnv(e);let s=e.database||e,i=e.database?e:null;if(t===void 0)throw new Error(ft.HASH_ATTRIBUTE_REQUIRED);if(sd(r),r=Jc(s,r),n===void 0)throw new Error(ft.ID_REQUIRED);let o=null,c=s.dbis[t].get(n,{transaction:i,lazy:r.length<3});return c&&(o=nd.parseRow(c,r)),o}a(sz,"searchByHash");function iz(e,t,r){Yr.validateEnv(e);let n=e.database||e,s=e.database?e:null;if(t===void 0)throw new Error(ft.HASH_ATTRIBUTE_REQUIRED);if(r===void 0)throw new Error(ft.ID_REQUIRED);let i=!0;return n.dbis[t].get(r,{transaction:s,lazy:!0})===void 0&&(i=!1),i}a(iz,"checkHashExists");function oz(e,t,r,n,s=[]){return iw(e,t,r,n,s),sw(e,t,r,n,s).map(i=>i[1])}a(oz,"batchSearchByHash");function az(e,t,r,n,s=[]){iw(e,t,r,n,s);let i=new Map;for(let[o,c]of sw(e,t,r,n,s))i.set(o,c);return i}a(az,"batchSearchByHashToMap");function sw(e,t,r,n,s=[]){return Zi(e,t,t,(i,o,c)=>{r=Jc(c,r);let u=r.length<3;return n.map(_=>{let l=c.dbis[t].get(_,{transaction:i,lazy:u});if(l)return[_,nd.parseRow(l,r)];s.push(_)}).filter(_=>_)})}a(sw,"batchHashSearch");function iw(e,t,r,n,s){if(Yr.validateEnv(e),t===void 0)throw new Error(ft.HASH_ATTRIBUTE_REQUIRED);if(sd(r),n==null)throw new Error(ft.IDS_REQUIRED);if(!n[Symbol.iterator])throw new Error(ft.IDS_MUST_BE_ITERABLE)}a(iw,"initializeBatchSearchByHash");function sd(e){if(!Array.isArray(e))throw e===void 0?new Error(ft.FETCH_ATTRIBUTES_REQUIRED):new Error(ft.FETCH_ATTRIBUTES_MUST_BE_ARRAY)}a(sd,"validateFetchAttributes");function li(e,t,r){if(Yr.validateEnv(e),t===void 0)throw new Error(ft.ATTRIBUTE_REQUIRED);if(r===void 0)throw new Error(ft.SEARCH_VALUE_REQUIRED);if(r?.length>$Q)throw new Error(ft.SEARCH_VALUE_TOO_LARGE)}a(li,"validateComparisonFunctions");function Jc(e,t){return t.length===1&&kQ.SEARCH_WILDCARDS.indexOf(t[0])>=0&&(t=ui.listDBIs(e)),t}a(Jc,"setGetWholeRowAttributes");ow.exports={searchAll:YQ,searchAllToMap:KQ,count:JQ,countAll:QQ,equals:zQ,startsWith:jQ,endsWith:XQ,contains:nw,searchByHash:sz,setGetWholeRowAttributes:Jc,batchSearchByHash:oz,batchSearchByHashToMap:az,checkHashExists:iz,iterateDBI:WQ,greaterThan:ZQ,greaterThanEqual:ez,lessThan:tz,lessThanEqual:rz,between:nz}});var sa=g((m_e,_w)=>{var aw=require("lodash"),cw=je(),he=require("joi"),cz=J(),{hdb_schema_table:jc,checkValidTable:uw,hdb_table:lw,hdb_database:id}=zn(),{handleHDBError:uz,hdb_errors:lz}=ne(),{getDatabases:_z}=(Oe(),ie(Fe)),{HTTP_STATUS_CODES:dz}=lz,fz=he.object({database:id,schema:id,table:lw,search_attribute:jc,search_value:he.any().required(),get_attributes:he.array().min(1).items(he.alternatives(jc,he.object())).optional(),desc:he.bool(),limit:he.number().integer().min(1),offset:he.number().integer().min(0)}),Ez=he.object({database:id,schema:id,table:lw,operator:he.string().valid("and","or").default("and").lowercase(),offset:he.number().integer().min(0),limit:he.number().integer().min(1),get_attributes:he.array().min(1).items(he.alternatives(jc,he.object())).optional(),sort:he.object({attribute:he.alternatives(jc,he.array().min(1)),descending:he.bool().optional()}).optional(),conditions:he.array().min(1).items(he.alternatives(he.object({operator:he.string().valid("and","or").default("and").lowercase(),conditions:he.array()}),he.object({search_attribute:he.alternatives(jc,he.array().min(1)),search_type:he.string().valid("equals","contains","starts_with","ends_with","greater_than","greater_than_equal","less_than","less_than_equal","between","not_equal").optional(),search_value:he.when("search_type",{switch:[{is:"equals",then:he.any()},{is:"between",then:he.array().items(he.alternatives([he.string(),he.number()])).length(2)}],otherwise:he.alternatives(he.string(),he.number())}).required()}))).required()});_w.exports=function(e,t){let r=null;switch(t){case"value":r=cw.validateBySchema(e,fz);break;case"hashes":let i=function(o){s?s+=". "+o:s=o};var n=i;a(i,"addError");let s;i(uw("database",e.schema)),i(uw("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=cw.validateBySchema(e,Ez);break;default:throw new Error(`Error validating search, unknown type: ${t}`)}if(!r&&e.schema!=="system"){let s=cz.checkGlobalSchemaTable(e.schema,e.table);if(s)return uz(new Error,s,dz.NOT_FOUND);let o=_z()[e.schema][e.table].attributes,c=e.get_attributes?[...e.get_attributes]:[];t==="value"&&c.push(e.search_attribute);let u=a(l=>{for(let d=0,E=l.conditions.length;d<E;d++){let f=l.conditions[d];f.conditions?u(f):c.push(f.search_attribute)}},"addConditions");t==="conditions"&&u(e);let _=aw.filter(c,l=>l!=="*"&&l.attribute!=="*"&&!Array.isArray(l)&&!l.name&&!aw.some(o,d=>d===l||d.attribute===l||d.attribute===l.attribute));if(_&&_.length>0){let l=_.join(", ");return l=l.replace(/,([^,]*)$/," and$1"),new Error(`unknown attribute '${l}'`)}}return r}});var Mp=g((S_e,dw)=>{"use strict";var hz=Ke(),mz=sa(),{getSchemaPath:pz}=ze();dw.exports=Sz;function Sz(e){let t=mz(e,"hashes");if(t)throw t;let r=pz(e.schema,e.table);return hz.openEnvironment(r,e.table)}a(Sz,"initialize")});var Pp=g((g_e,fw)=>{"use strict";var Tz=na(),gz=Mp();fw.exports=Rz;async function Rz(e){let t=await gz(e),r=t.useReadTransaction();r.database=t;let n=global.hdb_schema[e.schema][e.table];try{return Tz.batchSearchByHashToMap(r,n.hash_attribute,e.get_attributes,e.hash_values)}finally{r.done()}}a(Rz,"lmdbGetDataByHash")});var ia=g((A_e,Ew)=>{"use strict";var Up=class{static{a(this,"SearchByHashObject")}constructor(t,r,n,s){this.schema=t,this.table=r,this.hash_values=n,this.get_attributes=s}};Ew.exports=Up});var mw=g((y_e,hw)=>{"use strict";var b_e=ia(),Az=na(),Oz=Mp();hw.exports=bz;async function bz(e){let t=await Oz(e),r=global.hdb_schema[e.schema][e.table];return Az.batchSearchByHash(t,r.hash_attribute,e.get_attributes,e.hash_values)}a(bz,"lmdbSearchByHash")});var es=g((I_e,pw)=>{"use strict";var vp=class{static{a(this,"SearchObject")}constructor(t,r,n,s,i,o,c,u=!1,_=void 0,l=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=u,this.limit=_,this.offset=l}};pw.exports=vp});var od=g((C_e,Ow)=>{"use strict";var er=na(),yz=Ke(),Nz=J(),me=_t(),eo=P(),Iz=Fi(),Sw=Ur().LMDB_ERRORS_ENUM,{getSchemaPath:wz}=ze(),ys=eo.SEARCH_WILDCARDS;async function Cz(e,t,r){let n;e.schema===eo.SYSTEM_SCHEMA_NAME?n=Iz[e.table]:n=global.hdb_schema[e.schema][e.table];let s=Aw(e,n.hash_attribute,r,t);return gw(e,s,n.hash_attribute,r)}a(Cz,"prepSearch");async function gw(e,t,r,n){let s=wz(e.schema,e.table),i=await yz.openEnvironment(s,e.table),o=Rw(i,e,t,r),c=o.transaction||i;if([me.SEARCH_TYPES.BATCH_SEARCH_BY_HASH,me.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP,me.SEARCH_TYPES.SEARCH_ALL,me.SEARCH_TYPES.SEARCH_ALL_TO_MAP].indexOf(t)>=0)return o;if(Dz(e,r)===!1){let l=e.search_attribute;if(l===r)return n?Tw(o,()=>!0):o.map(E=>({[r]:E.key}));let d=a(E=>({[r]:E.value,[l]:E.key}),"toObject");return n?Tw(o,d):o.map(d)}let _=e.search_attribute===r?o.map(l=>l.key):o.map(l=>l.value);return n===!0?er.batchSearchByHashToMap(c,r,e.get_attributes,_):er.batchSearchByHash(c,r,e.get_attributes,_)}a(gw,"executeSearch");function Rw(e,t,r,n){let s,i=n;t.get_attributes.indexOf(n)<0&&(i=void 0);let{reverse:o,limit:c,offset:u}=t;switch(o=typeof o=="boolean"?o:!1,c=Number.isInteger(c)?c:void 0,u=Number.isInteger(u)?u:void 0,r){case me.SEARCH_TYPES.EQUALS:s=er.equals(e,i,t.search_attribute,t.search_value,o,c,u);break;case me.SEARCH_TYPES.CONTAINS:s=er.contains(e,i,t.search_attribute,t.search_value,o,c,u);break;case me.SEARCH_TYPES.ENDS_WITH:case me.SEARCH_TYPES._ENDS_WITH:s=er.endsWith(e,i,t.search_attribute,t.search_value,o,c,u);break;case me.SEARCH_TYPES.STARTS_WITH:case me.SEARCH_TYPES._STARTS_WITH:s=er.startsWith(e,i,t.search_attribute,t.search_value,o,c,u);break;case me.SEARCH_TYPES.BATCH_SEARCH_BY_HASH:return er.batchSearchByHash(e,t.search_attribute,t.get_attributes,[t.search_value]);case me.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP:return er.batchSearchByHashToMap(e,t.search_attribute,t.get_attributes,[t.search_value]);case me.SEARCH_TYPES.SEARCH_ALL:return er.searchAll(e,n,t.get_attributes,o,c,u);case me.SEARCH_TYPES.SEARCH_ALL_TO_MAP:return er.searchAllToMap(e,n,t.get_attributes,o,c,u);case me.SEARCH_TYPES.BETWEEN:s=er.between(e,i,t.search_attribute,t.search_value,t.end_value,o,c,u);break;case me.SEARCH_TYPES.GREATER_THAN:case me.SEARCH_TYPES._GREATER_THAN:s=er.greaterThan(e,i,t.search_attribute,t.search_value,o,c,u);break;case me.SEARCH_TYPES.GREATER_THAN_EQUAL:case me.SEARCH_TYPES._GREATER_THAN_EQUAL:s=er.greaterThanEqual(e,i,t.search_attribute,t.search_value,o,c,u);break;case me.SEARCH_TYPES.LESS_THAN:case me.SEARCH_TYPES._LESS_THAN:s=er.lessThan(e,i,t.search_attribute,t.search_value,o,c,u);break;case me.SEARCH_TYPES.LESS_THAN_EQUAL:case me.SEARCH_TYPES._LESS_THAN_EQUAL:s=er.lessThanEqual(e,i,t.search_attribute,t.search_value,o,c,u);break;default:return Object.create(null)}return s}a(Rw,"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 Dz(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(Dz,"checkToFetchMore");function Aw(e,t,r,n){if(Nz.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),ys.indexOf(s)>-1)return r===!0?me.SEARCH_TYPES.SEARCH_ALL_TO_MAP:me.SEARCH_TYPES.SEARCH_ALL;if(s.indexOf(ys[0])<0&&s.indexOf(ys[1])<0)return c===!0?r===!0?me.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP:me.SEARCH_TYPES.BATCH_SEARCH_BY_HASH:me.SEARCH_TYPES.EQUALS;if(ys.indexOf(i)>=0&&ys.indexOf(o)>=0)return e.search_value=e.search_value.slice(1,-1),me.SEARCH_TYPES.CONTAINS;if(ys.indexOf(i)>=0)return e.search_value=e.search_value.substr(1),me.SEARCH_TYPES.ENDS_WITH;if(ys.indexOf(o)>=0)return e.search_value=e.search_value.slice(0,-1),me.SEARCH_TYPES.STARTS_WITH;if(s.includes(ys[0])||s.includes(ys[1]))return me.SEARCH_TYPES.EQUALS;throw new Error(Sw.UNKNOWN_SEARCH_TYPE)}else switch(n){case eo.VALUE_SEARCH_COMPARATORS.BETWEEN:return me.SEARCH_TYPES.BETWEEN;case eo.VALUE_SEARCH_COMPARATORS.GREATER:return me.SEARCH_TYPES.GREATER_THAN;case eo.VALUE_SEARCH_COMPARATORS.GREATER_OR_EQ:return me.SEARCH_TYPES.GREATER_THAN_EQUAL;case eo.VALUE_SEARCH_COMPARATORS.LESS:return me.SEARCH_TYPES.LESS_THAN;case eo.VALUE_SEARCH_COMPARATORS.LESS_OR_EQ:return me.SEARCH_TYPES.LESS_THAN_EQUAL;default:throw new Error(Sw.UNKNOWN_SEARCH_TYPE)}}a(Aw,"createSearchTypeFromSearchObject");Ow.exports={executeSearch:gw,createSearchTypeFromSearchObject:Aw,prepSearch:Cz,searchByType:Rw}});var yw=g((M_e,bw)=>{"use strict";var L_e=es(),Lz=sa(),Mz=J(),Pz=P(),Uz=od();bw.exports=vz;function vz(e,t){if(!Mz.isEmpty(t)&&Pz.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[t]===void 0)throw new Error(`Value search comparator - ${t} - is not valid`);let n=Lz(e,"value");if(n)throw n;return Uz.prepSearch(e,t,!0)}a(vz,"lmdbGetDataByValue")});var Xc=g((v_e,Nw)=>{"use strict";var U_e=es(),Bz=sa(),Hz=J(),xz=P(),Gz=od();Nw.exports=qz;async function qz(e,t){if(!Hz.isEmpty(t)&&xz.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[t]===void 0)throw new Error(`Value search comparator - ${t} - is not valid`);let n=Bz(e,"value");if(n)throw n;return Gz.prepSearch(e,t,!1)}a(qz,"lmdbSearchByValue")});var ww=g((x_e,Iw)=>{"use strict";var H_e=_t(),Bp=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}},Hp=class{static{a(this,"SearchCondition")}constructor(t,r,n){this.search_attribute=t,this.search_type=r,this.search_value=n}},xp=class{static{a(this,"SortAttribute")}constructor(t,r){this.attribute=t,this.desc=r}};Iw.exports={SearchByConditionsObject:Bp,SearchCondition:Hp,SortAttribute:xp}});var Pw=g((k_e,Mw)=>{"use strict";var q_e=ww().SearchByConditionsObject,Fz=es(),kz=sa(),Gp=na(),ad=_t(),{Resource:F_e}=(Nn(),ie(qp)),Lw=od(),Vz=Lp(),$z=require("lodash"),{getSchemaPath:Yz}=ze(),Cw=Ke(),{handleHDBError:Kz,hdb_errors:Wz}=ne(),{HTTP_STATUS_CODES:Qz}=Wz,zz=1e8;Mw.exports=Jz;async function Jz(e){let t=kz(e,"conditions");if(t)throw Kz(t,t.message,Qz.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=Yz(e.schema,e.table),n=await Cw.openEnvironment(r,e.table),s=global.hdb_schema[e.schema][e.table];for(let _ of e.conditions)Cw.openDBI(n,_.search_attribute);let i=$z.sortBy(e.conditions,_=>{if(_.estimated_count===void 0){let l=_.search_type;l===ad.SEARCH_TYPES.EQUALS?_.estimated_count=Gp.count(n,_.search_attribute,_.search_value):l===ad.SEARCH_TYPES.CONTAINS||l===ad.SEARCH_TYPES.ENDS_WITH?_.estimated_count=1/0:_.estimated_count=zz}return _.estimated_count}),o=n.useReadTransaction();o.database=n;let c=await Dw(o,e,i[0],s.hash_attribute),u;if(!e.operator||e.operator.toLowerCase()==="and"){let _=n.dbis[s.hash_attribute],l=i.slice(1).map(Lw.filterByType),d=l.length,E=Gp.setGetWholeRowAttributes(n,e.get_attributes);u=c.map(f=>_.get(f,{transaction:o,lazy:!0})),d>0&&(u=u.filter(f=>{for(let h=0;h<d;h++)if(!l[h](f))return!1;return!0})),(e.offset||e.limit!==void 0)&&(u=u.slice(e.offset,e.limit!==void 0?(e.offset||0)+e.limit:void 0)),u=u.map(f=>Vz.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,l=e.offset||0;c=c.filter(d=>_.has(d)?!1:(_.add(d),!0)).slice(l,e.limit&&e.limit+l),u=Gp.batchSearchByHash(o,s.hash_attribute,e.get_attributes,c)}return u.onDone=()=>{o.done()},u}a(Jz,"lmdbSearchByConditions");async function Dw(e,t,r,n){let s=new Fz(t.schema,t.table,void 0,void 0,n,t.get_attributes),i=r.search_type;return s.search_attribute=r.search_attribute,i===ad.SEARCH_TYPES.BETWEEN?(s.search_value=r.search_value[0],s.end_value=r.search_value[1]):s.search_value=r.search_value,Lw.searchByType(e,s,i,n).map(o=>o.value)}a(Dw,"executeConditionSearch")});var oa=g(($_e,Uw)=>{"use strict";var jz=P().OPERATIONS_ENUM,Fp=class{static{a(this,"DeleteObject")}constructor(t,r,n,s=void 0){this.operation=jz.DELETE,this.schema=t,this.table=r,this.hash_values=n,this.__origin=s}};Uw.exports=Fp});var kp=g((K_e,kw)=>{"use strict";var xw=es(),Gw=oa(),qw=Xc(),Fw=Qc(),Er=P(),vw=J(),Bw=Ke(),{getTransactionAuditStorePath:Xz,getSchemaPath:Zz}=ze(),Hw=$();kw.exports=e2;async function e2(e){try{if(vw.isEmpty(global.hdb_schema[e.schema])||vw.isEmpty(global.hdb_schema[e.schema][e.table]))throw new Error(`unknown schema:${e.schema} and table ${e.table}`);await t2(e),await r2(e);let t=Zz(e.schema,e.table);try{await Bw.deleteEnvironment(t,e.table)}catch(r){if(r.message==="invalid environment")Hw.warn(`cannot delete environment for ${e.schema}.${e.table}, environment not found`);else throw r}try{let r=Xz(e.schema,e.table);await Bw.deleteEnvironment(r,e.table,!0)}catch(r){if(r.message==="invalid environment")Hw.warn(`cannot delete environment for ${e.schema}.${e.table}, environment not found`);else throw r}}catch(t){throw t}}a(e2,"lmdbDropTable");async function t2(e){let t=new xw(Er.SYSTEM_SCHEMA_NAME,Er.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,Er.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_TABLE_KEY,`${e.schema}.${e.table}`,void 0,[Er.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),r=Array.from(await qw(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 Gw(Er.SYSTEM_SCHEMA_NAME,Er.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,n);await Fw(s)}a(t2,"deleteAttributesFromSystem");async function r2(e){let t=new xw(Er.SYSTEM_SCHEMA_NAME,Er.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,Er.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY,e.table,void 0,[Er.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY,Er.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_KEY,Er.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),r,n;try{r=Array.from(await qw(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 Gw(Er.SYSTEM_SCHEMA_NAME,Er.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,[n.id]);try{await Fw(s)}catch(i){throw i}}a(r2,"dropTableFromSystem")});var $w=g((Q_e,Vw)=>{"use strict";var n2=require("fs-extra"),s2=es(),i2=ia(),o2=oa(),a2=kp(),c2=Qc(),u2=Pp(),l2=Xc(),Ns=P(),{getSchemaPath:_2}=ze(),{handleHDBError:d2,hdb_errors:f2}=ne(),{HDB_ERROR_MSGS:E2,HTTP_STATUS_CODES:h2}=f2;Vw.exports=m2;async function m2(e){let t;try{t=await p2(e.schema);let r=new s2(Ns.SYSTEM_SCHEMA_NAME,Ns.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,Ns.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_KEY,t,void 0,[Ns.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY]),n=Array.from(await l2(r));for(let o=0;o<n.length;o++){let c={schema:t,table:n[o].name};try{await a2(c)}catch(u){if(u.message!=="invalid environment")throw u}}let s=new o2(Ns.SYSTEM_SCHEMA_NAME,Ns.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,[t]);await c2(s);let i=_2(t);await n2.remove(i)}catch(r){throw r}}a(m2,"lmdbDropSchema");async function p2(e){let t=new i2(Ns.SYSTEM_SCHEMA_NAME,Ns.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,[e],[Ns.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY]),r,n;try{r=Array.from(await u2(t))}catch(s){throw s}for(let[,s]of r)s.name===e&&(n=e);if(!n)throw d2(new Error,E2.SCHEMA_NOT_FOUND(e),h2.NOT_FOUND,void 0,void 0,!0);return n}a(p2,"validateDropSchema")});var cd=g((J_e,Yw)=>{"use strict";var Vp=class{static{a(this,"CreateTableObject")}constructor(t,r,n){this.schema=t,this.table=r,this.hash_attribute=n}};Yw.exports=Vp});var Ww=g((Z_e,Kw)=>{"use strict";var S2=require("fs-extra"),ud=Ke(),{getTransactionAuditStorePath:T2}=ze(),$p=_t(),X_e=cd();Kw.exports=g2;async function g2(e){let t;try{let r=T2(e.schema,e.table);await S2.mkdirp(r),t=await ud.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{ud.createDBI(t,$p.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,!1,!0),ud.createDBI(t,$p.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE,!0,!1),ud.createDBI(t,$p.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(g2,"createTransactionsAuditEnvironment")});var jw=g((tde,Jw)=>{"use strict";var Yp=P(),Qw=Ke(),R2=Yo(),{getSystemSchemaPath:A2,getSchemaPath:O2}=ze(),b2=Fi(),y2=I_(),Kp=N_(),N2=$(),I2=Ww(),Qp=b2.hdb_table,zw=[];for(let e=0;e<Qp.attributes.length;e++)zw.push(Qp.attributes[e].attribute);Jw.exports=w2;async function w2(e,t){let r=O2(t.schema,t.table),n=new Kp(t.schema,t.table,Yp.TIME_STAMP_NAMES_ENUM.CREATED_TIME,void 0,!0),s=new Kp(t.schema,t.table,Yp.TIME_STAMP_NAMES_ENUM.UPDATED_TIME,void 0,!0),i=new Kp(t.schema,t.table,t.hash_attribute,void 0,!1,!0);try{if(await Qw.createEnvironment(r,t.table),e!==void 0){let o=await Qw.openEnvironment(A2(),Yp.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME);await R2.insertRecords(o,Qp.hash_attribute,zw,[e]),n.skip_table_check=!0,s.skip_table_check=!0,i.skip_table_check=!0,await Wp(n),await Wp(s),await Wp(i)}await I2(t)}catch(o){throw o}}a(w2,"lmdbCreateTable");async function Wp(e){try{await y2(e)}catch(t){N2.warn(`failed to create attribute ${e.attribute} due to ${t.message}`)}}a(Wp,"createAttribute")});var Zw=g((nde,Xw)=>{"use strict";var C2=Hc(),D2=Gc(),L2=ed(),Zc=P(),M2=Yo().updateRecords,P2=Ke(),{getSchemaPath:U2}=ze(),v2=Kc(),B2=$();Xw.exports=H2;async function H2(e){try{let{schema_table:t,attributes:r}=C2(e);D2(e,r,t.hash_attribute),e.schema!==Zc.SYSTEM_SCHEMA_NAME&&(r.includes(Zc.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||r.push(Zc.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.includes(Zc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||r.push(Zc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let n=await L2(e.hdb_auth_header,t,r),s=U2(e.schema,e.table),i=await P2.openEnvironment(s,e.table),o=await M2(i,t.hash_attribute,r,e.records,e.__origin?.timestamp);try{await v2(e,o)}catch(c){B2.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(H2,"lmdbUpdateRecords")});var tC=g((ide,eC)=>{"use strict";var x2=P().OPERATIONS_ENUM,zp=class{static{a(this,"UpsertObject")}constructor(t,r,n,s=void 0){this.operation=x2.UPSERT,this.schema=t,this.table=r,this.records=n,this.__origin=s}};eC.exports=zp});var nC=g((cde,rC)=>{"use strict";var ade=tC(),G2=Hc(),q2=Gc(),F2=ed(),eu=P(),k2=Yo().upsertRecords,V2=Ke(),{getSchemaPath:$2}=ze(),Y2=Kc(),K2=$(),{handleHDBError:W2,hdb_errors:Q2}=ne();rC.exports=z2;async function z2(e){let t;try{t=G2(e)}catch(u){throw W2(u,u.message,Q2.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0)}let{schema_table:r,attributes:n}=t;q2(e,n,r.hash_attribute),e.schema!==eu.SYSTEM_SCHEMA_NAME&&(n.includes(eu.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||n.push(eu.TIME_STAMP_NAMES_ENUM.CREATED_TIME),n.includes(eu.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||n.push(eu.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let s=await F2(e.hdb_auth_header,r,n),i=$2(e.schema,e.table),o=await V2.openEnvironment(i,e.table),c=await k2(o,r.hash_attribute,n,e.records,e.__origin?.timestamp);try{await Y2(e,c)}catch(u){K2.error(`unable to write transaction due to ${u.message}`)}return{written_hashes:c.written_hashes,schema_table:r,new_attributes:s,txn_time:c.txn_time}}a(z2,"lmdbUpsertRecords")});var iC=g((lde,sC)=>{"use strict";var Jp=class{static{a(this,"DeleteBeforeObject")}constructor(t,r,n){this.schema=t,this.table=r,this.timestamp=n}};sC.exports=Jp});var aC=g((dde,oC)=>{"use strict";var jp=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}};oC.exports=jp});var lC=g((hde,uC)=>{"use strict";var Xp=Ke(),{getTransactionAuditStorePath:J2}=ze(),Ede=iC(),tu=_t(),j2=J(),cC=aC(),X2=require("util").promisify,Z2=X2(setTimeout),eJ=1e4,tJ=100;uC.exports=rJ;async function rJ(e){let t=J2(e.schema,e.table),r=await Xp.openEnvironment(t,e.table,!0),n=Xp.listDBIs(r);Xp.initializeDBIs(r,tu.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,n);let s,i=new cC;do s=await nJ(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 Z2(tJ);while(s.transactions_deleted>0);return i}a(rJ,"deleteAuditLogsBefore");async function nJ(e,t){let r=new cC;try{let n=e.dbis[tu.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[tu.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME];j2.isEmpty(c)||(s=e.dbis[tu.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].remove(c,i));for(let u=0;u<o.hash_values.length;u++)s=e.dbis[tu.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE].remove(o.hash_values[u],i);if(r.transactions_deleted++,r.end_timestamp=i,r.transactions_deleted>eJ)break}return await s,r}catch(n){throw n}}a(nJ,"deleteTransactions")});var dC=g((pde,_C)=>{"use strict";var Zp=class{static{a(this,"DropAttributeObject")}constructor(t,r,n){this.schema=t,this.table=r,this.attribute=n}};_C.exports=Zp});var EC=g((gde,fC)=>{"use strict";var sJ=es(),iJ=oa(),Tde=dC(),ts=P(),oJ=J(),eS=Ke(),aJ=Fi(),cJ=Xc(),uJ=Qc(),{getSchemaPath:lJ}=ze();fC.exports=_J;async function _J(e,t=!0){let r;e.schema===ts.SYSTEM_SCHEMA_NAME?r=aJ[e.table]:r=global.hdb_schema[e.schema][e.table];let n=await fJ(e),s=lJ(e.schema,e.table),i=await eS.openEnvironment(s,e.table);return t===!0&&await dJ(e,i,r.hash_attribute),eS.dropDBI(i,e.attribute),n}a(_J,"lmdbDropAttribute");async function dJ(e,t,r){let n=eS.openDBI(t,r),s,i=e.attribute;for(let{key:o,value:c,version:u}of n.getRange({start:!1,versions:!0})){let _={};for(let l in c)l!==i&&(_[l]=c[l]);s=t.dbis[r].put(o,_,u)}await s}a(dJ,"removeAttributeFromAllObjects");async function fJ(e){let t=new sJ(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 cJ(t)).filter(o=>o[ts.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ATTRIBUTE_KEY]===e.attribute);if(oJ.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 iJ(ts.SYSTEM_SCHEMA_NAME,ts.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,s);return uJ(i)}a(fJ,"dropAttributeFromSystem")});var gC=g((Ode,TC)=>{"use strict";var tS=Ke(),aa=_t(),Ade=vr(),rS=P(),hC=J(),{getTransactionAuditStorePath:EJ}=ze(),hJ=na(),ld=ea(),mJ=$();TC.exports=pJ;async function pJ(e){let t=EJ(e.schema,e.table),r=await tS.openEnvironment(t,e.table,!0),n=tS.listDBIs(r);tS.initializeDBIs(r,aa.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,n);let s;switch(e.search_type){case rS.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.TIMESTAMP:return mC(r,e.search_values);case rS.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.HASH_VALUE:return s=global.hdb_schema[e.schema][e.table].hash_attribute,TJ(r,e.search_values,s);case rS.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.USERNAME:return SJ(r,e.search_values);default:return mC(r)}}a(pJ,"readAuditLog");function mC(e,t=[0,Date.now()]){hC.isEmpty(t[0])&&(t[0]=0),hC.isEmpty(t[1])&&(t[1]=Date.now());let r=e.dbis[aa.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 ld,s))}a(mC,"searchTransactionsByTimestamp");function SJ(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[aa.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].getValues(s))i.push(o);r.set(s,SC(e,i))}return Object.fromEntries(r)}a(SJ,"searchTransactionsByUsername");function TJ(e,t,r){let n=new Map;for(let c=0,u=t.length;c<u;c++){let _=t[c],l=hJ.equals(e,aa.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,aa.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE,_);for(let{value:d}of l){let E=Number(d);n.has(E)?n.get(E).push(_.toString()):n.set(E,[_.toString()])}}let s=Array.from(n.keys()),i=SC(e,s),o=new Map;for(let c=0;c<i.length;c++){let u=i[c],_=u.timestamp,l=n.get(_);pC(u,"records",r,l,o),pC(u,"original_records",r,l,o)}return Object.fromEntries(o)}a(TJ,"searchTransactionsByHashValues");function pC(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],u=c[r].toString();if(n.indexOf(u)>=0)if(s.has(u)){let _=s.get(u),l=_[_.length-1];if(l.timestamp===i)l[t]=[c];else{let d=new ld(e.operation,e.user_name,i,void 0);d[t]=[c],_.push(d)}}else{let _=new ld(e.operation,e.user_name,i,void 0);_[t]=[c],s.set(u,[_])}}}a(pC,"loopRecords");function SC(e,t){let r=[];try{let n=e.dbis[aa.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 ld,i);r.push(o)}}catch(i){mJ.warn(i)}return r}catch(n){throw n}}a(SC,"batchSearchTransactions")});var AC=g((Ide,RC)=>{"use strict";var{getSchemaPath:yde}=ze(),Nde=Ke(),{database:gJ}=(Oe(),ie(Fe));RC.exports={writeTransaction:RJ};async function RJ(e,t,r){return gJ({database:e,table:t}).transaction(r)}a(RJ,"writeTransaction")});var NC=g((Cde,yC)=>{"use strict";var{getSchemaPath:OC}=ze(),bC=Ke();yC.exports={flush:AJ,resetReadTxn:OJ};async function AJ(e,t){return(await bC.openEnvironment(OC(e,t),t.toString())).flushed}a(AJ,"flush");async function OJ(e,t){try{(await bC.openEnvironment(OC(e,t),t.toString())).resetReadTxn()}catch{}}a(OJ,"resetReadTxn")});var DC=g((Lde,CC)=>{"use strict";var{Readable:bJ}=require("stream"),{getDatabases:yJ}=(Oe(),ie(Fe)),{readSync:NJ,openSync:IJ,createReadStream:IC}=require("fs"),{open:wJ}=require("lmdb"),wC=Dc(),CJ=Lc(),{AUDIT_STORE_OPTIONS:DJ}=(ti(),ie(LC)),{INTERNAL_DBIS_NAME:LJ,AUDIT_STORE_NAME:MJ}=_t();CC.exports=UJ;var nS=32768,PJ=100;async function UJ(e){let t=e.database||e.schema||"data",r=yJ()[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 l=_.dbisDB,d=wJ({noSync:!0,maxDbs:CJ.MAX_DBS}),E,f=d.openDB(LJ,new wC(!1)),h=l.useReadTransaction(),p=0,S=a(async function(A,R){R.encoding="binary",R.encoder=void 0;let C=d.openDB(A,R),x=l.openDB(A,R);for(let{key:v,version:k,value:M}of x.getRange({start:null,transaction:h,versions:x.useVersions}))E=C.put(v,M,k),p++%PJ===0&&(await new Promise(Q=>setTimeout(Q,20)),h.openTimer&&(h.openTimer=0))},"copyDatabase");for(let{key:A,value:R}of l.getRange({transaction:h,start:!1}))if(s.some(C=>A.startsWith?.(C+"/"))){f.put(A,R);let[,C]=A.split("/"),x=!C,v=new wC(!x,x);await S(A,v)}e.include_audit&&await S(MJ,Object.assign({},DJ)),await E;let T=IC(d.path);return T.headers=u(),T.on("close",()=>{h.done(),d.close()}),T}let o=r[Object.keys(r)[0]].primaryStore,c=IJ(o.path);return o.transaction(()=>{let _=Buffer.alloc(nS);NJ(c,_,0,nS),o.resetReadTxn();let l=o.useReadTransaction();l.renew();let d=IC(null,{fd:c,start:nS}),E=new bJ.from(async function*(){yield _;for await(let f of d)l.openTimer&&(l.openTimer=0),yield f;l.done()}());return E.headers=u(),E});function u(){let _=new Map;return _.set("content-type","application/octet-stream"),_.set("content-disposition",`attachment; filename="${t}"`),_.set("date",n),_}}a(UJ,"getBackup")});var UC=g((Pde,PC)=>{"use strict";var vJ=$(),{handleHDBError:BJ}=ne(),HJ=Kb(),xJ=I_(),GJ=Np(),qJ=$I(),FJ=Qc(),kJ=Pp(),VJ=mw(),$J=yw(),YJ=Xc(),KJ=Pw(),WJ=$w(),QJ=jw(),zJ=Zw(),JJ=nC(),jJ=lC(),XJ=kp(),ZJ=EC(),e4=gC(),t4=AC(),MC=NC(),r4=DC(),sS=class extends HJ{static{a(this,"LMDBBridge")}async searchByConditions(t){return KJ(t)}async getDataByHash(t){return await kJ(t)}async searchByHash(t){return await VJ(t)}async getDataByValue(t,r){return await $J(t,r)}async searchByValue(t){return await YJ(t)}async createSchema(t){return await qJ(t)}async dropSchema(t){return await WJ(t)}async createTable(t,r){return await QJ(t,r)}async dropTable(t){return await XJ(t)}async createAttribute(t){return await xJ(t)}async createRecords(t){return await GJ(t)}async updateRecords(t){return await zJ(t)}async upsertRecords(t){try{return await JJ(t)}catch(r){throw BJ(r,null,null,vJ.ERR,r)}}async deleteRecords(t){return await FJ(t)}async dropAttribute(t){return await ZJ(t)}async deleteAuditLogsBefore(t){return await jJ(t)}async readAuditLog(t){return await e4(t)}writeTransaction(t,r,n){return t4.writeTransaction(t,r,n)}flush(t,r){return MC.flush(t,r)}resetReadTxn(t,r){return MC.resetReadTxn(t,r)}getBackup(t){return r4(t)}};PC.exports=sS});function o4(){i4=setInterval(function(){for(let e of iS)if(e.stale){let t=e[Ne]?.url;xC.error(`Transaction was open too long and has been aborted, from table: ${e.lmdbDb?.name+(t?" path: "+t:"")}`),e.abort()}else e.stale=!0},s4).unref()}var oS,HC,xC,GC,qC,FC,vC,iS,n4,ru,BC,to,_d,s4,i4,aS=Ae(()=>{oS=B(vr()),HC=B(ne()),xC=B($());Nn();GC=B(Z()),qC=B(P()),FC=B(J()),vC=100,iS=new Set,n4=(0,FC.convertToMS)(GC.get(qC.CONFIG_PARAMS.STORAGE_MAXTRANSACTIONQUEUETIME))||45e3,to=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),iS.add(this),this.readTxn}useReadTxn(){return this.getReadTxn(),this.readTxn.use(),this.readTxnsUsed++,this.readTxn}doneReadTxn(){this.readTxn&&(this.readTxn.done(),--this.readTxnsUsed===0&&(iS.delete(this),this.readTxn=null))}disregardReadTxn(){--this.readTxnRefCount===0&&this.readTxnsUsed===1&&this.doneReadTxn()}checkOverloaded(){if(ru&&!this.overloadChecked&&performance.now()-BC>n4)throw new HC.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,oS.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 A=T();h?h.push?h.push(A):h=[h,A]:h=A}}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"),u=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,u);s=s||E}else u();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)<vC>>n?u():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 ru||(ru=s,BC=performance.now(),ru.then(()=>{ru=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)+vC/2),t?t.retries=n+1:t={retries:1},this.commit(t)));let l={txnTime:r};if(this.next){let d=this.next?.commit(t);if(d?.then)return d?.then(E=>({txnTime:r,next:E}));l.next=d}return l}abort(){for(;this.readTxnsUsed>0;)this.doneReadTxn();this.open=0,this.writes=[]}},_d=class extends to{static{a(this,"ImmediateTransaction")}_timestamp;addWrite(t){super.addWrite(t),this.commit()}get timestamp(){return this._timestamp||(this._timestamp=(0,oS.getNextMonotonicTime)())}getReadTxn(){}},s4=3e4;a(o4,"startMonitoringTxns");o4()});function Xe(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 to;e.timestamp&&(n.timestamp=e.timestamp),n[Ne]=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 u=n.commit({letItLinger:r?.letItLinger});return u.then?u.then(()=>c):c}function o(c){throw n.abort({}),c}}var kC,ro=Ae(()=>{kC=require("../index");Nn();aS();a(Xe,"transaction");(0,kC._assignPackageExport)("transaction",Xe);Xe.commit=function(e){let t=(e[Ne]||e)?.transaction;if(!t)throw new Error("No active transaction is available to commit");return t.commit()};Xe.abort=function(e){let t=(e[Ne]||e)?.transaction;if(!t)throw new Error("No active transaction is available to abort");return t.abort()}});var jC={};qe(jC,{ResourceBridge:()=>lS});function _S({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 $C(e,t){let r=rs(e),n=_S(e,r);if(!r)throw new Pn.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;Xe(i,()=>new Promise(_=>o=_));let c=e.ids||e.hash_values,u=0;return{[Symbol.asyncIterator](){return{async next(){if(u<c.length){let _=c[u++],l=await r.get({id:_,lazy:s,select:n},i);return l=l&&fd(l),t?{value:{key:_,value:l}}:{value:l}}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||c4,r=hr()[t];if(!r)throw(0,Pn.handleHDBError)(new Error,a4.SCHEMA_NOT_FOUND(t),404);return r[e.table]}function YC(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*KC(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:u}=s;n?.timestamp===c?(n.hash_values.push(o),n.records.push(u)):(n&&(yield n),n={operation:i,user_name:s.user,timestamp:c,hash_values:[o],records:[u]})}n&&(yield n)}var WC,dd,Pn,QC,zC,Un,cS,uS,JC,a4,c4,u4,l4,VC,lS,XC=Ae(()=>{"use strict";WC=B(UC()),dd=B(sa()),Pn=B(ne());Oe();QC=B(Hc()),zC=B(Gc()),Un=B(P()),cS=B(bs()),uS=B(Mn()),JC=B(J());ro();Ed();({HDB_ERROR_MSGS:a4}=Pn.hdb_errors),c4="data",u4=1e4,l4=10,lS=class extends WC.default{static{a(this,"ResourceBridge")}constructor(t){super(t),VC=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,dd.default)(t,"conditions");if(r)throw(0,Pn.handleHDBError)(r,r.message,400,void 0,void 0,!0);let n=rs(t);if(!n)throw new Pn.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:_S(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 Pn.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.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,u)=>(c=Object.assign({},c),delete c[n],r.primaryStore.ifVersion(o,u,()=>r.primaryStore.put(o,c,u)).then(_=>{if(!_){let{value:l,version:d}=r.primaryStore.getEntry(o);return i(o,l,d)}})),"deleteRecord");for(let{key:o,value:c,version:u}of r.primaryStore.getRange({start:!0,versions:!0}))s=i(o,c,u),await new Promise(_=>setImmediate(_));await s}return`successfully deleted ${t.schema}.${t.table}.${t.attribute}`}dropTable(t){rs(t).dropTable()}createSchema(t){return nu({database:t.schema,table:null}),cS.signalSchemaChange(new uS.SchemaEventMsg(process.pid,Un.OPERATIONS_ENUM.CREATE_SCHEMA,t.schema))}async dropSchema(t){await dS(t.schema),cS.signalSchemaChange(new uS.SchemaEventMsg(process.pid,Un.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,VC.upsertRecords(t)}async upsertRecords(t){let{schema_table:r,attributes:n}=(0,QC.default)(t);(0,zC.default)(t,n,r.primaryKey);let s,i=hr()[t.schema][t.table],o={user:t.hdb_user,expiresAt:t.expiresAt};return Xe(o,async c=>{if(!i.schemaDefined){s=[];for(let l of n)i.attributes.find(E=>E.name==l)||s.push(l);s.length>0&&await i.addAttributes(s.map(l=>({name:l,indexed:!0})))}let u=[],_=[];for(let l of t.records){let d=await i.get(l[i.primaryKey],o);if(t.requires_existing&&!d||t.requires_no_existing&&d){_.push(l[i.primaryKey]);continue}d&&(d=fd(d));for(let E in l)if(Object.prototype.hasOwnProperty.call(l,E)){let f=l[E];if(typeof f=="function")try{let h=f([[d]]);Array.isArray(h)&&(f=h[0].func_val,l[E]=f)}catch(h){throw h.message+="Trying to set key "+E+" on object"+JSON.stringify(l),h}}if(d)for(let E in d)Object.prototype.hasOwnProperty.call(l,E)||(l[E]=d[E]);await i.put(l,o),u.push(l[i.primaryKey])}return{txn_time:c.timestamp,written_hashes:u,new_attributes:s,skipped_hashes:_}})}async deleteRecords(t){let r=hr()[t.schema][t.table],n={user:t.hdb_user};return Xe(n,async s=>{let i=t.hash_values||t.records.map(u=>u[r.primaryKey]),o=[],c=[];for(let u of i)await r.delete(u,n)?o.push(u):c.push(u);return YC(o,c,s.timestamp)})}async deleteRecordsBefore(t){let r=hr()[t.schema][t.table];if(!r.createdTimeProperty)throw new Pn.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:Un.VALUE_SEARCH_COMPARATORS.LESS}]}),s=!1,i=[],o=[],c=0,u=[],_=a(async()=>{let l=await this.deleteRecords({schema:t.schema,table:t.table,hash_values:u});i.push(...l.deleted_hashes),o.push(...l.skipped_hashes),await(0,JC.async_set_timeout)(l4),u=[],s=!0},"chunkDelete");for await(let l of n)u.push(l[r.primaryKey]),c++,c%u4===0&&await _();return u.length>0&&await _(),s?YC(i,o,void 0):{message:"No records found to delete"}}searchByHash(t){t.select!==void 0&&(t.get_attributes=t.select);let r=(0,dd.default)(t,"hashes");if(r)throw r;return $C(t)}async getDataByHash(t){let r=new Map;t._returnKeyValue=!0;for await(let{key:n,value:s}of $C(t,!0))r.set(n,s);return r}searchByValue(t,r){if(r&&Un.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,dd.default)(t,"value");if(n)throw n;let s=rs(t);if(!s)throw new Pn.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===Un.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:_S(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 Un.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 Un.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.USERNAME:let s=t.search_values;for await(let i of KC(r))s.includes(i.user_name)&&(n[i.user_name]||(n[i.user_name]=[])).push(i);return n;default:return KC(r,t.search_values?.[0],t.search_values?.[1])}}};a(_S,"getSelect");a($C,"getRecords");a(rs,"getTable");a(YC,"createDeleteResponse");a(KC,"groupRecordsInHistory")});var Cn=g((Qde,ZC)=>{"use strict";var{ResourceBridge:_4}=(XC(),ie(jC)),d4=Z();d4.initSync();var hd;function f4(){return hd||(hd=new _4,hd)}a(f4,"getBridge");ZC.exports=f4()});var nD=g((Jde,rD)=>{"use strict";var eD=require("lodash"),su=require("mathjs"),E4=require("jsonata"),tD=J();rD.exports={distinct_array:e=>Array.isArray(e)&&e.length>1?eD.uniqWith(e,eD.isEqual):e,searchJSON:h4,mad:iu.bind(null,su.mad),mean:iu.bind(null,su.mean),mode:iu.bind(null,su.mode),prod:iu.bind(null,su.prod),median:iu.bind(null,su.median)};function iu(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(iu,"aggregateFunction");function h4(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(tD.isEmpty(this.__ala__.res)&&(this.__ala__.res={}),tD.isEmpty(this.__ala__.res[r])){let n=E4(e);this.__ala__.res[r]=n}return this.__ala__.res[r].evaluate(t)}a(h4,"searchJSON")});var iD=g((Xde,sD)=>{"use strict";var Tt=require("moment"),fS="YYYY-MM-DDTHH:mm:ss.SSSZZ";Tt.suppressDeprecationWarnings=!0;sD.exports={current_date:()=>Tt().utc().format("YYYY-MM-DD"),current_time:()=>Tt().utc().format("HH:mm:ss.SSS"),extract:(e,t)=>{switch(t.toLowerCase()){case"year":return Tt(e).utc().format("YYYY");case"month":return Tt(e).utc().format("MM");case"day":return Tt(e).utc().format("DD");case"hour":return Tt(e).utc().format("HH");case"minute":return Tt(e).utc().format("mm");case"second":return Tt(e).utc().format("ss");case"millisecond":return Tt(e).utc().format("SSS");default:break}},date:e=>Tt(e).utc().format(fS),date_format:(e,t)=>Tt(e).utc().format(t),date_add:(e,t,r)=>Tt(e).utc().add(t,r).valueOf(),date_sub:(e,t,r)=>Tt(e).utc().subtract(t,r).valueOf(),date_diff:(e,t,r)=>{let n=Tt(e).utc(),s=Tt(t).utc();return r?n.diff(s,r,!0):n.diff(s)},now:()=>Tt().utc().valueOf(),get_server_time:()=>Tt().format(fS),offset_utc:(e,t)=>Tt(e).utc().utcOffset(t).format(fS)}});var uD=g((Zde,cD)=>{"use strict";var m4=require("@turf/area"),p4=require("@turf/length"),S4=require("@turf/circle"),T4=require("@turf/difference"),g4=require("@turf/distance"),R4=require("@turf/boolean-contains"),A4=require("@turf/boolean-equal"),O4=require("@turf/boolean-disjoint"),b4=require("@turf/helpers"),oD=P(),ge=J(),Is=$();cD.exports={geoArea:y4,geoLength:N4,geoCircle:I4,geoDifference:w4,geoDistance:aD,geoNear:C4,geoContains:D4,geoEqual:L4,geoCrosses:M4,geoConvert:P4};function y4(e){if(ge.isEmpty(e))return NaN;typeof e=="string"&&(e=ge.autoCastJSON(e));try{return m4.default(e)}catch(t){return Is.trace(t,e),NaN}}a(y4,"geoArea");function N4(e,t){if(ge.isEmpty(e))return NaN;typeof e=="string"&&(e=ge.autoCastJSON(e));try{return p4.default(e,{units:t||"kilometers"})}catch(r){return Is.trace(r,e),NaN}}a(N4,"geoLength");function I4(e,t,r){if(ge.isEmpty(e))return NaN;if(ge.isEmpty(t))return NaN;typeof e=="string"&&(e=ge.autoCastJSON(e));try{return S4.default(e,t,{units:r||"kilometers"})}catch(n){return Is.trace(n,e,t),NaN}}a(I4,"geoCircle");function w4(e,t){if(ge.isEmpty(e))return NaN;if(ge.isEmpty(t))return NaN;typeof e=="string"&&(e=ge.autoCastJSON(e)),typeof t=="string"&&(t=ge.autoCastJSON(t));try{return T4(e,t)}catch(r){return Is.trace(r,e,t),NaN}}a(w4,"geoDifference");function aD(e,t,r){if(ge.isEmpty(e))return NaN;if(ge.isEmpty(t))return NaN;typeof e=="string"&&(e=ge.autoCastJSON(e)),typeof t=="string"&&(t=ge.autoCastJSON(t));try{return g4.default(e,t,{units:r||"kilometers"})}catch(n){return Is.trace(n,e,t),NaN}}a(aD,"geoDistance");function C4(e,t,r,n){if(ge.isEmpty(e)||ge.isEmpty(t))return!1;if(ge.isEmpty(r))throw new Error("distance is required");if(typeof e=="string"&&(e=ge.autoCastJSON(e)),typeof t=="string"&&(t=ge.autoCastJSON(t)),isNaN(r))throw new Error("distance must be a number");try{return aD(e,t,n)<=r}catch(s){return Is.trace(s,e,t),!1}}a(C4,"geoNear");function D4(e,t){if(ge.isEmpty(e)||ge.isEmpty(t)||e.coordinates&&e.coordinates.includes?.(null)||t.coordinates&&t.coordinates.includes?.(null))return!1;typeof e=="string"&&(e=ge.autoCastJSON(e)),typeof t=="string"&&(t=ge.autoCastJSON(t));try{return R4.default(e,t)}catch(r){return Is.trace(r,e,t),!1}}a(D4,"geoContains");function L4(e,t){if(ge.isEmpty(e)||ge.isEmpty(t)||e.coordinates&&e.coordinates.includes?.(null)||t.coordinates&&t.coordinates.includes?.(null))return!1;typeof e=="string"&&(e=ge.autoCastJSON(e)),typeof t=="string"&&(t=ge.autoCastJSON(t));try{return A4.default(e,t)}catch(r){return Is.trace(r,e,t),!1}}a(L4,"geoEqual");function M4(e,t){if(ge.isEmpty(e)||ge.isEmpty(t)||e.coordinates&&e.coordinates.includes?.(null)||t.coordinates&&t.coordinates.includes?.(null))return!1;typeof e=="string"&&(e=ge.autoCastJSON(e)),typeof t=="string"&&(t=ge.autoCastJSON(t));try{return!O4.default(e,t)}catch(r){return Is.trace(r,e,t),!1}}a(M4,"geoCrosses");function P4(e,t,r){if(ge.isEmptyOrZeroLength(e))throw new Error("coordinates is required");if(ge.isEmpty(t))throw new Error("geo_type is required");if(ge.isEmpty(oD.GEO_CONVERSION_ENUM[t]))throw new Error(`geo_type of ${t} is invalid please use one of the following types: ${Object.keys(oD.GEO_CONVERSION_ENUM).join(",")}`);return typeof e=="string"&&(e=ge.autoCastJSON(e)),b4[t](e,r)}a(P4,"geoConvert")});var md=g((tfe,lD)=>{var no=nD(),Kr=iD(),ns=uD();lD.exports=e=>{e.aggr.mad=e.aggr.MAD=no.mad,e.aggr.mean=e.aggr.MEAN=no.mean,e.aggr.mode=e.aggr.MODE=no.mode,e.aggr.prod=e.aggr.PROD=no.prod,e.aggr.median=e.aggr.MEDIAN=no.median,e.fn.distinct_array=e.fn.DISTINCT_ARRAY=no.distinct_array,e.fn.search_json=e.fn.SEARCH_JSON=no.searchJSON,e.fn.__ala__=e,e.fn.current_date=e.fn.CURRENT_DATE=Kr.current_date,e.fn.current_time=e.fn.CURRENT_TIME=Kr.current_time,e.fn.extract=e.fn.EXTRACT=Kr.extract,e.fn.date=e.fn.DATE=Kr.date,e.fn.date_format=e.fn.DATE_FORMAT=Kr.date_format,e.fn.date_add=e.fn.DATE_ADD=Kr.date_add,e.fn.date_sub=e.fn.DATE_SUB=Kr.date_sub,e.fn.date_diff=e.fn.DATE_DIFF=e.fn.datediff=e.fn.DATEDIFF=Kr.date_diff,e.fn.now=e.fn.NOW=Kr.now,e.fn.offset_utc=e.fn.OFFSET_UTC=Kr.offset_utc,e.fn.get_server_time=e.fn.GET_SERVER_TIME=Kr.get_server_time,e.fn.getdate=e.fn.GETDATE=Kr.now,e.fn.current_timestamp=e.fn.CURRENT_TIMESTAMP=Kr.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 ED=g((rfe,fD)=>{"use strict";var ou=require("lodash"),mr=require("alasql");mr.options.cache=!1;var U4=md(),_D=require("clone"),pd=require("recursive-iterator"),_e=$(),De=J(),ca=Cn(),v4=P(),{hdb_errors:B4}=ne(),{getDatabases:dD}=(Oe(),ie(Fe)),H4="IS NULL",vn="There was a problem performing this search. Please check the logs and try again.";U4(mr);var ES=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(vn)}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(vn)}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(vn)}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(vn)}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(vn)}}_getColumns(){let t=new pd(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(_D(r)))}_getTables(){let t=[];this.all_table_attributes.forEach(r=>{t.push(r.table)}),this.tables=ou.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=dD()[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 pd(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 mr.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 mr.yy.LogicValue({value:i}):n instanceof mr.yy.StringValue&&De.autoCasterIsNumberCheck(i.toString())&&(r.right[s]=new mr.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 pd(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(v4.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 u=Array.isArray(r.right)?r.right:r.left;for(let _=0;_<u.length;_++)if(u[_].value)n.add(u[_].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&&ou.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 mr.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(_D(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(H4)>-1&&this.tables.forEach(s=>{let i={columnid:dD()[s.databaseid][s.tableid].primaryKey,tableid:s.tableid};this._addFetchColumns([i])}),this.statement.order&&(this._updateOrderByToAliases(),this._addNonAggregatorsToFetchColumns()),this.fetch_attributes=ou.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]},u=!1,_=[s.table.databaseid,s.table.tableid,s.attribute].join("/");if(s.attribute===o&&(u=!0),!De.isEmpty(this.exact_search_values[_])&&!this.exact_search_values[_].ignore&&!De.isEmptyOrZeroLength(this.exact_search_values[_].values))if(u)try{c.hash_values=Array.from(this.exact_search_values[_].values);let l=await ca.getDataByHash(c);for(let d of c.hash_values)l.get(d)&&!this.data[i].__merged_data[d]&&(this.data[i].__merged_data[d]=[...n[i]],this._setMergedHashAttribute(i,d))}catch(l){throw _e.error("Error thrown from getDataByHash function in SQLSearch class method getFetchAttributeValues exact match."),_e.error(l),new Error(vn)}else try{c.search_attribute=s.attribute,await Promise.all(Array.from(this.exact_search_values[_].values).map(async l=>{let d=Object.assign({},c);d.search_value=l;let E=await ca.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(l){throw _e.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues exact match."),_e.error(l),new Error(vn)}else if(!De.isEmpty(this.comparator_search_values[_])&&!this.comparator_search_values[_].ignore&&!De.isEmptyOrZeroLength(this.comparator_search_values[_].comparators))try{let l=this.comparator_search_values[_].comparators;for(let d=0,E=l.length;d<E;d++){let f=l[d];c.search_attribute=f.attribute,c.search_value=f.search_value;let h=await ca.getDataByValue(c,f.operation);if(u)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(l){throw _e.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues comparator search values."),_e.error(l),new Error(vn)}else try{c.search_attribute=s.attribute,c.search_value="*";let l=await ca.getDataByValue(c);if(u)for(let[d]of l)this.data[i].__merged_data[d]||(this.data[i].__merged_data[d]=[...n[i]],this._setMergedHashAttribute(i,d));else for(let[d,E]of l)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(l){throw _e.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues no comparator search values."),_e.error(l),new Error(vn)}}}_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 mr.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 mr.yy.Column;s.columnid=n.as,s.columnid_orig=n.as_orig,t.expression=s}else{t.initial_select_column=Object.assign(new mr.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 mr.yy.FuncValue:new mr.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 u=this.statement.where?"WHERE "+this.statement.where:"";u=u.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 l="",d="";!this.has_aggregator&&!this.statement.group&&!this.has_ordinal&&!this.statement.joins&&(l=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(" ")} ${u} ${_} ${l} ${d}`,h=this._convertColumnsToIndexes(f,s);E=await mr.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=ou.difference(h,[...f.keys].map(S=>S.toString()));for(let S=0,T=p.length;S<T;S++){let A=p[S];delete this.data[`${f.schema}_${f.table}`].__merged_data[A]}})}return{existing_attributes:c,joined_length:E?E.length:0}}async _getFinalAttributeData(t,r){if(r===0)return;let n=[],s=new pd(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=ou.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(vn)}}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 l in i)o.push(i[l][0]);this.data[n].__merged_attributes.push(...s.columns);let c={schema:s.schema,table:s.table,hash_values:o,get_attributes:s.columns},u=await ca.getDataByHash(c),_=s.columns.length;for(let l=0,d=o.length;l<d;l++){let E=o[l],f=u.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,u=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===u}).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 mr.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(B4.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 u=s[i],_=new RegExp(`${u}.\`${o}\``,"g"),l=`${u}.[${c}]`;n=n.replace(_,l)});for(let i in this.data)this.data[i].__merged_attributes.forEach((o,c)=>{let u=new RegExp(`\`${o}\``,"g"),_=`[${c}]`;n=n.replace(u,_)});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 ca.getDataByValue(i);for(let[c,u]of o)this.data[s].__merged_data[c]||(u[n.attribute]===void 0&&(u[n.attribute]=null),this.data[s].__merged_data[c]=Object.assign({},r[s])),this.data[s].__merged_data[c][t[n.attribute]]=u[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(vn)}}return Object.values(Object.values(this.data)[0].__merged_data)}};fD.exports=ES});var Gr=g((sfe,hD)=>{"use strict";var x4=$b();hD.exports={searchByConditions:q4,searchByHash:F4,searchByValue:k4,search:V4};var hS=Cn(),{transformReq:mS}=J(),G4=ED();async function q4(e){return mS(e),hS.searchByConditions(e)}a(q4,"searchByConditions");async function F4(e){mS(e),e.ids&&(e.hash_values=e.ids);let t=[];for await(let r of hS.searchByHash(e))r&&t.push(r);return t}a(F4,"searchByHash");async function k4(e){mS(e),e.hasOwnProperty("desc")===!0&&(e.reverse=e.desc);let t=[];for await(let r of hS.searchByValue(e))t.push(r);return t}a(k4,"searchByValue");function V4(e,t){try{let r=new x4(e);r.validate(),new G4(r.statement,r.attributes).search().then(s=>{t(null,s)}).catch(s=>{t(s,null)})}catch(r){return t(r)}}a(V4,"search")});var Sd=g((ofe,mD)=>{"use strict";var $4=Cn();mD.exports={writeTransaction:Y4};function Y4(e,t,r){return $4.writeTransaction(e,t,r)}a(Y4,"writeTransaction")});var gD=g((ufe,TD)=>{"use strict";var K4=Gr(),W4=Os(),pD=$(),Q4=qr(),cfe=Sd(),z4=require("clone"),SS=require("alasql"),J4=md(),SD=require("util"),j4=SD.promisify(W4.getTableSchema),X4=SD.promisify(K4.search),Z4=P(),pS=J();J4(SS);TD.exports={update:t3};var e3="There was a problem performing this update. Please check the logs and try again.";async function t3({statement:e,hdb_user:t}){let r=await j4(e.table.databaseid,e.table.tableid),n=r3(e.columns);pS.backtickASTSchemaItems(e);let{table:s,where:i}=e,o=z4(s),c=pS.isEmpty(i)?"":` WHERE ${i.toString()}`,u=`SELECT ${r.hash_attribute} FROM ${s.toString()} ${c}`,_=SS.parse(u).statements[0],l=await X4(_),d=n3(n,l);return s3(o,d,t)}a(t3,"update");function r3(e){try{let t={};return e.forEach(r=>{"value"in r.expression?t[r.column.columnid]=r.expression.value??null:t[r.column.columnid]=SS.compile(`SELECT ${r.expression.toString()} AS [${Z4.FUNC_VAL}] FROM ?`)}),t}catch(t){throw pD.error(t),new Error(e3)}}a(r3,"createUpdateRecord");function n3(e,t){return pS.isEmptyOrZeroLength(t)?[]:t.map(r=>Object.assign(r,e))}a(n3,"buildUpdateRecords");async function s3(e,t,r){let n={operation:"update",schema:e.databaseid_orig,table:e.tableid_orig,records:t,hdb_user:r},s=await Q4.update(n);try{delete s.new_attributes,delete s.txn_time}catch(i){pD.error(`Error delete new_attributes from update response: ${i}`)}return s}a(s3,"updateRecords")});var AD=g((ffe,RD)=>{var i3=require("alasql"),o3=Gr(),a3=$(),c3=Cn(),gS=require("util"),TS=J(),u3=P(),l3=Os(),_fe=Sd(),dfe=qr(),_3="record",d3="successfully deleted",f3=gS.callbackify(p3),E3=gS.promisify(o3.search),h3=gS.promisify(l3.getTableSchema);RD.exports={convertDelete:f3};function m3(e){return`${e.deleted_hashes.length} ${_3}${e.deleted_hashes.length===1?"":"s"} ${d3}`}a(m3,"generateReturnMessage");async function p3({statement:e,hdb_user:t}){let r=await h3(e.table.databaseid,e.table.tableid);TS.backtickASTSchemaItems(e);let{table:n,where:s}=e,i=TS.isEmpty(s)?"":` WHERE ${s.toString()}`,o=`SELECT ${r.hash_attribute} FROM ${n.toString()} ${i}`,c=i3.parse(o).statements[0],u={operation:u3.OPERATIONS_ENUM.DELETE,schema:n.databaseid_orig,table:n.tableid_orig,hdb_user:t};try{u.records=await E3(c);let _=await c3.deleteRecords(u);return TS.isEmptyOrZeroLength(_.message)&&(_.message=m3(_)),delete _.txn_time,_}catch(_){throw a3.error(_),_.hdb_code?_.message:_}}a(p3,"convertDelete")});var ID=g((hfe,ND)=>{"use strict";var S3=As(),{hdb_errors:OD}=ne(),{getDatabases:bD}=(Oe(),ie(Fe));ND.exports={checkSchemaExists:yD,checkSchemaTableExists:T3,schema_describe:S3};async function yD(e){if(!bD()[e])return OD.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}a(yD,"checkSchemaExists");async function T3(e,t){let r=await yD(e);if(r)return r;if(!bD()[e][t])return OD.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(T3,"checkSchemaTableExists")});var au=g((pfe,g3)=>{g3.exports={name:"harperdb",version:"4.3.18",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","cloud","enterprise","Fastify","NATS"],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.535.0","@aws-sdk/lib-storage":"3.535.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.12",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.3.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.16.0",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 du={};qe(du,{addAnalyticsListener:()=>_u,recordAction:()=>pr,recordActionBinary:()=>Wr,setAnalyticsEnabled:()=>R3});function R3(e){BD=e}function pr(e,t,r,n,s){if(!BD)return;let i=t+(r?"-"+r:"");n!==void 0&&(i+="-"+n),s!==void 0&&(i+="-"+s);let o=Rd.get(i);if(o)if(typeof e=="number"){let c=o.values,u=c.index++;if(u>=c.length){let _=c;o.values=c=new Float32Array(u*2),c.set(_),c.index=u+1}c[u]=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},Rd.set(i,o)}Td||A3()}function Wr(e,t,r,n,s){pr(!!e,t,r,n,s)}function _u(e){GD.push(e)}function A3(){Td=performance.now(),setTimeout(async()=>{let e=performance.now()-Td;Td=0;let t=[],r={time:Date.now(),period:e,threadId:so.threadId,metrics:t};for(let[s,i]of Rd){if(i.values){let o=i.values.subarray(0,i.values.index);o.sort();let c=o.length,u=0,_=[],l;for(let d of qD){let E=Math.floor(c*d),f=o[E-1];if(E>u){let h=E-u;if(f===l){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),l=f;u=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 FD()}let n=process.memoryUsage();t.push({metric:"memory",threadId:so.threadId,byThread:!0,...n});for(let s of GD)s(t);Rd=new Map,so.parentPort?so.parentPort.postMessage({type:xD,report:r}):$D({report:r})},HD).unref()}async function O3(e,t=6e4){let r=OS(),n=kD(),s=new Promise(p=>{let S=performance.now();setImmediate(()=>{let T=performance.now();T-S>5e3&&(0,cu.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,cu.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,u=new Map,_=[],l;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;l=p;let{metrics:T,threadId:A}=S;for(let R of T||[]){let{path:C,method:x,type:v,metric:k,count:M,total:Q,distribution:j,threads:z,...ae}=R;M||(M=1);let ue=k+(C?"-"+C:"");x!==void 0&&(ue+="-"+x),v!==void 0&&(ue+="-"+v);let de=c.get(ue);if(de){if(de.threads){let Ee=de.threads[A];if(Ee)de=Ee;else{de.threads[A]=Object.assign({},ae);continue}}de.count||(de.count=1);let xe=de.count;for(let Ee in ae){let Pt=ae[Ee];typeof Pt=="number"&&(de[Ee]=(de[Ee]*xe+Pt*M)/(xe+M))}de.count+=M,Q>=0&&(de.total+=Q,de.ratio=de.total/de.count)}else de=Object.assign({period:t},R),delete de.distribution,c.set(ue,de),de.byThread&&(de.threads=[],de.threads[A]=Object.assign({},ae),_.push(de));if(j){j=j.map(Ee=>typeof Ee=="number"?{value:Ee,count:1}:Ee);let xe=u.get(ue);xe?xe.push(...j):u.set(ue,j)}}await FD()}for(let p of _){let{path:S,method:T,type:A,metric:R,count:C,total:x,distribution:v,threads:k,...M}=p;k=k.filter(Q=>Q);for(let Q in M){if(typeof p[Q]!="number")continue;let j=0;for(let z of k){let ae=z[Q];typeof ae=="number"&&(j+=ae)}p[Q]=j}p.count=k.length,delete p.threads,delete p.byThread}for(let[p,S]of u){let T=c.get(p);S.sort((Ee,Pt)=>Ee.value>Pt.value?1:-1);let A=T.count-1,R=[],C=0,x=0,v;for(let Ee of qD){let Pt=A*Ee;for(;C<Pt;)v=S[x++],C+=v.count,x===1&&C--;let zl=S[x>1?x-2:0];v||(v=S[0]),R.push(v.value-(v.value-zl.value)*(C-Pt)/v.count)}let[k,M,Q,j,z,ae,ue,de,xe]=R;Object.assign(T,{p1:k,p10:M,p25:Q,median:j,p75:z,p90:ae,p95:ue,p99:de,p999:xe})}let d;for(let[p,S]of c)S.id=(0,gd.getNextMonotonicTime)(),S.time=l,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,gd.getNextMonotonicTime)(),S={id:p,metric:"main-thread-utilization",idle:f-wD,active:h-CD,taskQueueLatency:await s,time:E,...process.memoryUsage()};n.primaryStore.put(p,S,{append:!0}).then(T=>{T||n.primaryStore.put(p,S)})}wD=f,CD=h}async function DD(e,t){let r=Date.now()-t;for(let n of e.primaryStore.getKeys({start:!1,end:r}))e.primaryStore.remove(n)}function OS(){return LD||(LD=dt({table:"hdb_raw_analytics",database:"system",audit:!1,trackDeletes:!1,attributes:[{name:"id",isPrimaryKey:!0},{name:"action"},{name:"metrics"}]}))}function kD(){return MD||(MD=dt({table:"hdb_analytics",database:"system",audit:!1,trackDeletes:!1,attributes:[{name:"id",isPrimaryKey:!0},{name:"metric"},{name:"path"},{name:"method"},{name:"type"}]}))}function N3(){VD=!0;let e=(0,lu.get)(AS.CONFIG_PARAMS.ANALYTICS_AGGREGATEPERIOD)*1e3;e&&setInterval(async()=>{await O3(HD,e),await DD(OS(),b3),await DD(kD(),y3)},Math.min(e/2,2147483647)).unref()}function $D(e,t){let r=e.report;r.threadId=t?.threadId||so.threadId;for(let n of r.metrics)n.metric==="bytes-sent"&&(PD+=n.mean*n.count);r.totalBytesProcessed=PD,t&&(r.metrics.push({metric:"utilization",...t.performance.eventLoopUtilization(UD.get(t))}),UD.set(t,t.performance.eventLoopUtilization())),r.id=(0,gd.getNextMonotonicTime)(),OS().primaryStore.put(r.id,r),VD||N3(),I3&&(YD=C3(r))}async function C3(e){if(await YD,!_i){let r=(0,uu.dirname)((0,cu.getLogFilePath)());try{_i=await(0,RS.open)((0,uu.join)(r,"analytics.log"),"r+")}catch{_i=await(0,RS.open)((0,uu.join)(r,"analytics.log"),"w+")}}let t=(await _i.stat()).size;if(t>w3){let r=Buffer.alloc(t);await _i.read(r,{position:0}),r=r.subarray(r.indexOf(10,r.length/2)+1),await _i.write(r,{position:0}),await _i.truncate(r.length),t=r.length}await _i.write(JSON.stringify(e)+`
|
|
8
|
-
`,t)}var so,
|
|
6
|
+
`)},XY="certificate.pem",ZY="privateKey.pem",eK="ca.pem";DN.exports={CERTIFICATE_VALUES:jY,CERTIFICATE_PEM_NAME:XY,PRIVATEKEY_PEM_NAME:ZY,CA_PEM_NAME:eK}});var rp=g((lle,xN)=>{"use strict";var vN=require("fs-extra"),oe=require("joi"),tK=require("os"),{boolean:ye,string:er,number:rt,array:Y_}=oe.types(),{totalmem:MN}=require("os"),Wi=require("path"),rK=$(),K_=z(),ule=LN(),PN=P(),nK=Xe(),UN="log",sK="components",iK="Invalid logging.rotation.maxSize unit. Available units are G, M or K",oK="Invalid logging.rotation.interval unit. Available units are D, H or M (minutes)",aK="Invalid logging.rotation.maxSize value. Value should be a number followed by unit e.g. '10M'",cK="Invalid logging.rotation.interval value. Value should be a number followed by unit e.g. '10D'",uK="rootPath config parameter is undefined",lK="clustering.enabled config parameter is undefined",Qi=rt.min(0).required(),W_=Y_.items({host:er.required(),port:Qi}).empty(null),Xn,BN=!1;xN.exports={configValidator:_K,routesValidator:pK,route_constraints:W_};function _K(e,t=!1){if(BN=t,Xn=e.rootPath,K_.isEmpty(Xn))throw uK;let r=ye.required(),n=rt.min(0).max(1e3).empty(null).default(mK),s=er.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path").empty(null).default(Vc),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(Vc),u=oe.custom(fK).empty(null).default(Vc),_=e.clustering?.enabled;if(K_.isEmpty(_))throw lK;let l=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:Qi,routes:W_}).required()}).required(),leafNodes:oe.object({network:oe.object({port:Qi}).required()}).required(),network:oe.object({port:Qi}).required()}).required(),leafServer:oe.object({network:oe.object({port:Qi,routes:W_}).required(),streams:oe.object({maxAge:rt.min(120).allow(null).optional(),maxBytes:rt.min(1).allow(null).optional(),maxMsgs:rt.min(1).allow(null).optional(),path:c}).required()}).required(),logLevel:oe.valid("error","warn","info","debug","trace"),nodeName:o,republishMessages:ye.optional(),databaseLevel:ye.optional(),tls:oe.object({certificate:i,certificateAuthority:i,privateKey:i,insecure:ye.required(),verify:ye.optional()}),user:er.optional().empty(null)}).required():d=oe.object({enabled:r,tls:oe.object({certificate:i,certificateAuthority:i,privateKey:i,insecure:ye.required()})}).required(),oe.object({authentication:oe.object({authorizeLocal:ye,cacheTTL:rt.required(),enableSessions:ye}),analytics:oe.object({aggregatePeriod:rt}),componentsRoot:s.optional(),clustering:d,localStudio:oe.object({enabled:r}).required(),logging:oe.object({auditAuthEvents:oe.object({logFailed:ye,logSuccessful:ye}),file:ye.required(),level:oe.valid("notify","fatal","error","warn","info","debug","trace"),rotation:oe.object({enabled:ye.optional(),compress:ye.optional(),interval:er.custom(hK).optional().empty(null),maxSize:er.custom(EK).optional().empty(null),path:er.optional().empty(null).default(Vc)}).required(),root:s,stdStreams:ye.required(),auditLog:ye.required()}).required(),operationsApi:oe.object({network:oe.object({cors:ye.optional(),corsAccessList:Y_.optional(),headersTimeout:rt.min(1).optional(),keepAliveTimeout:rt.min(1).optional(),port:rt.optional().empty(null),domainSocket:oe.optional().empty("hdb/operations-server").default(Vc),securePort:rt.optional().empty(null),timeout:rt.min(1).optional()}).optional(),tls:oe.alternatives([oe.array().items(l),l])}).required(),rootPath:er.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path").required(),mqtt:oe.object({network:oe.object({port:Qi,securePort:Qi,mtls:oe.alternatives([ye.optional(),oe.object({user:er.optional(),certificateAuthority:i,required:ye.optional()})])}).required(),webSocket:ye.optional(),requireAuthentication:ye.optional()}),http:oe.object({compressionThreshold:rt.optional(),cors:ye.optional(),corsAccessList:Y_.optional(),headersTimeout:rt.min(1).optional(),port:rt.min(0).optional().empty(null),securePort:rt.min(0).optional().empty(null),maxHeaderSize:rt.optional(),mtls:oe.alternatives([ye.optional(),oe.object({user:er.optional(),certificateAuthority:i,required:ye.optional()})]),threadRange:oe.alternatives([Y_.optional(),er.optional()])}).required(),threads:oe.alternatives(n.optional(),oe.object({count:n.optional(),debug:oe.alternatives(ye.optional(),oe.object({startingPort:rt.min(1).optional(),host:er.optional(),waitForDebugger:ye.optional()})),maxHeapMemory:rt.min(0).optional()})),storage:oe.object({writeAsync:ye.required(),overlappingSync:ye.optional(),caching:ye.optional(),compression:oe.alternatives([ye.optional(),oe.object({dictionary:er.optional(),threshold:rt.optional()})]),compactOnStart:ye.optional(),compactOnStartKeepBackup:ye.optional(),noReadAhead:ye.optional(),path:u,prefetchWrites:ye.optional(),maxFreeSpaceToLoad:rt.optional(),maxFreeSpaceToRetain:rt.optional()}).required(),ignoreScripts:ye.optional(),tls:oe.alternatives([oe.array().items(l),l])}).validate(e,{allowUnknown:!0,abortEarly:!1,errors:{wrap:{label:"'"}}})}a(_K,"configValidator");function dK(e){return BN||vN.existsSync(e)?null:`Specified path ${e} does not exist.`}a(dK,"doesPathExist");function fK(e,t){oe.assert(e,er.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path"));let r=dK(e);if(r)return t.message(r)}a(fK,"validatePath");function EK(e,t){let r=e.slice(-1);if(r!=="G"&&r!=="M"&&r!=="K")return t.message(iK);let n=e.slice(0,-1);return isNaN(parseInt(n))?t.message(aK):e}a(EK,"validateRotationMaxSize");function hK(e,t){let r=e.slice(-1);if(r!=="D"&&r!=="H"&&r!=="M")return t.message(oK);let n=e.slice(0,-1);return isNaN(parseInt(n))?t.message(cK):e}a(hK,"validateRotationInterval");function mK(e,t){let r=t.state.path.join("."),n=tK.cpus().length,s=n-1;s<=2&&(s=2);let i=process.constrainedMemory?.()||MN();return i=Math.round(Math.min(i,MN())/1e6),s=Math.max(Math.min(s,Math.round((i-750)/300)),1),rK.info(`Detected ${n} cores and ${i}MB on this machine, defaulting ${r} to ${s}`),s}a(mK,"setDefaultThreads");function Vc(e,t){let r=t.state.path.join(".");if(!K_.isEmpty(t.original)&&r!=="operationsApi.network.domainSocket")return t.original;if(K_.isEmpty(Xn))throw new Error(`Error setting default root for: ${r}. HDB root is not defined`);switch(r){case"componentsRoot":return Wi.join(Xn,sK);case"logging.root":return Wi.join(Xn,UN);case"clustering.leafServer.streams.path":return Wi.join(Xn,"clustering","leaf");case"storage.path":let n=Wi.join(Xn,PN.LEGACY_DATABASES_DIR_NAME);return vN.existsSync(n)?n:Wi.join(Xn,PN.DATABASES_DIR_NAME);case"logging.rotation.path":return Wi.join(Xn,UN);case"operationsApi.network.domainSocket":return r==null?null:Wi.join(Xn,"operations-server");default:throw new Error(`Error setting default root for config parameter: ${r}. Unrecognized config parameter`)}}a(Vc,"setDefaultRoot");function pK(e){let t=oe.object({routes:W_});return nK.validateBySchema({routes:e},t)}a(pK,"routesValidator")});var Er=g((fle,KN)=>{"use strict";var kr=P(),Bt=z(),It=$(),{configValidator:SK,routesValidator:HN}=rp(),fr=require("fs-extra"),TK=require("yaml"),Dn=require("path"),gK=require("is-number"),qN=require("properties-reader"),RK=require("lodash"),{handleHDBError:AK}=ne(),{HTTP_STATUS_CODES:OK,HDB_ERROR_MSGS:Q_}=Ur(),dle=require("minimist"),{server:bK}=(lr(),ie(xi)),{DATABASES_PARAM_CONFIG:$c,CONFIG_PARAMS:Fr,CONFIG_PARAM_MAP:Ln}=kr,yK="Unable to get config value because config is uninitialized",NK="Config successfully initialized",IK="Error backing up config file",wK="Empty parameter sent to getConfigValue",FN=Dn.join(kr.PACKAGE_ROOT,"config","yaml",kr.HDB_DEFAULT_CONFIG_FILE),CK="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"},z_,wt,J_;KN.exports={createConfigFile:DK,getDefaultConfig:LK,getConfigValue:VN,initConfig:sp,flattenConfig:Qo,updateConfigValue:$N,updateConfigObject:PK,getConfiguration:BK,setConfiguration:xK,readConfigFile:op,getClusteringRoutes:HK,initOldConfig:YN,getConfigFromFile:GK,getConfigFilePath:zi,addConfig:qK,deleteConfigFromFile:FK,getConfigObj:kK};function DK(e,t=!1){let r=ai(FN);z_=Qo(r.toJSON());let n;for(let c in e){let u=Ln[c.toLowerCase()];if(u===Fr.DATABASES){Array.isArray(e[c])?n=e[c]:n=Object.keys(e[c]).map(_=>({[_]:e[c][_]}));continue}if(!u&&(c.endsWith("_package")||c.endsWith("_port"))&&(u=c),u!==void 0){let _=u.split("_"),l=np(u,e[c]);u==="rootPath"&&l?.endsWith("/")&&(l=l.slice(0,-1));try{r.setIn([..._],l)}catch(d){It.error(d)}}}n&&kN(r,n),ip(r,t);let s=r.toJSON();wt=Qo(s);let i=r.getIn(["rootPath"]),o=Dn.join(i,kr.HDB_CONFIG_FILE);fr.createFileSync(o),fr.writeFileSync(o,String(r)),It.trace(`Config file written to ${o}`)}a(DK,"createConfigFile");function kN(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($c.TABLES))for(let i in n[s][$c.TABLES])for(let o in n[s][$c.TABLES][i]){let c=n[s][$c.TABLES][i][o],u=[Fr.DATABASES,s,$c.TABLES,i,o];e.hasIn(u)?e.setIn(u,c):e.addIn(u,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){It.error("Error parsing schemas CLI/env config arguments",n)}}a(kN,"setSchemasConfig");function LK(e){if(z_===void 0){let r=ai(FN);z_=Qo(r.toJSON())}let t=Ln[e.toLowerCase()];if(t!==void 0)return z_[t.toLowerCase()]}a(LK,"getDefaultConfig");function VN(e){if(e==null){It.error(wK);return}if(wt===void 0){It.trace(yK);return}let t=Ln[e.toLowerCase()];if(t!==void 0)return wt[t.toLowerCase()]}a(VN,"getConfigValue");function zi(e=Bt.getPropsFilePath()){let t=Bt.getEnvCliRootPath();return t?Dn.join(t,kr.HDB_CONFIG_FILE):qN(e).get(kr.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY)}a(zi,"getConfigFilePath");function sp(e=!1){if(wt===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 It.error(i),new Error(`HarperDB properties file at path ${t} does not exist`)}}let r=zi(t),n;if(r.includes("config/settings.js"))try{YN(r);return}catch(i){if(i.code!==kr.NODE_ERROR_CODES.ENOENT)throw i}try{n=ai(r)}catch(i){if(i.code===kr.NODE_ERROR_CODES.ENOENT){It.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 It.error(i),new Error(`Error reading HarperDB config file at ${r}`)}MK(n,r),ip(n);let s=n.toJSON();if(bK.config=s,wt=Qo(s),wt.logging_rotation_rotate)for(let i in GN)wt[i]&&It.error(`Config ${GN[i]} has been deprecated. Please check https://docs.harperdb.io/docs/ for further details.`);It.trace(NK)}}a(sp,"initConfig");function MK(e,t){let r=e.getIn(["rootPath"]),n=!1;e.hasIn(["storage","path"])||(e.setIn(["storage","path"],Dn.join(r,"database")),n=!0),e.hasIn(["clustering","leafServer","streams","path"])||(e.setIn(["clustering","leafServer","streams","path"],Dn.join(r,"clustering","leaf")),n=!0),e.hasIn(["logging","rotation","path"])||(e.setIn(["logging","rotation","path"],Dn.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&&(It.trace("Updating config file with missing config params"),fr.writeFileSync(t,String(e)))}a(MK,"checkForUpdatedConfig");function ip(e,t=!1){let r=e.toJSON();r.componentsRoot=r.componentsRoot??r?.customFunctions?.root,r?.http?.threads&&(r.threads=r?.http?.threads);let n=SK(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(ip,"validateConfig");function PK(e,t){wt===void 0&&(wt={});let r=Ln[e.toLowerCase()];if(r===void 0){It.trace(`Unable to update config object because config param '${e}' does not exist`);return}wt[r.toLowerCase()]=t}a(PK,"updateConfigObject");function $N(e,t,r=void 0,n=!1,s=!1,i=!1){wt===void 0&&sp();let o=VN(Ln.hdb_root),c=Dn.join(o,kr.HDB_CONFIG_FILE),u=ai(c),_;if(r===void 0&&e.toLowerCase()===Fr.DATABASES)_=t;else if(r===void 0){let E;if(i)E=e;else if(E=Ln[e.toLowerCase()],E===void 0)throw new Error(`Unable to update config, unrecognized config parameter: ${e}`);let f=E.split("_"),h=np(E,t);u.setIn([...f],h)}else for(let E in r){let f=Ln[E.toLowerCase()];if(f===Fr.HTTP_SECUREPORT&&r[E]===wt[Fr.HTTP_PORT]?.toString()&&u.setIn(["http","port"],null),f===Fr.OPERATIONSAPI_NETWORK_SECUREPORT&&r[E]===wt[Fr.OPERATIONSAPI_NETWORK_PORT.toLowerCase()]?.toString()&&u.setIn(["operationsApi","network","port"],null),f===Fr.DATABASES){_=r[E];continue}if(f?.startsWith("threads_")){let h=u.getIn(["threads"]);h>=0&&(u.deleteIn(["threads"]),u.setIn(["threads","count"],h))}if(!f&&(E.endsWith("_package")||E.endsWith("_port"))&&(f=E),f!==void 0){let h=f.split("_"),p=kr.LEGACY_CONFIG_PARAMS[E.toUpperCase()];p&&p.startsWith("customFunctions")&&u.hasIn(p.split("_"))&&(f=p,h=p.split("_"));let S=np(f,r[E]);f==="rootPath"&&S?.endsWith("/")&&(S=S.slice(0,-1));try{h.length>1&&typeof u.getIn(h.slice(0,-1))=="boolean"&&u.deleteIn(h.slice(0,-1)),u.setIn([...h],S)}catch(T){It.error(T)}}}_&&kN(u,_),ip(u);let l=u.getIn(["rootPath"]),d=Dn.join(l,kr.HDB_CONFIG_FILE);n===!0&&UK(c,l),fr.writeFileSync(d,String(u)),s&&(wt=Qo(u.toJSON())),It.trace(`Config parameter: ${e} updated with value: ${t}`)}a($N,"updateConfigValue");function UK(e,t){try{let r=Dn.join(t,"backup",`${kr.HDB_CONFIG_FILE}.bak`);fr.copySync(e,r),It.trace(`Config file: ${e} backed up to: ${r}`)}catch(r){It.error(IK),It.error(r)}}a(UK,"backupConfigFile");var vK=["databases"];function Qo(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)),J_=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])&&!vK.includes(i)){let o=r(n[i]);for(let c in o){if(!o.hasOwnProperty(c))continue;c!=="package"&&(i=i.toLowerCase());let u=i+"_"+c;!Fr[u.toUpperCase()]&&Ln[u]&&(s[Ln[u].toLowerCase()]=o[c]),s[u]=o[c]}}n[i]!==void 0&&(s[i.toLowerCase()]=n[i])}return s}a(r,"squashObj")}a(Qo,"flattenConfig");function np(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(gK(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(np,"castConfigValue");function BK(){let e=Bt.getPropsFilePath(),t=zi(e);return ai(t).toJSON()}a(BK,"getConfiguration");async function xK(e){let{operation:t,hdb_user:r,hdb_auth_header:n,...s}=e;try{return $N(void 0,void 0,s,!0),CK}catch(i){throw typeof i=="string"||i instanceof String?AK(i,i,OK.BAD_REQUEST,void 0,void 0,!0):i}}a(xK,"setConfiguration");function op(){let e=Bt.getPropsFilePath();try{fr.accessSync(e,fr.constants.F_OK|fr.constants.R_OK)}catch(n){if(!Bt.noBootFile())throw It.error(n),new Error(`HarperDB properties file at path ${e} does not exist`)}let t=zi(e);return ai(t).toJSON()}a(op,"readConfigFile");function ai(e){return TK.parseDocument(fr.readFileSync(e,"utf8"),{simpleKeys:!0})}a(ai,"parseYamlDoc");function HK(){let e=op(),t=e?.clustering?.hubServer?.cluster?.network?.routes;t=Bt.isEmptyOrZeroLength(t)?[]:t;let r=HN(t);if(r)throw Q_.CONFIG_VALIDATION(r.message);let n=e?.clustering?.leafServer?.network?.routes;n=Bt.isEmptyOrZeroLength(n)?[]:n;let s=HN(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(HK,"getClusteringRoutes");function YN(e){let t=qN(e);wt={};for(let r in Ln){let n=t.get(r.toUpperCase());if(Bt.isEmpty(n)||typeof n=="string"&&n.trim().length===0)continue;let s=Ln[r].toLowerCase();s===Fr.LOGGING_ROOT?wt[s]=Dn.dirname(n):wt[s]=n}return wt}a(YN,"initOldConfig");function GK(e){let t=op();return RK.get(t,e.replaceAll("_","."))}a(GK,"getConfigFromFile");async function qK(e,t){let r=ai(zi());r.hasIn([e])?r.setIn([e],t):r.addIn([e],t),await fr.writeFile(zi(),String(r))}a(qK,"addConfig");function FK(e){let t=zi(Bt.getPropsFilePath()),r=ai(t);r.deleteIn(e);let n=r.getIn(["rootPath"]),s=Dn.join(n,kr.HDB_CONFIG_FILE);fr.writeFileSync(s,String(r))}a(FK,"deleteConfigFromFile");function kK(){return J_||(sp(),J_)}a(kK,"getConfigObj")});var QN=g((hle,WN)=>{"use strict";var j_=P(),X_=class{static{a(this,"BaseLicense")}constructor(t=0,r=j_.RAM_ALLOCATION_ENUM.DEFAULT,n=j_.LICENSE_VALUES.VERSION_DEFAULT,s){this.exp_date=t,this.ram_allocation=r,this.version=n,this.fingerprint=s}},ap=class extends X_{static{a(this,"ExtendedLicense")}constructor(t=0,r=j_.RAM_ALLOCATION_ENUM.DEFAULT,n=j_.LICENSE_VALUES.VERSION_DEFAULT,s,i=!1){super(t,r,n,s),this.enterprise=i}};WN.exports={BaseLicense:X_,ExtendedLicense:ap}});var Ji=g((ple,eI)=>{"use strict";var Jo=require("fs-extra"),JN=$_(),jN=require("crypto"),VK=require("moment"),$K=require("uuid").v4,tr=$(),up=require("path"),YK=z(),ci=P(),{totalmem:zN}=require("os"),KK=QN().ExtendedLicense,zo="invalid license key format",WK="061183",QK="mofi25",zK="aes-256-cbc",JK=16,jK=32,XN=Z();XN.initSync();var cp;eI.exports={validateLicense:ZN,generateFingerPrint:ZK,licenseSearch:dp,getLicense:rW,checkMemoryLimit:nW};function lp(){return up.join(XN.getHdbBasePath(),ci.LICENSE_KEY_DIR_NAME,ci.LICENSE_FILE_NAME)}a(lp,"getLicenseDirPath");function XK(){let e=lp();return up.join(e,ci.LICENSE_FILE_NAME)}a(XK,"getLicenseFilePath");function _p(){let e=lp();return up.join(e,ci.REG_KEY_FILE_NAME)}a(_p,"getFingerPrintFilePath");async function ZK(){let e=_p();try{return await Jo.readFile(e,"utf8")}catch(t){if(t.code==="ENOENT")return await eW();throw tr.error(`Error writing fingerprint file to ${e}`),tr.error(t),new Error("There was an error generating the fingerprint")}}a(ZK,"generateFingerPrint");async function eW(){let e=$K(),t=JN.hash(e),r=_p();try{await Jo.mkdirp(lp()),await Jo.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(eW,"writeFingerprint");function ZN(e,t){let r={valid_license:!1,valid_date:!1,valid_machine:!1,exp_date:null,ram_allocation:ci.RAM_ALLOCATION_ENUM.DEFAULT,version:ci.LICENSE_VALUES.VERSION_DEFAULT};if(!e)return tr.error("empty license key passed to validate."),r;let n=_p(),s=!1;try{s=Jo.statSync(n)}catch(i){tr.error(i)}if(s){let i;try{i=Jo.readFileSync(n,"utf8")}catch{tr.error("error validating this machine in the license"),r.valid_machine=!1;return}let o=e.split(QK),c=o[1];c=Buffer.concat([Buffer.from(c)],JK);let u=Buffer.concat([Buffer.from(i)],jK),_=jN.createDecipheriv(zK,u,c);r.valid_date=!0,r.valid_license=!0,r.valid_machine=!0;let l=null;try{l=_.update(o[0],"hex","utf8"),l.trim(),l+=_.final("utf8")}catch{let f=tW(o[0],i);if(f)l=f;else throw r.valid_license=!1,r.valid_machine=!1,console.error(zo),tr.error(zo),new Error(zo)}let d;if(isNaN(l))try{d=JSON.parse(l),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(zo),tr.error(zo),new Error(zo)}else r.exp_date=l;r.exp_date<VK().valueOf()&&(r.valid_date=!1),JN.validate(o[1],`${WK}${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(ZN,"validateLicense");function tW(e,t){try{let r=jN.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(tW,"checkOldLicense");function dp(){let e=new KK,t=[];try{t=Jo.readFileSync(XK(),"utf-8").split(ci.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(YK.isEmptyOrZeroLength(n))continue;let s=JSON.parse(n),i=ZN(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=ci.RAM_ALLOCATION_ENUM.DEFAULT,e.enterprise=!1}}return cp=e,e}a(dp,"licenseSearch");async function rW(){return cp||await dp(),cp}a(rW,"getLicense");function nW(){let e=dp().ram_allocation,t=process.constrainedMemory?.()||zN();if(t=Math.round(Math.min(t,zN())/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(nW,"checkMemoryLimit")});var ln=g((Ale,mI)=>{"use strict";var sI="username is required",iI="nothing to update, must supply active, role or password to update",oI="password cannot be an empty string",aI="If role is specified, it cannot be empty.",cI="active must be true or false";mI.exports={addUser:dW,alterUser:fW,dropUser:hW,getSuperUser:TW,userInfo:mW,listUsers:ed,listUsersExternal:pW,setUsersToGlobal:Xo,findAndValidateUser:EI,getClusterUser:gW,USERNAME_REQUIRED:sI,ALTERUSER_NOTHING_TO_UPDATE:iI,EMPTY_PASSWORD:oI,EMPTY_ROLE:aI,ACTIVE_BOOLEAN:cI};var uI=qr(),sW=oi(),hp=$_(),lI=IN(),_I=Gr(),mp=ys(),Vr=z(),dI=require("validate.js"),Oe=$(),{promisify:iW}=require("util"),pp=As(),tI=P(),rI=Ve(),oW=Er(),Tle=Z(),gle=Ji(),aW=Fi(),{table:Rle}=(Ae(),ie(ke)),{handleHDBError:Zn,hdb_errors:cW}=ne(),{HTTP_STATUS_CODES:es,AUTHENTICATION_ERROR_MSGS:fp,HDB_ERROR_MSGS:jo}=cW,{UserEventMsg:Sp}=Mn(),Ep=require("lodash"),{server:Tp}=(lr(),ie(xi)),uW=$();Tp.getUser=(e,t)=>EI(e,t,t!=null);var fI={username:!0,active:!0,role:!0,password:!0},nI=new Map,Z_=_I.searchByValue,lW=_I.searchByHash,_W=iW(sW.delete);async function dW(e){let t=dI.cleanAttributes(e,fI),r=lI.addUserValidation(t);if(r)throw Zn(new Error,r.message,es.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 Z_(n),s=s&&Array.from(s)}catch(u){throw Oe.error("There was an error searching for a role in add user"),Oe.error(u),u}if(!s||s.length<1)throw Zn(new Error,jo.ROLE_NAME_NOT_FOUND(t.role),es.NOT_FOUND,void 0,void 0,!0);if(s.length>1)throw Zn(new Error,jo.DUP_ROLES_FOUND(t.role),es.CONFLICT,void 0,void 0,!0);s[0].permission.cluster_user===!0&&(t.hash=pp.encrypt(t.password)),t.password=hp.hash(t.password),t.role=s[0].id;let i={operation:"insert",schema:"system",table:"hdb_user",records:[t]},o;try{o=await uI.insert(i)}catch(u){throw Oe.error("There was an error searching for a user."),Oe.error(u),u}Oe.debug(o);try{await Xo()}catch(u){throw Oe.error("Got an error setting users to global"),Oe.error(u),u}if(o.skipped_hashes.length===1)throw Zn(new Error,jo.USER_ALREADY_EXISTS(t.username),es.CONFLICT,void 0,void 0,!0);let c=Object.assign({},t);return c.role=s[0],mp.signalUserChange(new Sp(process.pid)),`${c.username} successfully added`}a(dW,"addUser");async function fW(e){let t=dI.cleanAttributes(e,fI);if(Vr.isEmptyOrZeroLength(t.username))throw new Error(sI);if(Vr.isEmptyOrZeroLength(t.password)&&Vr.isEmptyOrZeroLength(t.role)&&Vr.isEmptyOrZeroLength(t.active))throw new Error(iI);if(!Vr.isEmpty(t.password)&&Vr.isEmptyOrZeroLength(t.password.trim()))throw new Error(oI);if(!Vr.isEmpty(t.active)&&!Vr.isBoolean(t.active))throw new Error(cI);let r=EW(t.username);if(!Vr.isEmpty(t.password)&&!Vr.isEmptyOrZeroLength(t.password.trim())&&(r&&(t.hash=pp.encrypt(t.password)),t.password=hp.hash(t.password)),t.role==="")throw new Error(aI);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 Z_(i)||[])}catch(c){throw Oe.error("Got an error searching for a role."),Oe.error(c),c}if(!o||o.length===0){let c=jo.ALTER_USER_ROLE_NOT_FOUND(t.role);throw Oe.error(c),Zn(new Error,c,es.NOT_FOUND,void 0,void 0,!0)}if(o.length>1){let c=jo.ALTER_USER_DUP_ROLES(t.role);throw Oe.error(c),Zn(new Error,c,es.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 uI.update(n)}catch(i){throw Oe.error("Error during update."),Oe.error(i),i}try{await Xo()}catch(i){throw Oe.error("Got an error setting users to global"),Oe.error(i),i}return mp.signalUserChange(new Sp(process.pid)),s}a(fW,"alterUser");function EW(e){let t=!1,r=global.hdb_users.get(e);return r&&r.role.permission.cluster_user===!0&&(t=!0),t}a(EW,"isClusterUser");async function hW(e){try{let t=lI.dropUserValidation(e);if(t)throw new Error(t);let r={table:"hdb_user",schema:"system",hash_values:[e.username]};if(Vr.isEmpty(global.hdb_users.get(e.username)))throw Zn(new Error,jo.USER_NOT_EXIST(e.username),es.NOT_FOUND,void 0,void 0,!0);let n;try{n=await _W(r)}catch(s){throw Oe.error("Got an error deleting a user."),Oe.error(s),s}Oe.debug(n);try{await Xo()}catch(s){throw Oe.error("Got an error setting users to global."),Oe.error(s),s}return mp.signalUserChange(new Sp(process.pid)),`${e.username} successfully deleted`}catch(t){throw t}}a(hW,"dropUser");async function mW(e){let t={};try{if(!e||!e.hdb_user)return"There was no user info in the body";t=Ep.cloneDeep(e.hdb_user);let r={schema:"system",table:"hdb_role",hash_values:[t.role.id],get_attributes:["*"]},n;try{n=await lW(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(mW,"userInfo");async function pW(){let e;try{e=await ed()}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(pW,"listUsersExternal");async function ed(){try{let e={schema:"system",table:"hdb_role",search_value:"*",search_attribute:"role",get_attributes:["*"]},t;try{t=await Z_(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]=Ep.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 Z_(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=Ep.cloneDeep(o),o.role=r[o.role],SW(o.role),i.set(o.username,o);return i}catch(e){throw Oe.error("got an error listing users"),Oe.error(e),Vr.errorizeMessage(e)}return null}a(ed,"listUsers");function SW(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(aW)){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(SW,"appendSystemTablesToRole");async function Xo(){try{let e=await ed();global.hdb_users=e}catch(e){throw Oe.error(e),e}}a(Xo,"setUsersToGlobal");async function EI(e,t,r=!0){global.hdb_users||await Xo();let n=global.hdb_users.get(e);if(!n){if(!r)return{username:e};throw Zn(new Error,fp.GENERIC_AUTH_FAIL,es.UNAUTHORIZED,void 0,void 0,!0)}if(n&&!n.active)throw Zn(new Error,fp.USER_INACTIVE,es.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(nI.get(t)===n.password)return s;if(hp.validate(n.password,t))nI.set(t,n.password);else throw Zn(new Error,fp.GENERIC_AUTH_FAIL,es.UNAUTHORIZED,void 0,void 0,!0)}return s}a(EI,"findAndValidateUser");async function TW(){global.hdb_users||await Xo();for(let[,e]of global.hdb_users)if(e.role.role==="super_user")return e}a(TW,"getSuperUser");async function gW(){let e=await ed(),t=oW.getConfigFromFile(tI.CONFIG_PARAMS.CLUSTERING_USER),r=e.get(t);if(!Vr.isEmpty(r)&&r?.role?.role===tI.ROLE_TYPES_ENUM.CLUSTER_USER)return r.decrypt_hash=pp.decrypt(r.hash),r.uri_encoded_d_hash=encodeURIComponent(r.decrypt_hash),r.uri_encoded_name=encodeURIComponent(r.username),r.sys_name=r.username+rI.SERVER_SUFFIX.ADMIN,r.sys_name_encoded=r.uri_encoded_name+rI.SERVER_SUFFIX.ADMIN,r}a(gW,"getClusterUser");var hI=[];Tp.invalidateUser=function(e){for(let t of hI)try{t(e)}catch(r){uW.error("Error invalidating user",r)}};Tp.onInvalidatedUser=function(e){hI.push(e)}});var Kc=g((Nle,gI)=>{"use strict";var ji=$(),$r=P(),RW=Qy(),ble=bs(),yle=Os(),AW=ln(),{validateEvent:pI}=Mn(),Yc=Cn(),OW=require("process"),{resetDatabases:bW}=(Ae(),ie(ke)),yW={[$r.ITC_EVENT_TYPES.SCHEMA]:NW,[$r.ITC_EVENT_TYPES.USER]:TI};async function NW(e){let t=pI(e);if(t){ji.error(t);return}ji.trace("ITC schemaHandler received schema event:",e),await RW(e.message),await IW(e.message)}a(NW,"schemaHandler");async function IW(e){try{Yc.resetReadTxn($r.SYSTEM_SCHEMA_NAME,$r.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME),Yc.resetReadTxn($r.SYSTEM_SCHEMA_NAME,$r.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME),Yc.resetReadTxn($r.SYSTEM_SCHEMA_NAME,$r.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME);let t=bW();e.table&&e.database&&await t[e.database][e.table].put(Symbol.for("write-verify"),null)}catch(t){ji.error(t)}}a(IW,"syncSchemaMetadata");var SI=[];async function TI(e){try{try{Yc.resetReadTxn($r.SYSTEM_SCHEMA_NAME,$r.SYSTEM_TABLE_NAMES.USER_TABLE_NAME),Yc.resetReadTxn($r.SYSTEM_SCHEMA_NAME,$r.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME)}catch(r){ji.warn(r)}let t=pI(e);if(t){ji.error(t);return}ji.trace(`ITC userHandler ${$r.HDB_ITC_CLIENT_PREFIX}${OW.pid} received user event:`,e),await AW.setUsersToGlobal();for(let r of SI)r()}catch(t){ji.error(t)}}a(TI,"userHandler");TI.addListener=function(e){SI.push(e)};gI.exports=yW});var Mn=g((Mle,AI)=>{"use strict";var wle=$(),gp=z(),wW=P(),{ITC_ERRORS:Wc}=Ur(),{parentPort:Cle,threadId:CW,isMainThread:DW,workerData:Dle}=require("worker_threads"),{onMessageFromWorkers:LW,broadcast:Lle,broadcastWithAcknowledgement:MW}=We();AI.exports={sendItcEvent:PW,validateEvent:RI,SchemaEventMsg:UW,UserEventMsg:vW};var td;LW(async(e,t)=>{td=td||Kc(),RI(e),td[e.type]&&await td[e.type](e),e.requestId&&t&&t.postMessage({type:"ack",id:e.requestId})});function PW(e){return!DW&&e.message&&(e.message.originator=CW),MW(e)}a(PW,"sendItcEvent");function RI(e){if(typeof e!="object")return Wc.INVALID_ITC_DATA_TYPE;if(!e.hasOwnProperty("type")||gp.isEmpty(e.type))return Wc.MISSING_TYPE;if(!e.hasOwnProperty("message")||gp.isEmpty(e.message))return Wc.MISSING_MSG;if(!e.message.hasOwnProperty("originator")||gp.isEmpty(e.message.originator))return Wc.MISSING_ORIGIN;if(wW.ITC_EVENT_TYPES[e.type.toUpperCase()]===void 0)return Wc.INVALID_EVENT(e.type)}a(RI,"validateEvent");function UW(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(UW,"SchemaEventMsg");function vW(e){this.originator=e}a(vW,"UserEventMsg")});var ys=g((vle,NI)=>{"use strict";var OI=P(),Ule=z(),rd=$(),bI=Yy(),Zo,{sendItcEvent:yI}=Mn();function BW(e){try{rd.trace("signalSchemaChange called with message:",e),Zo=Zo||Kc();let t=new bI(OI.ITC_EVENT_TYPES.SCHEMA,e);return Zo.schema(t),yI(t)}catch(t){rd.error(t)}}a(BW,"signalSchemaChange");function xW(e){try{rd.trace("signalUserChange called with message:",e),Zo=Zo||Kc();let t=new bI(OI.ITC_EVENT_TYPES.USER,e);return Zo.user(t),yI(t)}catch(t){rd.error(t)}}a(xW,"signalUserChange");NI.exports={signalSchemaChange:BW,signalUserChange:xW}});var nd=g((xle,wI)=>{"use strict";var II=z(),HW=P(),GW=$(),qW=D_(),FW=C_(),kW=ys(),{SchemaEventMsg:VW}=Mn(),$W="already exists in";wI.exports=YW;async function YW(e,t,r){if(II.isEmptyOrZeroLength(r))return r;let n=[];II.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 KW(e,t.schema,t.name,i)})),s}a(YW,"lmdbCheckForNewAttributes");async function KW(e,t,r,n){let s=new FW(t,r,n,void 0,!0);e&&(s.hdb_auth_header=e);try{await WW(s)}catch(i){if(typeof i=="object"&&i.message!==void 0&&i.message.includes($W))GW.warn(`attribute ${t}.${r}.${n} already exists`);else throw i}}a(KW,"createNewAttribute");async function WW(e){let t;return t=await qW(e),kW.signalSchemaChange(new VW(process.pid,HW.OPERATIONS_ENUM.CREATE_ATTRIBUTE,e.schema,e.table,e.attribute)),t}a(WW,"createAttribute")});var ea=g((Gle,CI)=>{"use strict";var Rp=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}};CI.exports=Rp});var LI=g((Fle,DI)=>{"use strict";var QW=ea(),zW=P().OPERATIONS_ENUM,Ap=class extends QW{static{a(this,"LMDBInsertTransactionObject")}constructor(t,r,n,s,i=void 0){super(zW.INSERT,r,n,s,i),this.records=t}};DI.exports=Ap});var PI=g((Vle,MI)=>{"use strict";var JW=ea(),jW=P().OPERATIONS_ENUM,Op=class extends JW{static{a(this,"LMDBUpdateTransactionObject")}constructor(t,r,n,s,i,o=void 0){super(jW.UPDATE,n,s,i,o),this.records=t,this.original_records=r}};MI.exports=Op});var vI=g((Yle,UI)=>{"use strict";var XW=ea(),ZW=P().OPERATIONS_ENUM,bp=class extends XW{static{a(this,"LMDBUpsertTransactionObject")}constructor(t,r,n,s,i,o=void 0){super(ZW.UPSERT,n,s,i,o),this.records=t,this.original_records=r}};UI.exports=bp});var xI=g((Wle,BI)=>{"use strict";var eQ=ea(),tQ=P().OPERATIONS_ENUM,yp=class extends eQ{static{a(this,"LMDBDeleteTransactionObject")}constructor(t,r,n,s,i=void 0){super(tQ.DELETE,n,s,t,i),this.original_records=r}};BI.exports=yp});var Qc=g((Jle,FI)=>{"use strict";var zle=require("path"),HI=Qe(),rQ=LI(),nQ=PI(),sQ=vI(),iQ=xI(),ta=ft(),GI=z(),{CONFIG_PARAMS:oQ}=P(),qI=Z();qI.initSync();var sd=P().OPERATIONS_ENUM,{getTransactionAuditStorePath:aQ}=je();FI.exports=cQ;async function cQ(e,t){if(qI.get(oQ.LOGGING_AUDITLOG)===!1)return;let r=aQ(e.schema,e.table),n=await HI.openEnvironment(r,e.table,!0),s=uQ(e,t);if(!(s===void 0||s.hash_values.length===0)&&n!==void 0){HI.initializeDBIs(n,ta.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,ta.TRANSACTIONS_DBIS);let i=s.timestamp;return await n.dbis[ta.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP].ifNoExists(i,()=>{n.dbis[ta.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP].put(i,s),GI.isEmpty(s.user_name)||n.dbis[ta.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].put(s.user_name,i);for(let o=0;o<s.hash_values.length;o++)n.dbis[ta.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE].put(s.hash_values[o],i)})}}a(cQ,"writeTransaction");function uQ(e,t){let r=GI.isEmpty(e.hdb_user)?void 0:e.hdb_user.username;if(e.operation===sd.INSERT)return new rQ(e.records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===sd.UPDATE)return new nQ(e.records,t.original_records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===sd.UPSERT)return new sQ(e.records,t.original_records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===sd.DELETE)return new iQ(t.deleted,t.original_records,r,t.txn_time,e.__origin)}a(uQ,"createTransactionObject")});var Np=g((Zle,kI)=>{"use strict";var lQ=Gc(),Xle=qc(),zc=P(),_Q=Fc(),dQ=Yo().insertRecords,fQ=Qe(),EQ=$(),hQ=nd(),{getSchemaPath:mQ}=je(),pQ=Qc();kI.exports=SQ;async function SQ(e){try{let{schema_table:t,attributes:r}=lQ(e);_Q(e,r,t.hash_attribute),e.schema!==zc.SYSTEM_SCHEMA_NAME&&(r.includes(zc.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||r.push(zc.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.includes(zc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||r.push(zc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let n=await hQ(e.hdb_auth_header,t,r),s=mQ(e.schema,e.table),i=await fQ.openEnvironment(s,e.table),o=await dQ(i,t.hash_attribute,r,e.records,e.__origin?.timestamp);try{await pQ(e,o)}catch(c){EQ.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(SQ,"lmdbCreateRecords")});var YI=g((t_e,$I)=>{"use strict";var VI=P(),TQ=Np(),gQ=qc(),RQ=require("fs-extra"),{getSchemaPath:AQ}=je();$I.exports=OQ;async function OQ(e){let t=[{name:e.schema,createddate:Date.now()}],r=new gQ(VI.SYSTEM_SCHEMA_NAME,VI.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,void 0,t);await TQ(r),await RQ.mkdirp(AQ(e.schema))}a(OQ,"lmdbCreateSchema")});var WI=g((n_e,KI)=>{"use strict";var Ip=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}};KI.exports=Ip});var jI=g((c_e,JI)=>{"use strict";var QI=Qe(),wp=vr(),Cp=Ur().LMDB_ERRORS_ENUM,bQ=ft(),zI=$(),i_e=z(),yQ=require("lmdb"),NQ=WI(),IQ=P(),{OVERFLOW_MARKER:o_e,MAX_SEARCH_KEY_LENGTH:a_e}=bQ,wQ=IQ.TIME_STAMP_NAMES_ENUM.UPDATED_TIME;async function CQ(e,t,r,n){if(wp.validateEnv(e),t===void 0)throw new Error(Cp.HASH_ATTRIBUTE_REQUIRED);if(!Array.isArray(r))throw r===void 0?new Error(Cp.IDS_REQUIRED):new Error(Cp.IDS_MUST_BE_ITERABLE);try{let s=QI.listDBIs(e);QI.initializeDBIs(e,t,s);let i=new NQ,o,c=[],u=[];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[wQ]>n){i.skipped.push(o);continue}let p=e.dbis[t].ifVersion(o,yQ.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=wp.getIndexedValues(b);if(C)for(let x=0,v=C.length;x<v;x++)R.remove(C[x],o)}catch{zI.warn(`cannot delete from attribute: ${T}, ${b}:${o}`)}}});c.push(p),u.push(o),i.original_records.push(h)}catch(h){zI.warn(h),i.skipped.push(o)}let _=[],l=await Promise.all(c);for(let E=0,f=l.length;E<f;E++)l[E]===!0?i.deleted.push(u[E]):(i.skipped.push(u[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=wp.getNextMonotonicTime(),i}catch(s){throw s}}a(CQ,"deleteRecords");JI.exports={deleteRecords:CQ}});var Jc=g((l_e,ZI)=>{"use strict";var ra=z(),DQ=jI(),LQ=Qe(),{getSchemaPath:MQ}=je(),PQ=Qc(),UQ=$();ZI.exports=vQ;async function vQ(e,t=!0){let n=global.hdb_schema[e.schema][e.table].hash_attribute;if(ra.isEmpty(n))throw new Error(`could not retrieve hash attribute for schema:${e.schema} and table ${e.table}`);try{if(ra.isEmptyOrZeroLength(e.hash_values)&&!ra.isEmptyOrZeroLength(e.records)){e.hash_values=[];for(let c=0;c<e.records.length;c++){let u=e.records[c][n];ra.isEmpty(u)||e.hash_values.push(u)}}if(ra.isEmptyOrZeroLength(e.hash_values))return XI([],[]);if(!Array.isArray(e.hash_values))throw new Error("hash_values must be an array");if(ra.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=MQ(e.schema,e.table),i=await LQ.openEnvironment(s,e.table),o=await DQ.deleteRecords(i,n,e.hash_values,e.__origin?.timestamp);try{t===!0&&await PQ(e,o)}catch(c){UQ.error(`unable to write transaction due to ${c.message}`)}return XI(o.deleted,o.skipped,o.txn_time)}catch(s){throw s}}a(vQ,"lmdbDeleteRecords");function XI(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(XI,"createDeleteResponse")});var Lp=g((f_e,ew)=>{"use strict";var BQ=P(),d_e=vr();function Dp(e,t){let r=Object.create(null);if(t.length===1&&BQ.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(Dp,"parseRow");function xQ(e,t,r,n){let s=Dp(r,e);n.push(s)}a(xQ,"searchAll");function HQ(e,t,r,n){let s=Dp(r,e);n[t]=s}a(HQ,"searchAllToMap");function GQ(e,t,r){r[e]===void 0&&(r[e]=[]),r[e].push(t)}a(GQ,"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 qQ(e,t,r,n,s,i){t.toString().endsWith(e)&&Xi(t,r,n,s,i)}a(qQ,"endsWith");function FQ(e,t,r,n,s,i){t.toString().includes(e)&&Xi(t,r,n,s,i)}a(FQ,"contains");function kQ(e,t,r,n,s,i){t>e&&Xi(t,r,n,s,i)}a(kQ,"greaterThanCompare");function VQ(e,t,r,n,s,i){t>=e&&Xi(t,r,n,s,i)}a(VQ,"greaterThanEqualCompare");function $Q(e,t,r,n,s,i){t<e&&Xi(t,r,n,s,i)}a($Q,"lessThanCompare");function YQ(e,t,r,n,s,i){t<=e&&Xi(t,r,n,s,i)}a(YQ,"lessThanEqualCompare");ew.exports={parseRow:Dp,searchAll:xQ,searchAllToMap:HQ,iterateDBI:GQ,endsWith:qQ,contains:FQ,greaterThanCompare:kQ,greaterThanEqualCompare:VQ,lessThanCompare:$Q,lessThanEqualCompare:YQ,pushResults:Xi}});var na=g((S_e,aw)=>{"use strict";var ui=Qe(),h_e=$(),Yr=vr(),id=ft(),ht=Ur().LMDB_ERRORS_ENUM,m_e=z(),KQ=P(),od=Lp(),{parseRow:WQ}=od,p_e=require("lmdb"),{OVERFLOW_MARKER:tw,MAX_SEARCH_KEY_LENGTH:QQ}=id;function rw(e,t,r,n=!1,s=void 0,i=void 0){return Zi(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(rw,"iterateFullIndex");function jc(e,t,r,n,s,i=!1,o=void 0,c=void 0,u=!1,_=!1){return Zi(e,t,r,(l,d,E,f)=>{let R={transaction:l,start:i===!0?s:n,end:i===!0?n:s,reverse:i,limit:o,offset:c,inclusiveEnd:i===!0?!u:!_,exclusiveStart:i===!0?_:u};return f===r?(R.values=!1,d.getRange(R).map(b=>({value:b}))):d.getRange(R)})}a(jc,"iterateRangeBetween");function Zi(e,t,r,n){let s=e.database||e,i=ui.openDBI(s,r);i[id.DBI_DEFINITION_NAME].is_hash_attribute?t=r:t&&ui.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(Zi,"setupTransaction");function nw(e,t,r,n){let s;return function(i,o){if(typeof i=="string"&&i.endsWith(tw)){if(!s)if(r)s=ui.openDBI(e,r);else{let u=ui.listDBIs(e);for(let _=0,l=u.length;_<l&&(s=ui.openDBI(e,u[_]),!s[id.DBI_DEFINITION_NAME].is_hash_attribute);_++);}i=s.get(o,{transaction:t,lazy:!0})[n]}return i}}a(nw,"getOverflowCheck");function zQ(e,t,r,n=!1,s=void 0,i=void 0){if(Yr.validateEnv(e),t===void 0)throw new Error(ht.HASH_ATTRIBUTE_REQUIRED);return Zi(e,t,t,(o,c,u)=>(ad(r),r=Xc(u,r),c.getRange({transaction:o,start:n?void 0:!1,end:n?!1:void 0,limit:s,offset:i,reverse:n}).map(_=>WQ(_.value,r))))}a(zQ,"searchAll");function JQ(e,t,r,n=!1,s=void 0,i=void 0){if(Yr.validateEnv(e),t===void 0)throw new Error(ht.HASH_ATTRIBUTE_REQUIRED);ad(r),r=Xc(e.database||e,r);let o=new Map;for(let{key:c,value:u}of rw(e,t,t,n,s,i))o.set(c,od.parseRow(u,r));return o}a(JQ,"searchAllToMap");function jQ(e,t,r=!1,n=void 0,s=void 0){if(Yr.validateEnv(e),t===void 0)throw new Error(ht.ATTRIBUTE_REQUIRED);let i=Object.create(null),o=rw(e,void 0,t,r,n,s),c=o.transaction,u=nw(c.database,c,void 0,t);for(let{key:_,value:l}of o){let d=u(_,l);i[d]===void 0&&(i[d]=[]),i[d].push(l)}return i}a(jQ,"iterateDBI");function XQ(e,t){if(Yr.validateEnv(e),t===void 0)throw new Error(ht.HASH_ATTRIBUTE_REQUIRED);return ui.statDBI(e,t).entryCount}a(XQ,"countAll");function ZQ(e,t,r,n,s=!1,i=void 0,o=void 0){return li(e,r,n),Zi(e,t,r,(c,u,_,l)=>(n=Yr.convertKeyValueToWrite(n),l===r?u.get(n,{transaction:c,lazy:!0})===void 0?[]:[{key:n,value:n}]:u.getValues(n,{transaction:c,reverse:s,limit:i,offset:o}).map(d=>({key:n,value:d}))))}a(ZQ,"equals");function ez(e,t,r){return li(e,t,r),ui.openDBI(e,t).getValuesCount(r)}a(ez,"count");function tz(e,t,r,n,s=!1,i=void 0,o=void 0){return li(e,r,n),Zi(e,null,r,(c,u)=>{n=Yr.convertKeyValueToWrite(n);let _=!0;typeof n=="number"&&(_=!1);let l;if(s===!0){let d;for(let E of u.getKeys({transaction:c,start:n}))if(!E.startsWith(n)){d=E;break}return d!==void 0&&(Number.isInteger(o)?o++:i++),l=u.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 l.DONE}}),l.filter(E=>E)}else return l=u.getRange({transaction:c,start:n,reverse:s,limit:i,offset:o}).map(d=>{if(d.key.toString().startsWith(n))return d;if(_===!0)return l.DONE}),_?l:l.filter(d=>d)})}a(tz,"startsWith");function rz(e,t,r,n,s=!1,i=void 0,o=void 0){return sw(e,t,r,n,s,i,o,!0)}a(rz,"endsWith");function sw(e,t,r,n,s=!1,i=void 0,o=void 0,c=!1){return li(e,r,n),Zi(e,null,r,(u,_,l,d)=>{let E=nw(l,u,d,r);return o=Number.isInteger(o)?o:0,_.getKeys({transaction:u,end:s?!1:void 0,reverse:s}).flatMap(f=>{let h=f.toString();return h.endsWith(tw)?_.getValues(f,{transaction:u}).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))?_[id.DBI_DEFINITION_NAME].is_hash_attribute?{key:f,value:f}:_.getValues(f,{transaction:u}).map(p=>({key:f,value:p})):[]}).slice(o,i===void 0?void 0:i+(o||0))})}a(sw,"contains");function nz(e,t,r,n,s=!1,i=void 0,o=void 0){li(e,r,n);let c=typeof n,u;return c==="string"?u="\uFFFF":c==="number"?u=1/0:c==="boolean"&&(u=!0),jc(e,t,r,n,u,s,i,o,!0,!1)}a(nz,"greaterThan");function sz(e,t,r,n,s=!1,i=void 0,o=void 0){li(e,r,n);let c=typeof n,u;return c==="string"?u="\uFFFF":c==="number"?u=1/0:c==="boolean"&&(u=!0),jc(e,t,r,n,u,s,i,o,!1,!1)}a(sz,"greaterThanEqual");function iz(e,t,r,n,s=!1,i=void 0,o=void 0){li(e,r,n);let c=typeof n,u;return c==="string"?u="\0":c==="number"?u=-1/0:c==="boolean"&&(u=!1),jc(e,t,r,u,n,s,i,o,!1,!0)}a(iz,"lessThan");function oz(e,t,r,n,s=!1,i=void 0,o=void 0){li(e,r,n);let c=typeof n,u;return c==="string"?u="\0":c==="number"?u=-1/0:c==="boolean"&&(u=!1),jc(e,t,r,u,n,s,i,o,!1,!1)}a(oz,"lessThanEqual");function az(e,t,r,n,s,i=!1,o=void 0,c=void 0){if(Yr.validateEnv(e),r===void 0)throw new Error(ht.ATTRIBUTE_REQUIRED);if(n===void 0)throw new Error(ht.START_VALUE_REQUIRED);if(s===void 0)throw new Error(ht.END_VALUE_REQUIRED);if(n=Yr.convertKeyValueToWrite(n),s=Yr.convertKeyValueToWrite(s),n>s)throw new Error(ht.END_VALUE_MUST_BE_GREATER_THAN_START_VALUE);return jc(e,t,r,n,s,i,o,c)}a(az,"between");function cz(e,t,r,n){Yr.validateEnv(e);let s=e.database||e,i=e.database?e:null;if(t===void 0)throw new Error(ht.HASH_ATTRIBUTE_REQUIRED);if(ad(r),r=Xc(s,r),n===void 0)throw new Error(ht.ID_REQUIRED);let o=null,c=s.dbis[t].get(n,{transaction:i,lazy:r.length<3});return c&&(o=od.parseRow(c,r)),o}a(cz,"searchByHash");function uz(e,t,r){Yr.validateEnv(e);let n=e.database||e,s=e.database?e:null;if(t===void 0)throw new Error(ht.HASH_ATTRIBUTE_REQUIRED);if(r===void 0)throw new Error(ht.ID_REQUIRED);let i=!0;return n.dbis[t].get(r,{transaction:s,lazy:!0})===void 0&&(i=!1),i}a(uz,"checkHashExists");function lz(e,t,r,n,s=[]){return ow(e,t,r,n,s),iw(e,t,r,n,s).map(i=>i[1])}a(lz,"batchSearchByHash");function _z(e,t,r,n,s=[]){ow(e,t,r,n,s);let i=new Map;for(let[o,c]of iw(e,t,r,n,s))i.set(o,c);return i}a(_z,"batchSearchByHashToMap");function iw(e,t,r,n,s=[]){return Zi(e,t,t,(i,o,c)=>{r=Xc(c,r);let u=r.length<3;return n.map(_=>{let l=c.dbis[t].get(_,{transaction:i,lazy:u});if(l)return[_,od.parseRow(l,r)];s.push(_)}).filter(_=>_)})}a(iw,"batchHashSearch");function ow(e,t,r,n,s){if(Yr.validateEnv(e),t===void 0)throw new Error(ht.HASH_ATTRIBUTE_REQUIRED);if(ad(r),n==null)throw new Error(ht.IDS_REQUIRED);if(!n[Symbol.iterator])throw new Error(ht.IDS_MUST_BE_ITERABLE)}a(ow,"initializeBatchSearchByHash");function ad(e){if(!Array.isArray(e))throw e===void 0?new Error(ht.FETCH_ATTRIBUTES_REQUIRED):new Error(ht.FETCH_ATTRIBUTES_MUST_BE_ARRAY)}a(ad,"validateFetchAttributes");function li(e,t,r){if(Yr.validateEnv(e),t===void 0)throw new Error(ht.ATTRIBUTE_REQUIRED);if(r===void 0)throw new Error(ht.SEARCH_VALUE_REQUIRED);if(r?.length>QQ)throw new Error(ht.SEARCH_VALUE_TOO_LARGE)}a(li,"validateComparisonFunctions");function Xc(e,t){return t.length===1&&KQ.SEARCH_WILDCARDS.indexOf(t[0])>=0&&(t=ui.listDBIs(e)),t}a(Xc,"setGetWholeRowAttributes");aw.exports={searchAll:zQ,searchAllToMap:JQ,count:ez,countAll:XQ,equals:ZQ,startsWith:tz,endsWith:rz,contains:sw,searchByHash:cz,setGetWholeRowAttributes:Xc,batchSearchByHash:lz,batchSearchByHashToMap:_z,checkHashExists:uz,iterateDBI:jQ,greaterThan:nz,greaterThanEqual:sz,lessThan:iz,lessThanEqual:oz,between:az}});var sa=g((g_e,dw)=>{var cw=require("lodash"),uw=Xe(),fe=require("joi"),dz=z(),{hdb_schema_table:Zc,checkValidTable:lw,hdb_table:_w,hdb_database:cd}=Jn(),{handleHDBError:fz,hdb_errors:Ez}=ne(),{getDatabases:hz}=(Ae(),ie(ke)),{HTTP_STATUS_CODES:mz}=Ez,pz=fe.object({database:cd,schema:cd,table:_w,search_attribute:Zc,search_value:fe.any().required(),get_attributes:fe.array().min(1).items(fe.alternatives(Zc,fe.object())).optional(),desc:fe.bool(),limit:fe.number().integer().min(1),offset:fe.number().integer().min(0)}),Sz=fe.object({database:cd,schema:cd,table:_w,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(Zc,fe.object())).optional(),sort:fe.object({attribute:fe.alternatives(Zc,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(Zc,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()});dw.exports=function(e,t){let r=null;switch(t){case"value":r=uw.validateBySchema(e,pz);break;case"hashes":let i=function(o){s?s+=". "+o:s=o};var n=i;a(i,"addError");let s;i(lw("database",e.schema)),i(lw("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=uw.validateBySchema(e,Sz);break;default:throw new Error(`Error validating search, unknown type: ${t}`)}if(!r&&e.schema!=="system"){let s=dz.checkGlobalSchemaTable(e.schema,e.table);if(s)return fz(new Error,s,mz.NOT_FOUND);let o=hz()[e.schema][e.table].attributes,c=e.get_attributes?[...e.get_attributes]:[];t==="value"&&c.push(e.search_attribute);let u=a(l=>{for(let d=0,E=l.conditions.length;d<E;d++){let f=l.conditions[d];f.conditions?u(f):c.push(f.search_attribute)}},"addConditions");t==="conditions"&&u(e);let _=cw.filter(c,l=>l!=="*"&&l.attribute!=="*"&&!Array.isArray(l)&&!l.name&&!cw.some(o,d=>d===l||d.attribute===l||d.attribute===l.attribute));if(_&&_.length>0){let l=_.join(", ");return l=l.replace(/,([^,]*)$/," and$1"),new Error(`unknown attribute '${l}'`)}}return r}});var Mp=g((A_e,fw)=>{"use strict";var Tz=Qe(),gz=sa(),{getSchemaPath:Rz}=je();fw.exports=Az;function Az(e){let t=gz(e,"hashes");if(t)throw t;let r=Rz(e.schema,e.table);return Tz.openEnvironment(r,e.table)}a(Az,"initialize")});var Pp=g((b_e,Ew)=>{"use strict";var Oz=na(),bz=Mp();Ew.exports=yz;async function yz(e){let t=await bz(e),r=t.useReadTransaction();r.database=t;let n=global.hdb_schema[e.schema][e.table];try{return Oz.batchSearchByHashToMap(r,n.hash_attribute,e.get_attributes,e.hash_values)}finally{r.done()}}a(yz,"lmdbGetDataByHash")});var ia=g((N_e,hw)=>{"use strict";var Up=class{static{a(this,"SearchByHashObject")}constructor(t,r,n,s){this.schema=t,this.table=r,this.hash_values=n,this.get_attributes=s}};hw.exports=Up});var pw=g((C_e,mw)=>{"use strict";var w_e=ia(),Nz=na(),Iz=Mp();mw.exports=wz;async function wz(e){let t=await Iz(e),r=global.hdb_schema[e.schema][e.table];return Nz.batchSearchByHash(t,r.hash_attribute,e.get_attributes,e.hash_values)}a(wz,"lmdbSearchByHash")});var ts=g((L_e,Sw)=>{"use strict";var vp=class{static{a(this,"SearchObject")}constructor(t,r,n,s,i,o,c,u=!1,_=void 0,l=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=u,this.limit=_,this.offset=l}};Sw.exports=vp});var ud=g((P_e,bw)=>{"use strict";var rr=na(),Cz=Qe(),Dz=z(),Ee=ft(),eo=P(),Lz=Fi(),Tw=Ur().LMDB_ERRORS_ENUM,{getSchemaPath:Mz}=je(),Ns=eo.SEARCH_WILDCARDS;async function Pz(e,t,r){let n;e.schema===eo.SYSTEM_SCHEMA_NAME?n=Lz[e.table]:n=global.hdb_schema[e.schema][e.table];let s=Ow(e,n.hash_attribute,r,t);return Rw(e,s,n.hash_attribute,r)}a(Pz,"prepSearch");async function Rw(e,t,r,n){let s=Mz(e.schema,e.table),i=await Cz.openEnvironment(s,e.table),o=Aw(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(Uz(e,r)===!1){let l=e.search_attribute;if(l===r)return n?gw(o,()=>!0):o.map(E=>({[r]:E.key}));let d=a(E=>({[r]:E.value,[l]:E.key}),"toObject");return n?gw(o,d):o.map(d)}let _=e.search_attribute===r?o.map(l=>l.key):o.map(l=>l.value);return n===!0?rr.batchSearchByHashToMap(c,r,e.get_attributes,_):rr.batchSearchByHash(c,r,e.get_attributes,_)}a(Rw,"executeSearch");function Aw(e,t,r,n){let s,i=n;t.get_attributes.indexOf(n)<0&&(i=void 0);let{reverse:o,limit:c,offset:u}=t;switch(o=typeof o=="boolean"?o:!1,c=Number.isInteger(c)?c:void 0,u=Number.isInteger(u)?u:void 0,r){case Ee.SEARCH_TYPES.EQUALS:s=rr.equals(e,i,t.search_attribute,t.search_value,o,c,u);break;case Ee.SEARCH_TYPES.CONTAINS:s=rr.contains(e,i,t.search_attribute,t.search_value,o,c,u);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,u);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,u);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,u);case Ee.SEARCH_TYPES.SEARCH_ALL_TO_MAP:return rr.searchAllToMap(e,n,t.get_attributes,o,c,u);case Ee.SEARCH_TYPES.BETWEEN:s=rr.between(e,i,t.search_attribute,t.search_value,t.end_value,o,c,u);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,u);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,u);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,u);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,u);break;default:return Object.create(null)}return s}a(Aw,"searchByType");function gw(e,t){let r=new Map;for(let n of e)r.set(n.value,t(n));return r}a(gw,"createMapFromIterable");function Uz(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(Uz,"checkToFetchMore");function Ow(e,t,r,n){if(Dz.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),Ns.indexOf(s)>-1)return r===!0?Ee.SEARCH_TYPES.SEARCH_ALL_TO_MAP:Ee.SEARCH_TYPES.SEARCH_ALL;if(s.indexOf(Ns[0])<0&&s.indexOf(Ns[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(Ns.indexOf(i)>=0&&Ns.indexOf(o)>=0)return e.search_value=e.search_value.slice(1,-1),Ee.SEARCH_TYPES.CONTAINS;if(Ns.indexOf(i)>=0)return e.search_value=e.search_value.substr(1),Ee.SEARCH_TYPES.ENDS_WITH;if(Ns.indexOf(o)>=0)return e.search_value=e.search_value.slice(0,-1),Ee.SEARCH_TYPES.STARTS_WITH;if(s.includes(Ns[0])||s.includes(Ns[1]))return Ee.SEARCH_TYPES.EQUALS;throw new Error(Tw.UNKNOWN_SEARCH_TYPE)}else switch(n){case eo.VALUE_SEARCH_COMPARATORS.BETWEEN:return Ee.SEARCH_TYPES.BETWEEN;case eo.VALUE_SEARCH_COMPARATORS.GREATER:return Ee.SEARCH_TYPES.GREATER_THAN;case eo.VALUE_SEARCH_COMPARATORS.GREATER_OR_EQ:return Ee.SEARCH_TYPES.GREATER_THAN_EQUAL;case eo.VALUE_SEARCH_COMPARATORS.LESS:return Ee.SEARCH_TYPES.LESS_THAN;case eo.VALUE_SEARCH_COMPARATORS.LESS_OR_EQ:return Ee.SEARCH_TYPES.LESS_THAN_EQUAL;default:throw new Error(Tw.UNKNOWN_SEARCH_TYPE)}}a(Ow,"createSearchTypeFromSearchObject");bw.exports={executeSearch:Rw,createSearchTypeFromSearchObject:Ow,prepSearch:Pz,searchByType:Aw}});var Nw=g((B_e,yw)=>{"use strict";var v_e=ts(),vz=sa(),Bz=z(),xz=P(),Hz=ud();yw.exports=Gz;function Gz(e,t){if(!Bz.isEmpty(t)&&xz.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[t]===void 0)throw new Error(`Value search comparator - ${t} - is not valid`);let n=vz(e,"value");if(n)throw n;return Hz.prepSearch(e,t,!0)}a(Gz,"lmdbGetDataByValue")});var eu=g((G_e,Iw)=>{"use strict";var H_e=ts(),qz=sa(),Fz=z(),kz=P(),Vz=ud();Iw.exports=$z;async function $z(e,t){if(!Fz.isEmpty(t)&&kz.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[t]===void 0)throw new Error(`Value search comparator - ${t} - is not valid`);let n=qz(e,"value");if(n)throw n;return Vz.prepSearch(e,t,!1)}a($z,"lmdbSearchByValue")});var Cw=g((k_e,ww)=>{"use strict";var F_e=ft(),Bp=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}},xp=class{static{a(this,"SearchCondition")}constructor(t,r,n){this.search_attribute=t,this.search_type=r,this.search_value=n}},Hp=class{static{a(this,"SortAttribute")}constructor(t,r){this.attribute=t,this.desc=r}};ww.exports={SearchByConditionsObject:Bp,SearchCondition:xp,SortAttribute:Hp}});var Uw=g((K_e,Pw)=>{"use strict";var $_e=Cw().SearchByConditionsObject,Yz=ts(),Kz=sa(),Gp=na(),ld=ft(),{Resource:Y_e}=(Nn(),ie(qp)),Mw=ud(),Wz=Lp(),Qz=require("lodash"),{getSchemaPath:zz}=je(),Dw=Qe(),{handleHDBError:Jz,hdb_errors:jz}=ne(),{HTTP_STATUS_CODES:Xz}=jz,Zz=1e8;Pw.exports=eJ;async function eJ(e){let t=Kz(e,"conditions");if(t)throw Jz(t,t.message,Xz.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=zz(e.schema,e.table),n=await Dw.openEnvironment(r,e.table),s=global.hdb_schema[e.schema][e.table];for(let _ of e.conditions)Dw.openDBI(n,_.search_attribute);let i=Qz.sortBy(e.conditions,_=>{if(_.estimated_count===void 0){let l=_.search_type;l===ld.SEARCH_TYPES.EQUALS?_.estimated_count=Gp.count(n,_.search_attribute,_.search_value):l===ld.SEARCH_TYPES.CONTAINS||l===ld.SEARCH_TYPES.ENDS_WITH?_.estimated_count=1/0:_.estimated_count=Zz}return _.estimated_count}),o=n.useReadTransaction();o.database=n;let c=await Lw(o,e,i[0],s.hash_attribute),u;if(!e.operator||e.operator.toLowerCase()==="and"){let _=n.dbis[s.hash_attribute],l=i.slice(1).map(Mw.filterByType),d=l.length,E=Gp.setGetWholeRowAttributes(n,e.get_attributes);u=c.map(f=>_.get(f,{transaction:o,lazy:!0})),d>0&&(u=u.filter(f=>{for(let h=0;h<d;h++)if(!l[h](f))return!1;return!0})),(e.offset||e.limit!==void 0)&&(u=u.slice(e.offset,e.limit!==void 0?(e.offset||0)+e.limit:void 0)),u=u.map(f=>Wz.parseRow(f,E))}else{for(let d=1;d<i.length;d++){let E=i[d],f=await Lw(o,e,E,s.hash_attribute);c=c.concat(f)}let _=new Set,l=e.offset||0;c=c.filter(d=>_.has(d)?!1:(_.add(d),!0)).slice(l,e.limit&&e.limit+l),u=Gp.batchSearchByHash(o,s.hash_attribute,e.get_attributes,c)}return u.onDone=()=>{o.done()},u}a(eJ,"lmdbSearchByConditions");async function Lw(e,t,r,n){let s=new Yz(t.schema,t.table,void 0,void 0,n,t.get_attributes),i=r.search_type;return s.search_attribute=r.search_attribute,i===ld.SEARCH_TYPES.BETWEEN?(s.search_value=r.search_value[0],s.end_value=r.search_value[1]):s.search_value=r.search_value,Mw.searchByType(e,s,i,n).map(o=>o.value)}a(Lw,"executeConditionSearch")});var oa=g((Q_e,vw)=>{"use strict";var tJ=P().OPERATIONS_ENUM,Fp=class{static{a(this,"DeleteObject")}constructor(t,r,n,s=void 0){this.operation=tJ.DELETE,this.schema=t,this.table=r,this.hash_values=n,this.__origin=s}};vw.exports=Fp});var kp=g((J_e,Vw)=>{"use strict";var Gw=ts(),qw=oa(),Fw=eu(),kw=Jc(),hr=P(),Bw=z(),xw=Qe(),{getTransactionAuditStorePath:rJ,getSchemaPath:nJ}=je(),Hw=$();Vw.exports=sJ;async function sJ(e){try{if(Bw.isEmpty(global.hdb_schema[e.schema])||Bw.isEmpty(global.hdb_schema[e.schema][e.table]))throw new Error(`unknown schema:${e.schema} and table ${e.table}`);await iJ(e),await oJ(e);let t=nJ(e.schema,e.table);try{await xw.deleteEnvironment(t,e.table)}catch(r){if(r.message==="invalid environment")Hw.warn(`cannot delete environment for ${e.schema}.${e.table}, environment not found`);else throw r}try{let r=rJ(e.schema,e.table);await xw.deleteEnvironment(r,e.table,!0)}catch(r){if(r.message==="invalid environment")Hw.warn(`cannot delete environment for ${e.schema}.${e.table}, environment not found`);else throw r}}catch(t){throw t}}a(sJ,"lmdbDropTable");async function iJ(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 Fw(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 qw(hr.SYSTEM_SCHEMA_NAME,hr.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,n);await kw(s)}a(iJ,"deleteAttributesFromSystem");async function oJ(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 Fw(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 qw(hr.SYSTEM_SCHEMA_NAME,hr.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,[n.id]);try{await kw(s)}catch(i){throw i}}a(oJ,"dropTableFromSystem")});var Yw=g((X_e,$w)=>{"use strict";var aJ=require("fs-extra"),cJ=ts(),uJ=ia(),lJ=oa(),_J=kp(),dJ=Jc(),fJ=Pp(),EJ=eu(),Is=P(),{getSchemaPath:hJ}=je(),{handleHDBError:mJ,hdb_errors:pJ}=ne(),{HDB_ERROR_MSGS:SJ,HTTP_STATUS_CODES:TJ}=pJ;$w.exports=gJ;async function gJ(e){let t;try{t=await RJ(e.schema);let r=new cJ(Is.SYSTEM_SCHEMA_NAME,Is.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,Is.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_KEY,t,void 0,[Is.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY]),n=Array.from(await EJ(r));for(let o=0;o<n.length;o++){let c={schema:t,table:n[o].name};try{await _J(c)}catch(u){if(u.message!=="invalid environment")throw u}}let s=new lJ(Is.SYSTEM_SCHEMA_NAME,Is.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,[t]);await dJ(s);let i=hJ(t);await aJ.remove(i)}catch(r){throw r}}a(gJ,"lmdbDropSchema");async function RJ(e){let t=new uJ(Is.SYSTEM_SCHEMA_NAME,Is.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,[e],[Is.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY]),r,n;try{r=Array.from(await fJ(t))}catch(s){throw s}for(let[,s]of r)s.name===e&&(n=e);if(!n)throw mJ(new Error,SJ.SCHEMA_NOT_FOUND(e),TJ.NOT_FOUND,void 0,void 0,!0);return n}a(RJ,"validateDropSchema")});var _d=g((ede,Kw)=>{"use strict";var Vp=class{static{a(this,"CreateTableObject")}constructor(t,r,n){this.schema=t,this.table=r,this.hash_attribute=n}};Kw.exports=Vp});var Qw=g((nde,Ww)=>{"use strict";var AJ=require("fs-extra"),dd=Qe(),{getTransactionAuditStorePath:OJ}=je(),$p=ft(),rde=_d();Ww.exports=bJ;async function bJ(e){let t;try{let r=OJ(e.schema,e.table);await AJ.mkdirp(r),t=await dd.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{dd.createDBI(t,$p.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,!1,!0),dd.createDBI(t,$p.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE,!0,!1),dd.createDBI(t,$p.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(bJ,"createTransactionsAuditEnvironment")});var Xw=g((ide,jw)=>{"use strict";var Yp=P(),zw=Qe(),yJ=Yo(),{getSystemSchemaPath:NJ,getSchemaPath:IJ}=je(),wJ=Fi(),CJ=D_(),Kp=C_(),DJ=$(),LJ=Qw(),Qp=wJ.hdb_table,Jw=[];for(let e=0;e<Qp.attributes.length;e++)Jw.push(Qp.attributes[e].attribute);jw.exports=MJ;async function MJ(e,t){let r=IJ(t.schema,t.table),n=new Kp(t.schema,t.table,Yp.TIME_STAMP_NAMES_ENUM.CREATED_TIME,void 0,!0),s=new Kp(t.schema,t.table,Yp.TIME_STAMP_NAMES_ENUM.UPDATED_TIME,void 0,!0),i=new Kp(t.schema,t.table,t.hash_attribute,void 0,!1,!0);try{if(await zw.createEnvironment(r,t.table),e!==void 0){let o=await zw.openEnvironment(NJ(),Yp.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME);await yJ.insertRecords(o,Qp.hash_attribute,Jw,[e]),n.skip_table_check=!0,s.skip_table_check=!0,i.skip_table_check=!0,await Wp(n),await Wp(s),await Wp(i)}await LJ(t)}catch(o){throw o}}a(MJ,"lmdbCreateTable");async function Wp(e){try{await CJ(e)}catch(t){DJ.warn(`failed to create attribute ${e.attribute} due to ${t.message}`)}}a(Wp,"createAttribute")});var eC=g((ade,Zw)=>{"use strict";var PJ=Gc(),UJ=Fc(),vJ=nd(),tu=P(),BJ=Yo().updateRecords,xJ=Qe(),{getSchemaPath:HJ}=je(),GJ=Qc(),qJ=$();Zw.exports=FJ;async function FJ(e){try{let{schema_table:t,attributes:r}=PJ(e);UJ(e,r,t.hash_attribute),e.schema!==tu.SYSTEM_SCHEMA_NAME&&(r.includes(tu.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||r.push(tu.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.includes(tu.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||r.push(tu.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let n=await vJ(e.hdb_auth_header,t,r),s=HJ(e.schema,e.table),i=await xJ.openEnvironment(s,e.table),o=await BJ(i,t.hash_attribute,r,e.records,e.__origin?.timestamp);try{await GJ(e,o)}catch(c){qJ.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(FJ,"lmdbUpdateRecords")});var rC=g((ude,tC)=>{"use strict";var kJ=P().OPERATIONS_ENUM,zp=class{static{a(this,"UpsertObject")}constructor(t,r,n,s=void 0){this.operation=kJ.UPSERT,this.schema=t,this.table=r,this.records=n,this.__origin=s}};tC.exports=zp});var sC=g((dde,nC)=>{"use strict";var _de=rC(),VJ=Gc(),$J=Fc(),YJ=nd(),ru=P(),KJ=Yo().upsertRecords,WJ=Qe(),{getSchemaPath:QJ}=je(),zJ=Qc(),JJ=$(),{handleHDBError:jJ,hdb_errors:XJ}=ne();nC.exports=ZJ;async function ZJ(e){let t;try{t=VJ(e)}catch(u){throw jJ(u,u.message,XJ.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0)}let{schema_table:r,attributes:n}=t;$J(e,n,r.hash_attribute),e.schema!==ru.SYSTEM_SCHEMA_NAME&&(n.includes(ru.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||n.push(ru.TIME_STAMP_NAMES_ENUM.CREATED_TIME),n.includes(ru.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||n.push(ru.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let s=await YJ(e.hdb_auth_header,r,n),i=QJ(e.schema,e.table),o=await WJ.openEnvironment(i,e.table),c=await KJ(o,r.hash_attribute,n,e.records,e.__origin?.timestamp);try{await zJ(e,c)}catch(u){JJ.error(`unable to write transaction due to ${u.message}`)}return{written_hashes:c.written_hashes,schema_table:r,new_attributes:s,txn_time:c.txn_time}}a(ZJ,"lmdbUpsertRecords")});var oC=g((Ede,iC)=>{"use strict";var Jp=class{static{a(this,"DeleteBeforeObject")}constructor(t,r,n){this.schema=t,this.table=r,this.timestamp=n}};iC.exports=Jp});var cC=g((mde,aC)=>{"use strict";var jp=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}};aC.exports=jp});var _C=g((Tde,lC)=>{"use strict";var Xp=Qe(),{getTransactionAuditStorePath:e2}=je(),Sde=oC(),nu=ft(),t2=z(),uC=cC(),r2=require("util").promisify,n2=r2(setTimeout),s2=1e4,i2=100;lC.exports=o2;async function o2(e){let t=e2(e.schema,e.table),r=await Xp.openEnvironment(t,e.table,!0),n=Xp.listDBIs(r);Xp.initializeDBIs(r,nu.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,n);let s,i=new uC;do s=await a2(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 n2(i2);while(s.transactions_deleted>0);return i}a(o2,"deleteAuditLogsBefore");async function a2(e,t){let r=new uC;try{let n=e.dbis[nu.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[nu.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME];t2.isEmpty(c)||(s=e.dbis[nu.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].remove(c,i));for(let u=0;u<o.hash_values.length;u++)s=e.dbis[nu.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE].remove(o.hash_values[u],i);if(r.transactions_deleted++,r.end_timestamp=i,r.transactions_deleted>s2)break}return await s,r}catch(n){throw n}}a(a2,"deleteTransactions")});var fC=g((Rde,dC)=>{"use strict";var Zp=class{static{a(this,"DropAttributeObject")}constructor(t,r,n){this.schema=t,this.table=r,this.attribute=n}};dC.exports=Zp});var hC=g((bde,EC)=>{"use strict";var c2=ts(),u2=oa(),Ode=fC(),rs=P(),l2=z(),eS=Qe(),_2=Fi(),d2=eu(),f2=Jc(),{getSchemaPath:E2}=je();EC.exports=h2;async function h2(e,t=!0){let r;e.schema===rs.SYSTEM_SCHEMA_NAME?r=_2[e.table]:r=global.hdb_schema[e.schema][e.table];let n=await p2(e),s=E2(e.schema,e.table),i=await eS.openEnvironment(s,e.table);return t===!0&&await m2(e,i,r.hash_attribute),eS.dropDBI(i,e.attribute),n}a(h2,"lmdbDropAttribute");async function m2(e,t,r){let n=eS.openDBI(t,r),s,i=e.attribute;for(let{key:o,value:c,version:u}of n.getRange({start:!1,versions:!0})){let _={};for(let l in c)l!==i&&(_[l]=c[l]);s=t.dbis[r].put(o,_,u)}await s}a(m2,"removeAttributeFromAllObjects");async function p2(e){let t=new c2(rs.SYSTEM_SCHEMA_NAME,rs.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,rs.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_TABLE_KEY,`${e.schema}.${e.table}`,void 0,[rs.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY,rs.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ATTRIBUTE_KEY]),n=Array.from(await d2(t)).filter(o=>o[rs.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ATTRIBUTE_KEY]===e.attribute);if(l2.isEmptyOrZeroLength(n))throw new Error(`Attribute '${e.attribute}' was not found in '${e.schema}.${e.table}'`);let s=n.map(o=>o[rs.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),i=new u2(rs.SYSTEM_SCHEMA_NAME,rs.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,s);return f2(i)}a(p2,"dropAttributeFromSystem")});var RC=g((Ide,gC)=>{"use strict";var tS=Qe(),aa=ft(),Nde=vr(),rS=P(),mC=z(),{getTransactionAuditStorePath:S2}=je(),T2=na(),fd=ea(),g2=$();gC.exports=R2;async function R2(e){let t=S2(e.schema,e.table),r=await tS.openEnvironment(t,e.table,!0),n=tS.listDBIs(r);tS.initializeDBIs(r,aa.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,n);let s;switch(e.search_type){case rS.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.TIMESTAMP:return pC(r,e.search_values);case rS.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.HASH_VALUE:return s=global.hdb_schema[e.schema][e.table].hash_attribute,O2(r,e.search_values,s);case rS.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.USERNAME:return A2(r,e.search_values);default:return pC(r)}}a(R2,"readAuditLog");function pC(e,t=[0,Date.now()]){mC.isEmpty(t[0])&&(t[0]=0),mC.isEmpty(t[1])&&(t[1]=Date.now());let r=e.dbis[aa.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 fd,s))}a(pC,"searchTransactionsByTimestamp");function A2(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[aa.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].getValues(s))i.push(o);r.set(s,TC(e,i))}return Object.fromEntries(r)}a(A2,"searchTransactionsByUsername");function O2(e,t,r){let n=new Map;for(let c=0,u=t.length;c<u;c++){let _=t[c],l=T2.equals(e,aa.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,aa.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE,_);for(let{value:d}of l){let E=Number(d);n.has(E)?n.get(E).push(_.toString()):n.set(E,[_.toString()])}}let s=Array.from(n.keys()),i=TC(e,s),o=new Map;for(let c=0;c<i.length;c++){let u=i[c],_=u.timestamp,l=n.get(_);SC(u,"records",r,l,o),SC(u,"original_records",r,l,o)}return Object.fromEntries(o)}a(O2,"searchTransactionsByHashValues");function SC(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],u=c[r].toString();if(n.indexOf(u)>=0)if(s.has(u)){let _=s.get(u),l=_[_.length-1];if(l.timestamp===i)l[t]=[c];else{let d=new fd(e.operation,e.user_name,i,void 0);d[t]=[c],_.push(d)}}else{let _=new fd(e.operation,e.user_name,i,void 0);_[t]=[c],s.set(u,[_])}}}a(SC,"loopRecords");function TC(e,t){let r=[];try{let n=e.dbis[aa.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 fd,i);r.push(o)}}catch(i){g2.warn(i)}return r}catch(n){throw n}}a(TC,"batchSearchTransactions")});var OC=g((Lde,AC)=>{"use strict";var{getSchemaPath:Cde}=je(),Dde=Qe(),{database:b2}=(Ae(),ie(ke));AC.exports={writeTransaction:y2};async function y2(e,t,r){return b2({database:e,table:t}).transaction(r)}a(y2,"writeTransaction")});var IC=g((Pde,NC)=>{"use strict";var{getSchemaPath:bC}=je(),yC=Qe();NC.exports={flush:N2,resetReadTxn:I2};async function N2(e,t){return(await yC.openEnvironment(bC(e,t),t.toString())).flushed}a(N2,"flush");async function I2(e,t){try{(await yC.openEnvironment(bC(e,t),t.toString())).resetReadTxn()}catch{}}a(I2,"resetReadTxn")});var LC=g((vde,DC)=>{"use strict";var{Readable:w2}=require("stream"),{getDatabases:C2}=(Ae(),ie(ke)),{readSync:D2,openSync:L2,createReadStream:wC}=require("fs"),{open:M2}=require("lmdb"),CC=Mc(),P2=Pc(),{AUDIT_STORE_OPTIONS:U2}=(ti(),ie(MC)),{INTERNAL_DBIS_NAME:v2,AUDIT_STORE_NAME:B2}=ft();DC.exports=H2;var nS=32768,x2=100;async function H2(e){let t=e.database||e.schema||"data",r=C2()[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 l=_.dbisDB,d=M2({noSync:!0,maxDbs:P2.MAX_DBS}),E,f=d.openDB(v2,new CC(!1)),h=l.useReadTransaction(),p=0,S=a(async function(R,b){b.encoding="binary",b.encoder=void 0;let C=d.openDB(R,b),x=l.openDB(R,b);for(let{key:v,version:F,value:M}of x.getRange({start:null,transaction:h,versions:x.useVersions}))E=C.put(v,M,F),p++%x2===0&&(await new Promise(Q=>setTimeout(Q,20)),h.openTimer&&(h.openTimer=0))},"copyDatabase");for(let{key:R,value:b}of l.getRange({transaction:h,start:!1}))if(s.some(C=>R.startsWith?.(C+"/"))){f.put(R,b);let[,C]=R.split("/"),x=!C,v=new CC(!x,x);await S(R,v)}e.include_audit&&await S(B2,Object.assign({},U2)),await E;let T=wC(d.path);return T.headers=u(),T.on("close",()=>{h.done(),d.close()}),T}let o=r[Object.keys(r)[0]].primaryStore,c=L2(o.path);return o.transaction(()=>{let _=Buffer.alloc(nS);D2(c,_,0,nS),o.resetReadTxn();let l=o.useReadTransaction();l.renew();let d=wC(null,{fd:c,start:nS}),E=new w2.from(async function*(){yield _;for await(let f of d)l.openTimer&&(l.openTimer=0),yield f;l.done()}());return E.headers=u(),E});function u(){let _=new Map;return _.set("content-type","application/octet-stream"),_.set("content-disposition",`attachment; filename="${t}"`),_.set("date",n),_}}a(H2,"getBackup")});var vC=g((xde,UC)=>{"use strict";var G2=$(),{handleHDBError:q2}=ne(),F2=Wb(),k2=D_(),V2=Np(),$2=YI(),Y2=Jc(),K2=Pp(),W2=pw(),Q2=Nw(),z2=eu(),J2=Uw(),j2=Yw(),X2=Xw(),Z2=eC(),e4=sC(),t4=_C(),r4=kp(),n4=hC(),s4=RC(),i4=OC(),PC=IC(),o4=LC(),sS=class extends F2{static{a(this,"LMDBBridge")}async searchByConditions(t){return J2(t)}async getDataByHash(t){return await K2(t)}async searchByHash(t){return await W2(t)}async getDataByValue(t,r){return await Q2(t,r)}async searchByValue(t){return await z2(t)}async createSchema(t){return await $2(t)}async dropSchema(t){return await j2(t)}async createTable(t,r){return await X2(t,r)}async dropTable(t){return await r4(t)}async createAttribute(t){return await k2(t)}async createRecords(t){return await V2(t)}async updateRecords(t){return await Z2(t)}async upsertRecords(t){try{return await e4(t)}catch(r){throw q2(r,null,null,G2.ERR,r)}}async deleteRecords(t){return await Y2(t)}async dropAttribute(t){return await n4(t)}async deleteAuditLogsBefore(t){return await t4(t)}async readAuditLog(t){return await s4(t)}writeTransaction(t,r,n){return i4.writeTransaction(t,r,n)}flush(t,r){return PC.flush(t,r)}resetReadTxn(t,r){return PC.resetReadTxn(t,r)}getBackup(t){return o4(t)}};UC.exports=sS});function l4(){u4=setInterval(function(){for(let e of iS)if(e.stale){let t=e[be]?.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},c4).unref()}var oS,HC,GC,qC,FC,kC,BC,iS,a4,su,xC,to,Ed,c4,u4,aS=Re(()=>{oS=B(vr()),HC=B(ne()),GC=B($());Nn();qC=B(Z()),FC=B(P()),kC=B(z()),BC=100,iS=new Set,a4=(0,kC.convertToMS)(qC.get(FC.CONFIG_PARAMS.STORAGE_MAXTRANSACTIONQUEUETIME))||45e3,to=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),iS.add(this),this.readTxn}useReadTxn(){return this.getReadTxn(),this.readTxn.use(),this.readTxnsUsed++,this.readTxn}doneReadTxn(){this.readTxn&&(this.readTxn.done(),--this.readTxnsUsed===0&&(iS.delete(this),this.readTxn=null))}disregardReadTxn(){--this.readTxnRefCount===0&&this.readTxnsUsed===1&&this.doneReadTxn()}checkOverloaded(){if(su&&!this.overloadChecked&&performance.now()-xC>a4)throw new HC.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,oS.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"),u=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,u);s=s||E}else u();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)<BC>>n?u():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 su||(su=s,xC=performance.now(),su.then(()=>{su=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)+BC/2),t?t.retries=n+1:t={retries:1},this.commit(t)));let l={txnTime:r};if(this.next){let d=this.next?.commit(t);if(d?.then)return d?.then(E=>({txnTime:r,next:E}));l.next=d}return l}abort(){for(;this.readTxnsUsed>0;)this.doneReadTxn();this.open=0,this.writes=[]}},Ed=class extends to{static{a(this,"ImmediateTransaction")}_timestamp;addWrite(t){super.addWrite(t),this.commit()}get timestamp(){return this._timestamp||(this._timestamp=(0,oS.getNextMonotonicTime)())}getReadTxn(){}},c4=3e4;a(l4,"startMonitoringTxns");l4()});function Ze(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 to;e.timestamp&&(n.timestamp=e.timestamp),n[be]=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 u=n.commit({letItLinger:r?.letItLinger});return u.then?u.then(()=>c):c}function o(c){throw n.abort({}),c}}var VC,ro=Re(()=>{VC=require("../index");Nn();aS();a(Ze,"transaction");(0,VC._assignPackageExport)("transaction",Ze);Ze.commit=function(e){let t=(e[be]||e)?.transaction;if(!t)throw new Error("No active transaction is available to commit");return t.commit()};Ze.abort=function(e){let t=(e[be]||e)?.transaction;if(!t)throw new Error("No active transaction is available to abort");return t.abort()}});var XC={};Fe(XC,{ResourceBridge:()=>lS});function _S({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 YC(e,t){let r=ns(e),n=_S(e,r);if(!r)throw new Pn.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;Ze(i,()=>new Promise(_=>o=_));let c=e.ids||e.hash_values,u=0;return{[Symbol.asyncIterator](){return{async next(){if(u<c.length){let _=c[u++],l=await r.get({id:_,lazy:s,select:n},i);return l=l&&md(l),t?{value:{key:_,value:l}}:{value:l}}else return o(),{done:!0}},return(_){return o(),{value:_,done:!0}},throw(_){return o(),{done:!0}}}}}}function ns(e){let t=e.database||e.schema||d4,r=mr()[t];if(!r)throw(0,Pn.handleHDBError)(new Error,_4.SCHEMA_NOT_FOUND(t),404);return r[e.table]}function KC(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:u}=s;n?.timestamp===c?(n.hash_values.push(o),n.records.push(u)):(n&&(yield n),n={operation:i,user_name:s.user,timestamp:c,hash_values:[o],records:[u]})}n&&(yield n)}var QC,hd,Pn,zC,JC,Un,cS,uS,jC,_4,d4,f4,E4,$C,lS,ZC=Re(()=>{"use strict";QC=B(vC()),hd=B(sa()),Pn=B(ne());Ae();zC=B(Gc()),JC=B(Fc()),Un=B(P()),cS=B(ys()),uS=B(Mn()),jC=B(z());ro();pd();({HDB_ERROR_MSGS:_4}=Pn.hdb_errors),d4="data",f4=1e4,E4=10,lS=class extends QC.default{static{a(this,"ResourceBridge")}constructor(t){super(t),$C=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,hd.default)(t,"conditions");if(r)throw(0,Pn.handleHDBError)(r,r.message,400,void 0,void 0,!0);let n=ns(t);if(!n)throw new Pn.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:_S(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 Pn.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}]}Et({database:r.schema,table:r.table,attributes:n,schemaDefined:s,expiration:r.expiration})}async createAttribute(t){return await ns(t).addAttributes([{name:t.attribute,indexed:t.indexed??!0}]),`attribute ${t.schema}.${t.table}.${t.attribute} successfully created.`}async dropAttribute(t){let r=ns(t);if(await r.removeAttributes([t.attribute]),!r.schemaDefined){let n=t.attribute,s,i=a((o,c,u)=>(c=Object.assign({},c),delete c[n],r.primaryStore.ifVersion(o,u,()=>r.primaryStore.put(o,c,u)).then(_=>{if(!_){let{value:l,version:d}=r.primaryStore.getEntry(o);return i(o,l,d)}})),"deleteRecord");for(let{key:o,value:c,version:u}of r.primaryStore.getRange({start:!0,versions:!0}))s=i(o,c,u),await new Promise(_=>setImmediate(_));await s}return`successfully deleted ${t.schema}.${t.table}.${t.attribute}`}dropTable(t){ns(t).dropTable()}createSchema(t){return ca({database:t.schema,table:null}),cS.signalSchemaChange(new uS.SchemaEventMsg(process.pid,Un.OPERATIONS_ENUM.CREATE_SCHEMA,t.schema))}async dropSchema(t){await dS(t.schema),cS.signalSchemaChange(new uS.SchemaEventMsg(process.pid,Un.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,$C.upsertRecords(t)}async upsertRecords(t){let{schema_table:r,attributes:n}=(0,zC.default)(t);(0,JC.default)(t,n,r.primaryKey);let s,i=mr()[t.schema][t.table],o={user:t.hdb_user,expiresAt:t.expiresAt};return Ze(o,async c=>{if(!i.schemaDefined){s=[];for(let l of n)i.attributes.find(E=>E.name==l)||s.push(l);s.length>0&&await i.addAttributes(s.map(l=>({name:l,indexed:!0})))}let u=[],_=[];for(let l of t.records){let d=await i.get(l[i.primaryKey],o);if(t.requires_existing&&!d||t.requires_no_existing&&d){_.push(l[i.primaryKey]);continue}d&&(d=md(d));for(let E in l)if(Object.prototype.hasOwnProperty.call(l,E)){let f=l[E];if(typeof f=="function")try{let h=f([[d]]);Array.isArray(h)&&(f=h[0].func_val,l[E]=f)}catch(h){throw h.message+="Trying to set key "+E+" on object"+JSON.stringify(l),h}}if(d)for(let E in d)Object.prototype.hasOwnProperty.call(l,E)||(l[E]=d[E]);await i.put(l,o),u.push(l[i.primaryKey])}return{txn_time:c.timestamp,written_hashes:u,new_attributes:s,skipped_hashes:_}})}async deleteRecords(t){let r=mr()[t.schema][t.table],n={user:t.hdb_user};return Ze(n,async s=>{let i=t.hash_values||t.records.map(u=>u[r.primaryKey]),o=[],c=[];for(let u of i)await r.delete(u,n)?o.push(u):c.push(u);return KC(o,c,s.timestamp)})}async deleteRecordsBefore(t){let r=mr()[t.schema][t.table];if(!r.createdTimeProperty)throw new Pn.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:Un.VALUE_SEARCH_COMPARATORS.LESS}]}),s=!1,i=[],o=[],c=0,u=[],_=a(async()=>{let l=await this.deleteRecords({schema:t.schema,table:t.table,hash_values:u});i.push(...l.deleted_hashes),o.push(...l.skipped_hashes),await(0,jC.async_set_timeout)(E4),u=[],s=!0},"chunkDelete");for await(let l of n)u.push(l[r.primaryKey]),c++,c%f4===0&&await _();return u.length>0&&await _(),s?KC(i,o,void 0):{message:"No records found to delete"}}searchByHash(t){t.select!==void 0&&(t.get_attributes=t.select);let r=(0,hd.default)(t,"hashes");if(r)throw r;return YC(t)}async getDataByHash(t){let r=new Map;t._returnKeyValue=!0;for await(let{key:n,value:s}of YC(t,!0))r.set(n,s);return r}searchByValue(t,r){if(r&&Un.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,hd.default)(t,"value");if(n)throw n;let s=ns(t);if(!s)throw new Pn.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===Un.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:_S(t,s)})}async getDataByValue(t,r){let n=new Map,s=ns(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){ns({schema:t,table:r})?.primaryStore.resetReadTxn()}async deleteAuditLogsBefore(t){return ns(t).deleteHistory(t.timestamp)}async readAuditLog(t){let r=ns(t),n={};switch(t.search_type){case Un.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 Un.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(_S,"getSelect");a(YC,"getRecords");a(ns,"getTable");a(KC,"createDeleteResponse");a(WC,"groupRecordsInHistory")});var Cn=g((Xde,eD)=>{"use strict";var{ResourceBridge:h4}=(ZC(),ie(XC)),m4=Z();m4.initSync();var Sd;function p4(){return Sd||(Sd=new h4,Sd)}a(p4,"getBridge");eD.exports=p4()});var sD=g((efe,nD)=>{"use strict";var tD=require("lodash"),iu=require("mathjs"),S4=require("jsonata"),rD=z();nD.exports={distinct_array:e=>Array.isArray(e)&&e.length>1?tD.uniqWith(e,tD.isEqual):e,searchJSON:T4,mad:ou.bind(null,iu.mad),mean:ou.bind(null,iu.mean),mode:ou.bind(null,iu.mode),prod:ou.bind(null,iu.prod),median:ou.bind(null,iu.median)};function ou(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(ou,"aggregateFunction");function T4(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(rD.isEmpty(this.__ala__.res)&&(this.__ala__.res={}),rD.isEmpty(this.__ala__.res[r])){let n=S4(e);this.__ala__.res[r]=n}return this.__ala__.res[r].evaluate(t)}a(T4,"searchJSON")});var oD=g((rfe,iD)=>{"use strict";var Rt=require("moment"),fS="YYYY-MM-DDTHH:mm:ss.SSSZZ";Rt.suppressDeprecationWarnings=!0;iD.exports={current_date:()=>Rt().utc().format("YYYY-MM-DD"),current_time:()=>Rt().utc().format("HH:mm:ss.SSS"),extract:(e,t)=>{switch(t.toLowerCase()){case"year":return Rt(e).utc().format("YYYY");case"month":return Rt(e).utc().format("MM");case"day":return Rt(e).utc().format("DD");case"hour":return Rt(e).utc().format("HH");case"minute":return Rt(e).utc().format("mm");case"second":return Rt(e).utc().format("ss");case"millisecond":return Rt(e).utc().format("SSS");default:break}},date:e=>Rt(e).utc().format(fS),date_format:(e,t)=>Rt(e).utc().format(t),date_add:(e,t,r)=>Rt(e).utc().add(t,r).valueOf(),date_sub:(e,t,r)=>Rt(e).utc().subtract(t,r).valueOf(),date_diff:(e,t,r)=>{let n=Rt(e).utc(),s=Rt(t).utc();return r?n.diff(s,r,!0):n.diff(s)},now:()=>Rt().utc().valueOf(),get_server_time:()=>Rt().format(fS),offset_utc:(e,t)=>Rt(e).utc().utcOffset(t).format(fS)}});var lD=g((nfe,uD)=>{"use strict";var g4=require("@turf/area"),R4=require("@turf/length"),A4=require("@turf/circle"),O4=require("@turf/difference"),b4=require("@turf/distance"),y4=require("@turf/boolean-contains"),N4=require("@turf/boolean-equal"),I4=require("@turf/boolean-disjoint"),w4=require("@turf/helpers"),aD=P(),Se=z(),ws=$();uD.exports={geoArea:C4,geoLength:D4,geoCircle:L4,geoDifference:M4,geoDistance:cD,geoNear:P4,geoContains:U4,geoEqual:v4,geoCrosses:B4,geoConvert:x4};function C4(e){if(Se.isEmpty(e))return NaN;typeof e=="string"&&(e=Se.autoCastJSON(e));try{return g4.default(e)}catch(t){return ws.trace(t,e),NaN}}a(C4,"geoArea");function D4(e,t){if(Se.isEmpty(e))return NaN;typeof e=="string"&&(e=Se.autoCastJSON(e));try{return R4.default(e,{units:t||"kilometers"})}catch(r){return ws.trace(r,e),NaN}}a(D4,"geoLength");function L4(e,t,r){if(Se.isEmpty(e))return NaN;if(Se.isEmpty(t))return NaN;typeof e=="string"&&(e=Se.autoCastJSON(e));try{return A4.default(e,t,{units:r||"kilometers"})}catch(n){return ws.trace(n,e,t),NaN}}a(L4,"geoCircle");function M4(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 O4(e,t)}catch(r){return ws.trace(r,e,t),NaN}}a(M4,"geoDifference");function cD(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 b4.default(e,t,{units:r||"kilometers"})}catch(n){return ws.trace(n,e,t),NaN}}a(cD,"geoDistance");function P4(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 cD(e,t,n)<=r}catch(s){return ws.trace(s,e,t),!1}}a(P4,"geoNear");function U4(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 y4.default(e,t)}catch(r){return ws.trace(r,e,t),!1}}a(U4,"geoContains");function v4(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 N4.default(e,t)}catch(r){return ws.trace(r,e,t),!1}}a(v4,"geoEqual");function B4(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!I4.default(e,t)}catch(r){return ws.trace(r,e,t),!1}}a(B4,"geoCrosses");function x4(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(aD.GEO_CONVERSION_ENUM[t]))throw new Error(`geo_type of ${t} is invalid please use one of the following types: ${Object.keys(aD.GEO_CONVERSION_ENUM).join(",")}`);return typeof e=="string"&&(e=Se.autoCastJSON(e)),w4[t](e,r)}a(x4,"geoConvert")});var Td=g((ife,_D)=>{var no=sD(),Kr=oD(),ss=lD();_D.exports=e=>{e.aggr.mad=e.aggr.MAD=no.mad,e.aggr.mean=e.aggr.MEAN=no.mean,e.aggr.mode=e.aggr.MODE=no.mode,e.aggr.prod=e.aggr.PROD=no.prod,e.aggr.median=e.aggr.MEDIAN=no.median,e.fn.distinct_array=e.fn.DISTINCT_ARRAY=no.distinct_array,e.fn.search_json=e.fn.SEARCH_JSON=no.searchJSON,e.fn.__ala__=e,e.fn.current_date=e.fn.CURRENT_DATE=Kr.current_date,e.fn.current_time=e.fn.CURRENT_TIME=Kr.current_time,e.fn.extract=e.fn.EXTRACT=Kr.extract,e.fn.date=e.fn.DATE=Kr.date,e.fn.date_format=e.fn.DATE_FORMAT=Kr.date_format,e.fn.date_add=e.fn.DATE_ADD=Kr.date_add,e.fn.date_sub=e.fn.DATE_SUB=Kr.date_sub,e.fn.date_diff=e.fn.DATE_DIFF=e.fn.datediff=e.fn.DATEDIFF=Kr.date_diff,e.fn.now=e.fn.NOW=Kr.now,e.fn.offset_utc=e.fn.OFFSET_UTC=Kr.offset_utc,e.fn.get_server_time=e.fn.GET_SERVER_TIME=Kr.get_server_time,e.fn.getdate=e.fn.GETDATE=Kr.now,e.fn.current_timestamp=e.fn.CURRENT_TIMESTAMP=Kr.now,e.fn.geoarea=e.fn.GEOAREA=e.fn.geoArea=ss.geoArea,e.fn.geocircle=e.fn.GEOCIRCLE=e.fn.geoCircle=ss.geoCircle,e.fn.geocontains=e.fn.GEOCONTAINS=e.fn.geoContains=ss.geoContains,e.fn.geoconvert=e.fn.GEOCONVERT=e.fn.geoConvert=ss.geoConvert,e.fn.geocrosses=e.fn.GEOCROSSES=e.fn.geoCrosses=ss.geoCrosses,e.fn.geodifference=e.fn.GEODIFFERENCE=e.fn.geoDifference=ss.geoDifference,e.fn.geodistance=e.fn.GEODISTANCE=e.fn.geoDistance=ss.geoDistance,e.fn.geoequal=e.fn.GEOEQUAL=e.fn.geoEqual=ss.geoEqual,e.fn.geolength=e.fn.GEOLENGTH=e.fn.geoLength=ss.geoLength,e.fn.geonear=e.fn.GEONEAR=e.fn.geoNear=ss.geoNear}});var hD=g((ofe,ED)=>{"use strict";var au=require("lodash"),pr=require("alasql");pr.options.cache=!1;var H4=Td(),dD=require("clone"),gd=require("recursive-iterator"),_e=$(),De=z(),ua=Cn(),G4=P(),{hdb_errors:q4}=ne(),{getDatabases:fD}=(Ae(),ie(ke)),F4="IS NULL",vn="There was a problem performing this search. Please check the logs and try again.";H4(pr);var ES=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(vn)}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(vn)}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(vn)}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(vn)}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(vn)}}_getColumns(){let t=new gd(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(dD(r)))}_getTables(){let t=[];this.all_table_attributes.forEach(r=>{t.push(r.table)}),this.tables=au.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=fD()[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 gd(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 gd(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(G4.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 u=Array.isArray(r.right)?r.right:r.left;for(let _=0;_<u.length;_++)if(u[_].value)n.add(u[_].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&&au.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(dD(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(F4)>-1&&this.tables.forEach(s=>{let i={columnid:fD()[s.databaseid][s.tableid].primaryKey,tableid:s.tableid};this._addFetchColumns([i])}),this.statement.order&&(this._updateOrderByToAliases(),this._addNonAggregatorsToFetchColumns()),this.fetch_attributes=au.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]},u=!1,_=[s.table.databaseid,s.table.tableid,s.attribute].join("/");if(s.attribute===o&&(u=!0),!De.isEmpty(this.exact_search_values[_])&&!this.exact_search_values[_].ignore&&!De.isEmptyOrZeroLength(this.exact_search_values[_].values))if(u)try{c.hash_values=Array.from(this.exact_search_values[_].values);let l=await ua.getDataByHash(c);for(let d of c.hash_values)l.get(d)&&!this.data[i].__merged_data[d]&&(this.data[i].__merged_data[d]=[...n[i]],this._setMergedHashAttribute(i,d))}catch(l){throw _e.error("Error thrown from getDataByHash function in SQLSearch class method getFetchAttributeValues exact match."),_e.error(l),new Error(vn)}else try{c.search_attribute=s.attribute,await Promise.all(Array.from(this.exact_search_values[_].values).map(async l=>{let d=Object.assign({},c);d.search_value=l;let E=await ua.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(l){throw _e.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues exact match."),_e.error(l),new Error(vn)}else if(!De.isEmpty(this.comparator_search_values[_])&&!this.comparator_search_values[_].ignore&&!De.isEmptyOrZeroLength(this.comparator_search_values[_].comparators))try{let l=this.comparator_search_values[_].comparators;for(let d=0,E=l.length;d<E;d++){let f=l[d];c.search_attribute=f.attribute,c.search_value=f.search_value;let h=await ua.getDataByValue(c,f.operation);if(u)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(l){throw _e.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues comparator search values."),_e.error(l),new Error(vn)}else try{c.search_attribute=s.attribute,c.search_value="*";let l=await ua.getDataByValue(c);if(u)for(let[d]of l)this.data[i].__merged_data[d]||(this.data[i].__merged_data[d]=[...n[i]],this._setMergedHashAttribute(i,d));else for(let[d,E]of l)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(l){throw _e.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues no comparator search values."),_e.error(l),new Error(vn)}}}_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 u=this.statement.where?"WHERE "+this.statement.where:"";u=u.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 l="",d="";!this.has_aggregator&&!this.statement.group&&!this.has_ordinal&&!this.statement.joins&&(l=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(" ")} ${u} ${_} ${l} ${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=au.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 gd(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=au.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(vn)}}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 l in i)o.push(i[l][0]);this.data[n].__merged_attributes.push(...s.columns);let c={schema:s.schema,table:s.table,hash_values:o,get_attributes:s.columns},u=await ua.getDataByHash(c),_=s.columns.length;for(let l=0,d=o.length;l<d;l++){let E=o[l],f=u.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,u=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===u}).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(q4.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 u=s[i],_=new RegExp(`${u}.\`${o}\``,"g"),l=`${u}.[${c}]`;n=n.replace(_,l)});for(let i in this.data)this.data[i].__merged_attributes.forEach((o,c)=>{let u=new RegExp(`\`${o}\``,"g"),_=`[${c}]`;n=n.replace(u,_)});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 ua.getDataByValue(i);for(let[c,u]of o)this.data[s].__merged_data[c]||(u[n.attribute]===void 0&&(u[n.attribute]=null),this.data[s].__merged_data[c]=Object.assign({},r[s])),this.data[s].__merged_data[c][t[n.attribute]]=u[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(vn)}}return Object.values(Object.values(this.data)[0].__merged_data)}};ED.exports=ES});var Gr=g((cfe,mD)=>{"use strict";var k4=Yb();mD.exports={searchByConditions:$4,searchByHash:Y4,searchByValue:K4,search:W4};var hS=Cn(),{transformReq:mS}=z(),V4=hD();async function $4(e){return mS(e),hS.searchByConditions(e)}a($4,"searchByConditions");async function Y4(e){mS(e),e.ids&&(e.hash_values=e.ids);let t=[];for await(let r of hS.searchByHash(e))r&&t.push(r);return t}a(Y4,"searchByHash");async function K4(e){mS(e),e.hasOwnProperty("desc")===!0&&(e.reverse=e.desc);let t=[];for await(let r of hS.searchByValue(e))t.push(r);return t}a(K4,"searchByValue");function W4(e,t){try{let r=new k4(e);r.validate(),new V4(r.statement,r.attributes).search().then(s=>{t(null,s)}).catch(s=>{t(s,null)})}catch(r){return t(r)}}a(W4,"search")});var Rd=g((lfe,pD)=>{"use strict";var Q4=Cn();pD.exports={writeTransaction:z4};function z4(e,t,r){return Q4.writeTransaction(e,t,r)}a(z4,"writeTransaction")});var RD=g((ffe,gD)=>{"use strict";var J4=Gr(),j4=bs(),SD=$(),X4=qr(),dfe=Rd(),Z4=require("clone"),SS=require("alasql"),e3=Td(),TD=require("util"),t3=TD.promisify(j4.getTableSchema),r3=TD.promisify(J4.search),n3=P(),pS=z();e3(SS);gD.exports={update:i3};var s3="There was a problem performing this update. Please check the logs and try again.";async function i3({statement:e,hdb_user:t}){let r=await t3(e.table.databaseid,e.table.tableid),n=o3(e.columns);pS.backtickASTSchemaItems(e);let{table:s,where:i}=e,o=Z4(s),c=pS.isEmpty(i)?"":` WHERE ${i.toString()}`,u=`SELECT ${r.hash_attribute} FROM ${s.toString()} ${c}`,_=SS.parse(u).statements[0],l=await r3(_),d=a3(n,l);return c3(o,d,t)}a(i3,"update");function o3(e){try{let t={};return e.forEach(r=>{"value"in r.expression?t[r.column.columnid]=r.expression.value??null:t[r.column.columnid]=SS.compile(`SELECT ${r.expression.toString()} AS [${n3.FUNC_VAL}] FROM ?`)}),t}catch(t){throw SD.error(t),new Error(s3)}}a(o3,"createUpdateRecord");function a3(e,t){return pS.isEmptyOrZeroLength(t)?[]:t.map(r=>Object.assign(r,e))}a(a3,"buildUpdateRecords");async function c3(e,t,r){let n={operation:"update",schema:e.databaseid_orig,table:e.tableid_orig,records:t,hdb_user:r},s=await X4.update(n);try{delete s.new_attributes,delete s.txn_time}catch(i){SD.error(`Error delete new_attributes from update response: ${i}`)}return s}a(c3,"updateRecords")});var OD=g((pfe,AD)=>{var u3=require("alasql"),l3=Gr(),_3=$(),d3=Cn(),gS=require("util"),TS=z(),f3=P(),E3=bs(),hfe=Rd(),mfe=qr(),h3="record",m3="successfully deleted",p3=gS.callbackify(R3),S3=gS.promisify(l3.search),T3=gS.promisify(E3.getTableSchema);AD.exports={convertDelete:p3};function g3(e){return`${e.deleted_hashes.length} ${h3}${e.deleted_hashes.length===1?"":"s"} ${m3}`}a(g3,"generateReturnMessage");async function R3({statement:e,hdb_user:t}){let r=await T3(e.table.databaseid,e.table.tableid);TS.backtickASTSchemaItems(e);let{table:n,where:s}=e,i=TS.isEmpty(s)?"":` WHERE ${s.toString()}`,o=`SELECT ${r.hash_attribute} FROM ${n.toString()} ${i}`,c=u3.parse(o).statements[0],u={operation:f3.OPERATIONS_ENUM.DELETE,schema:n.databaseid_orig,table:n.tableid_orig,hdb_user:t};try{u.records=await S3(c);let _=await d3.deleteRecords(u);return TS.isEmptyOrZeroLength(_.message)&&(_.message=g3(_)),delete _.txn_time,_}catch(_){throw _3.error(_),_.hdb_code?_.message:_}}a(R3,"convertDelete")});var wD=g((Tfe,ID)=>{"use strict";var A3=Os(),{hdb_errors:bD}=ne(),{getDatabases:yD}=(Ae(),ie(ke));ID.exports={checkSchemaExists:ND,checkSchemaTableExists:O3,schema_describe:A3};async function ND(e){if(!yD()[e])return bD.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}a(ND,"checkSchemaExists");async function O3(e,t){let r=await ND(e);if(r)return r;if(!yD()[e][t])return bD.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(O3,"checkSchemaTableExists")});var cu=g((Rfe,b3)=>{b3.exports={name:"harperdb",version:"4.3.20",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","cloud","enterprise","Fastify","NATS"],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.535.0","@aws-sdk/lib-storage":"3.535.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.12",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 fu={};Fe(fu,{addAnalyticsListener:()=>du,recordAction:()=>Sr,recordActionBinary:()=>Wr,setAnalyticsEnabled:()=>y3});function y3(e){xD=e}function Sr(e,t,r,n,s){if(!xD)return;let i=t+(r?"-"+r:"");n!==void 0&&(i+="-"+n),s!==void 0&&(i+="-"+s);let o=bd.get(i);if(o)if(typeof e=="number"){let c=o.values,u=c.index++;if(u>=c.length){let _=c;o.values=c=new Float32Array(u*2),c.set(_),c.index=u+1}c[u]=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},bd.set(i,o)}Ad||N3()}function Wr(e,t,r,n,s){Sr(!!e,t,r,n,s)}function du(e){qD.push(e)}function N3(){Ad=performance.now(),setTimeout(async()=>{let e=performance.now()-Ad;Ad=0;let t=[],r={time:Date.now(),period:e,threadId:so.threadId,metrics:t};for(let[s,i]of bd){if(i.values){let o=i.values.subarray(0,i.values.index);o.sort();let c=o.length,u=0,_=[],l;for(let d of FD){let E=Math.floor(c*d),f=o[E-1];if(E>u){let h=E-u;if(f===l){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),l=f;u=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 kD()}let n=process.memoryUsage();t.push({metric:"memory",threadId:so.threadId,byThread:!0,...n});for(let s of qD)s(t);bd=new Map,so.parentPort?so.parentPort.postMessage({type:GD,report:r}):YD({report:r})},HD).unref()}async function I3(e,t=6e4){let r=OS(),n=VD(),s=new Promise(p=>{let S=performance.now();setImmediate(()=>{let T=performance.now();T-S>5e3&&(0,uu.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,uu.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,u=new Map,_=[],l;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;l=p;let{metrics:T,threadId:R}=S;for(let b of T||[]){let{path:C,method:x,type:v,metric:F,count:M,total:Q,distribution:J,threads:j,...ae}=b;M||(M=1);let ce=F+(C?"-"+C:"");x!==void 0&&(ce+="-"+x),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=u.get(ce);Ge?Ge.push(...J):u.set(ce,J)}}await kD()}for(let p of _){let{path:S,method:T,type:R,metric:b,count:C,total:x,distribution:v,threads:F,...M}=p;F=F.filter(Q=>Q);for(let Q in M){if(typeof p[Q]!="number")continue;let J=0;for(let j of F){let ae=j[Q];typeof ae=="number"&&(J+=ae)}p[Q]=J}p.count=F.length,delete p.threads,delete p.byThread}for(let[p,S]of u){let T=c.get(p);S.sort((Ne,ve)=>Ne.value>ve.value?1:-1);let R=T.count-1,b=[],C=0,x=0,v;for(let Ne of FD){let ve=R*Ne;for(;C<ve;)v=S[x++],C+=v.count,x===1&&C--;let Xl=S[x>1?x-2:0];v||(v=S[0]),b.push(v.value-(v.value-Xl.value)*(C-ve)/v.count)}let[F,M,Q,J,j,ae,ce,ge,Ge]=b;Object.assign(T,{p1:F,p10:M,p25:Q,median:J,p75:j,p90:ae,p95:ce,p99:ge,p999:Ge})}let d;for(let[p,S]of c)S.id=(0,Od.getNextMonotonicTime)(),S.time=l,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,Od.getNextMonotonicTime)(),S={id:p,metric:"main-thread-utilization",idle:f-CD,active:h-DD,taskQueueLatency:await s,time:E,...process.memoryUsage()};n.primaryStore.put(p,S,{append:!0}).then(T=>{T||n.primaryStore.put(p,S)})}CD=f,DD=h}async function LD(e,t){let r=Date.now()-t;for(let n of e.primaryStore.getKeys({start:!1,end:r}))e.primaryStore.remove(n)}function OS(){return MD||(MD=Et({table:"hdb_raw_analytics",database:"system",audit:!1,trackDeletes:!1,attributes:[{name:"id",isPrimaryKey:!0},{name:"action"},{name:"metrics"}]}))}function VD(){return PD||(PD=Et({table:"hdb_analytics",database:"system",audit:!1,trackDeletes:!1,attributes:[{name:"id",isPrimaryKey:!0},{name:"metric"},{name:"path"},{name:"method"},{name:"type"}]}))}function D3(){$D=!0;let e=(0,_u.get)(AS.CONFIG_PARAMS.ANALYTICS_AGGREGATEPERIOD)*1e3;e&&setInterval(async()=>{await I3(HD,e),await LD(OS(),w3),await LD(VD(),C3)},Math.min(e/2,2147483647)).unref()}function YD(e,t){let r=e.report;r.threadId=t?.threadId||so.threadId;for(let n of r.metrics)n.metric==="bytes-sent"&&(UD+=n.mean*n.count);r.totalBytesProcessed=UD,t&&(r.metrics.push({metric:"utilization",...t.performance.eventLoopUtilization(vD.get(t))}),vD.set(t,t.performance.eventLoopUtilization())),r.id=(0,Od.getNextMonotonicTime)(),OS().primaryStore.put(r.id,r),$D||D3(),L3&&(KD=P3(r))}async function P3(e){if(await KD,!_i){let r=(0,lu.dirname)((0,uu.getLogFilePath)());try{_i=await(0,RS.open)((0,lu.join)(r,"analytics.log"),"r+")}catch{_i=await(0,RS.open)((0,lu.join)(r,"analytics.log"),"w+")}}let t=(await _i.stat()).size;if(t>M3){let r=Buffer.alloc(t);await _i.read(r,{position:0}),r=r.subarray(r.indexOf(10,r.length/2)+1),await _i.write(r,{position:0}),await _i.truncate(r.length),t=r.length}await _i.write(JSON.stringify(e)+`
|
|
8
|
+
`,t)}var so,BD,uu,lu,RS,Od,_u,AS,bd,xD,Ad,HD,GD,qD,FD,CD,DD,kD,w3,C3,MD,PD,$D,UD,vD,L3,KD,_i,M3,Cs=Re(()=>{so=require("worker_threads"),BD=B(We());Ae();uu=B($()),lu=require("path"),RS=require("fs/promises"),Od=B(vr()),_u=B(Z()),AS=B(P());lr();(0,_u.initSync)();bd=new Map,xD=(0,_u.get)(AS.CONFIG_PARAMS.ANALYTICS_AGGREGATEPERIOD)>-1;a(y3,"setAnalyticsEnabled");a(Sr,"recordAction");at.recordAnalytics=Sr;a(Wr,"recordActionBinary");Ad=0,HD=1e3,GD="analytics-report",qD=[];a(du,"addAnalyticsListener");FD=[.01,.1,.25,.5,.75,.9,.95,.99,.999,1];a(N3,"sendAnalytics");a(I3,"aggregation");CD=0,DD=0,kD=a(()=>new Promise(setImmediate),"rest");a(LD,"cleanup");w3=36e5,C3=31536e6;a(OS,"getRawAnalyticsTable");a(VD,"getAnalyticsTable");(0,BD.setChildListenerByType)(GD,YD);a(D3,"startScheduledTasks");UD=0,vD=new Map,L3=!1;a(YD,"recordAnalytics");M3=1e6;a(P3,"logAnalytics")});var wS=g((Ufe,nL)=>{"use strict";var{decode:U3}=require("msgpackr"),{isMainThread:Lfe,parentPort:Mfe,threadId:Pfe}=require("worker_threads"),Id=ut(),la=Ve(),NS=P(),nr=$(),yS=Z(),v3=P(),{onMessageByType:B3}=We(),zD=As(),{recordAction:x3,recordActionBinary:H3}=(Cs(),ie(fu)),{publishToStream:G3}=Id,{ConsumerEvents:WD}=require("nats"),q3=Gr(),{promisify:F3}=require("util"),JD=F3(setTimeout),wd=1e4,Cd,Nd,k3,V3,jD,Eu=new Map,_a=new Map;nL.exports={initialize:XD,ingestConsumer:IS,setSubscription:$3,setIgnoreOrigin:W3,getDatabaseSubscriptions:K3,updateConsumer:ZD};async function XD(){B3(NS.ITC_EVENT_TYPES.NATS_CONSUMER_UPDATE,async n=>{await ZD(n)}),jD=!0,nr.notify("Initializing clustering ingest service.");let{connection:e,jsm:t,js:r}=await Id.getNATSReferences();Cd=e,Nd=e.info.server_name,k3=t,V3=r}a(XD,"initialize");async function ZD(e){if(e.status==="start"){let{js:t,jsm:r}=await eL(e.node_domain_name);IS(e.stream_name,t,r,e.node_domain_name)}else if(e.status==="stop"){let t=Eu.get(e.stream_name+e.node_domain_name);t&&(nr.notify("Closing ingest consumer for node:",e.node_domain_name,"stream:",e.stream_name),await t.close?.(),Eu.set(e.stream_name+e.node_domain_name,"close")),_a.get(e.node_domain_name)==="failed"&&_a.set(e.node_domain_name,"close")}}a(ZD,"updateConsumer");var Dd=new Map;function $3(e,t,r){let n=Dd.get(e);n||Dd.set(e,n=new Map),n.set(t,r),jD||XD().then(Y3)}a($3,"setSubscription");async function Y3(){let e=await q3.searchByValue({database:"system",table:"hdb_nodes",search_attribute:"name",search_value:"*"});for await(let t of e){let r=t.name+la.SERVER_SUFFIX.LEAF,n,s;for(let i of t.subscriptions)if(i.subscribe===!0){if(!n&&({js:n,jsm:s}=await eL(r),!n))break;let{schema:o,table:c}=i,u=zD.createNatsTableStreamName(o,c);IS(u,n,s,r)}}}a(Y3,"accessConsumers");async function eL(e){let t,r,n=1;for(;!r;)try{t=await Cd.jetstream({domain:e}),r=await Cd.jetstreamManager({domain:e,checkAPI:!1})}catch(s){if(_a.get(e)==="close")break;_a.set(e,"failed"),n%10===1&&nr.warn("Nats ingest attempting to connect to:",e,"Nats error:",s.message);let i=n++*100<wd?n++*100:wd;await JD(i)}return{js:t,jsm:r}}a(eL,"connectToRemoteJS");function K3(){return Dd}a(K3,"getDatabaseSubscriptions");var tL;function W3(e){tL=e}a(W3,"setIgnoreOrigin");var rL=100,QD=new Array(rL),yd=0;async function IS(e,t,r,n){let{connection:s}=await Id.getNATSReferences();Cd=s,Nd=s.info.server_name;let i,o=1;for(;!i;)try{i=await t.consumers.get(e,Nd),nr.notify("Initializing ingest consumer for node:",n,"stream:",e)}catch(_){if(_a.get(n)==="close")break;o%10===1&&nr.warn("Nats ingest error getting consumer:",n,"stream:",e,"Nats error:",_.message),_.code==="404"&&(nr.notify("Nats ingest creating consumer for node:",n,"stream:",e),i=await Id.createConsumer(r,e,Nd,new Date(Date.now()).toISOString()));let l=o++*100<wd?o++*100:wd;await JD(l)}let c=!1,u;for(;!c;){if(Eu.get(e+n)==="close"||_a.get(n)==="close"){Eu.delete(e+n),c=!0;continue}u=await i.consume({max_messages:yS.get(NS.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXCONSUMEMSGS)??100,bind:!0}),Eu.set(e+n,u);let _=!1;(async()=>{for await(let l of await u.status())if(l.type===WD.ConsumerDeleted&&(await u.close(),c=!0),l.type===WD.HeartbeatsMissed){let d=l.data;nr.trace(`${d} clustering ingest consumer heartbeats missed, node: ${n} stream: ${u.consumer.stream}`),d===100&&(nr.warn(`Restarting clustering ingest consumer due to missed heartbeat threshold being met, node: ${n} stream: ${u.consumer.stream}`),u.stop(),_=!0)}})();try{for await(let l of u)await QD[yd],QD[yd]=Q3(l).catch(d=>{nr.error(d)}),++yd>=rL&&(yd=0)}catch(l){l.message==="consumer deleted"?(nr.notify("Nats consumer deleted, closing messages for node:",n,"stream:",u.consumer.stream),await u.close(),c=!0):nr.error("Error consuming clustering ingest, restarting consumer",l)}}}a(IS,"ingestConsumer");async function Q3(e){let t=U3(e.data);x3(e.data.length,"bytes-received",e.subject,t.operation,"ingest"),nr.trace("Nats message processor message size:",e?.msg?._msg?.size,"bytes");let r=e.headers,n=!1,s=yS.get(NS.CONFIG_PARAMS.CLUSTERING_NODENAME);r.has(la.MSG_HEADERS.TRANSACTED_NODES)&&r.values(la.MSG_HEADERS.TRANSACTED_NODES).indexOf(s)>-1&&(n=!0);let i=r.get(la.MSG_HEADERS.ORIGIN);if(n||(n=i===s&&!tL),H3(n,"echo",e.subject,t.operation,"ingest"),n){e.ack();return}r.append(la.MSG_HEADERS.TRANSACTED_NODES,s);try{let{operation:o,schema:c,next:u,table:_,records:l,hash_values:d,__origin:E,expiresAt:f}=t;nr.trace("processing message:",o,c,_,(l?"records: "+l.map(C=>C?.id):"")+(d?"ids: "+d:""),"with sequence:",e.seq),nr.trace(`messageProcessor nats msg id: ${e.headers.get(la.MSG_HEADERS.NATS_MSG_ID)}`);let h;l||(l=d);let p=new Promise(C=>h=C),{timestamp:S,user:T,node_name:R}=E||{},b=Dd.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(l.length===1&&!u)b.send({type:bS(o),value:l[0],id:d?.[0],expiresAt:f,timestamp:S,table:_,onCommit:h,user:T,nodeName:R});else{let C=l.map((x,v)=>({type:bS(o),value:x,expiresAt:f,id:d?.[v],table:_}));for(;u;)C.push({type:bS(u.operation),value:u.record,expiresAt:u.expiresAt,id:u.id,table:u.table}),u=u.next;b.send({type:"transaction",writes:C,table:_,timestamp:S,onCommit:h,user:T,nodeName:R})}yS.get(v3.CONFIG_PARAMS.CLUSTERING_REPUBLISHMESSAGES)!==!1&&G3(e.subject.split(".").slice(0,-1).join("."),zD.createNatsTableStreamName(c,_),e.headers,e.data),await p}catch(o){nr.error(o)}e.ack()}a(Q3,"messageProcessor");function bS(e){switch(e){case"insert":case"upsert":case"update":return"put"}return e}a(bS,"convertOperation")});var ut=g((Ffe,gL)=>{"use strict";var xt=Z();xt.initSync();var z3=require("fs-extra"),J3=require("semver"),pu=require("path"),{monotonicFactory:j3}=require("ulidx"),iL=j3(),X3=require("util"),oL=require("child_process"),Z3=X3.promisify(oL.exec),ej=oL.spawn,Kt=Ve(),Ie=P(),Ld=z(),Bn=$(),Md=As(),tj=Rd(),hu=Er(),{broadcast:rj,onMessageByType:nj,getWorkerIndex:sj}=We(),{isMainThread:aL}=require("worker_threads"),{Encoder:ij,decode:MS}=require("msgpackr"),cL=new ij,{isEmpty:co}=Ld,uL=ln(),Bfe=48*36e11;aL&&nj(Ie.ITC_EVENT_TYPES.RESTART,()=>{Tr=void 0,ao=void 0});var{connect:oj,StorageType:aj,RetentionPolicy:cj,AckPolicy:PS,DeliverPolicy:US,DiscardPolicy:uj,NatsConnection:xfe,JetStreamManager:Hfe,JetStreamClient:Gfe,StringCodec:qfe,JSONCodec:lj,createInbox:vS,headers:_j,ErrorCode:sL}=require("nats"),{PACKAGE_ROOT:dj}=P(),fj=cu(),{recordAction:Ej}=(Cs(),ie(fu)),lL=lj(),hj="clustering",mj=fj.engines[Kt.NATS_SERVER_NAME],pj=pu.join(dj,"dependencies"),LS=pu.join(pj,`${process.platform}-${process.arch}`,Kt.NATS_BINARY_NAME),CS,DS,mu,io,oo;gL.exports={runCommand:_L,checkNATSServerInstalled:Sj,createConnection:BS,getConnection:Su,getJetStreamManager:Tu,getJetStream:fL,getNATSReferences:is,getServerList:gj,createLocalStream:xS,listStreams:EL,deleteLocalStream:Rj,getServerConfig:da,listRemoteStreams:Aj,viewStream:Oj,viewStreamIterator:bj,publishToStream:yj,request:wj,reloadNATS:HS,reloadNATSHub:Cj,reloadNATSLeaf:Dj,extractServerName:Ij,requestErrorHandler:Lj,createLocalTableStream:SL,createTableStreams:Uj,purgeTableStream:TL,purgeSchemaTableStreams:vj,getStreamInfo:Bj,updateLocalStreams:Hj,closeConnection:Tj,getJsmServerName:Pd,addNatsMsgHeader:hL,clearClientCache:dL,updateRemoteConsumer:Mj,createConsumer:mL,updateConsumerIterator:Pj};async function _L(e,t=void 0){let{stdout:r,stderr:n}=await Z3(e,{cwd:t});if(n)throw new Error(n.replace(`
|
|
9
9
|
`,""));return r.replace(`
|
|
10
|
-
`,"")}a(lL,"runCommand");async function Ej(){try{await Y3.access(LS)}catch{return!1}let e=await lL(`${LS} --version`,void 0),t=e.substring(e.lastIndexOf("v")+1,e.length);return K3.eq(t,dj)}a(Ej,"checkNATSServerInstalled");async function BS(e,t,r,n=!0,s="127.0.0.1"){if(!t&&!r){let o=await cL.getClusterUser();if(co(o))throw new Error("Unable to get nats connection. Cluster user is undefined.");t=o.username,r=o.decrypt_hash}Bn.trace("create nats connection called");let i=await rj({name:s,port:e,user:t,pass:r,maxReconnectAttempts:-1,waitOnFirstConnect:n,timeout:2e5,tls:{keyFile:Bt.get(Ie.CONFIG_PARAMS.CLUSTERING_TLS_PRIVATEKEY),certFile:Bt.get(Ie.CONFIG_PARAMS.CLUSTERING_TLS_CERTIFICATE),caFile:Bt.get(Ie.CONFIG_PARAMS.CLUSTERING_TLS_CERT_AUTH),rejectUnauthorized:!1}});return i.protocol.transport.socket.unref(),Bn.trace("create connection established a nats client connection with id",i?.info?.client_id),i.closed().then(o=>{o&&Bn.error("Error with Nats client connection, connection closed",o),_L()}),i}a(BS,"createConnection");function _L(){Sr=void 0,io=void 0,oo=void 0,ao=void 0}a(_L,"clearClientCache");async function hj(){Sr&&(await Sr.drain(),Sr=void 0,io=void 0,oo=void 0,ao=void 0)}a(hj,"closeConnection");var Sr,ao;async function pu(){return ao||(ao=BS(Bt.get(Ie.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),void 0,void 0),Sr=await ao),Sr||ao}a(pu,"getConnection");async function Su(){if(io)return io;co(Sr)&&await pu();let{domain:e}=_a(Ie.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);if(co(e))throw new Error("Error getting JetStream domain. Unable to get JetStream manager.");return io=await Sr.jetstreamManager({domain:e,timeout:6e4}),io}a(Su,"getJetStreamManager");async function dL(){if(oo)return oo;co(Sr)&&await pu();let{domain:e}=_a(Ie.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);if(co(e))throw new Error("Error getting JetStream domain. Unable to get JetStream manager.");return oo=Sr.jetstream({domain:e,timeout:6e4}),oo}a(dL,"getJetStream");async function ss(){let e=Sr||await pu(),t=io||await Su(),r=oo||await dL();return{connection:e,jsm:t,js:r}}a(ss,"getNATSReferences");async function mj(e){let t=Bt.get(Ie.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),{sys_name:r,decrypt_hash:n}=await cL.getClusterUser(),s=await BS(t,r,n),i=vS(),o=s.subscribe(i),c=[],u,_=(async()=>{for await(let l of o){let d=uL.decode(l.data);d.response_time=Date.now()-u,c.push(d)}})();return u=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 wd.async_set_timeout(e),await o.drain(),await s.close(),await _,c}a(mj,"getServerList");async function HS(e,t){let{jsm:r}=await ss(),n=Bt.get(Ie.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE);n=n===null?0:n*1e9;let s=Bt.get(Ie.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS);s=s===null?-1:s;let i=Bt.get(Ie.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES);i=i===null?-1:i,await r.streams.add({name:e,storage:nj.File,retention:sj.Limits,subjects:t,discard:ij.Old,max_msgs:s,max_bytes:i,max_age:n})}a(HS,"createLocalStream");async function fL(){let{jsm:e}=await ss(),t=await e.streams.list().next(),r=[];return t.forEach(n=>{r.push(n)}),r}a(fL,"listStreams");async function pj(e){let{jsm:t}=await ss();await t.streams.delete(e)}a(pj,"deleteLocalStream");async function Sj(e){let{connection:t}=await ss(),r=[],n=vS(),s=t.subscribe(n),i=(async()=>{for await(let o of s)r.push(uL.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(Sj,"listRemoteStreams");async function Tj(e,t=void 0,r=void 0){let{jsm:n,js:s}=await ss(),i=sL(),o={durable_name:i,ack_policy:PS.Explicit};t&&(o.deliver_policy=US.StartTime,o.opt_start_time=new Date(t).toISOString()),await n.consumers.add(e,o);let c=await s.consumers.get(e,i),u=r?await c.fetch({max_messages:r,expires:2e3}):await c.consume();if(c._info.num_pending===0)return[];let _=[];for await(let l of u){let d=MS(l.data),E={nats_timestamp:l.info.timestampNanos,nats_sequence:l.info.streamSequence,entry:d};if(l.headers&&(E.origin=l.headers.get(Yt.MSG_HEADERS.ORIGIN)),_.push(E),l.ack(),l.info.pending===0)break}return await c.delete(),_}a(Tj,"viewStream");async function*gj(e,t=void 0,r=void 0){let{jsm:n,js:s}=await ss(),i=sL(),o={durable_name:i,ack_policy:PS.Explicit};t&&(o.deliver_policy=US.StartTime,o.opt_start_time=new Date(t).toISOString()),await n.consumers.add(e,o);let c=await s.consumers.get(e,i),u=r?await c.fetch({max_messages:r,expires:2e3}):await c.consume();if(c._info.num_pending===0)return[];for await(let _ of u){let l=MS(_.data);l[0]||(l=[l]);for(let d of l){let E={nats_timestamp:_.info.timestampNanos,nats_sequence:_.info.streamSequence,entry:d};_.headers&&(E.origin=_.headers.get(Yt.MSG_HEADERS.ORIGIN)),yield E}if(_.ack(),_.info.pending===0)break}await c.delete()}a(gj,"viewStreamIterator");async function Rj(e,t,r,n){Bn.trace(`publishToStream called with subject: ${e}, stream: ${t}, entries:`,n.operation),r=EL(n,r);let{js:s}=await ss(),i=await Dd(),o=`${e}.${i}`,c=n instanceof Uint8Array?n:aL.encode(n);try{Bn.trace(`publishToStream publishing to subject: ${o}`),lj(c.length,"bytes-sent",e,n.operation,"replication"),await s.publish(o,c,{headers:r})}catch(u){if(u.code&&u.code.toString()==="503")return mL(async()=>{try{await s.publish(o,c,{headers:r})}catch{if(u.code&&u.code.toString()==="503"){Bn.trace(`publishToStream creating stream: ${t}`);let l=o.split(".");l[2]="*",await HS(t,[o]),await s.publish(o,c,{headers:r})}else throw u}});throw u}}a(Rj,"publishToStream");function EL(e,t){t===void 0&&(t=aj());let r=Bt.get(Ie.CONFIG_PARAMS.CLUSTERING_NODENAME);return!t.has(Yt.MSG_HEADERS.ORIGIN)&&r&&t.append(Yt.MSG_HEADERS.ORIGIN,r),t}a(EL,"addNatsMsgHeader");function _a(e){e=e.toLowerCase();let t=mu.join(Bt.get(Ie.CONFIG_PARAMS.ROOTPATH),_j);if(e===Ie.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase())return co(DS)&&(DS={port:Eu.getConfigFromFile(Ie.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),server_name:Eu.getConfigFromFile(Ie.CONFIG_PARAMS.CLUSTERING_NODENAME)+Yt.SERVER_SUFFIX.HUB,config_file:Yt.NATS_CONFIG_FILES.HUB_SERVER,pid_file_path:mu.join(t,Yt.PID_FILES.HUB),hdb_nats_path:t}),DS;if(e===Ie.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())return co(CS)&&(CS={port:Eu.getConfigFromFile(Ie.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),server_name:Eu.getConfigFromFile(Ie.CONFIG_PARAMS.CLUSTERING_NODENAME)+Yt.SERVER_SUFFIX.LEAF,config_file:Yt.NATS_CONFIG_FILES.LEAF_SERVER,domain:Eu.getConfigFromFile(Ie.CONFIG_PARAMS.CLUSTERING_NODENAME)+Yt.SERVER_SUFFIX.LEAF,pid_file_path:mu.join(t,Yt.PID_FILES.LEAF),hdb_nats_path:t}),CS;Bn.error(`Unable to get Nats server config. Unrecognized process: ${e}`)}a(_a,"getServerConfig");async function hL(e,t,r,n){try{await e.consumers.add(t,{ack_policy:PS.Explicit,durable_name:r,deliver_policy:US.StartTime,opt_start_time:n})}catch(s){if(s.message!=="consumer already exists")throw s}}a(hL,"createConsumer");async function Aj(e,t,r){await e.consumers.delete(t,r)}a(Aj,"removeConsumer");function Oj(e){return e.split(".")[1]}a(Oj,"extractServerName");async function bj(e,t,r=6e4,n=vS()){if(!wd.isObject(t))throw new Error("data param must be an object");let s=aL.encode(t),{connection:i}=await ss(),o={timeout:r};n&&(o.reply=n,o.noMux=!0);let c=await i.request(e,s,o);return MS(c.data)}a(bj,"request");function xS(e){return new Promise(async(t,r)=>{let n=J3(LS,["--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(xS,"reloadNATS");async function yj(){let{pid_file_path:e}=_a(Ie.PROCESS_DESCRIPTORS.CLUSTERING_HUB);await xS(e)}a(yj,"reloadNATSHub");async function Nj(){let{pid_file_path:e}=_a(Ie.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);await xS(e)}a(Nj,"reloadNATSLeaf");function Ij(e,t,r){let n;switch(e.code){case nL.NoResponders:n=`Unable to ${t}, node '${r}' is not listening.`;break;case nL.Timeout:n=`Unable to ${t}, node '${r}' is listening but did not respond.`;break;default:n=e.message;break}return n}a(Ij,"requestErrorHandler");async function wj(e,t){let r=t+Yt.SERVER_SUFFIX.LEAF,{connection:n}=await ss(),{jsm:s}=await Bj(r),{schema:i,table:o}=e,c=Cd.createNatsTableStreamName(i,o),u=e.start_time?e.start_time:new Date(Date.now()).toISOString();await mL(async()=>{if(e.subscribe===!0)await hL(s,c,n.info.server_name,u);else try{await Aj(s,c,n.info.server_name)}catch(_){Bn.trace(_)}})}a(wj,"updateRemoteConsumer");async function Cj(e,t,r,n){let s=Cd.createNatsTableStreamName(e,t),i=r+Yt.SERVER_SUFFIX.LEAF,o={type:Ie.ITC_EVENT_TYPES.NATS_CONSUMER_UPDATE,status:n,stream_name:s,node_domain_name:i};if(!oL&&ej()<Bt.get(Ie.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXINGESTTHREADS)){let{updateConsumer:c}=wS();await c(o)}await X3(o),n==="stop"&&await wd.async_set_timeout(1e3)}a(Cj,"updateConsumerIterator");function mL(e){return j3.writeTransaction(Ie.SYSTEM_SCHEMA_NAME,Ie.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,e)}a(mL,"exclusiveLock");async function pL(e,t){let r=Cd.createNatsTableStreamName(e,t),n=await Dd(),s=Pj(e,t,n);await HS(r,[s])}a(pL,"createLocalTableStream");async function Dj(e){for(let t=0,r=e.length;t<r;t++){let n=e[t].schema,s=e[t].table;await pL(n,s)}}a(Dj,"createTableStreams");async function SL(e,t,r=void 0){if(Bt.get(Ie.CONFIG_PARAMS.CLUSTERING_ENABLED))try{let n=Cd.createNatsTableStreamName(e,t),{domain:s}=_a(Ie.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);await(await(await pu()).jetstreamManager({domain:s,timeout:24e4})).streams.purge(n,r)}catch(n){if(n.message==="stream not found")Bn.warn(n);else throw n}}a(SL,"purgeTableStream");async function Lj(e,t){if(Bt.get(Ie.CONFIG_PARAMS.CLUSTERING_ENABLED))for(let r=0,n=t.length;r<n;r++)await SL(e,t[r])}a(Lj,"purgeSchemaTableStreams");async function Mj(e){return(await Su()).streams.info(e)}a(Mj,"getStreamInfo");function Pj(e,t,r){return`${Yt.SUBJECT_PREFIXES.TXN}.${e}${t?"."+t:""}.${r}`}a(Pj,"createSubjectName");async function Dd(){if(hu)return hu;if(hu=(await Su())?.nc?.info?.server_name,hu===void 0)throw new Error("Unable to get jetstream manager server name");return hu}a(Dd,"getJsmServerName");async function Uj(){let e=await Su(),t=await Dd(),r=await fL();for(let n of r){let s=n.config,i=s.subjects[0];if(!i)continue;let o=vj(n),c=i.split(".");if(c[c.length-1]===t&&!o||s.name==="__HARPERDB_WORK_QUEUE__")continue;let _=i.split(".");_[_.length-1]=t;let l=_.join(".");Bn.trace(`Updating stream subject name from: ${i} to: ${l}`),s.subjects[0]=l,await e.streams.update(s.name,s)}}a(Uj,"updateLocalStreams");function vj(e){let{config:t}=e,r=!1,n=Bt.get(Ie.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE);n=n===null?0:n*1e9;let s=Bt.get(Ie.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES);s=s===null?-1:s;let i=Bt.get(Ie.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(vj,"updateStreamLimits");async function Bj(e){let t,r;try{t=await Sr.jetstream({domain:e}),r=await Sr.jetstreamManager({domain:e,checkAPI:!1})}catch(n){throw Bn.error("Unable to connect to:",e),n}return{js:t,jsm:r}}a(Bj,"connectToRemoteJS")});var Tu=g((qfe,OL)=>{"use strict";var da=y_(),fa=ID(),Hj=$(),xj=require("uuid").v4,Gfe=require("clone"),Md=bs(),Ea=P(),Gj=require("util"),di=Cn(),{handleHDBError:Tr,hdb_errors:qj}=ne(),{HDB_ERROR_MSGS:Ld,HTTP_STATUS_CODES:gr}=qj,{SchemaEventMsg:Pd}=Mn(),gL=ot(),{getDatabases:Fj}=(Oe(),ie(Fe)),{transformReq:ha}=J();OL.exports={createSchema:kj,createSchemaStructure:RL,createTable:Vj,createTableStructure:AL,createAttribute:Qj,dropSchema:$j,dropTable:Yj,dropAttribute:Kj,getBackup:zj};async function kj(e){let t=await RL(e);return Md.signalSchemaChange(new Pd(process.pid,e.operation,e.schema)),t}a(kj,"createSchema");async function RL(e){let t=da.schema_object(e);if(t)throw Tr(t,t.message,gr.BAD_REQUEST,void 0,void 0,!0);if(ha(e),!await fa.checkSchemaExists(e.schema))throw Tr(new Error,Ld.SCHEMA_EXISTS_ERR(e.schema),gr.BAD_REQUEST,Ea.LOG_LEVELS.ERROR,Ld.SCHEMA_EXISTS_ERR(e.schema),!0);return await di.createSchema(e),`database '${e.schema}' successfully created`}a(RL,"createSchemaStructure");async function Vj(e){return ha(e),e.hash_attribute=e.primary_key??e.hash_attribute,await AL(e)}a(Vj,"createTable");async function AL(e){let t=da.create_table_object(e);if(t)throw Tr(t,t.message,gr.BAD_REQUEST,void 0,void 0,!0);if(da.validateTableResidence(e.residence),!await fa.checkSchemaTableExists(e.schema,e.table))throw Tr(new Error,Ld.TABLE_EXISTS_ERR(e.schema,e.table),gr.BAD_REQUEST,Ea.LOG_LEVELS.ERROR,Ld.TABLE_EXISTS_ERR(e.schema,e.table),!0);let n={name:e.table,schema:e.schema,id:xj(),hash_attribute:e.hash_attribute};try{if(e.residence)if(global.clustering_on)n.residence=e.residence,await di.createTable(n,e);else throw Tr(new Error,"Clustering does not appear to be enabled. Cannot insert table with property 'residence'.",gr.BAD_REQUEST);else await di.createTable(n,e);return`table '${e.schema}.${e.table}' successfully created.`}catch(s){throw s}}a(AL,"createTableStructure");async function $j(e){let t=!e.schema&&!e.database?new Error("database is required"):void 0,r=da.schema_object(e),n=t??r;if(n)throw Tr(n,n.message,gr.BAD_REQUEST,void 0,void 0,!0);ha(e);let s=await fa.checkSchemaExists(e.schema);if(s)throw Tr(new Error,s,gr.NOT_FOUND,Ea.LOG_LEVELS.ERROR,s,!0);let i=await fa.schema_describe.describeSchema({schema:e.schema}),o=Object.keys(global.hdb_schema[e.schema]);return await di.dropSchema(e),Md.signalSchemaChange(new Pd(process.pid,e.operation,e.schema)),await gL.purgeSchemaTableStreams(e.schema,o),`successfully deleted '${e.schema}'`}a($j,"dropSchema");async function Yj(e){let t=da.table_object(e);if(t)throw Tr(t,t.message,gr.BAD_REQUEST,void 0,void 0,!0);ha(e);let r=await fa.checkSchemaTableExists(e.schema,e.table);if(r)throw Tr(new Error,r,gr.NOT_FOUND,Ea.LOG_LEVELS.ERROR,r,!0);return await di.dropTable(e),await gL.purgeTableStream(e.schema,e.table),`successfully deleted table '${e.schema}.${e.table}'`}a(Yj,"dropTable");async function Kj(e){let t=da.attribute_object(e);if(t)throw Tr(t,t.message,gr.BAD_REQUEST,void 0,void 0,!0);ha(e);let r=await fa.checkSchemaTableExists(e.schema,e.table);if(r)throw Tr(new Error,r,gr.NOT_FOUND,Ea.LOG_LEVELS.ERROR,r,!0);if(e.attribute===global.hdb_schema[e.schema][e.table].hash_attribute)throw Tr(new Error,"You cannot drop a hash attribute",gr.BAD_REQUEST,void 0,void 0,!0);if(Ea.TIME_STAMP_NAMES.indexOf(e.attribute)>=0)throw Tr(new Error,`cannot drop internal timestamp attribute: ${e.attribute}`,gr.BAD_REQUEST,void 0,void 0,!0);try{return await di.dropAttribute(e),Wj(e),Md.signalSchemaChange(new Pd(process.pid,e.operation,e.schema,e.table,e.attribute)),`successfully deleted attribute '${e.attribute}'`}catch(n){throw Hj.error(`Got an error deleting attribute ${Gj.inspect(e)}.`),n}}a(Kj,"dropAttribute");function Wj(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(Wj,"dropAttributeFromGlobal");async function Qj(e){ha(e);let t=Fj()[e.schema][e.table].attributes;for(let{name:r}of t)if(r===e.attribute)throw Tr(new Error,`attribute '${e.attribute}' already exists in ${e.schema}.${e.table}`,gr.BAD_REQUEST,void 0,void 0,!0);return await di.createAttribute(e),Md.signalSchemaChange(new Pd(process.pid,e.operation,e.schema,e.table,e.attribute)),`attribute '${e.schema}.${e.table}.${e.attribute}' successfully created.`}a(Qj,"createAttribute");function zj(e){return di.getBackup(e)}a(zj,"getBackup")});var yL=g((kfe,bL)=>{"use strict";var{OPERATIONS_ENUM:Jj}=P(),GS=class{static{a(this,"ReadAuditLogObject")}constructor(t,r,n=void 0,s=void 0){this.operation=Jj.READ_AUDIT_LOG,this.schema=t,this.table=r,this.search_type=n,this.search_values=s}};bL.exports=GS});var qS=g((Yfe,DL)=>{"use strict";var jj=Cn(),$fe=yL(),Ud=J(),vd=P(),Xj=Z(),{handleHDBError:NL,hdb_errors:Zj}=ne(),{HDB_ERROR_MSGS:IL,HTTP_STATUS_CODES:wL}=Zj,eX=Object.values(vd.READ_AUDIT_LOG_SEARCH_TYPES_ENUM),CL="To use this operation audit log must be enabled in harperdb-config.yaml";DL.exports=tX;async function tX(e){if(Ud.isEmpty(e.schema))throw new Error(IL.SCHEMA_REQUIRED_ERR);if(Ud.isEmpty(e.table))throw new Error(IL.TABLE_REQUIRED_ERR);if(!Xj.get(vd.CONFIG_PARAMS.LOGGING_AUDITLOG))throw NL(new Error,CL,wL.BAD_REQUEST,vd.LOG_LEVELS.ERROR,CL,!0);let t=Ud.checkSchemaTableExist(e.schema,e.table);if(t)throw NL(new Error,t,wL.NOT_FOUND,vd.LOG_LEVELS.ERROR,t,!0);if(!Ud.isEmpty(e.search_type)&&eX.indexOf(e.search_type)<0)throw new Error(`Invalid search_type '${e.search_type}'`);return await jj.readAuditLog(e)}a(tX,"readAuditLog")});var ML=g((Wfe,LL)=>{"use strict";var{OPERATIONS_ENUM:rX}=P(),FS=class{static{a(this,"GetBackupObject")}constructor(t,r,n=void 0,s=void 0){this.operation=rX.GET_BACKUP,this.schema=t,this.table=r}};LL.exports=FS});var vL=g((jfe,UL)=>{"use strict";var nX=Cn(),zfe=ML(),kS=J(),sX=P(),Jfe=Z(),{handleHDBError:iX,hdb_errors:oX}=ne(),{HDB_ERROR_MSGS:PL,HTTP_STATUS_CODES:aX}=oX;UL.exports=cX;async function cX(e){if(kS.isEmpty(e.schema))throw new Error(PL.SCHEMA_REQUIRED_ERR);if(kS.isEmpty(e.table))throw new Error(PL.TABLE_REQUIRED_ERR);let t=kS.checkSchemaTableExist(e.schema,e.table);if(t)throw iX(new Error,t,aX.NOT_FOUND,sX.LOG_LEVELS.ERROR,t,!0);return await nX.getBackup(read_audit_log_object)}a(cX,"getBackup")});var FL=g((Zfe,qL)=>{var fi=require("validate.js"),HL=je(),ma=P(),{handleHDBError:uX,hdb_errors:lX}=ne(),{HDB_ERROR_MSGS:Et,HTTP_STATUS_CODES:_X}=lX,VS=a(()=>({role:{presence:!0,format:"[\\w\\-\\_]+"},id:{presence:!0,format:"[\\w\\-\\_]+"},permission:{presence:!0}}),"constraintsTemplate"),dX={STRUCTURE_USER:"structure_user"},BL=Object.values(ma.ROLE_TYPES_ENUM),fX="attribute_permissions",EX="attribute_name",{PERMS_CRUD_ENUM:pa}=ma,hX=[fX,...Object.values(pa)],xL=[pa.READ,pa.INSERT,pa.UPDATE],mX=[EX,...xL];function pX(e){let t=VS();return t.role.presence=!0,t.id.presence=!1,t.permission.presence=!0,GL(e,t)}a(pX,"addRoleValidation");function SX(e){let t=VS();return t.role.presence=!1,t.id.presence=!0,t.permission.presence=!0,GL(e,t)}a(SX,"alterRoleValidation");function TX(e){let t=VS();return t.role.presence=!1,t.id.presence=!0,t.permission.presence=!1,HL.validateObject(e,t)}a(TX,"dropRoleValidation");var gX=["operation","role","id","permission","hdb_user","hdb_auth_header"];function GL(e,t){let r={main_permissions:[],schema_permissions:{}},n=Object.keys(e),s=[];for(let o=0,c=n.length;o<c;o++)gX.includes(n[o])||s.push(n[o]);s.length>0&>(Et.INVALID_ROLE_JSON_KEYS(s),r);let i=HL.validateObject(e,t);if(i&&i.message.split(",").forEach(o=>{gt(o,r)}),e.permission){let o=RX(e);o&>(o,r),BL.forEach(c=>{e.permission[c]&&!fi.isBoolean(e.permission[c])&>(Et.SU_CU_ROLE_BOOLEAN_ERROR(c),r)})}for(let o in e.permission)if(BL.indexOf(o)<0){if(o===dX.STRUCTURE_USER){let u=e.permission[o];if(typeof u=="boolean")continue;if(Array.isArray(u)){for(let _=0,l=u.length;_<l;_++){let d=u[_];global.hdb_schema[d]||gt(Et.SCHEMA_NOT_FOUND(d),r)}continue}gt(Et.STRUCTURE_USER_ROLE_TYPE_ERROR(o),r);continue}let c=e.permission[o];if(!o||!global.hdb_schema[o]){gt(Et.SCHEMA_NOT_FOUND(o),r);continue}if(c.tables)for(let u in c.tables){let _=c.tables[u];if(!u||!global.hdb_schema[o][u]){gt(Et.TABLE_NOT_FOUND(o,u),r);continue}if(Object.keys(_).forEach(l=>{hX.includes(l)||gt(Et.INVALID_PERM_KEY(l),r,o,u)}),Object.values(pa).forEach(l=>{fi.isDefined(_[l])?fi.isBoolean(_[l])||gt(Et.TABLE_PERM_NOT_BOOLEAN(l),r,o,u):gt(Et.TABLE_PERM_MISSING(l),r,o,u)}),fi.isDefined(_.attribute_permissions)){if(!fi.isArray(_.attribute_permissions)){gt(Et.ATTR_PERMS_NOT_ARRAY,r,o,u);continue}}else{gt(Et.ATTR_PERMS_ARRAY_MISSING,r,o,u);continue}if(_.attribute_permissions){let l=global.hdb_schema[o][u].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=>{!mX.includes(p)&&p!==pa.DELETE&>(Et.INVALID_ATTR_PERM_KEY(p),r,o,u)}),!fi.isDefined(f.attribute_name)){gt(Et.ATTR_PERM_MISSING_NAME,r,o,u);continue}let h=f.attribute_name;if(!l.includes(h)){gt(Et.INVALID_ATTRIBUTE_IN_PERMS(h),r,o,u);continue}xL.forEach(p=>{fi.isDefined(f[p])?fi.isBoolean(f[p])||gt(Et.ATTR_PERM_NOT_BOOLEAN(p,h),r,o,u):gt(Et.ATTR_PERM_MISSING(p,h),r,o,u)}),!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}.${u}`;gt(Et.MISMATCHED_TABLE_ATTR_PERMS(E),r,o,u)}}}}return AX(r)}a(GL,"customValidate");qL.exports={addRoleValidation:pX,alterRoleValidation:SX,dropRoleValidation:TX};function RX(e){let{operation:t,permission:r}=e;if(t===ma.OPERATIONS_ENUM.ADD_ROLE||t===ma.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 Et.SU_CU_ROLE_COMBINED_ERROR;{let o=r.super_user?ma.ROLE_TYPES_ENUM.SUPER_USER:ma.ROLE_TYPES_ENUM.CLUSTER_USER;return Et.SU_CU_ROLE_NO_PERMS_ALLOWED(o)}}}return null}a(RX,"validateNoSUPerms");function AX(e){let{main_permissions:t,schema_permissions:r}=e;if(t.length>0||Object.keys(r).length>0){let n={error:Et.ROLE_PERMS_ERROR,...e};return uX(new Error,n,_X.BAD_REQUEST)}else return null}a(AX,"generateRolePermResponse");function gt(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(gt,"addPermError")});var zS=g((tEe,YL)=>{"use strict";var kL=qr(),VL=Gr(),OX=oi(),YS=FL(),KS=bs(),bX=require("uuid").v4,yX=require("util"),Bd=P(),NX=J(),WS=VL.searchByValue,IX=VL.searchByHash,wX=yX.promisify(OX.delete),CX=es(),DX=ia(),{hdb_errors:LX,handleHDBError:uo}=ne(),{HDB_ERROR_MSGS:$L,HTTP_STATUS_CODES:gu}=LX,{UserEventMsg:QS}=Mn();YL.exports={addRole:MX,alterRole:PX,dropRole:UX,listRoles:vX};function $S(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($S,"scrubRoleDetails");async function MX(e){let t=YS.addRoleValidation(e);if(t)throw t;e=$S(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 WS(r)||[])}catch(i){throw uo(i)}if(n&&n.length>0)throw uo(new Error,$L.ROLE_ALREADY_EXISTS(e.role),gu.CONFLICT,void 0,void 0,!0);e.id||(e.id=bX());let s={operation:"insert",schema:"system",table:"hdb_role",hash_attribute:"id",records:[e]};return await kL.insert(s),KS.signalUserChange(new QS(process.pid)),e=$S(e),e}a(MX,"addRole");async function PX(e){let t=YS.alterRoleValidation(e);if(t)throw t;e=$S(e);let r={operation:"update",schema:"system",table:"hdb_role",records:[e]},n;try{n=await kL.update(r)}catch(s){throw uo(s)}if(n&&n?.message==="updated 0 of 1 records")throw uo(new Error,"Invalid role id",gu.BAD_REQUEST,void 0,void 0,!0);return await KS.signalUserChange(new QS(process.pid)),e}a(PX,"alterRole");async function UX(e){let t=YS.dropRoleValidation(e);if(t)throw uo(new Error,t,gu.BAD_REQUEST,void 0,void 0,!0);let r=new DX(Bd.SYSTEM_SCHEMA_NAME,Bd.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME,[e.id],["role"]),n=Array.from(await IX(r));if(n.length===0)throw uo(new Error,$L.ROLE_NOT_FOUND,gu.NOT_FOUND,void 0,void 0,!0);let s=new CX(Bd.SYSTEM_SCHEMA_NAME,Bd.SYSTEM_TABLE_NAMES.USER_TABLE_NAME,"role",e.id,void 0,["username","active"]),i=Array.from(await WS(s)),o=!1;if(NX.isEmptyOrZeroLength(i)===!1){for(let u=0;u<i.length;u++)if(i[u].active===!0){o=!0;break}}if(o===!0)throw uo(new Error,`Cannot drop role ${n[0].role} as it has active user(s) tied to this role`,gu.CONFLICT,void 0,void 0,!0);let c={table:"hdb_role",schema:"system",hash_values:[e.id]};return await wX(c),KS.signalUserChange(new QS(process.pid)),`${n[0].role} successfully deleted`}a(UX,"dropRole");async function vX(){return WS({table:"hdb_role",schema:"system",hash_attribute:"id",search_attribute:"id",search_value:"*",get_attributes:["*"]})}a(vX,"listRoles")});var zL=g((nEe,QL)=>{"use strict";var BX=Z(),Ei=require("joi"),HX=je(),KL=require("moment"),xX=require("fs-extra"),JS=require("path"),GX=require("lodash"),Ru=P(),{LOG_LEVELS:lo}=P(),qX="YYYY-MM-DD hh:mm:ss",FX=JS.resolve(__dirname,"../logs");QL.exports=function(e){return HX.validateBySchema(e,kX)};var kX=Ei.object({from:Ei.custom(WL),until:Ei.custom(WL),level:Ei.valid(lo.NOTIFY,lo.FATAL,lo.ERROR,lo.WARN,lo.INFO,lo.DEBUG,lo.TRACE),order:Ei.valid("asc","desc"),limit:Ei.number().min(1),start:Ei.number().min(0),log_name:Ei.custom(VX)});function WL(e,t){if(KL(e,KL.ISO_8601).format(qX)==="Invalid date")return t.message(`'${t.state.path[0]}' date '${e}' is invalid.`)}a(WL,"validateDatetime");function VX(e,t){if(GX.invert(Ru.LOG_NAMES)[e]===void 0)return t.message(`'log_name' '${e}' is invalid.`);let n=BX.get(Ru.HDB_SETTINGS_NAMES.LOG_PATH_KEY),s=e===void 0?Ru.LOG_NAMES.HDB:e,i=s===Ru.LOG_NAMES.INSTALL?JS.join(FX,Ru.LOG_NAMES.INSTALL):JS.join(n,s);return xX.existsSync(i)?null:t.message(`'log_name' '${e}' does not exist.`)}a(VX,"validateReadLogPath")});var XS=g((iEe,jL)=>{"use strict";var Hd=P(),$X=$(),YX=Z(),KX=zL(),jS=require("path"),JL=require("fs-extra"),{once:WX}=require("events"),{handleHDBError:QX,hdb_errors:zX}=ne(),{PACKAGE_ROOT:JX}=P(),jX=jS.join(JX,"logs"),XX=1e3,ZX=200;jL.exports=eZ;async function eZ(e){let t=KX(e);if(t)throw QX(t,t.message,zX.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0);let r=YX.get(Hd.HDB_SETTINGS_NAMES.LOG_PATH_KEY),n=e.log_name===void 0?Hd.LOG_NAMES.HDB:e.log_name,s=n===Hd.LOG_NAMES.INSTALL?jS.join(jX,Hd.LOG_NAMES.INSTALL):jS.join(r,n),i=e.level!==void 0,o=i?e.level:void 0,c=e.from!==void 0,u=c?new Date(e.from):void 0,_=e.until!==void 0,l=_?new Date(e.until):void 0,d=e.limit===void 0?XX: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"&&!u&&!l&&(p=Math.max(JL.statSync(s).size-(h+5)*ZX,0));let S=JL.createReadStream(s,{start:p});S.on("error",v=>{$X.error(v)});let T=0,A=[],R="",C;S.on("data",v=>{let k=/(?:^|\n)(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:[\d\.]+Z) \[(.+?)]: /g;v=R+v;let M=0,Q;for(;(Q=k.exec(v))&&!S.destroyed;){C&&(C.message=v.slice(M,Q.index),x(C));let[j,z,ae]=Q,ue=ae.split("] ["),de=ue[0],xe=ue[1];ue.splice(0,2),C={timestamp:z,thread:de,level:xe,tags:ue,message:""},M=Q.index+j.length}R=v.slice(M)}),S.on("end",v=>{S.destroyed||C&&(C.message=R.trim(),x(C))}),S.resume();function x(v){let k,M,Q;switch(!0){case(i&&c&&_):k=new Date(v.timestamp),M=new Date(u),Q=new Date(l),v.level===o&&k>=M&&k<=Q&&T<f?T++:v.level===o&&k>=M&&k<=Q&&(hi(v,E,A),T++,T===h&&S.destroy());break;case(i&&c):k=new Date(v.timestamp),M=new Date(u),v.level===o&&k>=M&&T<f?T++:v.level===o&&k>=M&&(hi(v,E,A),T++,T===h&&S.destroy());break;case(i&&_):k=new Date(v.timestamp),Q=new Date(l),v.level===o&&k<=Q&&T<f?T++:v.level===o&&k<=Q&&(hi(v,E,A),T++,T===h&&S.destroy());break;case(c&&_):k=new Date(v.timestamp),M=new Date(u),Q=new Date(l),k>=M&&k<=Q&&T<f?T++:k>=M&&k<=Q&&(hi(v,E,A),T++,T===h&&S.destroy());break;case i:v.level===o&&T<f?T++:v.level===o&&(hi(v,E,A),T++,T===h&&S.destroy());break;case c:k=new Date(v.timestamp),M=new Date(u),k>=M&&T<f?T++:k>=M&&T>=f&&(hi(v,E,A),T++,T===h&&S.destroy());break;case _:k=new Date(v.timestamp),Q=new Date(l),k<=Q&&T<f?T++:k<=Q&&T>=f&&(hi(v,E,A),T++,T===h&&S.destroy());break;default:T<f?T++:(hi(v,E,A),T++,T===h&&S.destroy())}}return a(x,"onLogMessage"),await WX(S,"close"),A}a(eZ,"readLog");function hi(e,t,r){t==="desc"?tZ(e,r):t==="asc"?rZ(e,r):r.push(e)}a(hi,"pushLineToResult");function tZ(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(tZ,"insertDescending");function rZ(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(rZ,"insertAscending")});var xd=g((lEe,tM)=>{"use strict";var ZS=require("joi"),{string:Au,boolean:XL,date:nZ}=ZS.types(),sZ=je(),{validateSchemaExists:aEe,validateTableExists:cEe,validateSchemaName:uEe}=zn(),iZ=P(),oZ=ke(),ZL=Z();ZL.initSync();var aZ=Au.invalid(ZL.get(iZ.CONFIG_PARAMS.CLUSTERING_NODENAME)).pattern(oZ.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(),eM={operation:Au.valid("add_node","update_node","set_node_replication"),node_name:aZ,subscriptions:ZS.array().items({table:Au.optional(),schema:Au.optional(),database:Au.optional(),subscribe:XL.required(),publish:XL.required().custom(uZ),start_time:nZ.iso()}).min(1).required()};function cZ(e){return sZ.validateBySchema(e,ZS.object(eM))}a(cZ,"addUpdateNodeValidator");function uZ(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(uZ,"checkForFalsy");tM.exports={addUpdateNodeValidator:cZ,validation_schema:eM}});var nM=g((dEe,rM)=>{var lZ=je(),_Z={user:{presence:!0},schema:{presence:!0},table:{presence:!0},operation:{presence:!0}};rM.exports=function(e){return lZ.validateObject(e,_Z)}});var Gd=g((fEe,sM)=>{"use strict";var dZ=P().OPERATIONS_ENUM,eT=class{static{a(this,"UpdateObject")}constructor(t,r,n,s=void 0){this.operation=dZ.UPDATE,this.schema=t,this.table=r,this.records=n,this.__origin=s}};sM.exports=eT});var oM=g((hEe,iM)=>{"use strict";var fZ={OPERATION:"operation",REFRESH:"refresh"},tT=class{static{a(this,"JWTTokens")}constructor(t,r){this.operation_token=t,this.refresh_token=r}},rT=class{static{a(this,"JWTRSAKeys")}constructor(t,r,n){this.public_key=t,this.private_key=r,this.passphrase=n}};iM.exports={JWTTokens:tT,TOKEN_TYPE_ENUM:fZ,JWTRSAKeys:rT}});var yu=g((pEe,lM)=>{"use strict";var bu=require("jsonwebtoken"),nT=require("fs-extra"),sT=J(),_n=P(),{handleHDBError:Rr,hdb_errors:EZ}=ne(),{HTTP_STATUS_CODES:Ar,AUTHENTICATION_ERROR_MSGS:Or}=EZ,Ou=$(),aM=F_(),aT=ln(),hZ=qr().update,mZ=Gd(),pZ=bs(),{UserEventMsg:SZ}=Mn(),mi=Z();mi.initSync();var iT=require("path"),{JWTTokens:TZ,JWTRSAKeys:gZ,TOKEN_TYPE_ENUM:qd}=oM(),RZ=mi.get(_n.HDB_SETTINGS_NAMES.OPERATION_TOKEN_TIMEOUT_KEY)?mi.get(_n.HDB_SETTINGS_NAMES.OPERATION_TOKEN_TIMEOUT_KEY):"1d",AZ=mi.get(_n.HDB_SETTINGS_NAMES.REFRESH_TOKEN_TIMEOUT_KEY)?mi.get(_n.HDB_SETTINGS_NAMES.REFRESH_TOKEN_TIMEOUT_KEY):"30d",Fd="RS256",oT;lM.exports={createTokens:OZ,validateOperationToken:yZ,refreshOperationToken:bZ,validateRefreshToken:uM};async function OZ(e){if(sT.isEmpty(e)||typeof e!="object")throw Rr(new Error,Or.INVALID_AUTH_OBJECT,Ar.BAD_REQUEST,void 0,void 0,!0);if(sT.isEmpty(e.username))throw Rr(new Error,Or.USERNAME_REQUIRED,Ar.BAD_REQUEST,void 0,void 0,!0);if(sT.isEmpty(e.password))throw Rr(new Error,Or.PASSWORD_REQUIRED,Ar.BAD_REQUEST,void 0,void 0,!0);let t;try{if(t=await aT.findAndValidateUser(e.username,e.password),!t)throw Rr(new Error,Or.INVALID_CREDENTIALS,Ar.UNAUTHORIZED,void 0,void 0,!0)}catch(E){throw Ou.error(E),Rr(new Error,Or.INVALID_CREDENTIALS,Ar.UNAUTHORIZED,void 0,void 0,!0)}let r=await kd(),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 cM(i,r.private_key,r.passphrase),c=await bu.sign(i,{key:r.private_key,passphrase:r.passphrase},{expiresIn:AZ,algorithm:Fd,subject:qd.REFRESH}),u=aM.hash(c),_=new mZ(_n.SYSTEM_SCHEMA_NAME,_n.SYSTEM_TABLE_NAMES.USER_TABLE_NAME,[{username:e.username,refresh_token:u}]),l,d;try{l=await hZ(_)}catch(E){Ou.error(E),d=E}if(d!==void 0||l.skipped_hashes.length>0)throw Rr(new Error,Or.REFRESH_TOKEN_SAVE_FAILED,Ar.INTERNAL_SERVER_ERROR);return pZ.signalUserChange(new SZ(process.pid)),new TZ(o,c)}a(OZ,"createTokens");async function cM(e,t,r){return await bu.sign(e,{key:t,passphrase:r},{expiresIn:RZ,algorithm:Fd,subject:qd.OPERATION})}a(cM,"signOperationToken");async function kd(){if(oT===void 0)try{let e=iT.join(mi.getHdbBasePath(),_n.LICENSE_KEY_DIR_NAME,_n.JWT_ENUM.JWT_PASSPHRASE_NAME),t=iT.join(mi.getHdbBasePath(),_n.LICENSE_KEY_DIR_NAME,_n.JWT_ENUM.JWT_PRIVATE_KEY_NAME),r=iT.join(mi.getHdbBasePath(),_n.LICENSE_KEY_DIR_NAME,_n.JWT_ENUM.JWT_PUBLIC_KEY_NAME),n=(await nT.readFile(e)).toString(),s=(await nT.readFile(t)).toString(),i=(await nT.readFile(r)).toString();oT=new gZ(i,s,n)}catch(e){throw Ou.error(e),Rr(new Error,Or.NO_ENCRYPTION_KEYS,Ar.INTERNAL_SERVER_ERROR)}return oT}a(kd,"getJWTRSAKeys");async function bZ(e){if(!e)throw Rr(new Error,Or.INVALID_BODY,Ar.BAD_REQUEST,void 0,void 0,!0);if(!e.refresh_token)throw Rr(new Error,Or.REFRESH_TOKEN_REQUIRED,Ar.BAD_REQUEST,void 0,void 0,!0);await uM(e.refresh_token);let t=await kd(),r=await bu.decode(e.refresh_token);return{operation_token:await cM({username:r.username,super_user:r.super_user,cluster_user:r.cluster_user},t.private_key,t.passphrase)}}a(bZ,"refreshOperationToken");async function yZ(e){try{let t=await kd(),r=await bu.verify(e,t.public_key,{algorithms:Fd,subject:qd.OPERATION});return await aT.findAndValidateUser(r.username,void 0,!1)}catch(t){throw Ou.warn(t),t.name&&t.name==="TokenExpiredError"?Rr(new Error,Or.TOKEN_EXPIRED,Ar.FORBIDDEN):Rr(new Error,Or.INVALID_TOKEN,Ar.UNAUTHORIZED)}}a(yZ,"validateOperationToken");async function uM(e){let t;try{let r=await kd(),n=await bu.verify(e,r.public_key,{algorithms:Fd,subject:qd.REFRESH});t=await aT.findAndValidateUser(n.username,void 0,!1)}catch(r){throw Ou.warn(r),r.name&&r.name==="TokenExpiredError"?Rr(new Error,Or.TOKEN_EXPIRED,Ar.FORBIDDEN):Rr(new Error,Or.INVALID_TOKEN,Ar.UNAUTHORIZED)}if(!aM.validate(t.refresh_token,e))throw Rr(new Error,Or.INVALID_TOKEN,Ar.UNAUTHORIZED);return t}a(uM,"validateRefreshToken")});var cT=g((gEe,fM)=>{"use strict";var NZ=nM(),Sa=require("passport"),IZ=require("passport-local").Strategy,wZ=require("passport-http").BasicStrategy,CZ=require("util"),DZ=ln(),dM=CZ.callbackify(DZ.findAndValidateUser),TEe=Ur(),LZ=P(),_M=yu();Sa.use(new IZ(function(e,t,r){dM(e,t,r)}));Sa.use(new wZ(function(e,t,r){dM(e,t,r)}));Sa.serializeUser(function(e,t){t(null,e)});Sa.deserializeUser(function(e,t){t(null,e)});function MZ(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":Sa.authenticate("basic",{session:!1},(o,c)=>{i(o,c)})(e,t,r);break;case"Bearer":e.body?.operation&&e.body.operation===LZ.OPERATIONS_ENUM.REFRESH_OPERATION_TOKEN?_M.validateRefreshToken(s).then(o=>{e.body.refresh_token=s,r(null,o)}).catch(o=>{r(o)}):_M.validateOperationToken(s).then(o=>{r(null,o)}).catch(o=>{r(o)});break;default:Sa.authenticate("local",{session:!1},function(o,c){i(o,c)})(e,t,r);break}}a(MZ,"authorize");function PZ(e,t){let r=NZ(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(PZ,"checkPermissions");fM.exports={authorize:MZ,checkPermissions:PZ}});var pi=g((AEe,EM)=>{"use strict";var uT=class{static{a(this,"Node")}constructor(t,r,n){this.name=t,this.subscriptions=r,this.system_info=n}},lT=class{static{a(this,"NodeSubscription")}constructor(t,r,n,s){this.schema=t,this.table=r,this.publish=n,this.subscribe=s}};EM.exports={Node:uT,NodeSubscription:lT}});var mM=g((bEe,hM)=>{"use strict";var UZ=P().OPERATIONS_ENUM,_T=class{static{a(this,"UpsertObject")}constructor(t,r,n,s=void 0){this.operation=UZ.UPSERT,this.schema=t,this.table=r,this.records=n,this.__origin=s}};hM.exports=_T});var Nu=g((NEe,pM)=>{"use strict";var dT=class{static{a(this,"RemotePayloadObject")}constructor(t,r,n,s){this.operation=t,this.node_name=r,this.subscriptions=n,this.system_info=s}},fT=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)}};pM.exports={RemotePayloadObject:dT,RemotePayloadSubscription:fT}});var TM=g((wEe,SM)=>{"use strict";var ET=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}};SM.exports=ET});var AM=g((PEe,RM)=>{"use strict";var vZ=TM(),DEe=_t(),gM=Ke(),BZ=$(),{getSchemaPath:LEe,getTransactionAuditStorePath:MEe}=ze(),{getDatabases:HZ}=(Oe(),ie(Fe));RM.exports=xZ;async function xZ(e){let t=new vZ;try{let r=HZ()[e.schema]?.[e.name],n=r.primaryStore.getStats(),s=r.auditStore?.getStats(),i=await gM.environmentDataSize(schema_path,e.name),o=await gM.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){BZ.warn(`unable to stat table dbi due to ${r}`)}return t}a(xZ,"lmdbGetTableSize")});var bM=g((vEe,OM)=>{"use strict";var hT=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}};OM.exports=hT});var Ta=g((FEe,wM)=>{"use strict";var GZ=require("fs-extra"),qZ=require("path"),rr=require("systeminformation"),Si=$(),yM=ot(),HEe=ke(),$d=P(),FZ=AM(),kZ=As(),{getThreadInfo:NM}=Je(),NT=Z();NT.initSync();var VZ=bM(),{openEnvironment:xEe}=Ke(),{getSchemaPath:GEe}=ze(),{database:qEe,databases:mT}=(Oe(),ie(Fe)),Vd;wM.exports={getHDBProcessInfo:gT,getNetworkInfo:AT,getDiskInfo:RT,getMemoryInfo:TT,getCPUInfo:ST,getTimeInfo:pT,getSystemInformation:OT,systemInformation:$Z,getTableSize:bT,getMetrics:yT};function pT(){return rr.time()}a(pT,"getTimeInfo");async function ST(){try{let{family:e,model:t,stepping:r,revision:n,voltage:s,speedmin:i,speedmax:o,governor:c,socket:u,cache:_,...l}=await rr.cpu();l.cpu_speed=await rr.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,...A}=await rr.currentLoad();return A.cpus=[],T.forEach(R=>{let{raw_load:C,raw_load_idle:x,raw_load_irq:v,raw_load_nice:k,raw_load_system:M,raw_load_user:Q,...j}=R;A.cpus.push(j)}),l.current_load=A,l}catch(e){return Si.error(`error in getCPUInfo: ${e}`),{}}}a(ST,"getCPUInfo");async function TT(){try{let{buffers:e,cached:t,slab:r,buffcache:n,...s}=await rr.mem();return Object.assign(s,process.memoryUsage())}catch(e){return Si.error(`error in getMemoryInfo: ${e}`),{}}}a(TT,"getMemoryInfo");async function gT(){let e={core:[],clustering:[]};try{let t=await rr.processes(),r;try{r=Number.parseInt(await GZ.readFile(qZ.join(NT.get($d.CONFIG_PARAMS.ROOTPATH),$d.HDB_PID_FILE),"utf8"))}catch(n){if(n.code===$d.NODE_ERROR_CODES.ENOENT)Si.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 Si.error(`error in getHDBProcessInfo: ${t}`),e}}a(gT,"getHDBProcessInfo");async function RT(){let e={};try{let{rIO_sec:t,wIO_sec:r,tIO_sec:n,ms:s,...i}=await rr.disksIO();e.io=i;let{rx_sec:o,tx_sec:c,wx_sec:u,..._}=await rr.fsStats();return e.read_write=_,e.size=await rr.fsSize(),e}catch(t){return Si.error(`error in getDiskInfo: ${t}`),e}}a(RT,"getDiskInfo");async function AT(){let e={default_interface:null,latency:{},interfaces:[],stats:[],connections:[]};try{return e.default_interface=await rr.networkInterfaceDefault(),e.latency=await rr.inetChecksite("google.com"),(await rr.networkInterfaces()).forEach(n=>{let{internal:s,virtual:i,mtu:o,dhcp:c,dnsSuffix:u,ieee8021xAuth:_,ieee8021xState:l,carrier_changes:d,...E}=n;e.interfaces.push(E)}),(await rr.networkStats()).forEach(n=>{let{rx_sec:s,tx_sec:i,ms:o,...c}=n;e.stats.push(c)}),e}catch(t){return Si.error(`error in getNetworkInfo: ${t}`),e}}a(AT,"getNetworkInfo");async function OT(){if(Vd!==void 0)return Vd;let e={};try{let{codepage:t,logofile:r,serial:n,build:s,servicepack:i,uefi:o,...c}=await rr.osInfo();e=c;let u=await rr.versions("node, npm");return e.node_version=u.node,e.npm_version=u.npm,Vd=e,Vd}catch(t){return Si.error(`error in getSystemInformation: ${t}`),e}}a(OT,"getSystemInformation");async function bT(){let e=[],t=await kZ.describeAll();for(let r of Object.values(t))for(let n of Object.values(r))e.push(await FZ(n));return e}a(bT,"getTableSize");async function yT(){let e={};for(let t in mT){let r=e[t]={},n=r.tables={};for(let s in mT[t])try{let i=mT[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(u=>{let[_,l,d]=u.trim().split(" ");return{pid:_,thread:l,txnid:d}}),i.primaryStore.auditStore&&(r.audit=i.auditStore.getStats()));let o=i.primaryStore.getStats(),c={};for(let u of["treeDepth","treeBranchPageCount","treeLeafPageCount","entryCount","overflowPages"])c[u]=o[u];n[s]=c}catch(i){Si.notify(`Error getting stats for table ${s}: ${i}`)}}return e}a(yT,"getMetrics");async function IM(){if(NT.get($d.CONFIG_PARAMS.CLUSTERING_ENABLED)){let{jsm:e}=await yM.getNATSReferences(),t=await yM.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(IM,"getNatsStreamInfo");async function $Z(e){let t=new VZ;if(!Array.isArray(e.attributes)||e.attributes.length===0)return t.system=await OT(),t.time=pT(),t.cpu=await ST(),t.memory=await TT(),t.disk=await RT(),t.network=await AT(),t.harperdb_processes=await gT(),t.table_size=await bT(),t.metrics=await yT(),t.threads=await NM(),t.replication=await IM(),t;for(let r=0;r<e.attributes.length;r++)switch(e.attributes[r]){case"system":t.system=await OT();break;case"time":t.time=pT();break;case"cpu":t.cpu=await ST();break;case"memory":t.memory=await TT();break;case"disk":t.disk=await RT();break;case"network":t.network=await AT();break;case"harperdb_processes":t.harperdb_processes=await gT();break;case"table_size":t.table_size=await bT();break;case"database_metrics":case"metrics":t.metrics=await yT();break;case"threads":t.threads=await NM();break;case"replication":t.replication=await IM();break;default:break}return t}a($Z,"systemInformation")});var Kd=g((VEe,CM)=>{"use strict";CM.exports={version:YZ,printVersion:KZ};var Yd=au();function YZ(){if(Yd)return Yd.version}a(YZ,"version");function KZ(){Yd&&console.log(`HarperDB Version ${Yd.version}`)}a(KZ,"printVersion")});var dn=g((WEe,PM)=>{"use strict";var WZ=qr(),IT=J(),QZ=require("util"),_o=P(),DM=Z();DM.initSync();var zZ=cT(),LM=Gr(),{Node:YEe,NodeSubscription:KEe}=pi(),JZ=ia(),jZ=mM(),{RemotePayloadObject:XZ,RemotePayloadSubscription:ZZ}=Nu(),{handleHDBError:e5,hdb_errors:t5}=ne(),{HTTP_STATUS_CODES:r5,HDB_ERROR_MSGS:n5}=t5,s5=es(),i5=Ta(),o5=Kd(),{getDatabases:a5}=(Oe(),ie(Fe)),c5=QZ.promisify(zZ.authorize),u5=LM.searchByHash,l5=LM.searchByValue;PM.exports={authHeaderToUser:_5,isEmpty:d5,getNodeRecord:f5,upsertNodeRecord:E5,buildNodePayloads:h5,checkClusteringEnabled:m5,getAllNodeRecords:p5,getSystemInfo:S5,reverseSubscription:MM};async function _5(e){let t={headers:{authorization:e.hdb_auth_header}};return e.hdb_user=await c5(t,null),e}a(_5,"authHeaderToUser");function d5(e){return e==null}a(d5,"isEmpty");async function f5(e){let t=new JZ(_o.SYSTEM_SCHEMA_NAME,_o.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[e],["*"]);return u5(t)}a(f5,"getNodeRecord");async function E5(e){let t=new jZ(_o.SYSTEM_SCHEMA_NAME,_o.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[e]);return WZ.upsert(t)}a(E5,"upsertNodeRecord");function MM(e){if(IT.isEmpty(e.subscribe)||IT.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(MM,"reverseSubscription");function h5(e,t,r,n){let s=[];for(let i=0,o=e.length;i<o;i++){let c=e[i],{schema:u,table:_}=c,l=IT.getTableHashAttribute(u,_),{subscribe:d,publish:E}=MM(c),f=a5()[u]?.[_],h=new ZZ(u,_,l,E,d,c.start_time,f.schemaDefined?f.attributes:void 0);s.push(h)}return new XZ(r,t,s,n)}a(h5,"buildNodePayloads");function m5(){if(!DM.get(_o.CONFIG_PARAMS.CLUSTERING_ENABLED))throw e5(new Error,n5.CLUSTERING_NOT_ENABLED,r5.BAD_REQUEST,void 0,void 0,!0)}a(m5,"checkClusteringEnabled");async function p5(){let e=new s5(_o.SYSTEM_SCHEMA_NAME,_o.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,"name","*",void 0,["*"]);return Array.from(await l5(e))}a(p5,"getAllNodeRecords");async function S5(){let e=await i5.getSystemInformation();return{hdb_version:o5.version(),node_version:e.node_version,platform:e.platform}}a(S5,"getSystemInfo")});var wT=g((zEe,FM)=>{"use strict";var Wd=ot(),UM=J(),vM=ke(),BM=P(),Qd=$(),HM=Tu(),T5=cd(),{RemotePayloadObject:g5}=Nu(),{handleHDBError:xM,hdb_errors:R5}=ne(),{HTTP_STATUS_CODES:GM}=R5,{NodeSubscription:qM}=pi();FM.exports=A5;async function A5(e,t){let r;try{r=await Wd.request(`${t}.${vM.REQUEST_SUFFIX}`,new g5(BM.OPERATIONS_ENUM.DESCRIBE_ALL,t,void 0,void 0)),Qd.trace("Response from remote describe all request:",r)}catch(o){Qd.error(`addNode received error from describe all request to remote node: ${o}`);let c=Wd.requestErrorHandler(o,"add_node",t);throw xM(new Error,c,GM.INTERNAL_SERVER_ERROR,"error",c)}if(r.status===vM.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let o=`Error returned from remote node ${t}: ${r.message}`;throw xM(new Error,o,GM.INTERNAL_SERVER_ERROR,"error",o)}let n=r.message,s=[],i=[];for(let o of e){let{table:c}=o,u=o.database??o.schema??"data";if(u===BM.SYSTEM_SCHEMA_NAME){await Wd.createLocalTableStream(u,c);let h=new qM(u,c,o.publish,o.subscribe);h.start_time=o.start_time,i.push(h);continue}let _=UM.doesSchemaExist(u),l=n[u]!==void 0,d=c?UM.doesTableExist(u,c):!0,E=c?n?.[u]?.[c]!==void 0:!0;if(!_&&!l||!d&&!E){s.push(o);continue}if(!_&&l&&(Qd.trace(`addNode creating schema: ${u}`),await HM.createSchema({operation:"create_schema",schema:u})),!d&&E){Qd.trace(`addNode creating table: ${c} in schema: ${u} with attributes ${JSON.stringify(n[u][c].attributes)}`);let h=new T5(u,c,n[u][c].hash_attribute);n[u][c].attributes&&(h.attributes=n[u][c].attributes),await HM.createTable(h)}await Wd.createLocalTableStream(u,c);let f=new qM(u,c,o.publish,o.subscribe);f.start_time=o.start_time,i.push(f)}return{added:i,skipped:s}}a(A5,"reviewSubscriptions")});var Xd=g((jEe,$M)=>{"use strict";var{handleHDBError:zd,hdb_errors:O5}=ne(),{HTTP_STATUS_CODES:Jd}=O5,{addUpdateNodeValidator:b5}=xd(),jd=$(),VM=P(),kM=ke(),y5=J(),Iu=ot(),wu=dn(),N5=Z(),I5=wT(),{Node:w5,NodeSubscription:C5}=pi(),{broadcast:D5}=Je(),L5="Unable to create subscriptions due to schema and/or tables not existing on the local or remote node",M5="Some subscriptions were unsuccessful due to schema and/or tables not existing on the local or remote node",P5=N5.get(VM.CONFIG_PARAMS.CLUSTERING_NODENAME);$M.exports=U5;async function U5(e,t=!1){jd.trace("addNode called with:",e),wu.checkClusteringEnabled();let r=b5(e);if(r)throw zd(r,r.message,Jd.BAD_REQUEST,void 0,void 0,!0);let n=e.node_name;if(!t){let d=await wu.getNodeRecord(n);if(!y5.isEmptyOrZeroLength(d))throw zd(new Error,`Node '${n}' has already been added, perform update_node to proceed.`,Jd.BAD_REQUEST,void 0,void 0,!0)}let{added:s,skipped:i}=await I5(e.subscriptions,n),o={message:void 0,added:s,skipped:i};if(s.length===0)return o.message=L5,o;let c=wu.buildNodePayloads(s,P5,VM.OPERATIONS_ENUM.ADD_NODE,await wu.getSystemInfo()),u=[];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,u.push(new C5(f.schema,f.table,f.publish,f.subscribe))}jd.trace("addNode sending remote payload:",c);let _;try{_=await Iu.request(`${n}.${kM.REQUEST_SUFFIX}`,c)}catch(d){jd.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 Iu.updateRemoteConsumer(p,n)}let E=Iu.requestErrorHandler(d,"add_node",n);throw zd(new Error,E,Jd.INTERNAL_SERVER_ERROR,"error",E)}if(_.status===kM.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let d=`Error returned from remote node ${n}: ${_.message}`;throw zd(new Error,d,Jd.INTERNAL_SERVER_ERROR,"error",d)}jd.trace(_);for(let d=0,E=s.length;d<E;d++){let f=s[d];await Iu.updateRemoteConsumer(f,n),f.subscribe===!0&&await Iu.updateConsumerIterator(f.schema,f.table,n,"start")}let l=new w5(n,u,_.system_info);return await wu.upsertNodeRecord(l),D5({type:"nats_update"}),i.length>0?o.message=M5:o.message=`Successfully added '${n}' to manifest`,o}a(U5,"addNode")});var LT=g((ehe,WM)=>{"use strict";var{handleHDBError:CT,hdb_errors:v5}=ne(),{HTTP_STATUS_CODES:DT}=v5,{addUpdateNodeValidator:B5}=xd(),Cu=$(),KM=P(),YM=ke(),ZEe=J(),Du=ot(),Lu=dn(),H5=Z(),{cloneDeep:x5}=require("lodash"),G5=wT(),{Node:q5,NodeSubscription:F5}=pi(),{broadcast:k5}=Je(),V5="Unable to update subscriptions due to schema and/or tables not existing on the local or remote node",$5="Some subscriptions were unsuccessful due to schema and/or tables not existing on the local or remote node",Y5=H5.get(KM.CONFIG_PARAMS.CLUSTERING_NODENAME);WM.exports=K5;async function K5(e){Cu.trace("updateNode called with:",e),Lu.checkClusteringEnabled();let t=B5(e);if(t)throw CT(t,t.message,DT.BAD_REQUEST,void 0,void 0,!0);let r=e.node_name,n,s=await Lu.getNodeRecord(r);s.length>0&&(n=x5(s));let{added:i,skipped:o}=await G5(e.subscriptions,r),c={message:void 0,updated:i,skipped:o};if(i.length===0)return c.message=V5,c;let u=Lu.buildNodePayloads(i,Y5,KM.OPERATIONS_ENUM.UPDATE_NODE,await Lu.getSystemInfo());for(let l=0,d=i.length;l<d;l++){let E=i[l];Cu.trace(`updateNode updating work stream for node: ${r} subscription:`,E),i[l].start_time===void 0&&delete i[l].start_time}Cu.trace("updateNode sending remote payload:",u);let _;try{_=await Du.request(`${r}.${YM.REQUEST_SUFFIX}`,u)}catch(l){Cu.error(`updateNode received error from request: ${l}`);let d=Du.requestErrorHandler(l,"update_node",r);throw CT(new Error,d,DT.INTERNAL_SERVER_ERROR,"error",d)}if(_.status===YM.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let l=`Error returned from remote node ${r}: ${_.message}`;throw CT(new Error,l,DT.INTERNAL_SERVER_ERROR,"error",l)}Cu.trace(_);for(let l=0,d=i.length;l<d;l++){let E=i[l];await Du.updateRemoteConsumer(E,r),E.subscribe===!0?await Du.updateConsumerIterator(E.schema,E.table,r,"start"):await Du.updateConsumerIterator(E.schema,E.table,r,"stop")}return n||(n=[new q5(r,[],_.system_info)]),await W5(n[0],i,_.system_info),o.length>0?c.message=$5:c.message=`Successfully updated '${r}'`,c}a(K5,"updateNode");async function W5(e,t,r){let n=e;for(let s=0,i=t.length;s<i;s++){let o=t[s],c=!1;for(let u=0,_=e.subscriptions.length;u<_;u++){let l=n.subscriptions[u];if(l.schema===o.schema&&l.table===o.table){l.publish=o.publish,l.subscribe=o.subscribe,c=!0;break}}c||n.subscriptions.push(new F5(o.schema,o.table,o.publish,o.subscribe))}n.system_info=r,await Lu.upsertNodeRecord(n),k5({type:"nats_update"})}a(W5,"updateNodeTable")});var XM=g((rhe,jM)=>{"use strict";var JM=require("joi"),{string:QM}=JM.types(),Q5=je(),zM=P(),z5=Z(),J5=ke();jM.exports=j5;function j5(e){let t=QM.invalid(z5.get(zM.CONFIG_PARAMS.CLUSTERING_NODENAME)).pattern(J5.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=JM.object({operation:QM.valid(zM.OPERATIONS_ENUM.REMOVE_NODE).required(),node_name:t});return Q5.validateBySchema(e,r)}a(j5,"removeNodeValidator")});var ef=g((she,nP)=>{"use strict";var{handleHDBError:ZM,hdb_errors:X5}=ne(),{HTTP_STATUS_CODES:eP}=X5,Z5=XM(),Mu=$(),tP=dn(),e8=J(),Zd=P(),rP=ke(),MT=ot(),t8=Z(),{RemotePayloadObject:r8}=Nu(),{NodeSubscription:n8}=pi(),s8=oa(),i8=oi(),{broadcast:o8}=Je(),a8=t8.get(Zd.CONFIG_PARAMS.CLUSTERING_NODENAME);nP.exports=c8;async function c8(e){Mu.trace("removeNode called with:",e),tP.checkClusteringEnabled();let t=Z5(e);if(t)throw ZM(t,t.message,eP.BAD_REQUEST,void 0,void 0,!0);let r=e.node_name,n=await tP.getNodeRecord(r);if(e8.isEmptyOrZeroLength(n))throw ZM(new Error,`Node '${r}' was not found.`,eP.BAD_REQUEST,void 0,void 0,!0);n=n[0];let s=new r8(Zd.OPERATIONS_ENUM.REMOVE_NODE,a8,[]),i,o=!1;for(let u=0,_=n.subscriptions.length;u<_;u++){let l=n.subscriptions[u];l.subscribe===!0&&await MT.updateConsumerIterator(l.schema,l.table,r,"stop");try{await MT.updateRemoteConsumer(new n8(l.schema,l.table,!1,!1),r)}catch(d){Mu.error(d)}}try{i=await MT.request(`${r}.${rP.REQUEST_SUFFIX}`,s),Mu.trace("Remove node reply from remote node:",r,i)}catch(u){Mu.error("removeNode received error from request:",u),o=!0}let c=new s8(Zd.SYSTEM_SCHEMA_NAME,Zd.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[r]);return await i8.deleteRecord(c),o8({type:"nats_update"}),i?.status===rP.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR||o?(Mu.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(c8,"removeNode")});var oP=g((ohe,iP)=>{"use strict";var sP=require("joi"),{string:u8,array:l8}=sP.types(),_8=je(),d8=xd();iP.exports=f8;function f8(e){let t=sP.object({operation:u8.valid("configure_cluster").required(),connections:l8.items(d8.validation_schema).required()});return _8.validateBySchema(e,t)}a(f8,"configureClusterValidator")});var PT=g((che,_P)=>{"use strict";var E8=P(),tf=$(),h8=J(),m8=ef(),p8=Xd(),aP=dn(),S8=oP(),{handleHDBError:cP,hdb_errors:T8}=ne(),{HTTP_STATUS_CODES:uP}=T8,g8="Configure cluster complete.",R8="Failed to configure the cluster. Check the logs for more details.",A8="Configure cluster was partially successful. Errors occurred when attempting to configure the following nodes. Check the logs for more details.";_P.exports=O8;async function O8(e){tf.trace("configure cluster called with:",e),aP.checkClusteringEnabled();let t=S8(e);if(t)throw cP(t,t.message,uP.BAD_REQUEST,void 0,void 0,!0);let r=await aP.getAllNodeRecords(),n=[];for(let l=0,d=r.length;l<d;l++){let E=await lP(m8,{operation:E8.OPERATIONS_ENUM.REMOVE_NODE,node_name:r[l].name},r[l].name);n.push(E)}tf.trace("All results from configure_cluster remove node:",n);let s=[],i=e.connections.length;for(let l=0;l<i;l++){let d=e.connections[l],E=await lP(p8,d,d.node_name);s.push(E)}tf.trace("All results from configure_cluster add node:",s);let o=[],c=[],u=!1,_=n.concat(s);for(let l=0,d=_.length;l<d;l++){let E=_[l];E.status==="rejected"&&(tf.error(E),o.includes(E.node_name)||o.push(E.node_name)),(E?.result?.message?.includes?.("Successfully")||E?.result?.includes?.("Successfully"))&&(u=!0),!(typeof E.result=="string"&&E.result.includes("Successfully removed")||E.status==="rejected")&&c.push({node_name:E?.node_name,subscriptions:E?.result})}if(h8.isEmptyOrZeroLength(o))return{message:g8,connections:c};if(u)return{message:A8,failed_nodes:o,connections:c};throw cP(new Error,R8,uP.INTERNAL_SERVER_ERROR,void 0,void 0,!0)}a(O8,"configureCluster");async function lP(e,t,r){try{return{node_name:r,result:await e(t)}}catch(n){return{node_name:r,error:n,status:"rejected"}}}a(lP,"functionWrapper")});var hP=g((lhe,EP)=>{"use strict";var Pu=require("joi"),b8=je(),{validateSchemaExists:dP,validateTableExists:y8,validateSchemaName:fP}=zn(),N8=Pu.object({operation:Pu.string().valid("purge_stream"),schema:Pu.string().custom(dP).custom(fP).optional(),database:Pu.string().custom(dP).custom(fP).optional(),table:Pu.string().custom(y8).required()});function I8(e){return b8.validateBySchema(e,N8)}a(I8,"purgeStreamValidator");EP.exports=I8});var UT=g((dhe,mP)=>{"use strict";var{handleHDBError:w8,hdb_errors:C8}=ne(),{HTTP_STATUS_CODES:D8}=C8,L8=hP(),M8=ot(),P8=dn();mP.exports=U8;async function U8(e){e.schema=e.schema??e.database;let t=L8(e);if(t)throw w8(t,t.message,D8.BAD_REQUEST,void 0,void 0,!0);P8.checkClusteringEnabled();let{schema:r,table:n,options:s}=e;return await M8.purgeTableStream(r,n,s),`Successfully purged table '${r}.${n}'`}a(U8,"purgeStream")});var HT=g((Ehe,AP)=>{"use strict";var BT=dn(),v8=ot(),TP=Z(),rf=P(),fo=ke(),B8=J(),vT=$(),{RemotePayloadObject:H8}=Nu(),{ErrorCode:pP}=require("nats"),SP=TP.get(rf.CONFIG_PARAMS.CLUSTERING_ENABLED),gP=TP.get(rf.CONFIG_PARAMS.CLUSTERING_NODENAME);AP.exports={clusterStatus:x8,buildNodeStatus:RP};async function x8(){let e={node_name:gP,is_enabled:SP,connections:[]};if(!SP)return e;let t=await BT.getAllNodeRecords();if(B8.isEmptyOrZeroLength(t))return e;let r=[];for(let n=0,s=t.length;n<s;n++)r.push(RP(t[n],e.connections));return await Promise.allSettled(r),e}a(x8,"clusterStatus");async function RP(e,t){let r=e.name,n=new H8(rf.OPERATIONS_ENUM.CLUSTER_STATUS,gP,void 0,await BT.getSystemInfo()),s,i,o=fo.CLUSTER_STATUS_STATUSES.OPEN;try{let u=Date.now();s=await v8.request(fo.REQUEST_SUBJECT(r),n),i=Date.now()-u,s.status===fo.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR&&(o=fo.CLUSTER_STATUS_STATUSES.CLOSED,vT.error(`Error getting node status from ${r} `,s))}catch(u){vT.warn(`Error getting node status from ${r}`,u),u.code===pP.NoResponders?o=fo.CLUSTER_STATUS_STATUSES.NO_RESPONDERS:u.code===pP.Timeout?o=fo.CLUSTER_STATUS_STATUSES.TIMEOUT:o=fo.CLUSTER_STATUS_STATUSES.CLOSED}let c=new G8(r,o,s?.message?.ports?.clustering,s?.message?.ports?.operations_api,i,s?.message?.uptime,e.subscriptions,s?.message?.system_info);try{let u={name:r,system_info:s?.message?.system_info};e.system_info?.hdb_version!==rf.PRE_4_0_0_VERSION&&await BT.upsertNodeRecord(u)}catch(u){vT.error("Cluster status encountered an error updating system info for node:",r,u)}t.push(c)}a(RP,"buildNodeStatus");function G8(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(G8,"NodeStatusObject")});var GT=g((mhe,OP)=>{"use strict";var{handleHDBError:q8,hdb_errors:F8}=ne(),{HTTP_STATUS_CODES:k8}=F8,V8=ot(),$8=dn(),xT=J(),nf=require("joi"),Y8=je(),K8=2e3,W8=nf.object({timeout:nf.number().min(1),connected_nodes:nf.boolean(),routes:nf.boolean()});OP.exports=Q8;async function Q8(e){$8.checkClusteringEnabled();let t=Y8.validateBySchema(e,W8);if(t)throw q8(t,t.message,k8.BAD_REQUEST,void 0,void 0,!0);let{timeout:r,connected_nodes:n,routes:s}=e,i=n===void 0||xT.autoCastBoolean(n),o=s===void 0||xT.autoCastBoolean(s),c={nodes:[]},u=await V8.getServerList(r??K8),_={};if(i)for(let l=0,d=u.length;l<d;l++){let E=u[l].statsz;E&&(_[u[l].server.name]=E.routes)}for(let l=0,d=u.length;l<d;l++){if(u[l].statsz)continue;let E=u[l].server,f=u[l].data;if(E.name.endsWith("-hub")){let h={name:E.name.slice(0,-4),response_time:u[l].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:xT.autoCast(p.split(":")[1])})):[]),c.nodes.push(h)}}return c}a(Q8,"clusterNetwork")});var IP=g((She,NP)=>{"use strict";var qT=require("joi"),bP=je(),{route_constraints:yP}=rp();NP.exports={setRoutesValidator:z8,deleteRoutesValidator:J8};function z8(e){let t=qT.object({server:qT.valid("hub","leaf").required(),routes:yP.required()});return bP.validateBySchema(e,t)}a(z8,"setRoutesValidator");function J8(e){let t=qT.object({routes:yP.required()});return bP.validateBySchema(e,t)}a(J8,"deleteRoutesValidator")});var kT=g((ghe,LP)=>{"use strict";var Eo=fr(),FT=J(),sf=P(),wP=IP(),{handleHDBError:CP,hdb_errors:j8}=ne(),{HTTP_STATUS_CODES:DP}=j8,X8="cluster routes successfully set",Z8="cluster routes successfully deleted";LP.exports={setRoutes:e6,getRoutes:t6,deleteRoutes:r6};function e6(e){let t=wP.setRoutesValidator(e);if(t)throw CP(t,t.message,DP.BAD_REQUEST,void 0,void 0,!0);let r=Eo.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,u=e.routes.length;c<u;c++){let _=e.routes[c];_.port=FT.autoCast(_.port);let l=n.some(E=>E.host===_.host&&E.port===_.port),d=s.some(E=>E.host===_.host&&E.port===_.port);l||d?i.push(_):(n.push(_),o.push(_))}return e.server==="hub"?Eo.updateConfigValue(sf.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,n):Eo.updateConfigValue(sf.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,n),{message:X8,set:o,skipped:i}}a(e6,"setRoutes");function t6(){let e=Eo.getClusteringRoutes();return{hub:e.hub_routes,leaf:e.leaf_routes}}a(t6,"getRoutes");function r6(e){let t=wP.deleteRoutesValidator(e);if(t)throw CP(t,t.message,DP.BAD_REQUEST,void 0,void 0,!0);let r=Eo.getClusteringRoutes(),n=r.hub_routes,s=r.leaf_routes,i=[],o=[],c=!1,u=!1;for(let _=0,l=e.routes.length;_<l;_++){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),u=!0,f=!1,i.push(d);break}}f&&o.push(d)}}return c&&(n=FT.isEmptyOrZeroLength(n)?null:n,Eo.updateConfigValue(sf.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,n)),u&&(s=FT.isEmptyOrZeroLength(s)?null:s,Eo.updateConfigValue(sf.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,s)),{message:Z8,deleted:i,skipped:o}}a(r6,"deleteRoutes")});var PP=g((Ahe,MP)=>{"use strict";var Uu=require("alasql"),ho=require("recursive-iterator"),Hn=$(),n6=J(),vu=P(),VT=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,i6(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=>vu.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=>!vu.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][vu.PERMS_CRUD_ENUM.READ]){let c;t[i].tables[o].attribute_permissions.length>0?c=s6(t[i].tables[o].attribute_permissions):c=global.hdb_schema[i][o].attributes.map(_=>({attribute_name:_.attribute}));let u=this.affected_attributes.get(i).get(o).filter(_=>!vu.SEARCH_WILDCARDS.includes(_));c.forEach(({attribute_name:_})=>{let l=new Uu.yy.Column({columnid:_});s.tableid&&(l.tableid=s.tableid),this.ast.columns.push(l),u.includes(_)||u.push(_)}),this.affected_attributes.get(i).set(o,u)}}),this.ast}};function s6(e){return e.filter(t=>t[vu.PERMS_CRUD_ENUM.READ])}a(s6,"filterReadRestrictedAttrs");function i6(e,t,r,n,s){o6(e,t,r,n,s)}a(i6,"interpretAST");function Bu(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(Bu,"addSchemaTableToMap");function o6(e,t,r,n,s){if(!e){Hn.info("getRecordAttributesAST: invalid SQL syntax tree");return}e instanceof Uu.yy.Insert?l6(e,t,r):e instanceof Uu.yy.Select?a6(e,t,r,n,s):e instanceof Uu.yy.Update?c6(e,t,r):e instanceof Uu.yy.Delete?u6(e,t,r):Hn.error("AST in getRecordAttributesAST() is not a valid SQL type.")}a(o6,"getRecordAttributesAST");function a6(e,t,r,n,s){if(!e){Hn.info("getSelectAttributes: invalid SQL syntax tree");return}if(!e.from||e.from[0]===void 0)return;let i=e.from[0].databaseid;if(n6.isEmptyOrZeroLength(i)){Hn.error("No schema specified");return}e.from.forEach(c=>{Bu(c,t,r,n,s)}),e.joins&&e.joins.forEach(c=>{c.as&&(c.table.as=c.as),Bu(c.table,t,r,n,s)});let o=new ho(e.columns);for(let{node:c}of o)if(c&&c.columnid){let u=c.tableid,_=n.has(u)?n.get(u):i;if(u||(u=e.from[0].tableid),!t.get(_).has(u))if(r.has(u))u=r.get(u);else{Hn.info(`table specified as ${u} not found.`);return}t.get(_).get(u).indexOf(c.columnid)<0&&t.get(_).get(u).push(c.columnid)}if(e.where){let c=new ho(e.where),u=e.from[0].tableid;for(let{node:_}of c)if(_&&_.columnid){let l=_.tableid?_.tableid:u;if(!t.get(i).has(l))if(r.has(l))l=r.get(l);else{Hn.info(`table specified as ${l} not found.`);continue}t.get(i).get(l).indexOf(_.columnid)<0&&t.get(i).get(l).push(_.columnid)}}if(e.joins&&e.joins.forEach(c=>{let u=new ho(c.on);for(let{node:_}of u)if(_&&_.columnid){let l=_.tableid,d=s.get(l);if(!t.get(d).has(l))if(r.has(l))l=r.get(l);else{Hn.info(`table specified as ${l} not found.`);continue}t.get(d).get(l).indexOf(_.columnid)<0&&t.get(d).get(l).push(_.columnid)}}),e.order){let c=new ho(e.order);for(let{node:u}of c)if(u&&u.columnid){let _=u.tableid,l=n.has(_)?n.get(_):i;if(_||(_=e.from[0].tableid),!t.get(l).has(_))if(r.has(_))_=r.get(_);else{Hn.info(`table specified as ${_} not found.`);return}t.get(l).get(_).indexOf(u.columnid)<0&&t.get(l).get(_).push(u.columnid)}}}a(a6,"getSelectAttributes");function c6(e,t,r){if(!e){Hn.info("getUpdateAttributes: invalid SQL syntax tree");return}let n=new ho(e.columns),s=e.table.databaseid;Bu(e.table,t,r);for(let{node:i}of n)i&&i.columnid&&$T(e.table.tableid,s,i.columnid,t,r)}a(c6,"getUpdateAttributes");function u6(e,t,r){if(!e){Hn.info("getDeleteAttributes: invalid SQL syntax tree");return}let n=new ho(e.where),s=e.table.databaseid;Bu(e.table,t,r);for(let{node:i}of n)i&&i.columnid&&$T(e.table.tableid,s,i.columnid,t,r)}a(u6,"getDeleteAttributes");function l6(e,t,r){if(!e){Hn.info("getInsertAttributes: invalid SQL syntax tree");return}let n=new ho(e.columns),s=e.into.databaseid;Bu(e.into,t,r);for(let{node:i}of n)i&&i.columnid&&$T(e.into.tableid,s,i.columnid,t,r)}a(l6,"getInsertAttributes");function $T(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($T,"pushAttribute");MP.exports=VT});var WT=g((bhe,HP)=>{var of=Ji(),UP=require("chalk"),Qr=$(),vP=require("prompt"),{promisify:_6}=require("util"),YT=P(),d6=require("fs-extra"),f6=require("path"),E6=J(),h6=Kd(),BP=Z();BP.initSync();var m6=require("moment"),p6=_6(vP.get),S6=f6.join(BP.getHdbBasePath(),YT.LICENSE_KEY_DIR_NAME,YT.LICENSE_FILE_NAME,YT.LICENSE_FILE_NAME);HP.exports={getFingerprint:g6,setLicense:T6,parseLicense:KT,register:R6,getRegistrationInfo:O6};async function T6(e){if(e&&e.key&&e.company){try{Qr.info(`parsing license key: ${e.key} and `);let t=e.company.toString();await KT(e.key.trim(),t.trim())}catch(t){let r="There was an error parsing the license key.";throw Qr.error(r),Qr.error(t),new Error(r)}return"Wrote license key file. Registration successful."}throw new Error("Invalid key or company specified for license file.")}a(T6,"setLicense");async function g6(){let e={};try{e=await of.generateFingerPrint()}catch(t){let r="Error generating fingerprint.";throw Qr.error(r),Qr.error(t),new Error(r)}return e}a(g6,"getFingerprint");async function KT(e,t){if(!e||!t)throw new Error("Invalid entries for License Key and Customer Company");Qr.info("Validating license input...");let r=of.validateLicense(e,t);if(Qr.info("checking for valid license..."),!r.valid_license)throw new Error("Invalid license found.");if(Qr.info("checking valid license date..."),!r.valid_date)throw new Error("This License has expired.");if(Qr.info(`checking for valid machine license ${r.valid_machine}`),!r.valid_machine)throw new Error("This license is in use on another machine.");try{Qr.info("writing license to disk"),await d6.writeFile(S6,JSON.stringify({license_key:e,company:t}))}catch(n){throw Qr.error("Failed to write License"),n}return"Registration successful."}a(KT,"parseLicense");async function R6(){let e=await A6();return KT(e.HDB_LICENSE,e.CUSTOMER_COMPANY)}a(R6,"register");async function A6(){let e=await of.generateFingerPrint(),t={properties:{CUSTOMER_COMPANY:{description:UP.magenta("[COMPANY] Please enter your company name"),required:!0},HDB_LICENSE:{description:UP.magenta(`[HDB_LICENSE] Your fingerprint is ${e} Please enter your license key`),required:!0}}};try{vP.start()}catch(n){Qr.error(n)}let r;try{r=await p6(t)}catch(n){throw console.error("There was a problem prompting for registration input. Exiting."),n}return r}a(A6,"promptForRegistration");async function O6(){let e={registered:!1,version:null,ram_allocation:null,license_expiration_date:null},t;try{t=await of.getLicense()}catch(r){throw Qr.error(`There was an error when searching licenses due to: ${r.message}`),r}if(E6.isEmptyOrZeroLength(t))throw new Error("There were no licenses found.");if(e.registered=t.enterprise,e.version=h6.version(),e.ram_allocation=t.ram_allocation,isNaN(t.exp_date))e.license_expiration_date=t.enterprise?t.exp_date:null;else{let r=m6.utc(t.exp_date).format("YYYY-MM-DD");e.license_expiration_date=t.enterprise?r:null}return e}a(O6,"getRegistrationInfo")});var GP=g((Nhe,xP)=>{"use strict";var b6=ke(),QT=class{static{a(this,"HubConfigObject")}constructor(t,r,n,s,i,o,c,u,_,l,d,E,f,h){this.port=t,o===null&&(o=void 0),this.server_name=r+b6.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:u},this.leafnodes={port:_,tls:{cert_file:s,key_file:i,ca_file:o,insecure:c}},this.cluster={name:l,port:d,routes:E,tls:{cert_file:s,key_file:i,ca_file:o,insecure:c,verify:u}},this.accounts={SYS:{users:f},HDB:{users:h}},this.system_account="SYS"}};xP.exports=QT});var kP=g((whe,FP)=>{"use strict";var qP=ke(),zT=class{static{a(this,"LeafConfigObject")}constructor(t,r,n,s,i,o,c,u,_,l,d){this.port=t,d===null&&(d=void 0),this.server_name=r+qP.SERVER_SUFFIX.LEAF,this.pid_file=n,this.max_payload=67108864,this.jetstream={enabled:!0,store_dir:s,domain:r+qP.SERVER_SUFFIX.LEAF},this.tls={cert_file:_,key_file:l,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:u,jetstream:"enabled"}},this.system_account="SYS"}};FP.exports=zT});var $P=g((Dhe,VP)=>{"use strict";var JT=class{static{a(this,"HdbUserObject")}constructor(t,r){this.user=t,this.password=r}};VP.exports=JT});var KP=g((Mhe,YP)=>{"use strict";var y6=ke(),jT=class{static{a(this,"SysUserObject")}constructor(t,r){this.user=t+y6.SERVER_SUFFIX.ADMIN,this.password=r}};YP.exports=jT});var eg=g((Uhe,zP)=>{"use strict";var ga=require("path"),uf=require("fs-extra"),N6=GP(),I6=kP(),w6=$P(),C6=KP(),XT=ln(),Aa=J(),br=fr(),cf=P(),Hu=ke(),{CONFIG_PARAMS:ht}=cf,Oa=$(),xu=Z(),WP=Rs(),ZT=ot(),Ra="clustering",D6=1e4,QP=50;zP.exports={generateNatsConfig:M6,removeNatsConfig:P6,getHubConfigPath:L6};function L6(){let e=xu.get(ht.ROOTPATH);return ga.join(e,Ra,Hu.NATS_CONFIG_FILES.HUB_SERVER)}a(L6,"getHubConfigPath");async function M6(e=!1,t=void 0){xu.initSync();let r=xu.get(ht.ROOTPATH),n=ga.join(r,Ra,Hu.PID_FILES.HUB),s=ga.join(r,Ra,Hu.PID_FILES.LEAF),i=br.getConfigFromFile(ht.CLUSTERING_LEAFSERVER_STREAMS_PATH),o=ga.join(r,Ra,Hu.NATS_CONFIG_FILES.HUB_SERVER),c=ga.join(r,Ra,Hu.NATS_CONFIG_FILES.LEAF_SERVER),u=br.getConfigFromFile(ht.CLUSTERING_TLS_CERTIFICATE),_=br.getConfigFromFile(ht.CLUSTERING_TLS_PRIVATEKEY),l=br.getConfigFromFile(ht.CLUSTERING_TLS_CERT_AUTH),d=br.getConfigFromFile(ht.CLUSTERING_TLS_INSECURE),E=br.getConfigFromFile(ht.CLUSTERING_TLS_VERIFY),f=br.getConfigFromFile(ht.CLUSTERING_NODENAME),h=br.getConfigFromFile(ht.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT);await ZT.checkNATSServerInstalled()||lf("nats-server dependency is either missing or the wrong version. Run 'npm install' to fix");let p=await XT.listUsers(),S=br.getConfigFromFile(ht.CLUSTERING_USER),T=await XT.getClusterUser();(Aa.isEmpty(T)||T.active!==!0)&&lf(`Invalid cluster user '${S}'. A valid user with the role 'cluster_user' must be defined under clustering.user in harperdb-config.yaml`),e||(await af(ht.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),await af(ht.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT),await af(ht.CLUSTERING_HUBSERVER_NETWORK_PORT),await af(ht.CLUSTERING_LEAFSERVER_NETWORK_PORT));let A=[],R=[];for(let[j,z]of p.entries())z.role.role===cf.ROLE_TYPES_ENUM.CLUSTER_USER&&z.active&&(A.push(new C6(z.username,WP.decrypt(z.hash))),R.push(new w6(z.username,WP.decrypt(z.hash))));let C=[],{hub_routes:x}=br.getClusteringRoutes();if(!Aa.isEmptyOrZeroLength(x))for(let j of x)C.push(`tls://${T.sys_name_encoded}:${T.uri_encoded_d_hash}@${j.host}:${j.port}`);let v=new N6(br.getConfigFromFile(ht.CLUSTERING_HUBSERVER_NETWORK_PORT),f,n,u,_,l,d,E,h,br.getConfigFromFile(ht.CLUSTERING_HUBSERVER_CLUSTER_NAME),br.getConfigFromFile(ht.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),C,A,R);l==null&&(delete v.tls.ca_file,delete v.leafnodes.tls.ca_file),t=Aa.isEmpty(t)?void 0:t.toLowerCase(),(t===void 0||t===cf.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase())&&(await uf.writeJson(o,v),Oa.trace(`Hub server config written to ${o}`));let k=`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 I6(br.getConfigFromFile(ht.CLUSTERING_LEAFSERVER_NETWORK_PORT),f,s,i,[k],[M],A,R,u,_,l,d);l==null&&delete Q.tls.ca_file,(t===void 0||t===cf.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())&&(await uf.writeJson(c,Q),Oa.trace(`Leaf server config written to ${c}`))}a(M6,"generateNatsConfig");async function af(e){let t=xu.get(e);return Aa.isEmpty(t)&&lf(`port undefined for '${e}'`),await Aa.isPortTaken(t)&&lf(`'${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(af,"isPortAvailable");function lf(e){let t=`Error generating clustering config: ${e}`;Oa.error(t),console.error(t),process.exit(1)}a(lf,"generateNatsConfigError");async function P6(e){let{port:t,config_file:r}=ZT.getServerConfig(e),{username:n,decrypt_hash:s}=await XT.getClusterUser(),i=0,o=2e3;for(;i<QP;){try{let l=await ZT.createConnection(t,n,s,!1);if(l.protocol.connected===!0){l.close();break}}catch(l){Oa.trace(`removeNatsConfig waiting for ${e}. Caught and swallowed error ${l}`)}if(i++,i>=QP)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&&Oa.notify("Operations API waiting for Nats server connection. This could be caused by large Nats streams or incorrect clustering config."),await Aa.async_set_timeout(_)}let c="0".repeat(D6),u=ga.join(xu.get(ht.ROOTPATH),Ra,r);await uf.writeFile(u,c),await uf.remove(u),Oa.notify(e,"started.")}a(P6,"removeNatsConfig")});var tU=g((Bhe,eU)=>{"use strict";var zr=Z(),U6=Ji(),pe=P(),Gu=ke(),Cs=require("path"),{PACKAGE_ROOT:df}=P(),JP=Z(),_f=J(),ba="/dev/null",v6=Cs.join(df,"launchServiceScripts"),jP=Cs.join(df,"utility/scripts"),B6=Cs.join(jP,pe.HDB_RESTART_SCRIPT),XP=Cs.resolve(df,"dependencies",`${process.platform}-${process.arch}`,Gu.NATS_BINARY_NAME);function ZP(){let t=U6.licenseSearch().ram_allocation||pe.RAM_ALLOCATION_ENUM.DEFAULT,r=pe.MEM_SETTING_KEY+t,n={[pe.PROCESS_NAME_ENV_PROP]:pe.PROCESS_DESCRIPTORS.HDB,IS_SCRIPTED_SERVICE:!0};return _f.noBootFile()&&(n[pe.CONFIG_PARAMS.ROOTPATH.toUpperCase()]=_f.getEnvCliRootPath()),{name:pe.PROCESS_DESCRIPTORS.HDB,script:pe.LAUNCH_SERVICE_SCRIPTS.MAIN,exec_mode:"fork",env:n,node_args:r,cwd:df}}a(ZP,"generateMainServerConfig");var H6=9930;function x6(){zr.initSync(!0);let e=zr.get(pe.CONFIG_PARAMS.ROOTPATH),t=Cs.join(e,"clustering",Gu.NATS_CONFIG_FILES.HUB_SERVER),r=Cs.join(zr.get(pe.HDB_SETTINGS_NAMES.LOG_PATH_KEY),pe.LOG_NAMES.HDB),n=JP.get(pe.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),s=Gu.LOG_LEVEL_FLAGS[zr.get(pe.CONFIG_PARAMS.CLUSTERING_LOGLEVEL)]??void 0,i={name:pe.PROCESS_DESCRIPTORS.CLUSTERING_HUB+(n!==H6?"-"+n:""),script:XP,args:s?`${s} -c ${t}`:`-c ${t}`,exec_mode:"fork",env:{[pe.PROCESS_NAME_ENV_PROP]:pe.PROCESS_DESCRIPTORS.CLUSTERING_HUB},merge_logs:!0,out_file:r,error_file:r,instances:1};return zr.get(pe.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(i.out_file=ba,i.error_file=ba),i}a(x6,"generateNatsHubServerConfig");var G6=9940;function q6(){zr.initSync(!0);let e=zr.get(pe.CONFIG_PARAMS.ROOTPATH),t=Cs.join(e,"clustering",Gu.NATS_CONFIG_FILES.LEAF_SERVER),r=Cs.join(zr.get(pe.HDB_SETTINGS_NAMES.LOG_PATH_KEY),pe.LOG_NAMES.HDB),n=JP.get(pe.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),s=Gu.LOG_LEVEL_FLAGS[zr.get(pe.CONFIG_PARAMS.CLUSTERING_LOGLEVEL)]??void 0,i={name:pe.PROCESS_DESCRIPTORS.CLUSTERING_LEAF+(n!==G6?"-"+n:""),script:XP,args:s?`${s} -c ${t}`:`-c ${t}`,exec_mode:"fork",env:{[pe.PROCESS_NAME_ENV_PROP]:pe.PROCESS_DESCRIPTORS.CLUSTERING_LEAF},merge_logs:!0,out_file:r,error_file:r,instances:1};return zr.get(pe.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(i.out_file=ba,i.error_file=ba),i}a(q6,"generateNatsLeafServerConfig");function F6(){zr.initSync();let e=Cs.join(zr.get(pe.CONFIG_PARAMS.LOGGING_ROOT),pe.LOG_NAMES.HDB),t={name:pe.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0,script:pe.LAUNCH_SERVICE_SCRIPTS.NODES_UPGRADE_4_0_0,exec_mode:"fork",env:{[pe.PROCESS_NAME_ENV_PROP]:pe.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0},merge_logs:!0,out_file:e,error_file:e,instances:1,cwd:v6,autorestart:!1};return zr.get(pe.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(t.out_file=ba,t.error_file=ba),t}a(F6,"generateClusteringUpgradeV4ServiceConfig");function k6(){let e={[pe.PROCESS_NAME_ENV_PROP]:pe.PROCESS_DESCRIPTORS.RESTART_HDB};return _f.noBootFile()&&(e[pe.CONFIG_PARAMS.ROOTPATH.toUpperCase()]=_f.getEnvCliRootPath()),{...{name:pe.PROCESS_DESCRIPTORS.RESTART_HDB,exec_mode:"fork",env:e,instances:1,autorestart:!1,cwd:jP},script:B6}}a(k6,"generateRestart");function V6(){return{apps:[ZP()]}}a(V6,"generateAllServiceConfigs");eU.exports={generateAllServiceConfigs:V6,generateMainServerConfig:ZP,generateRestart:k6,generateNatsHubServerConfig:x6,generateNatsLeafServerConfig:q6,generateClusteringUpgradeV4ServiceConfig:F6}});var hU=g((Ghe,EU)=>{"use strict";var Ue=P(),$6=J(),Ls=eg(),ff=ot(),Ds=ke(),Ti=tU(),Ef=Z(),gi=$(),Y6=dn(),{startWorker:rU,onMessageFromWorkers:K6}=Je(),W6=Ta(),xhe=require("util"),Q6=require("child_process"),z6=require("fs"),{execFile:J6}=Q6,we;EU.exports={enterPM2Mode:j6,start:Ri,stop:tg,reload:sU,restart:iU,list:rg,describe:aU,connect:Ms,kill:r9,startAllServices:n9,startService:ng,getUniqueServicesList:cU,restartAllServices:s9,isServiceRegistered:uU,reloadStopStart:lU,restartHdb:oU,deleteProcess:e9,startClusteringProcesses:dU,startClusteringThreads:fU,isHdbRestartRunning:t9,isClusteringRunning:o9,stopClustering:i9,reloadClustering:a9};var qu=!1;K6(e=>{e.type==="restart"&&Ef.initSync(!0)});function j6(){qu=!0}a(j6,"enterPM2Mode");function Ms(){return we||(we=require("pm2")),new Promise((e,t)=>{we.connect((r,n)=>{gi.setupConsoleLogging(),r&&t(r),e(n)})})}a(Ms,"connect");var yr,X6=10,nU;function Ri(e,t=!1){if(qu)return Z6(e);let r=J6(e.script,e.args.split(" "),e);r.name=e.name,r.on("exit",async i=>{let o=yr.indexOf(r);o>-1&&yr.splice(o,1),!nU&&i!==0&&(e.restarts=(e.restarts||0)+1,e.restarts<X6&&(z6.existsSync(Ls.getHubConfigPath())?Ri(e):(await Ls.generateNatsConfig(!0),Ri(e),await new Promise(c=>setTimeout(c,3e3)),await Ls.removeNatsConfig(Ue.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await Ls.removeNatsConfig(Ue.PROCESS_DESCRIPTORS.CLUSTERING_LEAF))))});let n={serviceName:e.name.replace(/ /g,"-")};function s(i){let o=Ef.get(Ue.CONFIG_PARAMS.CLUSTERING_LOGLEVEL),c=/\[\d+][^\[]+\[(\w+)]/g,u,_=0,l;for(;u=c.exec(i);){if(u.index&&Ds.LOG_LEVEL_HIERARCHY[o]>=Ds.LOG_LEVEL_HIERARCHY[l||"info"]){let f=l===Ds.LOG_LEVELS.ERR||l===Ds.LOG_LEVELS.WRN?gi.OUTPUTS.STDERR:gi.OUTPUTS.STDOUT;gi.logCustomLevel(l||"info",f,n,i.slice(_,u.index).trim())}let[d,E]=u;_=u.index+d.length,l=Ds.LOG_LEVELS[E]}if(Ds.LOG_LEVEL_HIERARCHY[o]>=Ds.LOG_LEVEL_HIERARCHY[l||"info"]){let d=l===Ds.LOG_LEVELS.ERR||l===Ds.LOG_LEVELS.WRN?gi.OUTPUTS.STDERR:gi.OUTPUTS.STDOUT;gi.logCustomLevel(l||"info",d,n,i.slice(_).trim())}}if(a(s,"extractMessages"),r.stdout.on("data",s),r.stderr.on("data",s),r.unref(),yr=[],!yr&&!t){let i=a(()=>{nU=!0,yr&&(yr.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)}yr.push(r)}a(Ri,"start");function Z6(e){return new Promise(async(t,r)=>{try{await Ms()}catch(n){r(n)}we.start(e,(n,s)=>{n&&(we.disconnect(),r(n)),we.disconnect(),t(s)})})}a(Z6,"startWithPM2");function tg(e){if(!qu){for(let t of yr||[])t.name===e&&(yr.splice(yr.indexOf(t),1),t.kill());return}return new Promise(async(t,r)=>{try{await Ms()}catch(n){r(n)}we.stop(e,async(n,s)=>{n&&(we.disconnect(),r(n)),we.delete(e,(i,o)=>{i&&(we.disconnect(),r(n)),we.disconnect(),t(o)})})})}a(tg,"stop");function sU(e){return new Promise(async(t,r)=>{try{await Ms()}catch(n){r(n)}we.reload(e,(n,s)=>{n&&(we.disconnect(),r(n)),we.disconnect(),t(s)})})}a(sU,"reload");function iU(e){if(!qu)for(let t of yr||[])t.name===e&&t.kill();return new Promise(async(t,r)=>{try{await Ms()}catch(n){r(n)}we.restart(e,(n,s)=>{we.disconnect(),t(s)})})}a(iU,"restart");function e9(e){return new Promise(async(t,r)=>{try{await Ms()}catch(n){r(n)}we.delete(e,(n,s)=>{n&&(we.disconnect(),r(n)),we.disconnect(),t(s)})})}a(e9,"deleteProcess");async function oU(){await Ri(Ti.generateRestart())}a(oU,"restartHdb");async function t9(){let e=await rg();for(let t in e)if(e[t].name===Ue.PROCESS_DESCRIPTORS.RESTART_HDB)return!0;return!1}a(t9,"isHdbRestartRunning");function rg(){return new Promise(async(e,t)=>{try{await Ms()}catch(r){t(r)}we.list((r,n)=>{r&&(we.disconnect(),t(r)),we.disconnect(),e(n)})})}a(rg,"list");function aU(e){return new Promise(async(t,r)=>{try{await Ms()}catch(n){r(n)}we.describe(e,(n,s)=>{n&&(we.disconnect(),r(n)),we.disconnect(),t(s)})})}a(aU,"describe");function r9(){if(!qu){for(let e of yr||[])e.kill();yr=[];return}return new Promise(async(e,t)=>{try{await Ms()}catch(r){t(r)}we.killDaemon((r,n)=>{r&&(we.disconnect(),t(r)),we.disconnect(),e(n)})})}a(r9,"kill");async function n9(){try{await dU(),await fU(),await Ri(Ti.generateAllServiceConfigs())}catch(e){throw we?.disconnect(),e}}a(n9,"startAllServices");async function ng(e,t=!1){try{let r;switch(e=e.toLowerCase(),e){case Ue.PROCESS_DESCRIPTORS.HDB.toLowerCase():r=Ti.generateMainServerConfig();break;case Ue.PROCESS_DESCRIPTORS.CLUSTERING_INGEST_SERVICE.toLowerCase():r=Ti.generateNatsIngestServiceConfig();break;case Ue.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE.toLowerCase():r=Ti.generateNatsReplyServiceConfig();break;case Ue.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase():r=Ti.generateNatsHubServerConfig(),await Ri(r,t),await Ls.removeNatsConfig(e);return;case Ue.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase():r=Ti.generateNatsLeafServerConfig(),await Ri(r,t),await Ls.removeNatsConfig(e);return;case Ue.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0.toLowerCase():r=Ti.generateClusteringUpgradeV4ServiceConfig();break;default:throw new Error(`Start service called with unknown service config: ${e}`)}await Ri(r)}catch(r){throw we?.disconnect(),r}}a(ng,"startService");async function cU(){try{let e=await rg(),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 we?.disconnect(),e}}a(cU,"getUniqueServicesList");async function s9(e=[]){try{let t=!1,r=await cU();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 iU(o))}t&&await lU(Ue.PROCESS_DESCRIPTORS.HDB)}catch(t){throw we?.disconnect(),t}}a(s9,"restartAllServices");async function uU(e){if(yr?.find(r=>r.name===e))return!0;let t=await W6.getHDBProcessInfo();return t.core.length&&t.core[0]?.parent==="PM2"}a(uU,"isServiceRegistered");async function lU(e){let t=Ef.get(Ue.CONFIG_PARAMS.THREADS_COUNT)??Ef.get(Ue.CONFIG_PARAMS.THREADS),r=await aU(e),n=$6.isEmptyOrZeroLength(r)?0:r.length;t!==n?(await tg(e),await ng(e)):e===Ue.PROCESS_DESCRIPTORS.HDB?await oU():await sU(e)}a(lU,"reloadStopStart");var _U;async function dU(e=!1){for(let t in Ue.CLUSTERING_PROCESSES){let r=Ue.CLUSTERING_PROCESSES[t];await ng(r,e)}}a(dU,"startClusteringProcesses");async function fU(){_U=rU(Ue.LAUNCH_SERVICE_SCRIPTS.NATS_REPLY_SERVICE,{name:Ue.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE});try{await ff.deleteLocalStream("__HARPERDB_WORK_QUEUE__")}catch{}await ff.updateLocalStreams();let e=await Y6.getAllNodeRecords();for(let t=0,r=e.length;t<r;t++)if(e[t].system_info?.hdb_version===Ue.PRE_4_0_0_VERSION){gi.info("Starting clustering upgrade 4.0.0 process"),rU(Ue.LAUNCH_SERVICE_SCRIPTS.NODES_UPGRADE_4_0_0,{name:"Upgrade-4-0-0"});break}}a(fU,"startClusteringThreads");async function i9(){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 _U.terminate();else{let t=Ue.CLUSTERING_PROCESSES[e];await tg(t)}}a(i9,"stopClustering");async function o9(){for(let e in Ue.CLUSTERING_PROCESSES){let t=Ue.CLUSTERING_PROCESSES[e];if(await uU(t)===!1)return!1}return!0}a(o9,"isClusteringRunning");async function a9(){await Ls.generateNatsConfig(!0),await ff.reloadNATSHub(),await ff.reloadNATSLeaf(),await Ls.removeNatsConfig(Ue.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase()),await Ls.removeNatsConfig(Ue.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())}a(a9,"reloadClustering")});var AU={};qe(AU,{compactOnStart:()=>c9,copyDb:()=>RU});async function c9(){ku.notify("Running compact on start"),console.log("Running compact on start");let e=(0,sg.get)(Ai.CONFIG_PARAMS.ROOTPATH),t=new Map,r=hr();try{for(let n in r){if(n==="system")continue;let s;for(let u in r[n]){s=r[n][u].primaryStore.path;break}if(!s){console.log("Couldn't find any tables in database",n);continue}let i=(0,hf.join)(e,"backup",n+".mdb"),o=(0,hf.join)(e,Ai.DATABASES_DIR_NAME,n+"-copy.mdb"),c=await mU(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 RU(n,o),console.log("Backing up",n,"to",i),await(0,mo.move)(s,i,{overwrite:!0})}Fu();for(let[n,{db_path:s,copy_dest:i}]of t)console.log("Moving copy compacted",n,"to",s),await(0,mo.move)(i,s,{overwrite:!0}),await(0,mo.remove)((0,hf.join)(e,Ai.DATABASES_DIR_NAME,`${n}-copy.mdb-lock`));Fu()}catch(n){ku.error("Error compacting database, rolling back operation",n),console.error("Error compacting database, rolling back operation",n),(0,ig.updateConfigValue)(Ai.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,mo.move)(o,i,{overwrite:!0})}catch(c){console.error(c)}}throw Fu(),n}for(let[n,{backup_dest:s,record_count:i}]of t){let o=!0,c=await mU(n);if(console.log("Database",n,"after compact has a total record count of",c),i!==c){o=!1;let u=`There is a discrepancy between pre and post compact record count for database ${n}.
|
|
10
|
+
`,"")}a(_L,"runCommand");async function Sj(){try{await z3.access(LS)}catch{return!1}let e=await _L(`${LS} --version`,void 0),t=e.substring(e.lastIndexOf("v")+1,e.length);return J3.eq(t,mj)}a(Sj,"checkNATSServerInstalled");async function BS(e,t,r,n=!0,s="127.0.0.1"){if(!t&&!r){let o=await uL.getClusterUser();if(co(o))throw new Error("Unable to get nats connection. Cluster user is undefined.");t=o.username,r=o.decrypt_hash}Bn.trace("create nats connection called");let i=await oj({name:s,port:e,user:t,pass:r,maxReconnectAttempts:-1,waitOnFirstConnect:n,timeout:2e5,tls:{keyFile:xt.get(Ie.CONFIG_PARAMS.CLUSTERING_TLS_PRIVATEKEY),certFile:xt.get(Ie.CONFIG_PARAMS.CLUSTERING_TLS_CERTIFICATE),caFile:xt.get(Ie.CONFIG_PARAMS.CLUSTERING_TLS_CERT_AUTH),rejectUnauthorized:!1}});return i.protocol.transport.socket.unref(),Bn.trace("create connection established a nats client connection with id",i?.info?.client_id),i.closed().then(o=>{o&&Bn.error("Error with Nats client connection, connection closed",o),dL()}),i}a(BS,"createConnection");function dL(){Tr=void 0,io=void 0,oo=void 0,ao=void 0}a(dL,"clearClientCache");async function Tj(){Tr&&(await Tr.drain(),Tr=void 0,io=void 0,oo=void 0,ao=void 0)}a(Tj,"closeConnection");var Tr,ao;async function Su(){return ao||(ao=BS(xt.get(Ie.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),void 0,void 0),Tr=await ao),Tr||ao}a(Su,"getConnection");async function Tu(){if(io)return io;co(Tr)&&await Su();let{domain:e}=da(Ie.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);if(co(e))throw new Error("Error getting JetStream domain. Unable to get JetStream manager.");return io=await Tr.jetstreamManager({domain:e,timeout:6e4}),io}a(Tu,"getJetStreamManager");async function fL(){if(oo)return oo;co(Tr)&&await Su();let{domain:e}=da(Ie.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);if(co(e))throw new Error("Error getting JetStream domain. Unable to get JetStream manager.");return oo=Tr.jetstream({domain:e,timeout:6e4}),oo}a(fL,"getJetStream");async function is(){let e=Tr||await Su(),t=io||await Tu(),r=oo||await fL();return{connection:e,jsm:t,js:r}}a(is,"getNATSReferences");async function gj(e){let t=xt.get(Ie.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),{sys_name:r,decrypt_hash:n}=await uL.getClusterUser(),s=await BS(t,r,n),i=vS(),o=s.subscribe(i),c=[],u,_=(async()=>{for await(let l of o){let d=lL.decode(l.data);d.response_time=Date.now()-u,c.push(d)}})();return u=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 Ld.async_set_timeout(e),await o.drain(),await s.close(),await _,c}a(gj,"getServerList");async function xS(e,t){let{jsm:r}=await is(),n=xt.get(Ie.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE);n=n===null?0:n*1e9;let s=xt.get(Ie.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS);s=s===null?-1:s;let i=xt.get(Ie.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES);i=i===null?-1:i,await r.streams.add({name:e,storage:aj.File,retention:cj.Limits,subjects:t,discard:uj.Old,max_msgs:s,max_bytes:i,max_age:n})}a(xS,"createLocalStream");async function EL(){let{jsm:e}=await is(),t=await e.streams.list().next(),r=[];return t.forEach(n=>{r.push(n)}),r}a(EL,"listStreams");async function Rj(e){let{jsm:t}=await is();await t.streams.delete(e)}a(Rj,"deleteLocalStream");async function Aj(e){let{connection:t}=await is(),r=[],n=vS(),s=t.subscribe(n),i=(async()=>{for await(let o of s)r.push(lL.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(Aj,"listRemoteStreams");async function Oj(e,t=void 0,r=void 0){let{jsm:n,js:s}=await is(),i=iL(),o={durable_name:i,ack_policy:PS.Explicit};t&&(o.deliver_policy=US.StartTime,o.opt_start_time=new Date(t).toISOString()),await n.consumers.add(e,o);let c=await s.consumers.get(e,i),u=r?await c.fetch({max_messages:r,expires:2e3}):await c.consume();if(c._info.num_pending===0)return[];let _=[];for await(let l of u){let d=MS(l.data),E={nats_timestamp:l.info.timestampNanos,nats_sequence:l.info.streamSequence,entry:d};if(l.headers&&(E.origin=l.headers.get(Kt.MSG_HEADERS.ORIGIN)),_.push(E),l.ack(),l.info.pending===0)break}return await c.delete(),_}a(Oj,"viewStream");async function*bj(e,t=void 0,r=void 0){let{jsm:n,js:s}=await is(),i=iL(),o={durable_name:i,ack_policy:PS.Explicit};t&&(o.deliver_policy=US.StartTime,o.opt_start_time=new Date(t).toISOString()),await n.consumers.add(e,o);let c=await s.consumers.get(e,i),u=r?await c.fetch({max_messages:r,expires:2e3}):await c.consume();if(c._info.num_pending===0)return[];for await(let _ of u){let l=MS(_.data);l[0]||(l=[l]);for(let d of l){let E={nats_timestamp:_.info.timestampNanos,nats_sequence:_.info.streamSequence,entry:d};_.headers&&(E.origin=_.headers.get(Kt.MSG_HEADERS.ORIGIN)),yield E}if(_.ack(),_.info.pending===0)break}await c.delete()}a(bj,"viewStreamIterator");async function yj(e,t,r,n){Bn.trace(`publishToStream called with subject: ${e}, stream: ${t}, entries:`,n.operation),r=hL(n,r);let{js:s}=await is(),i=await Pd(),o=`${e}.${i}`,c=n instanceof Uint8Array?n:cL.encode(n);try{Bn.trace(`publishToStream publishing to subject: ${o}`),Ej(c.length,"bytes-sent",e,n.operation,"replication"),await s.publish(o,c,{headers:r})}catch(u){if(u.code&&u.code.toString()==="503")return pL(async()=>{try{await s.publish(o,c,{headers:r})}catch{if(u.code&&u.code.toString()==="503"){Bn.trace(`publishToStream creating stream: ${t}`);let l=o.split(".");l[2]="*",await xS(t,[o]),await s.publish(o,c,{headers:r})}else throw u}});throw u}}a(yj,"publishToStream");function hL(e,t){t===void 0&&(t=_j());let r=xt.get(Ie.CONFIG_PARAMS.CLUSTERING_NODENAME);return!t.has(Kt.MSG_HEADERS.ORIGIN)&&r&&t.append(Kt.MSG_HEADERS.ORIGIN,r),t}a(hL,"addNatsMsgHeader");function da(e){e=e.toLowerCase();let t=pu.join(xt.get(Ie.CONFIG_PARAMS.ROOTPATH),hj);if(e===Ie.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase())return co(DS)&&(DS={port:hu.getConfigFromFile(Ie.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),server_name:hu.getConfigFromFile(Ie.CONFIG_PARAMS.CLUSTERING_NODENAME)+Kt.SERVER_SUFFIX.HUB,config_file:Kt.NATS_CONFIG_FILES.HUB_SERVER,pid_file_path:pu.join(t,Kt.PID_FILES.HUB),hdb_nats_path:t}),DS;if(e===Ie.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())return co(CS)&&(CS={port:hu.getConfigFromFile(Ie.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),server_name:hu.getConfigFromFile(Ie.CONFIG_PARAMS.CLUSTERING_NODENAME)+Kt.SERVER_SUFFIX.LEAF,config_file:Kt.NATS_CONFIG_FILES.LEAF_SERVER,domain:hu.getConfigFromFile(Ie.CONFIG_PARAMS.CLUSTERING_NODENAME)+Kt.SERVER_SUFFIX.LEAF,pid_file_path:pu.join(t,Kt.PID_FILES.LEAF),hdb_nats_path:t}),CS;Bn.error(`Unable to get Nats server config. Unrecognized process: ${e}`)}a(da,"getServerConfig");async function mL(e,t,r,n){try{await e.consumers.add(t,{ack_policy:PS.Explicit,durable_name:r,deliver_policy:US.StartTime,opt_start_time:n})}catch(s){if(s.message!=="consumer already exists")throw s}}a(mL,"createConsumer");async function Nj(e,t,r){await e.consumers.delete(t,r)}a(Nj,"removeConsumer");function Ij(e){return e.split(".")[1]}a(Ij,"extractServerName");async function wj(e,t,r=6e4,n=vS()){if(!Ld.isObject(t))throw new Error("data param must be an object");let s=cL.encode(t),{connection:i}=await is(),o={timeout:r};n&&(o.reply=n,o.noMux=!0);let c=await i.request(e,s,o);return MS(c.data)}a(wj,"request");function HS(e){return new Promise(async(t,r)=>{let n=ej(LS,["--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(HS,"reloadNATS");async function Cj(){let{pid_file_path:e}=da(Ie.PROCESS_DESCRIPTORS.CLUSTERING_HUB);await HS(e)}a(Cj,"reloadNATSHub");async function Dj(){let{pid_file_path:e}=da(Ie.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);await HS(e)}a(Dj,"reloadNATSLeaf");function Lj(e,t,r){let n;switch(e.code){case sL.NoResponders:n=`Unable to ${t}, node '${r}' is not listening.`;break;case sL.Timeout:n=`Unable to ${t}, node '${r}' is listening but did not respond.`;break;default:n=e.message;break}return n}a(Lj,"requestErrorHandler");async function Mj(e,t){let r=t+Kt.SERVER_SUFFIX.LEAF,{connection:n}=await is(),{jsm:s}=await qj(r),{schema:i,table:o}=e,c=Md.createNatsTableStreamName(i,o),u=e.start_time?e.start_time:new Date(Date.now()).toISOString();await pL(async()=>{if(e.subscribe===!0)await mL(s,c,n.info.server_name,u);else try{await Nj(s,c,n.info.server_name)}catch(_){Bn.trace(_)}})}a(Mj,"updateRemoteConsumer");async function Pj(e,t,r,n){let s=Md.createNatsTableStreamName(e,t),i=r+Kt.SERVER_SUFFIX.LEAF,o={type:Ie.ITC_EVENT_TYPES.NATS_CONSUMER_UPDATE,status:n,stream_name:s,node_domain_name:i};if(!aL&&sj()<xt.get(Ie.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXINGESTTHREADS)){let{updateConsumer:c}=wS();await c(o)}await rj(o),n==="stop"&&await Ld.async_set_timeout(1e3)}a(Pj,"updateConsumerIterator");function pL(e){return tj.writeTransaction(Ie.SYSTEM_SCHEMA_NAME,Ie.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,e)}a(pL,"exclusiveLock");async function SL(e,t){let r=Md.createNatsTableStreamName(e,t),n=await Pd(),s=xj(e,t,n);await xS(r,[s])}a(SL,"createLocalTableStream");async function Uj(e){for(let t=0,r=e.length;t<r;t++){let n=e[t].schema,s=e[t].table;await SL(n,s)}}a(Uj,"createTableStreams");async function TL(e,t,r=void 0){if(xt.get(Ie.CONFIG_PARAMS.CLUSTERING_ENABLED))try{let n=Md.createNatsTableStreamName(e,t),{domain:s}=da(Ie.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);await(await(await Su()).jetstreamManager({domain:s,timeout:24e4})).streams.purge(n,r)}catch(n){if(n.message==="stream not found")Bn.warn(n);else throw n}}a(TL,"purgeTableStream");async function vj(e,t){if(xt.get(Ie.CONFIG_PARAMS.CLUSTERING_ENABLED))for(let r=0,n=t.length;r<n;r++)await TL(e,t[r])}a(vj,"purgeSchemaTableStreams");async function Bj(e){return(await Tu()).streams.info(e)}a(Bj,"getStreamInfo");function xj(e,t,r){return`${Kt.SUBJECT_PREFIXES.TXN}.${e}${t?"."+t:""}.${r}`}a(xj,"createSubjectName");async function Pd(){if(mu)return mu;if(mu=(await Tu())?.nc?.info?.server_name,mu===void 0)throw new Error("Unable to get jetstream manager server name");return mu}a(Pd,"getJsmServerName");async function Hj(){let e=await Tu(),t=await Pd(),r=await EL();for(let n of r){let s=n.config,i=s.subjects[0];if(!i)continue;let o=Gj(n),c=i.split(".");if(c[c.length-1]===t&&!o||s.name==="__HARPERDB_WORK_QUEUE__")continue;let _=i.split(".");_[_.length-1]=t;let l=_.join(".");Bn.trace(`Updating stream subject name from: ${i} to: ${l}`),s.subjects[0]=l,await e.streams.update(s.name,s)}}a(Hj,"updateLocalStreams");function Gj(e){let{config:t}=e,r=!1,n=xt.get(Ie.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE);n=n===null?0:n*1e9;let s=xt.get(Ie.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES);s=s===null?-1:s;let i=xt.get(Ie.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(Gj,"updateStreamLimits");async function qj(e){let t,r;try{t=await Tr.jetstream({domain:e}),r=await Tr.jetstreamManager({domain:e,checkAPI:!1})}catch(n){throw Bn.error("Unable to connect to:",e),n}return{js:t,jsm:r}}a(qj,"connectToRemoteJS")});var gu=g(($fe,bL)=>{"use strict";var fa=w_(),Ea=wD(),Fj=$(),kj=require("uuid").v4,Vfe=require("clone"),vd=ys(),ha=P(),Vj=require("util"),di=Cn(),{handleHDBError:gr,hdb_errors:$j}=ne(),{HDB_ERROR_MSGS:Ud,HTTP_STATUS_CODES:Rr}=$j,{SchemaEventMsg:Bd}=Mn(),RL=ut(),{getDatabases:Yj}=(Ae(),ie(ke)),{transformReq:ma}=z();bL.exports={createSchema:Kj,createSchemaStructure:AL,createTable:Wj,createTableStructure:OL,createAttribute:Xj,dropSchema:Qj,dropTable:zj,dropAttribute:Jj,getBackup:Zj};async function Kj(e){let t=await AL(e);return vd.signalSchemaChange(new Bd(process.pid,e.operation,e.schema)),t}a(Kj,"createSchema");async function AL(e){let t=fa.schema_object(e);if(t)throw gr(t,t.message,Rr.BAD_REQUEST,void 0,void 0,!0);if(ma(e),!await Ea.checkSchemaExists(e.schema))throw gr(new Error,Ud.SCHEMA_EXISTS_ERR(e.schema),Rr.BAD_REQUEST,ha.LOG_LEVELS.ERROR,Ud.SCHEMA_EXISTS_ERR(e.schema),!0);return await di.createSchema(e),`database '${e.schema}' successfully created`}a(AL,"createSchemaStructure");async function Wj(e){return ma(e),e.hash_attribute=e.primary_key??e.hash_attribute,await OL(e)}a(Wj,"createTable");async function OL(e){let t=fa.create_table_object(e);if(t)throw gr(t,t.message,Rr.BAD_REQUEST,void 0,void 0,!0);if(fa.validateTableResidence(e.residence),!await Ea.checkSchemaTableExists(e.schema,e.table))throw gr(new Error,Ud.TABLE_EXISTS_ERR(e.schema,e.table),Rr.BAD_REQUEST,ha.LOG_LEVELS.ERROR,Ud.TABLE_EXISTS_ERR(e.schema,e.table),!0);let n={name:e.table,schema:e.schema,id:kj(),hash_attribute:e.hash_attribute};try{if(e.residence)if(global.clustering_on)n.residence=e.residence,await di.createTable(n,e);else throw gr(new Error,"Clustering does not appear to be enabled. Cannot insert table with property 'residence'.",Rr.BAD_REQUEST);else await di.createTable(n,e);return`table '${e.schema}.${e.table}' successfully created.`}catch(s){throw s}}a(OL,"createTableStructure");async function Qj(e){let t=!e.schema&&!e.database?new Error("database is required"):void 0,r=fa.schema_object(e),n=t??r;if(n)throw gr(n,n.message,Rr.BAD_REQUEST,void 0,void 0,!0);ma(e);let s=await Ea.checkSchemaExists(e.schema);if(s)throw gr(new Error,s,Rr.NOT_FOUND,ha.LOG_LEVELS.ERROR,s,!0);let i=await Ea.schema_describe.describeSchema({schema:e.schema}),o=Object.keys(global.hdb_schema[e.schema]);return await di.dropSchema(e),vd.signalSchemaChange(new Bd(process.pid,e.operation,e.schema)),await RL.purgeSchemaTableStreams(e.schema,o),`successfully deleted '${e.schema}'`}a(Qj,"dropSchema");async function zj(e){let t=fa.table_object(e);if(t)throw gr(t,t.message,Rr.BAD_REQUEST,void 0,void 0,!0);ma(e);let r=await Ea.checkSchemaTableExists(e.schema,e.table);if(r)throw gr(new Error,r,Rr.NOT_FOUND,ha.LOG_LEVELS.ERROR,r,!0);return await di.dropTable(e),await RL.purgeTableStream(e.schema,e.table),`successfully deleted table '${e.schema}.${e.table}'`}a(zj,"dropTable");async function Jj(e){let t=fa.attribute_object(e);if(t)throw gr(t,t.message,Rr.BAD_REQUEST,void 0,void 0,!0);ma(e);let r=await Ea.checkSchemaTableExists(e.schema,e.table);if(r)throw gr(new Error,r,Rr.NOT_FOUND,ha.LOG_LEVELS.ERROR,r,!0);if(e.attribute===global.hdb_schema[e.schema][e.table].hash_attribute)throw gr(new Error,"You cannot drop a hash attribute",Rr.BAD_REQUEST,void 0,void 0,!0);if(ha.TIME_STAMP_NAMES.indexOf(e.attribute)>=0)throw gr(new Error,`cannot drop internal timestamp attribute: ${e.attribute}`,Rr.BAD_REQUEST,void 0,void 0,!0);try{return await di.dropAttribute(e),jj(e),vd.signalSchemaChange(new Bd(process.pid,e.operation,e.schema,e.table,e.attribute)),`successfully deleted attribute '${e.attribute}'`}catch(n){throw Fj.error(`Got an error deleting attribute ${Vj.inspect(e)}.`),n}}a(Jj,"dropAttribute");function jj(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(jj,"dropAttributeFromGlobal");async function Xj(e){ma(e);let t=Yj()[e.schema][e.table].attributes;for(let{name:r}of t)if(r===e.attribute)throw gr(new Error,`attribute '${e.attribute}' already exists in ${e.schema}.${e.table}`,Rr.BAD_REQUEST,void 0,void 0,!0);return await di.createAttribute(e),vd.signalSchemaChange(new Bd(process.pid,e.operation,e.schema,e.table,e.attribute)),`attribute '${e.schema}.${e.table}.${e.attribute}' successfully created.`}a(Xj,"createAttribute");function Zj(e){return di.getBackup(e)}a(Zj,"getBackup")});var NL=g((Kfe,yL)=>{"use strict";var{OPERATIONS_ENUM:eX}=P(),GS=class{static{a(this,"ReadAuditLogObject")}constructor(t,r,n=void 0,s=void 0){this.operation=eX.READ_AUDIT_LOG,this.schema=t,this.table=r,this.search_type=n,this.search_values=s}};yL.exports=GS});var qS=g((zfe,LL)=>{"use strict";var tX=Cn(),Qfe=NL(),xd=z(),Hd=P(),rX=Z(),{handleHDBError:IL,hdb_errors:nX}=ne(),{HDB_ERROR_MSGS:wL,HTTP_STATUS_CODES:CL}=nX,sX=Object.values(Hd.READ_AUDIT_LOG_SEARCH_TYPES_ENUM),DL="To use this operation audit log must be enabled in harperdb-config.yaml";LL.exports=iX;async function iX(e){if(xd.isEmpty(e.schema))throw new Error(wL.SCHEMA_REQUIRED_ERR);if(xd.isEmpty(e.table))throw new Error(wL.TABLE_REQUIRED_ERR);if(!rX.get(Hd.CONFIG_PARAMS.LOGGING_AUDITLOG))throw IL(new Error,DL,CL.BAD_REQUEST,Hd.LOG_LEVELS.ERROR,DL,!0);let t=xd.checkSchemaTableExist(e.schema,e.table);if(t)throw IL(new Error,t,CL.NOT_FOUND,Hd.LOG_LEVELS.ERROR,t,!0);if(!xd.isEmpty(e.search_type)&&sX.indexOf(e.search_type)<0)throw new Error(`Invalid search_type '${e.search_type}'`);return await tX.readAuditLog(e)}a(iX,"readAuditLog")});var PL=g((jfe,ML)=>{"use strict";var{OPERATIONS_ENUM:oX}=P(),FS=class{static{a(this,"GetBackupObject")}constructor(t,r,n=void 0,s=void 0){this.operation=oX.GET_BACKUP,this.schema=t,this.table=r}};ML.exports=FS});var BL=g((tEe,vL)=>{"use strict";var aX=Cn(),Zfe=PL(),kS=z(),cX=P(),eEe=Z(),{handleHDBError:uX,hdb_errors:lX}=ne(),{HDB_ERROR_MSGS:UL,HTTP_STATUS_CODES:_X}=lX;vL.exports=dX;async function dX(e){if(kS.isEmpty(e.schema))throw new Error(UL.SCHEMA_REQUIRED_ERR);if(kS.isEmpty(e.table))throw new Error(UL.TABLE_REQUIRED_ERR);let t=kS.checkSchemaTableExist(e.schema,e.table);if(t)throw uX(new Error,t,_X.NOT_FOUND,cX.LOG_LEVELS.ERROR,t,!0);return await aX.getBackup(read_audit_log_object)}a(dX,"getBackup")});var kL=g((nEe,FL)=>{var fi=require("validate.js"),HL=Xe(),pa=P(),{handleHDBError:fX,hdb_errors:EX}=ne(),{HDB_ERROR_MSGS:mt,HTTP_STATUS_CODES:hX}=EX,VS=a(()=>({role:{presence:!0,format:"[\\w\\-\\_]+"},id:{presence:!0,format:"[\\w\\-\\_]+"},permission:{presence:!0}}),"constraintsTemplate"),mX={STRUCTURE_USER:"structure_user"},xL=Object.values(pa.ROLE_TYPES_ENUM),pX="attribute_permissions",SX="attribute_name",{PERMS_CRUD_ENUM:Sa}=pa,TX=[pX,...Object.values(Sa)],GL=[Sa.READ,Sa.INSERT,Sa.UPDATE],gX=[SX,...GL];function RX(e){let t=VS();return t.role.presence=!0,t.id.presence=!1,t.permission.presence=!0,qL(e,t)}a(RX,"addRoleValidation");function AX(e){let t=VS();return t.role.presence=!1,t.id.presence=!0,t.permission.presence=!0,qL(e,t)}a(AX,"alterRoleValidation");function OX(e){let t=VS();return t.role.presence=!1,t.id.presence=!0,t.permission.presence=!1,HL.validateObject(e,t)}a(OX,"dropRoleValidation");var bX=["operation","role","id","permission","hdb_user","hdb_auth_header"];function qL(e,t){let r={main_permissions:[],schema_permissions:{}},n=Object.keys(e),s=[];for(let o=0,c=n.length;o<c;o++)bX.includes(n[o])||s.push(n[o]);s.length>0&&At(mt.INVALID_ROLE_JSON_KEYS(s),r);let i=HL.validateObject(e,t);if(i&&i.message.split(",").forEach(o=>{At(o,r)}),e.permission){let o=yX(e);o&&At(o,r),xL.forEach(c=>{e.permission[c]&&!fi.isBoolean(e.permission[c])&&At(mt.SU_CU_ROLE_BOOLEAN_ERROR(c),r)})}for(let o in e.permission)if(xL.indexOf(o)<0){if(o===mX.STRUCTURE_USER){let u=e.permission[o];if(typeof u=="boolean")continue;if(Array.isArray(u)){for(let _=0,l=u.length;_<l;_++){let d=u[_];global.hdb_schema[d]||At(mt.SCHEMA_NOT_FOUND(d),r)}continue}At(mt.STRUCTURE_USER_ROLE_TYPE_ERROR(o),r);continue}let c=e.permission[o];if(!o||!global.hdb_schema[o]){At(mt.SCHEMA_NOT_FOUND(o),r);continue}if(c.tables)for(let u in c.tables){let _=c.tables[u];if(!u||!global.hdb_schema[o][u]){At(mt.TABLE_NOT_FOUND(o,u),r);continue}if(Object.keys(_).forEach(l=>{TX.includes(l)||At(mt.INVALID_PERM_KEY(l),r,o,u)}),Object.values(Sa).forEach(l=>{fi.isDefined(_[l])?fi.isBoolean(_[l])||At(mt.TABLE_PERM_NOT_BOOLEAN(l),r,o,u):At(mt.TABLE_PERM_MISSING(l),r,o,u)}),fi.isDefined(_.attribute_permissions)){if(!fi.isArray(_.attribute_permissions)){At(mt.ATTR_PERMS_NOT_ARRAY,r,o,u);continue}}else{At(mt.ATTR_PERMS_ARRAY_MISSING,r,o,u);continue}if(_.attribute_permissions){let l=global.hdb_schema[o][u].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=>{!gX.includes(p)&&p!==Sa.DELETE&&At(mt.INVALID_ATTR_PERM_KEY(p),r,o,u)}),!fi.isDefined(f.attribute_name)){At(mt.ATTR_PERM_MISSING_NAME,r,o,u);continue}let h=f.attribute_name;if(!l.includes(h)){At(mt.INVALID_ATTRIBUTE_IN_PERMS(h),r,o,u);continue}GL.forEach(p=>{fi.isDefined(f[p])?fi.isBoolean(f[p])||At(mt.ATTR_PERM_NOT_BOOLEAN(p,h),r,o,u):At(mt.ATTR_PERM_MISSING(p,h),r,o,u)}),!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}.${u}`;At(mt.MISMATCHED_TABLE_ATTR_PERMS(E),r,o,u)}}}}return NX(r)}a(qL,"customValidate");FL.exports={addRoleValidation:RX,alterRoleValidation:AX,dropRoleValidation:OX};function yX(e){let{operation:t,permission:r}=e;if(t===pa.OPERATIONS_ENUM.ADD_ROLE||t===pa.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 mt.SU_CU_ROLE_COMBINED_ERROR;{let o=r.super_user?pa.ROLE_TYPES_ENUM.SUPER_USER:pa.ROLE_TYPES_ENUM.CLUSTER_USER;return mt.SU_CU_ROLE_NO_PERMS_ALLOWED(o)}}}return null}a(yX,"validateNoSUPerms");function NX(e){let{main_permissions:t,schema_permissions:r}=e;if(t.length>0||Object.keys(r).length>0){let n={error:mt.ROLE_PERMS_ERROR,...e};return fX(new Error,n,hX.BAD_REQUEST)}else return null}a(NX,"generateRolePermResponse");function At(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(At,"addPermError")});var zS=g((iEe,KL)=>{"use strict";var VL=qr(),$L=Gr(),IX=oi(),YS=kL(),KS=ys(),wX=require("uuid").v4,CX=require("util"),Gd=P(),DX=z(),WS=$L.searchByValue,LX=$L.searchByHash,MX=CX.promisify(IX.delete),PX=ts(),UX=ia(),{hdb_errors:vX,handleHDBError:uo}=ne(),{HDB_ERROR_MSGS:YL,HTTP_STATUS_CODES:Ru}=vX,{UserEventMsg:QS}=Mn();KL.exports={addRole:BX,alterRole:xX,dropRole:HX,listRoles:GX};function $S(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($S,"scrubRoleDetails");async function BX(e){let t=YS.addRoleValidation(e);if(t)throw t;e=$S(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 WS(r)||[])}catch(i){throw uo(i)}if(n&&n.length>0)throw uo(new Error,YL.ROLE_ALREADY_EXISTS(e.role),Ru.CONFLICT,void 0,void 0,!0);e.id||(e.id=wX());let s={operation:"insert",schema:"system",table:"hdb_role",hash_attribute:"id",records:[e]};return await VL.insert(s),KS.signalUserChange(new QS(process.pid)),e=$S(e),e}a(BX,"addRole");async function xX(e){let t=YS.alterRoleValidation(e);if(t)throw t;e=$S(e);let r={operation:"update",schema:"system",table:"hdb_role",records:[e]},n;try{n=await VL.update(r)}catch(s){throw uo(s)}if(n&&n?.message==="updated 0 of 1 records")throw uo(new Error,"Invalid role id",Ru.BAD_REQUEST,void 0,void 0,!0);return await KS.signalUserChange(new QS(process.pid)),e}a(xX,"alterRole");async function HX(e){let t=YS.dropRoleValidation(e);if(t)throw uo(new Error,t,Ru.BAD_REQUEST,void 0,void 0,!0);let r=new UX(Gd.SYSTEM_SCHEMA_NAME,Gd.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME,[e.id],["role"]),n=Array.from(await LX(r));if(n.length===0)throw uo(new Error,YL.ROLE_NOT_FOUND,Ru.NOT_FOUND,void 0,void 0,!0);let s=new PX(Gd.SYSTEM_SCHEMA_NAME,Gd.SYSTEM_TABLE_NAMES.USER_TABLE_NAME,"role",e.id,void 0,["username","active"]),i=Array.from(await WS(s)),o=!1;if(DX.isEmptyOrZeroLength(i)===!1){for(let u=0;u<i.length;u++)if(i[u].active===!0){o=!0;break}}if(o===!0)throw uo(new Error,`Cannot drop role ${n[0].role} as it has active user(s) tied to this role`,Ru.CONFLICT,void 0,void 0,!0);let c={table:"hdb_role",schema:"system",hash_values:[e.id]};return await MX(c),KS.signalUserChange(new QS(process.pid)),`${n[0].role} successfully deleted`}a(HX,"dropRole");async function GX(){return WS({table:"hdb_role",schema:"system",hash_attribute:"id",search_attribute:"id",search_value:"*",get_attributes:["*"]})}a(GX,"listRoles")});var JL=g((aEe,zL)=>{"use strict";var qX=Z(),Ei=require("joi"),FX=Xe(),WL=require("moment"),kX=require("fs-extra"),JS=require("path"),VX=require("lodash"),Au=P(),{LOG_LEVELS:lo}=P(),$X="YYYY-MM-DD hh:mm:ss",YX=JS.resolve(__dirname,"../logs");zL.exports=function(e){return FX.validateBySchema(e,KX)};var KX=Ei.object({from:Ei.custom(QL),until:Ei.custom(QL),level:Ei.valid(lo.NOTIFY,lo.FATAL,lo.ERROR,lo.WARN,lo.INFO,lo.DEBUG,lo.TRACE),order:Ei.valid("asc","desc"),limit:Ei.number().min(1),start:Ei.number().min(0),log_name:Ei.custom(WX)});function QL(e,t){if(WL(e,WL.ISO_8601).format($X)==="Invalid date")return t.message(`'${t.state.path[0]}' date '${e}' is invalid.`)}a(QL,"validateDatetime");function WX(e,t){if(VX.invert(Au.LOG_NAMES)[e]===void 0)return t.message(`'log_name' '${e}' is invalid.`);let n=qX.get(Au.HDB_SETTINGS_NAMES.LOG_PATH_KEY),s=e===void 0?Au.LOG_NAMES.HDB:e,i=s===Au.LOG_NAMES.INSTALL?JS.join(YX,Au.LOG_NAMES.INSTALL):JS.join(n,s);return kX.existsSync(i)?null:t.message(`'log_name' '${e}' does not exist.`)}a(WX,"validateReadLogPath")});var XS=g((uEe,XL)=>{"use strict";var qd=P(),QX=$(),zX=Z(),JX=JL(),jS=require("path"),jL=require("fs-extra"),{once:jX}=require("events"),{handleHDBError:XX,hdb_errors:ZX}=ne(),{PACKAGE_ROOT:eZ}=P(),tZ=jS.join(eZ,"logs"),rZ=1e3,nZ=200;XL.exports=sZ;async function sZ(e){let t=JX(e);if(t)throw XX(t,t.message,ZX.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0);let r=zX.get(qd.HDB_SETTINGS_NAMES.LOG_PATH_KEY),n=e.log_name===void 0?qd.LOG_NAMES.HDB:e.log_name,s=n===qd.LOG_NAMES.INSTALL?jS.join(tZ,qd.LOG_NAMES.INSTALL):jS.join(r,n),i=e.level!==void 0,o=i?e.level:void 0,c=e.from!==void 0,u=c?new Date(e.from):void 0,_=e.until!==void 0,l=_?new Date(e.until):void 0,d=e.limit===void 0?rZ: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"&&!u&&!l&&(p=Math.max(jL.statSync(s).size-(h+5)*nZ,0));let S=jL.createReadStream(s,{start:p});S.on("error",v=>{QX.error(v)});let T=0,R=[],b="",C;S.on("data",v=>{let F=/(?:^|\n)(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:[\d\.]+Z) \[(.+?)]: /g;v=b+v;let M=0,Q;for(;(Q=F.exec(v))&&!S.destroyed;){C&&(C.message=v.slice(M,Q.index),x(C));let[J,j,ae]=Q,ce=ae.split("] ["),ge=ce[0],Ge=ce[1];ce.splice(0,2),C={timestamp:j,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(),x(C))}),S.resume();function x(v){let F,M,Q;switch(!0){case(i&&c&&_):F=new Date(v.timestamp),M=new Date(u),Q=new Date(l),v.level===o&&F>=M&&F<=Q&&T<f?T++:v.level===o&&F>=M&&F<=Q&&(hi(v,E,R),T++,T===h&&S.destroy());break;case(i&&c):F=new Date(v.timestamp),M=new Date(u),v.level===o&&F>=M&&T<f?T++:v.level===o&&F>=M&&(hi(v,E,R),T++,T===h&&S.destroy());break;case(i&&_):F=new Date(v.timestamp),Q=new Date(l),v.level===o&&F<=Q&&T<f?T++:v.level===o&&F<=Q&&(hi(v,E,R),T++,T===h&&S.destroy());break;case(c&&_):F=new Date(v.timestamp),M=new Date(u),Q=new Date(l),F>=M&&F<=Q&&T<f?T++:F>=M&&F<=Q&&(hi(v,E,R),T++,T===h&&S.destroy());break;case i:v.level===o&&T<f?T++:v.level===o&&(hi(v,E,R),T++,T===h&&S.destroy());break;case c:F=new Date(v.timestamp),M=new Date(u),F>=M&&T<f?T++:F>=M&&T>=f&&(hi(v,E,R),T++,T===h&&S.destroy());break;case _:F=new Date(v.timestamp),Q=new Date(l),F<=Q&&T<f?T++:F<=Q&&T>=f&&(hi(v,E,R),T++,T===h&&S.destroy());break;default:T<f?T++:(hi(v,E,R),T++,T===h&&S.destroy())}}return a(x,"onLogMessage"),await jX(S,"close"),R}a(sZ,"readLog");function hi(e,t,r){t==="desc"?iZ(e,r):t==="asc"?oZ(e,r):r.push(e)}a(hi,"pushLineToResult");function iZ(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(iZ,"insertDescending");function oZ(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(oZ,"insertAscending")});var Fd=g((EEe,rM)=>{"use strict";var ZS=require("joi"),{string:Ou,boolean:ZL,date:aZ}=ZS.types(),cZ=Xe(),{validateSchemaExists:_Ee,validateTableExists:dEe,validateSchemaName:fEe}=Jn(),uZ=P(),lZ=Ve(),eM=Z();eM.initSync();var _Z=Ou.invalid(eM.get(uZ.CONFIG_PARAMS.CLUSTERING_NODENAME)).pattern(lZ.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(),tM={operation:Ou.valid("add_node","update_node","set_node_replication"),node_name:_Z,subscriptions:ZS.array().items({table:Ou.optional(),schema:Ou.optional(),database:Ou.optional(),subscribe:ZL.required(),publish:ZL.required().custom(fZ),start_time:aZ.iso()}).min(1).required()};function dZ(e){return cZ.validateBySchema(e,ZS.object(tM))}a(dZ,"addUpdateNodeValidator");function fZ(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(fZ,"checkForFalsy");rM.exports={addUpdateNodeValidator:dZ,validation_schema:tM}});var sM=g((mEe,nM)=>{var EZ=Xe(),hZ={user:{presence:!0},schema:{presence:!0},table:{presence:!0},operation:{presence:!0}};nM.exports=function(e){return EZ.validateObject(e,hZ)}});var kd=g((pEe,iM)=>{"use strict";var mZ=P().OPERATIONS_ENUM,eT=class{static{a(this,"UpdateObject")}constructor(t,r,n,s=void 0){this.operation=mZ.UPDATE,this.schema=t,this.table=r,this.records=n,this.__origin=s}};iM.exports=eT});var aM=g((TEe,oM)=>{"use strict";var pZ={OPERATION:"operation",REFRESH:"refresh"},tT=class{static{a(this,"JWTTokens")}constructor(t,r){this.operation_token=t,this.refresh_token=r}},rT=class{static{a(this,"JWTRSAKeys")}constructor(t,r,n){this.public_key=t,this.private_key=r,this.passphrase=n}};oM.exports={JWTTokens:tT,TOKEN_TYPE_ENUM:pZ,JWTRSAKeys:rT}});var Nu=g((REe,_M)=>{"use strict";var yu=require("jsonwebtoken"),nT=require("fs-extra"),sT=z(),_n=P(),{handleHDBError:Ar,hdb_errors:SZ}=ne(),{HTTP_STATUS_CODES:Or,AUTHENTICATION_ERROR_MSGS:br}=SZ,bu=$(),cM=$_(),aT=ln(),TZ=qr().update,gZ=kd(),RZ=ys(),{UserEventMsg:AZ}=Mn(),mi=Z();mi.initSync();var iT=require("path"),{JWTTokens:OZ,JWTRSAKeys:bZ,TOKEN_TYPE_ENUM:Vd}=aM(),yZ=mi.get(_n.HDB_SETTINGS_NAMES.OPERATION_TOKEN_TIMEOUT_KEY)?mi.get(_n.HDB_SETTINGS_NAMES.OPERATION_TOKEN_TIMEOUT_KEY):"1d",NZ=mi.get(_n.HDB_SETTINGS_NAMES.REFRESH_TOKEN_TIMEOUT_KEY)?mi.get(_n.HDB_SETTINGS_NAMES.REFRESH_TOKEN_TIMEOUT_KEY):"30d",$d="RS256",oT;_M.exports={createTokens:IZ,validateOperationToken:CZ,refreshOperationToken:wZ,validateRefreshToken:lM};async function IZ(e){if(sT.isEmpty(e)||typeof e!="object")throw Ar(new Error,br.INVALID_AUTH_OBJECT,Or.BAD_REQUEST,void 0,void 0,!0);if(sT.isEmpty(e.username))throw Ar(new Error,br.USERNAME_REQUIRED,Or.BAD_REQUEST,void 0,void 0,!0);if(sT.isEmpty(e.password))throw Ar(new Error,br.PASSWORD_REQUIRED,Or.BAD_REQUEST,void 0,void 0,!0);let t;try{if(t=await aT.findAndValidateUser(e.username,e.password),!t)throw Ar(new Error,br.INVALID_CREDENTIALS,Or.UNAUTHORIZED,void 0,void 0,!0)}catch(E){throw bu.error(E),Ar(new Error,br.INVALID_CREDENTIALS,Or.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 uM(i,r.private_key,r.passphrase),c=await yu.sign(i,{key:r.private_key,passphrase:r.passphrase},{expiresIn:NZ,algorithm:$d,subject:Vd.REFRESH}),u=cM.hash(c),_=new gZ(_n.SYSTEM_SCHEMA_NAME,_n.SYSTEM_TABLE_NAMES.USER_TABLE_NAME,[{username:e.username,refresh_token:u}]),l,d;try{l=await TZ(_)}catch(E){bu.error(E),d=E}if(d!==void 0||l.skipped_hashes.length>0)throw Ar(new Error,br.REFRESH_TOKEN_SAVE_FAILED,Or.INTERNAL_SERVER_ERROR);return RZ.signalUserChange(new AZ(process.pid)),new OZ(o,c)}a(IZ,"createTokens");async function uM(e,t,r){return await yu.sign(e,{key:t,passphrase:r},{expiresIn:yZ,algorithm:$d,subject:Vd.OPERATION})}a(uM,"signOperationToken");async function Yd(){if(oT===void 0)try{let e=iT.join(mi.getHdbBasePath(),_n.LICENSE_KEY_DIR_NAME,_n.JWT_ENUM.JWT_PASSPHRASE_NAME),t=iT.join(mi.getHdbBasePath(),_n.LICENSE_KEY_DIR_NAME,_n.JWT_ENUM.JWT_PRIVATE_KEY_NAME),r=iT.join(mi.getHdbBasePath(),_n.LICENSE_KEY_DIR_NAME,_n.JWT_ENUM.JWT_PUBLIC_KEY_NAME),n=(await nT.readFile(e)).toString(),s=(await nT.readFile(t)).toString(),i=(await nT.readFile(r)).toString();oT=new bZ(i,s,n)}catch(e){throw bu.error(e),Ar(new Error,br.NO_ENCRYPTION_KEYS,Or.INTERNAL_SERVER_ERROR)}return oT}a(Yd,"getJWTRSAKeys");async function wZ(e){if(!e)throw Ar(new Error,br.INVALID_BODY,Or.BAD_REQUEST,void 0,void 0,!0);if(!e.refresh_token)throw Ar(new Error,br.REFRESH_TOKEN_REQUIRED,Or.BAD_REQUEST,void 0,void 0,!0);await lM(e.refresh_token);let t=await Yd(),r=await yu.decode(e.refresh_token);return{operation_token:await uM({username:r.username,super_user:r.super_user,cluster_user:r.cluster_user},t.private_key,t.passphrase)}}a(wZ,"refreshOperationToken");async function CZ(e){try{let t=await Yd(),r=await yu.verify(e,t.public_key,{algorithms:$d,subject:Vd.OPERATION});return await aT.findAndValidateUser(r.username,void 0,!1)}catch(t){throw bu.warn(t),t.name&&t.name==="TokenExpiredError"?Ar(new Error,br.TOKEN_EXPIRED,Or.FORBIDDEN):Ar(new Error,br.INVALID_TOKEN,Or.UNAUTHORIZED)}}a(CZ,"validateOperationToken");async function lM(e){let t;try{let r=await Yd(),n=await yu.verify(e,r.public_key,{algorithms:$d,subject:Vd.REFRESH});t=await aT.findAndValidateUser(n.username,void 0,!1)}catch(r){throw bu.warn(r),r.name&&r.name==="TokenExpiredError"?Ar(new Error,br.TOKEN_EXPIRED,Or.FORBIDDEN):Ar(new Error,br.INVALID_TOKEN,Or.UNAUTHORIZED)}if(!cM.validate(t.refresh_token,e))throw Ar(new Error,br.INVALID_TOKEN,Or.UNAUTHORIZED);return t}a(lM,"validateRefreshToken")});var cT=g((bEe,EM)=>{"use strict";var DZ=sM(),Ta=require("passport"),LZ=require("passport-local").Strategy,MZ=require("passport-http").BasicStrategy,PZ=require("util"),UZ=ln(),fM=PZ.callbackify(UZ.findAndValidateUser),OEe=Ur(),vZ=P(),dM=Nu();Ta.use(new LZ(function(e,t,r){fM(e,t,r)}));Ta.use(new MZ(function(e,t,r){fM(e,t,r)}));Ta.serializeUser(function(e,t){t(null,e)});Ta.deserializeUser(function(e,t){t(null,e)});function BZ(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":Ta.authenticate("basic",{session:!1},(o,c)=>{i(o,c)})(e,t,r);break;case"Bearer":e.body?.operation&&e.body.operation===vZ.OPERATIONS_ENUM.REFRESH_OPERATION_TOKEN?dM.validateRefreshToken(s).then(o=>{e.body.refresh_token=s,r(null,o)}).catch(o=>{r(o)}):dM.validateOperationToken(s).then(o=>{r(null,o)}).catch(o=>{r(o)});break;default:Ta.authenticate("local",{session:!1},function(o,c){i(o,c)})(e,t,r);break}}a(BZ,"authorize");function xZ(e,t){let r=DZ(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(xZ,"checkPermissions");EM.exports={authorize:BZ,checkPermissions:xZ}});var pi=g((NEe,hM)=>{"use strict";var uT=class{static{a(this,"Node")}constructor(t,r,n){this.name=t,this.subscriptions=r,this.system_info=n}},lT=class{static{a(this,"NodeSubscription")}constructor(t,r,n,s){this.schema=t,this.table=r,this.publish=n,this.subscribe=s}};hM.exports={Node:uT,NodeSubscription:lT}});var pM=g((wEe,mM)=>{"use strict";var HZ=P().OPERATIONS_ENUM,_T=class{static{a(this,"UpsertObject")}constructor(t,r,n,s=void 0){this.operation=HZ.UPSERT,this.schema=t,this.table=r,this.records=n,this.__origin=s}};mM.exports=_T});var Iu=g((DEe,SM)=>{"use strict";var dT=class{static{a(this,"RemotePayloadObject")}constructor(t,r,n,s){this.operation=t,this.node_name=r,this.subscriptions=n,this.system_info=s}},fT=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)}};SM.exports={RemotePayloadObject:dT,RemotePayloadSubscription:fT}});var gM=g((MEe,TM)=>{"use strict";var ET=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}};TM.exports=ET});var OM=g((xEe,AM)=>{"use strict";var GZ=gM(),UEe=ft(),RM=Qe(),qZ=$(),{getSchemaPath:vEe,getTransactionAuditStorePath:BEe}=je(),{getDatabases:FZ}=(Ae(),ie(ke));AM.exports=kZ;async function kZ(e){let t=new GZ;try{let r=FZ()[e.schema]?.[e.name],n=r.primaryStore.getStats(),s=r.auditStore?.getStats(),i=await RM.environmentDataSize(schema_path,e.name),o=await RM.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){qZ.warn(`unable to stat table dbi due to ${r}`)}return t}a(kZ,"lmdbGetTableSize")});var yM=g((GEe,bM)=>{"use strict";var hT=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}};bM.exports=hT});var ga=g((YEe,CM)=>{"use strict";var VZ=require("fs-extra"),$Z=require("path"),sr=require("systeminformation"),Si=$(),NM=ut(),FEe=Ve(),Wd=P(),YZ=OM(),KZ=Os(),{getThreadInfo:IM}=We(),NT=Z();NT.initSync();var WZ=yM(),{openEnvironment:kEe}=Qe(),{getSchemaPath:VEe}=je(),{database:$Ee,databases:mT}=(Ae(),ie(ke)),Kd;CM.exports={getHDBProcessInfo:gT,getNetworkInfo:AT,getDiskInfo:RT,getMemoryInfo:TT,getCPUInfo:ST,getTimeInfo:pT,getSystemInformation:OT,systemInformation:QZ,getTableSize:bT,getMetrics:yT};function pT(){return sr.time()}a(pT,"getTimeInfo");async function ST(){try{let{family:e,model:t,stepping:r,revision:n,voltage:s,speedmin:i,speedmax:o,governor:c,socket:u,cache:_,...l}=await sr.cpu();l.cpu_speed=await sr.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 sr.currentLoad();return R.cpus=[],T.forEach(b=>{let{raw_load:C,raw_load_idle:x,raw_load_irq:v,raw_load_nice:F,raw_load_system:M,raw_load_user:Q,...J}=b;R.cpus.push(J)}),l.current_load=R,l}catch(e){return Si.error(`error in getCPUInfo: ${e}`),{}}}a(ST,"getCPUInfo");async function TT(){try{let{buffers:e,cached:t,slab:r,buffcache:n,...s}=await sr.mem();return Object.assign(s,process.memoryUsage())}catch(e){return Si.error(`error in getMemoryInfo: ${e}`),{}}}a(TT,"getMemoryInfo");async function gT(){let e={core:[],clustering:[]};try{let t=await sr.processes(),r;try{r=Number.parseInt(await VZ.readFile($Z.join(NT.get(Wd.CONFIG_PARAMS.ROOTPATH),Wd.HDB_PID_FILE),"utf8"))}catch(n){if(n.code===Wd.NODE_ERROR_CODES.ENOENT)Si.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 Si.error(`error in getHDBProcessInfo: ${t}`),e}}a(gT,"getHDBProcessInfo");async function RT(){let e={};try{let{rIO_sec:t,wIO_sec:r,tIO_sec:n,ms:s,...i}=await sr.disksIO();e.io=i;let{rx_sec:o,tx_sec:c,wx_sec:u,..._}=await sr.fsStats();return e.read_write=_,e.size=await sr.fsSize(),e}catch(t){return Si.error(`error in getDiskInfo: ${t}`),e}}a(RT,"getDiskInfo");async function AT(){let e={default_interface:null,latency:{},interfaces:[],stats:[],connections:[]};try{return e.default_interface=await sr.networkInterfaceDefault(),e.latency=await sr.inetChecksite("google.com"),(await sr.networkInterfaces()).forEach(n=>{let{internal:s,virtual:i,mtu:o,dhcp:c,dnsSuffix:u,ieee8021xAuth:_,ieee8021xState:l,carrier_changes:d,...E}=n;e.interfaces.push(E)}),(await sr.networkStats()).forEach(n=>{let{rx_sec:s,tx_sec:i,ms:o,...c}=n;e.stats.push(c)}),e}catch(t){return Si.error(`error in getNetworkInfo: ${t}`),e}}a(AT,"getNetworkInfo");async function OT(){if(Kd!==void 0)return Kd;let e={};try{let{codepage:t,logofile:r,serial:n,build:s,servicepack:i,uefi:o,...c}=await sr.osInfo();e=c;let u=await sr.versions("node, npm");return e.node_version=u.node,e.npm_version=u.npm,Kd=e,Kd}catch(t){return Si.error(`error in getSystemInformation: ${t}`),e}}a(OT,"getSystemInformation");async function bT(){let e=[],t=await KZ.describeAll();for(let r of Object.values(t))for(let n of Object.values(r))e.push(await YZ(n));return e}a(bT,"getTableSize");async function yT(){let e={};for(let t in mT){let r=e[t]={},n=r.tables={};for(let s in mT[t])try{let i=mT[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(u=>{let[_,l,d]=u.trim().split(" ");return{pid:_,thread:l,txnid:d}}),i.primaryStore.auditStore&&(r.audit=i.auditStore.getStats()));let o=i.primaryStore.getStats(),c={};for(let u of["treeDepth","treeBranchPageCount","treeLeafPageCount","entryCount","overflowPages"])c[u]=o[u];n[s]=c}catch(i){Si.notify(`Error getting stats for table ${s}: ${i}`)}}return e}a(yT,"getMetrics");async function wM(){if(NT.get(Wd.CONFIG_PARAMS.CLUSTERING_ENABLED)){let{jsm:e}=await NM.getNATSReferences(),t=await NM.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(wM,"getNatsStreamInfo");async function QZ(e){let t=new WZ;if(!Array.isArray(e.attributes)||e.attributes.length===0)return t.system=await OT(),t.time=pT(),t.cpu=await ST(),t.memory=await TT(),t.disk=await RT(),t.network=await AT(),t.harperdb_processes=await gT(),t.table_size=await bT(),t.metrics=await yT(),t.threads=await IM(),t.replication=await wM(),t;for(let r=0;r<e.attributes.length;r++)switch(e.attributes[r]){case"system":t.system=await OT();break;case"time":t.time=pT();break;case"cpu":t.cpu=await ST();break;case"memory":t.memory=await TT();break;case"disk":t.disk=await RT();break;case"network":t.network=await AT();break;case"harperdb_processes":t.harperdb_processes=await gT();break;case"table_size":t.table_size=await bT();break;case"database_metrics":case"metrics":t.metrics=await yT();break;case"threads":t.threads=await IM();break;case"replication":t.replication=await wM();break;default:break}return t}a(QZ,"systemInformation")});var zd=g((WEe,DM)=>{"use strict";DM.exports={version:zZ,printVersion:JZ};var Qd=cu();function zZ(){if(Qd)return Qd.version}a(zZ,"version");function JZ(){Qd&&console.log(`HarperDB Version ${Qd.version}`)}a(JZ,"printVersion")});var dn=g((jEe,UM)=>{"use strict";var jZ=qr(),IT=z(),XZ=require("util"),_o=P(),LM=Z();LM.initSync();var ZZ=cT(),MM=Gr(),{Node:zEe,NodeSubscription:JEe}=pi(),e5=ia(),t5=pM(),{RemotePayloadObject:r5,RemotePayloadSubscription:n5}=Iu(),{handleHDBError:s5,hdb_errors:i5}=ne(),{HTTP_STATUS_CODES:o5,HDB_ERROR_MSGS:a5}=i5,c5=ts(),u5=ga(),l5=zd(),{getDatabases:_5}=(Ae(),ie(ke)),d5=XZ.promisify(ZZ.authorize),f5=MM.searchByHash,E5=MM.searchByValue;UM.exports={authHeaderToUser:h5,isEmpty:m5,getNodeRecord:p5,upsertNodeRecord:S5,buildNodePayloads:T5,checkClusteringEnabled:g5,getAllNodeRecords:R5,getSystemInfo:A5,reverseSubscription:PM};async function h5(e){let t={headers:{authorization:e.hdb_auth_header}};return e.hdb_user=await d5(t,null),e}a(h5,"authHeaderToUser");function m5(e){return e==null}a(m5,"isEmpty");async function p5(e){let t=new e5(_o.SYSTEM_SCHEMA_NAME,_o.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[e],["*"]);return f5(t)}a(p5,"getNodeRecord");async function S5(e){let t=new t5(_o.SYSTEM_SCHEMA_NAME,_o.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[e]);return jZ.upsert(t)}a(S5,"upsertNodeRecord");function PM(e){if(IT.isEmpty(e.subscribe)||IT.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(PM,"reverseSubscription");function T5(e,t,r,n){let s=[];for(let i=0,o=e.length;i<o;i++){let c=e[i],{schema:u,table:_}=c,l=IT.getTableHashAttribute(u,_),{subscribe:d,publish:E}=PM(c),f=_5()[u]?.[_],h=new n5(u,_,l,E,d,c.start_time,f.schemaDefined?f.attributes:void 0);s.push(h)}return new r5(r,t,s,n)}a(T5,"buildNodePayloads");function g5(){if(!LM.get(_o.CONFIG_PARAMS.CLUSTERING_ENABLED))throw s5(new Error,a5.CLUSTERING_NOT_ENABLED,o5.BAD_REQUEST,void 0,void 0,!0)}a(g5,"checkClusteringEnabled");async function R5(){let e=new c5(_o.SYSTEM_SCHEMA_NAME,_o.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,"name","*",void 0,["*"]);return Array.from(await E5(e))}a(R5,"getAllNodeRecords");async function A5(){let e=await u5.getSystemInformation();return{hdb_version:l5.version(),node_version:e.node_version,platform:e.platform}}a(A5,"getSystemInfo")});var wT=g((ZEe,kM)=>{"use strict";var Jd=ut(),vM=z(),BM=Ve(),xM=P(),jd=$(),HM=gu(),O5=_d(),{RemotePayloadObject:b5}=Iu(),{handleHDBError:GM,hdb_errors:y5}=ne(),{HTTP_STATUS_CODES:qM}=y5,{NodeSubscription:FM}=pi();kM.exports=N5;async function N5(e,t){let r;try{r=await Jd.request(`${t}.${BM.REQUEST_SUFFIX}`,new b5(xM.OPERATIONS_ENUM.DESCRIBE_ALL,t,void 0,void 0)),jd.trace("Response from remote describe all request:",r)}catch(o){jd.error(`addNode received error from describe all request to remote node: ${o}`);let c=Jd.requestErrorHandler(o,"add_node",t);throw GM(new Error,c,qM.INTERNAL_SERVER_ERROR,"error",c)}if(r.status===BM.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let o=`Error returned from remote node ${t}: ${r.message}`;throw GM(new Error,o,qM.INTERNAL_SERVER_ERROR,"error",o)}let n=r.message,s=[],i=[];for(let o of e){let{table:c}=o,u=o.database??o.schema??"data";if(u===xM.SYSTEM_SCHEMA_NAME){await Jd.createLocalTableStream(u,c);let h=new FM(u,c,o.publish,o.subscribe);h.start_time=o.start_time,i.push(h);continue}let _=vM.doesSchemaExist(u),l=n[u]!==void 0,d=c?vM.doesTableExist(u,c):!0,E=c?n?.[u]?.[c]!==void 0:!0;if(!_&&!l||!d&&!E){s.push(o);continue}if(!_&&l&&(jd.trace(`addNode creating schema: ${u}`),await HM.createSchema({operation:"create_schema",schema:u})),!d&&E){jd.trace(`addNode creating table: ${c} in schema: ${u} with attributes ${JSON.stringify(n[u][c].attributes)}`);let h=new O5(u,c,n[u][c].hash_attribute);n[u][c].attributes&&(h.attributes=n[u][c].attributes),await HM.createTable(h)}await Jd.createLocalTableStream(u,c);let f=new FM(u,c,o.publish,o.subscribe);f.start_time=o.start_time,i.push(f)}return{added:i,skipped:s}}a(N5,"reviewSubscriptions")});var tf=g((the,YM)=>{"use strict";var{handleHDBError:Xd,hdb_errors:I5}=ne(),{HTTP_STATUS_CODES:Zd}=I5,{addUpdateNodeValidator:w5}=Fd(),ef=$(),$M=P(),VM=Ve(),C5=z(),wu=ut(),Cu=dn(),D5=Z(),L5=wT(),{Node:M5,NodeSubscription:P5}=pi(),{broadcast:U5}=We(),v5="Unable to create subscriptions due to schema and/or tables not existing on the local or remote node",B5="Some subscriptions were unsuccessful due to schema and/or tables not existing on the local or remote node",x5=D5.get($M.CONFIG_PARAMS.CLUSTERING_NODENAME);YM.exports=H5;async function H5(e,t=!1){ef.trace("addNode called with:",e),Cu.checkClusteringEnabled();let r=w5(e);if(r)throw Xd(r,r.message,Zd.BAD_REQUEST,void 0,void 0,!0);let n=e.node_name;if(!t){let d=await Cu.getNodeRecord(n);if(!C5.isEmptyOrZeroLength(d))throw Xd(new Error,`Node '${n}' has already been added, perform update_node to proceed.`,Zd.BAD_REQUEST,void 0,void 0,!0)}let{added:s,skipped:i}=await L5(e.subscriptions,n),o={message:void 0,added:s,skipped:i};if(s.length===0)return o.message=v5,o;let c=Cu.buildNodePayloads(s,x5,$M.OPERATIONS_ENUM.ADD_NODE,await Cu.getSystemInfo()),u=[];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,u.push(new P5(f.schema,f.table,f.publish,f.subscribe))}ef.trace("addNode sending remote payload:",c);let _;try{_=await wu.request(`${n}.${VM.REQUEST_SUFFIX}`,c)}catch(d){ef.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 wu.updateRemoteConsumer(p,n)}let E=wu.requestErrorHandler(d,"add_node",n);throw Xd(new Error,E,Zd.INTERNAL_SERVER_ERROR,"error",E)}if(_.status===VM.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let d=`Error returned from remote node ${n}: ${_.message}`;throw Xd(new Error,d,Zd.INTERNAL_SERVER_ERROR,"error",d)}ef.trace(_);for(let d=0,E=s.length;d<E;d++){let f=s[d];await wu.updateRemoteConsumer(f,n),f.subscribe===!0&&await wu.updateConsumerIterator(f.schema,f.table,n,"start")}let l=new M5(n,u,_.system_info);return await Cu.upsertNodeRecord(l),U5({type:"nats_update"}),i.length>0?o.message=B5:o.message=`Successfully added '${n}' to manifest`,o}a(H5,"addNode")});var LT=g((she,QM)=>{"use strict";var{handleHDBError:CT,hdb_errors:G5}=ne(),{HTTP_STATUS_CODES:DT}=G5,{addUpdateNodeValidator:q5}=Fd(),Du=$(),WM=P(),KM=Ve(),nhe=z(),Lu=ut(),Mu=dn(),F5=Z(),{cloneDeep:k5}=require("lodash"),V5=wT(),{Node:$5,NodeSubscription:Y5}=pi(),{broadcast:K5}=We(),W5="Unable to update subscriptions due to schema and/or tables not existing on the local or remote node",Q5="Some subscriptions were unsuccessful due to schema and/or tables not existing on the local or remote node",z5=F5.get(WM.CONFIG_PARAMS.CLUSTERING_NODENAME);QM.exports=J5;async function J5(e){Du.trace("updateNode called with:",e),Mu.checkClusteringEnabled();let t=q5(e);if(t)throw CT(t,t.message,DT.BAD_REQUEST,void 0,void 0,!0);let r=e.node_name,n,s=await Mu.getNodeRecord(r);s.length>0&&(n=k5(s));let{added:i,skipped:o}=await V5(e.subscriptions,r),c={message:void 0,updated:i,skipped:o};if(i.length===0)return c.message=W5,c;let u=Mu.buildNodePayloads(i,z5,WM.OPERATIONS_ENUM.UPDATE_NODE,await Mu.getSystemInfo());for(let l=0,d=i.length;l<d;l++){let E=i[l];Du.trace(`updateNode updating work stream for node: ${r} subscription:`,E),i[l].start_time===void 0&&delete i[l].start_time}Du.trace("updateNode sending remote payload:",u);let _;try{_=await Lu.request(`${r}.${KM.REQUEST_SUFFIX}`,u)}catch(l){Du.error(`updateNode received error from request: ${l}`);let d=Lu.requestErrorHandler(l,"update_node",r);throw CT(new Error,d,DT.INTERNAL_SERVER_ERROR,"error",d)}if(_.status===KM.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let l=`Error returned from remote node ${r}: ${_.message}`;throw CT(new Error,l,DT.INTERNAL_SERVER_ERROR,"error",l)}Du.trace(_);for(let l=0,d=i.length;l<d;l++){let E=i[l];await Lu.updateRemoteConsumer(E,r),E.subscribe===!0?await Lu.updateConsumerIterator(E.schema,E.table,r,"start"):await Lu.updateConsumerIterator(E.schema,E.table,r,"stop")}return n||(n=[new $5(r,[],_.system_info)]),await j5(n[0],i,_.system_info),o.length>0?c.message=Q5:c.message=`Successfully updated '${r}'`,c}a(J5,"updateNode");async function j5(e,t,r){let n=e;for(let s=0,i=t.length;s<i;s++){let o=t[s],c=!1;for(let u=0,_=e.subscriptions.length;u<_;u++){let l=n.subscriptions[u];if(l.schema===o.schema&&l.table===o.table){l.publish=o.publish,l.subscribe=o.subscribe,c=!0;break}}c||n.subscriptions.push(new Y5(o.schema,o.table,o.publish,o.subscribe))}n.system_info=r,await Mu.upsertNodeRecord(n),K5({type:"nats_update"})}a(j5,"updateNodeTable")});var ZM=g((ohe,XM)=>{"use strict";var jM=require("joi"),{string:zM}=jM.types(),X5=Xe(),JM=P(),Z5=Z(),e8=Ve();XM.exports=t8;function t8(e){let t=zM.invalid(Z5.get(JM.CONFIG_PARAMS.CLUSTERING_NODENAME)).pattern(e8.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=jM.object({operation:zM.valid(JM.OPERATIONS_ENUM.REMOVE_NODE).required(),node_name:t});return X5.validateBySchema(e,r)}a(t8,"removeNodeValidator")});var nf=g((che,sP)=>{"use strict";var{handleHDBError:eP,hdb_errors:r8}=ne(),{HTTP_STATUS_CODES:tP}=r8,n8=ZM(),Pu=$(),rP=dn(),s8=z(),rf=P(),nP=Ve(),MT=ut(),i8=Z(),{RemotePayloadObject:o8}=Iu(),{NodeSubscription:a8}=pi(),c8=oa(),u8=oi(),{broadcast:l8}=We(),_8=i8.get(rf.CONFIG_PARAMS.CLUSTERING_NODENAME);sP.exports=d8;async function d8(e){Pu.trace("removeNode called with:",e),rP.checkClusteringEnabled();let t=n8(e);if(t)throw eP(t,t.message,tP.BAD_REQUEST,void 0,void 0,!0);let r=e.node_name,n=await rP.getNodeRecord(r);if(s8.isEmptyOrZeroLength(n))throw eP(new Error,`Node '${r}' was not found.`,tP.BAD_REQUEST,void 0,void 0,!0);n=n[0];let s=new o8(rf.OPERATIONS_ENUM.REMOVE_NODE,_8,[]),i,o=!1;for(let u=0,_=n.subscriptions.length;u<_;u++){let l=n.subscriptions[u];l.subscribe===!0&&await MT.updateConsumerIterator(l.schema,l.table,r,"stop");try{await MT.updateRemoteConsumer(new a8(l.schema,l.table,!1,!1),r)}catch(d){Pu.error(d)}}try{i=await MT.request(`${r}.${nP.REQUEST_SUFFIX}`,s),Pu.trace("Remove node reply from remote node:",r,i)}catch(u){Pu.error("removeNode received error from request:",u),o=!0}let c=new c8(rf.SYSTEM_SCHEMA_NAME,rf.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[r]);return await u8.deleteRecord(c),l8({type:"nats_update"}),i?.status===nP.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR||o?(Pu.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(d8,"removeNode")});var aP=g((lhe,oP)=>{"use strict";var iP=require("joi"),{string:f8,array:E8}=iP.types(),h8=Xe(),m8=Fd();oP.exports=p8;function p8(e){let t=iP.object({operation:f8.valid("configure_cluster").required(),connections:E8.items(m8.validation_schema).required()});return h8.validateBySchema(e,t)}a(p8,"configureClusterValidator")});var PT=g((dhe,dP)=>{"use strict";var S8=P(),sf=$(),T8=z(),g8=nf(),R8=tf(),cP=dn(),A8=aP(),{handleHDBError:uP,hdb_errors:O8}=ne(),{HTTP_STATUS_CODES:lP}=O8,b8="Configure cluster complete.",y8="Failed to configure the cluster. Check the logs for more details.",N8="Configure cluster was partially successful. Errors occurred when attempting to configure the following nodes. Check the logs for more details.";dP.exports=I8;async function I8(e){sf.trace("configure cluster called with:",e),cP.checkClusteringEnabled();let t=A8(e);if(t)throw uP(t,t.message,lP.BAD_REQUEST,void 0,void 0,!0);let r=await cP.getAllNodeRecords(),n=[];for(let l=0,d=r.length;l<d;l++){let E=await _P(g8,{operation:S8.OPERATIONS_ENUM.REMOVE_NODE,node_name:r[l].name},r[l].name);n.push(E)}sf.trace("All results from configure_cluster remove node:",n);let s=[],i=e.connections.length;for(let l=0;l<i;l++){let d=e.connections[l],E=await _P(R8,d,d.node_name);s.push(E)}sf.trace("All results from configure_cluster add node:",s);let o=[],c=[],u=!1,_=n.concat(s);for(let l=0,d=_.length;l<d;l++){let E=_[l];E.status==="rejected"&&(sf.error(E),o.includes(E.node_name)||o.push(E.node_name)),(E?.result?.message?.includes?.("Successfully")||E?.result?.includes?.("Successfully"))&&(u=!0),!(typeof E.result=="string"&&E.result.includes("Successfully removed")||E.status==="rejected")&&c.push({node_name:E?.node_name,subscriptions:E?.result})}if(T8.isEmptyOrZeroLength(o))return{message:b8,connections:c};if(u)return{message:N8,failed_nodes:o,connections:c};throw uP(new Error,y8,lP.INTERNAL_SERVER_ERROR,void 0,void 0,!0)}a(I8,"configureCluster");async function _P(e,t,r){try{return{node_name:r,result:await e(t)}}catch(n){return{node_name:r,error:n,status:"rejected"}}}a(_P,"functionWrapper")});var mP=g((Ehe,hP)=>{"use strict";var Uu=require("joi"),w8=Xe(),{validateSchemaExists:fP,validateTableExists:C8,validateSchemaName:EP}=Jn(),D8=Uu.object({operation:Uu.string().valid("purge_stream"),schema:Uu.string().custom(fP).custom(EP).optional(),database:Uu.string().custom(fP).custom(EP).optional(),table:Uu.string().custom(C8).required()});function L8(e){return w8.validateBySchema(e,D8)}a(L8,"purgeStreamValidator");hP.exports=L8});var UT=g((mhe,pP)=>{"use strict";var{handleHDBError:M8,hdb_errors:P8}=ne(),{HTTP_STATUS_CODES:U8}=P8,v8=mP(),B8=ut(),x8=dn();pP.exports=H8;async function H8(e){e.schema=e.schema??e.database;let t=v8(e);if(t)throw M8(t,t.message,U8.BAD_REQUEST,void 0,void 0,!0);x8.checkClusteringEnabled();let{schema:r,table:n,options:s}=e;return await B8.purgeTableStream(r,n,s),`Successfully purged table '${r}.${n}'`}a(H8,"purgeStream")});var xT=g((She,OP)=>{"use strict";var BT=dn(),G8=ut(),gP=Z(),of=P(),fo=Ve(),q8=z(),vT=$(),{RemotePayloadObject:F8}=Iu(),{ErrorCode:SP}=require("nats"),TP=gP.get(of.CONFIG_PARAMS.CLUSTERING_ENABLED),RP=gP.get(of.CONFIG_PARAMS.CLUSTERING_NODENAME);OP.exports={clusterStatus:k8,buildNodeStatus:AP};async function k8(){let e={node_name:RP,is_enabled:TP,connections:[]};if(!TP)return e;let t=await BT.getAllNodeRecords();if(q8.isEmptyOrZeroLength(t))return e;let r=[];for(let n=0,s=t.length;n<s;n++)r.push(AP(t[n],e.connections));return await Promise.allSettled(r),e}a(k8,"clusterStatus");async function AP(e,t){let r=e.name,n=new F8(of.OPERATIONS_ENUM.CLUSTER_STATUS,RP,void 0,await BT.getSystemInfo()),s,i,o=fo.CLUSTER_STATUS_STATUSES.OPEN;try{let u=Date.now();s=await G8.request(fo.REQUEST_SUBJECT(r),n),i=Date.now()-u,s.status===fo.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR&&(o=fo.CLUSTER_STATUS_STATUSES.CLOSED,vT.error(`Error getting node status from ${r} `,s))}catch(u){vT.warn(`Error getting node status from ${r}`,u),u.code===SP.NoResponders?o=fo.CLUSTER_STATUS_STATUSES.NO_RESPONDERS:u.code===SP.Timeout?o=fo.CLUSTER_STATUS_STATUSES.TIMEOUT:o=fo.CLUSTER_STATUS_STATUSES.CLOSED}let c=new V8(r,o,s?.message?.ports?.clustering,s?.message?.ports?.operations_api,i,s?.message?.uptime,e.subscriptions,s?.message?.system_info);try{let u={name:r,system_info:s?.message?.system_info};e.system_info?.hdb_version!==of.PRE_4_0_0_VERSION&&await BT.upsertNodeRecord(u)}catch(u){vT.error("Cluster status encountered an error updating system info for node:",r,u)}t.push(c)}a(AP,"buildNodeStatus");function V8(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(V8,"NodeStatusObject")});var GT=g((ghe,bP)=>{"use strict";var{handleHDBError:$8,hdb_errors:Y8}=ne(),{HTTP_STATUS_CODES:K8}=Y8,W8=ut(),Q8=dn(),HT=z(),af=require("joi"),z8=Xe(),J8=2e3,j8=af.object({timeout:af.number().min(1),connected_nodes:af.boolean(),routes:af.boolean()});bP.exports=X8;async function X8(e){Q8.checkClusteringEnabled();let t=z8.validateBySchema(e,j8);if(t)throw $8(t,t.message,K8.BAD_REQUEST,void 0,void 0,!0);let{timeout:r,connected_nodes:n,routes:s}=e,i=n===void 0||HT.autoCastBoolean(n),o=s===void 0||HT.autoCastBoolean(s),c={nodes:[]},u=await W8.getServerList(r??J8),_={};if(i)for(let l=0,d=u.length;l<d;l++){let E=u[l].statsz;E&&(_[u[l].server.name]=E.routes)}for(let l=0,d=u.length;l<d;l++){if(u[l].statsz)continue;let E=u[l].server,f=u[l].data;if(E.name.endsWith("-hub")){let h={name:E.name.slice(0,-4),response_time:u[l].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:HT.autoCast(p.split(":")[1])})):[]),c.nodes.push(h)}}return c}a(X8,"clusterNetwork")});var wP=g((Ahe,IP)=>{"use strict";var qT=require("joi"),yP=Xe(),{route_constraints:NP}=rp();IP.exports={setRoutesValidator:Z8,deleteRoutesValidator:e6};function Z8(e){let t=qT.object({server:qT.valid("hub","leaf").required(),routes:NP.required()});return yP.validateBySchema(e,t)}a(Z8,"setRoutesValidator");function e6(e){let t=qT.object({routes:NP.required()});return yP.validateBySchema(e,t)}a(e6,"deleteRoutesValidator")});var kT=g((bhe,MP)=>{"use strict";var Eo=Er(),FT=z(),cf=P(),CP=wP(),{handleHDBError:DP,hdb_errors:t6}=ne(),{HTTP_STATUS_CODES:LP}=t6,r6="cluster routes successfully set",n6="cluster routes successfully deleted";MP.exports={setRoutes:s6,getRoutes:i6,deleteRoutes:o6};function s6(e){let t=CP.setRoutesValidator(e);if(t)throw DP(t,t.message,LP.BAD_REQUEST,void 0,void 0,!0);let r=Eo.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,u=e.routes.length;c<u;c++){let _=e.routes[c];_.port=FT.autoCast(_.port);let l=n.some(E=>E.host===_.host&&E.port===_.port),d=s.some(E=>E.host===_.host&&E.port===_.port);l||d?i.push(_):(n.push(_),o.push(_))}return e.server==="hub"?Eo.updateConfigValue(cf.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,n):Eo.updateConfigValue(cf.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,n),{message:r6,set:o,skipped:i}}a(s6,"setRoutes");function i6(){let e=Eo.getClusteringRoutes();return{hub:e.hub_routes,leaf:e.leaf_routes}}a(i6,"getRoutes");function o6(e){let t=CP.deleteRoutesValidator(e);if(t)throw DP(t,t.message,LP.BAD_REQUEST,void 0,void 0,!0);let r=Eo.getClusteringRoutes(),n=r.hub_routes,s=r.leaf_routes,i=[],o=[],c=!1,u=!1;for(let _=0,l=e.routes.length;_<l;_++){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),u=!0,f=!1,i.push(d);break}}f&&o.push(d)}}return c&&(n=FT.isEmptyOrZeroLength(n)?null:n,Eo.updateConfigValue(cf.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,n)),u&&(s=FT.isEmptyOrZeroLength(s)?null:s,Eo.updateConfigValue(cf.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,s)),{message:n6,deleted:i,skipped:o}}a(o6,"deleteRoutes")});var UP=g((Nhe,PP)=>{"use strict";var vu=require("alasql"),ho=require("recursive-iterator"),xn=$(),a6=z(),Bu=P(),VT=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,u6(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=>Bu.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=>!Bu.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][Bu.PERMS_CRUD_ENUM.READ]){let c;t[i].tables[o].attribute_permissions.length>0?c=c6(t[i].tables[o].attribute_permissions):c=global.hdb_schema[i][o].attributes.map(_=>({attribute_name:_.attribute}));let u=this.affected_attributes.get(i).get(o).filter(_=>!Bu.SEARCH_WILDCARDS.includes(_));c.forEach(({attribute_name:_})=>{let l=new vu.yy.Column({columnid:_});s.tableid&&(l.tableid=s.tableid),this.ast.columns.push(l),u.includes(_)||u.push(_)}),this.affected_attributes.get(i).set(o,u)}}),this.ast}};function c6(e){return e.filter(t=>t[Bu.PERMS_CRUD_ENUM.READ])}a(c6,"filterReadRestrictedAttrs");function u6(e,t,r,n,s){l6(e,t,r,n,s)}a(u6,"interpretAST");function xu(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(xu,"addSchemaTableToMap");function l6(e,t,r,n,s){if(!e){xn.info("getRecordAttributesAST: invalid SQL syntax tree");return}e instanceof vu.yy.Insert?E6(e,t,r):e instanceof vu.yy.Select?_6(e,t,r,n,s):e instanceof vu.yy.Update?d6(e,t,r):e instanceof vu.yy.Delete?f6(e,t,r):xn.error("AST in getRecordAttributesAST() is not a valid SQL type.")}a(l6,"getRecordAttributesAST");function _6(e,t,r,n,s){if(!e){xn.info("getSelectAttributes: invalid SQL syntax tree");return}if(!e.from||e.from[0]===void 0)return;let i=e.from[0].databaseid;if(a6.isEmptyOrZeroLength(i)){xn.error("No schema specified");return}e.from.forEach(c=>{xu(c,t,r,n,s)}),e.joins&&e.joins.forEach(c=>{c.as&&(c.table.as=c.as),xu(c.table,t,r,n,s)});let o=new ho(e.columns);for(let{node:c}of o)if(c&&c.columnid){let u=c.tableid,_=n.has(u)?n.get(u):i;if(u||(u=e.from[0].tableid),!t.get(_).has(u))if(r.has(u))u=r.get(u);else{xn.info(`table specified as ${u} not found.`);return}t.get(_).get(u).indexOf(c.columnid)<0&&t.get(_).get(u).push(c.columnid)}if(e.where){let c=new ho(e.where),u=e.from[0].tableid;for(let{node:_}of c)if(_&&_.columnid){let l=_.tableid?_.tableid:u;if(!t.get(i).has(l))if(r.has(l))l=r.get(l);else{xn.info(`table specified as ${l} not found.`);continue}t.get(i).get(l).indexOf(_.columnid)<0&&t.get(i).get(l).push(_.columnid)}}if(e.joins&&e.joins.forEach(c=>{let u=new ho(c.on);for(let{node:_}of u)if(_&&_.columnid){let l=_.tableid,d=s.get(l);if(!t.get(d).has(l))if(r.has(l))l=r.get(l);else{xn.info(`table specified as ${l} not found.`);continue}t.get(d).get(l).indexOf(_.columnid)<0&&t.get(d).get(l).push(_.columnid)}}),e.order){let c=new ho(e.order);for(let{node:u}of c)if(u&&u.columnid){let _=u.tableid,l=n.has(_)?n.get(_):i;if(_||(_=e.from[0].tableid),!t.get(l).has(_))if(r.has(_))_=r.get(_);else{xn.info(`table specified as ${_} not found.`);return}t.get(l).get(_).indexOf(u.columnid)<0&&t.get(l).get(_).push(u.columnid)}}}a(_6,"getSelectAttributes");function d6(e,t,r){if(!e){xn.info("getUpdateAttributes: invalid SQL syntax tree");return}let n=new ho(e.columns),s=e.table.databaseid;xu(e.table,t,r);for(let{node:i}of n)i&&i.columnid&&$T(e.table.tableid,s,i.columnid,t,r)}a(d6,"getUpdateAttributes");function f6(e,t,r){if(!e){xn.info("getDeleteAttributes: invalid SQL syntax tree");return}let n=new ho(e.where),s=e.table.databaseid;xu(e.table,t,r);for(let{node:i}of n)i&&i.columnid&&$T(e.table.tableid,s,i.columnid,t,r)}a(f6,"getDeleteAttributes");function E6(e,t,r){if(!e){xn.info("getInsertAttributes: invalid SQL syntax tree");return}let n=new ho(e.columns),s=e.into.databaseid;xu(e.into,t,r);for(let{node:i}of n)i&&i.columnid&&$T(e.into.tableid,s,i.columnid,t,r)}a(E6,"getInsertAttributes");function $T(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($T,"pushAttribute");PP.exports=VT});var WT=g((whe,HP)=>{var uf=Ji(),vP=require("chalk"),Qr=$(),BP=require("prompt"),{promisify:h6}=require("util"),YT=P(),m6=require("fs-extra"),p6=require("path"),S6=z(),T6=zd(),xP=Z();xP.initSync();var g6=require("moment"),R6=h6(BP.get),A6=p6.join(xP.getHdbBasePath(),YT.LICENSE_KEY_DIR_NAME,YT.LICENSE_FILE_NAME,YT.LICENSE_FILE_NAME);HP.exports={getFingerprint:b6,setLicense:O6,parseLicense:KT,register:y6,getRegistrationInfo:I6};async function O6(e){if(e&&e.key&&e.company){try{Qr.info(`parsing license key: ${e.key} and `);let t=e.company.toString();await KT(e.key.trim(),t.trim())}catch(t){let r="There was an error parsing the license key.";throw Qr.error(r),Qr.error(t),new Error(r)}return"Wrote license key file. Registration successful."}throw new Error("Invalid key or company specified for license file.")}a(O6,"setLicense");async function b6(){let e={};try{e=await uf.generateFingerPrint()}catch(t){let r="Error generating fingerprint.";throw Qr.error(r),Qr.error(t),new Error(r)}return e}a(b6,"getFingerprint");async function KT(e,t){if(!e||!t)throw new Error("Invalid entries for License Key and Customer Company");Qr.info("Validating license input...");let r=uf.validateLicense(e,t);if(Qr.info("checking for valid license..."),!r.valid_license)throw new Error("Invalid license found.");if(Qr.info("checking valid license date..."),!r.valid_date)throw new Error("This License has expired.");if(Qr.info(`checking for valid machine license ${r.valid_machine}`),!r.valid_machine)throw new Error("This license is in use on another machine.");try{Qr.info("writing license to disk"),await m6.writeFile(A6,JSON.stringify({license_key:e,company:t}))}catch(n){throw Qr.error("Failed to write License"),n}return"Registration successful."}a(KT,"parseLicense");async function y6(){let e=await N6();return KT(e.HDB_LICENSE,e.CUSTOMER_COMPANY)}a(y6,"register");async function N6(){let e=await uf.generateFingerPrint(),t={properties:{CUSTOMER_COMPANY:{description:vP.magenta("[COMPANY] Please enter your company name"),required:!0},HDB_LICENSE:{description:vP.magenta(`[HDB_LICENSE] Your fingerprint is ${e} Please enter your license key`),required:!0}}};try{BP.start()}catch(n){Qr.error(n)}let r;try{r=await R6(t)}catch(n){throw console.error("There was a problem prompting for registration input. Exiting."),n}return r}a(N6,"promptForRegistration");async function I6(){let e={registered:!1,version:null,ram_allocation:null,license_expiration_date:null},t;try{t=await uf.getLicense()}catch(r){throw Qr.error(`There was an error when searching licenses due to: ${r.message}`),r}if(S6.isEmptyOrZeroLength(t))throw new Error("There were no licenses found.");if(e.registered=t.enterprise,e.version=T6.version(),e.ram_allocation=t.ram_allocation,isNaN(t.exp_date))e.license_expiration_date=t.enterprise?t.exp_date:null;else{let r=g6.utc(t.exp_date).format("YYYY-MM-DD");e.license_expiration_date=t.enterprise?r:null}return e}a(I6,"getRegistrationInfo")});var qP=g((Dhe,GP)=>{"use strict";var w6=Ve(),QT=class{static{a(this,"HubConfigObject")}constructor(t,r,n,s,i,o,c,u,_,l,d,E,f,h){this.port=t,o===null&&(o=void 0),this.server_name=r+w6.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:u},this.leafnodes={port:_,tls:{cert_file:s,key_file:i,ca_file:o,insecure:c}},this.cluster={name:l,port:d,routes:E,tls:{cert_file:s,key_file:i,ca_file:o,insecure:c,verify:u}},this.accounts={SYS:{users:f},HDB:{users:h}},this.system_account="SYS"}};GP.exports=QT});var VP=g((Mhe,kP)=>{"use strict";var FP=Ve(),zT=class{static{a(this,"LeafConfigObject")}constructor(t,r,n,s,i,o,c,u,_,l,d){this.port=t,d===null&&(d=void 0),this.server_name=r+FP.SERVER_SUFFIX.LEAF,this.pid_file=n,this.max_payload=67108864,this.jetstream={enabled:!0,store_dir:s,domain:r+FP.SERVER_SUFFIX.LEAF},this.tls={cert_file:_,key_file:l,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:u,jetstream:"enabled"}},this.system_account="SYS"}};kP.exports=zT});var YP=g((Uhe,$P)=>{"use strict";var JT=class{static{a(this,"HdbUserObject")}constructor(t,r){this.user=t,this.password=r}};$P.exports=JT});var WP=g((Bhe,KP)=>{"use strict";var C6=Ve(),jT=class{static{a(this,"SysUserObject")}constructor(t,r){this.user=t+C6.SERVER_SUFFIX.ADMIN,this.password=r}};KP.exports=jT});var eg=g((Hhe,JP)=>{"use strict";var Ra=require("path"),df=require("fs-extra"),D6=qP(),L6=VP(),M6=YP(),P6=WP(),XT=ln(),Oa=z(),yr=Er(),_f=P(),Hu=Ve(),{CONFIG_PARAMS:pt}=_f,ba=$(),Gu=Z(),QP=As(),ZT=ut(),Aa="clustering",U6=1e4,zP=50;JP.exports={generateNatsConfig:B6,removeNatsConfig:x6,getHubConfigPath:v6};function v6(){let e=Gu.get(pt.ROOTPATH);return Ra.join(e,Aa,Hu.NATS_CONFIG_FILES.HUB_SERVER)}a(v6,"getHubConfigPath");async function B6(e=!1,t=void 0){Gu.initSync();let r=Gu.get(pt.ROOTPATH),n=Ra.join(r,Aa,Hu.PID_FILES.HUB),s=Ra.join(r,Aa,Hu.PID_FILES.LEAF),i=yr.getConfigFromFile(pt.CLUSTERING_LEAFSERVER_STREAMS_PATH),o=Ra.join(r,Aa,Hu.NATS_CONFIG_FILES.HUB_SERVER),c=Ra.join(r,Aa,Hu.NATS_CONFIG_FILES.LEAF_SERVER),u=yr.getConfigFromFile(pt.CLUSTERING_TLS_CERTIFICATE),_=yr.getConfigFromFile(pt.CLUSTERING_TLS_PRIVATEKEY),l=yr.getConfigFromFile(pt.CLUSTERING_TLS_CERT_AUTH),d=yr.getConfigFromFile(pt.CLUSTERING_TLS_INSECURE),E=yr.getConfigFromFile(pt.CLUSTERING_TLS_VERIFY),f=yr.getConfigFromFile(pt.CLUSTERING_NODENAME),h=yr.getConfigFromFile(pt.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT);await ZT.checkNATSServerInstalled()||ff("nats-server dependency is either missing or the wrong version. Run 'npm install' to fix");let p=await XT.listUsers(),S=yr.getConfigFromFile(pt.CLUSTERING_USER),T=await XT.getClusterUser();(Oa.isEmpty(T)||T.active!==!0)&&ff(`Invalid cluster user '${S}'. A valid user with the role 'cluster_user' must be defined under clustering.user in harperdb-config.yaml`),e||(await lf(pt.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),await lf(pt.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT),await lf(pt.CLUSTERING_HUBSERVER_NETWORK_PORT),await lf(pt.CLUSTERING_LEAFSERVER_NETWORK_PORT));let R=[],b=[];for(let[J,j]of p.entries())j.role.role===_f.ROLE_TYPES_ENUM.CLUSTER_USER&&j.active&&(R.push(new P6(j.username,QP.decrypt(j.hash))),b.push(new M6(j.username,QP.decrypt(j.hash))));let C=[],{hub_routes:x}=yr.getClusteringRoutes();if(!Oa.isEmptyOrZeroLength(x))for(let J of x)C.push(`tls://${T.sys_name_encoded}:${T.uri_encoded_d_hash}@${J.host}:${J.port}`);let v=new D6(yr.getConfigFromFile(pt.CLUSTERING_HUBSERVER_NETWORK_PORT),f,n,u,_,l,d,E,h,yr.getConfigFromFile(pt.CLUSTERING_HUBSERVER_CLUSTER_NAME),yr.getConfigFromFile(pt.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),C,R,b);l==null&&(delete v.tls.ca_file,delete v.leafnodes.tls.ca_file),t=Oa.isEmpty(t)?void 0:t.toLowerCase(),(t===void 0||t===_f.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase())&&(await df.writeJson(o,v),ba.trace(`Hub server config written to ${o}`));let F=`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 L6(yr.getConfigFromFile(pt.CLUSTERING_LEAFSERVER_NETWORK_PORT),f,s,i,[F],[M],R,b,u,_,l,d);l==null&&delete Q.tls.ca_file,(t===void 0||t===_f.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())&&(await df.writeJson(c,Q),ba.trace(`Leaf server config written to ${c}`))}a(B6,"generateNatsConfig");async function lf(e){let t=Gu.get(e);return Oa.isEmpty(t)&&ff(`port undefined for '${e}'`),await Oa.isPortTaken(t)&&ff(`'${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(lf,"isPortAvailable");function ff(e){let t=`Error generating clustering config: ${e}`;ba.error(t),console.error(t),process.exit(1)}a(ff,"generateNatsConfigError");async function x6(e){let{port:t,config_file:r}=ZT.getServerConfig(e),{username:n,decrypt_hash:s}=await XT.getClusterUser(),i=0,o=2e3;for(;i<zP;){try{let l=await ZT.createConnection(t,n,s,!1);if(l.protocol.connected===!0){l.close();break}}catch(l){ba.trace(`removeNatsConfig waiting for ${e}. Caught and swallowed error ${l}`)}if(i++,i>=zP)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&&ba.notify("Operations API waiting for Nats server connection. This could be caused by large Nats streams or incorrect clustering config."),await Oa.async_set_timeout(_)}let c="0".repeat(U6),u=Ra.join(Gu.get(pt.ROOTPATH),Aa,r);await df.writeFile(u,c),await df.remove(u),ba.notify(e,"started.")}a(x6,"removeNatsConfig")});var rU=g((qhe,tU)=>{"use strict";var zr=Z(),H6=Ji(),he=P(),qu=Ve(),Ds=require("path"),{PACKAGE_ROOT:hf}=P(),jP=Z(),Ef=z(),ya="/dev/null",G6=Ds.join(hf,"launchServiceScripts"),XP=Ds.join(hf,"utility/scripts"),q6=Ds.join(XP,he.HDB_RESTART_SCRIPT),ZP=Ds.resolve(hf,"dependencies",`${process.platform}-${process.arch}`,qu.NATS_BINARY_NAME);function eU(){let t=H6.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 Ef.noBootFile()&&(n[he.CONFIG_PARAMS.ROOTPATH.toUpperCase()]=Ef.getEnvCliRootPath()),{name:he.PROCESS_DESCRIPTORS.HDB,script:he.LAUNCH_SERVICE_SCRIPTS.MAIN,exec_mode:"fork",env:n,node_args:r,cwd:hf}}a(eU,"generateMainServerConfig");var F6=9930;function k6(){zr.initSync(!0);let e=zr.get(he.CONFIG_PARAMS.ROOTPATH),t=Ds.join(e,"clustering",qu.NATS_CONFIG_FILES.HUB_SERVER),r=Ds.join(zr.get(he.HDB_SETTINGS_NAMES.LOG_PATH_KEY),he.LOG_NAMES.HDB),n=jP.get(he.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),s=qu.LOG_LEVEL_FLAGS[zr.get(he.CONFIG_PARAMS.CLUSTERING_LOGLEVEL)]??void 0,i={name:he.PROCESS_DESCRIPTORS.CLUSTERING_HUB+(n!==F6?"-"+n:""),script:ZP,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 zr.get(he.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(i.out_file=ya,i.error_file=ya),i}a(k6,"generateNatsHubServerConfig");var V6=9940;function $6(){zr.initSync(!0);let e=zr.get(he.CONFIG_PARAMS.ROOTPATH),t=Ds.join(e,"clustering",qu.NATS_CONFIG_FILES.LEAF_SERVER),r=Ds.join(zr.get(he.HDB_SETTINGS_NAMES.LOG_PATH_KEY),he.LOG_NAMES.HDB),n=jP.get(he.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),s=qu.LOG_LEVEL_FLAGS[zr.get(he.CONFIG_PARAMS.CLUSTERING_LOGLEVEL)]??void 0,i={name:he.PROCESS_DESCRIPTORS.CLUSTERING_LEAF+(n!==V6?"-"+n:""),script:ZP,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 zr.get(he.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(i.out_file=ya,i.error_file=ya),i}a($6,"generateNatsLeafServerConfig");function Y6(){zr.initSync();let e=Ds.join(zr.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:G6,autorestart:!1};return zr.get(he.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(t.out_file=ya,t.error_file=ya),t}a(Y6,"generateClusteringUpgradeV4ServiceConfig");function K6(){let e={[he.PROCESS_NAME_ENV_PROP]:he.PROCESS_DESCRIPTORS.RESTART_HDB};return Ef.noBootFile()&&(e[he.CONFIG_PARAMS.ROOTPATH.toUpperCase()]=Ef.getEnvCliRootPath()),{...{name:he.PROCESS_DESCRIPTORS.RESTART_HDB,exec_mode:"fork",env:e,instances:1,autorestart:!1,cwd:XP},script:q6}}a(K6,"generateRestart");function W6(){return{apps:[eU()]}}a(W6,"generateAllServiceConfigs");tU.exports={generateAllServiceConfigs:W6,generateMainServerConfig:eU,generateRestart:K6,generateNatsHubServerConfig:k6,generateNatsLeafServerConfig:$6,generateClusteringUpgradeV4ServiceConfig:Y6}});var mU=g((Vhe,hU)=>{"use strict";var Ue=P(),Q6=z(),Ms=eg(),mf=ut(),Ls=Ve(),Ti=rU(),pf=Z(),gi=$(),z6=dn(),{startWorker:nU,onMessageFromWorkers:J6}=We(),j6=ga(),khe=require("util"),X6=require("child_process"),Z6=require("fs"),{execFile:e9}=X6,we;hU.exports={enterPM2Mode:t9,start:Ri,stop:tg,reload:iU,restart:oU,list:rg,describe:cU,connect:Ps,kill:o9,startAllServices:a9,startService:ng,getUniqueServicesList:uU,restartAllServices:c9,isServiceRegistered:lU,reloadStopStart:_U,restartHdb:aU,deleteProcess:s9,startClusteringProcesses:fU,startClusteringThreads:EU,isHdbRestartRunning:i9,isClusteringRunning:l9,stopClustering:u9,reloadClustering:_9};var Fu=!1;J6(e=>{e.type==="restart"&&pf.initSync(!0)});function t9(){Fu=!0}a(t9,"enterPM2Mode");function Ps(){return we||(we=require("pm2")),new Promise((e,t)=>{we.connect((r,n)=>{gi.setupConsoleLogging(),r&&t(r),e(n)})})}a(Ps,"connect");var Nr,r9=10,sU;function Ri(e,t=!1){if(Fu)return n9(e);let r=e9(e.script,e.args.split(" "),e);r.name=e.name,r.on("exit",async i=>{let o=Nr.indexOf(r);o>-1&&Nr.splice(o,1),!sU&&i!==0&&(e.restarts=(e.restarts||0)+1,e.restarts<r9&&(Z6.existsSync(Ms.getHubConfigPath())?Ri(e):(await Ms.generateNatsConfig(!0),Ri(e),await new Promise(c=>setTimeout(c,3e3)),await Ms.removeNatsConfig(Ue.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await Ms.removeNatsConfig(Ue.PROCESS_DESCRIPTORS.CLUSTERING_LEAF))))});let n={serviceName:e.name.replace(/ /g,"-")};function s(i){let o=pf.get(Ue.CONFIG_PARAMS.CLUSTERING_LOGLEVEL),c=/\[\d+][^\[]+\[(\w+)]/g,u,_=0,l;for(;u=c.exec(i);){if(u.index&&Ls.LOG_LEVEL_HIERARCHY[o]>=Ls.LOG_LEVEL_HIERARCHY[l||"info"]){let f=l===Ls.LOG_LEVELS.ERR||l===Ls.LOG_LEVELS.WRN?gi.OUTPUTS.STDERR:gi.OUTPUTS.STDOUT;gi.logCustomLevel(l||"info",f,n,i.slice(_,u.index).trim())}let[d,E]=u;_=u.index+d.length,l=Ls.LOG_LEVELS[E]}if(Ls.LOG_LEVEL_HIERARCHY[o]>=Ls.LOG_LEVEL_HIERARCHY[l||"info"]){let d=l===Ls.LOG_LEVELS.ERR||l===Ls.LOG_LEVELS.WRN?gi.OUTPUTS.STDERR:gi.OUTPUTS.STDOUT;gi.logCustomLevel(l||"info",d,n,i.slice(_).trim())}}if(a(s,"extractMessages"),r.stdout.on("data",s),r.stderr.on("data",s),r.unref(),Nr=[],!Nr&&!t){let i=a(()=>{sU=!0,Nr&&(Nr.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)}Nr.push(r)}a(Ri,"start");function n9(e){return new Promise(async(t,r)=>{try{await Ps()}catch(n){r(n)}we.start(e,(n,s)=>{n&&(we.disconnect(),r(n)),we.disconnect(),t(s)})})}a(n9,"startWithPM2");function tg(e){if(!Fu){for(let t of Nr||[])t.name===e&&(Nr.splice(Nr.indexOf(t),1),t.kill());return}return new Promise(async(t,r)=>{try{await Ps()}catch(n){r(n)}we.stop(e,async(n,s)=>{n&&(we.disconnect(),r(n)),we.delete(e,(i,o)=>{i&&(we.disconnect(),r(n)),we.disconnect(),t(o)})})})}a(tg,"stop");function iU(e){return new Promise(async(t,r)=>{try{await Ps()}catch(n){r(n)}we.reload(e,(n,s)=>{n&&(we.disconnect(),r(n)),we.disconnect(),t(s)})})}a(iU,"reload");function oU(e){if(!Fu)for(let t of Nr||[])t.name===e&&t.kill();return new Promise(async(t,r)=>{try{await Ps()}catch(n){r(n)}we.restart(e,(n,s)=>{we.disconnect(),t(s)})})}a(oU,"restart");function s9(e){return new Promise(async(t,r)=>{try{await Ps()}catch(n){r(n)}we.delete(e,(n,s)=>{n&&(we.disconnect(),r(n)),we.disconnect(),t(s)})})}a(s9,"deleteProcess");async function aU(){await Ri(Ti.generateRestart())}a(aU,"restartHdb");async function i9(){let e=await rg();for(let t in e)if(e[t].name===Ue.PROCESS_DESCRIPTORS.RESTART_HDB)return!0;return!1}a(i9,"isHdbRestartRunning");function rg(){return new Promise(async(e,t)=>{try{await Ps()}catch(r){t(r)}we.list((r,n)=>{r&&(we.disconnect(),t(r)),we.disconnect(),e(n)})})}a(rg,"list");function cU(e){return new Promise(async(t,r)=>{try{await Ps()}catch(n){r(n)}we.describe(e,(n,s)=>{n&&(we.disconnect(),r(n)),we.disconnect(),t(s)})})}a(cU,"describe");function o9(){if(!Fu){for(let e of Nr||[])e.kill();Nr=[];return}return new Promise(async(e,t)=>{try{await Ps()}catch(r){t(r)}we.killDaemon((r,n)=>{r&&(we.disconnect(),t(r)),we.disconnect(),e(n)})})}a(o9,"kill");async function a9(){try{await fU(),await EU(),await Ri(Ti.generateAllServiceConfigs())}catch(e){throw we?.disconnect(),e}}a(a9,"startAllServices");async function ng(e,t=!1){try{let r;switch(e=e.toLowerCase(),e){case Ue.PROCESS_DESCRIPTORS.HDB.toLowerCase():r=Ti.generateMainServerConfig();break;case Ue.PROCESS_DESCRIPTORS.CLUSTERING_INGEST_SERVICE.toLowerCase():r=Ti.generateNatsIngestServiceConfig();break;case Ue.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE.toLowerCase():r=Ti.generateNatsReplyServiceConfig();break;case Ue.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase():r=Ti.generateNatsHubServerConfig(),await Ri(r,t),await Ms.removeNatsConfig(e);return;case Ue.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase():r=Ti.generateNatsLeafServerConfig(),await Ri(r,t),await Ms.removeNatsConfig(e);return;case Ue.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0.toLowerCase():r=Ti.generateClusteringUpgradeV4ServiceConfig();break;default:throw new Error(`Start service called with unknown service config: ${e}`)}await Ri(r)}catch(r){throw we?.disconnect(),r}}a(ng,"startService");async function uU(){try{let e=await rg(),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 we?.disconnect(),e}}a(uU,"getUniqueServicesList");async function c9(e=[]){try{let t=!1,r=await uU();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 oU(o))}t&&await _U(Ue.PROCESS_DESCRIPTORS.HDB)}catch(t){throw we?.disconnect(),t}}a(c9,"restartAllServices");async function lU(e){if(Nr?.find(r=>r.name===e))return!0;let t=await j6.getHDBProcessInfo();return t.core.length&&t.core[0]?.parent==="PM2"}a(lU,"isServiceRegistered");async function _U(e){let t=pf.get(Ue.CONFIG_PARAMS.THREADS_COUNT)??pf.get(Ue.CONFIG_PARAMS.THREADS),r=await cU(e),n=Q6.isEmptyOrZeroLength(r)?0:r.length;t!==n?(await tg(e),await ng(e)):e===Ue.PROCESS_DESCRIPTORS.HDB?await aU():await iU(e)}a(_U,"reloadStopStart");var dU;async function fU(e=!1){for(let t in Ue.CLUSTERING_PROCESSES){let r=Ue.CLUSTERING_PROCESSES[t];await ng(r,e)}}a(fU,"startClusteringProcesses");async function EU(){dU=nU(Ue.LAUNCH_SERVICE_SCRIPTS.NATS_REPLY_SERVICE,{name:Ue.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE});try{await mf.deleteLocalStream("__HARPERDB_WORK_QUEUE__")}catch{}await mf.updateLocalStreams();let e=await z6.getAllNodeRecords();for(let t=0,r=e.length;t<r;t++)if(e[t].system_info?.hdb_version===Ue.PRE_4_0_0_VERSION){gi.info("Starting clustering upgrade 4.0.0 process"),nU(Ue.LAUNCH_SERVICE_SCRIPTS.NODES_UPGRADE_4_0_0,{name:"Upgrade-4-0-0"});break}}a(EU,"startClusteringThreads");async function u9(){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 dU.terminate();else{let t=Ue.CLUSTERING_PROCESSES[e];await tg(t)}}a(u9,"stopClustering");async function l9(){for(let e in Ue.CLUSTERING_PROCESSES){let t=Ue.CLUSTERING_PROCESSES[e];if(await lU(t)===!1)return!1}return!0}a(l9,"isClusteringRunning");async function _9(){await Ms.generateNatsConfig(!0),await mf.reloadNATSHub(),await mf.reloadNATSLeaf(),await Ms.removeNatsConfig(Ue.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase()),await Ms.removeNatsConfig(Ue.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())}a(_9,"reloadClustering")});var OU={};Fe(OU,{compactOnStart:()=>d9,copyDb:()=>AU});async function d9(){Vu.notify("Running compact on start"),console.log("Running compact on start");let e=(0,sg.get)(Ai.CONFIG_PARAMS.ROOTPATH),t=new Map,r=mr();try{for(let n in r){if(n==="system")continue;let s;for(let u in r[n]){s=r[n][u].primaryStore.path;break}if(!s){console.log("Couldn't find any tables in database",n);continue}let i=(0,Sf.join)(e,"backup",n+".mdb"),o=(0,Sf.join)(e,Ai.DATABASES_DIR_NAME,n+"-copy.mdb"),c=await pU(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 AU(n,o),console.log("Backing up",n,"to",i),await(0,mo.move)(s,i,{overwrite:!0})}ku();for(let[n,{db_path:s,copy_dest:i}]of t)console.log("Moving copy compacted",n,"to",s),await(0,mo.move)(i,s,{overwrite:!0}),await(0,mo.remove)((0,Sf.join)(e,Ai.DATABASES_DIR_NAME,`${n}-copy.mdb-lock`));ku()}catch(n){Vu.error("Error compacting database, rolling back operation",n),console.error("Error compacting database, rolling back operation",n),(0,ig.updateConfigValue)(Ai.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,mo.move)(o,i,{overwrite:!0})}catch(c){console.error(c)}}throw ku(),n}for(let[n,{backup_dest:s,record_count:i}]of t){let o=!0,c=await pU(n);if(console.log("Database",n,"after compact has a total record count of",c),i!==c){o=!1;let u=`There is a discrepancy between pre and post compact record count for database ${n}.
|
|
11
11
|
Total record count before compaction: ${i}, total after: ${c}.
|
|
12
|
-
Database backup has not been removed and can be found here: ${s}`;
|
|
13
|
-
${r.stack}`;throw lg.error(n),LU(new Error)}}}a(O9,"getRolePermissions");function b9(e,t){let r=Object.create(null);r.super_user=!1;let n=e.permission;r[Nr.SYSTEM_SCHEMA_NAME]=n[Nr.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]=y9(t[i]);return}r[i]=vU(),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],u=t[i][o],_=N9(c,u);r[i].describe||HU.forEach(l=>{_[l]&&(r[i].describe=!0)}),r[i].tables[o]=_}else r[i].tables[o]=_g()})):Object.keys(t[i]).forEach(o=>{r[i].tables[o]=_g()})}),r}a(b9,"translateRolePermissions");function y9(e){let t=vU(!0);return Object.keys(e).forEach(r=>{t.tables[r]=_g(!0,!0,!0,!0,!0)}),t}a(y9,"createStructureUserPermissions");function N9(e,t){let{attribute_permissions:r}=e;if(r.length>0){let s=Object.assign({},e);s.attribute_permissions=[];let i=r.reduce((_,l)=>{let{attribute_name:d}=l,E=l;return Nr.TIME_STAMP_NAMES.includes(d)&&(E=PU(d,l[Ku])),_[d]=E,_},{}),o=t.primaryKey||t.hash_attribute,c=!!i[o],u=MU(o);return t.attributes.forEach(({attribute:_})=>{if(i[_]){let l=i[_];l.describe=GU(l),s.attribute_permissions.push(l),c||I9(l,u)}else if(_!==o){let l;Nr.TIME_STAMP_NAMES.includes(_)?l=PU(_):l=MU(_),s.attribute_permissions.push(l)}}),c||s.attribute_permissions.push(u),s.describe=UU(s),s}else return e.describe=UU(e),e}a(N9,"getTableAttrPerms");function UU(e){return HU.filter(t=>e[t]).length>0}a(UU,"getSchemaTableDescribePerm");function GU(e){return xU.filter(t=>e[t]).length>0}a(GU,"getAttributeDescribePerm");function I9(e,t){xU.forEach(r=>{e[r]&&!t[r]&&(t[r]=!0,t.describe=!0)})}a(I9,"checkForHashPerms")});var kU={};qe(kU,{Resources:()=>Of,keyArrayToString:()=>Na,resetResources:()=>w9,resources:()=>Oi});function w9(){return Oi=new Of}function Na(e){return Array.isArray(e)?e[e.length-1]===null?e.slice(0,-1).join("/")+"/":e.join("/"):e}var Of,Oi,Wu=Ae(()=>{ro();Of=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,u]of this){let _=2;for(;(_=c.indexOf("/",_))>-1;){let l=this.get(c.slice(0,_));l&&(l.hasSubPaths=!0),_+=2}}}getMatch(t,r){let n=2,s;for(;(n=t.indexOf("/",n))>-1;){let c=t.slice(0,n),u=this.get(c);if(u){if(u.relativeURL=t.slice(n),!u.hasSubPaths)return u;s=u}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 Xe(r,async()=>{let s=this.getMatch(t);if(s)return t=s.relativeURL,n(s.Resource,s.path,t)})}setRepresentation(t,r,n){}};a(w9,"resetResources");a(Na,"keyArrayToString")});var VU={};qe(VU,{Headers:()=>bi,appendHeader:()=>Eg});function Eg(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 bi,Qu=Ae(()=>{bi=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(Eg,"appendHeader")});var zu={};qe(zu,{authentication:()=>jU,bypassAuth:()=>v9,login:()=>H9,logout:()=>x9,start:()=>B9});function v9(){JU=!0}async function jU(e,t){let r=e.headers.asObject,n=r.authorization,s=r.cookie,i=r.origin,o=[];try{if(i){let f=e.isOperationsServer?M9?L9:[]:D9?C9:[];if(f.includes(i)||f.includes("*")){if(e.method==="OPTIONS"){let h=new bi([["Access-Control-Allow-Methods","POST, GET, PUT, DELETE, PATCH, OPTIONS"],["Access-Control-Allow-Headers","Accept, Content-Type, Authorization"],["Access-Control-Allow-Origin",i]]);return bf&&h.set("Access-Control-Allow-Credentials","true"),{status:200,headers:h}}o.push("Access-Control-Allow-Origin",i),bf&&o.push("Access-Control-Allow-Credentials","true")}}let u,_;if(bf){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(";");u=p.slice(f.length,S===-1?p.length:S),_=await YU.get(u);break}e.session=_||(_={})}let l=a((f,h,p)=>{let S=new Ia.AuthAuditLog(f,h,Ht.AUTH_AUDIT_TYPES.AUTHENTICATION,r["x-forwarded-for"]??e.ip,e.method,e.pathname);S.auth_strategy=p,u&&(S.session_id=u),r.referer&&(S.referer=r.referer),r.origin&&(S.origin=r.origin),h===Ht.AUTH_AUDIT_STATUS.SUCCESS?$U.notify(S):$U.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),l(f,Ht.AUTH_AUDIT_STATUS.SUCCESS,"mTLS")):(0,Ia.debug)("HTTPS/WSS mTLS authorized connection (mTLS did not authorize a user)","from",e.ip)}let d;if(!e.user)if(n){if(d=So.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 A=atob(p),R=A.indexOf(":");S=A.slice(0,R),T=A.slice(R+1),d=S||T?await st.getUser(S,T,e):null;break;case"Bearer":try{d=await(0,yf.validateOperationToken)(p)}catch(C){if(C.message==="invalid token")try{return await(0,yf.validateRefreshToken)(p),c({status:-1})}catch{throw C}}break}}catch(A){return U9&&(So.get(p)||(So.set(p,p),l(S,Ht.AUTH_AUDIT_STATUS.FAILURE,h))),c({status:401,body:To({error:A.message},e)})}So.set(n,d),P9&&l(d.username,Ht.AUTH_AUDIT_STATUS.SUCCESS,h)}e.user=d}else _?.user?e.user=await st.getUser(_.user,null,e):(JU&&(e.ip?.includes("127.0.0.1")||e.ip=="::1")||e?._nodeRequest?.socket?.server?._pipeName&&e.ip===void 0)&&(e.user=await(0,WU.getSuperUser)());bf&&(e.session.update=function(f){if(!u){u=(0,QU.v4)();let p=`${(i?i.replace(/^https?:\/\//,"").replace(/\W/,"_")+"-":"")+"hdb-session="}${u}; 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=u,YU.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")&&Oi.loginPath?(E.status=302,E.headers.set("Location",Oi.loginPath(e))):E.headers.set("WWW-Authenticate","Basic")),c(E))}catch(u){throw c(u)}function c(u){let _=o.length;if(_>0){let l=u.headers;l||(u.headers=l=new bi);for(let d=0;d<_;){let E=o[d++];l.set(E,o[d++])}}return o=null,u}a(c,"applyResponseHeaders")}function B9({server:e,port:t}){e.http(jU,{port:t||"all"}),KU||(KU=!0,setInterval(()=>{So=new Map},En.get(Ht.CONFIG_PARAMS.AUTHENTICATION_CACHETTL)).unref(),zU.user.addListener(()=>{So=new Map}))}async function H9(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 x9(e){if(!e.baseRequest.session)throw new Error("No session for logout");return await e.baseRequest.session.update({user:null}),"Logout successful"}var WU,yf,QU,En,Ht,Ia,zU,$U,C9,D9,L9,M9,YU,bf,JU,P9,U9,So,KU,Nf=Ae(()=>{WU=B(ln());ur();Wu();yf=B(yu());Oe();QU=require("uuid"),En=B(Z()),Ht=B(P()),Ia=B($()),zU=B($c());Qu();wa();$U=(0,Ia.loggerWithTag)("auth-event");En.initSync();C9=En.get(Ht.CONFIG_PARAMS.HTTP_CORSACCESSLIST),D9=En.get(Ht.CONFIG_PARAMS.HTTP_CORS),L9=En.get(Ht.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_CORSACCESSLIST),M9=En.get(Ht.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_CORS),YU=dt({table:"hdb_session",database:"system",attributes:[{name:"id",isPrimaryKey:!0},{name:"user"}]}),bf=En.get(Ht.CONFIG_PARAMS.AUTHENTICATION_ENABLESESSIONS)??!0,JU=En.get(Ht.CONFIG_PARAMS.AUTHENTICATION_AUTHORIZELOCAL)??process.env.DEV_MODE,P9=En.get(Ht.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)??!1,U9=En.get(Ht.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGFAILED)??!1,So=new Map;st.onInvalidatedUser(()=>{So=new Map});a(v9,"bypassAuth");a(jU,"authentication");a(B9,"start");a(H9,"login");a(x9,"logout")});var sv=g((ime,nv)=>{"use strict";var Ce=require("joi"),XU=require("fs-extra"),ZU=require("path"),Us=je(),ev=Z(),tv=P(),rv=$(),{hdb_errors:G9}=ne(),{HDB_ERROR_MSGS:nr}=G9,Ps=/^[a-zA-Z0-9-_]+$/;nv.exports={getDropCustomFunctionValidator:F9,setCustomFunctionValidator:k9,addComponentValidator:K9,dropCustomFunctionProjectValidator:W9,packageComponentValidator:Q9,deployComponentValidator:z9,setComponentFileValidator:V9,getComponentFileValidator:Y9,dropComponentFileValidator:$9};function If(e,t,r){try{let n=ev.get(tv.CONFIG_PARAMS.COMPONENTSROOT),s=ZU.join(n,t);return XU.existsSync(s)?e?t:r.message(nr.PROJECT_EXISTS):e?r.message(nr.NO_PROJECT):t}catch(n){return rv.error(n),r.message(nr.VALIDATION_ERR)}}a(If,"checkProjectExists");function Ju(e,t){return e.includes("..")?t.message("Invalid file path"):e}a(Ju,"checkFilePath");function q9(e,t,r,n){try{let s=ev.get(tv.CONFIG_PARAMS.COMPONENTSROOT),i=ZU.join(s,e,t,r+".js");return XU.existsSync(i)?r:n.message(nr.NO_FILE)}catch(s){return rv.error(s),n.message(nr.VALIDATION_ERR)}}a(q9,"checkFileExists");function F9(e){let t=Ce.object({project:Ce.string().pattern(Ps).custom(If.bind(null,!0)).required().messages({"string.pattern.base":nr.BAD_PROJECT_NAME}),type:Ce.string().valid("helpers","routes").required(),file:Ce.string().pattern(Ps).custom(q9.bind(null,e.project,e.type)).custom(Ju).required().messages({"string.pattern.base":nr.BAD_FILE_NAME})});return Us.validateBySchema(e,t)}a(F9,"getDropCustomFunctionValidator");function k9(e){let t=Ce.object({project:Ce.string().pattern(Ps).custom(If.bind(null,!0)).required().messages({"string.pattern.base":nr.BAD_PROJECT_NAME}),type:Ce.string().valid("helpers","routes").required(),file:Ce.string().custom(Ju).required(),function_content:Ce.string().required()});return Us.validateBySchema(e,t)}a(k9,"setCustomFunctionValidator");function V9(e){let t=Ce.object({project:Ce.string().pattern(Ps).required().messages({"string.pattern.base":nr.BAD_PROJECT_NAME}),file:Ce.string().custom(Ju).required(),payload:Ce.string().allow("").optional(),encoding:Ce.string().valid("utf8","ASCII","binary","hex","base64","utf16le","latin1","ucs2").optional()});return Us.validateBySchema(e,t)}a(V9,"setComponentFileValidator");function $9(e){let t=Ce.object({project:Ce.string().pattern(Ps).required().messages({"string.pattern.base":nr.BAD_PROJECT_NAME}),file:Ce.string().custom(Ju).optional()});return Us.validateBySchema(e,t)}a($9,"dropComponentFileValidator");function Y9(e){let t=Ce.object({project:Ce.string().required(),file:Ce.string().custom(Ju).required(),encoding:Ce.string().valid("utf8","ASCII","binary","hex","base64","utf16le","latin1","ucs2").optional()});return Us.validateBySchema(e,t)}a(Y9,"getComponentFileValidator");function K9(e){let t=Ce.object({project:Ce.string().pattern(Ps).custom(If.bind(null,!1)).required().messages({"string.pattern.base":nr.BAD_PROJECT_NAME})});return Us.validateBySchema(e,t)}a(K9,"addComponentValidator");function W9(e){let t=Ce.object({project:Ce.string().pattern(Ps).custom(If.bind(null,!0)).required().messages({"string.pattern.base":nr.BAD_PROJECT_NAME})});return Us.validateBySchema(e,t)}a(W9,"dropCustomFunctionProjectValidator");function Q9(e){let t=Ce.object({project:Ce.string().pattern(Ps).required().messages({"string.pattern.base":nr.BAD_PROJECT_NAME}),skip_node_modules:Ce.boolean()});return Us.validateBySchema(e,t)}a(Q9,"packageComponentValidator");function z9(e){let t=Ce.object({project:Ce.string().pattern(Ps).required().messages({"string.pattern.base":nr.BAD_PROJECT_NAME}),payload:Ce.string().optional().messages({"string.pattern.base":nr.BAD_PACKAGE}),package:Ce.string().optional()});return Us.validateBySchema(e,t)}a(z9,"deployComponentValidator")});var Lf=g((ame,_v)=>{"use strict";var wf=require("joi"),Cf=require("path"),iv=require("fs-extra"),{exec:J9}=require("child_process"),j9=require("util"),ov=j9.promisify(J9),ju=P(),{handleHDBError:Ca,hdb_errors:X9}=ne(),{HTTP_STATUS_CODES:Da}=X9,Xu=Z(),Z9=je(),La=$();Xu.initSync();var hg=Xu.get(ju.CONFIG_PARAMS.COMPONENTSROOT),av="npm install --omit=dev --json",e7=`${av} --dry-run`;_v.exports={installModules:s7,auditModules:i7,installAllRootModules:t7,uninstallRootModule:r7,linkHarperdb:n7};async function t7(e=!1){await Df(),await Zu(e?"npm install --ignore-scripts":"npm install",Xu.get(ju.CONFIG_PARAMS.ROOTPATH))}a(t7,"installAllRootModules");async function r7(e){await Zu(`npm uninstall ${e}`,Xu.get(ju.CONFIG_PARAMS.ROOTPATH))}a(r7,"uninstallRootModule");async function n7(){await Df(),await Zu(`npm link ${ju.PACKAGE_ROOT}`,Xu.get(ju.CONFIG_PARAMS.ROOTPATH))}a(n7,"linkHarperdb");async function Zu(e,t=void 0){let r,n;try{({stdout:r,stderr:n}=await ov(e,{cwd:t}))}catch(s){throw new Error(s.stderr.replace(`
|
|
14
|
-
`,""))}return n&&!n.includes("Debugger listening")&&
|
|
15
|
-
`,"")}a(
|
|
12
|
+
Database backup has not been removed and can be found here: ${s}`;Vu.error(u),console.error(u)}(0,sg.get)(Ai.CONFIG_PARAMS.STORAGE_COMPACTONSTARTKEEPBACKUP)===!0||o===!1||(console.log("Removing backup",s),await(0,mo.remove)(s))}(0,ig.updateConfigValue)(Ai.CONFIG_PARAMS.STORAGE_COMPACTONSTART,!1)}async function pU(e){let t=await(0,RU.describeSchema)({database:e}),r=0;for(let n in t)r+=t[n].record_count;return r}async function AU(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,SU.open)(new TU.default(t)),c=o.openDB(Tf.INTERNAL_DBIS_NAME),u,_=0,l=s.useReadTransaction();try{for(let{key:f,value:h}of s.getRange({transaction:l})){let p=h.is_hash_attribute||h.isPrimaryKey,S,T;if(p&&(S=h.compression,T=Rf(),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 gU.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,l)}let d=n.openDB(Tf.AUDIT_STORE_NAME,gf);console.log("copying audit log"),E(i,d,!1,l);async function E(f,h,p,S){let T=0,R=0;for(let{key:b,value:C,version:x}of f.getRange({start:null,versions:p,transaction:S}))u=h.put(b,C,x),T++,S.openTimer&&(S.openTimer=0),R+=(b?.length||10)+C.length,_++>5e3&&(await u,console.log("copied",T,"entries",R,"bytes"),_=0);console.log("finish copying, copied",T,"entries",R,"bytes")}a(E,"copyDbi"),await u,console.log("copied database "+e+" to "+t)}finally{l.done(),o.close()}}var SU,Sf,mo,sg,TU,gU,Tf,Ai,RU,ig,Vu,bU=Re(()=>{Ae();SU=require("lmdb"),Sf=require("path"),mo=require("fs-extra"),sg=B(Z()),TU=B(Pc()),gU=B(Mc()),Tf=B(ft()),Ai=B(P());ti();RU=B(Os()),ig=B(Er()),Vu=B($());a(d9,"compactOnStart");a(pU,"getTotalDBRecordCount");a(AU,"copyDb")});var Wu=g((Jhe,DU)=>{"use strict";var f9=require("minimist"),{isMainThread:cg,parentPort:og,threadId:Qhe}=require("worker_threads"),nt=P(),{PROCESS_DESCRIPTORS_VALIDATE:$u}=nt,os=$(),ug=z(),Of=eg(),Af=ut(),zhe=Ve(),IU=Er(),as=mU(),yU=ga(),{compactOnStart:E9}=(bU(),ie(OU)),h9=vh(),{restartWorkers:bf,onMessageByType:m9}=We(),{handleHDBError:p9,hdb_errors:S9}=ne(),{HTTP_STATUS_CODES:T9}=S9,Ku=Z();Ku.initSync();var Yu=`Restarting HarperDB. This may take up to ${nt.RESTART_TIMEOUT_MS/1e3} seconds.`,g9="Restart is not available from the CLI when running in non-pm2 mode. Either call restart from the API or stop and start HarperDB.",NU="Clustering is not enabled so cannot be restarted",R9="Invalid service",Na,fn;DU.exports={restart:wU,restartService:lg};cg&&m9(nt.ITC_EVENT_TYPES.RESTART,async(e,t)=>{e.workerType?await lg({service:e.workerType}):wU({operation:"restart"}),t.postMessage({type:"restart-complete"})});async function wU(e){fn=Object.keys(e).length===0,Na=await as.isServiceRegistered(nt.HDB_PROC_DESCRIPTOR);let t=f9(process.argv);if(t.service){await lg(t);return}if(fn&&!Na){console.error(g9);return}if(fn&&console.log(Yu),Na){as.enterPM2Mode(),os.notify(Yu);let r=h9(Object.keys(nt.CONFIG_PARAM_MAP),!0);return ug.isEmptyOrZeroLength(Object.keys(r))||IU.updateConfigValue(void 0,void 0,r,!0,!0),A9(),Yu}return cg?(os.notify(Yu),Ku.get(nt.CONFIG_PARAMS.STORAGE_COMPACTONSTART)&&await E9(),setTimeout(()=>{bf()},50)):og.postMessage({type:nt.ITC_EVENT_TYPES.RESTART}),Yu}a(wU,"restart");async function lg(e){let{service:t}=e;if(nt.PROCESS_DESCRIPTORS_VALIDATE[t]===void 0)throw p9(new Error,R9,T9.BAD_REQUEST,void 0,void 0,!0);if(Na=await as.isServiceRegistered(nt.HDB_PROC_DESCRIPTOR),!cg)return og.postMessage({type:nt.ITC_EVENT_TYPES.RESTART,workerType:t}),new Promise(n=>{og.on("message",s=>{s.type==="restart-complete"&&n()})});let r;switch(t){case $u.clustering:if(!Ku.get(nt.CONFIG_PARAMS.CLUSTERING_ENABLED)){r=NU;break}fn&&console.log("Restarting clustering"),os.notify("Restarting clustering"),await CU();break;case $u.clustering_config:case $u["clustering config"]:if(!Ku.get(nt.CONFIG_PARAMS.CLUSTERING_ENABLED)){r=NU;break}fn&&console.log("Restarting clustering_config"),os.notify("Restarting clustering_config"),await as.reloadClustering();break;case"custom_functions":case"custom functions":case $u.harperdb:case $u.http_workers:if(fn&&!Na){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}fn&&console.log("Restarting http_workers"),os.notify("Restarting http_workers"),fn?await as.restart(nt.HDB_PROC_DESCRIPTOR):await bf("http");break;default:r=`Unrecognized service: ${t}`;break}return r?(os.error(r),fn&&console.error(r),r):(t==="custom_functions"&&(t="Custom Functions"),`Restarting ${t}`)}a(lg,"restartService");async function A9(){await CU(),await as.restart(nt.HDB_PROC_DESCRIPTOR),await ug.async_set_timeout(2e3),Ku.get(nt.CONFIG_PARAMS.CLUSTERING_ENABLED)&&await ag(),fn&&(await Af.closeConnection(),process.exit(0))}a(A9,"restartPM2Mode");async function CU(){if(!IU.getConfigFromFile(nt.CONFIG_PARAMS.CLUSTERING_ENABLED))return;if((await yU.getHDBProcessInfo()).clustering.length===0)os.trace("Clustering not running, restart will start clustering services"),await Of.generateNatsConfig(!0),await as.startClusteringProcesses(),await as.startClusteringThreads(),await ag(),fn&&await Af.closeConnection();else{await Of.generateNatsConfig(!0),Na?(os.trace("Restart clustering restarting PM2 managed Hub and Leaf servers"),await as.restart(nt.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await as.restart(nt.PROCESS_DESCRIPTORS.CLUSTERING_LEAF)):(await yU.getHDBProcessInfo()).clustering.forEach(s=>{os.trace("Restart clustering killing process pid",s.pid),process.kill(s.pid)}),await ug.async_set_timeout(3e3),await ag(),await Af.updateLocalStreams(),fn&&await Af.closeConnection(),os.trace("Restart clustering restarting ingest and reply service threads");let t=bf(nt.LAUNCH_SERVICE_SCRIPTS.NATS_INGEST_SERVICE),r=bf(nt.LAUNCH_SERVICE_SCRIPTS.NATS_REPLY_SERVICE);await t,await r}}a(CU,"restartClustering");async function ag(){await Of.removeNatsConfig(nt.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await Of.removeNatsConfig(nt.PROCESS_DESCRIPTORS.CLUSTERING_LEAF)}a(ag,"removeNatsConfig")});var FU=g((Zhe,qU)=>{"use strict";var Xhe=require("lodash"),Ir=P(),{handleHDBError:LU,hdb_errors:O9}=ne(),{HDB_ERROR_MSGS:b9,HTTP_STATUS_CODES:y9}=O9,_g=$();qU.exports={getRolePermissions:I9};var po=Object.create(null),N9=a(e=>({key:e,perms:{}}),"perms_template_obj"),vU=a((e=!1)=>({describe:e,tables:{}}),"schema_perms_template"),BU=a((e=!1,t=!1,r=!1,n=!1)=>({[Ir.PERMS_CRUD_ENUM.READ]:e,[Ir.PERMS_CRUD_ENUM.INSERT]:t,[Ir.PERMS_CRUD_ENUM.UPDATE]:r,[Ir.PERMS_CRUD_ENUM.DELETE]:n}),"permissions_template"),dg=a((e=!1,t=!1,r=!1,n=!1,s=!1)=>({attribute_permissions:[],describe:e,...BU(t,r,n,s)}),"table_perms_template"),MU=a((e,t=BU())=>({attribute_name:e,describe:GU(t),[Qu]:t[Qu],[fg]:t[fg],[Eg]:t[Eg]}),"attr_perms_template"),PU=a((e,t=!1)=>({attribute_name:e,describe:t,[Qu]:t}),"timestamp_attr_perms_template"),{READ:Qu,INSERT:fg,UPDATE:Eg}=Ir.PERMS_CRUD_ENUM,xU=Object.values(Ir.PERMS_CRUD_ENUM),HU=[Qu,fg,Eg];function I9(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[Ir.SYSTEM_SCHEMA_NAME],t=e.role;let n=JSON.stringify([e.__updatedtime__,r]);if(po[t]&&po[t].key===n)return po[t].perms;let s=w9(e,r);return po[t]?po[t].key=n:po[t]=N9(n),po[t].perms=s,s}catch(r){if(!e[Ir.TIME_STAMP_NAMES_ENUM.UPDATED_TIME]||e[Ir.TIME_STAMP_NAMES_ENUM.UPDATED_TIME]<Ir.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 _g.error(n),_g.debug(r),LU(new Error,b9.OUTDATED_PERMS_TRANSLATION_ERROR,y9.BAD_REQUEST)}else{let n=`There was an error while translating role permissions for role: ${t}.
|
|
13
|
+
${r.stack}`;throw _g.error(n),LU(new Error)}}}a(I9,"getRolePermissions");function w9(e,t){let r=Object.create(null);r.super_user=!1;let n=e.permission;r[Ir.SYSTEM_SCHEMA_NAME]=n[Ir.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]=C9(t[i]);return}r[i]=vU(),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],u=t[i][o],_=D9(c,u);r[i].describe||xU.forEach(l=>{_[l]&&(r[i].describe=!0)}),r[i].tables[o]=_}else r[i].tables[o]=dg()})):Object.keys(t[i]).forEach(o=>{r[i].tables[o]=dg()})}),r}a(w9,"translateRolePermissions");function C9(e){let t=vU(!0);return Object.keys(e).forEach(r=>{t.tables[r]=dg(!0,!0,!0,!0,!0)}),t}a(C9,"createStructureUserPermissions");function D9(e,t){let{attribute_permissions:r}=e;if(r.length>0){let s=Object.assign({},e);s.attribute_permissions=[];let i=r.reduce((_,l)=>{let{attribute_name:d}=l,E=l;return Ir.TIME_STAMP_NAMES.includes(d)&&(E=PU(d,l[Qu])),_[d]=E,_},{}),o=t.primaryKey||t.hash_attribute,c=!!i[o],u=MU(o);return t.attributes.forEach(({attribute:_})=>{if(i[_]){let l=i[_];l.describe=GU(l),s.attribute_permissions.push(l),c||L9(l,u)}else if(_!==o){let l;Ir.TIME_STAMP_NAMES.includes(_)?l=PU(_):l=MU(_),s.attribute_permissions.push(l)}}),c||s.attribute_permissions.push(u),s.describe=UU(s),s}else return e.describe=UU(e),e}a(D9,"getTableAttrPerms");function UU(e){return xU.filter(t=>e[t]).length>0}a(UU,"getSchemaTableDescribePerm");function GU(e){return HU.filter(t=>e[t]).length>0}a(GU,"getAttributeDescribePerm");function L9(e,t){HU.forEach(r=>{e[r]&&!t[r]&&(t[r]=!0,t.describe=!0)})}a(L9,"checkForHashPerms")});var kU={};Fe(kU,{Resources:()=>yf,keyArrayToString:()=>Ia,resetResources:()=>M9,resources:()=>Oi});function M9(){return Oi=new yf}function Ia(e){return Array.isArray(e)?e[e.length-1]===null?e.slice(0,-1).join("/")+"/":e.join("/"):e}var yf,Oi,zu=Re(()=>{ro();yf=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,u]of this){let _=2;for(;(_=c.indexOf("/",_))>-1;){let l=this.get(c.slice(0,_));l&&(l.hasSubPaths=!0),_+=2}}}getMatch(t,r){let n=2,s;for(;(n=t.indexOf("/",n))>-1;){let c=t.slice(0,n),u=this.get(c);if(u){if(u.relativeURL=t.slice(n),!u.hasSubPaths)return u;s=u}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 Ze(r,async()=>{let s=this.getMatch(t);if(s)return t=s.relativeURL,n(s.Resource,s.path,t)})}setRepresentation(t,r,n){}};a(M9,"resetResources");a(Ia,"keyArrayToString")});var VU={};Fe(VU,{Headers:()=>bi,appendHeader:()=>hg});function hg(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 bi,Ju=Re(()=>{bi=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(hg,"appendHeader")});var ju={};Fe(ju,{authentication:()=>jU,bypassAuth:()=>G9,login:()=>F9,logout:()=>k9,start:()=>q9});function G9(){JU=!0}async function jU(e,t){let r=e.headers.asObject,n=r.authorization,s=r.cookie,i=r.origin,o=[];try{if(i){let f=e.isOperationsServer?B9?v9:[]:U9?P9:[];if(f.includes(i)||f.includes("*")){if(e.method==="OPTIONS"){let h=new bi([["Access-Control-Allow-Methods","POST, GET, PUT, DELETE, PATCH, OPTIONS"],["Access-Control-Allow-Headers","Accept, Content-Type, Authorization"],["Access-Control-Allow-Origin",i]]);return Nf&&h.set("Access-Control-Allow-Credentials","true"),{status:200,headers:h}}o.push("Access-Control-Allow-Origin",i),Nf&&o.push("Access-Control-Allow-Credentials","true")}}let u,_;if(Nf){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(";");u=p.slice(f.length,S===-1?p.length:S),_=await YU.get(u);break}e.session=_||(_={})}let l=a((f,h,p)=>{let S=new wa.AuthAuditLog(f,h,Ht.AUTH_AUDIT_TYPES.AUTHENTICATION,r["x-forwarded-for"]??e.ip,e.method,e.pathname);S.auth_strategy=p,u&&(S.session_id=u),r.referer&&(S.referer=r.referer),r.origin&&(S.origin=r.origin),h===Ht.AUTH_AUDIT_STATUS.SUCCESS?$U.notify(S):$U.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 at.getUser(f,null,null),l(f,Ht.AUTH_AUDIT_STATUS.SUCCESS,"mTLS")):(0,wa.debug)("HTTPS/WSS mTLS authorized connection (mTLS did not authorize a user)","from",e.ip)}let d;if(!e.user)if(n){if(d=So.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 at.getUser(S,T,e):null;break;case"Bearer":try{d=await(0,If.validateOperationToken)(p)}catch(C){if(C.message==="invalid token")try{return await(0,If.validateRefreshToken)(p),c({status:-1})}catch{throw C}}break}}catch(R){return H9&&(So.get(p)||(So.set(p,p),l(S,Ht.AUTH_AUDIT_STATUS.FAILURE,h))),c({status:401,body:To({error:R.message},e)})}So.set(n,d),x9&&l(d.username,Ht.AUTH_AUDIT_STATUS.SUCCESS,h)}e.user=d}else _?.user?e.user=await at.getUser(_.user,null,e):(JU&&(e.ip?.includes("127.0.0.1")||e.ip=="::1")||e?._nodeRequest?.socket?.server?._pipeName&&e.ip===void 0)&&(e.user=await(0,WU.getSuperUser)());Nf&&(e.session.update=function(f){if(!u){u=(0,QU.v4)();let p=`${(i?i.replace(/^https?:\/\//,"").replace(/\W/,"_")+"-":"")+"hdb-session="}${u}; 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=u,YU.put(f)},e.login=async function(f,h){e.user=await at.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")&&Oi.loginPath?(E.status=302,E.headers.set("Location",Oi.loginPath(e))):E.headers.set("WWW-Authenticate","Basic")),c(E))}catch(u){throw c(u)}function c(u){let _=o.length;if(_>0){let l=u.headers;l||(u.headers=l=new bi);for(let d=0;d<_;){let E=o[d++];l.set(E,o[d++])}}return o=null,u}a(c,"applyResponseHeaders")}function q9({server:e,port:t}){e.http(jU,{port:t||"all"}),KU||(KU=!0,setInterval(()=>{So=new Map},En.get(Ht.CONFIG_PARAMS.AUTHENTICATION_CACHETTL)).unref(),zU.user.addListener(()=>{So=new Map}))}async function F9(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 k9(e){if(!e.baseRequest.session)throw new Error("No session for logout");return await e.baseRequest.session.update({user:null}),"Logout successful"}var WU,If,QU,En,Ht,wa,zU,$U,P9,U9,v9,B9,YU,Nf,JU,x9,H9,So,KU,wf=Re(()=>{WU=B(ln());lr();zu();If=B(Nu());Ae();QU=require("uuid"),En=B(Z()),Ht=B(P()),wa=B($()),zU=B(Kc());Ju();Ca();$U=(0,wa.loggerWithTag)("auth-event");En.initSync();P9=En.get(Ht.CONFIG_PARAMS.HTTP_CORSACCESSLIST),U9=En.get(Ht.CONFIG_PARAMS.HTTP_CORS),v9=En.get(Ht.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_CORSACCESSLIST),B9=En.get(Ht.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_CORS),YU=Et({table:"hdb_session",database:"system",attributes:[{name:"id",isPrimaryKey:!0},{name:"user"}]}),Nf=En.get(Ht.CONFIG_PARAMS.AUTHENTICATION_ENABLESESSIONS)??!0,JU=En.get(Ht.CONFIG_PARAMS.AUTHENTICATION_AUTHORIZELOCAL)??process.env.DEV_MODE,x9=En.get(Ht.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)??!1,H9=En.get(Ht.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGFAILED)??!1,So=new Map;at.onInvalidatedUser(()=>{So=new Map});a(G9,"bypassAuth");a(jU,"authentication");a(q9,"start");a(F9,"login");a(k9,"logout")});var sv=g((lme,nv)=>{"use strict";var Ce=require("joi"),XU=require("fs-extra"),ZU=require("path"),vs=Xe(),ev=Z(),tv=P(),rv=$(),{hdb_errors:V9}=ne(),{HDB_ERROR_MSGS:ir}=V9,Us=/^[a-zA-Z0-9-_]+$/;nv.exports={getDropCustomFunctionValidator:Y9,setCustomFunctionValidator:K9,addComponentValidator:J9,dropCustomFunctionProjectValidator:j9,packageComponentValidator:X9,deployComponentValidator:Z9,setComponentFileValidator:W9,getComponentFileValidator:z9,dropComponentFileValidator:Q9};function Cf(e,t,r){try{let n=ev.get(tv.CONFIG_PARAMS.COMPONENTSROOT),s=ZU.join(n,t);return XU.existsSync(s)?e?t:r.message(ir.PROJECT_EXISTS):e?r.message(ir.NO_PROJECT):t}catch(n){return rv.error(n),r.message(ir.VALIDATION_ERR)}}a(Cf,"checkProjectExists");function Xu(e,t){return e.includes("..")?t.message("Invalid file path"):e}a(Xu,"checkFilePath");function $9(e,t,r,n){try{let s=ev.get(tv.CONFIG_PARAMS.COMPONENTSROOT),i=ZU.join(s,e,t,r+".js");return XU.existsSync(i)?r:n.message(ir.NO_FILE)}catch(s){return rv.error(s),n.message(ir.VALIDATION_ERR)}}a($9,"checkFileExists");function Y9(e){let t=Ce.object({project:Ce.string().pattern(Us).custom(Cf.bind(null,!0)).required().messages({"string.pattern.base":ir.BAD_PROJECT_NAME}),type:Ce.string().valid("helpers","routes").required(),file:Ce.string().pattern(Us).custom($9.bind(null,e.project,e.type)).custom(Xu).required().messages({"string.pattern.base":ir.BAD_FILE_NAME})});return vs.validateBySchema(e,t)}a(Y9,"getDropCustomFunctionValidator");function K9(e){let t=Ce.object({project:Ce.string().pattern(Us).custom(Cf.bind(null,!0)).required().messages({"string.pattern.base":ir.BAD_PROJECT_NAME}),type:Ce.string().valid("helpers","routes").required(),file:Ce.string().custom(Xu).required(),function_content:Ce.string().required()});return vs.validateBySchema(e,t)}a(K9,"setCustomFunctionValidator");function W9(e){let t=Ce.object({project:Ce.string().pattern(Us).required().messages({"string.pattern.base":ir.BAD_PROJECT_NAME}),file:Ce.string().custom(Xu).required(),payload:Ce.string().allow("").optional(),encoding:Ce.string().valid("utf8","ASCII","binary","hex","base64","utf16le","latin1","ucs2").optional()});return vs.validateBySchema(e,t)}a(W9,"setComponentFileValidator");function Q9(e){let t=Ce.object({project:Ce.string().pattern(Us).required().messages({"string.pattern.base":ir.BAD_PROJECT_NAME}),file:Ce.string().custom(Xu).optional()});return vs.validateBySchema(e,t)}a(Q9,"dropComponentFileValidator");function z9(e){let t=Ce.object({project:Ce.string().required(),file:Ce.string().custom(Xu).required(),encoding:Ce.string().valid("utf8","ASCII","binary","hex","base64","utf16le","latin1","ucs2").optional()});return vs.validateBySchema(e,t)}a(z9,"getComponentFileValidator");function J9(e){let t=Ce.object({project:Ce.string().pattern(Us).custom(Cf.bind(null,!1)).required().messages({"string.pattern.base":ir.BAD_PROJECT_NAME})});return vs.validateBySchema(e,t)}a(J9,"addComponentValidator");function j9(e){let t=Ce.object({project:Ce.string().pattern(Us).custom(Cf.bind(null,!0)).required().messages({"string.pattern.base":ir.BAD_PROJECT_NAME})});return vs.validateBySchema(e,t)}a(j9,"dropCustomFunctionProjectValidator");function X9(e){let t=Ce.object({project:Ce.string().pattern(Us).required().messages({"string.pattern.base":ir.BAD_PROJECT_NAME}),skip_node_modules:Ce.boolean()});return vs.validateBySchema(e,t)}a(X9,"packageComponentValidator");function Z9(e){let t=Ce.object({project:Ce.string().pattern(Us).required().messages({"string.pattern.base":ir.BAD_PROJECT_NAME}),payload:Ce.string().optional().messages({"string.pattern.base":ir.BAD_PACKAGE}),package:Ce.string().optional()});return vs.validateBySchema(e,t)}a(Z9,"deployComponentValidator")});var Pf=g((dme,_v)=>{"use strict";var Df=require("joi"),Lf=require("path"),iv=require("fs-extra"),{exec:e7}=require("child_process"),t7=require("util"),ov=t7.promisify(e7),Zu=P(),{handleHDBError:Da,hdb_errors:r7}=ne(),{HTTP_STATUS_CODES:La}=r7,el=Z(),n7=Xe(),Ma=$();el.initSync();var mg=el.get(Zu.CONFIG_PARAMS.COMPONENTSROOT),av="npm install --omit=dev --json",s7=`${av} --dry-run`;_v.exports={installModules:c7,auditModules:u7,installAllRootModules:i7,uninstallRootModule:o7,linkHarperdb:a7};async function i7(e=!1){await Mf(),await tl(e?"npm install --ignore-scripts":"npm install",el.get(Zu.CONFIG_PARAMS.ROOTPATH))}a(i7,"installAllRootModules");async function o7(e){await tl(`npm uninstall ${e}`,el.get(Zu.CONFIG_PARAMS.ROOTPATH))}a(o7,"uninstallRootModule");async function a7(){await Mf(),await tl(`npm link ${Zu.PACKAGE_ROOT}`,el.get(Zu.CONFIG_PARAMS.ROOTPATH))}a(a7,"linkHarperdb");async function tl(e,t=void 0){let r,n;try{({stdout:r,stderr:n}=await ov(e,{cwd:t}))}catch(s){throw new Error(s.stderr.replace(`
|
|
14
|
+
`,""))}return n&&!n.includes("Debugger listening")&&Ma.error("Error running NPM command:",e,n),Ma.trace(r,n),r?.replace(`
|
|
15
|
+
`,"")}a(tl,"runCommand");async function c7(e){Ma.info(`starting installModules for request: ${e}`);let t=lv(e);if(t)throw Da(t,t.message,La.BAD_REQUEST);let{projects:r,dry_run:n}=e,s=n===!0?s7:av;await Mf(),await uv(r);let i={};for(let o=0,c=r.length;o<c;o++){let u=r[o];i[u]={npm_output:null,npm_error:null};let _=Lf.join(mg,u),l,d=null;try{let{stdout:E,stderr:f}=await ov(s,{cwd:_});l=E?E.replace(`
|
|
16
16
|
`,""):null,d=f?f.replace(`
|
|
17
|
-
`,""):null}catch(E){E.stderr?i[u].npm_error=cv(E.stderr):i[u].npm_error=E.message;continue}try{i[u].npm_output=JSON.parse(l)}catch{i[u].npm_output=l}try{i[u].npm_error=JSON.parse(d)}catch{i[u].npm_error=d}}return
|
|
18
|
-
`);return r>-1&&n>-1?JSON.parse(e.substring(r+t.length-1,n+1)):e}a(cv,"parseNPMStdErr");async function i7(e){La.info(`starting auditModules for request: ${e}`);let t=lv(e);if(t)throw Ca(t,t.message,Da.BAD_REQUEST);let{projects:r}=e;await Df(),await uv(r);let n={};for(let s=0,i=r.length;s<i;s++){let o=r[s],c=Cf.join(hg,o);n[o]={npm_output:null,npm_error:null};try{let u=await Zu("npm audit --json",c);n[o].npm_output=JSON.parse(u)}catch(u){n[o].npm_error=cv(u.stderr)}}return La.info(`finished auditModules with response ${n}`),n}a(i7,"auditModules");async function Df(){try{return await Zu("npm -v"),!0}catch{throw Ca(new Error,"Unable to install project dependencies: npm is not installed on this instance of HarperDB.",Da.BAD_REQUEST,void 0,void 0,!0)}}a(Df,"checkNPMInstalled");async function uv(e){if(!Array.isArray(e)||e.length===0)throw Ca(new Error,"projects argument must be an array with at least 1 element",Da.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=Cf.join(hg,i.toString());if(!await iv.pathExists(o)){t.push(i);continue}let u=Cf.join(o,"package.json");await iv.pathExists(u)||r.push(i)}if(t.length>0)throw Ca(new Error,`Unable to install project dependencies: custom function projects '${t.join(",")}' does not exist.`,Da.BAD_REQUEST,void 0,void 0,!0);if(r.length>0)throw Ca(new Error,`Unable to install project dependencies: custom function projects '${r.join(",")}' do not have a package.json file.`,Da.BAD_REQUEST,void 0,void 0,!0)}a(uv,"checkProjectPaths");function lv(e){let t=wf.object({projects:wf.array().min(1).items(wf.string()).required(),dry_run:wf.boolean().default(!1)});return Z9.validateBySchema(e,t)}a(lv,"modulesValidator")});var pg=g((ume,mv)=>{"use strict";var Ma=require("fs-extra"),mg=require("path"),Mf=$(),dv=J(),Pf=P(),hv=Z(),o7=fr();mv.exports=a7;async function a7(){let e=c7(),t=hv.get(Pf.CONFIG_PARAMS.ROOTPATH),r=mg.join(t,"package.json"),n={dependencies:{harperdb:"file:"+Pf.PACKAGE_ROOT}},s=mg.join(t,"node_modules");await Ma.ensureDir(s);let i,o=!0,c=!1;try{i=await Ma.readJson(r)}catch(u){if(dv.isEmptyOrZeroLength(e))return;if(u.code!==Pf.NODE_ERROR_CODES.ENOENT)throw u;o=!1}if(!dv.isEmptyOrZeroLength(e)){for(let{name:u,package:_}of e){let l=await fv(_);n.dependencies[u]=l+_}if(!o){Mf.notify("Installing components"),await Ev(r,n,null);return}for(let{name:u,package:_}of e){let l=i.dependencies[u],d=await fv(_);if(l===void 0||l!==d+_){c=!0;break}}}for(let u in i.dependencies)n.dependencies[u]===void 0&&(Mf.notify("Removing component",u),c=!0);c&&(Mf.notify("Updating components."),await Ev(r,n,i))}a(a7,"installComponents");function c7(){let e=o7.getConfiguration(),t=[];for(let r in e)e[r]?.package&&t.push(Object.assign(e[r],{name:r}));return t}a(c7,"getComponentsConfig");async function fv(e){return e.includes(":")?"":e.startsWith("@")||!e.startsWith("@")&&!e.includes("/")?"npm:":mg.extname(e)||await Ma.pathExists(e)?"file:":"github:"}a(fv,"getPkgPrefix");async function Ev(e,t,r){Mf.trace("npm installing components package.json",t),await Ma.writeFile(e,JSON.stringify(t,null," "));try{await Lf().installAllRootModules(hv.get(Pf.CONFIG_PARAMS.IGNORE_SCRIPTS)===!0)}catch(n){throw r?await Ma.writeFile(e,JSON.stringify(r,null," ")):await Ma.unlink(e),n}}a(Ev,"installPackages")});var gg=g((dme,gv)=>{"use strict";var Ve=require("fs-extra"),Sg=require("fast-glob"),Re=require("path"),Sv=require("tar-fs"),_me=require("uuid").v4,Tg=require("normalize-path"),as=sv(),wt=$(),We=P(),Rt=Z(),el=fr(),u7=J(),{PACKAGE_ROOT:l7}=P(),{handleHDBError:xt,hdb_errors:_7}=ne(),{basename:d7}=require("path"),f7=pg(),Tv=Z(),E7=P(),{Readable:h7}=require("stream"),{isMainThread:m7}=require("worker_threads"),{HDB_ERROR_MSGS:go,HTTP_STATUS_CODES:Gt}=_7,p7=Re.join(l7,"application-template"),pv=Re.join(Rt.get(We.HDB_SETTINGS_NAMES.HDB_ROOT_KEY),"tmp");function S7(){wt.trace("getting custom api status");let e={};try{e={port:Rt.get(We.CONFIG_PARAMS.HTTP_PORT),directory:Rt.get(We.CONFIG_PARAMS.COMPONENTSROOT),is_enabled:!0}}catch(t){throw xt(new Error,go.FUNCTION_STATUS,Gt.INTERNAL_SERVER_ERROR,wt.ERR,t)}return e}a(S7,"customFunctionsStatus");function T7(){wt.trace("getting custom api endpoints");let e={},t=Rt.get(We.CONFIG_PARAMS.COMPONENTSROOT);try{Sg.sync(Tg(`${t}/*`),{onlyDirectories:!0}).forEach(n=>{let s=n.split("/").pop();e[s]={routes:Sg.sync(Tg(`${n}/routes/*.js`)).map(i=>i.split("/").pop().split(".js")[0]),helpers:Sg.sync(Tg(`${n}/helpers/*.js`)).map(i=>i.split("/").pop().split(".js")[0])}})}catch(r){throw xt(new Error,go.GET_FUNCTIONS,Gt.INTERNAL_SERVER_ERROR,wt.ERR,r)}return e}a(T7,"getCustomFunctions");function g7(e){e.project&&(e.project=Re.parse(e.project).name),e.file&&(e.file=Re.parse(e.file).name);let t=as.getDropCustomFunctionValidator(e);if(t)throw xt(t,t.message,Gt.BAD_REQUEST);wt.trace("getting custom api endpoint file content");let r=Rt.get(We.CONFIG_PARAMS.COMPONENTSROOT),{project:n,type:s,file:i}=e,o=Re.join(r,n,s,i+".js");try{return Ve.readFileSync(o,{encoding:"utf8"})}catch(c){throw xt(new Error,go.GET_FUNCTION,Gt.INTERNAL_SERVER_ERROR,wt.ERR,c)}}a(g7,"getCustomFunction");function R7(e){e.project&&(e.project=Re.parse(e.project).name),e.file&&(e.file=Re.parse(e.file).name);let t=as.setCustomFunctionValidator(e);if(t)throw xt(t,t.message,Gt.BAD_REQUEST);wt.trace("setting custom function file content");let r=Rt.get(We.CONFIG_PARAMS.COMPONENTSROOT),{project:n,type:s,file:i,function_content:o}=e;try{return Ve.outputFileSync(Re.join(r,n,s,i+".js"),o),`Successfully updated custom function: ${i}.js`}catch(c){throw xt(new Error,go.SET_FUNCTION,Gt.INTERNAL_SERVER_ERROR,wt.ERR,c)}}a(R7,"setCustomFunction");function A7(e){e.project&&(e.project=Re.parse(e.project).name),e.file&&(e.file=Re.parse(e.file).name);let t=as.getDropCustomFunctionValidator(e);if(t)throw xt(t,t.message,Gt.BAD_REQUEST);wt.trace("dropping custom function file");let r=Rt.get(We.CONFIG_PARAMS.COMPONENTSROOT),{project:n,type:s,file:i}=e;try{return Ve.unlinkSync(Re.join(r,n,s,i+".js")),`Successfully deleted custom function: ${i}.js`}catch(o){throw xt(new Error,go.DROP_FUNCTION,Gt.INTERNAL_SERVER_ERROR,wt.ERR,o)}}a(A7,"dropCustomFunction");function O7(e){e.project&&(e.project=Re.parse(e.project).name);let t=as.addComponentValidator(e);if(t)throw xt(t,t.message,Gt.BAD_REQUEST);wt.trace("adding component");let r=Rt.get(We.CONFIG_PARAMS.COMPONENTSROOT),{project:n}=e;try{let s=Re.join(r,n);return Ve.mkdirSync(s,{recursive:!0}),Ve.copySync(p7,s),`Successfully added project: ${n}`}catch(s){throw xt(new Error,go.ADD_FUNCTION,Gt.INTERNAL_SERVER_ERROR,wt.ERR,s)}}a(O7,"addComponent");function b7(e){e.project&&(e.project=Re.parse(e.project).name);let t=as.dropCustomFunctionProjectValidator(e);if(t)throw xt(t,t.message,Gt.BAD_REQUEST);wt.trace("dropping custom function project");let r=Rt.get(We.CONFIG_PARAMS.COMPONENTSROOT),{project:n}=e,s=Rt.get(We.CONFIG_PARAMS.APPS);if(!u7.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 el.updateConfigValue(We.CONFIG_PARAMS.APPS,s),`Successfully deleted project: ${n}`}try{let i=Re.join(r,n);return Ve.rmSync(i,{recursive:!0}),`Successfully deleted project: ${n}`}catch(i){throw xt(new Error,go.DROP_FUNCTION_PROJECT,Gt.INTERNAL_SERVER_ERROR,wt.ERR,i)}}a(b7,"dropCustomFunctionProject");async function y7(e){e.project&&(e.project=Re.parse(e.project).name);let t=as.packageComponentValidator(e);if(t)throw xt(t,t.message,Gt.BAD_REQUEST);let r=Rt.get(We.CONFIG_PARAMS.COMPONENTSROOT),{project:n}=e;wt.trace("packaging component",n);let s;try{s=await Ve.realpath(Re.join(r,n))}catch(u){if(u.code!==We.NODE_ERROR_CODES.ENOENT)throw u;try{s=await Ve.realpath(Re.join(Rt.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(pv);let i=Re.join(pv,`${n}.tar`),o={};(e.skip_node_modules===!0||e.skip_node_modules==="true")&&(o={ignore:u=>u.includes(Re.join(s,"node_modules"))}),Sv.pack(s,o).pipe(Ve.createWriteStream(i,{overwrite:!0})),await new Promise(u=>setTimeout(u,2e3));let c=Ve.readFileSync(i,{encoding:"base64"});return await Ve.remove(i),{project:n,payload:c}}a(y7,"packageComponent");async function N7(e){e.project&&(e.project=Re.parse(e.project).name);let t=as.deployComponentValidator(e);if(t)throw xt(t,t.message,Gt.BAD_REQUEST);let r=Rt.get(We.CONFIG_PARAMS.COMPONENTSROOT),{project:n,payload:s,package:i}=e;if(wt.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 Ve.ensureDir(o);let E=h7.from(Buffer.from(s,"base64"));await new Promise((h,p)=>{E.pipe(Sv.extract(o,{finish:h})).on("error",p)});let f=await Ve.readdir(o);f.length===1&&f[0]==="package"&&(await Ve.copy(Re.join(o,"package"),o),await Ve.remove(Re.join(o,"package")))}if(await el.addConfig(n,{package:i}),!s){await f7();let E=Tv.get(E7.CONFIG_PARAMS.ROOTPATH);o=Re.join(E,"node_modules",n)}if(m7)return;let c=new Map;c.isWorker=!0;let u=(vf(),ie(Uf)),_;u.setErrorReporter(E=>_=E);let l=d7(o),d=u.component_errors.get(l);try{await u.loadComponent(o,c)}finally{u.component_errors.set(l,d)}if(_)throw _;return wt.info("Installed component"),`Successfully deployed: ${n}`}a(N7,"deployComponent");async function I7(){let e=el.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 u=await Ve.readdir(o,{withFileTypes:!0});for(let _ of u){let l=_.name;if(l.startsWith(".")||l==="node_modules")continue;let d=Re.join(o,l);if(_.isDirectory()||_.isSymbolicLink()){let E={name:l,entries:[]};c.entries.push(E),await r(d,E)}else{let E=await Ve.stat(d),f={name:Re.basename(l),mtime:E.mtime,size:E.size};c.entries.push(f)}}return c}catch(u){return wt.warn("Error loading package",u),{error:u.toString(),entries:[]}}},"walk_dir"),n=await r(Rt.get(We.CONFIG_PARAMS.COMPONENTSROOT),{name:Rt.get(We.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(Rt.get(We.CONFIG_PARAMS.ROOTPATH),"node_modules",o.name),{name:o.name,entries:[]});Object.assign(o,c)}let i=(vf(),ie(Uf)).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(I7,"getComponents");async function w7(e){let t=as.getComponentFileValidator(e);if(t)throw xt(t,t.message,Gt.BAD_REQUEST);let n=el.getConfigObj()[e.project]||e.project==="harperdb"?Re.join(Tv.get(We.CONFIG_PARAMS.ROOTPATH),"node_modules"):Rt.get(We.CONFIG_PARAMS.COMPONENTSROOT),s=e.encoding?{encoding:e.encoding}:{encoding:"utf8"};try{let i=await Ve.stat(Re.join(n,e.project,e.file));return{message:await Ve.readFile(Re.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 '${Re.join(e.project,e.file)}'`):i}}a(w7,"getComponentFile");async function C7(e){let t=as.setComponentFileValidator(e);if(t)throw xt(t,t.message,Gt.BAD_REQUEST);let r=e.encoding?{encoding:e.encoding}:{encoding:"utf8"},n=Re.join(Rt.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(C7,"setComponentFile");async function D7(e){let t=as.dropComponentFileValidator(e);if(t)throw xt(t,t.message,Gt.BAD_REQUEST);let r=e.file?Re.join(e.project,e.file):e.project,n=Re.join(Rt.get(We.CONFIG_PARAMS.COMPONENTSROOT),r);return await Ve.pathExists(n)&&await Ve.remove(n),el.deleteConfigFromFile([e.project]),"Successfully dropped: "+r}a(D7,"dropComponent");gv.exports={customFunctionsStatus:S7,getCustomFunctions:T7,getCustomFunction:g7,setCustomFunction:R7,dropCustomFunction:A7,addComponent:O7,dropCustomFunctionProject:b7,packageComponent:y7,deployComponent:N7,getComponents:I7,getComponentFile:w7,setComponentFile:C7,dropComponent:D7}});var Rg=g((Eme,Av)=>{"use strict";var cs=require("joi"),Rv=je();Av.exports={readTransactionLogValidator:L7,deleteTransactionLogsBeforeValidator:M7};function L7(e){let t=cs.object({schema:cs.string().required(),table:cs.string().required(),from:cs.date().timestamp(),to:cs.date().timestamp(),limit:cs.number().min(1)});return Rv.validateBySchema(e,t)}a(L7,"readTransactionLogValidator");function M7(e){let t=cs.object({schema:cs.string().required(),table:cs.string().required(),timestamp:cs.date().timestamp().required()});return Rv.validateBySchema(e,t)}a(M7,"deleteTransactionLogsBeforeValidator")});var Bf=g((mme,Iv)=>{"use strict";var Ag=P(),tl=ot(),Ov=J(),bv=Z(),yv=Rs(),{handleHDBError:Pa,hdb_errors:P7}=ne(),{HTTP_STATUS_CODES:Ua}=P7,{readTransactionLogValidator:U7,deleteTransactionLogsBeforeValidator:v7}=Rg(),Nv="This operation relies on clustering and cannot run with it disable.",B7="Logs successfully deleted from transaction log.",H7="All logs successfully deleted from transaction log.";Iv.exports={readTransactionLog:x7,deleteTransactionLogsBefore:G7};async function*x7(e){let t=U7(e);if(t)throw Pa(t,t.message,Ua.BAD_REQUEST,void 0,void 0,!0);if(!bv.get(Ag.CONFIG_PARAMS.CLUSTERING_ENABLED))throw Pa(new Error,Nv,Ua.NOT_FOUND,void 0,void 0,!0);let{schema:r,table:n}=e,s=Ov.checkSchemaTableExist(r,n);if(s)throw Pa(new Error,s,Ua.NOT_FOUND,void 0,void 0,!0);let i=yv.createNatsTableStreamName(r,n),o=await tl.viewStreamIterator(i,parseInt(e.from),e.limit);for await(let c of o){let u=Math.floor(c?.nats_timestamp/1e6);if(e.to&&u>e.to)break;let _={operation:c?.entry?.operation,user:c?.entry?.__origin?.user,timestamp:u,records:c?.entry?.records,attributes:c?.entry?.attributes};c?.entry?.operation===Ag.OPERATIONS_ENUM.DELETE&&(_.hash_values=c?.entry?.hash_values),yield _}}a(x7,"readTransactionLog");async function G7(e){let t=v7(e);if(t)throw Pa(t,t.message,Ua.BAD_REQUEST,void 0,void 0,!0);if(!bv.get(Ag.CONFIG_PARAMS.CLUSTERING_ENABLED))throw Pa(new Error,Nv,Ua.NOT_FOUND,void 0,void 0,!0);let{schema:r,table:n,timestamp:s}=e,i=Ov.checkSchemaTableExist(r,n);if(i)throw Pa(new Error,i,Ua.NOT_FOUND,void 0,void 0,!0);let o=yv.createNatsTableStreamName(r,n),{jsm:c}=await tl.getNATSReferences(),u=await tl.getStreamInfo(o),_=new Date(u.state.first_ts).getTime();if(s<=_)return`No transactions exist before: ${s}`;let l=B7,d,E=new Date(u.state.last_ts).getTime();return s>E?(d=u.state.last_seq+1,l=H7):d=(await tl.viewStream(o,parseInt(s),1))[0].nats_sequence,await tl.purgeTableStream(r,n,{seq:d}),l}a(G7,"deleteTransactionLogsBefore")});var Cv=g((Sme,wv)=>{"use strict";var Og=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}};wv.exports=Og});var Lv=g((gme,Dv)=>{"use strict";var bg=class{static{a(this,"PermissionAttributeResponseObject")}constructor(t,r=[]){this.attribute_name=t,this.required_permissions=r}};Dv.exports=bg});var Ng=g((Ame,Pv)=>{"use strict";var Mv=Cv(),q7=Lv(),{HDB_ERROR_MSGS:F7}=Ur(),yg=class{static{a(this,"PermissionResponseObject")}constructor(){this.error=F7.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 Mv(t,r,n),i=`${t}_${r}`;this.unauthorized_access[i]=s}addUnauthorizedAttributes(t,r,n,s){let i=[];t.forEach(c=>{let u=new q7(c,s[c]);i.push(u)});let o=`${r}_${n}`;if(this.unauthorized_access[o])this.unauthorized_access[o].required_attribute_permissions=i;else{let c=new Mv(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}};Pv.exports=yg});var qf=g((bme,zv)=>{"use strict";var Ig=qr(),Hf=Gr(),mn=Tu(),sl=As(),wg=oi(),k7=qS(),V7=vL(),il=ln(),xf=zS(),Ct=$(),$7=XS(),Y7=Xd(),K7=LT(),W7=ef(),Q7=PT(),z7=UT(),J7=HT(),j7=GT(),Cg=kT(),vs=J(),X7=PP(),Dg=WT(),Bv=Af(),hn=P(),Hv=FU(),Z7=Ta(),xv=yu(),Gv=(Nf(),ie(zu)),qv=fr(),Jr=gg(),eee=require("alasql"),Fv=Bf(),kv=Lf(),Vv=Ng(),{handleHDBError:Ir,hdb_errors:$v}=ne(),{HDB_ERROR_MSGS:Kt,HTTP_STATUS_CODES:rl}=$v,V=new Map,Yv="delete",yi="insert",Bs="read",Ro="update",nl="describe",Uv=sl.describeSchema.name,vv=sl.describeTable.name,Kv={delete:!0,deleteRecord:!0,update:!0,updateData:!0,dropAttribute:!0,dropTable:!0,dropSchema:!0,upsert:!0,upsertData:!0},tee="catchup",ree="handleGetJob",nee="handleGetJobsByStartDate",Gf={CSV_DATA_LOAD:"csvDataLoad",CSV_URL_LOAD:"csvURLLoad",CSV_FILE_LOAD:"csvFileLoad",IMPORT_FROM_S3:"importFromS3"},see=[mn.createTable.name,mn.createAttribute.name,mn.dropTable.name,mn.dropAttribute.name],Wv={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(Ig.insert.name,new W(!1,[yi]));V.set(Ig.update.name,new W(!1,[Ro]));V.set(Ig.upsert.name,new W(!1,[yi,Ro]));V.set(Hf.searchByConditions.name,new W(!1,[Bs]));V.set(Hf.searchByHash.name,new W(!1,[Bs]));V.set(Hf.searchByValue.name,new W(!1,[Bs]));V.set(Hf.search.name,new W(!1,[Bs]));V.set(mn.createSchema.name,new W(!0,[]));V.set(mn.createTable.name,new W(!0,[]));V.set(mn.createAttribute.name,new W(!1,[yi]));V.set(mn.dropSchema.name,new W(!0,[]));V.set(mn.dropTable.name,new W(!0,[]));V.set(mn.dropAttribute.name,new W(!0,[]));V.set(sl.describeSchema.name,new W(!1,[Bs]));V.set(sl.describeTable.name,new W(!1,[Bs]));V.set(wg.deleteRecord.name,new W(!1,[Yv]));V.set(il.addUser.name,new W(!0,[]));V.set(il.alterUser.name,new W(!0,[]));V.set(il.dropUser.name,new W(!0,[]));V.set(il.listUsersExternal.name,new W(!0,[]));V.set(xf.listRoles.name,new W(!0,[]));V.set(xf.addRole.name,new W(!0,[]));V.set(xf.alterRole.name,new W(!0,[]));V.set(xf.dropRole.name,new W(!0,[]));V.set($7.name,new W(!0,[]));V.set(Y7.name,new W(!0,[]));V.set(K7.name,new W(!0,[]));V.set(W7.name,new W(!0,[]));V.set(Q7.name,new W(!0,[]));V.set(z7.name,new W(!0,[]));V.set(Cg.setRoutes.name,new W(!0,[]));V.set(Cg.getRoutes.name,new W(!0,[]));V.set(Cg.deleteRoutes.name,new W(!0,[]));V.set(qv.setConfiguration.name,new W(!0,[]));V.set(J7.clusterStatus.name,new W(!0,[]));V.set(j7.name,new W(!0,[]));V.set(Dg.getFingerprint.name,new W(!0,[]));V.set(Dg.setLicense.name,new W(!0,[]));V.set(wg.deleteFilesBefore.name,new W(!0,[]));V.set(wg.deleteAuditLogsBefore.name,new W(!0,[]));V.set(Bv.restart.name,new W(!0,[]));V.set(Bv.restartService.name,new W(!0,[]));V.set(k7.name,new W(!0,[]));V.set(V7.name,new W(!0,[Bs]));V.set(Z7.systemInformation.name,new W(!0,[]));V.set(qv.getConfiguration.name,new W(!0,[]));V.set(Fv.readTransactionLog.name,new W(!0,[]));V.set(Fv.deleteTransactionLogsBefore.name,new W(!0,[]));V.set(kv.installModules.name,new W(!0,[]));V.set(kv.auditModules.name,new W(!0,[]));V.set(xv.createTokens.name,new W(!1,[]));V.set(xv.refreshOperationToken.name,new W(!1,[]));V.set(Gv.login.name,new W(!1,[]));V.set(Gv.logout.name,new W(!1,[]));V.set(Jr.customFunctionsStatus.name,new W(!0,[]));V.set(Jr.getCustomFunctions.name,new W(!0,[]));V.set(Jr.getComponents.name,new W(!0,[]));V.set(Jr.getComponentFile.name,new W(!0,[]));V.set(Jr.setComponentFile.name,new W(!0,[]));V.set(Jr.dropComponent.name,new W(!0,[]));V.set(Jr.getCustomFunction.name,new W(!0,[]));V.set(Jr.setCustomFunction.name,new W(!0,[]));V.set(Jr.dropCustomFunction.name,new W(!0,[]));V.set(Jr.addComponent.name,new W(!0,[]));V.set(Jr.dropCustomFunctionProject.name,new W(!0,[]));V.set(Jr.packageComponent.name,new W(!0,[]));V.set(Jr.deployComponent.name,new W(!0,[]));V.set(Dg.getRegistrationInfo.name,new W(!1,[]));V.set(il.userInfo.name,new W(!1,[]));V.set(sl.describeAll.name,new W(!1,[]));V.set(ree,new W(!1,[]));V.set(nee,new W(!0,[]));V.set(tee,new W(!0,[]));V.set(Gf.CSV_DATA_LOAD,new W(!1,[yi,Ro]));V.set(Gf.CSV_URL_LOAD,new W(!1,[yi,Ro]));V.set(Gf.CSV_FILE_LOAD,new W(!1,[yi,Ro]));V.set(Gf.IMPORT_FROM_S3,new W(!1,[yi,Ro]));V.set(Wv.EXPORT_TO_S3,new W(!0,[]));V.set(Wv.EXPORT_LOCAL,new W(!0,[]));V.set(hn.VALID_SQL_OPS_ENUM.DELETE,new W(!1,[Yv]));V.set(hn.VALID_SQL_OPS_ENUM.SELECT,new W(!1,[Bs]));V.set(hn.VALID_SQL_OPS_ENUM.INSERT,new W(!1,[yi]));V.set(hn.VALID_SQL_OPS_ENUM.UPDATE,new W(!1,[Ro]));zv.exports={verifyPerms:oee,verifyPermsAst:iee,verifyBulkLoadAttributePerms:cee};function iee(e,t,r){if(vs.isEmptyOrZeroLength(e))throw Ct.info("verify_perms_ast has an empty user parameter"),Ir(new Error);if(vs.isEmptyOrZeroLength(t))throw Ct.info("verify_perms_ast has an empty user parameter"),Ir(new Error);if(vs.isEmptyOrZeroLength(r))throw Ct.info("verify_perms_ast has a null operation parameter"),Ir(new Error);try{let n=new Vv,s=new X7(e),i=s.getSchemas(),o=new Map;if((!i||i.length===0)&&s.affected_attributes&&s.affected_attributes.size>0)throw Ct.info("No schemas defined in verifyPermsAst(), will not continue."),Ir(new Error);let c=!!t.role.permission.super_user,u=i.includes("system");if(u&&Kv[r])throw Ir(new Error,Kt.DROP_SYSTEM,rl.FORBIDDEN);if(c&&!u)return null;let _=Hv.getRolePermissions(t.role);t.role.permission=_,!c&&e instanceof eee.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 l=Qv(t,r,o,n);return l||(o.forEach((d,E)=>{for(let f=0;f<d.length;f++){let h=s.getAttributesBySchemaTableName(E,d[f]),p=Mg(t.role.permission,E,d[f]);Lg(h,p,r,d[f],E,n)}}),n.getPermsResponse())}catch(n){throw Ir(n)}}a(iee,"verifyPermsAst");function oee(e,t){if(e===null||t===null||e.hdb_user===void 0||e.hdb_user===null)throw Ct.info("null required parameter in verifyPerms"),Ir(new Error,Kt.DEFAULT_INVALID_REQUEST,rl.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 Vv;if(vs.isEmptyOrZeroLength(e.hdb_user.role)||vs.isEmptyOrZeroLength(e.hdb_user.role.permission))return Ct.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 u=!!e.hdb_user.role.permission.super_user,_=e.hdb_user.role.permission.structure_user,l=o.has(hn.SYSTEM_SCHEMA_NAME)||s===hn.SYSTEM_SCHEMA_NAME;if(l&&Kv[r])throw Ir(new Error,Kt.DROP_SYSTEM,rl.FORBIDDEN);if(u&&!l||_===!0&&(r===mn.createSchema.name||r===mn.dropSchema.name))return null;if(see.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=Hv.getRolePermissions(e.hdb_user.role);if(e.hdb_user.role.permission=d,r===Uv||r===vv){if(s===hn.SYSTEM_SCHEMA_NAME)return c.handleUnauthorizedItem(Kt.SCHEMA_PERM_ERROR(s));if(!d.super_user){if(r===Uv&&(!d[s]||!d[s][nl]))return c.handleInvalidItem(Kt.SCHEMA_NOT_FOUND(s));if(r===vv&&(!d[s]||!d[s].tables[i]||!d[s].tables[i][nl]))return c.handleInvalidItem(Kt.TABLE_NOT_FOUND(s,i))}}let E=Qv(e.hdb_user,r,o,c,n);if(E)return E;if(V.get(r)&&V.get(r).perms.length===0)return null;if(!u&&e.get_attributes&&hn.SEARCH_WILDCARDS.includes(e.get_attributes[0])){let p=[],S=d[s].tables[i];S[hn.PERMS_CRUD_ENUM.READ]&&(S.attribute_permissions.length>0?S.attribute_permissions.filter(A=>A[hn.PERMS_CRUD_ENUM.READ]).forEach(A=>{p.push(A.attribute_name)}):p=global.hdb_schema[s][i].attributes.map(T=>T.attribute),e.get_attributes=p)}let f=aee(e),h=Mg(e.hdb_user.role.permission,s,i);return Lg(f,h,r,i,s,c,n),c.getPermsResponse()}a(oee,"verifyPerms");function Qv(e,t,r,n,s){if(vs.arrayHasEmptyValues([e,t,r]))throw Ct.info("hasPermissions has an invalid parameter"),Ir(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 Ct.info(`operation ${t} not found.`),Ir(new Error,Kt.OP_NOT_FOUND(t),rl.BAD_REQUEST);if(V.get(t)&&V.get(t).requires_su)return Ct.info(`operation ${t} requires SU permissions.`),n.handleUnauthorizedItem(Kt.OP_IS_SU_ONLY(t));let c=r.keys();for(let u of c){try{if(u&&!o[u]||o[u][nl]===!1){n.addInvalidItem(Kt.SCHEMA_NOT_FOUND(u));continue}}catch{n.addInvalidItem(Kt.SCHEMA_NOT_FOUND(u));continue}let _=r.get(u);for(let l of _){let d=o[u].tables[l];if(!d||d[nl]===!1)n.addInvalidItem(Kt.TABLE_NOT_FOUND(u,l));else try{let E=[],f=V.get(t).perms;!vs.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)&&(Ct.info(`Required ${p} permission not found for ${t} ${s?`${s} `:""}operation in role ${e.role.id}`),E.push(p))}E.length>0&&n.addUnauthorizedTable(u,l,E)}catch(E){let f=Kt.UNKNOWN_OP_AUTH_ERROR(t,u,l);throw Ct.error(f),Ct.error(E),Ir($v.CHECK_LOGS_WRAPPER(f))}}}return r.size<2?n.getPermsResponse():null}a(Qv,"hasPermissions");function Lg(e,t,r,n,s,i,o){if(!e||!t)throw Ct.info("no attributes specified in checkAttributePerms."),Ir(new Error);let c=V.get(r).perms;if(!c||c==="")throw Ct.info(`no permissions found for ${r} in checkAttributePerms().`),Ir(new Error);if(vs.isEmptyOrZeroLength(t))return Ct.info("No role permissions set (this is OK)."),null;o&&c.includes(o)&&(c=[o]);let u={};for(let l of e){let d=t.get(l);if(d){if(d[nl]===!1){i.addInvalidItem(Kt.ATTR_NOT_FOUND(s,n,l),s,n);continue}if(c)for(let E of c){if(hn.TIME_STAMP_NAMES.includes(d.attribute_name)&&E!==Bs)throw Ir(new Error,Kt.SYSTEM_TIMESTAMP_PERMS_ERR,rl.FORBIDDEN);d[E]===!1&&(u[d.attribute_name]?u[d.attribute_name].push(E):u[d.attribute_name]=[E])}}else i.addInvalidItem(Kt.ATTR_NOT_FOUND(s,n,l),s,n)}let _=Object.keys(u);_.length>0&&i.addUnauthorizedAttributes(_,s,n,u)}a(Lg,"checkAttributePerms");function aee(e){let t=new Set;try{if(e.action)return t;if(e.operation===hn.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){Ct.info(r)}return t}a(aee,"getRecordAttributes");function Mg(e,t,r){let n=new Map;if(vs.isEmpty(e))return Ct.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{Ct.info(`No attribute permissions found for schema ${t} and table ${r}.`)}return n}a(Mg,"getAttributePermissions");function cee(e,t,r,n,s,i,o){let c=new Set(i),u=Mg(e,n,s);Lg(c,u,t,s,n,o,r)}a(cee,"verifyBulkLoadAttributePerms")});var kf=g((Nme,e0)=>{"use strict";e0.exports={evaluateSQL:Ree,processAST:Zv,convertSQLToAST:Xv,checkASTPermissions:jv};var uee=qr(),Jv=require("util"),lee=Jv.callbackify(uee.insert),_ee=Gr().search,dee=gD().update,fee=Jv.callbackify(dee),Eee=AD().convertDelete,Ni=require("alasql"),hee=qf(),Ff=$(),mee=md(),pee=J(),ol=P(),{hdb_errors:See,handleHDBError:Pg}=ne(),{HTTP_STATUS_CODES:Ug}=See;mee(Ni);var Tee=403,gee="There was a problem performing this insert. Please check the logs and try again.",vg=class{static{a(this,"ParsedSQLObject")}constructor(){this.ast=void 0,this.variant=void 0,this.permissions_checked=!1}};function Ree(e,t){let r=e.parsed_sql_object;if(!r){r=Xv(e.sql);let n,s=r.ast.statements[0];if(s instanceof Ni.yy.Insert?n=s.into.databaseid:s instanceof Ni.yy.Select?n=s.from?s.from[0].databaseid:null:s instanceof Ni.yy.Update||s instanceof Ni.yy.Delete?n=s.table.databaseid:Ff.error("AST in evaluateSQL is not a valid SQL type."),!(s instanceof Ni.yy.Select)&&pee.isEmptyOrZeroLength(n))return t("No schema specified",null)}Zv(e,r,(n,s)=>{if(n)return t(n);t(null,s)})}a(Ree,"evaluateSQL");function jv(e,t){let r;try{r=hee.verifyPermsAst(t.ast.statements[0],e.hdb_user,t.variant),t.permissions_checked=!0}catch(n){throw n}return r||null}a(jv,"checkASTPermissions");function Xv(e){let t=new vg;if(!e)throw Pg(new Error,"The 'sql' parameter is missing from the request body",Ug.BAD_REQUEST);try{let r=e.trim(),n=Ni.parse(r),s=r.split(" ")[0].toLowerCase();t.ast=n,t.variant=s}catch(r){let n=r.message.split(`
|
|
19
|
-
`);throw n[1]?Pg(r,`Invalid SQL at: ${n[1]}. Please ensure your SQL is valid. Try adding backticks to reserved words and schema table references.`,Ug.BAD_REQUEST):Pg(r,"We had trouble parsing your request. Please ensure your SQL is valid. Try adding backticks to reserved words and schema table references.",Ug.BAD_REQUEST)}return t}a(Xv,"convertSQLToAST");function Zv(e,t,r){try{let n=Aee;if(!e.bypass_auth&&!t.permissions_checked){let i=jv(e,t);if(i&&i.length>0)return r(Tee,i)}let s={statement:t.ast.statements[0],hdb_user:e.hdb_user};switch(t.variant){case ol.VALID_SQL_OPS_ENUM.SELECT:n=_ee,s=t.ast.statements[0];break;case ol.VALID_SQL_OPS_ENUM.INSERT:n=Oee;break;case ol.VALID_SQL_OPS_ENUM.UPDATE:n=fee;break;case ol.VALID_SQL_OPS_ENUM.DELETE:n=Eee;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(Zv,"processAST");function Aee(e,t){Ff.info(e),t("unknown sql statement")}a(Aee,"nullFunction");function Oee({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=bee(i,e.values)}catch(o){return r(o)}lee(s,(o,c)=>{if(o)return r(o);try{delete c.new_attributes,delete c.txn_time}catch(u){Ff.error(`Error delete new_attributes from insert response: ${u}`)}r(null,c)})}a(Oee,"convertInsert");function bee(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]]=Ni.compile(`SELECT ${s.toString()} AS [${ol.FUNC_VAL}] FROM ?`)}),n})}catch(r){throw Ff.error(r),new Error(gee)}}a(bee,"createDataObjects")});var Bg=g((wme,r0)=>{"use strict";var{S3:yee,GetObjectCommand:Nee}=require("@aws-sdk/client-s3");r0.exports={getFileStreamFromS3:Iee,getS3AuthObj:t0};async function Iee(e){let{s3:t}=e,r={Bucket:t.bucket,Key:t.key};return(await t0(t.aws_access_key_id,t.aws_secret_access_key,t.region).send(new Nee(r))).Body}a(Iee,"getFileStreamFromS3");function t0(e,t,r){return new yee({credentials:{accessKeyId:e,secretAccessKey:t},region:r})}a(t0,"getS3AuthObj")});var Vf=g((Dme,_0)=>{"use strict";var xg=Gr(),wee=kf(),Cee=Bg(),{AsyncParser:Dee,Transform:Lee}=require("json2csv"),cl=require("stream"),jr=J(),Hg=require("fs-extra"),Mee=require("path"),pn=$(),{promisify:i0}=require("util"),al=J(),{handleHDBError:At,hdb_errors:Pee}=ne(),{HDB_ERROR_MSGS:wr,HTTP_STATUS_CODES:Ot}=Pee,{streamAsJSON:Uee}=(rm(),ie(Lb)),{Upload:vee}=require("@aws-sdk/lib-storage"),n0=["search_by_value","search_by_hash","sql","search_by_conditions"],s0=["json","csv"],o0="json",a0="csv",Bee="Successfully exported JSON locally.",Hee="Successfully exported CSV locally.",xee=1e3,Gee=xg.searchByHash,qee=xg.searchByValue,Fee=i0(wee.evaluateSQL),kee=i0(cl.finished);_0.exports={export_to_s3:Kee,export_local:Vee,toCsvStream:c0};async function Vee(e){pn.trace(`export_local request to path: ${e.path}, filename: ${e.filename}, format: ${e.format}`);let t=u0(e);if(!jr.isEmpty(t))throw pn.error(t),At(new Error,t,Ot.BAD_REQUEST,void 0,void 0,!0);if(jr.isEmpty(e.path))throw pn.error(wr.MISSING_VALUE("path")),At(new Error,wr.MISSING_VALUE("path"),Ot.BAD_REQUEST,void 0,void 0,!0);let r=(jr.isEmpty(e.filename)?new Date().getTime():e.filename)+"."+e.format;e.path.endsWith(Mee.sep)&&(e.path=e.path.substring(0,e.path.length-1));let n=jr.buildFolderPath(e.path,r);await $ee(e.path);let s=await l0(e);return await Yee(n,e.format,s)}a(Vee,"export_local");async function $ee(e){if(pn.trace("in confirmPath"),jr.isEmptyOrZeroLength(e))throw At(new Error,`Invalid path: ${e}`,Ot.BAD_REQUEST,void 0,void 0,!0);let t;try{t=await Hg.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,pn.error(n),At(new Error,n,Ot.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 pn.error(r),At(new Error,r,Ot.BAD_REQUEST,void 0,void 0,!0)}return!0}a($ee,"confirmPath");async function Yee(e,t,r){if(pn.trace("in saveToLocal"),al.isEmptyOrZeroLength(e))throw At(new Error,wr.INVALID_VALUE("file_path"),Ot.BAD_REQUEST,void 0,void 0,!0);if(al.isEmptyOrZeroLength(t))throw At(new Error,wr.INVALID_VALUE("Source format"),Ot.BAD_REQUEST,void 0,void 0,!0);if(al.isEmpty(r))throw At(new Error,wr.NOT_FOUND("Data"),Ot.BAD_REQUEST,void 0,void 0,!0);if(t===o0){let n=Hg.createWriteStream(e);return Uee(r).pipe(n),await kee(n),{message:Bee,path:e}}else if(t===a0){let n=Hg.createWriteStream(e),s=cl.Readable.from(r),i={},o=r.getColumns?.();o&&(i.fields=o.map(l=>({label:l,value:l})));let c={objectMode:!0};return await new Dee(i,c).fromInput(s).toOutput(n).promise(!1),{message:Hee,path:e}}throw At(new Error,wr.INVALID_VALUE("format"),Ot.BAD_REQUEST)}a(Yee,"saveToLocal");async function Kee(e){if(!e.s3||Object.keys(e.s3).length===0)throw At(new Error,wr.MISSING_VALUE("S3 object"),Ot.BAD_REQUEST);if(jr.isEmptyOrZeroLength(e.s3.aws_access_key_id))throw At(new Error,wr.MISSING_VALUE("aws_access_key_id"),Ot.BAD_REQUEST);if(jr.isEmptyOrZeroLength(e.s3.aws_secret_access_key))throw At(new Error,wr.MISSING_VALUE("aws_secret_access_key"),Ot.BAD_REQUEST);if(jr.isEmptyOrZeroLength(e.s3.bucket))throw At(new Error,wr.MISSING_VALUE("bucket"),Ot.BAD_REQUEST);if(jr.isEmptyOrZeroLength(e.s3.key))throw At(new Error,wr.MISSING_VALUE("key"),Ot.BAD_REQUEST);if(jr.isEmptyOrZeroLength(e.s3.region))throw At(new Error,wr.MISSING_VALUE("region"),Ot.BAD_REQUEST);let t=u0(e);if(!jr.isEmpty(t))throw At(new Error,t,Ot.BAD_REQUEST);pn.trace(`called export_to_s3 to bucket: ${e.s3.bucket} and query ${e.search_operation.sql}`);let r;try{r=await l0(e)}catch(u){throw pn.error(u),u}let n,s=await Cee.getS3AuthObj(e.s3.aws_access_key_id,e.s3.aws_secret_access_key,e.s3.region),i,o=new cl.PassThrough;if(e.format===a0){i=e.s3.key+".csv";let u=c0(r,r.getColumns?.());u.on("error",_=>{throw _}),u.pipe(o)}else if(e.format===o0){i=e.s3.key+".json";let u=new cl.Readable;u.pipe(o),u.on("error",d=>{throw d}),u.push("[");let _=r.length,l="";for(let[d,E]of r.entries()){let f=d===_-1?JSON.stringify(E):JSON.stringify(E)+",";l+=f,d!==0&&d%xee===0&&(u.push(l),l="")}l.length!==0&&u.push(l),u.push("]"),u.push(null)}else throw At(new Error,wr.INVALID_VALUE("format"),Ot.BAD_REQUEST);return new vee({client:s,params:{Bucket:e.s3.bucket,Key:i,Body:o}}).done()}a(Kee,"export_to_s3");function c0(e,t){let r=cl.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 Lee(n,s);return r.pipe(i)}a(c0,"toCsvStream");function u0(e){if(pn.trace("in exportCoreValidation"),jr.isEmpty(e.format))return"format missing";if(s0.indexOf(e.format)<0)return`format invalid. must be one of the following values: ${s0.join(", ")}`;let t=e.search_operation.operation;if(jr.isEmpty(t))return"search_operation.operation missing";if(n0.indexOf(t)<0)return`search_operation.operation must be one of the following values: ${n0.join(", ")}`}a(u0,"exportCoreValidation");async function l0(e){pn.trace("in getRecords");let t,r;if(al.isEmpty(e.search_operation)||al.isEmptyOrZeroLength(e.search_operation.operation))throw At(new Error,wr.INVALID_VALUE("Search operation"),Ot.BAD_REQUEST);switch(e.search_operation.operation){case"search_by_value":t=qee;break;case"search_by_hash":t=Gee;break;case"search_by_conditions":t=xg.searchByConditions;break;case"sql":t=Fee;break;default:throw r=`Operation ${e.search_operation.operation} is not support by export.`,pn.error(r),At(new Error,r,Ot.BAD_REQUEST)}return e.search_operation.hdb_user=e.hdb_user,t(e.search_operation)}a(l0,"getRecords")});var T0={};qe(T0,{contentTypes:()=>kg,findBestSerializer:()=>Kf,getDeserializer:()=>Oo,registerContentHandlers:()=>Vg,serialize:()=>Wf,serializeMessage:()=>To});function Wee(e){try{return e?.[0]===123?Fg(e):e}catch{return e}}function Vg(e){e.register(zee,{serializers:[{regex:/^application\/json$/,serializer:bc},{regex:/^application\/cbor$/,serializer:function(t){return new Ao.EncoderStream(ll).end(t)}},{regex:/^application\/(x-)?msgpack$/,serializer:function(t){return(t?.[Symbol.iterator]||t?.[Symbol.asyncIterator])&&!Array.isArray(t)?Yf.Readable.from((0,us.encodeIter)(t,ll)):(0,us.pack)(t)}},{regex:/^text\/csv$/,serializer:function(t){return this.header("Content-Disposition",'attachment; filename="data.csv"'),(0,$f.toCsvStream)(t)}}]}),e.addContentTypeParser("application/x-msgpack",{parseAs:"buffer"},(t,r,n)=>{try{n(null,(0,us.unpack)(r))}catch(s){s.statusCode=400,n(s)}}),e.addContentTypeParser("application/cbor",{parseAs:"buffer"},(t,r,n)=>{try{n(null,(0,Ao.decode)(r))}catch(s){s.statusCode=400,n(s)}})}function Kf(e){let r=(e.headers.asObject||e.headers).accept,n,s=0,i,o,c=r?r.toLowerCase().split(/\s*,\s*/):[];for(let u of c){let[_,...l]=u.split(/\s*;\s*/),d=1,E={q:1};for(let h of l){let p=h.indexOf("=");E[h.substring(0,p)]=h.substring(p+1)}d=+E.q;let f=qt.get(_);if(f){let h=(f.q||1)*d;h>s&&(n=f,i=f.type||_,s=h,o=E)}}if(!n){if(r)return{serializer(){this.code(406).send("No supported content types found in Accept header, supported types include: "+Array.from(qt.keys()).join(", "))}};n=qt.get("application/json"),i="application/json"}return{serializer:n,type:i,parameters:o}}function Wf(e,t,r){let n=f0&&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=Kf(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,Hs.createBrotliCompress)({params:{[Hs.constants.BROTLI_PARAM_MODE]:i.type.includes("json")||i.type.includes("text")?Hs.constants.BROTLI_MODE_TEXT:Hs.constants.BROTLI_MODE_GENERIC,[Hs.constants.BROTLI_PARAM_QUALITY]:2}}))),o}s=i.serializer.serialize(e,r)}return n&&s?.length>f0?(r.headers.set("Content-Encoding","br"),new Promise((i,o)=>(0,Hs.brotliCompress)(s,(c,u)=>{c?o(c):i(u)}))):s}function To(e,t){if(e?.contentType!=null&&e.data!=null)return e.data;if(!t)return ul(e);let r=t.serialize;if(r)return r(e);let n=Kf(t);return r=t.serialize=n.serializer.serialize,r(e)}function Jee(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 Oo(e,t){e||(e="");let r=e.indexOf(";"),n;r>-1&&(n=e.slice(r+1),e=e.slice(0,r));let s=qt.get(e);if(t){if(s?.deserializeStream)return s.deserializeStream;let i=qt.get(e)?.deserialize||E0(e,n);return o=>Jee(o).then(i)}return e&&qt.get(e)?.deserialize||E0(e,n)}function E0(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 Fg(r)}catch{}return{contentType:e||"application/octet-stream",data:r}}}function jee(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 $f,us,Ao,Hs,Yf,h0,Gg,qg,m0,p0,ul,Fg,ll,qt,kg,d0,S0,Qee,zee,f0,wa=Ae(()=>{rm();$f=B(Vf()),us=require("msgpackr"),Ao=require("cbor-x"),Hs=require("zlib"),Yf=require("stream");ur();h0=require("../index"),Gg=B(Z()),qg=B(P()),m0=B(require("yaml")),p0=Gg.default.get(qg.CONFIG_PARAMS.SERIALIZATION_BIGINT)!==!1,ul=p0?xi:JSON.stringify,Fg=p0?tm:JSON.parse,ll={useRecords:!1,useToJSON:!0},qt=new Map,kg=qt;st.contentTypes=kg;(0,h0._assignPackageExport)("contentTypes",kg);qt.set("application/json",{serializeStream:bc,serialize:ul,deserialize:Fg,q:.8});d0=new Ao.Encoder(ll);qt.set("application/cbor",{serializeStream(e){return e[Symbol.asyncIterator]&&(e[Symbol.iterator]=null),new Ao.EncoderStream(ll).end(e)},serialize:d0.encode,deserialize:d0.decode,q:1});qt.set("application/x-msgpack",{serializeStream(e){return(e?.[Symbol.iterator]||e?.[Symbol.asyncIterator])&&!Array.isArray(e)?Yf.Readable.from((0,us.encodeIter)(e,ll)):(0,us.pack)(e)},serialize:us.pack,deserialize:us.unpack,q:.9});qt.set("text/csv",{serializeStream(e,t){return t.headers.set("Content-Disposition",'attachment; filename="data.csv"'),(0,$f.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,$f.toCsvStream)(e,e?.getColumns?.())},q:.1});qt.set("text/plain",{serialize(e){return e.toString()},deserialize(e){return e.toString()},q:.2});qt.set("text/yaml",{serialize(e){return m0.stringify(e,{aliasDuplicateObjects:!1})},q:.7});qt.set("text/event-stream",{serializeStream:function(e){return Yf.Readable.from(jee(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+`
|
|
20
|
-
`),e.data){let r=e.data;typeof r=="object"&&(r=
|
|
17
|
+
`,""):null}catch(E){E.stderr?i[u].npm_error=cv(E.stderr):i[u].npm_error=E.message;continue}try{i[u].npm_output=JSON.parse(l)}catch{i[u].npm_output=l}try{i[u].npm_error=JSON.parse(d)}catch{i[u].npm_error=d}}return Ma.info(`finished installModules with response ${i}`),i}a(c7,"installModules");function cv(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(cv,"parseNPMStdErr");async function u7(e){Ma.info(`starting auditModules for request: ${e}`);let t=lv(e);if(t)throw Da(t,t.message,La.BAD_REQUEST);let{projects:r}=e;await Mf(),await uv(r);let n={};for(let s=0,i=r.length;s<i;s++){let o=r[s],c=Lf.join(mg,o);n[o]={npm_output:null,npm_error:null};try{let u=await tl("npm audit --json",c);n[o].npm_output=JSON.parse(u)}catch(u){n[o].npm_error=cv(u.stderr)}}return Ma.info(`finished auditModules with response ${n}`),n}a(u7,"auditModules");async function Mf(){try{return await tl("npm -v"),!0}catch{throw Da(new Error,"Unable to install project dependencies: npm is not installed on this instance of HarperDB.",La.BAD_REQUEST,void 0,void 0,!0)}}a(Mf,"checkNPMInstalled");async function uv(e){if(!Array.isArray(e)||e.length===0)throw Da(new Error,"projects argument must be an array with at least 1 element",La.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=Lf.join(mg,i.toString());if(!await iv.pathExists(o)){t.push(i);continue}let u=Lf.join(o,"package.json");await iv.pathExists(u)||r.push(i)}if(t.length>0)throw Da(new Error,`Unable to install project dependencies: custom function projects '${t.join(",")}' does not exist.`,La.BAD_REQUEST,void 0,void 0,!0);if(r.length>0)throw Da(new Error,`Unable to install project dependencies: custom function projects '${r.join(",")}' do not have a package.json file.`,La.BAD_REQUEST,void 0,void 0,!0)}a(uv,"checkProjectPaths");function lv(e){let t=Df.object({projects:Df.array().min(1).items(Df.string()).required(),dry_run:Df.boolean().default(!1)});return n7.validateBySchema(e,t)}a(lv,"modulesValidator")});var Sg=g((Eme,mv)=>{"use strict";var Pa=require("fs-extra"),pg=require("path"),Uf=$(),dv=z(),vf=P(),hv=Z(),l7=Er();mv.exports=_7;async function _7(){let e=d7(),t=hv.get(vf.CONFIG_PARAMS.ROOTPATH),r=pg.join(t,"package.json"),n={dependencies:{harperdb:"file:"+vf.PACKAGE_ROOT}},s=pg.join(t,"node_modules");await Pa.ensureDir(s);let i,o=!0,c=!1;try{i=await Pa.readJson(r)}catch(u){if(dv.isEmptyOrZeroLength(e))return;if(u.code!==vf.NODE_ERROR_CODES.ENOENT)throw u;o=!1}if(!dv.isEmptyOrZeroLength(e)){for(let{name:u,package:_}of e){let l=await fv(_);n.dependencies[u]=l+_}if(!o){Uf.notify("Installing components"),await Ev(r,n,null);return}for(let{name:u,package:_}of e){let l=i.dependencies[u],d=await fv(_);if(l===void 0||l!==d+_){c=!0;break}}}for(let u in i.dependencies)n.dependencies[u]===void 0&&(Uf.notify("Removing component",u),c=!0);c&&(Uf.notify("Updating components."),await Ev(r,n,i))}a(_7,"installComponents");function d7(){let e=l7.getConfiguration(),t=[];for(let r in e)e[r]?.package&&t.push(Object.assign(e[r],{name:r}));return t}a(d7,"getComponentsConfig");async function fv(e){return e.includes(":")?"":e.startsWith("@")||!e.startsWith("@")&&!e.includes("/")?"npm:":pg.extname(e)||await Pa.pathExists(e)?"file:":"github:"}a(fv,"getPkgPrefix");async function Ev(e,t,r){Uf.trace("npm installing components package.json",t),await Pa.writeFile(e,JSON.stringify(t,null," "));try{await Pf().installAllRootModules(hv.get(vf.CONFIG_PARAMS.IGNORE_SCRIPTS)===!0)}catch(n){throw r?await Pa.writeFile(e,JSON.stringify(r,null," ")):await Pa.unlink(e),n}}a(Ev,"installPackages")});var Rg=g((pme,gv)=>{"use strict";var $e=require("fs-extra"),Tg=require("fast-glob"),Te=require("path"),Sv=require("tar-fs"),mme=require("uuid").v4,gg=require("normalize-path"),cs=sv(),Ct=$(),ze=P(),Ot=Z(),rl=Er(),f7=z(),{PACKAGE_ROOT:E7}=P(),{handleHDBError:Gt,hdb_errors:h7}=ne(),{basename:m7}=require("path"),p7=Sg(),Tv=Z(),S7=P(),{Readable:T7}=require("stream"),{isMainThread:g7}=require("worker_threads"),{HDB_ERROR_MSGS:go,HTTP_STATUS_CODES:qt}=h7,R7=Te.join(E7,"application-template"),pv=Te.join(Ot.get(ze.HDB_SETTINGS_NAMES.HDB_ROOT_KEY),"tmp");function A7(){Ct.trace("getting custom api status");let e={};try{e={port:Ot.get(ze.CONFIG_PARAMS.HTTP_PORT),directory:Ot.get(ze.CONFIG_PARAMS.COMPONENTSROOT),is_enabled:!0}}catch(t){throw Gt(new Error,go.FUNCTION_STATUS,qt.INTERNAL_SERVER_ERROR,Ct.ERR,t)}return e}a(A7,"customFunctionsStatus");function O7(){Ct.trace("getting custom api endpoints");let e={},t=Ot.get(ze.CONFIG_PARAMS.COMPONENTSROOT);try{Tg.sync(gg(`${t}/*`),{onlyDirectories:!0}).forEach(n=>{let s=n.split("/").pop();e[s]={routes:Tg.sync(gg(`${n}/routes/*.js`)).map(i=>i.split("/").pop().split(".js")[0]),helpers:Tg.sync(gg(`${n}/helpers/*.js`)).map(i=>i.split("/").pop().split(".js")[0])}})}catch(r){throw Gt(new Error,go.GET_FUNCTIONS,qt.INTERNAL_SERVER_ERROR,Ct.ERR,r)}return e}a(O7,"getCustomFunctions");function b7(e){e.project&&(e.project=Te.parse(e.project).name),e.file&&(e.file=Te.parse(e.file).name);let t=cs.getDropCustomFunctionValidator(e);if(t)throw Gt(t,t.message,qt.BAD_REQUEST);Ct.trace("getting custom api endpoint file content");let r=Ot.get(ze.CONFIG_PARAMS.COMPONENTSROOT),{project:n,type:s,file:i}=e,o=Te.join(r,n,s,i+".js");try{return $e.readFileSync(o,{encoding:"utf8"})}catch(c){throw Gt(new Error,go.GET_FUNCTION,qt.INTERNAL_SERVER_ERROR,Ct.ERR,c)}}a(b7,"getCustomFunction");function y7(e){e.project&&(e.project=Te.parse(e.project).name),e.file&&(e.file=Te.parse(e.file).name);let t=cs.setCustomFunctionValidator(e);if(t)throw Gt(t,t.message,qt.BAD_REQUEST);Ct.trace("setting custom function file content");let r=Ot.get(ze.CONFIG_PARAMS.COMPONENTSROOT),{project:n,type:s,file:i,function_content:o}=e;try{return $e.outputFileSync(Te.join(r,n,s,i+".js"),o),`Successfully updated custom function: ${i}.js`}catch(c){throw Gt(new Error,go.SET_FUNCTION,qt.INTERNAL_SERVER_ERROR,Ct.ERR,c)}}a(y7,"setCustomFunction");function N7(e){e.project&&(e.project=Te.parse(e.project).name),e.file&&(e.file=Te.parse(e.file).name);let t=cs.getDropCustomFunctionValidator(e);if(t)throw Gt(t,t.message,qt.BAD_REQUEST);Ct.trace("dropping custom function file");let r=Ot.get(ze.CONFIG_PARAMS.COMPONENTSROOT),{project:n,type:s,file:i}=e;try{return $e.unlinkSync(Te.join(r,n,s,i+".js")),`Successfully deleted custom function: ${i}.js`}catch(o){throw Gt(new Error,go.DROP_FUNCTION,qt.INTERNAL_SERVER_ERROR,Ct.ERR,o)}}a(N7,"dropCustomFunction");function I7(e){e.project&&(e.project=Te.parse(e.project).name);let t=cs.addComponentValidator(e);if(t)throw Gt(t,t.message,qt.BAD_REQUEST);Ct.trace("adding component");let r=Ot.get(ze.CONFIG_PARAMS.COMPONENTSROOT),{project:n}=e;try{let s=Te.join(r,n);return $e.mkdirSync(s,{recursive:!0}),$e.copySync(R7,s),`Successfully added project: ${n}`}catch(s){throw Gt(new Error,go.ADD_FUNCTION,qt.INTERNAL_SERVER_ERROR,Ct.ERR,s)}}a(I7,"addComponent");function w7(e){e.project&&(e.project=Te.parse(e.project).name);let t=cs.dropCustomFunctionProjectValidator(e);if(t)throw Gt(t,t.message,qt.BAD_REQUEST);Ct.trace("dropping custom function project");let r=Ot.get(ze.CONFIG_PARAMS.COMPONENTSROOT),{project:n}=e,s=Ot.get(ze.CONFIG_PARAMS.APPS);if(!f7.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 rl.updateConfigValue(ze.CONFIG_PARAMS.APPS,s),`Successfully deleted project: ${n}`}try{let i=Te.join(r,n);return $e.rmSync(i,{recursive:!0}),`Successfully deleted project: ${n}`}catch(i){throw Gt(new Error,go.DROP_FUNCTION_PROJECT,qt.INTERNAL_SERVER_ERROR,Ct.ERR,i)}}a(w7,"dropCustomFunctionProject");async function C7(e){e.project&&(e.project=Te.parse(e.project).name);let t=cs.packageComponentValidator(e);if(t)throw Gt(t,t.message,qt.BAD_REQUEST);let r=Ot.get(ze.CONFIG_PARAMS.COMPONENTSROOT),{project:n}=e;Ct.trace("packaging component",n);let s;try{s=await $e.realpath(Te.join(r,n))}catch(u){if(u.code!==ze.NODE_ERROR_CODES.ENOENT)throw u;try{s=await $e.realpath(Te.join(Ot.get(ze.CONFIG_PARAMS.ROOTPATH),"node_modules",n))}catch(_){if(_.code===ze.NODE_ERROR_CODES.ENOENT)throw new Error(`Unable to locate project '${n}'`)}}await $e.ensureDir(pv);let i=Te.join(pv,`${n}.tar`),o={};(e.skip_node_modules===!0||e.skip_node_modules==="true")&&(o={ignore:u=>u.includes(Te.join(s,"node_modules"))}),Sv.pack(s,o).pipe($e.createWriteStream(i,{overwrite:!0})),await new Promise(u=>setTimeout(u,2e3));let c=$e.readFileSync(i,{encoding:"base64"});return await $e.remove(i),{project:n,payload:c}}a(C7,"packageComponent");async function D7(e){e.project&&(e.project=Te.parse(e.project).name);let t=cs.deployComponentValidator(e);if(t)throw Gt(t,t.message,qt.BAD_REQUEST);let r=Ot.get(ze.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 $e.emptyDir(o);let E=T7.from(Buffer.from(s,"base64"));await new Promise((h,p)=>{E.pipe(Sv.extract(o,{finish:h})).on("error",p)});let f=await $e.readdir(o);f.length===1&&f[0]==="package"&&(await $e.copy(Te.join(o,"package"),o),await $e.remove(Te.join(o,"package")))}if(await rl.addConfig(n,{package:i}),!s){await p7();let E=Tv.get(S7.CONFIG_PARAMS.ROOTPATH);o=Te.join(E,"node_modules",n)}if(g7)return;let c=new Map;c.isWorker=!0;let u=(xf(),ie(Bf)),_;u.setErrorReporter(E=>_=E);let l=m7(o),d=u.component_errors.get(l);try{await u.loadComponent(o,c)}finally{u.component_errors.set(l,d)}if(_)throw _;return Ct.info("Installed component"),`Successfully deployed: ${n}`}a(D7,"deployComponent");async function L7(){let e=rl.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 u=await $e.readdir(o,{withFileTypes:!0});for(let _ of u){let l=_.name;if(l.startsWith(".")||l==="node_modules")continue;let d=Te.join(o,l);if(_.isDirectory()||_.isSymbolicLink()){let E={name:l,entries:[]};c.entries.push(E),await r(d,E)}else{let E=await $e.stat(d),f={name:Te.basename(l),mtime:E.mtime,size:E.size};c.entries.push(f)}}return c}catch(u){return Ct.warn("Error loading package",u),{error:u.toString(),entries:[]}}},"walk_dir"),n=await r(Ot.get(ze.CONFIG_PARAMS.COMPONENTSROOT),{name:Ot.get(ze.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(Ot.get(ze.CONFIG_PARAMS.ROOTPATH),"node_modules",o.name),{name:o.name,entries:[]});Object.assign(o,c)}let i=(xf(),ie(Bf)).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(L7,"getComponents");async function M7(e){let t=cs.getComponentFileValidator(e);if(t)throw Gt(t,t.message,qt.BAD_REQUEST);let n=rl.getConfigObj()[e.project]||e.project==="harperdb"?Te.join(Tv.get(ze.CONFIG_PARAMS.ROOTPATH),"node_modules"):Ot.get(ze.CONFIG_PARAMS.COMPONENTSROOT),s=e.encoding?{encoding:e.encoding}:{encoding:"utf8"};try{let i=await $e.stat(Te.join(n,e.project,e.file));return{message:await $e.readFile(Te.join(n,e.project,e.file),s),size:i.size,birthtime:i.birthtime,mtime:i.mtime}}catch(i){throw i.code===ze.NODE_ERROR_CODES.ENOENT?new Error(`Component file not found '${Te.join(e.project,e.file)}'`):i}}a(M7,"getComponentFile");async function P7(e){let t=cs.setComponentFileValidator(e);if(t)throw Gt(t,t.message,qt.BAD_REQUEST);let r=e.encoding?{encoding:e.encoding}:{encoding:"utf8"},n=Te.join(Ot.get(ze.CONFIG_PARAMS.COMPONENTSROOT),e.project,e.file);return e.payload!==void 0?(await $e.ensureFile(n),await $e.outputFile(n,e.payload,r)):await $e.ensureDir(n),"Successfully set component: "+e.file}a(P7,"setComponentFile");async function U7(e){let t=cs.dropComponentFileValidator(e);if(t)throw Gt(t,t.message,qt.BAD_REQUEST);let r=e.file?Te.join(e.project,e.file):e.project,n=Te.join(Ot.get(ze.CONFIG_PARAMS.COMPONENTSROOT),r);return await $e.pathExists(n)&&await $e.remove(n),rl.deleteConfigFromFile([e.project]),"Successfully dropped: "+r}a(U7,"dropComponent");gv.exports={customFunctionsStatus:A7,getCustomFunctions:O7,getCustomFunction:b7,setCustomFunction:y7,dropCustomFunction:N7,addComponent:I7,dropCustomFunctionProject:w7,packageComponent:C7,deployComponent:D7,getComponents:L7,getComponentFile:M7,setComponentFile:P7,dropComponent:U7}});var Ag=g((Tme,Av)=>{"use strict";var us=require("joi"),Rv=Xe();Av.exports={readTransactionLogValidator:v7,deleteTransactionLogsBeforeValidator:B7};function v7(e){let t=us.object({schema:us.string().required(),table:us.string().required(),from:us.date().timestamp(),to:us.date().timestamp(),limit:us.number().min(1)});return Rv.validateBySchema(e,t)}a(v7,"readTransactionLogValidator");function B7(e){let t=us.object({schema:us.string().required(),table:us.string().required(),timestamp:us.date().timestamp().required()});return Rv.validateBySchema(e,t)}a(B7,"deleteTransactionLogsBeforeValidator")});var Hf=g((Rme,Iv)=>{"use strict";var Og=P(),nl=ut(),Ov=z(),bv=Z(),yv=As(),{handleHDBError:Ua,hdb_errors:x7}=ne(),{HTTP_STATUS_CODES:va}=x7,{readTransactionLogValidator:H7,deleteTransactionLogsBeforeValidator:G7}=Ag(),Nv="This operation relies on clustering and cannot run with it disable.",q7="Logs successfully deleted from transaction log.",F7="All logs successfully deleted from transaction log.";Iv.exports={readTransactionLog:k7,deleteTransactionLogsBefore:V7};async function*k7(e){let t=H7(e);if(t)throw Ua(t,t.message,va.BAD_REQUEST,void 0,void 0,!0);if(!bv.get(Og.CONFIG_PARAMS.CLUSTERING_ENABLED))throw Ua(new Error,Nv,va.NOT_FOUND,void 0,void 0,!0);let{schema:r,table:n}=e,s=Ov.checkSchemaTableExist(r,n);if(s)throw Ua(new Error,s,va.NOT_FOUND,void 0,void 0,!0);let i=yv.createNatsTableStreamName(r,n),o=await nl.viewStreamIterator(i,parseInt(e.from),e.limit);for await(let c of o){let u=Math.floor(c?.nats_timestamp/1e6);if(e.to&&u>e.to)break;let _={operation:c?.entry?.operation,user:c?.entry?.__origin?.user,timestamp:u,records:c?.entry?.records,attributes:c?.entry?.attributes};c?.entry?.operation===Og.OPERATIONS_ENUM.DELETE&&(_.hash_values=c?.entry?.hash_values),yield _}}a(k7,"readTransactionLog");async function V7(e){let t=G7(e);if(t)throw Ua(t,t.message,va.BAD_REQUEST,void 0,void 0,!0);if(!bv.get(Og.CONFIG_PARAMS.CLUSTERING_ENABLED))throw Ua(new Error,Nv,va.NOT_FOUND,void 0,void 0,!0);let{schema:r,table:n,timestamp:s}=e,i=Ov.checkSchemaTableExist(r,n);if(i)throw Ua(new Error,i,va.NOT_FOUND,void 0,void 0,!0);let o=yv.createNatsTableStreamName(r,n),{jsm:c}=await nl.getNATSReferences(),u=await nl.getStreamInfo(o),_=new Date(u.state.first_ts).getTime();if(s<=_)return`No transactions exist before: ${s}`;let l=q7,d,E=new Date(u.state.last_ts).getTime();return s>E?(d=u.state.last_seq+1,l=F7):d=(await nl.viewStream(o,parseInt(s),1))[0].nats_sequence,await nl.purgeTableStream(r,n,{seq:d}),l}a(V7,"deleteTransactionLogsBefore")});var Cv=g((Ome,wv)=>{"use strict";var bg=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}};wv.exports=bg});var Lv=g((yme,Dv)=>{"use strict";var yg=class{static{a(this,"PermissionAttributeResponseObject")}constructor(t,r=[]){this.attribute_name=t,this.required_permissions=r}};Dv.exports=yg});var Ig=g((Ime,Pv)=>{"use strict";var Mv=Cv(),$7=Lv(),{HDB_ERROR_MSGS:Y7}=Ur(),Ng=class{static{a(this,"PermissionResponseObject")}constructor(){this.error=Y7.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 Mv(t,r,n),i=`${t}_${r}`;this.unauthorized_access[i]=s}addUnauthorizedAttributes(t,r,n,s){let i=[];t.forEach(c=>{let u=new $7(c,s[c]);i.push(u)});let o=`${r}_${n}`;if(this.unauthorized_access[o])this.unauthorized_access[o].required_attribute_permissions=i;else{let c=new Mv(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}};Pv.exports=Ng});var kf=g((Cme,zv)=>{"use strict";var wg=qr(),Gf=Gr(),mn=gu(),ol=Os(),Cg=oi(),K7=qS(),W7=BL(),al=ln(),qf=zS(),Dt=$(),Q7=XS(),z7=tf(),J7=LT(),j7=nf(),X7=PT(),Z7=UT(),eee=xT(),tee=GT(),Dg=kT(),Bs=z(),ree=UP(),Lg=WT(),Bv=Wu(),hn=P(),xv=FU(),nee=ga(),Hv=Nu(),Gv=(wf(),ie(ju)),qv=Er(),Jr=Rg(),see=require("alasql"),Fv=Hf(),kv=Pf(),Vv=Ig(),{handleHDBError:wr,hdb_errors:$v}=ne(),{HDB_ERROR_MSGS:Wt,HTTP_STATUS_CODES:sl}=$v,V=new Map,Yv="delete",yi="insert",xs="read",Ro="update",il="describe",Uv=ol.describeSchema.name,vv=ol.describeTable.name,Kv={delete:!0,deleteRecord:!0,update:!0,updateData:!0,dropAttribute:!0,dropTable:!0,dropSchema:!0,upsert:!0,upsertData:!0},iee="catchup",oee="handleGetJob",aee="handleGetJobsByStartDate",Ff={CSV_DATA_LOAD:"csvDataLoad",CSV_URL_LOAD:"csvURLLoad",CSV_FILE_LOAD:"csvFileLoad",IMPORT_FROM_S3:"importFromS3"},cee=[mn.createTable.name,mn.createAttribute.name,mn.dropTable.name,mn.dropAttribute.name],Wv={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(wg.insert.name,new W(!1,[yi]));V.set(wg.update.name,new W(!1,[Ro]));V.set(wg.upsert.name,new W(!1,[yi,Ro]));V.set(Gf.searchByConditions.name,new W(!1,[xs]));V.set(Gf.searchByHash.name,new W(!1,[xs]));V.set(Gf.searchByValue.name,new W(!1,[xs]));V.set(Gf.search.name,new W(!1,[xs]));V.set(mn.createSchema.name,new W(!0,[]));V.set(mn.createTable.name,new W(!0,[]));V.set(mn.createAttribute.name,new W(!1,[yi]));V.set(mn.dropSchema.name,new W(!0,[]));V.set(mn.dropTable.name,new W(!0,[]));V.set(mn.dropAttribute.name,new W(!0,[]));V.set(ol.describeSchema.name,new W(!1,[xs]));V.set(ol.describeTable.name,new W(!1,[xs]));V.set(Cg.deleteRecord.name,new W(!1,[Yv]));V.set(al.addUser.name,new W(!0,[]));V.set(al.alterUser.name,new W(!0,[]));V.set(al.dropUser.name,new W(!0,[]));V.set(al.listUsersExternal.name,new W(!0,[]));V.set(qf.listRoles.name,new W(!0,[]));V.set(qf.addRole.name,new W(!0,[]));V.set(qf.alterRole.name,new W(!0,[]));V.set(qf.dropRole.name,new W(!0,[]));V.set(Q7.name,new W(!0,[]));V.set(z7.name,new W(!0,[]));V.set(J7.name,new W(!0,[]));V.set(j7.name,new W(!0,[]));V.set(X7.name,new W(!0,[]));V.set(Z7.name,new W(!0,[]));V.set(Dg.setRoutes.name,new W(!0,[]));V.set(Dg.getRoutes.name,new W(!0,[]));V.set(Dg.deleteRoutes.name,new W(!0,[]));V.set(qv.setConfiguration.name,new W(!0,[]));V.set(eee.clusterStatus.name,new W(!0,[]));V.set(tee.name,new W(!0,[]));V.set(Lg.getFingerprint.name,new W(!0,[]));V.set(Lg.setLicense.name,new W(!0,[]));V.set(Cg.deleteFilesBefore.name,new W(!0,[]));V.set(Cg.deleteAuditLogsBefore.name,new W(!0,[]));V.set(Bv.restart.name,new W(!0,[]));V.set(Bv.restartService.name,new W(!0,[]));V.set(K7.name,new W(!0,[]));V.set(W7.name,new W(!0,[xs]));V.set(nee.systemInformation.name,new W(!0,[]));V.set(qv.getConfiguration.name,new W(!0,[]));V.set(Fv.readTransactionLog.name,new W(!0,[]));V.set(Fv.deleteTransactionLogsBefore.name,new W(!0,[]));V.set(kv.installModules.name,new W(!0,[]));V.set(kv.auditModules.name,new W(!0,[]));V.set(Hv.createTokens.name,new W(!1,[]));V.set(Hv.refreshOperationToken.name,new W(!1,[]));V.set(Gv.login.name,new W(!1,[]));V.set(Gv.logout.name,new W(!1,[]));V.set(Jr.customFunctionsStatus.name,new W(!0,[]));V.set(Jr.getCustomFunctions.name,new W(!0,[]));V.set(Jr.getComponents.name,new W(!0,[]));V.set(Jr.getComponentFile.name,new W(!0,[]));V.set(Jr.setComponentFile.name,new W(!0,[]));V.set(Jr.dropComponent.name,new W(!0,[]));V.set(Jr.getCustomFunction.name,new W(!0,[]));V.set(Jr.setCustomFunction.name,new W(!0,[]));V.set(Jr.dropCustomFunction.name,new W(!0,[]));V.set(Jr.addComponent.name,new W(!0,[]));V.set(Jr.dropCustomFunctionProject.name,new W(!0,[]));V.set(Jr.packageComponent.name,new W(!0,[]));V.set(Jr.deployComponent.name,new W(!0,[]));V.set(Lg.getRegistrationInfo.name,new W(!1,[]));V.set(al.userInfo.name,new W(!1,[]));V.set(ol.describeAll.name,new W(!1,[]));V.set(oee,new W(!1,[]));V.set(aee,new W(!0,[]));V.set(iee,new W(!0,[]));V.set(Ff.CSV_DATA_LOAD,new W(!1,[yi,Ro]));V.set(Ff.CSV_URL_LOAD,new W(!1,[yi,Ro]));V.set(Ff.CSV_FILE_LOAD,new W(!1,[yi,Ro]));V.set(Ff.IMPORT_FROM_S3,new W(!1,[yi,Ro]));V.set(Wv.EXPORT_TO_S3,new W(!0,[]));V.set(Wv.EXPORT_LOCAL,new W(!0,[]));V.set(hn.VALID_SQL_OPS_ENUM.DELETE,new W(!1,[Yv]));V.set(hn.VALID_SQL_OPS_ENUM.SELECT,new W(!1,[xs]));V.set(hn.VALID_SQL_OPS_ENUM.INSERT,new W(!1,[yi]));V.set(hn.VALID_SQL_OPS_ENUM.UPDATE,new W(!1,[Ro]));zv.exports={verifyPerms:lee,verifyPermsAst:uee,verifyBulkLoadAttributePerms:dee};function uee(e,t,r){if(Bs.isEmptyOrZeroLength(e))throw Dt.info("verify_perms_ast has an empty user parameter"),wr(new Error);if(Bs.isEmptyOrZeroLength(t))throw Dt.info("verify_perms_ast has an empty user parameter"),wr(new Error);if(Bs.isEmptyOrZeroLength(r))throw Dt.info("verify_perms_ast has a null operation parameter"),wr(new Error);try{let n=new Vv,s=new ree(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."),wr(new Error);let c=!!t.role.permission.super_user,u=i.includes("system");if(u&&Kv[r])throw wr(new Error,Wt.DROP_SYSTEM,sl.FORBIDDEN);if(c&&!u)return null;let _=xv.getRolePermissions(t.role);t.role.permission=_,!c&&e instanceof see.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 l=Qv(t,r,o,n);return l||(o.forEach((d,E)=>{for(let f=0;f<d.length;f++){let h=s.getAttributesBySchemaTableName(E,d[f]),p=Pg(t.role.permission,E,d[f]);Mg(h,p,r,d[f],E,n)}}),n.getPermsResponse())}catch(n){throw wr(n)}}a(uee,"verifyPermsAst");function lee(e,t){if(e===null||t===null||e.hdb_user===void 0||e.hdb_user===null)throw Dt.info("null required parameter in verifyPerms"),wr(new Error,Wt.DEFAULT_INVALID_REQUEST,sl.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 Vv;if(Bs.isEmptyOrZeroLength(e.hdb_user.role)||Bs.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(Wt.USER_HAS_NO_PERMS(e.hdb_user.username));let u=!!e.hdb_user.role.permission.super_user,_=e.hdb_user.role.permission.structure_user,l=o.has(hn.SYSTEM_SCHEMA_NAME)||s===hn.SYSTEM_SCHEMA_NAME;if(l&&Kv[r])throw wr(new Error,Wt.DROP_SYSTEM,sl.FORBIDDEN);if(u&&!l||_===!0&&(r===mn.createSchema.name||r===mn.dropSchema.name))return null;if(cee.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=xv.getRolePermissions(e.hdb_user.role);if(e.hdb_user.role.permission=d,r===Uv||r===vv){if(s===hn.SYSTEM_SCHEMA_NAME)return c.handleUnauthorizedItem(Wt.SCHEMA_PERM_ERROR(s));if(!d.super_user){if(r===Uv&&(!d[s]||!d[s][il]))return c.handleInvalidItem(Wt.SCHEMA_NOT_FOUND(s));if(r===vv&&(!d[s]||!d[s].tables[i]||!d[s].tables[i][il]))return c.handleInvalidItem(Wt.TABLE_NOT_FOUND(s,i))}}let E=Qv(e.hdb_user,r,o,c,n);if(E)return E;if(V.get(r)&&V.get(r).perms.length===0)return null;if(!u&&e.get_attributes&&hn.SEARCH_WILDCARDS.includes(e.get_attributes[0])){let p=[],S=d[s].tables[i];S[hn.PERMS_CRUD_ENUM.READ]&&(S.attribute_permissions.length>0?S.attribute_permissions.filter(R=>R[hn.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=_ee(e),h=Pg(e.hdb_user.role.permission,s,i);return Mg(f,h,r,i,s,c,n),c.getPermsResponse()}a(lee,"verifyPerms");function Qv(e,t,r,n,s){if(Bs.arrayHasEmptyValues([e,t,r]))throw Dt.info("hasPermissions has an invalid parameter"),wr(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.`),wr(new Error,Wt.OP_NOT_FOUND(t),sl.BAD_REQUEST);if(V.get(t)&&V.get(t).requires_su)return Dt.info(`operation ${t} requires SU permissions.`),n.handleUnauthorizedItem(Wt.OP_IS_SU_ONLY(t));let c=r.keys();for(let u of c){try{if(u&&!o[u]||o[u][il]===!1){n.addInvalidItem(Wt.SCHEMA_NOT_FOUND(u));continue}}catch{n.addInvalidItem(Wt.SCHEMA_NOT_FOUND(u));continue}let _=r.get(u);for(let l of _){let d=o[u].tables[l];if(!d||d[il]===!1)n.addInvalidItem(Wt.TABLE_NOT_FOUND(u,l));else try{let E=[],f=V.get(t).perms;!Bs.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(u,l,E)}catch(E){let f=Wt.UNKNOWN_OP_AUTH_ERROR(t,u,l);throw Dt.error(f),Dt.error(E),wr($v.CHECK_LOGS_WRAPPER(f))}}}return r.size<2?n.getPermsResponse():null}a(Qv,"hasPermissions");function Mg(e,t,r,n,s,i,o){if(!e||!t)throw Dt.info("no attributes specified in checkAttributePerms."),wr(new Error);let c=V.get(r).perms;if(!c||c==="")throw Dt.info(`no permissions found for ${r} in checkAttributePerms().`),wr(new Error);if(Bs.isEmptyOrZeroLength(t))return Dt.info("No role permissions set (this is OK)."),null;o&&c.includes(o)&&(c=[o]);let u={};for(let l of e){let d=t.get(l);if(d){if(d[il]===!1){i.addInvalidItem(Wt.ATTR_NOT_FOUND(s,n,l),s,n);continue}if(c)for(let E of c){if(hn.TIME_STAMP_NAMES.includes(d.attribute_name)&&E!==xs)throw wr(new Error,Wt.SYSTEM_TIMESTAMP_PERMS_ERR,sl.FORBIDDEN);d[E]===!1&&(u[d.attribute_name]?u[d.attribute_name].push(E):u[d.attribute_name]=[E])}}else i.addInvalidItem(Wt.ATTR_NOT_FOUND(s,n,l),s,n)}let _=Object.keys(u);_.length>0&&i.addUnauthorizedAttributes(_,s,n,u)}a(Mg,"checkAttributePerms");function _ee(e){let t=new Set;try{if(e.action)return t;if(e.operation===hn.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(_ee,"getRecordAttributes");function Pg(e,t,r){let n=new Map;if(Bs.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(Pg,"getAttributePermissions");function dee(e,t,r,n,s,i,o){let c=new Set(i),u=Pg(e,n,s);Mg(c,u,t,s,n,o,r)}a(dee,"verifyBulkLoadAttributePerms")});var $f=g((Lme,e0)=>{"use strict";e0.exports={evaluateSQL:yee,processAST:Zv,convertSQLToAST:Xv,checkASTPermissions:jv};var fee=qr(),Jv=require("util"),Eee=Jv.callbackify(fee.insert),hee=Gr().search,mee=RD().update,pee=Jv.callbackify(mee),See=OD().convertDelete,Ni=require("alasql"),Tee=kf(),Vf=$(),gee=Td(),Ree=z(),cl=P(),{hdb_errors:Aee,handleHDBError:Ug}=ne(),{HTTP_STATUS_CODES:vg}=Aee;gee(Ni);var Oee=403,bee="There was a problem performing this insert. Please check the logs and try again.",Bg=class{static{a(this,"ParsedSQLObject")}constructor(){this.ast=void 0,this.variant=void 0,this.permissions_checked=!1}};function yee(e,t){let r=e.parsed_sql_object;if(!r){r=Xv(e.sql);let n,s=r.ast.statements[0];if(s instanceof Ni.yy.Insert?n=s.into.databaseid:s instanceof Ni.yy.Select?n=s.from?s.from[0].databaseid:null:s instanceof Ni.yy.Update||s instanceof Ni.yy.Delete?n=s.table.databaseid:Vf.error("AST in evaluateSQL is not a valid SQL type."),!(s instanceof Ni.yy.Select)&&Ree.isEmptyOrZeroLength(n))return t("No schema specified",null)}Zv(e,r,(n,s)=>{if(n)return t(n);t(null,s)})}a(yee,"evaluateSQL");function jv(e,t){let r;try{r=Tee.verifyPermsAst(t.ast.statements[0],e.hdb_user,t.variant),t.permissions_checked=!0}catch(n){throw n}return r||null}a(jv,"checkASTPermissions");function Xv(e){let t=new Bg;if(!e)throw Ug(new Error,"The 'sql' parameter is missing from the request body",vg.BAD_REQUEST);try{let r=e.trim(),n=Ni.parse(r),s=r.split(" ")[0].toLowerCase();t.ast=n,t.variant=s}catch(r){let n=r.message.split(`
|
|
19
|
+
`);throw n[1]?Ug(r,`Invalid SQL at: ${n[1]}. Please ensure your SQL is valid. Try adding backticks to reserved words and schema table references.`,vg.BAD_REQUEST):Ug(r,"We had trouble parsing your request. Please ensure your SQL is valid. Try adding backticks to reserved words and schema table references.",vg.BAD_REQUEST)}return t}a(Xv,"convertSQLToAST");function Zv(e,t,r){try{let n=Nee;if(!e.bypass_auth&&!t.permissions_checked){let i=jv(e,t);if(i&&i.length>0)return r(Oee,i)}let s={statement:t.ast.statements[0],hdb_user:e.hdb_user};switch(t.variant){case cl.VALID_SQL_OPS_ENUM.SELECT:n=hee,s=t.ast.statements[0];break;case cl.VALID_SQL_OPS_ENUM.INSERT:n=Iee;break;case cl.VALID_SQL_OPS_ENUM.UPDATE:n=pee;break;case cl.VALID_SQL_OPS_ENUM.DELETE:n=See;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(Zv,"processAST");function Nee(e,t){Vf.info(e),t("unknown sql statement")}a(Nee,"nullFunction");function Iee({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=wee(i,e.values)}catch(o){return r(o)}Eee(s,(o,c)=>{if(o)return r(o);try{delete c.new_attributes,delete c.txn_time}catch(u){Vf.error(`Error delete new_attributes from insert response: ${u}`)}r(null,c)})}a(Iee,"convertInsert");function wee(e,t){try{return t.map(r=>{if(e.length!==r.length)throw"number of values do not match number of columns in insert";let n={};return r.forEach((s,i)=>{if(s.columnid)throw"cannot use a column in insert value";"value"in s?n[e[i]]=s.value:n[e[i]]=Ni.compile(`SELECT ${s.toString()} AS [${cl.FUNC_VAL}] FROM ?`)}),n})}catch(r){throw Vf.error(r),new Error(bee)}}a(wee,"createDataObjects")});var xg=g((Pme,r0)=>{"use strict";var{S3:Cee,GetObjectCommand:Dee}=require("@aws-sdk/client-s3");r0.exports={getFileStreamFromS3:Lee,getS3AuthObj:t0};async function Lee(e){let{s3:t}=e,r={Bucket:t.bucket,Key:t.key};return(await t0(t.aws_access_key_id,t.aws_secret_access_key,t.region).send(new Dee(r))).Body}a(Lee,"getFileStreamFromS3");function t0(e,t,r){return new Cee({credentials:{accessKeyId:e,secretAccessKey:t},region:r})}a(t0,"getS3AuthObj")});var Yf=g((vme,_0)=>{"use strict";var Gg=Gr(),Mee=$f(),Pee=xg(),{AsyncParser:Uee,Transform:vee}=require("json2csv"),ll=require("stream"),jr=z(),Hg=require("fs-extra"),Bee=require("path"),pn=$(),{promisify:i0}=require("util"),ul=z(),{handleHDBError:bt,hdb_errors:xee}=ne(),{HDB_ERROR_MSGS:Cr,HTTP_STATUS_CODES:yt}=xee,{streamAsJSON:Hee}=(rm(),ie(Mb)),{Upload:Gee}=require("@aws-sdk/lib-storage"),n0=["search_by_value","search_by_hash","sql","search_by_conditions"],s0=["json","csv"],o0="json",a0="csv",qee="Successfully exported JSON locally.",Fee="Successfully exported CSV locally.",kee=1e3,Vee=Gg.searchByHash,$ee=Gg.searchByValue,Yee=i0(Mee.evaluateSQL),Kee=i0(ll.finished);_0.exports={export_to_s3:Jee,export_local:Wee,toCsvStream:c0};async function Wee(e){pn.trace(`export_local request to path: ${e.path}, filename: ${e.filename}, format: ${e.format}`);let t=u0(e);if(!jr.isEmpty(t))throw pn.error(t),bt(new Error,t,yt.BAD_REQUEST,void 0,void 0,!0);if(jr.isEmpty(e.path))throw pn.error(Cr.MISSING_VALUE("path")),bt(new Error,Cr.MISSING_VALUE("path"),yt.BAD_REQUEST,void 0,void 0,!0);let r=(jr.isEmpty(e.filename)?new Date().getTime():e.filename)+"."+e.format;e.path.endsWith(Bee.sep)&&(e.path=e.path.substring(0,e.path.length-1));let n=jr.buildFolderPath(e.path,r);await Qee(e.path);let s=await l0(e);return await zee(n,e.format,s)}a(Wee,"export_local");async function Qee(e){if(pn.trace("in confirmPath"),jr.isEmptyOrZeroLength(e))throw bt(new Error,`Invalid path: ${e}`,yt.BAD_REQUEST,void 0,void 0,!0);let t;try{t=await Hg.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,pn.error(n),bt(new Error,n,yt.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 pn.error(r),bt(new Error,r,yt.BAD_REQUEST,void 0,void 0,!0)}return!0}a(Qee,"confirmPath");async function zee(e,t,r){if(pn.trace("in saveToLocal"),ul.isEmptyOrZeroLength(e))throw bt(new Error,Cr.INVALID_VALUE("file_path"),yt.BAD_REQUEST,void 0,void 0,!0);if(ul.isEmptyOrZeroLength(t))throw bt(new Error,Cr.INVALID_VALUE("Source format"),yt.BAD_REQUEST,void 0,void 0,!0);if(ul.isEmpty(r))throw bt(new Error,Cr.NOT_FOUND("Data"),yt.BAD_REQUEST,void 0,void 0,!0);if(t===o0){let n=Hg.createWriteStream(e);return Hee(r).pipe(n),await Kee(n),{message:qee,path:e}}else if(t===a0){let n=Hg.createWriteStream(e),s=ll.Readable.from(r),i={},o=r.getColumns?.();o&&(i.fields=o.map(l=>({label:l,value:l})));let c={objectMode:!0};return await new Uee(i,c).fromInput(s).toOutput(n).promise(!1),{message:Fee,path:e}}throw bt(new Error,Cr.INVALID_VALUE("format"),yt.BAD_REQUEST)}a(zee,"saveToLocal");async function Jee(e){if(!e.s3||Object.keys(e.s3).length===0)throw bt(new Error,Cr.MISSING_VALUE("S3 object"),yt.BAD_REQUEST);if(jr.isEmptyOrZeroLength(e.s3.aws_access_key_id))throw bt(new Error,Cr.MISSING_VALUE("aws_access_key_id"),yt.BAD_REQUEST);if(jr.isEmptyOrZeroLength(e.s3.aws_secret_access_key))throw bt(new Error,Cr.MISSING_VALUE("aws_secret_access_key"),yt.BAD_REQUEST);if(jr.isEmptyOrZeroLength(e.s3.bucket))throw bt(new Error,Cr.MISSING_VALUE("bucket"),yt.BAD_REQUEST);if(jr.isEmptyOrZeroLength(e.s3.key))throw bt(new Error,Cr.MISSING_VALUE("key"),yt.BAD_REQUEST);if(jr.isEmptyOrZeroLength(e.s3.region))throw bt(new Error,Cr.MISSING_VALUE("region"),yt.BAD_REQUEST);let t=u0(e);if(!jr.isEmpty(t))throw bt(new Error,t,yt.BAD_REQUEST);pn.trace(`called export_to_s3 to bucket: ${e.s3.bucket} and query ${e.search_operation.sql}`);let r;try{r=await l0(e)}catch(u){throw pn.error(u),u}let n,s=await Pee.getS3AuthObj(e.s3.aws_access_key_id,e.s3.aws_secret_access_key,e.s3.region),i,o=new ll.PassThrough;if(e.format===a0){i=e.s3.key+".csv";let u=c0(r,r.getColumns?.());u.on("error",_=>{throw _}),u.pipe(o)}else if(e.format===o0){i=e.s3.key+".json";let u=new ll.Readable;u.pipe(o),u.on("error",d=>{throw d}),u.push("[");let _=r.length,l="";for(let[d,E]of r.entries()){let f=d===_-1?JSON.stringify(E):JSON.stringify(E)+",";l+=f,d!==0&&d%kee===0&&(u.push(l),l="")}l.length!==0&&u.push(l),u.push("]"),u.push(null)}else throw bt(new Error,Cr.INVALID_VALUE("format"),yt.BAD_REQUEST);return new Gee({client:s,params:{Bucket:e.s3.bucket,Key:i,Body:o}}).done()}a(Jee,"export_to_s3");function c0(e,t){let r=ll.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 vee(n,s);return r.pipe(i)}a(c0,"toCsvStream");function u0(e){if(pn.trace("in exportCoreValidation"),jr.isEmpty(e.format))return"format missing";if(s0.indexOf(e.format)<0)return`format invalid. must be one of the following values: ${s0.join(", ")}`;let t=e.search_operation.operation;if(jr.isEmpty(t))return"search_operation.operation missing";if(n0.indexOf(t)<0)return`search_operation.operation must be one of the following values: ${n0.join(", ")}`}a(u0,"exportCoreValidation");async function l0(e){pn.trace("in getRecords");let t,r;if(ul.isEmpty(e.search_operation)||ul.isEmptyOrZeroLength(e.search_operation.operation))throw bt(new Error,Cr.INVALID_VALUE("Search operation"),yt.BAD_REQUEST);switch(e.search_operation.operation){case"search_by_value":t=$ee;break;case"search_by_hash":t=Vee;break;case"search_by_conditions":t=Gg.searchByConditions;break;case"sql":t=Yee;break;default:throw r=`Operation ${e.search_operation.operation} is not support by export.`,pn.error(r),bt(new Error,r,yt.BAD_REQUEST)}return e.search_operation.hdb_user=e.hdb_user,t(e.search_operation)}a(l0,"getRecords")});var T0={};Fe(T0,{contentTypes:()=>Vg,findBestSerializer:()=>Qf,getDeserializer:()=>Oo,registerContentHandlers:()=>$g,serialize:()=>zf,serializeMessage:()=>To});function jee(e){try{return e?.[0]===123?kg(e):e}catch{return e}}function $g(e){e.register(Zee,{serializers:[{regex:/^application\/json$/,serializer:Nc},{regex:/^application\/cbor$/,serializer:function(t){return new Ao.EncoderStream(dl).end(t)}},{regex:/^application\/(x-)?msgpack$/,serializer:function(t){return(t?.[Symbol.iterator]||t?.[Symbol.asyncIterator])&&!Array.isArray(t)?Wf.Readable.from((0,ls.encodeIter)(t,dl)):(0,ls.pack)(t)}},{regex:/^text\/csv$/,serializer:function(t){return this.header("Content-Disposition",'attachment; filename="data.csv"'),(0,Kf.toCsvStream)(t)}}]}),e.addContentTypeParser("application/x-msgpack",{parseAs:"buffer"},(t,r,n)=>{try{n(null,(0,ls.unpack)(r))}catch(s){s.statusCode=400,n(s)}}),e.addContentTypeParser("application/cbor",{parseAs:"buffer"},(t,r,n)=>{try{n(null,(0,Ao.decode)(r))}catch(s){s.statusCode=400,n(s)}})}function Qf(e){let r=(e.headers.asObject||e.headers).accept,n,s=0,i,o,c=r?r.toLowerCase().split(/\s*,\s*/):[];for(let u of c){let[_,...l]=u.split(/\s*;\s*/),d=1,E={q:1};for(let h of l){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)return{serializer(){this.code(406).send("No supported content types found in Accept header, supported types include: "+Array.from(Ft.keys()).join(", "))}};n=Ft.get("application/json"),i="application/json"}return{serializer:n,type:i,parameters:o}}function zf(e,t,r){let n=f0&&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=Qf(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,Hs.createBrotliCompress)({params:{[Hs.constants.BROTLI_PARAM_MODE]:i.type.includes("json")||i.type.includes("text")?Hs.constants.BROTLI_MODE_TEXT:Hs.constants.BROTLI_MODE_GENERIC,[Hs.constants.BROTLI_PARAM_QUALITY]:2}}))),o}s=i.serializer.serialize(e,r)}return n&&s?.length>f0?(r.headers.set("Content-Encoding","br"),new Promise((i,o)=>(0,Hs.brotliCompress)(s,(c,u)=>{c?o(c):i(u)}))):s}function To(e,t){if(e?.contentType!=null&&e.data!=null)return e.data;if(!t)return _l(e);let r=t.serialize;if(r)return r(e);let n=Qf(t);return r=t.serialize=n.serializer.serialize,r(e)}function ete(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 Oo(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||E0(e,n);return o=>ete(o).then(i)}return e&&Ft.get(e)?.deserialize||E0(e,n)}function E0(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 kg(r)}catch{}return{contentType:e||"application/octet-stream",data:r}}}function tte(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 Kf,ls,Ao,Hs,Wf,h0,qg,Fg,m0,p0,_l,kg,dl,Ft,Vg,d0,S0,Xee,Zee,f0,Ca=Re(()=>{rm();Kf=B(Yf()),ls=require("msgpackr"),Ao=require("cbor-x"),Hs=require("zlib"),Wf=require("stream");lr();h0=require("../index"),qg=B(Z()),Fg=B(P()),m0=B(require("yaml")),p0=qg.default.get(Fg.CONFIG_PARAMS.SERIALIZATION_BIGINT)!==!1,_l=p0?Hi:JSON.stringify,kg=p0?tm:JSON.parse,dl={useRecords:!1,useToJSON:!0},Ft=new Map,Vg=Ft;at.contentTypes=Vg;(0,h0._assignPackageExport)("contentTypes",Vg);Ft.set("application/json",{serializeStream:Nc,serialize:_l,deserialize:kg,q:.8});d0=new Ao.Encoder(dl);Ft.set("application/cbor",{serializeStream(e){return e[Symbol.asyncIterator]&&(e[Symbol.iterator]=null),new Ao.EncoderStream(dl).end(e)},serialize:d0.encode,deserialize:d0.decode,q:1});Ft.set("application/x-msgpack",{serializeStream(e){return(e?.[Symbol.iterator]||e?.[Symbol.asyncIterator])&&!Array.isArray(e)?Wf.Readable.from((0,ls.encodeIter)(e,dl)):(0,ls.pack)(e)},serialize:ls.pack,deserialize:ls.unpack,q:.9});Ft.set("text/csv",{serializeStream(e,t){return t.headers.set("Content-Disposition",'attachment; filename="data.csv"'),(0,Kf.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,Kf.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 m0.stringify(e,{aliasDuplicateObjects:!1})},q:.7});Ft.set("text/event-stream",{serializeStream:function(e){return Wf.Readable.from(tte(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+`
|
|
20
|
+
`),e.data){let r=e.data;typeof r=="object"&&(r=_l(r)),t+="data: "+r+`
|
|
21
21
|
`}return e.id&&(t+="id: "+e.id+`
|
|
22
22
|
`),e.retry&&(t+="retry: "+e.retry+`
|
|
23
23
|
`),t+`
|
|
24
|
-
`}else return typeof e=="object"?`data: ${
|
|
24
|
+
`}else return typeof e=="object"?`data: ${_l(e)}
|
|
25
25
|
|
|
26
26
|
`:`data: ${e}
|
|
27
27
|
|
|
28
|
-
`},compressible:!1,q:.8});qt.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()}});S0={type:"application/json",serializeStream:bc,serialize:ul,deserialize:Wee,q:.5};qt.set("*/*",S0);qt.set("",S0);a(Wee,"tryJSONParse");a(Vg,"registerContentHandlers");Qee=require("fastify-plugin"),zee=Qee(function(e,t,r){e.addHook("preSerialization",async(n,s)=>{if(s.raw.getHeader("content-type"))return;let{serializer:o,type:c}=Kf(n.raw);s.type(c),s.serializer(function(u){return(o.serializeStream||o.serialize)(u,{headers:{set:(_,l)=>{s.header(_,l)}}})})}),r()},{name:"content-type-negotiation"});a(Kf,"findBestSerializer");f0=Gg.default.get(qg.CONFIG_PARAMS.HTTP_COMPRESSIONTHRESHOLD);a(Wf,"serialize");a(To,"serializeMessage");a(Jee,"streamToBuffer");a(Oo,"getDeserializer");a(E0,"deserializerUnknownType");a(jee,"transformIterable")});function Kg(e,t,r,n,s,i,o,c){let u=e[0];if(t==="or"){let d=_(u);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=_(u),E=l(e.slice(1),!0,u.estimated_count);return E.length>0?o(d,E):d}function _(d){return d.conditions?Kg(d.conditions,d.operator,r,n,s,i,o,c):Ha(d,n,d.descending||s.reverse===!0,r,s.allowFullScan,c)}a(_,"executeCondition");function l(d,E,f){return d.map((h,p)=>{if(h.conditions){let A=h.operator==="or",R=l(h.conditions,!A,f);return A?(C,x)=>R.some(v=>v(C,x)):(C,x)=>R.every(v=>v(C,x))}let S=(h.attribute||h[0])===r.primaryKey,T=Qg(h,r,i,c,S,f);return E&&p<d.length-1&&f&&(f=ote(r.primaryStore,h.estimated_count,f)),T}).filter(Boolean)}a(l,"mapConditionsToFilters")}function Ha(e,t,r,n,s,i){let o=e[0]??e.attribute,c=e[1]??e.value,u=e.comparator;if(Array.isArray(o)){let A=o[0],R=Gs(n.attributes,A);if(R.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=R.definition?.tableClass||R.elements?.definition?.tableClass,x=new Map,v=Ha({attribute:o.length>2?o.slice(1):o[1],value:c,comparator:u},t,r,C,s,x);if(R.relationship.to){i[o[0]]=x;let k=!!Gs(C.attributes,R.relationship.to)?.elements;v=rte(v,R,C.primaryStore,k,x)}if(R.relationship.from){let k=a(M=>Ha({attribute:R.relationship.from,value:M},t,r,n,s,x),"searchEntry");R.elements?(i[o[0]]=x,v=nte(v,R,C.primaryStore,x,k)):v=v.flatMap(k)}return v}else if(o.length===1)o=o[0];else throw new Xr.ClientError("Unable to query by attribute "+JSON.stringify(o))}let _,l,d,E;c instanceof Date&&(c=c.getTime());let f;switch(Wg[u]||u){case"lt":_=!0,l=c;break;case"le":_=!0,l=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,l=c.slice(0),l[l.length-1]=ls.MAXIMUM_KEY;break;case"starts_with":_=c.toString(),l=c+"\uFFFF";break;case"between":_=c[0],_ instanceof Date&&(_=_.getTime()),l=c[1],l instanceof Date&&(l=l.getTime()),d=!0;break;case"equals":case void 0:_=c,l=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 "${u}"`)}if(r){let A=_;_=l,l=A,A=!E,E=!d,d=A}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 ${u||"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=Qg(e),!S)throw new Xr.ClientError(`Unknown search operator ${e.comparator}`)}let T={start:_,end:l,inclusiveEnd:d,exclusiveStart:E,values:!0,versions:h,transaction:t,reverse:r};if(h){let A=p.getRange(T).map(S?function({key:R,value:C}){return this.isSync?C&&S(C)?R:Ii.SKIP:new Promise((x,v)=>setImmediate(()=>{try{x(C&&S(C)?R:Ii.SKIP)}catch(k){v(k)}}))}:R=>R.value==null?Ii.SKIP:R);return A.hasEntries=!0,A}else return p?p.getRange(T).map(S?function({key:A,value:R}){return this.isSync?S({[o]:A})?R:Ii.SKIP:new Promise((C,x)=>setImmediate(()=>{try{C(S({[o]:A})?R:Ii.SKIP)}catch(v){x(v)}}))}:({value:A})=>A):n.primaryStore.getRange(r?{end:!0,transaction:t,reverse:!0}:{start:!0,transaction:t}).map(function({key:A,value:R}){return this.isSync?R&&S(R)?A:Ii.SKIP:new Promise((C,x)=>setImmediate(()=>{try{C(R&&S(R)?A:Ii.SKIP)}catch(v){x(v)}}))})}function Gs(e,t){if(Array.isArray(t))if(t.length>1){let r=Gs(e,t[0]),n=(r?.definition?.tableClass||r?.elements.definition?.tableClass)?.attributes;return n?Gs(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 rte(e,t,r,n,s){return new e.constructor({[Symbol.iterator](){let i;s.hasMappings=!0;let o;return{next(){if(!i){let u=t.relationship.to,_=a((l,d)=>{let E=l;Array.isArray(l)&&(E=xn(l),o=!0);let f=s.get(E);f?f.push(d):s.set(E,f=[d]),l!==E&&(f.key=l)},"add_entry");for(let l of e){let d=l.value??r.get(l.key??l),E=d?.[u];if(E!=null&&!s.filters?.some(f=>!f(d)))if(n)for(let f=0;f<E.length;f++)_(E[f],l);else _(E,l)}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 nte(e,t,r,n,s){return new e.constructor({[Symbol.iterator](){let i,o,c=new Set;return{next(){let u;if(o)for(;u=o.next(),!u.done;){let _=xn(u.value);if(!c.has(_))return c.add(_),u}if(!i){let _=new Map;n.fromRecord=l=>l[t.relationship.from]?.filter?.(d=>_.has(xn(d)));for(let l of e){if(n.filters){let d=r.get(l);if(n.filters.some(E=>!E(d)))continue}_.set(xn(l),l)}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 Qg(e,t,r,n,s,i){let o=e.comparator,c=e[0]??e.attribute,u=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 l=c[0],d=Gs(t.attributes,l),E=d.definition?.tableClass||d.elements.definition?.tableClass,f=n?.[l],h=Qg({attribute:c.length>2?c.slice(1):c[1],value:u,comparator:o},E,r,f?.[l]?.joined,c[1]===E.primaryKey,i);if(!h)return;if(f){f.filters||(f.filters=[]),f.filters.push(h);return}let p=t.propertyResolvers?.[l],S,T=a((A,R)=>{let C,x;if(p){if(p.from&&h.idFilter){if(!S)if(h.idFilter.idSet?.size===1){for(let k of h.idFilter.idSet)e={attribute:p.from,value:k};S=_(p.from,h.idFilter,!0,!0)}else S=_(p.from,h.idFilter,!1,!0);let v=S(A);return S.idFilter&&(T.idFilter=S.idFilter),v}x=p(A,r,R),C=x?.value}else C=A[l];return C?Array.isArray(C)?C.some(h):h(C,x):!1},"recordFilter");return T}}switch(u instanceof Date&&(u=u.getTime()),Wg[o]||o){case $g.SEARCH_TYPES.EQUALS:case void 0:return _(c,l=>l===u,!0);case"contains":return _(c,l=>l?.toString().includes(u));case"ends_with":return _(c,l=>l?.toString().endsWith(u));case"starts_with":return _(c,l=>typeof l=="string"&&l.startsWith(u),!0);case"prefix":return Array.isArray(u)?u[u.length-1]==null&&(u=u.slice(0,-1)):u=[u],_(c,l=>{if(!Array.isArray(l))return!1;for(let d=0,E=u.length;d<E;d++)if(l[d]!==u[d])return!1;return!0},!0);case"between":return u[0]instanceof Date&&(u[0]=u[0].getTime()),u[1]instanceof Date&&(u[1]=u[1].getTime()),_(c,l=>(0,ls.compareKeys)(l,u[0])>=0&&(0,ls.compareKeys)(l,u[1])<=0,!0);case"gt":return _(c,l=>(0,ls.compareKeys)(l,u)>0);case"ge":return _(c,l=>(0,ls.compareKeys)(l,u)>=0);case"lt":return _(c,l=>(0,ls.compareKeys)(l,u)<0);case"le":return _(c,l=>(0,ls.compareKeys)(l,u)<=0);case"ne":return _(c,l=>(0,ls.compareKeys)(l,u)!==0);case"sort":return()=>!0;default:throw new Xr.ClientError(`Unknown query comparator "${o}"`)}function _(l,d,E,f){let h;E=E&&!s&&t?.indices[l]&&i>3,E&&(e.estimated_count==null&&zf(t)(e),h=e.estimated_count>>4,(isNaN(h)||h>=i)&&(E=!1));let p=0,S=3;function T(A){let R=A[l],C;if(typeof R!="object"||!R||f?C=d(R):Array.isArray(R)?C=R.some(d):R instanceof Date&&(C=d(R.getTime())),E&&(S++,!C&&!T.idFilter&&++p/S*(i-S)>h)){let x=Ha(e,r.transaction.getReadTxn(),!1,t).map(xn),v=new Set(x);T.idFilter=k=>v.has(xn(k)),T.idFilter.idSet=v}return C}return a(T,"recordFilter"),s&&(T.idFilter=d),T}a(_,"attributeComparator")}function zf(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/xs(e.primaryStore):i.estimated_count}return r.estimated_count=s,r.estimated_count}let n=r.comparator||r.search_type;if(n=Wg[n]||n,n===$g.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=Gs(e.attributes,s[0]),o=i.definition?.tableClass||i.elements.definition?.tableClass,c=zf(o)({value:r.value,attribute:s.length>2?s.slice(1):s[1],comparator:"equals"}),u=e.indices[i.relationship.from];r.estimated_count=c+(u?c*xs(e.indices[i.relationship.from])/(xs(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=xs(e.primaryStore)-(i?i.getValuesCount(null):0):r.estimated_count=1/0}else n==="starts_with"||n==="prefix"?r.estimated_count=ete*xs(e.primaryStore)+1:n==="between"?r.estimated_count=Zee*xs(e.primaryStore)+1:n==="sort"?r.estimated_count=xs(e.primaryStore)+1:r.estimated_count=Xee*xs(e.primaryStore)+1;typeof r.descending=="boolean"&&(r.estimated_count/=2)}return r.estimated_count}return a(t,"estimateConditionForTable"),t}function Jf(e){if(e)if(wi=e,va.lastIndex=0,ste.test(e))try{let t=_l(new Ba,"");if(Cr!==wi.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 '${wi}'`,t}else{let t=new URLSearchParams(e);return t.conditions=t,t}}function _l(e,t){let r=va,n,s,i,o,c,u=decodeURIComponent,_;for(;n=r.exec(wi);){Cr=r.lastIndex;let[,l,d]=n;if(o){if(l)throw new SyntaxError(`expected operator, but encountered '${l}'`);o=!1,c=!1}else c=!0;let E;switch(d){case"=":if(s){if(l.length<=2)i=l;else throw new SyntaxError(`invalid FIQL operator ${l}`);u=g0}else{if(u=decodeURIComponent,i="equals",!l)throw new SyntaxError("attribute must be specified before equality comparator");s=dl(l)}break;case"==":case"!=":case"<":case"<=":case">":case">=":case"===":case"!==":if(i=tte[d],u=Yg[i]?g0:decodeURIComponent,!l)throw new SyntaxError(`attribute must be specified before comparator ${d}`);s=dl(l);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:u(l)};i==="eq"&&R0(h,l),Qf(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(dl(l)),s=void 0;break;case"(":va.lastIndex=Cr;let f=_l(l?[]:new Ba,")");switch(l){case"":Qf(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=A0(f);break;default:throw new SyntaxError(`unknown query function call ${l}`)}wi[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(!l)throw new SyntaxError("property sets must have a defined parent property name");va.lastIndex=Cr,E=_l([],"}"),E.name=l,e.push(E),wi[Cr]===","?r.lastIndex=++Cr:o=!0;break;case"[":va.lastIndex=Cr,l?(E=_l(new Ba,"]"),E.name=l):E=_l(e.conditions?new Ba:[],"]"),e.conditions?(Qf(e,_),e.conditions.push(E),s=null):e.push(E),wi[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:u(l)};i==="eq"&&R0(h,l),Qf(e,_),e.conditions.push(h)}else if(l)throw new SyntaxError("no attribute or comparison specified")}else(l||e.length>0&&c)&&e.push(dl(l));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?ite:va,r.lastIndex=Cr),Cr===wi.length)return e}if(t)throw new SyntaxError(`expected '${t}', but encountered end of string`)}function Qf(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 dl(e){return e.indexOf(".")>-1?e.split(".").map(dl):decodeURIComponent(e)}function g0(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 R0(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 A0(e){let t=O0(e[0]);return e.length>1&&(t.next=A0(e.slice(1))),t}function O0(e){if(Array.isArray(e)){let t=O0(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 xn(e){return Array.isArray(e)?e.join("\0"):e}function xs(e){let t=Date.now();return(e.estimatedEntryCountExpires||0)<t&&(e.estimatedEntryCount=e.getStats().entryCount,e.estimatedEntryCountExpires=t+1e4),e.estimatedEntryCount}function ote(e,t,r){return t*r/xs(e)}var Xr,$g,ls,Ii,Xee,Zee,ete,tte,Yg,Wg,ste,va,ite,Cr,wi,Ba,jf=Ae(()=>{Xr=B(ne()),$g=B(_t()),ls=require("ordered-binary"),Ii=require("lmdb"),Xee=.3,Zee=.1,ete=.05,tte={"<":"lt","<=":"le",">":"gt",">=":"ge","!=":"ne","==":"eq","===":"equals","!==":"not_equal"},Yg={lt:!0,le:!0,gt:!0,ge:!0,ne:!0,eq:!0};a(Kg,"executeConditions");a(Ha,"searchByIndex");a(Gs,"findAttribute");a(rte,"joinTo");a(nte,"joinFrom");Wg={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(Qg,"filterByType");a(zf,"estimateCondition");ste=/[()[\]|!<>.]|(=\w*=)/,va=/([^?&|=<>!([{}\]),]*)([([{}\])|,&]|[=<>!]*)/g,ite=/([^&|=[\]{}]+)([[\]{}]|[&|=]*)/g;a(Jf,"parseQuery");a(_l,"parseBlock");a(Qf,"assignOperator");a(dl,"decodeProperty");a(g0,"typedDecoding");a(R0,"wildcardDecoding");a(A0,"toSortObject");a(O0,"toSortEntry");Ba=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(xn,"flattenKey");a(xs,"estimatedEntryCount");a(ote,"intersectionEstimate")});function w0(e){let t={openapi:ate,info:{title:"HarperDB HTTP REST interface",version:(0,I0.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:u}=n.Resource;if(c=c??"id",!c)continue;let _={},l=[];if(o)for(let{type:R,name:C,elements:x,relationship:v,definition:k}of o){if(v)R==="array"?_[C]={type:"array",items:{$ref:Ci+x.type}}:_[C]={$ref:Ci+R};else{let M=k??x?.definition;if(M){if(!t.components.schemas[M.type]){let Q={};M.properties.forEach(j=>{Q[j.name]=new Xg(zg[j.type],j.type)}),t.components.schemas[M.type]=new N0(Q)}R==="array"?_[C]={type:"array",items:{$ref:Ci+M.type}}:_[C]={$ref:Ci+M.type}}else R==="array"?x.type==="Any"||x.type=="ID"?_[C]={type:"array",items:{format:x.type}}:_[C]={type:"array",items:new Xg(zg[x.type],x.type)}:R==="Any"||R=="ID"?_[C]={format:R}:_[C]=new Xg(zg[R],R)}l.push(new Zg(C,"query",_[C]))}let d=Object.keys(_),E=new Zg(c,"path",{format:"ID"});E.required=!0,E.description="primary key of record";let f=new Zg("property","path",{enum:d});f.required=!0,t.components.schemas[i]=new N0(_);let h=u.post!==Resource.prototype.post||u.update,p=typeof u.put=="function",S=typeof u.get=="function",T=typeof u.delete=="function",A="/"+s+"/";h&&(t.paths[A]={},t.paths[A].post=new cte(i,r,"create a new record auto-assigning a primary key")),S&&(t.paths[A]||(t.paths[A]={}),t.paths[A].get=new Jg(l,r,{200:new jg({$ref:Ci+i})},"search for records by the specified property name and value pairs")),T&&(t.paths[A]||(t.paths[A]={}),t.paths[A].delete=new y0(l,r,"delete all the records that match the provided query",{204:new b0})),A="/"+s+"/{"+c+"}",S&&(t.paths[A]={},t.paths[A].get=new Jg([E],r,{200:new jg({$ref:Ci+i})},"retrieve a record by its primary key")),p&&(t.paths[A]||(t.paths[A]={}),t.paths[A].put=new ute([E],r,i,"create or update the record with the URL path that maps to the record's primary key")),T&&(t.paths[A]||(t.paths[A]={}),t.paths[A].delete=new y0([E],r,"delete a record with the given primary key",{204:new b0})),S&&f.schema.enum.length>0&&(A="/"+s+"/{"+c+"}.{property}",t.paths[A]={},t.paths[A].get=new Jg([E,f],r,{200:new jg({enum:d})},"used to retrieve the specified property of the specified record"))}return t}function cte(e,t,r){this.description=r,this.requestBody={content:{"application/json":{schema:{$ref:Ci+e}}}},this.security=t,this.responses={200:{description:eR,headers:{Location:{description:"primary key of new record",schema:{type:"string",format:"ID"}}},content:{"application/json":{schema:{type:"string",format:"ID"}}}}}}function Jg(e,t,r,n){this.description=n,this.parameters=e,this.security=t,this.responses=r}function jg(e){this.description=eR,this.content={"application/json":{schema:e}}}function b0(){this.description="successfully processed request, no content returned to client"}function ute(e,t,r,n){this.description=n,this.parameters=e,this.security=t,this.requestBody={content:{"application/json":{schema:{$ref:Ci+r}}}},this.responses={200:{description:eR}}}function y0(e,t,r,n){this.description=r,this.parameters=e,this.security=t,this.responses=n}function N0(e){this.type="object",this.properties=e}function Xg(e,t){this.type=e,this.format=t}function Zg(e,t,r){this.name=e,this.in=t,this.schema=r}var I0,ate,zg,Ci,eR,C0=Ae(()=>{I0=B(Kd()),ate="3.0.3",zg={Int:"integer",Float:"number",Long:"integer",String:"string",Boolean:"boolean",Date:"string",Bytes:"string",BigInt:"integer",array:"array"},Ci="#/components/schemas/",eR="successful operation";a(w0,"generateJsonApi");a(cte,"Post");a(Jg,"Get");a(jg,"Response200");a(b0,"Response204");a(ute,"Put");a(y0,"Delete");a(N0,"ResourceSchema");a(Xg,"Type");a(Zg,"Parameter")});var Zf={};qe(Zf,{start:()=>dte});async function _te(e,t){let r=e.headers.asObject,n=r.accept==="text/event-stream"?"CONNECT":e.method;e.search&&Jf(e);let s=new bi;try{e.responseHeaders=s;let i=e.url.slice(1),o,c;if(i!==D0){let h=Xf.getMatch(i);if(!h)return t(e);e.handlerPath=h.path,o={url:h.relativeURL,async:!0},c=h.Resource}let u=r["cache-control"];if(u){u=u.toLowerCase();let h=u.match(/max-age=(\d+)/)?.[1];h&&(e.expiresAt=h*1e3+Date.now()),u.includes("only-if-cached")&&(e.onlyIfCached=!0),u.includes("no-cache")&&(e.noCache=!0),u.includes("no-store")&&(e.noCacheStore=!0),u.includes("stale-if-error")&&(e.staleIfError=!0),u.includes("must-revalidate")&&(e.mustRevalidate=!0)}let _=await Xe(e,()=>{if(r["content-length"]||r["transfer-encoding"])try{e.data=Oo(r["content-type"],!0)(e.body,e.headers)}catch(h){throw new xa.ClientError(h,400)}if(e.authorize=!0,i===D0&&n==="GET"){if(e?.user?.role?.permission?.super_user)return w0(Xf);throw new xa.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 xa.ClientError("HarperDB is short and stout and can't brew coffee",418);default:throw new xa.ServerError(`Method ${n} is not recognized`,501)}}),l=200,d;if(_==null)l=n==="GET"||n==="HEAD"?404:204,tR.lastModified&&e.lastModified&&s.setIfNone("Last-Modified",new Date(e.lastModified).toUTCString());else if(d=e.lastModified){lte[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(),l=304,_=void 0):s.setIfNone("ETag",h),tR.lastModified&&s.setIfNone("Last-Modified",new Date(d).toUTCString())}e.createdResource&&(l=201),e.newLocation&&s.setIfNone("Location",e.newLocation);let E={status:l,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=Wf(_,e,E),n==="HEAD"&&(E.body=void 0)),E}catch(i){i.statusCode?i.statusCode===500?bo.warn(i):bo.info(i):bo.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=Wf(i.contentType?i:i.toString(),e,o),o}}function dte(e){tR=e,!L0&&(L0=!0,Xf=e.resources,e.server.http(async(t,r)=>{if(!t.isWebSocket)return _te(t,r)},e),e.server.ws(async(t,r,n)=>{fl++;let s=new yn;M0||(M0=!0,_u(u=>{fl>0&&u.push({metric:"ws-connections",connections:fl,byThread:!0})}));let i;t.on("error",u=>{i=!0,bo.warn(u)});let o;t.on("message",a(function(_){o||(o=Oo(r.headers.asObject["content-type"]));let l=o(_);s.push(l)},"message"));let c;t.on("close",()=>{fl--,Wr(!i,"connection","ws","disconnect"),s.emit("close"),c&&c.return()});try{await n;let u=r.url.slice(1),_=Xf.getMatch(u);if(Wr(!!_,"connection","ws","connect"),_){r.handlerPath=_.path,pr(h=>({count:h.count,total:fl}),"connections",r.handlerPath,"connect","ws"),r.authorize=!0;let l={url:_.relativeURL,async:!0},d=_.Resource;c=(await Xe(r,()=>d.connect(l,s,r)))[Symbol.asyncIterator]();let f;for(;!(f=await c.next()).done;){let h=To(f.value,r);t.send(h),pr(h.length,"bytes-sent",r.handlerPath,"message","ws")}}else return t.close(1011,`No resource was found to handle ${r.pathname}`)}catch(u){t.close(fte[u.statusCode]||1011,u.toString()),t.close("login fialed")}t.close()},e))}var bo,xa,Wt,lte,tR,D0,L0,Xf,M0,fl,fte,P0=Ae(()=>{wa();ws();bo=B($()),xa=B(ne());jf();Ac();ro();Qu();C0();Wt=new Uint8Array(8),lte=new Float64Array(Wt.buffer,0,1),tR={},D0="openapi";a(_te,"http");fl=0;a(dte,"start");fte={401:3e3,403:3003}});var rR=g((Qme,U0)=>{var{recordAction:eE,recordActionBinary:Ete}=(ws(),ie(du)),hte=require("fastify-plugin"),mte=200;U0.exports=hte(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(),u=s.request.routeOptions,_,l,d;u.config?.isOperation?(_=n.body?.operation,l="operation"):(_=u.url,l="fastify-route",d=u.method),eE(o,"duration",_,d,l),Ete(s.raw.statusCode<400,"success",_,d,l);let E=mte;i?.pipe?(i.on("data",h=>{E+=h.length}),i.on("end",()=>{eE(performance.now()-c,"transfer",_,d,l),eE(E,"bytes-sent",_,d,l)})):(E+=i?.length||0,eE(E,"bytes-sent",_,d,l));let f=o.toFixed(3);s.header("Server-Timing",`db;dur=${f}`)}),r()},{name:"hdb-request-time"})});var cR=g((jme,x0)=>{var sE=require("clone"),iE=je(),pte=J(),rE=P(),zme=$(),nR=require("fs"),iR=require("joi"),{string:nE}=iR.types(),{hdb_errors:Ste,handleHDBError:tE}=ne(),{HDB_ERROR_MSGS:Jme,HTTP_STATUS_CODES:sR}=Ste,{common_validators:Ga}=zn(),v0=" is required",Tte=["insert","update","upsert"],oR={database:{presence:!1,format:Ga.schema_format,length:Ga.schema_length},schema:{presence:!1,format:Ga.schema_format,length:Ga.schema_length},table:{presence:!0,format:Ga.schema_format,length:Ga.schema_length},action:{inclusion:{within:Tte,message:"is required and must be either insert, update, or upsert"}},file_path:{},csv_url:{url:{allowLocal:!0}},data:{},passthrough_headers:{}},gte={schema:nE.required(),table:nE.required(),action:nE.valid("insert","update","upsert")},{AWS_ACCESS_KEY:Rte,AWS_SECRET:Ate,AWS_BUCKET:Ote,AWS_FILE_KEY:bte,REGION:yte}=rE.S3_BUCKET_AUTH_KEYS,Nte={s3:{presence:!0},[`s3.${Rte}`]:{presence:!0,type:"String"},[`s3.${Ate}`]:{presence:!0,type:"String"},[`s3.${Ote}`]:{presence:!0,type:"String"},[`s3.${bte}`]:{presence:!0,type:"String",hasValidFileExt:[".csv",".json"]},[`s3.${yte}`]:{presence:!0,type:"String"}},B0=sE(oR);B0.data.presence={message:v0};var H0=sE(oR);H0.file_path.presence={message:v0};var Ite=Object.assign(sE(oR),Nte),aR=sE(gte);aR.csv_url=nE.uri().messages({"string.uri":"'csv_url' must be a valid url"}).required();aR.passthrough_headers=iR.object();function wte(e){let t=iE.validateObject(e,B0);return oE(e,t)}a(wte,"dataObject");function Cte(e){let t=iE.validateBySchema(e,iR.object(aR));return oE(e,t)}a(Cte,"urlObject");function Dte(e){let t=iE.validateObject(e,H0);return oE(e,t)}a(Dte,"fileObject");function Lte(e){let t=iE.validateObject(e,Ite);return oE(e,t)}a(Lte,"s3FileObject");function oE(e,t){if(!t){let r=pte.checkGlobalSchemaTable(e.schema,e.table);if(r)return tE(new Error,r,sR.BAD_REQUEST);if(e.operation===rE.OPERATIONS_ENUM.CSV_FILE_LOAD)try{nR.accessSync(e.file_path,nR.constants.R_OK|nR.constants.F_OK)}catch(n){return n.code===rE.NODE_ERROR_CODES.ENOENT?tE(n,`No such file or directory ${n.path}`,sR.BAD_REQUEST):n.code===rE.NODE_ERROR_CODES.EACCES?tE(n,`Permission denied ${n.path}`,sR.BAD_REQUEST):tE(n)}}return t}a(oE,"postValidateChecks");x0.exports={dataObject:wte,urlObject:Cte,fileObject:Dte,s3FileObject:Lte}});var uR=g((Zme,G0)=>{"use strict";var El=$(),aE=P();async function Mte(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===aE.OPERATIONS_ENUM.INSERT||t.operation===aE.OPERATIONS_ENUM.UPDATE||t.operation===aE.OPERATIONS_ENUM.UPSERT?(delete s.new_attributes,delete s.txn_time):t.operation===aE.OPERATIONS_ENUM.DELETE&&delete s.txn_time,s}catch(i){throw i.message&&typeof i.message=="string"&&i.message.includes("already exists")?(El.info(i.message),i):i.http_resp_msg?(El.error(`Error calling operation: ${e.name}`),El.error(i.http_resp_msg),i):(El.error(`Error calling operation: ${e.name}`),El.error(i),i)}}a(Mte,"callOperationFunctionAsAwait");G0.exports={callOperationFunctionAsAwait:Mte}});var F0=g((tpe,q0)=>{"use strict";var lR=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}},_R=class{static{a(this,"BulkLoadDataObject")}constructor(t,r,n,s){this.action=t,this.schema=r,this.table=n,this.data=s}};q0.exports={BulkLoadFileObject:lR,BulkLoadDataObject:_R}});var V0=g((npe,k0)=>{"use strict";var dR=class{static{a(this,"ClusteringOriginObject")}constructor(t,r,n){this.timestamp=t,this.user=r,this.node_name=n}};k0.exports=dR});var SR=g((upe,oB)=>{"use strict";var cE=qr(),lE=cR(),Pte=require("needle"),Gn=P(),ipe=ke(),qa=J(),{handleHDBError:at,hdb_errors:X0}=ne(),{HTTP_STATUS_CODES:Qt,HDB_ERROR_MSGS:Dt,CHECK_LOGS_WRAPPER:No}=X0,Fa=$(),fR=require("papaparse");qa.promisifyPapaParse();var qn=require("fs-extra"),Ute=require("path"),{chain:$0}=require("stream-chain"),Y0=require("stream-json/streamers/StreamArray"),K0=require("stream-json/utils/Batch"),W0=require("stream-chain/utils/comp"),{finished:Q0}=require("stream"),vte=Z(),Z0=uR(),Bte=Bg(),{BulkLoadFileObject:hR,BulkLoadDataObject:Hte}=F0(),mR=Ng(),{verifyBulkLoadAttributePerms:eB}=qf(),ope=V0(),ape=ot(),cpe=Rs(),{databases:xte}=(Oe(),ie(Fe)),{coerceType:Gte}=(_E(),ie(TR)),z0="No records parsed from csv file.",yo=`${vte.get("HDB_ROOT")}/tmp`,{schema_regex:qte}=zn(),J0=1024*1024*2,j0=5e3,Fte={"text/csv":!0,"application/octet-stream":!0,"text/plain":!0,"application/vnd.ms-excel":!0};oB.exports={csvDataLoad:kte,csvURLLoad:Vte,csvFileLoad:$te,importFromS3:Yte};async function kte(e,t){let r=lE.dataObject(e);if(r)throw at(r,r.message,Qt.BAD_REQUEST,void 0,void 0,!0);let n={};try{let s=nB(e.schema,e.table),i=fR.parse(e.data,{header:!0,skipEmptyLines:!0,transform:ER.bind(null,s),dynamicTyping:!1}),o=new mR;e.hdb_user&&e.hdb_user.role&&e.hdb_user.role.permission&&e.hdb_user.role.permission.super_user!==!0&&eB(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 at(new Error,c,Qt.BAD_REQUEST,void 0,void 0,!0);let u=new Hte(e.action,e.schema,e.table,i.data);return n=await Z0.callOperationFunctionAsAwait(sB,u,null),n.message===z0?z0:iB(n.records,n.number_written)}catch(s){throw Io(s)}}a(kte,"csvDataLoad");async function Vte(e){let t=lE.urlObject(e);if(t)throw at(t,t.message,Qt.BAD_REQUEST,void 0,void 0,!0);let r=`${Date.now()}.csv`,n=`${yo}/${r}`;try{await Kte(e,r)}catch(s){throw Fa.error(Dt.DOWNLOAD_FILE_ERR(r)+" - "+s),at(s,No(Dt.DOWNLOAD_FILE_ERR(r)))}try{let s=new hR(this.job_operation_function.name,e.action,e.schema,e.table,n,Gn.VALID_S3_FILE_TYPES.CSV,e.hdb_user.role.permission),i=await pR(s);return await uE(n),i}catch(s){throw await uE(n),Io(s)}}a(Vte,"csvURLLoad");async function $te(e){let t=lE.fileObject(e);if(t)throw at(t,t.message,Qt.BAD_REQUEST,void 0,void 0,!0);let r=new hR(this.job_operation_function.name,e.action,e.schema,e.table,e.file_path,Gn.VALID_S3_FILE_TYPES.CSV,e.hdb_user.role.permission);try{return await pR(r)}catch(n){throw Io(n)}}a($te,"csvFileLoad");async function Yte(e){let t=lE.s3FileObject(e);if(t)throw at(t,t.message,Qt.BAD_REQUEST,void 0,void 0,!0);let r;try{let n=Ute.extname(e.s3.key),s=`${Date.now()}${n}`;r=`${yo}/${s}`;let i=new hR(this.job_operation_function.name,e.action,e.schema,e.table,r,n,e.hdb_user.role.permission);await Wte(s,e);let o=await pR(i);return await uE(r),o}catch(n){throw await uE(r),Io(n)}}a(Yte,"importFromS3");async function Kte(e,t){let r;try{let n=e.passthrough_headers?{headers:e.passthrough_headers}:void 0;r=await Pte("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 at(n,s,n.statusCode,Gn.LOG_LEVELS.ERROR,"Error downloading CSV file - "+n)}zte(r,e.csv_url),await Qte(t,r.raw)}a(Kte,"downloadCSVFile");async function Wte(e,t){try{let r=`${yo}/${e}`;await qn.mkdirp(yo),await qn.writeFile(`${yo}/${e}`,"",{flag:"a+"});let n=await qn.createWriteStream(r),s=await Bte.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(){Fa.info(`${t.s3.key} successfully downloaded to ${r}`),i()})})}catch(r){throw Fa.error(Dt.S3_DOWNLOAD_ERR+" - "+r),at(r,No(Dt.S3_DOWNLOAD_ERR))}}a(Wte,"downloadFileFromS3");async function Qte(e,t){try{await qn.mkdirp(yo),await qn.writeFile(`${yo}/${e}`,t)}catch(r){throw Fa.error(Dt.WRITE_TEMP_FILE_ERR),at(r,No(Dt.DEFAULT_BULK_LOAD_ERR))}}a(Qte,"writeFileToTempFolder");async function uE(e){if(e)try{await qn.access(e),await qn.unlink(e)}catch{Fa.warn(`could not delete temp csv file at ${e}, file does not exist`)}}a(uE,"deleteTempFile");function zte(e,t){if(e.statusCode!==X0.HTTP_STATUS_CODES.OK)throw at(new Error,`CSV Load failed from URL: ${t}, status code: ${e.statusCode}, message: ${e.statusMessage}`,Qt.BAD_REQUEST);if(!Fte[e.headers["content-type"]])throw at(new Error,`CSV Load failed from URL: ${t}, unsupported content type: ${e.headers["content-type"]}`,Qt.BAD_REQUEST);if(!e.raw)throw at(new Error,`CSV Load failed from URL: ${t}, no csv found at url`,Qt.BAD_REQUEST)}a(zte,"validateURLResponse");async function pR(e){try{let t;switch(e.file_type){case Gn.VALID_S3_FILE_TYPES.CSV:t=await Jte(e);break;case Gn.VALID_S3_FILE_TYPES.JSON:t=await jte(e);break;default:throw at(new Error,Dt.DEFAULT_BULK_LOAD_ERR,Qt.BAD_REQUEST,Gn.LOG_LEVELS.ERROR,Dt.INVALID_FILE_EXT_ERR(e))}return iB(t.records,t.number_written)}catch(t){throw Io(t)}}a(pR,"fileLoad");async function tB(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 cE.validation(o);e.role_perms&&e.role_perms.super_user!==!0&&eB(e.role_perms,e.op,e.action,e.schema,e.table,c,t),s&&s.resume()}catch(c){let u=at(c);r(u)}}a(tB,"validateChunk");async function rB(e,t,r,n,s){let i=n.data?n.data:n;if(i.length===0)return;qa.autoCastJSONDeep(i),s&&s.pause();let o=n.meta?n.meta.fields:null;if(o)i.forEach(c=>{!qa.isEmpty(c)&&!qa.isEmpty(c.__parsed_extra)&&delete c.__parsed_extra});else{let c=new Set;i.forEach(u=>{Object.keys(u).forEach(_=>c.add(_))}),o=[...c]}try{let c={schema:e.schema,table:e.table,action:e.action,data:i},u=await Z0.callOperationFunctionAsAwait(sB,c,null);t.records+=u.records,t.number_written+=u.number_written,s&&s.resume()}catch(c){let u=at(c,No(Dt.INSERT_CSV_ERR),Qt.INTERNAL_SERVER_ERROR,Gn.LOG_LEVELS.ERROR,Dt.INSERT_CSV_ERR+" - "+c);r(u)}}a(rB,"insertChunk");async function Jte(e){let t={records:0,number_written:0},r=nB(e.schema,e.table);try{let n=new mR,s=qn.createReadStream(e.file_path,{highWaterMark:J0});s.setEncoding("utf8"),await fR.parsePromise(s,tB.bind(null,e,n),ER.bind(null,r));let i=n.getPermsResponse();if(i)throw at(new Error,i,Qt.BAD_REQUEST);return s=qn.createReadStream(e.file_path,{highWaterMark:J0}),s.setEncoding("utf8"),await fR.parsePromise(s,rB.bind(null,e,t),ER.bind(null,r)),s.destroy(),t}catch(n){throw at(n,No(Dt.PAPA_PARSE_ERR),Qt.INTERNAL_SERVER_ERROR,Gn.LOG_LEVELS.ERROR,Dt.PAPA_PARSE_ERR+n)}}a(Jte,"callPapaParse");function nB(e,t){let r=xte[e][t].attributes,n=new Map;for(let s of r)s.type&&n.set(s.name,i=>Gte(i,s));return n}a(nB,"createTransformMap");function ER(e,t,r){let n=e.get(r);return n?n(t):qa.autoCast(t)}a(ER,"typeFunction");async function jte(e){let t={records:0,number_written:0},r=a(n=>{throw n},"throwErr");try{let n=new mR,s=$0([qn.createReadStream(e.file_path,{encoding:"utf-8"}),Y0.withParser(),c=>c.value,new K0({batchSize:j0}),W0(async c=>{await tB(e,n,r,c)})]);await new Promise((c,u)=>{Q0(s,_=>{_?u(_):c()}),s.resume()});let i=n.getPermsResponse();if(i)throw at(new Error,i,Qt.BAD_REQUEST);let o=$0([qn.createReadStream(e.file_path,{encoding:"utf-8"}),Y0.withParser(),c=>c.value,new K0({batchSize:j0}),W0(async c=>{await rB(e,t,r,c)})]);return await new Promise((c,u)=>{Q0(o,_=>{_?u(_):c()}),o.resume()}),t}catch(n){throw at(n,No(Dt.INSERT_JSON_ERR),Qt.INTERNAL_SERVER_ERROR,Gn.LOG_LEVELS.ERROR,Dt.INSERT_JSON_ERR+n)}}a(jte,"insertJson");async function sB(e){let t={};try{e.data&&e.data.length>0&&Xte(e.data[0])?t=await Zte(e.data,e.schema,e.table,e.action):(t.message="No records parsed from csv file.",Fa.info(t.message))}catch(r){throw Io(r)}return t}a(sB,"callBulkFileLoad");function Xte(e){let t=Object.keys(e);for(let r of t)if(!qte.test(r))throw new Error(`Invalid column name '${r}', cancelling load operation`);return!0}a(Xte,"validateColumnNames");async function Zte(e,t,r,n){n||(n="insert");let s={operation:n,schema:t,table:r,records:e},i;switch(n){case"insert":i=cE.insert;break;case"update":i=cE.update;break;case"upsert":i=cE.upsert;break;default:throw at(new Error,Dt.INVALID_ACTION_PARAM_ERR(n),Qt.BAD_REQUEST,Gn.LOG_LEVELS.ERROR,Dt.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 l=global.hdb_schema[t][r].hash_attribute,d=e.length;for(;d--;)o.skipped_hashes.indexOf(e[d][l])>=0&&e.splice(d,1)}let u=qa.isEmptyOrZeroLength(c)?0:c.length;return{records:e.length,number_written:u,new_attributes:o.new_attributes}}catch(o){throw Io(o)}}a(Zte,"bulkFileLoad");function iB(e,t){return`successfully loaded ${t} of ${e} records`}a(iB,"buildResponseMsg");function Io(e){return at(e,No(Dt.DEFAULT_BULK_LOAD_ERR),Qt.INTERNAL_SERVER_ERROR,Gn.LOG_LEVELS.ERROR,Dt.DEFAULT_BULK_LOAD_ERR+" - "+e)}a(Io,"buildTopLevelErrMsg")});var cB=g((_pe,aB)=>{"use strict";var gR=class{static{a(this,"SqlSearchObject")}constructor(t,r){this.operation="sql",this.sql=t,this.hdb_user=r}};aB.exports=gR});var _B=g((fpe,lB)=>{"use strict";var ere=P(),uB=require("moment"),tre=require("uuid").v4,RR=class{static{a(this,"JobObject")}constructor(){this.id=tre(),this.type=void 0,this.start_datetime=uB().valueOf(),this.created_datetime=uB().valueOf(),this.end_datetime=void 0,this.status=ere.JOB_STATUS_ENUM.CREATED,this.message=void 0,this.user=void 0,this.request=void 0}};lB.exports=RR});var AR=g((hpe,pB)=>{"use strict";var rre=require("uuid").v4,EB=qr(),hB=Gr(),nre=es(),sre=ia(),ire=cB(),ct=P(),ore=_B(),are=Gd(),Sn=$(),cre=xc(),ka=J(),{promisify:ure}=require("util"),wo=require("moment"),lre=kf(),dE=cR(),dB=Wm(),{deleteTransactionLogsBeforeValidator:_re}=Rg(),{handleHDBError:dre,hdb_errors:fre}=ne(),{HTTP_STATUS_CODES:Ere}=fre,fB=hB.searchByValue,hre=hB.searchByHash,mre=EB.insert,pre=ure(lre.evaluateSQL),Sre=EB.update;pB.exports={addJob:Rre,updateJob:Ore,handleGetJob:Tre,handleGetJobsByStartDate:gre,getJobById:mB};async function Tre(e){try{let t=await mB(e.id);return ka.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 Sn.error("There was an error getting job",t),new Error(r)}}a(Tre,"handleGetJob");async function gre(e){try{let t=await Are(e);if(Sn.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=wo(r.start_datetime)),r.end_datetime&&(r.end_datetime_converted=wo(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 Sn.error(r),new Error(r)}}a(gre,"handleGetJobsByStartDate");async function Rre(e){let t={message:"",error:"",success:!1,createdJob:void 0};if(!e||Object.keys(e).length===0||ka.isEmptyOrZeroLength(e.operation)){let l="job parameter is invalid";return Sn.info(l),t.error=l,t}if(!ct.JOB_TYPE_ENUM[e.operation])return Sn.info(`invalid job type specified: ${e.operation}.`),t;let r=e.operation,n;switch(r){case ct.OPERATIONS_ENUM.CSV_FILE_LOAD:n=dE.fileObject(e);break;case ct.OPERATIONS_ENUM.CSV_URL_LOAD:n=dE.urlObject(e);break;case ct.OPERATIONS_ENUM.CSV_DATA_LOAD:n=dE.dataObject(e);break;case ct.OPERATIONS_ENUM.IMPORT_FROM_S3:n=dE.s3FileObject(e);break;case ct.OPERATIONS_ENUM.DELETE_FILES_BEFORE:case ct.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE:n=dB(e,"date");break;case ct.OPERATIONS_ENUM.DELETE_AUDIT_LOGS_BEFORE:n=dB(e,"timestamp");break;case ct.OPERATIONS_ENUM.DELETE_TRANSACTION_LOGS_BEFORE:n=_re(e);break;default:break}if(n)throw dre(n,n.message,Ere.BAD_REQUEST,void 0,void 0,!0);let s=new ore;s.type=e.operation===ct.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE?ct.OPERATIONS_ENUM.DELETE_FILES_BEFORE:e.operation,s.type=e.operation,s.user=e.hdb_user.username;let i=new nre(ct.SYSTEM_SCHEMA_NAME,ct.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,"id",s.id,"id",["id"]),o;try{o=Array.from(await fB(i))}catch(l){let d=`There was an error inserting a new job: ${l}`;return Sn.error(d),t}let c=Array.isArray(o)?o:Object.keys(o);if(c&&c.length>0){s.id=rre();try{o=await fB(i)}catch(l){let d=`There was an error inserting a new job: ${l}`;return Sn.error(d),t}if(c=Array.isArray(o)?o:Object.keys(o),c&&c.length>0)return Sn.error("Error creating a job, could not find a unique job id."),t}s.request=e;let u=new cre(ct.SYSTEM_SCHEMA_NAME,ct.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,"id",[s]),_;try{_=await mre(u)}catch(l){return Sn.error(`There was an error inserting a job for job type: ${e.operation} -- ${l}`),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 l=`Created a job with type ${s.type} and id ${s.id}`;t.message=l,t.createdJob=s,t.success=!0,Sn.trace(l)}return t}a(Rre,"addJob");async function Are(e){let t=wo(e.from_date,wo.ISO_8601),r=wo(e.to_date,wo.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 ire(n,e.hdb_user);try{return await pre(s)}catch(i){throw Sn.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(Are,"getJobsInDateRange");async function mB(e){if(ka.isEmptyOrZeroLength(e))return ka.errorizeMessage("Invalid job ID specified.");let t=new sre(ct.SYSTEM_SCHEMA_NAME,ct.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,[e],["*"]);try{return await hre(t)}catch(r){let n=`There was an error searching for a job by id: ${e} ${r}`;return Sn.error(n),ka.errorizeMessage("there was an error searching for jobs. Please check the log for details.")}}a(mB,"getJobById");async function Ore(e){if(Object.keys(e).length===0)throw new Error("invalid job object passed to updateJob");if(ka.isEmptyOrZeroLength(e.id))throw new Error("invalid ID passed to updateJob");(e.status===ct.JOB_STATUS_ENUM.COMPLETE||e.status===ct.JOB_STATUS_ENUM.ERROR)&&(e.end_datetime=wo().valueOf());let t=new are(ct.SYSTEM_SCHEMA_NAME,ct.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,[e]),r;return r=await Sre(t),r}a(Ore,"updateJob")});var OB=g((ppe,AB)=>{"use strict";var SB=J(),Dr=P(),bre=require("moment"),fE=SR(),EE=$(),TB=AR(),gB=Vf(),RB=oi(),yre=Je(),Nre=Bf(),OR=class{static{a(this,"RunnerMessage")}constructor(t,r){this.job=t,this.json=r}};async function Ire(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(SB.isEmptyOrZeroLength(e.json.operation))throw new Error("Invalid operation");if(SB.isEmptyOrZeroLength(e.job.id))throw new Error("Empty job id specified");switch(e.json.operation){case Dr.JOB_TYPE_ENUM.csv_file_load:await qs(e,fE.csvFileLoad);break;case Dr.JOB_TYPE_ENUM.csv_url_load:await qs(e,fE.csvURLLoad);break;case Dr.JOB_TYPE_ENUM.csv_data_load:await qs(e,fE.csvDataLoad);break;case Dr.JOB_TYPE_ENUM.import_from_s3:await qs(e,fE.importFromS3);break;case Dr.JOB_TYPE_ENUM.empty_trash:break;case Dr.JOB_TYPE_ENUM.export_local:await qs(e,gB.export_local);break;case Dr.JOB_TYPE_ENUM.export_to_s3:await qs(e,gB.export_to_s3);break;case Dr.JOB_TYPE_ENUM.delete_files_before:case Dr.JOB_TYPE_ENUM.delete_records_before:await qs(e,RB.deleteFilesBefore);break;case Dr.JOB_TYPE_ENUM.delete_audit_logs_before:await qs(e,RB.deleteAuditLogsBefore);break;case Dr.JOB_TYPE_ENUM.delete_transaction_logs_before:await qs(e,Nre.deleteTransactionLogsBefore);break;default:return`Invalid operation ${e.json.operation} specified`}}a(Ire,"parseMessage");async function qs(e,t){try{e.job.status=Dr.JOB_STATUS_ENUM.IN_PROGRESS,e.job.start_datetime=bre().valueOf(),await TB.updateJob(e.job),await wre(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):EE.error(`There was an error running ${t.name} job with id ${e.job.id}`),EE.error(n),e.job.message=n,e.job.status=Dr.JOB_STATUS_ENUM.ERROR;try{await TB.updateJob(e.job)}catch(s){throw EE.error(`Unable to update job with id ${e.job.id}`),s}throw r}}a(qs,"runJob");async function wre(e){EE.trace("launching job thread:",e),yre.startWorker("server/jobs/jobProcess.js",{autoRestart:!1,name:"job",env:Object.assign({},process.env,{[Dr.PROCESS_NAME_ENV_PROP]:`JOB-${e}`})})}a(wre,"launchJobThread");AB.exports={parseMessage:Ire,RunnerMessage:OR}});var yB=g((Tpe,bB)=>{"use strict";var bR=class{static{a(this,"OperationFunctionObject")}constructor(t,r=void 0){this.operation_function=t,this.job_operation_function=r}};bB.exports=bR});var kB=g((Rpe,DR)=>{"use strict";var TE=Gr(),IR=kf(),hE=SR(),Fs=Tu(),mE=As(),ml=oi(),Cre=qS(),hl=ln(),pE=zS(),zt=gg(),SE=$(),Dre=XS(),Lre=Xd(),NB=LT(),Mre=ef(),Pre=PT(),Ure=UT(),vre=HT(),Bre=GT(),yR=kT(),IB=Vf(),Hre=qf(),wR=AR(),q=P(),{hdb_errors:Sl,handleHDBError:pl}=ne(),{HTTP_STATUS_CODES:wB}=Sl,NR=WT(),CB=Af(),xB=require("util"),Va=qr(),xre=Os(),Gre=Ta(),DB=OB(),LB=yu(),MB=(Nf(),ie(zu)),PB=fr(),UB=Bf(),vB=Lf(),{setServerUtilities:qre}=(_E(),ie(TR)),{CONTEXT:Fre}=(Nn(),ie(qp)),{_assignPackageExport:kre}=require("../index"),{transformReq:Vre}=J(),{server:$re}=(ur(),ie(Hi)),sr=SE.loggerWithTag("operation"),Yre=uR(),BB=TE.searchByHash,Kre=TE.searchByValue,Wre=xB.promisify(TE.search),Qre=xB.promisify(IR.evaluateSQL),zre={[q.OPERATIONS_ENUM.CREATE_ATTRIBUTE]:!0,[q.OPERATIONS_ENUM.CREATE_TABLE]:!0,[q.OPERATIONS_ENUM.CREATE_SCHEMA]:!0,[q.OPERATIONS_ENUM.DROP_ATTRIBUTE]:!0,[q.OPERATIONS_ENUM.DROP_TABLE]:!0,[q.OPERATIONS_ENUM.DROP_SCHEMA]:!0},Y=yB();async function GB(e,t){try{if(e.body.operation!=="read_log"&&(SE.log_level===q.LOG_LEVELS.INFO||SE.log_level===q.LOG_LEVELS.DEBUG||SE.log_level===q.LOG_LEVELS.TRACE)){let{hdb_user:n,hdb_auth_header:s,password:i,...o}=e.body;sr.info(o)}}catch(n){sr.error(n)}let r=await Yre.callOperationFunctionAsAwait(t,e.body,null);if(typeof r!="object"&&(r={message:r}),r instanceof Error)throw r;return zre[e.body.operation]&&xre.setSchemaDataToGlobal(n=>{n&&sr.error(n)}),r}a(GB,"processLocalTransaction");var HB=jre();DR.exports={chooseOperation:qB,getOperationFunction:FB,operation:CR,processLocalTransaction:GB};qre(DR.exports);$re.operation=CR;function qB(e){let t;try{t=FB(e)}catch(s){throw sr.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=IR.convertSQLToAST(s);if(e.parsed_sql_object=i,!e.bypass_auth){let o=IR.checkASTPermissions(e,i);if(o)throw sr.error(`${wB.FORBIDDEN} from operation ${e.operation}`),sr.warn(`User '${e.hdb_user.username}' is not permitted to ${e.operation}`),pl(new Error,o,Sl.HTTP_STATUS_CODES.FORBIDDEN,void 0,void 0,!0)}}else if(!e.bypass_auth&&e.operation!==q.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS&&e.operation!==q.OPERATIONS_ENUM.LOGIN&&e.operation!==q.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=Hre.verifyPerms(i,s);if(o)throw sr.error(`${wB.FORBIDDEN} from operation ${e.operation}`),sr.warn(`User '${i.hdb_user.username}' is not permitted to ${i.operation}`),pl(new Error,o,Sl.HTTP_STATUS_CODES.FORBIDDEN,void 0,!1,!0)}}catch(s){throw pl(s,"There was an error when trying to choose an operation path")}return r}a(qB,"chooseOperation");function FB(e){if(sr.trace(`getOperationFunction with operation: ${e.operation}`),HB.has(e.operation))return HB.get(e.operation);throw pl(new Error,Sl.HDB_ERROR_MSGS.OP_NOT_FOUND(e.operation),Sl.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0)}a(FB,"getOperationFunction");kre("operation",CR);function CR(e,t){e.hdb_user=this[Fre]?.user,e.bypass_auth=!t;let r=qB(e);return GB({body:e},r)}a(CR,"operation");async function Jre(e){sr.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[q.CLUSTERING_FLAG]=!0;let o;switch(i.operation){case q.OPERATIONS_ENUM.INSERT:o=await Va.insert(i);break;case q.OPERATIONS_ENUM.UPDATE:o=await Va.update(i);break;case q.OPERATIONS_ENUM.UPSERT:o=await Va.upsert(i);break;case q.OPERATIONS_ENUM.DELETE:o=await ml.deleteRecord(i);break;default:sr.warn("invalid operation in catchup");break}await transact_to_clustering_utils.postOperationHandler(i,o,e)}catch(o){sr.info("Invalid operation in transaction"),sr.error(o)}}a(Jre,"catchup");async function _s(e){Vre(e);let t,r;try{r=await wR.addJob(e),t=r.createdJob,sr.info("addJob result",r);let n=new DB.RunnerMessage(t,e);return await DB.parseMessage(n),{message:`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 sr.error(s),pl(n,s)}}a(_s,"executeJob");function jre(){let e=new Map;return e.set(q.OPERATIONS_ENUM.INSERT,new Y(Va.insert)),e.set(q.OPERATIONS_ENUM.UPDATE,new Y(Va.update)),e.set(q.OPERATIONS_ENUM.UPSERT,new Y(Va.upsert)),e.set(q.OPERATIONS_ENUM.SEARCH_BY_CONDITIONS,new Y(TE.searchByConditions)),e.set(q.OPERATIONS_ENUM.SEARCH_BY_HASH,new Y(BB)),e.set(q.OPERATIONS_ENUM.SEARCH_BY_ID,new Y(BB)),e.set(q.OPERATIONS_ENUM.SEARCH_BY_VALUE,new Y(Kre)),e.set(q.OPERATIONS_ENUM.SEARCH,new Y(Wre)),e.set(q.OPERATIONS_ENUM.SQL,new Y(Qre)),e.set(q.OPERATIONS_ENUM.CSV_DATA_LOAD,new Y(_s,hE.csvDataLoad)),e.set(q.OPERATIONS_ENUM.CSV_FILE_LOAD,new Y(_s,hE.csvFileLoad)),e.set(q.OPERATIONS_ENUM.CSV_URL_LOAD,new Y(_s,hE.csvURLLoad)),e.set(q.OPERATIONS_ENUM.IMPORT_FROM_S3,new Y(_s,hE.importFromS3)),e.set(q.OPERATIONS_ENUM.CREATE_SCHEMA,new Y(Fs.createSchema)),e.set(q.OPERATIONS_ENUM.CREATE_DATABASE,new Y(Fs.createSchema)),e.set(q.OPERATIONS_ENUM.CREATE_TABLE,new Y(Fs.createTable)),e.set(q.OPERATIONS_ENUM.CREATE_ATTRIBUTE,new Y(Fs.createAttribute)),e.set(q.OPERATIONS_ENUM.DROP_SCHEMA,new Y(Fs.dropSchema)),e.set(q.OPERATIONS_ENUM.DROP_DATABASE,new Y(Fs.dropSchema)),e.set(q.OPERATIONS_ENUM.DROP_TABLE,new Y(Fs.dropTable)),e.set(q.OPERATIONS_ENUM.DROP_ATTRIBUTE,new Y(Fs.dropAttribute)),e.set(q.OPERATIONS_ENUM.DESCRIBE_SCHEMA,new Y(mE.describeSchema)),e.set(q.OPERATIONS_ENUM.DESCRIBE_DATABASE,new Y(mE.describeSchema)),e.set(q.OPERATIONS_ENUM.DESCRIBE_TABLE,new Y(mE.describeTable)),e.set(q.OPERATIONS_ENUM.DESCRIBE_ALL,new Y(mE.describeAll)),e.set(q.OPERATIONS_ENUM.DELETE,new Y(ml.deleteRecord)),e.set(q.OPERATIONS_ENUM.ADD_USER,new Y(hl.addUser)),e.set(q.OPERATIONS_ENUM.ALTER_USER,new Y(hl.alterUser)),e.set(q.OPERATIONS_ENUM.DROP_USER,new Y(hl.dropUser)),e.set(q.OPERATIONS_ENUM.LIST_USERS,new Y(hl.listUsersExternal)),e.set(q.OPERATIONS_ENUM.LIST_ROLES,new Y(pE.listRoles)),e.set(q.OPERATIONS_ENUM.ADD_ROLE,new Y(pE.addRole)),e.set(q.OPERATIONS_ENUM.ALTER_ROLE,new Y(pE.alterRole)),e.set(q.OPERATIONS_ENUM.DROP_ROLE,new Y(pE.dropRole)),e.set(q.OPERATIONS_ENUM.USER_INFO,new Y(hl.userInfo)),e.set(q.OPERATIONS_ENUM.READ_LOG,new Y(Dre)),e.set(q.OPERATIONS_ENUM.ADD_NODE,new Y(Lre)),e.set(q.OPERATIONS_ENUM.UPDATE_NODE,new Y(NB)),e.set(q.OPERATIONS_ENUM.SET_NODE_REPLICATION,new Y(NB)),e.set(q.OPERATIONS_ENUM.REMOVE_NODE,new Y(Mre)),e.set(q.OPERATIONS_ENUM.CONFIGURE_CLUSTER,new Y(Pre)),e.set(q.OPERATIONS_ENUM.PURGE_STREAM,new Y(Ure)),e.set(q.OPERATIONS_ENUM.SET_CONFIGURATION,new Y(PB.setConfiguration)),e.set(q.OPERATIONS_ENUM.CLUSTER_STATUS,new Y(vre.clusterStatus)),e.set(q.OPERATIONS_ENUM.CLUSTER_NETWORK,new Y(Bre)),e.set(q.OPERATIONS_ENUM.CLUSTER_SET_ROUTES,new Y(yR.setRoutes)),e.set(q.OPERATIONS_ENUM.CLUSTER_GET_ROUTES,new Y(yR.getRoutes)),e.set(q.OPERATIONS_ENUM.CLUSTER_DELETE_ROUTES,new Y(yR.deleteRoutes)),e.set(q.OPERATIONS_ENUM.EXPORT_TO_S3,new Y(_s,IB.export_to_s3)),e.set(q.OPERATIONS_ENUM.DELETE_FILES_BEFORE,new Y(_s,ml.deleteFilesBefore)),e.set(q.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE,new Y(_s,ml.deleteFilesBefore)),e.set(q.OPERATIONS_ENUM.EXPORT_LOCAL,new Y(_s,IB.export_local)),e.set(q.OPERATIONS_ENUM.SEARCH_JOBS_BY_START_DATE,new Y(wR.handleGetJobsByStartDate)),e.set(q.OPERATIONS_ENUM.GET_JOB,new Y(wR.handleGetJob)),e.set(q.OPERATIONS_ENUM.GET_FINGERPRINT,new Y(NR.getFingerprint)),e.set(q.OPERATIONS_ENUM.SET_LICENSE,new Y(NR.setLicense)),e.set(q.OPERATIONS_ENUM.GET_REGISTRATION_INFO,new Y(NR.getRegistrationInfo)),e.set(q.OPERATIONS_ENUM.RESTART,new Y(CB.restart)),e.set(q.OPERATIONS_ENUM.RESTART_SERVICE,new Y(CB.restartService)),e.set(q.OPERATIONS_ENUM.CATCHUP,new Y(Jre)),e.set(q.OPERATIONS_ENUM.SYSTEM_INFORMATION,new Y(Gre.systemInformation)),e.set(q.OPERATIONS_ENUM.DELETE_AUDIT_LOGS_BEFORE,new Y(_s,ml.deleteAuditLogsBefore)),e.set(q.OPERATIONS_ENUM.READ_AUDIT_LOG,new Y(Cre)),e.set(q.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS,new Y(LB.createTokens)),e.set(q.OPERATIONS_ENUM.REFRESH_OPERATION_TOKEN,new Y(LB.refreshOperationToken)),e.set(q.OPERATIONS_ENUM.LOGIN,new Y(MB.login)),e.set(q.OPERATIONS_ENUM.LOGOUT,new Y(MB.logout)),e.set(q.OPERATIONS_ENUM.GET_CONFIGURATION,new Y(PB.getConfiguration)),e.set(q.OPERATIONS_ENUM.CUSTOM_FUNCTIONS_STATUS,new Y(zt.customFunctionsStatus)),e.set(q.OPERATIONS_ENUM.GET_CUSTOM_FUNCTIONS,new Y(zt.getCustomFunctions)),e.set(q.OPERATIONS_ENUM.GET_COMPONENT_FILE,new Y(zt.getComponentFile)),e.set(q.OPERATIONS_ENUM.GET_COMPONENTS,new Y(zt.getComponents)),e.set(q.OPERATIONS_ENUM.SET_COMPONENT_FILE,new Y(zt.setComponentFile)),e.set(q.OPERATIONS_ENUM.DROP_COMPONENT,new Y(zt.dropComponent)),e.set(q.OPERATIONS_ENUM.GET_CUSTOM_FUNCTION,new Y(zt.getCustomFunction)),e.set(q.OPERATIONS_ENUM.SET_CUSTOM_FUNCTION,new Y(zt.setCustomFunction)),e.set(q.OPERATIONS_ENUM.DROP_CUSTOM_FUNCTION,new Y(zt.dropCustomFunction)),e.set(q.OPERATIONS_ENUM.ADD_CUSTOM_FUNCTION_PROJECT,new Y(zt.addComponent)),e.set(q.OPERATIONS_ENUM.ADD_COMPONENT,new Y(zt.addComponent)),e.set(q.OPERATIONS_ENUM.DROP_CUSTOM_FUNCTION_PROJECT,new Y(zt.dropCustomFunctionProject)),e.set(q.OPERATIONS_ENUM.PACKAGE_CUSTOM_FUNCTION_PROJECT,new Y(zt.packageComponent)),e.set(q.OPERATIONS_ENUM.PACKAGE_COMPONENT,new Y(zt.packageComponent)),e.set(q.OPERATIONS_ENUM.DEPLOY_CUSTOM_FUNCTION_PROJECT,new Y(zt.deployComponent)),e.set(q.OPERATIONS_ENUM.DEPLOY_COMPONENT,new Y(zt.deployComponent)),e.set(q.OPERATIONS_ENUM.READ_TRANSACTION_LOG,new Y(UB.readTransactionLog)),e.set(q.OPERATIONS_ENUM.DELETE_TRANSACTION_LOGS_BEFORE,new Y(_s,UB.deleteTransactionLogsBefore)),e.set(q.OPERATIONS_ENUM.INSTALL_NODE_MODULES,new Y(vB.installModules)),e.set(q.OPERATIONS_ENUM.AUDIT_NODE_MODULES,new Y(vB.auditModules)),e.set(q.OPERATIONS_ENUM.GET_BACKUP,new Y(Fs.getBackup)),e}a(jre,"initializeOperationFunctionMap")});var RE=g((Ope,YB)=>{"use strict";var LR=P(),Xre=J(),Tl=$(),{handleHDBError:MR,hdb_errors:gE}=ne(),{isMainThread:Zre}=require("worker_threads"),{Readable:ene}=require("stream"),VB=require("os"),tne=require("util"),rne=cT(),nne=tne.promisify(rne.authorize),$B=kB(),{createGzip:sne,constants:ine}=require("zlib");function one(e){let t=`Found an uncaught exception with message: ${e.message}. ${VB.EOL}Stack: ${e.stack} ${VB.EOL}Terminating ${Zre?"HDB":"thread"}.`;console.error(t),Tl.fatal(t),process.exit(1)}a(one,"handleServerUncaughtException");function ane(e,t,r){if(Tl[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:gE.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(ane,"serverErrorHandler");function cne(e,t,r){if(!e.body||Object.keys(e.body).length===0||typeof e.body!="object"){let n=MR(new Error,"Invalid JSON.",gE.HTTP_STATUS_CODES.BAD_REQUEST);r(n,null)}if(Xre.isEmpty(e.body.operation)){let n=MR(new Error,"Request body must include an 'operation' property.",gE.HTTP_STATUS_CODES.BAD_REQUEST);r(n,null)}r()}a(cne,"reqBodyValidationHandler");function une(e,t,r){let n;e.body.operation!==LR.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS&&e.body.operation!==LR.OPERATIONS_ENUM.LOGIN&&e.body.operation!==LR.OPERATIONS_ENUM.LOGOUT?nne(e,t).then(s=>{n=s,e.body.hdb_user=n,e.body.hdb_auth_header=e.headers.authorization,r()}).catch(s=>{Tl.warn(s),Tl.warn(`{"ip":"${e.socket.remoteAddress}", "error":"${s.stack}"`);let i=typeof s=="string"?{error:s}:{error:s.message};r(MR(s,i,gE.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(une,"authHandler");async function lne(e,t,r=!1){let n;try{r&&(e.body.operation!=="configure_cluster"||e.body.operation!=="set_configuration")&&(e.body.bypass_auth=r),n=$B.chooseOperation(e.body);let s=await $B.processLocalTransaction(e,n);if(s instanceof ene&&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(sne({level:ine.Z_BEST_SPEED})))}return s}catch(s){throw Tl.error(s),s}}a(lne,"handlePostRequest");YB.exports={authHandler:une,handlePostRequest:lne,handleServerUncaughtException:one,serverErrorHandler:ane,reqBodyValidationHandler:cne}});var zB=g((ype,QB)=>{"use strict";var _ne=require("fastify-plugin"),{handlePostRequest:KB,authHandler:dne,reqBodyValidationHandler:fne}=RE();async function Ene(e){e.decorate("hdbCore",{preValidation:[fne,dne],request:t=>WB(KB(t,response)),requestWithoutAuthentication:(t,r)=>WB(KB(t,r,!0))})}a(Ene,"hdbCore");async function WB(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(WB,"convertAsyncIterators");QB.exports=_ne(Ene)});var XB=g((wpe,jB)=>{"use strict";var Ipe=require("fs"),PR=Z();PR.initSync();var{CONFIG_PARAMS:JB}=P(),hne=1024*1024*1024;function mne(e){let t=PR.get(JB.HTTP_TIMEOUT),r=PR.get(JB.HTTP_KEEPALIVETIMEOUT);return{bodyLimit:hne,connectionTimeout:t,keepAliveTimeout:r,return503OnClosing:!1,forceCloseConnections:!0,ignoreTrailingSlash:!0,https:e}}a(mne,"getServerOptions");jB.exports=mne});var tH=g((Dpe,eH)=>{"use strict";var UR=Z();UR.initSync();var{CONFIG_PARAMS:ZB}=P();function pne(){let e=UR.get(ZB.HTTP_CORSACCESSLIST),t=UR.get(ZB.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(pne,"getCORSOptions");eH.exports=pne});var sH=g((Mpe,nH)=>{"use strict";var rH=Z();rH.initSync();var Sne=P();function Tne(){return rH.get(Sne.CONFIG_PARAMS.HTTP_HEADERSTIMEOUT)??6e4}a(Tne,"getHeaderTimeoutConfig");nH.exports=Tne});var BR={};qe(BR,{customFunctionsServer:()=>Ane,ready:()=>TH,start:()=>Rne});function Rne(e){let t=e.securePort>0;return{async handleFile(r,n,s,i){ks||(ks=SH(t),st.http((await ks).server));let o=await ks,c=(0,vR.dirname)(s),u=(0,vR.dirname)(n);if(u.startsWith("/")&&(u=u.slice(1)),!iH.has(c)){iH.add(c);try{o.register(bne(c,u))}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:TH}}async function Ane(){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 One();let e=_H.get(dH.CONFIG_PARAMS.HTTP_SECUREPORT)>0,t;try{t=ks=await SH(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 One(){try{$e.info("Custom Functions starting configuration."),await fH.setUsersToGlobal(),$e.info("Custom Functions completed configuration.")}catch(e){$e.error(e)}}function bne(e,t){return async function(r){try{$e.info("Custom Functions starting buildRoutes"),$e.trace("Loading fastify routes folder "+e),(0,oH.existsSync)(e)&&r.register(lH.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 SH(e){$e.info("Custom Functions starting buildServer.");let t=(0,EH.default)(e),r=(0,aH.default)(t);r.server.headersTimeout=(0,mH.default)(),r.setErrorHandler(pH.serverErrorHandler);let n=(0,hH.default)();return n&&r.register(cH.default,n),r.register(function(s,i,o){s.setNotFoundHandler(function(c,u){r.server.emit("unhandled",c.raw,u.raw)}),o()}),r.register(uH.default),await r.register(gne),await r.after(),Vg(r),$e.info("Custom Functions completed buildServer."),r}function TH(){if(ks)return ks.then?ks.then(e=>e.ready()):ks.ready()}var vR,oH,aH,cH,uH,lH,_H,dH,$e,gne,fH,EH,hH,mH,pH,ks,iH,gH=Ae(()=>{vR=require("path"),oH=require("fs"),aH=B(require("fastify")),cH=B(require("@fastify/cors")),uH=B(rR()),lH=B(require("@fastify/autoload")),_H=B(Z()),dH=B(P()),$e=B($()),gne=B(zB()),fH=B(ln()),EH=B(XB()),hH=B(tH()),mH=B(sH()),pH=B(RE());wa();ur();iH=new Set;a(Rne,"start");a(Ane,"customFunctionsServer");a(One,"setUp");a(bne,"buildRouteFolder");a(SH,"buildServer");a(TH,"ready")});var HR={};qe(HR,{start:()=>yne});function yne(e){return{handleDirectory(t,r){if(t==="/"){let n=(0,yH.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){AH||(AH=!0,e.server.http(async(s,i)=>{if(!s.isWebSocket){let o=RH.get(s.pathname);if(o)return{handlesHeaders:!0,body:(0,OH.default)(s,(0,bH.realpathSync)(o))}}return i(s)},{runFirst:!0})),RH.set(r,n)}}}var OH,bH,yH,RH,AH,NH=Ae(()=>{OH=B(require("send")),bH=require("fs"),yH=B(require("serve-static")),RH=new Map;a(yne,"start")});function wne(e,t=1,r){if(xR++,(0,Co.startWorker)("server/threads/threadServer.js",{name:bE.THREAD_TYPES.HTTP,workerIndex:e,threadCount:t,async onStarted(n){let s=new Promise((o,c)=>{function u(_){_.type===bE.CLUSTER_MESSAGE_TYPE_ENUM.CHILD_STARTED&&(n.removeListener("message",u),o(n))}a(u,"onMessage"),n.on("message",u),n.on("error",c)});Ine.push(s),await s,$a.push(n),n.expectedIdle=1,n.lastIdle=0,n.requests=1,n.on("message",o=>{if(o.requestId){let c=OE.get(o.requestId);c&&c(o)}}),n.on("exit",i),n.on("shutdown",i);function i(){let o=$a.indexOf(n);o>-1&&$a.splice(o,1)}if(a(i,"removeWorker"),Ya){let o=Ya;Ya=[];for(let c of o)DH[c.localPort](null,c)}}}),r){let n=setInterval(()=>{GR?GR=!1:(clearInterval(n),console.log("shut down dynamic thread due to inactivity"),(0,Co.shutdownWorkers)(),xR=0,setTimeout(()=>{global.gc?.()},5e3))},1e4)}}function LH(e=0,t){if(typeof e=="string")try{(0,yE.existsSync)(e)&&(0,yE.unlinkSync)(e)}catch{}let r;t?t==="ip"?r=Cne:r=Dne(t):r=FR;let n=(0,Ka.createServer)({allowHalfOpen:!0,pauseOnConnect:!r.readsData}).listen(e);if(n._handle){n._handle.onconnection=DH[e]=function(i,o){r.readsData||(o.reading=!1,o.readStop()),GR=!0,r(o,(c,u)=>{if(!c){if(IH){let l=o._socket||new Ka.Socket({handle:o,writable:!0,readable:!0});IH.deliverSocket(l,e,u),l.resume()}else xR>0?(Ya.length===0&&setTimeout(()=>{Ya.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,Ya.push(o)):(console.log("start up a dynamic thread to handle request"),wne(0));pr(!1,"socket-routed");return}c.requests++;let _=o.fd;if(_>=0)c.postMessage({port:e,fd:_,data:u});else{let l=o._socket||new Ka.Socket({handle:o,writable:!0,readable:!0});Une(l,c,e)}pr(!0,"socket-routed")})};let s=au();qR.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 FR(e,t){let r,n=0;for(let s of $a){if(s.threadId===-1)continue;let i=s.expectedIdle/s.requests;if(i>n)r=s;else if(n>=AE)return AE=i,t(r);n=i}AE=0,t(r)}function Cne(e,t){let r={};e.getpeername(r);let n=r.address,s=Wa.get(n),i=Date.now();if(s&&s.worker.threadId!==-1)return s.lastUsed=i,t(s.worker);FR(e,o=>{Wa.set(n,{worker:o,lastUsed:i}),t(o)})}function Dne(e){let t=new RegExp(`${e}:\\s*(.+)`,"i");return r.readsData=!0,r;function r(n,s){let i=new Ka.Socket({handle:n,readable:!0,writable:!0});n._socket=i,i.on("data",o=>{n.readStop();let u=o.toString("latin1").match(t)?.[1],_=Wa.get(u),l=Date.now();if(_&&_.worker.threadId!==-1)return _.lastUsed=l,s(_.worker);FR(n,d=>{Wa.set(u,{worker:d,lastUsed:l}),s(d,o)})})}a(r,"findByHeaderAffinity")}function Mne(){AE=0;for(let e of $a)e.expectedIdle=e.recentELU.idle+Lne,e.requests=1;$a.sort((e,t)=>e.expectedIdle>t.expectedIdle?-1:1)}function Une(e,t,r){let n=Pne++;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(),OE.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")),OE.delete(n)),s.event=="destroy"&&(e.destroy(),OE.delete(n))})}var Co,Ka,bE,qR,yE,CH,Nne,$a,Ya,DH,IH,xR,Ine,GR,AE,wH,Wa,Lne,OE,Pne,MH=Ae(()=>{Co=B(Je()),Ka=require("net"),bE=B(P()),qR=B($()),yE=require("fs");ws();CH=require("worker_threads"),Nne=B(Ji()),$a=[],Ya=[],DH=[],xR=0,Ine=[];CH.isMainThread&&process.on("uncaughtException",e=>{e.code!=="ECONNRESET"&&e.message!=="write EIO"&&console.error("uncaughtException",e)});a(wne,"startHTTPWorker");a(LH,"startSocketServer");AE=0;a(FR,"findMostIdleWorker");wH=36e5,Wa=new Map;a(Cne,"findByRemoteAddressAffinity");a(Dne,"makeFindByHeaderAffinity");setInterval(()=>{let e=Date.now();for(let[t,r]of Wa)r.lastUsed+wH<e&&Wa.delete(t)},wH).unref();Lne=1e3;a(Mne,"updateWorkerIdleness");(0,Co.setMonitorListener)(Mne);OE=new Map,Pne=1;a(Une,"proxySocket")});var YR={};qe(YR,{Request:()=>kR,createReuseportFd:()=>NE});var PH,kR,VR,$R,NE,IE=Ae(()=>{PH=require("os"),kR=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 $R(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 VR(this._nodeRequest))}get host(){return this._nodeRequest.authority||this._nodeRequest.headers.host}get isAborted(){return!1}},VR=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)}},$R=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,PH.platform)()!="win32"&&(NE=require("node-unix-socket").createReuseportFd)});var HH=g((Wpe,BH)=>{"use strict";var vne=require("cluster"),Do=Z();Do.initSync();var vH=P(),kpe=require("util"),Vs=$(),Vpe=require("fs"),Bne=require("fastify"),$pe=au(),Hne=require("@fastify/cors"),xne=require("@fastify/compress"),Gne=require("@fastify/static"),qne=rR(),Fne=require("path"),{PACKAGE_ROOT:kne}=P(),Vne=Os(),$ne=J(),Yne=ln(),Kne=Ji(),{server:Wne}=(ur(),ie(Hi)),{node_request_key:Ype}=(IE(),ie(YR)),{authHandler:Qne,handlePostRequest:zne,serverErrorHandler:Jne,reqBodyValidationHandler:jne}=RE(),Kpe=require("net"),{registerContentHandlers:Xne}=(wa(),ie(T0)),Zne=6e4,ese=1024*1024*1024,tse="TRUE",{CONFIG_PARAMS:gl}=vH,Qa;BH.exports={hdbServer:UH,start:UH};async function UH(e){try{Vs.info("In Fastify server"+process.cwd()),Vs.info(`Running with NODE_ENV set as: ${process.env.NODE_ENV}`),Vs.debug(`HarperDB server process ${process.pid} starting up.`),global.clustering_on=!1,global.isMaster=vne.isMaster,await rse();let t=e.securePort>0;Qa=nse(t),await Qa.ready(),e||(e={}),e.isOperationsServer=!0;try{Wne.http(Qa.server,e),Qa.server.closeIdleConnections||await Qa.listen({port:0,host:"::"})}catch(r){throw Qa.close(),Vs.error(r),Vs.error("Error configuring operations server"),r}}catch(t){console.error(`Failed to build server on ${process.pid}`,t),Vs.fatal(t),process.exit(1)}}a(UH,"operationsServer");async function rse(){Vs.trace("Configuring HarperDB process."),Vne.setSchemaDataToGlobal(),await Yne.setUsersToGlobal(),await Kne.getLicense()}a(rse,"setUp");function nse(e){Vs.debug(`HarperDB process starting to build ${e?"HTTPS":"HTTP"} server.`);let t=sse(e),r=Bne(t);r.server.headersTimeout=ose(),r.setErrorHandler(Jne);let n=ise();n&&r.register(Hne,n),r.register(function(i,o,c){i.setNotFoundHandler(function(u,_){r.server.emit("unhandled",u.raw,_.raw)}),c()}),r.register(qne),r.register(xne),r.register(Gne,{root:Fne.join(kne,"studio/build-local")}),Xne(r);let s=Do.get(vH.HDB_SETTINGS_NAMES.LOCAL_STUDIO_ON);return r.get("/",function(i,o){return!$ne.isEmpty(s)&&s.toString().toLowerCase()==="true"?o.sendFile("index.html"):o.sendFile("running.html")}),r.post("/",{preValidation:[jne,Qne],config:{isOperation:!0}},async function(i,o){return i.body?.operation?.startsWith("restart")&&o.header("Connection","close"),zne(i,o)}),r.get("/health",()=>"HarperDB is running."),Vs.debug(`HarperDB process starting up ${e?"HTTPS":"HTTP"} server listener.`),r}a(nse,"buildServer");function sse(e){let t=Do.get(gl.OPERATIONSAPI_NETWORK_TIMEOUT),r=Do.get(gl.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT);return{bodyLimit:ese,connectionTimeout:t,keepAliveTimeout:r,forceCloseConnections:!0,return503OnClosing:!1,https:e}}a(sse,"getServerOptions");function ise(){let e=Do.get(gl.OPERATIONSAPI_NETWORK_CORS),t=Do.get(gl.OPERATIONSAPI_NETWORK_CORSACCESSLIST),r;return e&&(e===!0||e.toUpperCase()===tse)&&(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(ise,"getCORSOpts");function ose(){return Do.get(gl.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT)??Zne}a(ose,"getHeaderTimeoutConfig")});var jR={};qe(jR,{disableNATS:()=>cse,publishToStream:()=>DE,setNATSReplicator:()=>KR,setPublishToStream:()=>use,setSubscription:()=>JR,start:()=>ase});function ase(){Rl.default.get(Al.default.CONFIG_PARAMS.CLUSTERING_ENABLED)&&_se()}function cse(e=!0){kH=e}function use(e,t){DE=e,JR=t}function _se(){if(kH||process.env._DISABLE_NATS)return;let e=hr(),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];KR(s,r,i)}}XR((r,n)=>{KR(r.tableName,r.databaseName,r),n&&$H(r)}),!xH&&(xH=!0)}function KR(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 Vt{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){$H(i)}static subscribe(){let i=new yn;return JR(t,e,i),i}static subscribeOnThisThread(i){return i<(Rl.default.get(Al.default.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXINGESTTHREADS)??lse)}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 wE(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=VH;return i}a(n,"getNATSTransaction")}function $H(e){let t=Rl.default.get(Al.default.CONFIG_PARAMS.CLUSTERING_NODENAME);DE(`${QR.SUBJECT_PREFIXES.TXN}.${e.databaseName}.${e.tableName}`,(0,zR.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 GH,QR,zR,qH,FH,Rl,Al,CE,kH,DE,JR,lse,VH,xH,wE,WR,YH=Ae(()=>{Oe();Nn();GH=B(ot()),QR=B(ke()),zR=B(Rs());Ac();qH=B(wS()),FH=B(vr()),Rl=B(Z()),Al=B(P()),CE=B($());a(ase,"start");a(cse,"disableNATS");DE=GH.publishToStream,JR=qH.setSubscription;a(use,"setPublishToStream");lse=2;a(_se,"assignReplicationSource");a(KR,"setNATSReplicator");a($H,"publishSchema");wE=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=Rl.default.get(Al.default.CONFIG_PARAMS.CLUSTERING_NODENAME),n=[];for(let[s,i]of this.writes_by_db){let o=[],c=[],u,_;for(let l of i){let d=l.table,E=l.operation=="put"?"upsert":l.operation;u||(CE.trace(`Sending transaction event ${E}`),_=u={operation:E,schema:s,table:d,__origin:{user:this.user?.username,timestamp:t,node_name:r}},u.hash_values=c,E!=="delete"&&E!=="invalidate"&&(u.records=o)),u.table===d&&u.operation===E?(o.push(l.record),c.push(l.id)):_=_.next={operation:E,table:d,id:l.id,record:l.record},l.expiresAt&&(_.expiresAt=l.expiresAt)}u&&n.push(DE(`${QR.SUBJECT_PREFIXES.TXN}.${s}.${u.table}`,(0,zR.createNatsTableStreamName)(s,u.table),void 0,u)?.catch(l=>{throw CE.error("An error has occurred trying to replicate transaction",u,l),l.statusCode=504,l}))}return Promise.all(n)}},WR=class extends wE{static{a(this,"ImmmediateNATSTransaction")}constructor(){super({get timestamp(){return(0,FH.getNextMonotonicTime)()}})}addWrite(t,r){super.addWrite(t,r),this.commit({})}};VH=new WR});var ix=g(Di=>{"use strict";var{isMainThread:tA,parentPort:bl,threadId:LE}=require("worker_threads"),{Socket:dse,createServer:fse}=require("net"),{createServer:Ese,IncomingMessage:hse}=require("http"),{createServer:mse}=require("https"),{readFileSync:pse,unlinkSync:KH,existsSync:Sse}=require("fs"),Lt=$(),He=Z(),ut=P(),{server:UE}=(ur(),ie(Hi)),{WebSocketServer:Tse}=require("ws"),{createSecureContext:gse,createServer:Rse}=require("node:tls"),{getTicketKeys:JH,restartNumber:Ase,getWorkerIndex:yl}=Je(),{Headers:jH,appendHeader:Ose}=(Qu(),ie(VU)),{recordAction:Ol,recordActionBinary:bse}=(ws(),ie(du)),{Request:XH,createReuseportFd:WH}=(IE(),ie(YR)),{checkMemoryLimit:yse}=Ji(),{X509Certificate:Nse}=require("crypto"),ZH=require("tls"),Ise=ZH.createSecureContext,za;ZH.createSecureContext=function(e){return za||Ise(e)};var ex=He.get(ut.CONFIG_PARAMS.THREADS_DEBUG);if(ex){let e;if(tA)e=He.get(ut.CONFIG_PARAMS.THREADS_DEBUG_PORT)??9229,process.on(["SIGINT","SIGTERM","SIGQUIT","exit"],()=>{try{require("inspector").close()}catch(t){Lt.info("Could not close debugger",t)}});else{let t=He.get(ut.CONFIG_PARAMS.THREADS_DEBUG_STARTINGPORT);t&&yl()>=0&&(e=t+yl())}if(e){let t=He.get(ut.CONFIG_PARAMS.THREADS_DEBUG_HOST),r=He.get(ut.CONFIG_PARAMS.THREADS_DEBUG_WAITFORDEBUGGER);try{require("inspector").open(e,t,r)}catch(n){Lt.trace(`Could not start debugging on port ${e}, you may already be debugging:`,n.message)}}}else if(process.env.DEV_MODE&&tA)try{require("inspector").open(9229)}catch(e){Ase<=1&&Lt.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:eSe,CONFIG_PARAMS:wse}=ut;He.initSync();var Cse=He.get(wse.HTTP_SESSIONAFFINITY),ds={};Di.registerServer=iA;Di.httpServer=oA;Di.deliverSocket=sA;Di.startServers=tx;Di.when_components_loaded=null;Di.createSNICallback=aA;UE.http=oA;UE.request=Pse;UE.socket=Use;UE.ws=vse;var ZR={},ME={},Dse,$s={},PE={},Lse=[],rA=[];function tx(){return Di.when_components_loaded=cA().loadRootComponents(!0).then(()=>{bl?.on("message",t=>{let{port:r,fd:n,data:s}=t;if(n)sA(n,r,s);else if(t.requestId)Mse(t);else if(t.type===ut.ITC_EVENT_TYPES.SHUTDOWN){Lt.trace("received shutdown request",LE);for(let i in ds){let o=ds[i],c;if(o.closeIdleConnections){let _=Object.getOwnPropertySymbols(o).find(E=>E.description.includes("connections")),l=0,d=setInterval(()=>{l++;let E=l>=100,f=o[_][E?"all":"idle"]();if(f.length===0){E&&clearInterval(d);return}l===1?Lt.info(`Closing ${f.length} idle connections`):E&&Lt.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
|
|
28
|
+
`},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()}});S0={type:"application/json",serializeStream:Nc,serialize:_l,deserialize:jee,q:.5};Ft.set("*/*",S0);Ft.set("",S0);a(jee,"tryJSONParse");a($g,"registerContentHandlers");Xee=require("fastify-plugin"),Zee=Xee(function(e,t,r){e.addHook("preSerialization",async(n,s)=>{if(s.raw.getHeader("content-type"))return;let{serializer:o,type:c}=Qf(n.raw);s.type(c),s.serializer(function(u){return(o.serializeStream||o.serialize)(u,{headers:{set:(_,l)=>{s.header(_,l)}}})})}),r()},{name:"content-type-negotiation"});a(Qf,"findBestSerializer");f0=qg.default.get(Fg.CONFIG_PARAMS.HTTP_COMPRESSIONTHRESHOLD);a(zf,"serialize");a(To,"serializeMessage");a(ete,"streamToBuffer");a(Oo,"getDeserializer");a(E0,"deserializerUnknownType");a(tte,"transformIterable")});function Wg(e,t,r,n,s,i,o,c){let u=e[0];if(t==="or"){let d=_(u);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=_(u),E=l(e.slice(1),!0,u.estimated_count);return E.length>0?o(d,E):d}function _(d){return d.conditions?Wg(d.conditions,d.operator,r,n,s,i,o,c):Ha(d,n,d.descending||s.reverse===!0,r,s.allowFullScan,c)}a(_,"executeCondition");function l(d,E,f){return d.map((h,p)=>{if(h.conditions){let R=h.operator==="or",b=l(h.conditions,!R,f);return R?(C,x)=>b.some(v=>v(C,x)):(C,x)=>b.every(v=>v(C,x))}let S=(h.attribute||h[0])===r.primaryKey,T=zg(h,r,i,c,S,f);return E&&p<d.length-1&&f&&(f=lte(r.primaryStore,h.estimated_count,f)),T}).filter(Boolean)}a(l,"mapConditionsToFilters")}function Ha(e,t,r,n,s,i){let o=e[0]??e.attribute,c=e[1]??e.value,u=e.comparator;if(Array.isArray(o)){let R=o[0],b=qs(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,x=new Map,v=Ha({attribute:o.length>2?o.slice(1):o[1],value:c,comparator:u},t,r,C,s,x);if(b.relationship.to){i[o[0]]=x;let F=!!qs(C.attributes,b.relationship.to)?.elements;v=ote(v,b,C.primaryStore,F,x)}if(b.relationship.from){let F=a(M=>Ha({attribute:b.relationship.from,value:M},t,r,n,s,x),"searchEntry");b.elements?(i[o[0]]=x,v=ate(v,b,C.primaryStore,x,F)):v=v.flatMap(F)}return v}else if(o.length===1)o=o[0];else throw new Xr.ClientError("Unable to query by attribute "+JSON.stringify(o))}let _,l,d,E;c instanceof Date&&(c=c.getTime());let f;switch(Qg[u]||u){case"lt":_=!0,l=c;break;case"le":_=!0,l=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,l=c.slice(0),l[l.length-1]=_s.MAXIMUM_KEY;break;case"starts_with":_=c.toString(),l=c+"\uFFFF";break;case"between":_=c[0],_ instanceof Date&&(_=_.getTime()),l=c[1],l instanceof Date&&(l=l.getTime()),d=!0;break;case"equals":case void 0:_=c,l=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 "${u}"`)}if(r){let R=_;_=l,l=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 ${u||"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=zg(e),!S)throw new Xr.ClientError(`Unknown search operator ${e.comparator}`)}let T={start:_,end:l,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:Ii.SKIP:new Promise((x,v)=>setImmediate(()=>{try{x(C&&S(C)?b:Ii.SKIP)}catch(F){v(F)}}))}:b=>b.value==null?Ii.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:Ii.SKIP:new Promise((C,x)=>setImmediate(()=>{try{C(S({[o]:R})?b:Ii.SKIP)}catch(v){x(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:Ii.SKIP:new Promise((C,x)=>setImmediate(()=>{try{C(b&&S(b)?R:Ii.SKIP)}catch(v){x(v)}}))})}function qs(e,t){if(Array.isArray(t))if(t.length>1){let r=qs(e,t[0]),n=(r?.definition?.tableClass||r?.elements.definition?.tableClass)?.attributes;return n?qs(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 ote(e,t,r,n,s){return new e.constructor({[Symbol.iterator](){let i;s.hasMappings=!0;let o;return{next(){if(!i){let u=t.relationship.to,_=a((l,d)=>{let E=l;Array.isArray(l)&&(E=Hn(l),o=!0);let f=s.get(E);f?f.push(d):s.set(E,f=[d]),l!==E&&(f.key=l)},"add_entry");for(let l of e){let d=l.value??r.get(l.key??l),E=d?.[u];if(E!=null&&!s.filters?.some(f=>!f(d)))if(n)for(let f=0;f<E.length;f++)_(E[f],l);else _(E,l)}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 ate(e,t,r,n,s){return new e.constructor({[Symbol.iterator](){let i,o,c=new Set;return{next(){let u;if(o)for(;u=o.next(),!u.done;){let _=Hn(u.value);if(!c.has(_))return c.add(_),u}if(!i){let _=new Map;n.fromRecord=l=>l[t.relationship.from]?.filter?.(d=>_.has(Hn(d)));for(let l of e){if(n.filters){let d=r.get(l);if(n.filters.some(E=>!E(d)))continue}_.set(Hn(l),l)}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 zg(e,t,r,n,s,i){let o=e.comparator,c=e[0]??e.attribute,u=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 l=c[0],d=qs(t.attributes,l),E=d.definition?.tableClass||d.elements.definition?.tableClass,f=n?.[l],h=zg({attribute:c.length>2?c.slice(1):c[1],value:u,comparator:o},E,r,f?.[l]?.joined,c[1]===E.primaryKey,i);if(!h)return;if(f){f.filters||(f.filters=[]),f.filters.push(h);return}let p=t.propertyResolvers?.[l],S,T=a((R,b)=>{let C,x;if(p){if(p.from&&h.idFilter){if(!S)if(h.idFilter.idSet?.size===1){for(let F of h.idFilter.idSet)e={attribute:p.from,value:F};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}x=p(R,r,b),C=x?.value}else C=R[l];return C?Array.isArray(C)?C.some(h):h(C,x):!1},"recordFilter");return T}}switch(u instanceof Date&&(u=u.getTime()),Qg[o]||o){case Yg.SEARCH_TYPES.EQUALS:case void 0:return _(c,l=>l===u,!0);case"contains":return _(c,l=>l?.toString().includes(u));case"ends_with":return _(c,l=>l?.toString().endsWith(u));case"starts_with":return _(c,l=>typeof l=="string"&&l.startsWith(u),!0);case"prefix":return Array.isArray(u)?u[u.length-1]==null&&(u=u.slice(0,-1)):u=[u],_(c,l=>{if(!Array.isArray(l))return!1;for(let d=0,E=u.length;d<E;d++)if(l[d]!==u[d])return!1;return!0},!0);case"between":return u[0]instanceof Date&&(u[0]=u[0].getTime()),u[1]instanceof Date&&(u[1]=u[1].getTime()),_(c,l=>(0,_s.compareKeys)(l,u[0])>=0&&(0,_s.compareKeys)(l,u[1])<=0,!0);case"gt":return _(c,l=>(0,_s.compareKeys)(l,u)>0);case"ge":return _(c,l=>(0,_s.compareKeys)(l,u)>=0);case"lt":return _(c,l=>(0,_s.compareKeys)(l,u)<0);case"le":return _(c,l=>(0,_s.compareKeys)(l,u)<=0);case"ne":return _(c,l=>(0,_s.compareKeys)(l,u)!==0);case"sort":return()=>!0;default:throw new Xr.ClientError(`Unknown query comparator "${o}"`)}function _(l,d,E,f){let h;E=E&&!s&&t?.indices[l]&&i>3,E&&(e.estimated_count==null&&jf(t)(e),h=e.estimated_count>>4,(isNaN(h)||h>=i)&&(E=!1));let p=0,S=3;function T(R){let b=R[l],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 x=Ha(e,r.transaction.getReadTxn(),!1,t).map(Hn),v=new Set(x);T.idFilter=F=>v.has(Hn(F)),T.idFilter.idSet=v}return C}return a(T,"recordFilter"),s&&(T.idFilter=d),T}a(_,"attributeComparator")}function jf(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/Gs(e.primaryStore):i.estimated_count}return r.estimated_count=s,r.estimated_count}let n=r.comparator||r.search_type;if(n=Qg[n]||n,n===Yg.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=qs(e.attributes,s[0]),o=i.definition?.tableClass||i.elements.definition?.tableClass,c=jf(o)({value:r.value,attribute:s.length>2?s.slice(1):s[1],comparator:"equals"}),u=e.indices[i.relationship.from];r.estimated_count=c+(u?c*Gs(e.indices[i.relationship.from])/(Gs(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=Gs(e.primaryStore)-(i?i.getValuesCount(null):0):r.estimated_count=1/0}else n==="starts_with"||n==="prefix"?r.estimated_count=ste*Gs(e.primaryStore)+1:n==="between"?r.estimated_count=nte*Gs(e.primaryStore)+1:n==="sort"?r.estimated_count=Gs(e.primaryStore)+1:r.estimated_count=rte*Gs(e.primaryStore)+1;typeof r.descending=="boolean"&&(r.estimated_count/=2)}return r.estimated_count}return a(t,"estimateConditionForTable"),t}function Xf(e){if(e)if(wi=e,Ba.lastIndex=0,cte.test(e))try{let t=fl(new xa,"");if(Dr!==wi.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 ${Dr} in '${wi}'`,t}else{let t=new URLSearchParams(e);return t.conditions=t,t}}function fl(e,t){let r=Ba,n,s,i,o,c,u=decodeURIComponent,_;for(;n=r.exec(wi);){Dr=r.lastIndex;let[,l,d]=n;if(o){if(l)throw new SyntaxError(`expected operator, but encountered '${l}'`);o=!1,c=!1}else c=!0;let E;switch(d){case"=":if(s){if(l.length<=2)i=l;else throw new SyntaxError(`invalid FIQL operator ${l}`);u=g0}else{if(u=decodeURIComponent,i="equals",!l)throw new SyntaxError("attribute must be specified before equality comparator");s=El(l)}break;case"==":case"!=":case"<":case"<=":case">":case">=":case"===":case"!==":if(i=ite[d],u=Kg[i]?g0:decodeURIComponent,!l)throw new SyntaxError(`attribute must be specified before comparator ${d}`);s=El(l);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:u(l)};i==="eq"&&R0(h,l),Jf(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(El(l)),s=void 0;break;case"(":Ba.lastIndex=Dr;let f=fl(l?[]:new xa,")");switch(l){case"":Jf(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=A0(f);break;default:throw new SyntaxError(`unknown query function call ${l}`)}wi[Dr]===","?r.lastIndex=++Dr:o=!0,s=null;break;case"{":if(e.conditions)throw new SyntaxError("property sets are not allowed in a queries");if(!l)throw new SyntaxError("property sets must have a defined parent property name");Ba.lastIndex=Dr,E=fl([],"}"),E.name=l,e.push(E),wi[Dr]===","?r.lastIndex=++Dr:o=!0;break;case"[":Ba.lastIndex=Dr,l?(E=fl(new xa,"]"),E.name=l):E=fl(e.conditions?new xa:[],"]"),e.conditions?(Jf(e,_),e.conditions.push(E),s=null):e.push(E),wi[Dr]===","?r.lastIndex=++Dr:o=!0;break;case")":case"]":case"}":if(t===d[0]){if(e.conditions){if(s){let h={comparator:i||"equals",attribute:s,value:u(l)};i==="eq"&&R0(h,l),Jf(e,_),e.conditions.push(h)}else if(l)throw new SyntaxError("no attribute or comparison specified")}else(l||e.length>0&&c)&&e.push(El(l));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?ute:Ba,r.lastIndex=Dr),Dr===wi.length)return e}if(t)throw new SyntaxError(`expected '${t}', but encountered end of string`)}function Jf(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 El(e){return e.indexOf(".")>-1?e.split(".").map(El):decodeURIComponent(e)}function g0(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 R0(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 A0(e){let t=O0(e[0]);return e.length>1&&(t.next=A0(e.slice(1))),t}function O0(e){if(Array.isArray(e)){let t=O0(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 Hn(e){return Array.isArray(e)?e.join("\0"):e}function Gs(e){let t=Date.now();return(e.estimatedEntryCountExpires||0)<t&&(e.estimatedEntryCount=e.getStats().entryCount,e.estimatedEntryCountExpires=t+1e4),e.estimatedEntryCount}function lte(e,t,r){return t*r/Gs(e)}var Xr,Yg,_s,Ii,rte,nte,ste,ite,Kg,Qg,cte,Ba,ute,Dr,wi,xa,Zf=Re(()=>{Xr=B(ne()),Yg=B(ft()),_s=require("ordered-binary"),Ii=require("lmdb"),rte=.3,nte=.1,ste=.05,ite={"<":"lt","<=":"le",">":"gt",">=":"ge","!=":"ne","==":"eq","===":"equals","!==":"not_equal"},Kg={lt:!0,le:!0,gt:!0,ge:!0,ne:!0,eq:!0};a(Wg,"executeConditions");a(Ha,"searchByIndex");a(qs,"findAttribute");a(ote,"joinTo");a(ate,"joinFrom");Qg={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(zg,"filterByType");a(jf,"estimateCondition");cte=/[()[\]|!<>.]|(=\w*=)/,Ba=/([^?&|=<>!([{}\]),]*)([([{}\])|,&]|[=<>!]*)/g,ute=/([^&|=[\]{}]+)([[\]{}]|[&|=]*)/g;a(Xf,"parseQuery");a(fl,"parseBlock");a(Jf,"assignOperator");a(El,"decodeProperty");a(g0,"typedDecoding");a(R0,"wildcardDecoding");a(A0,"toSortObject");a(O0,"toSortEntry");xa=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(Hn,"flattenKey");a(Gs,"estimatedEntryCount");a(lte,"intersectionEstimate")});function w0(e){let t={openapi:_te,info:{title:"HarperDB HTTP REST interface",version:(0,I0.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:u}=n.Resource;if(c=c??"id",!c)continue;let _={},l=[];if(o)for(let{type:b,name:C,elements:x,relationship:v,definition:F}of o){if(v)b==="array"?_[C]={type:"array",items:{$ref:Ci+x.type}}:_[C]={$ref:Ci+b};else{let M=F??x?.definition;if(M){if(!t.components.schemas[M.type]){let Q={};M.properties.forEach(J=>{Q[J.name]=new Zg(Jg[J.type],J.type)}),t.components.schemas[M.type]=new N0(Q)}b==="array"?_[C]={type:"array",items:{$ref:Ci+M.type}}:_[C]={$ref:Ci+M.type}}else b==="array"?x.type==="Any"||x.type=="ID"?_[C]={type:"array",items:{format:x.type}}:_[C]={type:"array",items:new Zg(Jg[x.type],x.type)}:b==="Any"||b=="ID"?_[C]={format:b}:_[C]=new Zg(Jg[b],b)}l.push(new eR(C,"query",_[C]))}let d=Object.keys(_),E=new eR(c,"path",{format:"ID"});E.required=!0,E.description="primary key of record";let f=new eR("property","path",{enum:d});f.required=!0,t.components.schemas[i]=new N0(_);let h=u.post!==Resource.prototype.post||u.update,p=typeof u.put=="function",S=typeof u.get=="function",T=typeof u.delete=="function",R="/"+s+"/";h&&(t.paths[R]={},t.paths[R].post=new dte(i,r,"create a new record auto-assigning a primary key")),S&&(t.paths[R]||(t.paths[R]={}),t.paths[R].get=new jg(l,r,{200:new Xg({$ref:Ci+i})},"search for records by the specified property name and value pairs")),T&&(t.paths[R]||(t.paths[R]={}),t.paths[R].delete=new y0(l,r,"delete all the records that match the provided query",{204:new b0})),R="/"+s+"/{"+c+"}",S&&(t.paths[R]={},t.paths[R].get=new jg([E],r,{200:new Xg({$ref:Ci+i})},"retrieve a record by its primary key")),p&&(t.paths[R]||(t.paths[R]={}),t.paths[R].put=new fte([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 y0([E],r,"delete a record with the given primary key",{204:new b0})),S&&f.schema.enum.length>0&&(R="/"+s+"/{"+c+"}.{property}",t.paths[R]={},t.paths[R].get=new jg([E,f],r,{200:new Xg({enum:d})},"used to retrieve the specified property of the specified record"))}return t}function dte(e,t,r){this.description=r,this.requestBody={content:{"application/json":{schema:{$ref:Ci+e}}}},this.security=t,this.responses={200:{description:tR,headers:{Location:{description:"primary key of new record",schema:{type:"string",format:"ID"}}},content:{"application/json":{schema:{type:"string",format:"ID"}}}}}}function jg(e,t,r,n){this.description=n,this.parameters=e,this.security=t,this.responses=r}function Xg(e){this.description=tR,this.content={"application/json":{schema:e}}}function b0(){this.description="successfully processed request, no content returned to client"}function fte(e,t,r,n){this.description=n,this.parameters=e,this.security=t,this.requestBody={content:{"application/json":{schema:{$ref:Ci+r}}}},this.responses={200:{description:tR}}}function y0(e,t,r,n){this.description=r,this.parameters=e,this.security=t,this.responses=n}function N0(e){this.type="object",this.properties=e}function Zg(e,t){this.type=e,this.format=t}function eR(e,t,r){this.name=e,this.in=t,this.schema=r}var I0,_te,Jg,Ci,tR,C0=Re(()=>{I0=B(zd()),_te="3.0.3",Jg={Int:"integer",Float:"number",Long:"integer",String:"string",Boolean:"boolean",Date:"string",Bytes:"string",BigInt:"integer",array:"array"},Ci="#/components/schemas/",tR="successful operation";a(w0,"generateJsonApi");a(dte,"Post");a(jg,"Get");a(Xg,"Response200");a(b0,"Response204");a(fte,"Put");a(y0,"Delete");a(N0,"ResourceSchema");a(Zg,"Type");a(eR,"Parameter")});var tE={};Fe(tE,{start:()=>mte});async function hte(e,t){let r=e.headers.asObject,n=r.accept==="text/event-stream"?"CONNECT":e.method;e.search&&Xf(e);let s=new bi;try{e.responseHeaders=s;let i=e.url.slice(1),o,c;if(i!==D0){let h=eE.getMatch(i);if(!h)return t(e);e.handlerPath=h.path,o={url:h.relativeURL,async:!0},c=h.Resource}let u=r["cache-control"];if(u){u=u.toLowerCase();let h=u.match(/max-age=(\d+)/)?.[1];h&&(e.expiresAt=h*1e3+Date.now()),u.includes("only-if-cached")&&(e.onlyIfCached=!0),u.includes("no-cache")&&(e.noCache=!0),u.includes("no-store")&&(e.noCacheStore=!0),u.includes("stale-if-error")&&(e.staleIfError=!0),u.includes("must-revalidate")&&(e.mustRevalidate=!0)}let _=await Ze(e,()=>{if(r["content-length"]||r["transfer-encoding"])try{e.data=Oo(r["content-type"],!0)(e.body,e.headers)}catch(h){throw new Ga.ClientError(h,400)}if(e.authorize=!0,i===D0&&n==="GET"){if(e?.user?.role?.permission?.super_user)return w0(eE);throw new Ga.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 Ga.ClientError("HarperDB is short and stout and can't brew coffee",418);default:throw new Ga.ServerError(`Method ${n} is not recognized`,501)}}),l=200,d;if(_==null)l=n==="GET"||n==="HEAD"?404:204,rR.lastModified&&e.lastModified&&s.setIfNone("Last-Modified",new Date(e.lastModified).toUTCString());else if(d=e.lastModified){Ete[0]=d;let h=String.fromCharCode(34,(Qt[0]&63)+62,(Qt[0]>>6)+(Qt[1]<<2&63)+62,(Qt[1]>>4)+(Qt[2]<<4&63)+62,(Qt[2]>>2)+62,(Qt[3]&63)+62,(Qt[3]>>6)+(Qt[4]<<2&63)+62,(Qt[4]>>4)+(Qt[5]<<4&63)+62,(Qt[5]>>2)+62,(Qt[6]&63)+62,(Qt[6]>>6)+(Qt[7]<<2&63)+62,34),p=r["if-none-match"];p&&h==p?(_?.onDone&&_.onDone(),l=304,_=void 0):s.setIfNone("ETag",h),rR.lastModified&&s.setIfNone("Last-Modified",new Date(d).toUTCString())}e.createdResource&&(l=201),e.newLocation&&s.setIfNone("Location",e.newLocation);let E={status:l,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=zf(_,e,E),n==="HEAD"&&(E.body=void 0)),E}catch(i){i.statusCode?i.statusCode===500?bo.warn(i):bo.info(i):bo.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=zf(i.contentType?i:i.toString(),e,o),o}}function mte(e){rR=e,!L0&&(L0=!0,eE=e.resources,e.server.http(async(t,r)=>{if(!t.isWebSocket)return hte(t,r)},e),e.server.ws(async(t,r,n)=>{hl++;let s=new yn;M0||(M0=!0,du(u=>{hl>0&&u.push({metric:"ws-connections",connections:hl,byThread:!0})}));let i;t.on("error",u=>{i=!0,bo.warn(u)});let o;t.on("message",a(function(_){o||(o=Oo(r.headers.asObject["content-type"]));let l=o(_);s.push(l)},"message"));let c;t.on("close",()=>{hl--,Wr(!i,"connection","ws","disconnect"),s.emit("close"),c&&c.return()});try{await n;let u=r.url.slice(1),_=eE.getMatch(u);if(Wr(!!_,"connection","ws","connect"),_){r.handlerPath=_.path,Sr(h=>({count:h.count,total:hl}),"connections",r.handlerPath,"connect","ws"),r.authorize=!0;let l={url:_.relativeURL,async:!0},d=_.Resource;c=(await Ze(r,()=>d.connect(l,s,r)))[Symbol.asyncIterator]();let f;for(;!(f=await c.next()).done;){let h=To(f.value,r);t.send(h),Sr(h.length,"bytes-sent",r.handlerPath,"message","ws")}}else return t.close(1011,`No resource was found to handle ${r.pathname}`)}catch(u){t.close(pte[u.statusCode]||1011,u.toString()),t.close("login fialed")}t.close()},e))}var bo,Ga,Qt,Ete,rR,D0,L0,eE,M0,hl,pte,P0=Re(()=>{Ca();Cs();bo=B($()),Ga=B(ne());Zf();bc();ro();Ju();C0();Qt=new Uint8Array(8),Ete=new Float64Array(Qt.buffer,0,1),rR={},D0="openapi";a(hte,"http");hl=0;a(mte,"start");pte={401:3e3,403:3003}});var nR=g((Zme,U0)=>{var{recordAction:rE,recordActionBinary:Ste}=(Cs(),ie(fu)),Tte=require("fastify-plugin"),gte=200;U0.exports=Tte(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(),u=s.request.routeOptions,_,l,d;u.config?.isOperation?(_=n.body?.operation,l="operation"):(_=u.url,l="fastify-route",d=u.method),rE(o,"duration",_,d,l),Ste(s.raw.statusCode<400,"success",_,d,l);let E=gte;i?.pipe?(i.on("data",S=>{E+=S.length}),i.on("end",()=>{rE(performance.now()-c,"transfer",_,d,l),rE(E,"bytes-sent",_,d,l)})):(E+=i?.length||0,rE(E,"bytes-sent",_,d,l));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 uR=g((rpe,H0)=>{var oE=require("clone"),aE=Xe(),Rte=z(),sE=P(),epe=$(),sR=require("fs"),oR=require("joi"),{string:iE}=oR.types(),{hdb_errors:Ate,handleHDBError:nE}=ne(),{HDB_ERROR_MSGS:tpe,HTTP_STATUS_CODES:iR}=Ate,{common_validators:qa}=Jn(),v0=" is required",Ote=["insert","update","upsert"],aR={database:{presence:!1,format:qa.schema_format,length:qa.schema_length},schema:{presence:!1,format:qa.schema_format,length:qa.schema_length},table:{presence:!0,format:qa.schema_format,length:qa.schema_length},action:{inclusion:{within:Ote,message:"is required and must be either insert, update, or upsert"}},file_path:{},csv_url:{url:{allowLocal:!0}},data:{},passthrough_headers:{}},bte={schema:iE.required(),table:iE.required(),action:iE.valid("insert","update","upsert")},{AWS_ACCESS_KEY:yte,AWS_SECRET:Nte,AWS_BUCKET:Ite,AWS_FILE_KEY:wte,REGION:Cte}=sE.S3_BUCKET_AUTH_KEYS,Dte={s3:{presence:!0},[`s3.${yte}`]:{presence:!0,type:"String"},[`s3.${Nte}`]:{presence:!0,type:"String"},[`s3.${Ite}`]:{presence:!0,type:"String"},[`s3.${wte}`]:{presence:!0,type:"String",hasValidFileExt:[".csv",".json"]},[`s3.${Cte}`]:{presence:!0,type:"String"}},B0=oE(aR);B0.data.presence={message:v0};var x0=oE(aR);x0.file_path.presence={message:v0};var Lte=Object.assign(oE(aR),Dte),cR=oE(bte);cR.csv_url=iE.uri().messages({"string.uri":"'csv_url' must be a valid url"}).required();cR.passthrough_headers=oR.object();function Mte(e){let t=aE.validateObject(e,B0);return cE(e,t)}a(Mte,"dataObject");function Pte(e){let t=aE.validateBySchema(e,oR.object(cR));return cE(e,t)}a(Pte,"urlObject");function Ute(e){let t=aE.validateObject(e,x0);return cE(e,t)}a(Ute,"fileObject");function vte(e){let t=aE.validateObject(e,Lte);return cE(e,t)}a(vte,"s3FileObject");function cE(e,t){if(!t){let r=Rte.checkGlobalSchemaTable(e.schema,e.table);if(r)return nE(new Error,r,iR.BAD_REQUEST);if(e.operation===sE.OPERATIONS_ENUM.CSV_FILE_LOAD)try{sR.accessSync(e.file_path,sR.constants.R_OK|sR.constants.F_OK)}catch(n){return n.code===sE.NODE_ERROR_CODES.ENOENT?nE(n,`No such file or directory ${n.path}`,iR.BAD_REQUEST):n.code===sE.NODE_ERROR_CODES.EACCES?nE(n,`Permission denied ${n.path}`,iR.BAD_REQUEST):nE(n)}}return t}a(cE,"postValidateChecks");H0.exports={dataObject:Mte,urlObject:Pte,fileObject:Ute,s3FileObject:vte}});var lR=g((spe,G0)=>{"use strict";var ml=$(),uE=P();async function Bte(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===uE.OPERATIONS_ENUM.INSERT||t.operation===uE.OPERATIONS_ENUM.UPDATE||t.operation===uE.OPERATIONS_ENUM.UPSERT?(delete s.new_attributes,delete s.txn_time):t.operation===uE.OPERATIONS_ENUM.DELETE&&delete s.txn_time,s}catch(i){throw i.message&&typeof i.message=="string"&&i.message.includes("already exists")?(ml.info(i.message),i):i.http_resp_msg?(ml.error(`Error calling operation: ${e.name}`),ml.error(i.http_resp_msg),i):(ml.error(`Error calling operation: ${e.name}`),ml.error(i),i)}}a(Bte,"callOperationFunctionAsAwait");G0.exports={callOperationFunctionAsAwait:Bte}});var F0=g((ope,q0)=>{"use strict";var _R=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}},dR=class{static{a(this,"BulkLoadDataObject")}constructor(t,r,n,s){this.action=t,this.schema=r,this.table=n,this.data=s}};q0.exports={BulkLoadFileObject:_R,BulkLoadDataObject:dR}});var V0=g((cpe,k0)=>{"use strict";var fR=class{static{a(this,"ClusteringOriginObject")}constructor(t,r,n){this.timestamp=t,this.user=r,this.node_name=n}};k0.exports=fR});var TR=g((Epe,oB)=>{"use strict";var lE=qr(),dE=uR(),xte=require("needle"),Gn=P(),lpe=Ve(),Fa=z(),{handleHDBError:lt,hdb_errors:X0}=ne(),{HTTP_STATUS_CODES:zt,HDB_ERROR_MSGS:Lt,CHECK_LOGS_WRAPPER:No}=X0,ka=$(),ER=require("papaparse");Fa.promisifyPapaParse();var qn=require("fs-extra"),Hte=require("path"),{chain:$0}=require("stream-chain"),Y0=require("stream-json/streamers/StreamArray"),K0=require("stream-json/utils/Batch"),W0=require("stream-chain/utils/comp"),{finished:Q0}=require("stream"),Gte=Z(),Z0=lR(),qte=xg(),{BulkLoadFileObject:mR,BulkLoadDataObject:Fte}=F0(),pR=Ig(),{verifyBulkLoadAttributePerms:eB}=kf(),_pe=V0(),dpe=ut(),fpe=As(),{databases:kte}=(Ae(),ie(ke)),{coerceType:Vte}=(fE(),ie(gR)),z0="No records parsed from csv file.",yo=`${Gte.get("HDB_ROOT")}/tmp`,{schema_regex:$te}=Jn(),J0=1024*1024*2,j0=5e3,Yte={"text/csv":!0,"application/octet-stream":!0,"text/plain":!0,"application/vnd.ms-excel":!0};oB.exports={csvDataLoad:Kte,csvURLLoad:Wte,csvFileLoad:Qte,importFromS3:zte};async function Kte(e,t){let r=dE.dataObject(e);if(r)throw lt(r,r.message,zt.BAD_REQUEST,void 0,void 0,!0);let n={};try{let s=nB(e.schema,e.table),i=ER.parse(e.data,{header:!0,skipEmptyLines:!0,transform:hR.bind(null,s),dynamicTyping:!1}),o=new pR;e.hdb_user&&e.hdb_user.role&&e.hdb_user.role.permission&&e.hdb_user.role.permission.super_user!==!0&&eB(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,zt.BAD_REQUEST,void 0,void 0,!0);let u=new Fte(e.action,e.schema,e.table,i.data);return n=await Z0.callOperationFunctionAsAwait(sB,u,null),n.message===z0?z0:iB(n.records,n.number_written)}catch(s){throw Io(s)}}a(Kte,"csvDataLoad");async function Wte(e){let t=dE.urlObject(e);if(t)throw lt(t,t.message,zt.BAD_REQUEST,void 0,void 0,!0);let r=`${Date.now()}.csv`,n=`${yo}/${r}`;try{await Jte(e,r)}catch(s){throw ka.error(Lt.DOWNLOAD_FILE_ERR(r)+" - "+s),lt(s,No(Lt.DOWNLOAD_FILE_ERR(r)))}try{let s=new mR(this.job_operation_function.name,e.action,e.schema,e.table,n,Gn.VALID_S3_FILE_TYPES.CSV,e.hdb_user.role.permission),i=await SR(s);return await _E(n),i}catch(s){throw await _E(n),Io(s)}}a(Wte,"csvURLLoad");async function Qte(e){let t=dE.fileObject(e);if(t)throw lt(t,t.message,zt.BAD_REQUEST,void 0,void 0,!0);let r=new mR(this.job_operation_function.name,e.action,e.schema,e.table,e.file_path,Gn.VALID_S3_FILE_TYPES.CSV,e.hdb_user.role.permission);try{return await SR(r)}catch(n){throw Io(n)}}a(Qte,"csvFileLoad");async function zte(e){let t=dE.s3FileObject(e);if(t)throw lt(t,t.message,zt.BAD_REQUEST,void 0,void 0,!0);let r;try{let n=Hte.extname(e.s3.key),s=`${Date.now()}${n}`;r=`${yo}/${s}`;let i=new mR(this.job_operation_function.name,e.action,e.schema,e.table,r,n,e.hdb_user.role.permission);await jte(s,e);let o=await SR(i);return await _E(r),o}catch(n){throw await _E(r),Io(n)}}a(zte,"importFromS3");async function Jte(e,t){let r;try{let n=e.passthrough_headers?{headers:e.passthrough_headers}:void 0;r=await xte("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,Gn.LOG_LEVELS.ERROR,"Error downloading CSV file - "+n)}Zte(r,e.csv_url),await Xte(t,r.raw)}a(Jte,"downloadCSVFile");async function jte(e,t){try{let r=`${yo}/${e}`;await qn.mkdirp(yo),await qn.writeFile(`${yo}/${e}`,"",{flag:"a+"});let n=await qn.createWriteStream(r),s=await qte.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(){ka.info(`${t.s3.key} successfully downloaded to ${r}`),i()})})}catch(r){throw ka.error(Lt.S3_DOWNLOAD_ERR+" - "+r),lt(r,No(Lt.S3_DOWNLOAD_ERR))}}a(jte,"downloadFileFromS3");async function Xte(e,t){try{await qn.mkdirp(yo),await qn.writeFile(`${yo}/${e}`,t)}catch(r){throw ka.error(Lt.WRITE_TEMP_FILE_ERR),lt(r,No(Lt.DEFAULT_BULK_LOAD_ERR))}}a(Xte,"writeFileToTempFolder");async function _E(e){if(e)try{await qn.access(e),await qn.unlink(e)}catch{ka.warn(`could not delete temp csv file at ${e}, file does not exist`)}}a(_E,"deleteTempFile");function Zte(e,t){if(e.statusCode!==X0.HTTP_STATUS_CODES.OK)throw lt(new Error,`CSV Load failed from URL: ${t}, status code: ${e.statusCode}, message: ${e.statusMessage}`,zt.BAD_REQUEST);if(!Yte[e.headers["content-type"]])throw lt(new Error,`CSV Load failed from URL: ${t}, unsupported content type: ${e.headers["content-type"]}`,zt.BAD_REQUEST);if(!e.raw)throw lt(new Error,`CSV Load failed from URL: ${t}, no csv found at url`,zt.BAD_REQUEST)}a(Zte,"validateURLResponse");async function SR(e){try{let t;switch(e.file_type){case Gn.VALID_S3_FILE_TYPES.CSV:t=await ere(e);break;case Gn.VALID_S3_FILE_TYPES.JSON:t=await tre(e);break;default:throw lt(new Error,Lt.DEFAULT_BULK_LOAD_ERR,zt.BAD_REQUEST,Gn.LOG_LEVELS.ERROR,Lt.INVALID_FILE_EXT_ERR(e))}return iB(t.records,t.number_written)}catch(t){throw Io(t)}}a(SR,"fileLoad");async function tB(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 lE.validation(o);e.role_perms&&e.role_perms.super_user!==!0&&eB(e.role_perms,e.op,e.action,e.schema,e.table,c,t),s&&s.resume()}catch(c){let u=lt(c);r(u)}}a(tB,"validateChunk");async function rB(e,t,r,n,s){let i=n.data?n.data:n;if(i.length===0)return;Fa.autoCastJSONDeep(i),s&&s.pause();let o=n.meta?n.meta.fields:null;if(o)i.forEach(c=>{!Fa.isEmpty(c)&&!Fa.isEmpty(c.__parsed_extra)&&delete c.__parsed_extra});else{let c=new Set;i.forEach(u=>{Object.keys(u).forEach(_=>c.add(_))}),o=[...c]}try{let c={schema:e.schema,table:e.table,action:e.action,data:i},u=await Z0.callOperationFunctionAsAwait(sB,c,null);t.records+=u.records,t.number_written+=u.number_written,s&&s.resume()}catch(c){let u=lt(c,No(Lt.INSERT_CSV_ERR),zt.INTERNAL_SERVER_ERROR,Gn.LOG_LEVELS.ERROR,Lt.INSERT_CSV_ERR+" - "+c);r(u)}}a(rB,"insertChunk");async function ere(e){let t={records:0,number_written:0},r=nB(e.schema,e.table);try{let n=new pR,s=qn.createReadStream(e.file_path,{highWaterMark:J0});s.setEncoding("utf8"),await ER.parsePromise(s,tB.bind(null,e,n),hR.bind(null,r));let i=n.getPermsResponse();if(i)throw lt(new Error,i,zt.BAD_REQUEST);return s=qn.createReadStream(e.file_path,{highWaterMark:J0}),s.setEncoding("utf8"),await ER.parsePromise(s,rB.bind(null,e,t),hR.bind(null,r)),s.destroy(),t}catch(n){throw lt(n,No(Lt.PAPA_PARSE_ERR),zt.INTERNAL_SERVER_ERROR,Gn.LOG_LEVELS.ERROR,Lt.PAPA_PARSE_ERR+n)}}a(ere,"callPapaParse");function nB(e,t){let r=kte[e][t].attributes,n=new Map;for(let s of r)s.type&&n.set(s.name,i=>Vte(i,s));return n}a(nB,"createTransformMap");function hR(e,t,r){let n=e.get(r);return n?n(t):Fa.autoCast(t)}a(hR,"typeFunction");async function tre(e){let t={records:0,number_written:0},r=a(n=>{throw n},"throwErr");try{let n=new pR,s=$0([qn.createReadStream(e.file_path,{encoding:"utf-8"}),Y0.withParser(),c=>c.value,new K0({batchSize:j0}),W0(async c=>{await tB(e,n,r,c)})]);await new Promise((c,u)=>{Q0(s,_=>{_?u(_):c()}),s.resume()});let i=n.getPermsResponse();if(i)throw lt(new Error,i,zt.BAD_REQUEST);let o=$0([qn.createReadStream(e.file_path,{encoding:"utf-8"}),Y0.withParser(),c=>c.value,new K0({batchSize:j0}),W0(async c=>{await rB(e,t,r,c)})]);return await new Promise((c,u)=>{Q0(o,_=>{_?u(_):c()}),o.resume()}),t}catch(n){throw lt(n,No(Lt.INSERT_JSON_ERR),zt.INTERNAL_SERVER_ERROR,Gn.LOG_LEVELS.ERROR,Lt.INSERT_JSON_ERR+n)}}a(tre,"insertJson");async function sB(e){let t={};try{e.data&&e.data.length>0&&rre(e.data[0])?t=await nre(e.data,e.schema,e.table,e.action):(t.message="No records parsed from csv file.",ka.info(t.message))}catch(r){throw Io(r)}return t}a(sB,"callBulkFileLoad");function rre(e){let t=Object.keys(e);for(let r of t)if(!$te.test(r))throw new Error(`Invalid column name '${r}', cancelling load operation`);return!0}a(rre,"validateColumnNames");async function nre(e,t,r,n){n||(n="insert");let s={operation:n,schema:t,table:r,records:e},i;switch(n){case"insert":i=lE.insert;break;case"update":i=lE.update;break;case"upsert":i=lE.upsert;break;default:throw lt(new Error,Lt.INVALID_ACTION_PARAM_ERR(n),zt.BAD_REQUEST,Gn.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 l=global.hdb_schema[t][r].hash_attribute,d=e.length;for(;d--;)o.skipped_hashes.indexOf(e[d][l])>=0&&e.splice(d,1)}let u=Fa.isEmptyOrZeroLength(c)?0:c.length;return{records:e.length,number_written:u,new_attributes:o.new_attributes}}catch(o){throw Io(o)}}a(nre,"bulkFileLoad");function iB(e,t){return`successfully loaded ${t} of ${e} records`}a(iB,"buildResponseMsg");function Io(e){return lt(e,No(Lt.DEFAULT_BULK_LOAD_ERR),zt.INTERNAL_SERVER_ERROR,Gn.LOG_LEVELS.ERROR,Lt.DEFAULT_BULK_LOAD_ERR+" - "+e)}a(Io,"buildTopLevelErrMsg")});var cB=g((mpe,aB)=>{"use strict";var RR=class{static{a(this,"SqlSearchObject")}constructor(t,r){this.operation="sql",this.sql=t,this.hdb_user=r}};aB.exports=RR});var _B=g((Spe,lB)=>{"use strict";var sre=P(),uB=require("moment"),ire=require("uuid").v4,AR=class{static{a(this,"JobObject")}constructor(){this.id=ire(),this.type=void 0,this.start_datetime=uB().valueOf(),this.created_datetime=uB().valueOf(),this.end_datetime=void 0,this.status=sre.JOB_STATUS_ENUM.CREATED,this.message=void 0,this.user=void 0,this.request=void 0}};lB.exports=AR});var OR=g((gpe,TB)=>{"use strict";var ore=require("uuid").v4,mB=qr(),pB=Gr(),are=ts(),cre=ia(),ure=cB(),et=P(),lre=_B(),_re=kd(),Sn=$(),dre=qc(),Va=z(),{promisify:fre}=require("util"),wo=require("moment"),Ere=$f(),EE=uR(),dB=Wm(),{deleteTransactionLogsBeforeValidator:hre}=Ag(),{handleHDBError:fB,hdb_errors:mre}=ne(),{HTTP_STATUS_CODES:EB}=mre,hB=pB.searchByValue,pre=pB.searchByHash,Sre=mB.insert,Tre=fre(Ere.evaluateSQL),gre=mB.update;TB.exports={addJob:Ore,updateJob:yre,handleGetJob:Rre,handleGetJobsByStartDate:Are,getJobById:SB};async function Rre(e){try{let t=await SB(e.id);return Va.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 Sn.error("There was an error getting job",t),new Error(r)}}a(Rre,"handleGetJob");async function Are(e){try{let t=await bre(e);if(Sn.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=wo(r.start_datetime)),r.end_datetime&&(r.end_datetime_converted=wo(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 Sn.error(r),new Error(r)}}a(Are,"handleGetJobsByStartDate");async function Ore(e){let t={message:"",error:"",success:!1,createdJob:void 0};if(!e||Object.keys(e).length===0||Va.isEmptyOrZeroLength(e.operation)){let l="job parameter is invalid";return Sn.info(l),t.error=l,t}if(!et.JOB_TYPE_ENUM[e.operation])return Sn.info(`invalid job type specified: ${e.operation}.`),t;let r=e.operation,n;switch(r){case et.OPERATIONS_ENUM.CSV_FILE_LOAD:n=EE.fileObject(e);break;case et.OPERATIONS_ENUM.CSV_URL_LOAD:n=EE.urlObject(e);break;case et.OPERATIONS_ENUM.CSV_DATA_LOAD:n=EE.dataObject(e);break;case et.OPERATIONS_ENUM.IMPORT_FROM_S3:n=EE.s3FileObject(e);break;case et.OPERATIONS_ENUM.DELETE_FILES_BEFORE:case et.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE:n=dB(e,"date");break;case et.OPERATIONS_ENUM.DELETE_AUDIT_LOGS_BEFORE:n=dB(e,"timestamp");break;case et.OPERATIONS_ENUM.DELETE_TRANSACTION_LOGS_BEFORE:n=hre(e);break;case et.OPERATIONS_ENUM.RESTART_SERVICE:if(et.PROCESS_DESCRIPTORS_VALIDATE[e.service]===void 0)throw fB(new Error,"Invalid service",EB.BAD_REQUEST,void 0,void 0,!0);break;default:break}if(n)throw fB(n,n.message,EB.BAD_REQUEST,void 0,void 0,!0);let s=new lre;s.type=e.operation===et.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE?et.OPERATIONS_ENUM.DELETE_FILES_BEFORE:e.operation,s.type=e.operation,s.user=e.hdb_user.username;let i=new are(et.SYSTEM_SCHEMA_NAME,et.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,"id",s.id,"id",["id"]),o;try{o=Array.from(await hB(i))}catch(l){let d=`There was an error inserting a new job: ${l}`;return Sn.error(d),t}let c=Array.isArray(o)?o:Object.keys(o);if(c&&c.length>0){s.id=ore();try{o=await hB(i)}catch(l){let d=`There was an error inserting a new job: ${l}`;return Sn.error(d),t}if(c=Array.isArray(o)?o:Object.keys(o),c&&c.length>0)return Sn.error("Error creating a job, could not find a unique job id."),t}s.request=e;let u=new dre(et.SYSTEM_SCHEMA_NAME,et.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,"id",[s]),_;try{_=await Sre(u)}catch(l){return Sn.error(`There was an error inserting a job for job type: ${e.operation} -- ${l}`),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 l=`Created a job with type ${s.type} and id ${s.id}`;t.message=l,t.createdJob=s,t.success=!0,Sn.trace(l)}return t}a(Ore,"addJob");async function bre(e){let t=wo(e.from_date,wo.ISO_8601),r=wo(e.to_date,wo.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 ure(n,e.hdb_user);try{return await Tre(s)}catch(i){throw Sn.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(bre,"getJobsInDateRange");async function SB(e){if(Va.isEmptyOrZeroLength(e))return Va.errorizeMessage("Invalid job ID specified.");let t=new cre(et.SYSTEM_SCHEMA_NAME,et.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,[e],["*"]);try{return await pre(t)}catch(r){let n=`There was an error searching for a job by id: ${e} ${r}`;return Sn.error(n),Va.errorizeMessage("there was an error searching for jobs. Please check the log for details.")}}a(SB,"getJobById");async function yre(e){if(Object.keys(e).length===0)throw new Error("invalid job object passed to updateJob");if(Va.isEmptyOrZeroLength(e.id))throw new Error("invalid ID passed to updateJob");(e.status===et.JOB_STATUS_ENUM.COMPLETE||e.status===et.JOB_STATUS_ENUM.ERROR)&&(e.end_datetime=wo().valueOf());let t=new _re(et.SYSTEM_SCHEMA_NAME,et.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,[e]),r;return r=await gre(t),r}a(yre,"updateJob")});var IB=g((Ape,NB)=>{"use strict";var gB=z(),Mt=P(),Nre=require("moment"),hE=TR(),pl=$(),RB=OR(),AB=Yf(),OB=oi(),bB=We(),Ire=Hf(),wre=Wu(),{parentPort:Cre,isMainThread:yB}=require("worker_threads"),{onMessageByType:Dre}=We(),bR=class{static{a(this,"RunnerMessage")}constructor(t,r){this.job=t,this.json=r}};async function Lre(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(gB.isEmptyOrZeroLength(e.json.operation))throw new Error("Invalid operation");if(gB.isEmptyOrZeroLength(e.job.id))throw new Error("Empty job id specified");switch(e.json.operation){case Mt.JOB_TYPE_ENUM.csv_file_load:await ds(e,hE.csvFileLoad);break;case Mt.JOB_TYPE_ENUM.csv_url_load:await ds(e,hE.csvURLLoad);break;case Mt.JOB_TYPE_ENUM.csv_data_load:await ds(e,hE.csvDataLoad);break;case Mt.JOB_TYPE_ENUM.import_from_s3:await ds(e,hE.importFromS3);break;case Mt.JOB_TYPE_ENUM.empty_trash:break;case Mt.JOB_TYPE_ENUM.export_local:await ds(e,AB.export_local);break;case Mt.JOB_TYPE_ENUM.export_to_s3:await ds(e,AB.export_to_s3);break;case Mt.JOB_TYPE_ENUM.delete_files_before:case Mt.JOB_TYPE_ENUM.delete_records_before:await ds(e,OB.deleteFilesBefore);break;case Mt.JOB_TYPE_ENUM.delete_audit_logs_before:await ds(e,OB.deleteAuditLogsBefore);break;case Mt.JOB_TYPE_ENUM.delete_transaction_logs_before:await ds(e,Ire.deleteTransactionLogsBefore);break;case Mt.JOB_TYPE_ENUM.restart_service:return await ds(e,wre.restartService),`Restarting ${e.json.service}`;break;default:return`Invalid operation ${e.json.operation} specified`}}a(Lre,"parseMessage");async function ds(e,t){try{e.job.status=Mt.JOB_STATUS_ENUM.IN_PROGRESS,e.job.start_datetime=Nre().valueOf(),await RB.updateJob(e.job),await Mre(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):pl.error(`There was an error running ${t.name} job with id ${e.job.id}`),pl.error(n),e.job.message=n,e.job.status=Mt.JOB_STATUS_ENUM.ERROR;try{await RB.updateJob(e.job)}catch(s){throw pl.error(`Unable to update job with id ${e.job.id}`),s}throw r}}a(ds,"runJob");async function Mre(e){pl.trace("launching job thread:",e),yB?bB.startWorker("server/jobs/jobProcess.js",{autoRestart:!1,name:"job",env:Object.assign({},process.env,{[Mt.PROCESS_NAME_ENV_PROP]:`JOB-${e}`})}):Cre.postMessage({type:Mt.ITC_EVENT_TYPES.START_JOB,jobId:e})}a(Mre,"launchJobThread");yB&&Dre(Mt.ITC_EVENT_TYPES.START_JOB,async(e,t)=>{try{bB.startWorker("server/jobs/jobProcess.js",{autoRestart:!1,name:"job",env:Object.assign({},process.env,{[Mt.PROCESS_NAME_ENV_PROP]:`JOB-${e.jobId}`})})}catch(r){pl.error(r)}});NB.exports={parseMessage:Lre,RunnerMessage:bR}});var CB=g((bpe,wB)=>{"use strict";var yR=class{static{a(this,"OperationFunctionObject")}constructor(t,r=void 0){this.operation_function=t,this.job_operation_function=r}};wB.exports=yR});var KB=g((Npe,LR)=>{"use strict";var gE=Gr(),wR=$f(),mE=TR(),Fs=gu(),pE=Os(),Tl=oi(),Pre=qS(),Sl=ln(),SE=zS(),Jt=Rg(),TE=$(),Ure=XS(),vre=tf(),DB=LT(),Bre=nf(),xre=PT(),Hre=UT(),Gre=xT(),qre=GT(),NR=kT(),LB=Yf(),Fre=kf(),CR=OR(),q=P(),{hdb_errors:Rl,handleHDBError:gl}=ne(),{HTTP_STATUS_CODES:MB}=Rl,IR=WT(),PB=Wu(),kB=require("util"),$a=qr(),kre=bs(),Vre=ga(),UB=IB(),vB=Nu(),BB=(wf(),ie(ju)),xB=Er(),HB=Hf(),GB=Pf(),{setServerUtilities:$re}=(fE(),ie(gR)),{CONTEXT:Yre}=(Nn(),ie(qp)),{_assignPackageExport:Kre}=require("../index"),{transformReq:Wre}=z(),{server:Qre}=(lr(),ie(xi)),or=TE.loggerWithTag("operation"),zre=lR(),qB=gE.searchByHash,Jre=gE.searchByValue,jre=kB.promisify(gE.search),Xre=kB.promisify(wR.evaluateSQL),Zre={[q.OPERATIONS_ENUM.CREATE_ATTRIBUTE]:!0,[q.OPERATIONS_ENUM.CREATE_TABLE]:!0,[q.OPERATIONS_ENUM.CREATE_SCHEMA]:!0,[q.OPERATIONS_ENUM.DROP_ATTRIBUTE]:!0,[q.OPERATIONS_ENUM.DROP_TABLE]:!0,[q.OPERATIONS_ENUM.DROP_SCHEMA]:!0},Y=CB();async function VB(e,t){try{if(e.body.operation!=="read_log"&&(TE.log_level===q.LOG_LEVELS.INFO||TE.log_level===q.LOG_LEVELS.DEBUG||TE.log_level===q.LOG_LEVELS.TRACE)){let{hdb_user:n,hdb_auth_header:s,password:i,...o}=e.body;or.info(o)}}catch(n){or.error(n)}let r=await zre.callOperationFunctionAsAwait(t,e.body,null);if(typeof r!="object"&&(r={message:r}),r instanceof Error)throw r;return Zre[e.body.operation]&&kre.setSchemaDataToGlobal(n=>{n&&or.error(n)}),r}a(VB,"processLocalTransaction");var FB=tne();LR.exports={chooseOperation:$B,getOperationFunction:YB,operation:DR,processLocalTransaction:VB};$re(LR.exports);Qre.operation=DR;function $B(e){let t;try{t=YB(e)}catch(s){throw or.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=wR.convertSQLToAST(s);if(e.parsed_sql_object=i,!e.bypass_auth){let o=wR.checkASTPermissions(e,i);if(o)throw or.error(`${MB.FORBIDDEN} from operation ${e.operation}`),or.warn(`User '${e.hdb_user.username}' is not permitted to ${e.operation}`),gl(new Error,o,Rl.HTTP_STATUS_CODES.FORBIDDEN,void 0,void 0,!0)}}else if(!e.bypass_auth&&e.operation!==q.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS&&e.operation!==q.OPERATIONS_ENUM.LOGIN&&e.operation!==q.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=Fre.verifyPerms(i,s);if(o)throw or.error(`${MB.FORBIDDEN} from operation ${e.operation}`),or.warn(`User '${i.hdb_user.username}' is not permitted to ${i.operation}`),gl(new Error,o,Rl.HTTP_STATUS_CODES.FORBIDDEN,void 0,!1,!0)}}catch(s){throw gl(s,"There was an error when trying to choose an operation path")}return r}a($B,"chooseOperation");function YB(e){if(or.trace(`getOperationFunction with operation: ${e.operation}`),FB.has(e.operation))return FB.get(e.operation);throw gl(new Error,Rl.HDB_ERROR_MSGS.OP_NOT_FOUND(e.operation),Rl.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0)}a(YB,"getOperationFunction");Kre("operation",DR);function DR(e,t){e.hdb_user=this[Yre]?.user,e.bypass_auth=!t;let r=$B(e);return VB({body:e},r)}a(DR,"operation");async function ene(e){or.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[q.CLUSTERING_FLAG]=!0;let o;switch(i.operation){case q.OPERATIONS_ENUM.INSERT:o=await $a.insert(i);break;case q.OPERATIONS_ENUM.UPDATE:o=await $a.update(i);break;case q.OPERATIONS_ENUM.UPSERT:o=await $a.upsert(i);break;case q.OPERATIONS_ENUM.DELETE:o=await Tl.deleteRecord(i);break;default:or.warn("invalid operation in catchup");break}await transact_to_clustering_utils.postOperationHandler(i,o,e)}catch(o){or.info("Invalid operation in transaction"),or.error(o)}}a(ene,"catchup");async function Fn(e){Wre(e);let t,r;try{r=await CR.addJob(e),t=r.createdJob,or.info("addJob result",r);let n=new UB.RunnerMessage(t,e);return{message:await UB.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 or.error(s),gl(n,s)}}a(Fn,"executeJob");function tne(){let e=new Map;return e.set(q.OPERATIONS_ENUM.INSERT,new Y($a.insert)),e.set(q.OPERATIONS_ENUM.UPDATE,new Y($a.update)),e.set(q.OPERATIONS_ENUM.UPSERT,new Y($a.upsert)),e.set(q.OPERATIONS_ENUM.SEARCH_BY_CONDITIONS,new Y(gE.searchByConditions)),e.set(q.OPERATIONS_ENUM.SEARCH_BY_HASH,new Y(qB)),e.set(q.OPERATIONS_ENUM.SEARCH_BY_ID,new Y(qB)),e.set(q.OPERATIONS_ENUM.SEARCH_BY_VALUE,new Y(Jre)),e.set(q.OPERATIONS_ENUM.SEARCH,new Y(jre)),e.set(q.OPERATIONS_ENUM.SQL,new Y(Xre)),e.set(q.OPERATIONS_ENUM.CSV_DATA_LOAD,new Y(Fn,mE.csvDataLoad)),e.set(q.OPERATIONS_ENUM.CSV_FILE_LOAD,new Y(Fn,mE.csvFileLoad)),e.set(q.OPERATIONS_ENUM.CSV_URL_LOAD,new Y(Fn,mE.csvURLLoad)),e.set(q.OPERATIONS_ENUM.IMPORT_FROM_S3,new Y(Fn,mE.importFromS3)),e.set(q.OPERATIONS_ENUM.CREATE_SCHEMA,new Y(Fs.createSchema)),e.set(q.OPERATIONS_ENUM.CREATE_DATABASE,new Y(Fs.createSchema)),e.set(q.OPERATIONS_ENUM.CREATE_TABLE,new Y(Fs.createTable)),e.set(q.OPERATIONS_ENUM.CREATE_ATTRIBUTE,new Y(Fs.createAttribute)),e.set(q.OPERATIONS_ENUM.DROP_SCHEMA,new Y(Fs.dropSchema)),e.set(q.OPERATIONS_ENUM.DROP_DATABASE,new Y(Fs.dropSchema)),e.set(q.OPERATIONS_ENUM.DROP_TABLE,new Y(Fs.dropTable)),e.set(q.OPERATIONS_ENUM.DROP_ATTRIBUTE,new Y(Fs.dropAttribute)),e.set(q.OPERATIONS_ENUM.DESCRIBE_SCHEMA,new Y(pE.describeSchema)),e.set(q.OPERATIONS_ENUM.DESCRIBE_DATABASE,new Y(pE.describeSchema)),e.set(q.OPERATIONS_ENUM.DESCRIBE_TABLE,new Y(pE.describeTable)),e.set(q.OPERATIONS_ENUM.DESCRIBE_ALL,new Y(pE.describeAll)),e.set(q.OPERATIONS_ENUM.DELETE,new Y(Tl.deleteRecord)),e.set(q.OPERATIONS_ENUM.ADD_USER,new Y(Sl.addUser)),e.set(q.OPERATIONS_ENUM.ALTER_USER,new Y(Sl.alterUser)),e.set(q.OPERATIONS_ENUM.DROP_USER,new Y(Sl.dropUser)),e.set(q.OPERATIONS_ENUM.LIST_USERS,new Y(Sl.listUsersExternal)),e.set(q.OPERATIONS_ENUM.LIST_ROLES,new Y(SE.listRoles)),e.set(q.OPERATIONS_ENUM.ADD_ROLE,new Y(SE.addRole)),e.set(q.OPERATIONS_ENUM.ALTER_ROLE,new Y(SE.alterRole)),e.set(q.OPERATIONS_ENUM.DROP_ROLE,new Y(SE.dropRole)),e.set(q.OPERATIONS_ENUM.USER_INFO,new Y(Sl.userInfo)),e.set(q.OPERATIONS_ENUM.READ_LOG,new Y(Ure)),e.set(q.OPERATIONS_ENUM.ADD_NODE,new Y(vre)),e.set(q.OPERATIONS_ENUM.UPDATE_NODE,new Y(DB)),e.set(q.OPERATIONS_ENUM.SET_NODE_REPLICATION,new Y(DB)),e.set(q.OPERATIONS_ENUM.REMOVE_NODE,new Y(Bre)),e.set(q.OPERATIONS_ENUM.CONFIGURE_CLUSTER,new Y(xre)),e.set(q.OPERATIONS_ENUM.PURGE_STREAM,new Y(Hre)),e.set(q.OPERATIONS_ENUM.SET_CONFIGURATION,new Y(xB.setConfiguration)),e.set(q.OPERATIONS_ENUM.CLUSTER_STATUS,new Y(Gre.clusterStatus)),e.set(q.OPERATIONS_ENUM.CLUSTER_NETWORK,new Y(qre)),e.set(q.OPERATIONS_ENUM.CLUSTER_SET_ROUTES,new Y(NR.setRoutes)),e.set(q.OPERATIONS_ENUM.CLUSTER_GET_ROUTES,new Y(NR.getRoutes)),e.set(q.OPERATIONS_ENUM.CLUSTER_DELETE_ROUTES,new Y(NR.deleteRoutes)),e.set(q.OPERATIONS_ENUM.EXPORT_TO_S3,new Y(Fn,LB.export_to_s3)),e.set(q.OPERATIONS_ENUM.DELETE_FILES_BEFORE,new Y(Fn,Tl.deleteFilesBefore)),e.set(q.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE,new Y(Fn,Tl.deleteFilesBefore)),e.set(q.OPERATIONS_ENUM.EXPORT_LOCAL,new Y(Fn,LB.export_local)),e.set(q.OPERATIONS_ENUM.SEARCH_JOBS_BY_START_DATE,new Y(CR.handleGetJobsByStartDate)),e.set(q.OPERATIONS_ENUM.GET_JOB,new Y(CR.handleGetJob)),e.set(q.OPERATIONS_ENUM.GET_FINGERPRINT,new Y(IR.getFingerprint)),e.set(q.OPERATIONS_ENUM.SET_LICENSE,new Y(IR.setLicense)),e.set(q.OPERATIONS_ENUM.GET_REGISTRATION_INFO,new Y(IR.getRegistrationInfo)),e.set(q.OPERATIONS_ENUM.RESTART,new Y(PB.restart)),e.set(q.OPERATIONS_ENUM.RESTART_SERVICE,new Y(Fn,PB.restartService)),e.set(q.OPERATIONS_ENUM.CATCHUP,new Y(ene)),e.set(q.OPERATIONS_ENUM.SYSTEM_INFORMATION,new Y(Vre.systemInformation)),e.set(q.OPERATIONS_ENUM.DELETE_AUDIT_LOGS_BEFORE,new Y(Fn,Tl.deleteAuditLogsBefore)),e.set(q.OPERATIONS_ENUM.READ_AUDIT_LOG,new Y(Pre)),e.set(q.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS,new Y(vB.createTokens)),e.set(q.OPERATIONS_ENUM.REFRESH_OPERATION_TOKEN,new Y(vB.refreshOperationToken)),e.set(q.OPERATIONS_ENUM.LOGIN,new Y(BB.login)),e.set(q.OPERATIONS_ENUM.LOGOUT,new Y(BB.logout)),e.set(q.OPERATIONS_ENUM.GET_CONFIGURATION,new Y(xB.getConfiguration)),e.set(q.OPERATIONS_ENUM.CUSTOM_FUNCTIONS_STATUS,new Y(Jt.customFunctionsStatus)),e.set(q.OPERATIONS_ENUM.GET_CUSTOM_FUNCTIONS,new Y(Jt.getCustomFunctions)),e.set(q.OPERATIONS_ENUM.GET_COMPONENT_FILE,new Y(Jt.getComponentFile)),e.set(q.OPERATIONS_ENUM.GET_COMPONENTS,new Y(Jt.getComponents)),e.set(q.OPERATIONS_ENUM.SET_COMPONENT_FILE,new Y(Jt.setComponentFile)),e.set(q.OPERATIONS_ENUM.DROP_COMPONENT,new Y(Jt.dropComponent)),e.set(q.OPERATIONS_ENUM.GET_CUSTOM_FUNCTION,new Y(Jt.getCustomFunction)),e.set(q.OPERATIONS_ENUM.SET_CUSTOM_FUNCTION,new Y(Jt.setCustomFunction)),e.set(q.OPERATIONS_ENUM.DROP_CUSTOM_FUNCTION,new Y(Jt.dropCustomFunction)),e.set(q.OPERATIONS_ENUM.ADD_CUSTOM_FUNCTION_PROJECT,new Y(Jt.addComponent)),e.set(q.OPERATIONS_ENUM.ADD_COMPONENT,new Y(Jt.addComponent)),e.set(q.OPERATIONS_ENUM.DROP_CUSTOM_FUNCTION_PROJECT,new Y(Jt.dropCustomFunctionProject)),e.set(q.OPERATIONS_ENUM.PACKAGE_CUSTOM_FUNCTION_PROJECT,new Y(Jt.packageComponent)),e.set(q.OPERATIONS_ENUM.PACKAGE_COMPONENT,new Y(Jt.packageComponent)),e.set(q.OPERATIONS_ENUM.DEPLOY_CUSTOM_FUNCTION_PROJECT,new Y(Jt.deployComponent)),e.set(q.OPERATIONS_ENUM.DEPLOY_COMPONENT,new Y(Jt.deployComponent)),e.set(q.OPERATIONS_ENUM.READ_TRANSACTION_LOG,new Y(HB.readTransactionLog)),e.set(q.OPERATIONS_ENUM.DELETE_TRANSACTION_LOGS_BEFORE,new Y(Fn,HB.deleteTransactionLogsBefore)),e.set(q.OPERATIONS_ENUM.INSTALL_NODE_MODULES,new Y(GB.installModules)),e.set(q.OPERATIONS_ENUM.AUDIT_NODE_MODULES,new Y(GB.auditModules)),e.set(q.OPERATIONS_ENUM.GET_BACKUP,new Y(Fs.getBackup)),e}a(tne,"initializeOperationFunctionMap")});var AE=g((wpe,zB)=>{"use strict";var MR=P(),rne=z(),Al=$(),{handleHDBError:PR,hdb_errors:RE}=ne(),{isMainThread:nne}=require("worker_threads"),{Readable:sne}=require("stream"),WB=require("os"),ine=require("util"),one=cT(),ane=ine.promisify(one.authorize),QB=KB(),{createGzip:cne,constants:une}=require("zlib");function lne(e){let t=`Found an uncaught exception with message: ${e.message}. ${WB.EOL}Stack: ${e.stack} ${WB.EOL}Terminating ${nne?"HDB":"thread"}.`;console.error(t),Al.fatal(t),process.exit(1)}a(lne,"handleServerUncaughtException");function _ne(e,t,r){if(Al[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:RE.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(_ne,"serverErrorHandler");function dne(e,t,r){if(!e.body||Object.keys(e.body).length===0||typeof e.body!="object"){let n=PR(new Error,"Invalid JSON.",RE.HTTP_STATUS_CODES.BAD_REQUEST);r(n,null)}if(rne.isEmpty(e.body.operation)){let n=PR(new Error,"Request body must include an 'operation' property.",RE.HTTP_STATUS_CODES.BAD_REQUEST);r(n,null)}r()}a(dne,"reqBodyValidationHandler");function fne(e,t,r){let n;e.body.operation!==MR.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS&&e.body.operation!==MR.OPERATIONS_ENUM.LOGIN&&e.body.operation!==MR.OPERATIONS_ENUM.LOGOUT?ane(e,t).then(s=>{n=s,e.body.hdb_user=n,e.body.hdb_auth_header=e.headers.authorization,r()}).catch(s=>{Al.warn(s),Al.warn(`{"ip":"${e.socket.remoteAddress}", "error":"${s.stack}"`);let i=typeof s=="string"?{error:s}:{error:s.message};r(PR(s,i,RE.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(fne,"authHandler");async function Ene(e,t,r=!1){let n;try{r&&(e.body.operation!=="configure_cluster"||e.body.operation!=="set_configuration")&&(e.body.bypass_auth=r),n=QB.chooseOperation(e.body);let s=await QB.processLocalTransaction(e,n);if(s instanceof sne&&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(cne({level:une.Z_BEST_SPEED})))}return s}catch(s){throw Al.error(s),s}}a(Ene,"handlePostRequest");zB.exports={authHandler:fne,handlePostRequest:Ene,handleServerUncaughtException:lne,serverErrorHandler:_ne,reqBodyValidationHandler:dne}});var ZB=g((Dpe,XB)=>{"use strict";var hne=require("fastify-plugin"),{handlePostRequest:JB,authHandler:mne,reqBodyValidationHandler:pne}=AE();async function Sne(e){e.decorate("hdbCore",{preValidation:[pne,mne],request:t=>jB(JB(t,response)),requestWithoutAuthentication:(t,r)=>jB(JB(t,r,!0))})}a(Sne,"hdbCore");async function jB(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(jB,"convertAsyncIterators");XB.exports=hne(Sne)});var rx=g((Ppe,tx)=>{"use strict";var Mpe=require("fs"),UR=Z();UR.initSync();var{CONFIG_PARAMS:ex}=P(),Tne=1024*1024*1024;function gne(e){let t=UR.get(ex.HTTP_TIMEOUT),r=UR.get(ex.HTTP_KEEPALIVETIMEOUT);return{bodyLimit:Tne,connectionTimeout:t,keepAliveTimeout:r,return503OnClosing:!1,forceCloseConnections:!0,ignoreTrailingSlash:!0,https:e}}a(gne,"getServerOptions");tx.exports=gne});var ix=g((vpe,sx)=>{"use strict";var vR=Z();vR.initSync();var{CONFIG_PARAMS:nx}=P();function Rne(){let e=vR.get(nx.HTTP_CORSACCESSLIST),t=vR.get(nx.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(Rne,"getCORSOptions");sx.exports=Rne});var cx=g((xpe,ax)=>{"use strict";var ox=Z();ox.initSync();var Ane=P();function One(){return ox.get(Ane.CONFIG_PARAMS.HTTP_HEADERSTIMEOUT)??6e4}a(One,"getHeaderTimeoutConfig");ax.exports=One});var xR={};Fe(xR,{customFunctionsServer:()=>Nne,ready:()=>Ox,start:()=>yne});function yne(e){let t=e.securePort>0;return{async handleFile(r,n,s,i){ks||(ks=Ax(t),at.http((await ks).server));let o=await ks,c=(0,BR.dirname)(s),u=(0,BR.dirname)(n);if(u.startsWith("/")&&(u=u.slice(1)),!ux.has(c)){ux.add(c);try{o.register(wne(c,u))}catch(_){if(_.message==="Root plugin has already booted")Ye.warn(`Could not load root fastify route for ${s}, this may require a restart to install properly`);else throw _}}},ready:Ox}}async function Nne(){try{Ye.info("In Custom Functions Fastify server"+process.cwd()),Ye.info(`Custom Functions Running with NODE_ENV set as: ${process.env.NODE_ENV}`),Ye.debug(`Custom Functions server process ${process.pid} starting up.`),await Ine();let e=hx.get(mx.CONFIG_PARAMS.HTTP_SECUREPORT)>0,t;try{t=ks=await Ax(e)}catch(r){throw Ye.error(`Custom Functions buildServer error: ${r}`),r}try{await t.ready()}catch(r){throw Ye.error(`Custom Functions server.ready() error: ${r}`),r}t.server.cantCleanupProperly=!0}catch(e){Ye.error(`Custom Functions ${process.pid} Error: ${e}`),Ye.error(e),process.exit(1)}}async function Ine(){try{Ye.info("Custom Functions starting configuration."),await px.setUsersToGlobal(),Ye.info("Custom Functions completed configuration.")}catch(e){Ye.error(e)}}function wne(e,t){return async function(r){try{Ye.info("Custom Functions starting buildRoutes"),Ye.trace("Loading fastify routes folder "+e),(0,lx.existsSync)(e)&&r.register(Ex.default,s=>({dir:e,dirNameRoutePrefix:!1,options:{hdbCore:s.hdbCore,logger:Ye.loggerWithTag("custom-function"),prefix:`/${t}`}})).after((s,i,o)=>{s?.message?Ye.error(s.message):s&&Ye.error(s),o()})}catch(n){Ye.error(`Custom Functions errored buildRoutes: ${n}`)}}}async function Ax(e){Ye.info("Custom Functions starting buildServer.");let t=(0,Sx.default)(e),r=(0,_x.default)(t);r.server.headersTimeout=(0,gx.default)(),r.setErrorHandler(Rx.serverErrorHandler);let n=(0,Tx.default)();return n&&r.register(dx.default,n),r.register(function(s,i,o){s.setNotFoundHandler(function(c,u){r.server.emit("unhandled",c.raw,u.raw)}),o()}),r.register(fx.default),await r.register(bne),await r.after(),$g(r),Ye.info("Custom Functions completed buildServer."),r}function Ox(){if(ks)return ks.then?ks.then(e=>e.ready()):ks.ready()}var BR,lx,_x,dx,fx,Ex,hx,mx,Ye,bne,px,Sx,Tx,gx,Rx,ks,ux,bx=Re(()=>{BR=require("path"),lx=require("fs"),_x=B(require("fastify")),dx=B(require("@fastify/cors")),fx=B(nR()),Ex=B(require("@fastify/autoload")),hx=B(Z()),mx=B(P()),Ye=B($()),bne=B(ZB()),px=B(ln()),Sx=B(rx()),Tx=B(ix()),gx=B(cx()),Rx=B(AE());Ca();lr();ux=new Set;a(yne,"start");a(Nne,"customFunctionsServer");a(Ine,"setUp");a(wne,"buildRouteFolder");a(Ax,"buildServer");a(Ox,"ready")});var HR={};Fe(HR,{start:()=>Cne});function Cne(e){return{handleDirectory(t,r){if(t==="/"){let n=(0,Cx.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){Nx||(Nx=!0,e.server.http(async(s,i)=>{if(!s.isWebSocket){let o=yx.get(s.pathname);if(o)return{handlesHeaders:!0,body:(0,Ix.default)(s,(0,wx.realpathSync)(o))}}return i(s)},{runFirst:!0})),yx.set(r,n)}}}var Ix,wx,Cx,yx,Nx,Dx=Re(()=>{Ix=B(require("send")),wx=require("fs"),Cx=B(require("serve-static")),yx=new Map;a(Cne,"start")});function Mne(e,t=1,r){if(GR++,(0,Co.startWorker)("server/threads/threadServer.js",{name:yE.THREAD_TYPES.HTTP,workerIndex:e,threadCount:t,async onStarted(n){let s=new Promise((o,c)=>{function u(_){_.type===yE.CLUSTER_MESSAGE_TYPE_ENUM.CHILD_STARTED&&(n.removeListener("message",u),o(n))}a(u,"onMessage"),n.on("message",u),n.on("error",c)});Lne.push(s),await s,Ya.push(n),n.expectedIdle=1,n.lastIdle=0,n.requests=1,n.on("message",o=>{if(o.requestId){let c=bE.get(o.requestId);c&&c(o)}}),n.on("exit",i),n.on("shutdown",i);function i(){let o=Ya.indexOf(n);o>-1&&Ya.splice(o,1)}if(a(i,"removeWorker"),Ka){let o=Ka;Ka=[];for(let c of o)Ux[c.localPort](null,c)}}}),r){let n=setInterval(()=>{qR?qR=!1:(clearInterval(n),console.log("shut down dynamic thread due to inactivity"),(0,Co.shutdownWorkers)(),GR=0,setTimeout(()=>{global.gc?.()},5e3))},1e4)}}function vx(e=0,t){if(typeof e=="string")try{(0,NE.existsSync)(e)&&(0,NE.unlinkSync)(e)}catch{}let r;t?t==="ip"?r=Pne:r=Une(t):r=kR;let n=(0,Wa.createServer)({allowHalfOpen:!0,pauseOnConnect:!r.readsData}).listen(e);if(n._handle){n._handle.onconnection=Ux[e]=function(i,o){r.readsData||(o.reading=!1,o.readStop()),qR=!0,r(o,(c,u)=>{if(!c){if(Lx){let l=o._socket||new Wa.Socket({handle:o,writable:!0,readable:!0});Lx.deliverSocket(l,e,u),l.resume()}else GR>0?(Ka.length===0&&setTimeout(()=>{Ka.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,Ka.push(o)):(console.log("start up a dynamic thread to handle request"),Mne(0));Sr(!1,"socket-routed");return}c.requests++;let _=o.fd;if(_>=0)c.postMessage({port:e,fd:_,data:u});else{let l=o._socket||new Wa.Socket({handle:o,writable:!0,readable:!0});Hne(l,c,e)}Sr(!0,"socket-routed")})};let s=cu();FR.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 kR(e,t){let r,n=0;for(let s of Ya){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 Pne(e,t){let r={};e.getpeername(r);let n=r.address,s=Qa.get(n),i=Date.now();if(s&&s.worker.threadId!==-1)return s.lastUsed=i,t(s.worker);kR(e,o=>{Qa.set(n,{worker:o,lastUsed:i}),t(o)})}function Une(e){let t=new RegExp(`${e}:\\s*(.+)`,"i");return r.readsData=!0,r;function r(n,s){let i=new Wa.Socket({handle:n,readable:!0,writable:!0});n._socket=i,i.on("data",o=>{n.readStop();let u=o.toString("latin1").match(t)?.[1],_=Qa.get(u),l=Date.now();if(_&&_.worker.threadId!==-1)return _.lastUsed=l,s(_.worker);kR(n,d=>{Qa.set(u,{worker:d,lastUsed:l}),s(d,o)})})}a(r,"findByHeaderAffinity")}function Bne(){OE=0;for(let e of Ya)e.expectedIdle=e.recentELU.idle+vne,e.requests=1;Ya.sort((e,t)=>e.expectedIdle>t.expectedIdle?-1:1)}function Hne(e,t,r){let n=xne++;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(),bE.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")),bE.delete(n)),s.event=="destroy"&&(e.destroy(),bE.delete(n))})}var Co,Wa,yE,FR,NE,Px,Dne,Ya,Ka,Ux,Lx,GR,Lne,qR,OE,Mx,Qa,vne,bE,xne,Bx=Re(()=>{Co=B(We()),Wa=require("net"),yE=B(P()),FR=B($()),NE=require("fs");Cs();Px=require("worker_threads"),Dne=B(Ji()),Ya=[],Ka=[],Ux=[],GR=0,Lne=[];Px.isMainThread&&process.on("uncaughtException",e=>{e.code!=="ECONNRESET"&&e.message!=="write EIO"&&console.error("uncaughtException",e)});a(Mne,"startHTTPWorker");a(vx,"startSocketServer");OE=0;a(kR,"findMostIdleWorker");Mx=36e5,Qa=new Map;a(Pne,"findByRemoteAddressAffinity");a(Une,"makeFindByHeaderAffinity");setInterval(()=>{let e=Date.now();for(let[t,r]of Qa)r.lastUsed+Mx<e&&Qa.delete(t)},Mx).unref();vne=1e3;a(Bne,"updateWorkerIdleness");(0,Co.setMonitorListener)(Bne);bE=new Map,xne=1;a(Hne,"proxySocket")});var KR={};Fe(KR,{Request:()=>VR,createReuseportFd:()=>IE});var xx,VR,$R,YR,IE,wE=Re(()=>{xx=require("os"),VR=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 YR(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 $R(this._nodeRequest))}get host(){return this._nodeRequest.authority||this._nodeRequest.headers.host}get isAborted(){return!1}},$R=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)}},YR=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,xx.platform)()!="win32"&&(IE=require("node-unix-socket").createReuseportFd)});var Fx=g((Xpe,qx)=>{"use strict";var Gne=require("cluster"),Do=Z();Do.initSync();var Gx=P(),Wpe=require("util"),Vs=$(),Qpe=require("fs"),qne=require("fastify"),zpe=cu(),Fne=require("@fastify/cors"),kne=require("@fastify/compress"),Vne=require("@fastify/static"),$ne=nR(),Yne=require("path"),{PACKAGE_ROOT:Kne}=P(),Wne=bs(),Qne=z(),zne=ln(),Jne=Ji(),{server:jne}=(lr(),ie(xi)),{node_request_key:Jpe}=(wE(),ie(KR)),{authHandler:Xne,handlePostRequest:Zne,serverErrorHandler:ese,reqBodyValidationHandler:tse}=AE(),jpe=require("net"),{registerContentHandlers:rse}=(Ca(),ie(T0)),nse=6e4,sse=1024*1024*1024,ise="TRUE",{CONFIG_PARAMS:Ol}=Gx,za;qx.exports={hdbServer:Hx,start:Hx};async function Hx(e){try{Vs.info("In Fastify server"+process.cwd()),Vs.info(`Running with NODE_ENV set as: ${process.env.NODE_ENV}`),Vs.debug(`HarperDB server process ${process.pid} starting up.`),global.clustering_on=!1,global.isMaster=Gne.isMaster,await ose();let t=e.securePort>0;za=ase(t),await za.ready(),e||(e={}),e.isOperationsServer=!0;try{jne.http(za.server,e),za.server.closeIdleConnections||await za.listen({port:0,host:"::"})}catch(r){throw za.close(),Vs.error(r),Vs.error("Error configuring operations server"),r}}catch(t){console.error(`Failed to build server on ${process.pid}`,t),Vs.fatal(t),process.exit(1)}}a(Hx,"operationsServer");async function ose(){Vs.trace("Configuring HarperDB process."),Wne.setSchemaDataToGlobal(),await zne.setUsersToGlobal(),await Jne.getLicense()}a(ose,"setUp");function ase(e){Vs.debug(`HarperDB process starting to build ${e?"HTTPS":"HTTP"} server.`);let t=cse(e),r=qne(t);r.server.headersTimeout=lse(),r.setErrorHandler(ese);let n=use();n&&r.register(Fne,n),r.register(function(i,o,c){i.setNotFoundHandler(function(u,_){r.server.emit("unhandled",u.raw,_.raw)}),c()}),r.register($ne),r.register(kne),r.register(Vne,{root:Yne.join(Kne,"studio/build-local")}),rse(r);let s=Do.get(Gx.HDB_SETTINGS_NAMES.LOCAL_STUDIO_ON);return r.get("/",function(i,o){return!Qne.isEmpty(s)&&s.toString().toLowerCase()==="true"?o.sendFile("index.html"):o.sendFile("running.html")}),r.post("/",{preValidation:[tse,Xne],config:{isOperation:!0}},async function(i,o){return i.body?.operation?.startsWith("restart")&&o.header("Connection","close"),Zne(i,o)}),r.get("/health",()=>"HarperDB is running."),Vs.debug(`HarperDB process starting up ${e?"HTTPS":"HTTP"} server listener.`),r}a(ase,"buildServer");function cse(e){let t=Do.get(Ol.OPERATIONSAPI_NETWORK_TIMEOUT),r=Do.get(Ol.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT);return{bodyLimit:sse,connectionTimeout:t,keepAliveTimeout:r,forceCloseConnections:!0,return503OnClosing:!1,https:e}}a(cse,"getServerOptions");function use(){let e=Do.get(Ol.OPERATIONSAPI_NETWORK_CORS),t=Do.get(Ol.OPERATIONSAPI_NETWORK_CORSACCESSLIST),r;return e&&(e===!0||e.toUpperCase()===ise)&&(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(use,"getCORSOpts");function lse(){return Do.get(Ol.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT)??nse}a(lse,"getHeaderTimeoutConfig")});var XR={};Fe(XR,{disableNATS:()=>dse,publishToStream:()=>LE,setNATSReplicator:()=>WR,setPublishToStream:()=>fse,setSubscription:()=>jR,start:()=>_se});function _se(){bl.default.get(yl.default.CONFIG_PARAMS.CLUSTERING_ENABLED)&&hse()}function dse(e=!0){Kx=e}function fse(e,t){LE=e,jR=t}function hse(){if(Kx||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];WR(s,r,i)}}ZR((r,n)=>{WR(r.tableName,r.databaseName,r),n&&Qx(r)}),!kx&&(kx=!0)}function WR(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){Qx(i)}static subscribe(){let i=new yn;return jR(t,e,i),i}static subscribeOnThisThread(i){return i<(bl.default.get(yl.default.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXINGESTTHREADS)??Ese)}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 CE(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=Wx;return i}a(n,"getNATSTransaction")}function Qx(e){let t=bl.default.get(yl.default.CONFIG_PARAMS.CLUSTERING_NODENAME);LE(`${zR.SUBJECT_PREFIXES.TXN}.${e.databaseName}.${e.tableName}`,(0,JR.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 Vx,zR,JR,$x,Yx,bl,yl,DE,Kx,LE,jR,Ese,Wx,kx,CE,QR,zx=Re(()=>{Ae();Nn();Vx=B(ut()),zR=B(Ve()),JR=B(As());bc();$x=B(wS()),Yx=B(vr()),bl=B(Z()),yl=B(P()),DE=B($());a(_se,"start");a(dse,"disableNATS");LE=Vx.publishToStream,jR=$x.setSubscription;a(fse,"setPublishToStream");Ese=2;a(hse,"assignReplicationSource");a(WR,"setNATSReplicator");a(Qx,"publishSchema");CE=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=bl.default.get(yl.default.CONFIG_PARAMS.CLUSTERING_NODENAME),n=[];for(let[s,i]of this.writes_by_db){let o=[],c=[],u,_;for(let l of i){let d=l.table,E=l.operation=="put"?"upsert":l.operation;u||(DE.trace(`Sending transaction event ${E}`),_=u={operation:E,schema:s,table:d,__origin:{user:this.user?.username,timestamp:t,node_name:r}},u.hash_values=c,E!=="delete"&&E!=="invalidate"&&(u.records=o)),u.table===d&&u.operation===E?(o.push(l.record),c.push(l.id)):_=_.next={operation:E,table:d,id:l.id,record:l.record},l.expiresAt&&(_.expiresAt=l.expiresAt)}u&&n.push(LE(`${zR.SUBJECT_PREFIXES.TXN}.${s}.${u.table}`,(0,JR.createNatsTableStreamName)(s,u.table),void 0,u)?.catch(l=>{throw DE.error("An error has occurred trying to replicate transaction",u,l),l.statusCode=504,l}))}return Promise.all(n)}},QR=class extends CE{static{a(this,"ImmmediateNATSTransaction")}constructor(){super({get timestamp(){return(0,Yx.getNextMonotonicTime)()}})}addWrite(t,r){super.addWrite(t,r),this.commit({})}};Wx=new QR});var uH=g(Di=>{"use strict";var{isMainThread:rA,parentPort:Il,threadId:ME}=require("worker_threads"),{Socket:mse,createServer:pse}=require("net"),{createServer:Sse,IncomingMessage:Tse}=require("http"),{createServer:gse}=require("https"),{readFileSync:Rse,unlinkSync:Jx,existsSync:Ase}=require("fs"),Pt=$(),He=Z(),_t=P(),{server:vE}=(lr(),ie(xi)),{WebSocketServer:Ose}=require("ws"),{createSecureContext:bse,createServer:yse}=require("node:tls"),{getTicketKeys:eH,restartNumber:Nse,getWorkerIndex:wl}=We(),{Headers:tH,appendHeader:Ise}=(Ju(),ie(VU)),{recordAction:Nl,recordActionBinary:wse}=(Cs(),ie(fu)),{Request:rH,createReuseportFd:jx}=(wE(),ie(KR)),{checkMemoryLimit:Cse}=Ji(),{X509Certificate:Dse}=require("crypto"),nH=require("tls"),Lse=nH.createSecureContext,Ja;nH.createSecureContext=function(e){return Ja||Lse(e)};var sH=He.get(_t.CONFIG_PARAMS.THREADS_DEBUG);if(sH){let e;if(rA)e=He.get(_t.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=He.get(_t.CONFIG_PARAMS.THREADS_DEBUG_STARTINGPORT);t&&wl()>=0&&(e=t+wl())}if(e){let t=He.get(_t.CONFIG_PARAMS.THREADS_DEBUG_HOST),r=He.get(_t.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&&rA)try{require("inspector").open(9229)}catch(e){Nse<=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:iSe,CONFIG_PARAMS:Mse}=_t;He.initSync();var Pse=He.get(Mse.HTTP_SESSIONAFFINITY),Es={};Di.registerServer=oA;Di.httpServer=aA;Di.deliverSocket=iA;Di.startServers=iH;Di.when_components_loaded=null;Di.createSNICallback=cA;vE.http=aA;vE.request=xse;vE.socket=Hse;vE.ws=Gse;var eA={},PE={},Use,$s={},UE={},vse=[],nA=[];function iH(){return Di.when_components_loaded=uA().loadRootComponents(!0).then(()=>{Il?.on("message",t=>{let{port:r,fd:n,data:s}=t;if(n)iA(n,r,s);else if(t.requestId)Bse(t);else if(t.type===_t.ITC_EVENT_TYPES.SHUTDOWN){Pt.trace("received shutdown request",ME);for(let i in Es){let o=Es[i],c;if(o.closeIdleConnections){let _=Object.getOwnPropertySymbols(o).find(E=>E.description.includes("connections")),l=0,d=setInterval(()=>{l++;let E=l>=100,f=o[_][E?"all":"idle"]();if(f.length===0){E&&clearInterval(d);return}l===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
|
|
29
29
|
Connection: close\r
|
|
30
30
|
\r
|
|
31
|
-
`))}},25).unref()}o.close?.(()=>{if(He.get(
|
|
32
|
-
`)}a(zH,"defaultNotFound");function eA(e){return e.startsWith("-----BEGIN")?e:pse(e)}a(eA,"readPEM");function aA(e){let t=[];for(let i=0;e[i];i++)t.push(e[i]);t.length||t.push(e);let r=new Map,n,s=!1;for(let i of t){let o=eA(i.privateKey),c=eA(i.certificate),u=i.certificateAuthority&&eA(i.certificateAuthority);if(!o||!c)throw new Error("Missing private key or certificate for secure server");let _={ciphers:i.ciphers,ca:u,ticketKeys:JH()},l=gse(_);l.options=_,_.instantiatedContext=l,l.context.setCert(c),l.context.setKey(o,void 0),_.cert=c,_.key=o,l.certStart=c.slice(0,100).toString(),n||(n=l);let d=new Nse(c),E=i.hostname??i.host??i.hostnames??i.hosts??(d.subjectAltName?d.subjectAltName.split(",").map(f=>{let h=f.indexOf(":");return f.slice(h+1)}):[d.subject.match(/CN=(.*)/)?.[1]]);Array.isArray(E)||(E=[E]);for(let f of E)f?(f[0]==="*"&&(s=!0,f=f.slice(1)),r.has(f)||r.set(f,l)):Lt.error("No hostname found for certificate at",i.certificate)}return(i,o)=>{let c=i;for(;;){let u=r.get(c);if(u)return Lt.debug("Found certificate for",i,u.certStart),o(null,u);if(s&&c){let _=c.indexOf(".",1);_<0?c="":c=c.slice(_)}else break}Lt.debug("No certificate found to match",i,"using the first certificate"),o(null,n)}}a(aA,"createSNICallback")});async function ux({clientId:e,user:t,clean:r,will:n,keepalive:s}){let i;if(e&&!r){let o=await uA.get(e,{returnNonexistent:!0});i=new dA(e,t,o),o&&(i.sessionWasPresent=!0)}else{if(e){let o=await uA.get(e);o&&o.delete()}i=new BE(e,t)}return n&&(n.id=e,n.user={username:t?.username},Nl.put(n)),s&&(i.keepalive=s,i.receivedPacket()),i}function lA(){return vE++,vE>65500&&(vE=1),vE}function _A(e,t,r){let{topic:n,retain:s}=e;e.data=t,e.async=!0,r.authorize=!0;let i=Oi.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 Xe(r,()=>s?t===void 0?o.delete(e,r):o.put(e,e.data,r):o.publish(e,e.data,r))}var ox,Li,ax,cx,uA,Nl,vE,BE,dA,lx=Ae(()=>{Oe();Wu();ox=B(vr()),Li=B($());ro();ax=B(Je()),cx=B(ix());ur();uA=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"}]}}]}),Nl=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,ax.getWorkerIndex)()===0&&(async()=>{await cx.when_components_loaded,await new Promise(e=>setTimeout(e,2e3));for await(let e of Nl.search({})){let t=e.data,r=Object.assign({},e);r.user?.username&&(r.user=await st.getUser(r.user.username)),Xe(r,()=>{try{_A(r,t,r)}catch{(0,Li.warn)("Failed to publish will",t)}Nl.delete(e.id,r)})}})();a(ux,"getSession");vE=1;a(lA,"getNextMessageId");BE=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("?"),u,_;if(c>-1?(u=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 l=this.subscriptions.find(T=>T.topic===s),d;l?(d=i>0,l.end(),this.subscriptions.splice(this.subscriptions.indexOf(l),1)):d=i===2;let E={search:u,async:!0,user:this.user,startTime:o,omitCurrent:d,url:""};o&&(0,Li.trace)("Resuming subscription from",s,"from",o);let f=Oi.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 A=T.split("/"),R;for(let v=0;v<A.length;v++)if(A[v].indexOf("+")>-1)if(A[v]==="+")R=!0;else throw new Error("Single-level wildcards can only be used as a topic level (between or after slashes)");if(n&&R)throw new Error("Filters can not be combined");let C=!0;A[A.length-1]==="#"&&(A.length--,C=!1),R&&(n=a(v=>{let k=v.id;if(!Array.isArray(k)||C&&k.length!==A.length)return!1;for(let M=0;M<A.length;M++)if(A[M]!=="+"&&A[M]!==k[M])return!1;return!0},"filter"));let x=A.indexOf("+");E.url="/"+(x>-1?A.slice(0,x):A).concat("").join("/")}}let h=f.path,p=f.Resource,S=await Xe(E,async()=>{let T=this.createContext();T.topic=s,T.retainHandling=i;let A=await p.subscribe(E,T);if(!A)throw new Error(`No subscription was returned from subscribe for topic ${s}`);if(!A[Symbol.asyncIterator])throw new Error(`Subscription is not (async) iterable for topic ${s}`);return(async()=>{for await(let R of A)try{let C;if(R.type&&R.type!=="put"&&R.type!=="delete"&&R.type!=="message"&&R.type!=="patch"||n&&!n(R))continue;r?(R.topic=s,C=this.needsAcknowledge(R)):(R.acknowledge?.(),C=lA());let x=R.id;Array.isArray(x)&&(x=Na(x)),x==null&&(x=""),this.listener(h+"/"+x,R.value,C,t)}catch(C){(0,Li.warn)(C)}})(),A});return S.topic=s,S.qos=t.qos,this.subscriptions.push(S),S}resume(){}needsAcknowledge(t){let r=lA();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 _A(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();Xe(r,async()=>{try{if(!t){let n=await Nl.get(this.sessionId);n?.doesExist()&&await _A(n,n.data,r)}}finally{await Nl.delete(this.sessionId)}}).catch(n=>{(0,Li.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(_A,"publish");dA=class extends BE{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=lA(),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,Li.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,ox.getNextMonotonicTime)()),(0,Li.trace)("Added durable subscription",t.topic,r),{qos:t.qos,topic:t.topic,startTime:r}}),uA.put(this.sessionRecord)}}});var EA={};qe(EA,{bypassAuth:()=>Bse,start:()=>Hse});function Bse(){hx=!0}function Hse({server:e,port:t,network:r,webSocket:n,securePort:s,requireAuthentication:i}){e.mqtt||(e.mqtt={requireAuthentication:i,sessions:new Set,events:new Ex.EventEmitter},e.mqtt.events.on("error",()=>{}));let o=e.mqtt,c,u=r?.mtls;return n&&(c=e.ws((_,l,d)=>{if(_.protocol==="mqtt"){o.events.emit("connection",_),ir.debug("Received WebSocket connection for MQTT from",_._socket.remoteAddress);let{onMessage:E,onClose:f}=dx(_,(h,p)=>{if(_.send(h),p&&_._socket.writableNeedDrain)return new Promise(S=>this._socket.once("drain",S))},l,Promise.resolve(d).then(()=>l?.user),o);_.on("message",E),_.on("close",f),_.on("error",h=>{ir.info("WebSocket error",h)})}},Object.assign({subProtocol:"mqtt"},n))),(t||s)&&(c=e.socket(async _=>{let l;if(o.events.emit("connection",_),ir.debug(`Received ${_.getCertificate?"SSL":"TCP"} connection for MQTT from ${_.remoteAddress}`),u){if(_.authorized)try{let f=u.user;if(f!==null){(f===void 0||f==="Common Name"||f==="CN")&&(f=_.getPeerCertificate().subject.CN);try{l=await e.getUser(f,null,null),(0,Ja.get)(Jt.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)&&xE.notify({username:l?.username,status:Jt.AUTH_AUDIT_STATUS.SUCCESS,type:Jt.AUTH_AUDIT_TYPES.AUTHENTICATION,auth_strategy:"MQTT mTLS",remote_address:_.remoteAddress})}catch(h){throw(0,Ja.get)(Jt.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGFAILED)&&xE.error({username:f,status:Jt.AUTH_AUDIT_STATUS.FAILURE,type:Jt.AUTH_AUDIT_TYPES.AUTHENTICATION,auth_strategy:"mqtt",remote_address:_.remoteAddress}),h}}else ir.debug("MQTT mTLS authorized connection (mTLS did not authorize a user)","from",_.remoteAddress)}catch(f){o.events.emit("error",f,_),ir.error(f)}else if(u.required)return ir.info(`Unauthorized connection attempt, no authorized client certificate provided, error: ${_.authorizationError}`),_.end()}!l&&hx&&_.remoteAddress.includes("127.0.0.1")&&(l=await(0,fx.getSuperUser)(),ir.debug("Auto-authorizing local connection",l?.username));let{onMessage:d,onClose:E}=dx(_,f=>_.write(f),null,l,o);_.on("data",d),_.on("close",E),_.on("error",f=>{ir.info("Socket error",f)})},{port:t,securePort:s,mtls:u})),c}function dx(e,t,r,n,s){_x||(_x=!0,_u(d=>{HE>0&&d.push({metric:"mqtt-connections",connections:HE,byThread:!0})}));let i;HE++;let o,c={protocolVersion:4},u=(0,GE.parser)({protocolVersion:5});function _(d){u.parse(d)}a(_,"onMessage");function l(){HE--,i||(i=!0,o?.disconnect?.(),s.events.emit("disconnected",o,e),s.sessions.delete(o),Wr(!1,"connection","mqtt","disconnect"),ir.debug("MQTT connection was closed",e.remoteAddress))}return a(l,"onClose"),u.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;pr(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,Ja.get)(Jt.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)&&xE.notify({username:n?.username,status:Jt.AUTH_AUDIT_STATUS.SUCCESS,type:Jt.AUTH_AUDIT_TYPES.AUTHENTICATION,auth_strategy:"MQTT",remote_address:e.remoteAddress})}catch(M){return(0,Ja.get)(Jt.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGFAILED)&&xE.error({username:d.username,status:Jt.AUTH_AUDIT_STATUS.FAILURE,type:Jt.AUTH_AUDIT_TYPES.AUTHENTICATION,auth_strategy:"mqtt",remote_address:e.remoteAddress}),s.events.emit("auth-failed",d,e,M),Wr(!1,"connection","mqtt","connect"),p({cmd:"connack",reasonCode:4,returnCode:134})}if(!n&&s.requireAuthentication)return s.events.emit("auth-failed",d,e),Wr(!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=Oo(r?.headers.get?.("content-type")));d.will.data=d.will.payload?.length>0?M(d.will.payload):void 0,delete d.will.payload}o=ux({user:n,...d}),o=await o,o.socket=e,r&&(o.request=r),s.sessions.add(o)}catch(M){return ir.error(M),s.events.emit("auth-failed",d,e,M),Wr(!1,"connection","mqtt","connect"),p({cmd:"connack",reasonCode:M.code||5,returnCode:M.code||128})}s.events.emit("connected",o,e),Wr(!0,"connection","mqtt","connect"),p({cmd:"connack",sessionPresent:o.sessionWasPresent,reasonCode:0,returnCode:0}),o.setListener((M,Q,j,z)=>{try{let ae=M.indexOf("/",1),ue=ae>0?M.slice(0,ae):M;p({cmd:"publish",topic:M,payload:T(Q),messageId:j||Math.floor(Math.random()*1e8),qos:z.qos},ue)}catch(ae){ir.error(ae),o?.disconnect(),s.sessions.delete(o)}}),o.sessionWasPresent&&await o.resume();break;case"subscribe":let A=[];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),ir.error(j),Q=c.protocolVersion<5?128:j.statusCode===403?135:j.statusCode===404?143:128}A.push(Q)}await o.committed,p({cmd:"suback",granted:A,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 R=d.qos===2?"pubrec":"puback",C=e.deserialize||(e.deserialize=Oo(r?.headers.get?.("content-type"))),v=(d.payload?.length||0)>0?C(d.payload):void 0,k;try{k=await o.publish(d,v)}catch(M){s.events.emit("error",M,e,d,o),ir.warn(M),d.qos>0&&p({cmd:R,messageId:d.messageId,reasonCode:128},d.topic);break}d.qos>0&&p({cmd:R,messageId:d.messageId,reasonCode:k===!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),Wr(!0,"connection","mqtt","disconnect"),ir.debug("Received disconnect command, closing MQTT session",e.remoteAddress),e.close?e.close():e.end();break}}catch(A){s.events.emit("error",A,e,d,o),ir.error(A),p({cmd:"disconnect"})}function p(A,R){let C=(0,GE.generate)(A,c);t(C),pr(C.length,"bytes-sent",R,S(A),"mqtt")}a(p,"sendPacket");function S(A){return A.qos>0?A.cmd+",qos="+A.qos:A.cmd}a(S,"packetMethodName");function T(A){return To(A,r)}a(T,"serialize")}),{onMessage:_,onClose:l}}var GE,fx,Ja,Jt,fA,Ex,xE,ir,hx,_x,HE,mx=Ae(()=>{GE=require("mqtt-packet");lx();fx=B(ln());wa();ws();ur();Ja=B(Z()),Jt=B(P()),fA=B($()),Ex=require("events"),xE=(0,fA.loggerWithTag)("auth-event"),ir=(0,fA.loggerWithTag)("mqtt"),hx=(0,Ja.get)(Jt.CONFIG_PARAMS.AUTHENTICATION_AUTHORIZELOCAL)??process.env.DEV_MODE;a(Bse,"bypassAuth");a(Hse,"start");HE=0;a(dx,"onSocket")});var Uf={};qe(Uf,{component_errors:()=>Xa,loadComponent:()=>qE,loadComponentDirectories:()=>yx,setErrorReporter:()=>Fse});function yx(e,t){t&&(mA=t),e&&(pA=e);let r=[];if((0,bt.existsSync)(hA)){let s=(0,bt.readdirSync)(hA,{withFileTypes:!0});for(let i of s){if(!i.isDirectory()&&!i.isSymbolicLink())continue;let o=i.name,c=(0,tt.join)(hA,o);r.push(qE(c,mA,"hdb",!1))}}let n=process.env.RUN_HDB_APP;return n&&r.push(qE(n,mA,n,!1,null,process.env.DEV_MODE)),Promise.all(r).then(()=>{bx=!0})}function Fse(e){Il=e}async function qE(e,t,r,n,s,i){if(!Sx.has(e)){Sx.set(e,!0),s&&(pA=s);try{let o;n&&(Xa=new Map);let c=(0,tt.join)(e,n?"harperdb-config.yaml":"config.yaml");(0,bt.existsSync)(c)?o=n?(0,Ox.getConfigObj)():(0,Tx.parseDocument)((0,bt.readFileSync)(c,"utf8"),{simpleKeys:!0}).toJSON():o=SA;let u=(0,tt.join)(e,"node_modules","harperdb");try{Lo.isMainThread&&((0,bt.existsSync)(u)||n)&&((0,bt.rmSync)(u,{recursive:!0,force:!0}),(0,bt.existsSync)((0,tt.join)(e,"node_modules"))||(0,bt.mkdirSync)((0,tt.join)(e,"node_modules")),(0,bt.symlinkSync)(Cl.PACKAGE_ROOT,u,"dir"))}catch(d){ja.default.error("Error symlinking harperdb module",d)}let _=[],l=n;for(let d in o){let E=o[d];if(Xa.set(n?d:(0,tt.basename)(e),!1),!E)continue;let f,h=E.package;try{if(h){let R=e,C;for(;!(0,bt.existsSync)(C=(0,tt.join)(R,"node_modules",d));)if(R=(0,tt.dirname)(R),R.length<(0,Ax.getHdbBasePath)().length){C=null;break}if(C)f=await qE(C,t,r,!1),l=!0;else throw new Error(`Unable to find package ${d}:${h}`)}else f=qse[d];if(!f)continue;_.push(f);let p=a(R=>(R.origin=r,dt(R)),"ensureTable"),S=E.network||(E.port||E.securePort)&&E,T=S?.securePort||S?.https&&S.port,A=!S?.https&&S?.port;if(Lo.isMainThread&&(f=await f.startOnMainThread?.({server:st,ensureTable:p,port:A,securePort:T,resources:t,...E})||f,n&&S))for(let R of[A,T])try{if(+R&&!px.includes(R)){let C=TA.get(Cl.CONFIG_PARAMS.HTTP_SESSIONAFFINITY);C&&ja.default.warn("Session affinity is not recommended and may cause memory leaks"),(C||!NE)&&(px.push(R),LH(R,C))}}catch(C){console.error("Error listening on socket",R,C,d)}if(t.isWorker&&(f=await f.start?.({server:st,ensureTable:p,port:A,securePort:T,resources:t,...E})||f),pA.set(f,!0),(f.handleFile||f.handleDirectory)&&E.files){if(E.files.includes(".."))throw(0,Rx.handleHDBError)("Can not reference parent directories");let R=(0,tt.join)(e,E.files).replace(/\\/g,"/"),C=R.indexOf("/*");if(C>-1&&E.files!==SA[d]?.files&&!(0,bt.existsSync)(R.slice(0,C)))throw new Error(`The path '${R.slice(0,C)}' does not exist and cannot be used as the base of the resolved 'files' path value '${E.files}'`);let x=(0,tt.basename)(e),v=E.path||"/";v=v.startsWith("/")?v:v.startsWith("./")?"/"+x+v.slice(2):v==="."?"/"+x:"/"+x+"/"+v;let k,M,Q;if(E.root){let z=E.root;z.startsWith("/")&&(z=z.slice(1)),z.endsWith("/")&&(z=z.slice(0,-1)),z+="/",M=(0,tt.join)(e,z)}else(Q=R.indexOf("/*"))>-1&&(M=R.slice(0,Q+1),k=(0,tt.relative)(e,M));let j=!1;if(Lo.isMainThread&&f.setupDirectory&&(j=await f.setupDirectory?.(v,M,t)),t.isWorker&&f.handleDirectory&&(j=await f.handleDirectory?.(v,M,t)),j)continue;for(let z of await(0,gx.default)(R,{onlyFiles:!1,objectMode:!0})){let{path:ae,dirent:ue}=z;l=!0;let de=(0,tt.relative)(e,ae).replace(/\\/g,"/");if(k)if(de.startsWith(k))de=de.slice(k.length+1);else throw new Error(`The root path '${E.root}' does not reference a valid part of the file path '${de}'.The root path should be used to indicate the relative path/part of the file path for determining the exported web path.`);let xe=v+(v.endsWith("/")?"":"/")+de;try{if(ue.isFile()){let Ee=await Gse(ae);Lo.isMainThread&&await f.setupFile?.(Ee,xe,ae,t),t.isWorker&&await f.handleFile?.(Ee,xe,ae,t)}else Lo.isMainThread&&await f.setupDirectory?.(xe,ae,t),t.isWorker&&await f.handleDirectory?.(xe,ae,t)}catch(Ee){Ee.message=`Could not load ${ue.isFile()?"file":"directory"} '${ae}'${E.module?" using '"+E.module+"'":""} for application '${e}' due to: ${Ee.message}`,Il?.(Ee),((0,Za.getWorkerIndex)()===0?console:ja.default).error(Ee),t.set(E.path||"/",new wl(Ee)),Xa.set(n?d:(0,tt.basename)(e),Ee.message)}}}}catch(p){p.message=`Could not load component '${d}' for application '${(0,tt.basename)(e)}' due to: ${p.message}`,Il?.(p),((0,Za.getWorkerIndex)()===0?console:ja.default).error(p),t.set(E.path||"/",new wl(p),null,!0),Xa.set(n?d:(0,tt.basename)(e),p.message)}}if(Lo.isMainThread&&!bx&&i&&(0,Za.watchDir)(e,async()=>yx()),o.extensionModule)return await __((0,tt.join)(e,o.extensionModule));if(!l&&t.isWorker){let d=`${e} did not load any modules, resources, or files, is this a valid component?`;Il?.(new Error(d)),((0,Za.getWorkerIndex)()===0?console:ja.default).error(d),Xa.set((0,tt.basename)(e),d)}}catch(o){console.error(`Could not load application directory ${e}`,o),o.message=`Could not load application due to ${o.message}`,Il?.(o),t.set("",new wl(o))}}}var bt,tt,Lo,Tx,TA,Cl,gx,Za,ja,Rx,Ax,xse,Ox,Gse,hA,pA,bx,mA,Xa,qse,SA,px,Sx,Il,wl,vf=Ae(()=>{bt=require("fs"),tt=require("path"),Lo=require("worker_threads"),Tx=require("yaml"),TA=B(Z()),Cl=B(P());Tb();Ob();bb();P0();gH();NH();gx=B(require("fast-glob")),Za=B(Je()),ja=B($());zh();ur();Rx=B(ne());Nn();Oe();MH();Ax=B(Z()),xse=B(HH());Nf();YH();mx();Ox=B(fr());IE();({readFile:Gse}=bt.promises),hA=TA.get(Cl.CONFIG_PARAMS.COMPONENTSROOT),pA=new Map,Xa=new Map;a(yx,"loadComponentDirectories");qse={REST:Zf,rest:Zf,graphqlSchema:Qh,jsResource:jh,fastifyRoutes:BR,login:Zh,static:HR,operationsApi:xse,customFunctions:{},http:{},clustering:jR,authentication:zu,mqtt:EA},SA={rest:!0,graphqlSchema:{files:"*.graphql"},jsResource:{files:"resources.js"},fastifyRoutes:{files:"routes/*.js",path:"."}};Object.defineProperty(SA,"static",{value:{files:"web/**"}});px=[],Sx=new Map;a(Fse,"setErrorReporter");a(qE,"loadComponent");wl=class extends Vt{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 cA=g((OSe,Ix)=>{var{isMainThread:Nx}=require("worker_threads"),{getTables:kse}=(Oe(),ie(Fe)),{loadComponentDirectories:Vse,loadComponent:$se}=(vf(),ie(Uf)),{resetResources:Yse}=(Wu(),ie(kU)),Kse=pg(),Wse=fr(),{dirname:Qse}=require("path"),{getConnection:zse}=ot(),Jse=Z(),jse=P(),gA=new Map;async function Xse(e=!1){!Nx&&Jse.get(jse.CONFIG_PARAMS.CLUSTERING_ENABLED)&&zse();try{Nx&&await Kse()}catch(n){console.error(n)}let t=Yse();kse(),t.isWorker=e,await $se(Qse(Wse.getConfigFilePath()),t,"hdb",!0,gA),await Vse(gA,t);let r=[];for(let[n]of gA)n.ready&&r.push(n.ready());r.length>0&&await Promise.all(r)}a(Xse,"loadRootComponents");Ix.exports.loadRootComponents=Xse});var Je=g((ySe,Pi)=>{"use strict";var{Worker:Zse,MessageChannel:eie,parentPort:Es,isMainThread:yA,threadId:tie,workerData:Ys}=require("worker_threads"),{PACKAGE_ROOT:rie}=P(),{join:Lx,isAbsolute:nie,extname:sie}=require("path"),{server:Mx}=(ur(),ie(Hi)),{watch:iie,readdir:oie}=require("fs/promises"),{totalmem:wx}=require("os"),Dl=P(),Px=Z(),Ks=$(),{randomBytes:aie}=require("crypto"),{_assignPackageExport:cie}=require("../index"),uie=P(),Cx=1024*1024,Mi=[],Tn=[],lie=50,NA=1e4,_ie="restart",Ux="request_thread_info",vx="resource_report",Bx="thread_info",Hx="added-port",die="ack",RA;cie("threads",Tn);Pi.exports={startWorker:AA,restartWorkers:wA,shutdownWorkers:pie,workers:Mi,setMonitorListener:yie,onMessageFromWorkers:Sie,onMessageByType:$x,broadcast:gie,broadcastWithAcknowledgement:Aie,setChildListenerByType:mie,getWorkerIndex:xx,getWorkerCount:Gx,getTicketKeys:Fx,setMainIsWorker:Eie,setTerminateTimeout:fie,restartNumber:Ys?.restartNumber||1};Tn.onMessageByType=$x;Tn.sendToThread=function(e,t){if(!t?.type)throw new Error("A message with a type must be provided");let r=Tn.find(n=>n.threadId===e);if(r)return r.postMessage(t),!0};var IA;function fie(e){NA=e}a(fie,"setTerminateTimeout");function xx(){return Ys?Ys.workerIndex:IA?0:void 0}a(xx,"getWorkerIndex");function Gx(){return Ys?Ys.workerCount:IA?1:void 0}a(Gx,"getWorkerCount");function Eie(e){IA=e}a(Eie,"setMainIsWorker");var qx=1,FE;function Fx(){return FE||(FE=yA?aie(48):Ys.ticketKeys,FE)}a(Fx,"getTicketKeys");Object.defineProperty(Mx,"workerIndex",{get(){return xx()}});Object.defineProperty(Mx,"workerCount",{get(){return Gx()}});var kx={[Ux](e,t){Oie(t)},[vx](e,t){bie(t,e)}};function AA(e,t={}){let r=process.constrainedMemory?.()||wx();r=Math.min(r,wx(),2e4*Cx);let n=Px.get(Dl.CONFIG_PARAMS.THREADS_MAXHEAPMEMORY)??Math.max(Math.floor(r/Cx/(10+(t.threadCount||1)/4)),512),s=Math.min(Math.max(n>>6,16),64),i=[],o=[];for(let u of Tn){let _=new eie;_.existingPort=u,i.push(_),o.push(_.port2)}sie(e)||(e+=".js");let c=new Zse(nie(e)?e:Lx(rie,e),Object.assign({resourceLimits:{maxOldGenerationSizeMb:n,maxYoungGenerationSizeMb:s},execArgv:["--enable-source-maps"],argv:process.argv.slice(2),workerData:{addPorts:o,addThreadIds:i.map(u=>u.existingPort.threadId),workerIndex:t.workerIndex,workerCount:qx=t.threadCount,name:t.name,restartNumber:Pi.exports.restartNumber,ticketKeys:Fx()},transferList:o},t));for(let{port1:u,existingPort:_}of i)_.postMessage({type:Hx,port:u,threadId:c.threadId},[u]);return VE(c,!0),c.unexpectedRestarts=t.unexpectedRestarts||0,c.startCopy=()=>AA(e,t),c.on("error",u=>{Ks.error(`Worker index ${t.workerIndex} error:`,u)}),c.on("exit",u=>{Mi.splice(Mi.indexOf(c),1),!c.wasShutdown&&t.autoRestart!==!1&&(c.unexpectedRestarts<lie?(t.unexpectedRestarts=c.unexpectedRestarts+1,AA(e,t)):Ks.error(`Thread has been restarted ${c.restarts} times and will not be restarted`))}),c.on("message",u=>{kx[u.type]?.(u,c)}),Mi.push(c),Iie(),t.onStarted&&t.onStarted(c),c.name=t.name,c}a(AA,"startWorker");var hie=[Dl.THREAD_TYPES.HTTP];async function wA(e=null,t=Math.max(qx>3,1),r=!0){if(yA){if(r){let{loadRootComponents:o}=cA();await o()}Pi.exports.restartNumber++,t<1&&(t=t*Mi.length);let n=[],s=[];for(let o of Mi.slice(0)){if(e&&o.name!==e||o.wasShutdown)continue;Ks.trace("sending shutdown request to ",o.threadId),o.postMessage({restartNumber:Pi.exports.restartNumber,type:Dl.ITC_EVENT_TYPES.SHUTDOWN}),o.wasShutdown=!0,o.emit("shutdown",{});let c=hie.indexOf(o.name)>-1,u=new Promise(_=>{let l=setTimeout(()=>o.terminate(),NA*2).unref();o.on("exit",()=>{clearTimeout(l),n.splice(n.indexOf(u)),!c&&r&&o.startCopy(),_()})});if(n.push(u),c&&r){let _=o.startCopy(),l=new Promise(d=>{let E=a(f=>{f.type===uie.ITC_EVENT_TYPES.CHILD_STARTED&&(Ks.trace("Worker has started",_.threadId),d(),s.splice(s.indexOf(l)),_.off("message",E))},"startListener");Ks.trace("Waiting for worker to start",_.threadId),_.on("message",E)});s.push(l),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}=Af();r&&(e==="http"||!e)&&Px.get(Dl.CONFIG_PARAMS.CLUSTERING_ENABLED)&&await i({service:"clustering"})}else Es.postMessage({type:_ie,workerType:e})}a(wA,"restartWorkers");function mie(e,t){kx[e]=t}a(mie,"setChildListenerByType");function pie(e){return wA(e,1/0,!1)}a(pie,"shutdownWorkers");var Vx=[];function Sie(e){Vx.push(e)}a(Sie,"onMessageFromWorkers");var OA=new Map;function $x(e,t){let r=OA.get(e);r||OA.set(e,r=[]),r.push(t)}a($x,"onMessageByType");var Tie=10;async function gie(e){let t=0;for(let r of Tn)try{r.postMessage(e),t++>Tie&&(t=0,await new Promise(setImmediate))}catch(n){Ks.error("Unable to send message to worker",n)}}a(gie,"broadcast");var kE=new Map,Rie=1;function Aie(e){return new Promise(t=>{let r=0;for(let n of Tn)try{let s=Rie++,i=a(()=>{kE.delete(s),--r===0&&t(),n!==Es&&--n.refCount===0&&n.unref()},"ack_handler");i.port=n,n.ref(),n.refCount=(n.refCount||0)+1,kE.set(e.requestId=s,i),n.hasAckCloseListener||(n.hasAckCloseListener=!0,n.on(n.close?"close":"exit",()=>{for(let[,o]of kE)o.port===n&&o()})),n.postMessage(e),r++}catch(s){Ks.error("Unable to send message to worker",s)}r===0&&t()})}a(Aie,"broadcastWithAcknowledgement");function Oie(e){e.postMessage({type:Bx,workers:Yx()})}a(Oie,"sendThreadInfo");function Yx(){let e=Date.now();return Mi.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(Yx,"getChildWorkerInfo");function bie(e,t){e.resources=t,e.resources.updated=Date.now()}a(bie,"recordResourceReport");var bA;function yie(e){bA=e}a(yie,"setMonitorListener");var Nie=1e3,Dx=!1;function Iie(){Dx||(Dx=!0,setInterval(()=>{for(let e of Mi){let t=e.performance.eventLoopUtilization(),r;e.lastTotalELU?r=e.performance.eventLoopUtilization(t,e.lastTotalELU):r=t,e.lastTotalELU=t,e.recentELU=r}bA&&bA()},Nie).unref())}a(Iie,"startMonitoring");var wie=1e3;if(Es){VE(Es);for(let e=0,t=Ys.addPorts.length;e<t;e++){let r=Ys.addPorts[e];r.threadId=Ys.addThreadIds[e],VE(r)}setInterval(()=>{let e=process.memoryUsage();Es.postMessage({type:vx,heapTotal:e.heapTotal,heapUsed:e.heapUsed,external:e.external,arrayBuffers:e.arrayBuffers})},wie).unref(),RA=a(()=>new Promise((e,t)=>{Es.on("message",r),Es.postMessage({type:Ux});function r(n){n.type===Bx&&(Es.off("message",r),e(n.workers))}a(r,"receiveThreadInfo")}),"getThreadInfo")}else RA=Yx;Pi.exports.getThreadInfo=RA;function VE(e,t){Tn.push(e),e.on("message",r=>{if(r.type===Hx)r.port.threadId=r.threadId,VE(r.port);else if(r.type===die){let n=kE.get(r.id);n&&n()}else{for(let s of Vx)s(r,e);let n=OA.get(r.type);if(n)for(let s of n)try{s(r,e)}catch(i){Ks.error(i)}}}).on("close",()=>{Tn.splice(Tn.indexOf(e),1)}).on("exit",()=>{Tn.splice(Tn.indexOf(e),1)}),t?e.refCount=100:e.unref()}a(VE,"addPort");if(yA){let e,t,r=new Set,n=a(async(s,i)=>{i&&(e=i);for(let o of await oie(s,{withFileTypes:!0}))o.isDirectory()&&o.name!=="node_modules"&&n(Lx(s,o.name));try{for await(let{filename:o}of iie(s,{persistent:!1}))r.add(o),t&&clearTimeout(t),t=setTimeout(async()=>{e&&await e(),await wA(),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");Pi.exports.watchDir=n,process.env.WATCH_DIR&&n(process.env.WATCH_DIR)}else Es.on("message",async e=>{let{type:t}=e;t===Dl.ITC_EVENT_TYPES.SHUTDOWN&&(Pi.exports.restartNumber=e.restartNumber,Es.unref(),setTimeout(()=>{Ks.warn("Thread did not voluntarily terminate",tie),process.exit(0)},NA).unref())})});var LC={};qe(LC,{AUDIT_STORE_OPTIONS:()=>pf,createAuditEntry:()=>m_,openAuditStore:()=>WE,readAuditEntry:()=>Ut,setAuditRetention:()=>Die,transactionKeyEncoder:()=>eG});function WE(e){let t=e.auditStore=e.openDB(jx.AUDIT_STORE_NAME,pf);t.rootStore=e;let r=[];t.addDeleteRemovalCallback=function(i,o){return r[i]=o,{remove(){delete r[i]}}};let n=null;function s(i=$E){clearTimeout(n),n=setTimeout(async()=>{if(t.rootStore.status==="closed")return;let o=0,c;try{for(let{key:u,value:_}of t.getRange({start:0,snapshot:!1,end:Date.now()-CA})){if((_[0]&15)===MA){let l=Ut(_),d=l.tableId;r[d]?.(l.recordId)}if(c=t.remove(u),await new Promise(setImmediate),++o>=Cie){i=10;break}}await c}finally{o===0&&(i=Math.min(i<<1,CA/10)),s(i)}},i).unref()}return a(s,"scheduleAuditCleanup"),t.scheduleAuditCleanup=s,(0,KE.getWorkerIndex)()===(0,KE.getWorkerCount)()-1&&s($E),t}function Die(e,t=$E){CA=e,$E=t}function m_(e,t,r,n,s,i,o){let c=tG[i];if(!c)throw new Error(`Invalid audit entry type ${i}`);let u=1;n&&(n>1?ec.setFloat64(0,n):gn.set(hm),u=9),E(0),E(t),d(r),ec.setFloat64(u,e),u+=8,s?d(s):gn[u++]=0,gn[n?8:0]=c;let l=gn.subarray(0,u);if(o)return Buffer.concat([l,o]);return l;function d(f){let h=u;u+=1,u=(0,tc.writeKey)(f,gn,u);let p=u-h-1;p>127?p>16383?(UA.error("Key or username was too large for audit entry",f),u=h+1,gn[h]=0):(gn.copyWithin(h+2,h+1,u),ec.setUint16(h,p|32768),u++):gn[h]=p}function E(f){f<128?gn[u++]=f:f<16384?(ec.setUint16(u,f|32768),u+=2):f<1056964608?(ec.setUint32(u,f|3221225472),u+=4):(gn[u]=255,ec.setUint32(u+1,f),u+=5)}}function Ut(e){try{let t=e.dataView||(e.dataView=new PA(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,u=t.position+=o,_=t.readFloat64();o=t.readInt();let l=t.position,d=t.position+=o;return{type:tG[n&7],tableId:i,get recordId(){return Jx(e,c,u)},version:_,previousLocalTime:r,get user(){return d>l?Jx(e,l,d):void 0},getValue(E,f,h){if(n&DA||n&LA&&!f)return E.decoder.decode(e.subarray(t.position));if(n&LA&&h)return vA(E.getEntry(this.recordId),h,E)}}}catch(t){return UA.error("Reading audit entry error",t,e),{}}}function Jx(e,t,r){let n=e.subarray(t,r);return(0,tc.readKey)(n,0,r-t)}var tc,YE,jx,Xx,KE,Zx,UA,gn,ec,eG,pf,CA,Cie,$E,DA,LA,Kx,MA,Wx,Qx,zx,tG,PA,ti=Ae(()=>{tc=require("ordered-binary"),YE=B(Z()),jx=B(_t()),Xx=B(P()),KE=B(Je()),Zx=B(J());Cc();UA=B($());QE();(0,YE.initSync)();gn=Buffer.alloc(1024),ec=new DataView(gn.buffer,gn.byteOffset,1024),eG={writeKey(e,t,r){return e===wc?(t.set(wc,r),r+8):typeof e=="number"?((t.dataView||(t.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength))).setFloat64(r,e),r+8):(0,tc.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,tc.readKey)(e,t,r)}},pf={encoding:"binary",keyEncoder:eG},CA=(0,Zx.convertToMS)((0,YE.get)(Xx.CONFIG_PARAMS.LOGGING_AUDITRETENTION))||86400*3,Cie=1e3,$E=1e4;a(WE,"openAuditStore");a(Die,"setAuditRetention");DA=16,LA=32,Kx=1,MA=2,Wx=3,Qx=4,zx=5,tG={put:Kx|DA,[Kx]:"put",delete:MA,[MA]:"delete",message:Wx|DA,[Wx]:"message",invalidate:Qx,[Qx]:"invalidate",patch:zx|LA,[zx]:"patch"};a(m_,"createAuditEntry");a(Ut,"readAuditEntry");PA=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(Jx,"readKeySafely")});var BA={};qe(BA,{add:()=>zE,applyReverse:()=>rG,getRecordAtTime:()=>vA,rebuildUpdateBefore:()=>JE});function zE(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 JE(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,zE(r,n,s)}}else r||(r={}),r[n]=e[n];return r}function rG(e,t){for(let r in t){let n=t[r];if(n?.__op__){let s=Lie[n.__op__]?.reverse;if(s)s(e,r,{value:n.value});else throw new Error(`Unsupported operation ${n.__op__}`)}else e[r]=nG}}function vA(e,t,r){let n=r.rootStore.auditStore,s=Object.assign({},e.value),i=e.localTime;for(;i>t;){let u=n.get(i),_=Ut(u);switch(_.type){case"put":s=_.getValue(r);break;case"patch":rG(s,_.getValue(r));break;case"delete":s=null}i=_.previousLocalTime}let o={},c=0;for(let u in s)s[u]===nG&&(o[u]=!0,c++);for(;c>0&&i>0;){let u=n.get(i),_=Ut(u),l;switch(_.type){case"put":l=_.getValue(r);break;case"patch":l=_.getValue(r);break}for(let d in l)o[d]&&(s[d]=l[d],o[d]=!1,c--);i=_.previousLocalTime}if(c>0)for(let u in o)s[u]=null;return s}var Lie,nG,QE=Ae(()=>{ti();a(zE,"add");zE.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)};Lie={add:zE};a(JE,"rebuildUpdateBefore");a(rG,"applyReverse");nG={};a(vA,"getRecordAtTime")});function Zr(e){return e[yt]||(e[yt]=Object.create(null))}function th(e,t){let r=e.prototype,n={},s=t.attributes||t.properties||[];for(let o of s){let c=o.name,u,_;if(o.resolve)_={get(){return o.resolve(this,this[Ne])},set(l){return o.set(this,l)},configurable:!0};else{switch(o.type){case"String":u=a(function(l){if(!(typeof l=="string"||l==null&&o.nullable!==!1))throw new Rn.ClientError(`${c} must be a string, attempt to assign ${l}`);Zr(this)[c]=l},"set");break;case"ID":u=a(function(l){if(!(typeof l=="string"||l?.length>0&&l.every?.(d=>typeof d=="string")||l==null&&o.nullable!==!1))throw new Rn.ClientError(`${c} must be a string, attempt to assign ${l}`);Zr(this)[c]=l},"set");break;case"Float":case"Number":u=a(function(l){let d=l?.__op__?l.value:l;if(!(typeof d=="number"||l==null&&o.nullable!==!1))throw new Rn.ClientError(`${c} must be a number, attempt to assign ${d}`);Zr(this)[c]=l},"set");break;case"Int":u=a(function(l){let d=l?.__op__?l.value:l;if(!(d>>0===d||l==null&&o.nullable!==!1))if(typeof d=="number"&&Math.abs((d>>0)-d)<=1)d=Math.round(d),l?.__op__?l.value=d:l=d;else throw new Rn.ClientError(`${c} must be an integer between -2147483648 and 2147483647, attempt to assign ${l}`);Zr(this)[c]=l},"set");break;case"Long":u=a(function(l){let d=l?.__op__?l.value:l;if(!(Math.round(d)===l&&Math.abs(d)<=9007199254740992||l==null&&o.nullable!==!1))if(typeof d=="number"&&Math.abs(d)<=9007199254740992)d=Math.round(d),l?.__op__?l.value=d:l=d;else throw new Rn.ClientError(`${c} must be an integer between -9007199254740992 and 9007199254740992, attempt to assign ${l}`);Zr(this)[c]=l},"set");break;case"BigInt":u=a(function(l){let d=l?.__op__?l.value:l;if(!(typeof d=="bigint"||l==null&&o.nullable!==!1))if(typeof d=="string"||typeof d=="number")d=BigInt(d),l?.__op__?l.value=d:l=d;else throw new Rn.ClientError(`${c} must be a number, attempt to assign ${l}`);Zr(this)[c]=l},"set");break;case"Boolean":u=a(function(l){if(!(typeof l=="boolean"||l==null&&o.nullable!==!1))throw new Rn.ClientError(`${c} must be a boolean, attempt to assign ${l}`);Zr(this)[c]=l},"set");break;case"Date":u=a(function(l){if(!(l instanceof Date||l==null&&o.nullable!==!1))if(typeof l=="string"||typeof l=="number")l=new Date(l);else throw new Rn.ClientError(`${c} must be a Date, attempt to assign ${l}`);Zr(this)[c]=l},"set");break;case"Bytes":u=a(function(l){if(!(l instanceof Uint8Array||l==null&&o.nullable!==!1))throw new Rn.ClientError(`${c} must be a Buffer or Uint8Array, attempt to assign ${l}`);Zr(this)[c]=l},"set");break;case"Any":case void 0:u=a(function(l){Zr(this)[c]=l},"set");break;default:u=a(function(l){if(!(typeof l=="object"||l==null&&o.nullable!==!1))throw new Rn.ClientError(`${c} must be an object, attempt to assign ${l}`);Zr(this)[c]=l},"set")}_={get(){let l=this[yt];if(l&&c in l){let E=l[c];if(E?.__op__){let f=this[fe]?.[c];return E.update(f)}return E}let d=this[fe]?.[c];if(d&&typeof d=="object"){let E=iG(d,o);if(E)return l||(l=this[yt]=Object.create(null)),l[c]=E}return d},set:u,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 u=this[yt];return u?.[o]!==void 0?u[o]:this[fe]?.[o]}),i("set",function(o,c){let u=n[o];if(u)return u.set.call(this,c);if(t.sealed)throw new Rn.ClientError("Can not add a property to a sealed table schema");Zr(this)[o]=c}),i("deleteProperty",function(o){Zr(this)[o]=void 0}),i("toJSON",function(){let o=this[yt],c;for(let _ in o){c||(c=Object.assign({},this[fe]));let l=o[_];if(l?.__op__){let d=c[_];l=l.update(d)}c[_]=l}return Object.keys(this).length>0&&(c||(c=Object.assign({},this[fe])),Object.assign(c,this)),c||this[fe]}),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 iG(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?.[fe])throw new Error("Can not track an already tracked object, check for circular references");this[fe]=s}},th(r,t)),new r(e)):new jE(e);case Array:let n=new ZE(e.length);n[fe]=e;for(let s=0,i=e.length;s<i;s++){let o=e[s];o&&typeof o=="object"&&(o=iG(o,t?.elements)),n[s]=o}return n;default:return e}}function fd(e){let t=e[yt],r;for(let s in t){r||(r=Object.assign({},e[fe]));let i=t[s];if(i&&typeof i=="object")if(i.__op__){let o=r[s];i=i.update(o)}else i=fd(i);r[s]=i}return Object.keys(e).length>0&&(r||(r=Object.assign({},e[fe])),Object.assign(r,e)),r||e[fe]}function Po(e,t=e[yt]){let r;if(sG.call(e,fe)&&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=Po(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[fe]));let s=t[n];if(s&&typeof s=="object")if(s.__op__){let i=BA[s?.__op__];if(i)i(r,n,s);else throw new Error("Invalid CRDT operation "+s.__op__);continue}else s=Po(s);r[n]=s}return r?Object.freeze(r):sG.call(e,fe)?e[fe]:e}function XE(e){let t=e[fe];if(t===void 0)return!0;if(e.constructor===Array){if(!t||e[Mo]||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?.[fe]===s){if(XE(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[fe]===i){if(XE(s))return!0}else return!0}else return!0}}return!1}var Rn,yt,jE,sG,Mo,ZE,eh,Ed=Ae(()=>{Nn();Rn=B(ne());QE();yt=Symbol("own-data");a(Zr,"getChanges");a(th,"assignTrackedAccessors");a(iG,"trackObject");jE=class{static{a(this,"GenericTrackedObject")}constructor(t){if(t?.[fe])throw new Error("Can not track an already tracked object, check for circular references");this[fe]=t}};th(jE,{});a(fd,"collapseData");sG=Object.prototype.hasOwnProperty;a(Po,"deepFreeze");a(XE,"hasChanges");Mo=Symbol.for("has-array-changes"),ZE=class extends Array{static{a(this,"TrackedArray")}[Mo];constructor(t){super(t)}splice(...t){return this[Mo]=!0,super.splice(...t)}push(...t){return this[Mo]=!0,super.push(...t)}pop(){return this[Mo]=!0,super.pop()}unshift(...t){return this[Mo]=!0,super.unshift(...t)}shift(){return this[Mo]=!0,super.shift()}};ZE.prototype.constructor=Array;eh=class{constructor(t){this.value=t}static{a(this,"Addition")}__op__="add";update(t){return(+t||0)+this.value}}});var qp={};qe(qp,{CONTEXT:()=>Ne,ID_PROPERTY:()=>Le,IS_COLLECTION:()=>Fn,RECORD_PROPERTY:()=>fe,Resource:()=>Vt,snake_case:()=>Pie,transformForSelect:()=>nh});function Pie(e){return e[0].toLowerCase()+e.slice(1).replace(/[a-z][A-Z][a-z]/g,t=>t[0]+"_"+t.slice(1))}function oG(e,t){if(Ll=!1,e==="")return null;if(e=e.slice(1),e.indexOf("/")===-1)return e===""?(Ll=!0,null):(e.startsWith("$")&&(e=parseInt(e,36)),t.coerceId(decodeURIComponent(e)));let r=e.split("/"),n=new xA;for(let s=0;s<r.length;s++){let i=r[s];if(!i&&s===r.length-1){Ll=!0;break}n[s]=t.coerceId(decodeURIComponent(i))}return n}function en(e,t){n.reliesOnPrototype=!0;let r=t.hasContent;return n;function n(s,i,o){let c,u,_,l;if(r?(o?(l=i,o=o[Ne]||o):i?typeof s=="object"&&s&&(!Array.isArray(s)||typeof s[0]=="object")?(l=s,c=l[this.primaryKey]??null,o=i[Ne]||i):l=i:(l=s,c=l[Le]??l[this.primaryKey]??null),c==null&&(_=!0)):i?o=i[Ne]||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(u=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]),u.slice&&(u=u.slice(c.length,u.length),u.length===0&&(u=null,_=!1)))}else{if(typeof(c=s.url)=="string"){let f=c.indexOf("?");if(f>-1){let p=this.parseQuery(c.slice(f+1));u?u=Object.assign(p,u):u=p,c=c.slice(0,f)}let h=this.parsePath(c,o,u);h?.id!==void 0?(h.query&&(u?u=Object.assign(h.query,u):u=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(u?.ensureLoaded!=null||u?.async||_?(d=Object.assign({},t),u?.ensureLoaded!=null&&(d.ensureLoaded=u.ensureLoaded),u?.async&&(d.async=u.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 Xe(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,u,o):t.type==="update"?f.doesExist?.()===!1?f.allowCreate(o.user,l,o):f.allowUpdate(o.user,l,o):t.type==="create"?f.allowCreate(o.user,l,o):f.allowDelete(o.user,u,o);if(h?.then)return h.then(p=>{if(!p)throw new rh(o.user);return typeof l?.then=="function"?l.then(S=>e(f,u,o,S)):e(f,u,o,l)});if(!h)throw new rh(o.user)}return typeof l?.then=="function"?l.then(h=>e(f,u,o,h)):e(f,u,o,l)}a(E,"authorizeActionOnResource")}}function tn(e,t){let r=new uG.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 HA(e,t,r){let n=e[fe];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 nh(e,t){let r=t?.propertyResolvers,n=t[Ne],s;if(typeof e=="string")return a(function o(c){return c.then?c.then(o):Array.isArray(c)?c.map(o):HA(c,r,n)(e)},"transform");if(typeof e=="object"){if(e.asArray)return a(function c(u){if(u.then)return u.then(c);if(Array.isArray(u))return u.map(c);let _=[],l=i(HA(u,r,n));for(let d of e)_.push(l(d));return _},"transform");let o=e.forceNulls;return a(function c(u){if(u.then)return u.then(c);if(Array.isArray(u))return u.map(E=>E&&typeof E=="object"?c(E):E);let _={},l=i(HA(u,r,n)),d;for(let E of e){let f=l(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 u=s[c.name];if(!u){let l=r[c.name]?.definition?.tableClass;u=s[c.name]=nh(c.select||c,l)}let _=o(c.name);return u(_)}else return o(c);else return c}}a(i,"handleProperty")}var aG,cG,uG,Ne,Le,Fn,fe,Mie,Vt,rh,Ll,xA,Nn=Ae(()=>{aG=require("crypto");Ac();cG=require("../index"),uG=B(ne());Ed();ro();jf();Ne=Symbol.for("context"),Le=Symbol.for("primary-key"),Fn=Symbol("is-collection"),fe=Symbol("stored-record"),Mie={json:"application/json",cbor:"application/cbor",msgpack:"application/x-msgpack",csv:"text/csv"},Vt=class{static{a(this,"Resource")}static transactions;constructor(t,r){this[Le]=t;let n=r?.[Ne];this[Ne]=n!==void 0?n:r||null}static get=en(function(t,r,n,s){let i=t.get?.(r);if(i?.then)return i.then(o);return o(i);function o(c){let u;if((u=r?.select)&&c!=null&&!c.selectApplied){let _=nh(u,t.constructor);return typeof c?.map=="function"?c.map(_):_(c)}return c}},{type:"read",letItLinger:!0,ensureLoaded:!0,async:!0});static put=en(function(t,r,n,s){if(Array.isArray(s)&&t[Fn]){let i=[],o=n.authorize;for(let c of s){let u=t.constructor,_=u.getResource(c[u.primaryKey],n,{async:!0});_.then?i.push(_.then(l=>l.put(c,n))):i.push(_.put(c,n))}return Promise.all(i)}return t.put?t.put(s,r):tn(t,"put")},{hasContent:!0,type:"update"});static patch=en(function(t,r,n,s){return t.patch?t.patch(s,r):tn(t,"patch")},{hasContent:!0,type:"update"});static delete=en(function(t,r,n,s){return t.delete?t.delete(r):tn(t,"delete")},{hasContent:!1,type:"delete"});static getNewId(){return(0,aG.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={}),Xe(n,()=>{let i=new this(s,n),o=i.update?i.update(r,!0):tn(i,"update");return n.newLocation=s,n.createdResource=!0,o?.then?o.then(()=>s):s})}static invalidate=en(function(t,r,n,s){return t.invalidate?t.invalidate(r):tn(t,"delete")},{hasContent:!1,type:"update"});static post=en(function(t,r,n,s){return t[Le]!=null&&t.update?.(),t.post(s,r)},{hasContent:!0,type:"create"});static connect=en(function(t,r,n,s){return t.connect?t.connect(s,r):tn(t,"connect")},{hasContent:!0,type:"read"});static subscribe=en(function(t,r,n,s){return t.subscribe?t.subscribe(r):tn(t,"subscribe")},{type:"read"});static publish=en(function(t,r,n,s){return t[Le]!=null&&t.update?.(),t.publish?t.publish(s,r):tn(t,"publish")},{hasContent:!0,type:"create"});static search=en(function(t,r,n,s){let i=t.search?t.search(r):tn(t,"search"),o=n.select;if(o&&n.hasOwnProperty("select")&&i!=null&&!i.selectApplied){let c=nh(o,t.constructor);return i.map(c)}return i},{type:"read"});static query=en(function(t,r,n,s){return t.search?t.search(s,r):tn(t,"search")},{hasContent:!0,type:"read"});static copy=en(function(t,r,n,s){return t.copy?t.copy(s,r):tn(t,"copy")},{type:"create"});static move=en(function(t,r,n,s){return t.move?t.move(s,r):tn(t,"move")},{type:"delete"});post(t){if(this[Fn])return this.constructor.create(this[Le],t,this[Ne]);tn(this,"post")}static isCollection(t){return t?.[Fn]}static coerceId(t){return t}static parseQuery(t){return Jf(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&&Mie[o];if(c)r.headers.set("accept",c);else if(n)n.property=o;else return{query:{property:o},id:oG(t,this),isCollection:Ll}}let i=oG(t,this);return Ll?{id:i,isCollection:!0}:i}static getResource(t,r,n){let s,i=r[Ne],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 u;if(i.resourceCache?u=i.resourceCache:u=i.resourceCache=[],u.asMap){let _=u.asMap.get(t);if(s=_?.find(l=>l.constructor===c),s)return s;_||u.asMap.set(t,_=[]),_.push(s=new c(t,i))}else{if(s=u.find(_=>_[Le]===t&&_.constructor===c),s)return s;if(u.push(s=new c(t,i)),u.length>10){let _=new Map;for(let l of u){let d=l[Le],E=_.get(d);E?E.push(l):_.set(d,[l])}i.resourceCache.length=0,i.resourceCache.asMap=_}}}else s=new c(t,i);return o&&(s[Fn]=!0),s}subscribe(t){return new yn}connect(t){return t?.subscribe!==!1?this.subscribe?.(t):new yn}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[Ne]}};Vt.prototype[Ne]=null;(0,cG._assignPackageExport)("Resource",Vt);a(Pie,"snake_case");rh=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(oG,"pathToId");xA=class extends Array{static{a(this,"MulitPartId")}toString(){return this.join("/")}};a(en,"transactional");a(tn,"missingMethod");a(HA,"selectFromObject");a(nh,"transformForSelect")});function dG(e,t,r,n,s){let i=e.primaryStore.env.path,o=e.primaryStore.tableId,c;s?.crossThreads===!1?(c=_G,Uie(e.primaryStore,e.auditStore)):(c=lG,e.primaryStore.env.hasSubscriptionCommitListener||(e.primaryStore.env.hasSubscriptionCommitListener=!0,e.primaryStore.on("committed",()=>{fG(lG[i])})));let u=c[i]||(c[i]=[]);u.auditStore=e.auditStore,u.lastTxnTime==null&&(u.lastTxnTime=Date.now());let _=u[o];_||(_=u[o]=new Map,_.envs=u,_.tableId=o,_.store=e.primaryStore),t=Na(t);let l=new qA(r);l.startTime=n;let d=_.get(t);return d?d.push(l):(_.set(t,d=[l]),d.tables=_,d.key=t),l.subscriptions=d,l}function fG(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=Ut(s),o=e[i.tableId];if(!o)continue;let c=i.recordId,u,_=Na(i.recordId),l=0;do{let d=o.get(_);if(d){for(let f of d)if(!(l>0&&!(f.includeDescendants&&!(f.onlyChildren&&l>1)))){if(f.startTime>=n){(0,GA.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,GA.info)(h)}}}if(_==null)break;let E=_.lastIndexOf?.("/",_.length-2);E>-1?_=_.slice(0,E):_=null,l++}while(!0)}if(r)for(let n of r)n.txnInProgress=null,n.listener(null,{type:"end_txn"},e.lastTxnTime,!0)}function Uie(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 u=_G[s];if(!u)return;let _=a(()=>{r.threadLocalWrites||(r.threadLocalWrites=new Float64Array(r.getUserSharedBuffer("last-thread-local-write",new ArrayBuffer(8)))),u.txnTime=r.threadLocalWrites[0]||Date.now(),fG(u),r.threadLocalWrites[0]=u.lastTxnTime,r.unlock("thread-local-writes")},"acquiredLock");r.attemptLock("thread-local-writes",_)&&_()})}}var GA,lG,_G,qA,EG=Ae(()=>{GA=B($());Ac();Wu();ti();lG=Object.create(null),_G=Object.create(null);a(dG,"addSubscription");qA=class extends yn{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(fG,"notifyFromTransactionData");a(Uie,"listenToCommits")});var TR={};qe(TR,{coerceType:()=>sh,makeTable:()=>ah,setServerUtilities:()=>Vie,updateResource:()=>ih});function ah(e){let{primaryKey:t,indices:r,tableId:n,tableName:s,primaryStore:i,databasePath:o,databaseName:c,auditStore:u,schemaDefined:_,dbisDB:l,sealed:d}=e,{expirationMS:E,evictionMS:f,audit:h,trackDeletes:p}=e,{attributes:S}=e;S||(S=[]);let T=Sm(i,n,u),A=0,R,C,x={},v=Promise.resolve(),k,M,Q;for(let K of S)(K.assignCreatedTime||K.name==="__createdtime__")&&(k=K),(K.assignUpdatedTime||K.name==="__updatedtime__")&&(M=K),K.expiresAt&&(Q=K),K.isPrimaryKey&&(x=K);let j,z=[],ae=[],ue=1,de=2,xe={},Ee={},Pt=864e5,zl,Jl,zs,aO=!1,bh,yh,Sq=i.getRange({start:!1,end:!1}).constructor,Tq=10,gq=6;h&&lO();class Qe extends Vt{static name=s;static primaryStore=i;static auditStore=u;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=k;static updatedTimeProperty=M;static propertyResolvers;static sources=[];static get expirationMS(){return E}static dbisDB=l;static schemaDefined=_;static sourcedFrom(m,O){O&&(this.sourceOptions=O,(O.expiration||O.eviction||O.scanInterval)&&this.setTTLExpiration(O)),O?.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(U=>U[L]&&(!U[L].reliesOnPrototype||U.prototype[L])),N.length>0)if(N.length===1){let U=N[0];return(F,D,H)=>{if(F?.source!==U)return U[L](D,H,F)}}else return(U,F,D)=>{let H=[];for(let G of N){if(U?.source===G)break;H.push(G[L](F,D,U))}return Promise.all(H)}},"getApplyToIntermediateSource"),y=this.sources[this.sources.length-1],b=a(L=>{if(y[L]&&(!y[L].reliesOnPrototype||y.prototype[L]))return(N,U,F)=>{if(!N?.source)return y[L](U,F,N)}},"getApplyToCanonicalSource");return xe={put:b("put"),patch:b("patch"),delete:b("delete"),publish:b("publish")},Ee={put:w("put"),patch:w("patch"),delete:w("delete"),publish:w("publish"),invalidate:w("invalidate")},(async()=>{let L=!1,N=a(async(U,F)=>{let D=U.value,H=U.table?it[c][U.table]:Qe;if(c===Vn.SYSTEM_SCHEMA_NAME&&(U.table===Vn.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME||U.table===Vn.SYSTEM_TABLE_NAMES.USER_TABLE_NAME)&&(L=!0),U.id===void 0&&(U.id=D[H.primaryKey],U.id===void 0))throw new Error("Replication message without an id "+JSON.stringify(U));U.source=m;let G=await H.getResource(U.id,F,rc);switch(U.type){case"put":return G._writeUpdate(D,!0,rc);case"patch":return G._writeUpdate(D,!1,rc);case"delete":return G._writeDelete(rc);case"publish":return G._writePublish(D,rc);case"invalidate":return G.invalidate(rc);default:rt.error("Unknown operation",U.type,U.id)}},"writeUpdate");try{let U=m.subscribe;U&&p==null&&(p=!0);let F=m.subscribeOnThisThread?m.subscribeOnThisThread((0,vo.getWorkerIndex)()):(0,vo.getWorkerIndex)()===0,D=U&&F&&await m.subscribe?.({crossThreads:!1,inTransactionUpdates:!0,supportsTransactions:!0,omitCurrent:!0});if(D){let H;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,H)if(G.beginTxn)H.resolve();else{N(G,H);continue}if(G.type==="end_txn")continue;let Se=Xe(G,()=>{if(G.type==="transaction"){let te=[];for(let Pe of G.writes)try{te.push(N(Pe,G))}catch(ce){throw ce.message+=" writing "+JSON.stringify(Pe)+" of event "+JSON.stringify(G),ce}return Promise.all(te)}else if(G.type==="define_schema"){let te=this.attributes.slice(0),Pe;for(let ce of G.attributes)te.find(Ge=>Ge.name===ce.name)||(te.push(ce),Pe=!0);Pe&&(dt({table:s,database:c,attributes:te,origin:"cluster"}),xl.signalSchemaChange(new Gl.SchemaEventMsg(process.pid,Vn.OPERATIONS_ENUM.CREATE_TABLE,c,s)))}else return G.beginTxn?(H=G,N(G,G),new Promise(te=>{H.resolve=te})):N(G,G)});L&&(await Se,xl.signalUserChange(new Gl.UserEventMsg(process.pid))),G.onCommit&&(Se?.then?Se.then(G.onCommit):G.onCommit())}catch(se){rt.error("error in subscription handler",se)}}}catch(U){rt.error(U)}})(),this}static getResource(m,O,w){let y=super.getResource(m,O,w);if(m!=null){ac(m);try{if(y.hasOwnProperty(fe))return y;if(typeof m=="object"&&m&&!Array.isArray(m))throw new Error(`Invalid id ${JSON.stringify(m)}`);let b=!w?.async||i.cache?.get(m),L=On(O),N=L.getReadTxn();if(N?.isDone)throw new Error("You can not read from a transaction that has already been committed/aborted");return Nh(m,O,{transaction:N},b,U=>{if(U?ih(y,U):y[fe]=null,O.onlyIfCached&&O.noCacheStore){if(!y.doesExist())throw new rn.ServerError("Entry is not cached",504)}else if(w?.ensureLoaded){let F=Ih(m,U,O,y);if(F)return L?.disregardReadTxn(),y[FA]=!0,VA(F,D=>(ih(y,D),y))}return y})}catch(b){throw b.message.includes("Unable to serialize object")&&(b.message+=": "+JSON.stringify(m)),b}}return y}ensureLoaded(){let m=Ih(this[Le],this[Lr],this[Ne]);if(m)return this[FA]=!0,VA(m,O=>{this[Lr]=O,this[fe]=O.value,this[Bl]=O.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,Pt=m.scanInterval*1e3;else throw new Error("Invalid expiration value type");if(E<0)throw new Error("Expiration can not be negative");Pt=Pt||(E+f)/4,Ch()}static enableAuditing(m=!0){h=m,m&&lO(),Qe.audit=m}static coerceId(m){return m===""?null:sh(m,x)}static async dropTable(){if(delete it[c][s],c===o){for(let m of S)l.remove(Qe.tableName+"/"+m.name),r[m.name]?.drop();l.remove(Qe.tableName+"/"),i.drop(),await l.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));xl.signalSchemaChange(new Gl.SchemaEventMsg(process.pid,Vn.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 O=Qe.getRecordCount();return{recordCount:O.recordCount,estimatedRecordRange:O.estimatedRange,records:"./",name:s,database:c,attributes:S}}if(m?.property)return this.getProperty(m.property);if(this.doesExist()||m?.ensureLoaded===!1||this[Ne]?.returnNonexistent)return this}allowRead(m,O){let w=Xl(m);if(w?.read){if(w.isSuperUser)return!0;let y=w.attribute_permissions,b=O?.select;if(y?.length>0||aO&&b){if(O||(O={}),b){let L=y?.length>0&&kA(y,"read");O.select=b.map(N=>{let U=N.name||N;if(!L||L[U]){let F=zs[U]?.definition?.tableClass;if(F){if(N.name||(N={name:N}),!F.prototype.allowRead.call(null,m,N))return!1;if(!N.select)return N.name}return N}}).filter(Boolean)}else O.select=y.filter(L=>L.read&&!zs[L.attribute_name]).map(L=>L.attribute_name);return O}else return!0}}allowUpdate(m,O){let w=Xl(m);if(w?.update){let y=w.attribute_permissions;if(y?.length>0){let b=kA(y,"update");for(let L in O)if(!b[L])return!1;for(let L of y){let N=L.attribute_name;!L.update&&!(N in O)&&(O[N]=this.getProperty(N))}}return!0}}allowCreate(m,O){if(this[Fn]){let w=Xl(m);if(w?.insert){let y=w.attribute_permissions;if(y?.length>0){let b=kA(y,"insert");for(let L in O)if(!b[L])return!1}else return!0}}else return this.allowUpdate(m,{})}allowDelete(m){return Xl(m)?.delete}update(m,O){if(!On(this[Ne]))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&&(O?(Object.isFrozen(m)&&(m=Object.assign({},m)),this[fe]={},this[yt]=m):(y=this[yt],y&&(m=Object.assign(y,m)),this[yt]=y=m)),this._writeUpdate(this[yt],O),this}addTo(m,O){if(typeof O=="number"||typeof O=="bigint")this[Ml]===mG?this.set(m,(+this.getProperty(m)||0)+O):(this[Ml]||this.update(),this.set(m,new eh(O)));else throw new Error("Can not add a non-numeric value")}subtractFrom(m,O){if(typeof O=="number")return this.addTo(m,-O);throw new Error("Can not subtract a non-numeric value")}getMetadata(){return this[Lr]}invalidate(m){let O=this[Ne],w=this[Le];ac(w),On(this[Ne]).addWrite({key:w,store:i,invalidated:!0,entry:this[Lr],nodeName:this[Ne]?.nodeName,before:xe.invalidate?.bind(this,O,w),beforeIntermediate:Ee.invalidate?.bind(this,O,w),commit:(b,L)=>{if(L?.version>b)return;let N=null;for(let U in r)N||(N={}),N[U]=this.getProperty(U);T(w,N,this[Lr],b,Pl,h,this[Ne],0,"invalidate")}})}static evict(m,O,w){let y=this.Source,b;if(!((C||h)&&(!O||(b=i.getEntry(m),!b||!O)||b.version!==w))){if(C){if(i.hasLock(m,b.version))return;let L;for(let N in r)L||(L={}),L[N]=O[N];if(L)return T(m,L,b,w,Ul,null,null,0,null,!0)}return i.ifVersion(m,w,()=>{jl(m,O,null)}),h?T(m,null,b,w,Ul,null,null,0,null,!0):i.remove(m,w)}}lock(){throw new Error("Not yet implemented")}static operation(m,O){return m.table||=s,m.schema||=c,AG.operation(m,O)}put(m){this.update(m,!0)}patch(m){this.update(m,!1)}_writeUpdate(m,O,w){let y=this[Ne],b=On(y),L=this[Le];ac(L);let N=this[Lr];this[Ml]=O?mG:qie;let U={key:L,store:i,entry:N,nodeName:y?.nodeName,validate:F=>{m||(m=this[yt]),O||m&&XE(this[yt]===m?this:m)?y?.source||(b.checkOverloaded(),this.validate(m,!O),M&&(m[M.name]=M.type==="Date"?new Date(F):M.type==="String"?new Date(F).toISOString():F),O&&(t&&m[t]!==L&&(m[t]=L),k&&(N?.value?m[k.name]=N?.value[k.name]:m[k.name]=k.type==="Date"?new Date(F):k.type==="String"?new Date(F).toISOString():F),m=Po(m))):b.removeWrite(U)},before:O?xe.put?()=>xe.put(y,L,m):null:xe.patch?()=>xe.patch(y,L,m):xe.put?()=>xe.put(y,L,Po(this)):null,beforeIntermediate:O?Ee.put?()=>Ee.put(y,L,m):null:Ee.patch?()=>Ee.patch(y,L,m):Ee.put?()=>Ee.put(y,L,Po(this)):null,commit:(F,D,H)=>{if(H){if(y&&D?.version>(y.lastModified||0)&&(y.lastModified=D.version),this[Lr]=D,D?.value?.[fe])throw new Error("Can not assign a record to a record, check for circular references");O||(this[fe]=D?.value??null)}this[yt]=void 0,this[Bl]=F;let G=D?.value,se=m;if(this[Ml]=0,D?.version>=F)if(h){let ce=D.localTime,Ge=D.version;for(;se&&(ce>F||Ge>=F&&ce>0);){let re=u.get(ce);if(!re)break;let X=Ut(re);if(Ge=X.version,Ge>F){if(X.type==="patch"){let Te=X.getValue(i);se=JE(se,Te)}else if(X.type==="put"||X.type==="delete")return}else if(Ge===F)return;ce=X.previousLocalTime}}else{if(O)return;se=JE(se,G)}let Se;if(O?Se=se:(this[fe]=G,Se=O?se:Po(this,se)),this[fe]=Se,Se?.[fe])throw new Error("Can not assign a record to a record, check for circular references");let te;O||(te=m),jl(L,G,Se);let Pe=O?"put":"patch";T(L,Se,D,F,0,h,y,y.expiresAt||(E?E+Date.now():0),Pe,!1,te)}};b.addWrite(U)}async delete(m){if(typeof m=="string")return this.deleteProperty(m);if(this[Fn]){for await(let O of this.search(m))(await Qe.getResource(O[t],this.getContext(),{ensureLoaded:!1}))._writeDelete(m);return}return this[fe]?this._writeDelete(m):!1}_writeDelete(m){let O=On(this[Ne]),w=this[Le];ac(w);let y=this[Ne];return O.addWrite({key:w,store:i,resource:this,nodeName:y?.nodeName,before:xe.delete?.bind(this,y,w),beforeIntermediate:Ee.delete?.bind(this,y,w),commit:(b,L,N)=>{let U=L?.value;N&&(y&&L?.version>(y.lastModified||0)&&(y.lastModified=L.version),ih(this,L)),!(L?.version>b)&&(jl(this[Le],U),rt.trace("Write delete entry",w,b),h||p?(T(w,null,this[Lr],b,0,h,this[Ne],0,"delete"),h||Ch()):i.remove(this[Le]))}}),!0}search(m){let O=this[Ne],w=On(O);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 b,L={};function N(X,Te){let ve;switch(Te){case"and":case void 0:if(X.length<1)throw new Error('An "and" operator requires at least one condition');ve=!0;break;case"or":if(X.length<2)throw new Error('An "or" operator requires at least two conditions');break;default:throw new Error("Invalid operator "+Te)}let $n=ve&&{},Js;for(let Ye of X){if(Ye.conditions){Ye.conditions=N(Ye.conditions,Ye.operator);continue}let Ft=Ye[0]??Ye.attribute,on=Ft==null?x:Gs(S,Ft);if(on){if(ve){let Yn=xn(Ft),kt=$n[Yn];kt?(kt.push(Ye),Js=!0):$n[Yn]=[Ye]}(on.type||Yg[Ye.comparator])&&(Ye[1]===void 0?Ye.value=F(Ye.value,on):Ye[1]=F(Ye[1],on))}else if(Ft!=null)throw(0,rn.handleHDBError)(new Error,`${Ft} is not a defined attribute`,404)}if(m.enforceExecutionOrder)return X;if(Js)for(let Ye in $n){let Ft=$n[Ye],on=Ft.length;if(on>1)for(let Yn=0;Yn<on;Yn++){let kt=Ft[Yn];if(kt.comparator==="ge"||kt.comparator==="greater_than_equal")for(let js=0;js<on;js++){let qo=Ft[js];(qo.comparator==="le"||qo.comparator==="less_than_equal")&&(kt.comparator="between",kt.value=[kt.value,qo.value],X.splice(X.indexOf(qo),1))}if(kt.comparator==="equals"||!kt.comparator){for(let js=0;js<on;js++)if(js!==Yn){let qo=Ft[js];X.splice(X.indexOf(qo),1)}break}}}return X}a(N,"prepareConditions");function U(X,Te){if(m.enforceExecutionOrder)return X;for(let ve of X)ve.conditions&&(ve.conditions=U(ve.conditions,ve.operator));return X.length>1&&Te!=="or"?(0,RG.sortBy)(X,zf(Qe)):X}a(U,"orderConditions");function F(X,Te){return Array.isArray(X)?X.map(ve=>sh(ve,Te)):sh(X,Te)}a(F,"coerceTypedValues");let D=m.operator;(y.length>0||D)&&(y=N(y,D));let H=typeof m.sort=="object"&&m.sort,G;if(H&&D!=="or"){let X=H.attribute;if(b=y.find(Te=>xn(Te.attribute)===xn(X)),!b){let Te=Gs(S,X);if(!Te)throw(0,rn.handleHDBError)(new Error,`${Array.isArray(X)?X.join("."):X} is not a defined attribute`,404);if(Te.indexed)b={attribute:X,comparator:"sort"},y.push(b);else if(y.length===0&&!m.allowFullScan)throw(0,rn.handleHDBError)(new Error,`${Array.isArray(X)?X.join("."):X} is not indexed and not combined with any other conditions`,404)}b&&(b.descending=!!H.descending)}y=U(y,D),H&&(b&&y[0]===b?H.next&&(G={dbOrderedAttribute:H.attribute,attribute:H.next.attribute,descending:H.next.descending,next:H.next.next}):(b&&y.splice(y.indexOf(b),1),G=H));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 Se=w.useReadTxn(),te=Kg(y,D,Qe,Se,m,O,(X,Te)=>cO(X,se,O,Se,Te),L),Pe=m.ensureLoaded!==!1;G||(te=re(te));let ce=Qe.transformEntryForSelect(se,O,Se,L,Pe,!0),Ge=Qe.transformToOrderedSelect(te,se,G,Se,O,ce);function re(X){return m.offset||m.limit!==void 0?X.slice(m.offset,m.limit!==void 0?(m.offset||0)+m.limit:void 0):X}return a(re,"applyOffset"),G&&(Ge=re(Ge)),Ge.onDone=()=>{Ge.onDone=null,w.doneReadTxn()},Ge.selectApplied=!0,Ge.getColumns=()=>{if(se){let X=[];for(let Te of se)Te==="*"?X.push(...S.map(ve=>ve.name)):X.push(Te.name||Te);return X}return S.map(X=>X.name)},Ge}static transformToOrderedSelect(m,O,w,y,b,L){let N=new Sq;if(w){m=cO(m,O,y,b,null);let U;N.iterate=function(){let D,H=m[Symbol.asyncIterator]?m[Symbol.asyncIterator]():m[Symbol.iterator](),G,se=w.dbOrderedAttribute,Se,te,Pe=!0;function ce(re){let X=re.next&&ce(re.next),Te=re.descending;return(ve,$n)=>{let Js=wh(ve,re.attribute,y),Ye=wh($n,re.attribute,y),Ft=Te?(0,Bo.compareKeys)(Ye,Js):(0,Bo.compareKeys)(Js,Ye);return Ft===0?X?.(ve,$n)||0:Ft}}a(ce,"createComparator");let Ge=ce(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)};U=[],Se&&U.push(Se);do if(re=await H.next(),re.done){if(G=!0,U.length)break;return N.onDone&&N.onDone(),re}else{let X=re.value;if(X?.then&&(X=await X),se){let Te=wh(X,se,y);if(Pe)Pe=!1,te=Te;else if(Te!==te){te=Te,Se=X;break}}U.push(X)}while(!0);return w.isGrouped,U.sort(Ge),D=U[Symbol.iterator](),re=D.next(),re.done?(N.onDone&&N.onDone(),re):{value:await L.call(this,re.value)}},return(){N.onDone&&N.onDone(),H.return()},throw(){N.onDone&&N.onDone(),H.throw()}}};let F=a(D=>{if(typeof O=="object"&&Array.isArray(D.attribute))for(let H=0;H<O.length;H++){let G=O[H],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]&&(O[H]=se={name:G,sort:{attribute:D.attribute.slice(1),descending:D.descending}})}D.next&&F(D.next)},"applySortingOnSelect");F(w)}else N.iterate=(m[Symbol.asyncIterator]||m[Symbol.iterator]).bind(m),N=N.map(L);return N}static transformEntryForSelect(m,O,w,y,b,L){if(m&&(m===t||m?.length===1&&m[0]===t)){let D=a(H=>(O?.transaction?.stale&&(O.transaction.stale=!1),H?.key??H),"transform");return m===t?D:m.asArray?H=>[D(H)]:H=>({[t]:D(H)})}let N;b&&C&&!m?.every(D=>{let H;return typeof D=="object"?H=D.name:H=D,r[H]||H===t})&&(N=!0);let U,F=a(function(D){let H;if(O?.transaction?.stale&&(O.transaction.stale=!1),D!=null){if(bh=D,H=D.value||D.deref?.(),!H&&(D.key===void 0||D.deref)){if(D=Nh(D.key??D,O,{transaction:w,lazy:m?.length<4},this.isSync,G=>G),D?.then)return D.then(F.bind(this));H=D?.value}if(N&&(D.metadataFlags&(Pl|Ul)||D.expiresAt&&D.expiresAt<Date.now())){let G=Ih(D.key??D,D,O);if(G?.then)return G.then(F)}}if(H==null)return L?Uo.SKIP:H;if(m&&!(m[0]==="*"&&m.length===1)){let G,se=a((te,Pe)=>{let ce;typeof te=="object"?ce=te.name:ce=te;let Ge=zs?.[ce],re;if(Ge){let X=y?.[ce];if(X)if(X.hasMappings){let ve=Ge.from?H[Ge.from]:xn(D.key);re=X.get(ve),re||(re=[])}else re=X.fromRecord?.(H);else re=Ge(H,O,D);let Te=a(ve=>{if(ve&&typeof ve=="object"){let $n=Ge.definition?.tableClass||Qe;U||(U={});let Js=U[ce]||(U[ce]=$n.transformEntryForSelect(ce===te?null:te.select||(Array.isArray(te)?te:null),O,w,X,b));if(Array.isArray(ve)){let Ye=[],Ft=$n.transformToOrderedSelect(ve,te.select,typeof te.sort=="object"&&te.sort,O,w,Js)[this.isSync?Symbol.iterator:Symbol.asyncIterator](),on=a(kt=>{for(;!kt.done;){if(kt?.then)return kt.then(on);Ye.push(kt.value),kt=Ft.next()}Pe(Ye,ce)},"nextValue"),Yn=on(Ft.next());Yn&&(G||(G=[]),G.push(Yn));return}else if(ve=Js.call(this,ve),ve?.then){G||(G=[]),G.push(ve.then(Ye=>Pe(Ye,ce)));return}}Pe(ve,ce)},"handleResolvedValue");re?.then?(G||(G=[]),G.push(re.then(Te))):Te(re);return}else re=H[ce],re&&typeof re=="object"&&ce!==te&&(re=Qe.transformEntryForSelect(te.select||te,O,w,null)({value:re}));Pe(re,ce)},"selectAttribute"),Se;if(typeof m=="string")se(m,te=>{Se=te});else if(Array.isArray(m))if(m.asArray)Se=[],m.forEach((te,Pe)=>{te==="*"?m[Pe]=H:se(te,ce=>Se[Pe]=ce)});else{Se={};let te=m.forceNulls;for(let Pe of m)if(Pe==="*")for(let ce in H)Se[ce]=H[ce];else se(Pe,(ce,Ge)=>{ce===void 0&&te&&(ce=null),Se[Ge]=ce})}else throw new rn.ClientError("Invalid select"+m);return G?Promise.all(G).then(()=>Se):Se}return H},"transform");return F}async subscribe(m){if(!u)throw new Error("Can not subscribe to a table without an audit log");h||dt({table:s,database:c,schemaDefined:_,attributes:S,audit:!0}),m||(m={});let O=!m.rawEvents,w=dG(Qe,this[Le]??null,function(N,U,F,D){try{let H=U.getValue?.(i,O);if(!H&&U.type==="patch"&&O){let G=i.getEntry(N);G?.version===U.version?H=G.value:H=U.getValue?.(i,!0,F),U.type="put"}this.send({id:N,timestamp:F,value:H,version:U.version,type:U.type,beginTxn:D})}catch(H){rt.error(H)}},m.startTime||0,m);this[Fn]&&(w.includeDescendants=!0,m.onlyChildren&&(w.onlyChildren=!0)),m.supportsTransactions&&(w.supportsTransactions=!0);let y=this[Le],b=m.previousCount;b>1e3&&(b=1e3);let L=m.startTime;if(this[Fn]){if(L){if(b)throw new rn.ClientError("startTime and previousCount can not be combined for a table level subscription");for(let{key:N,value:U}of u.getRange({start:L,exclusiveStart:!0})){let F=Ut(U);if(F.tableId!==n)continue;let D=F.recordId;if(y==null||TG(y,D)){let H=F.getValue(i,O,N);w.send({id:D,timestamp:N,value:H,version:F.version,type:F.type})}w.startTime=N}}else if(b){let N=[];for(let{key:U,value:F}of u.getRange({start:"z",end:!1,reverse:!0}))try{let D=Ut(F);if(D.tableId!==n)continue;let H=D.recordId;if(y==null||TG(y,H)){let G=D.getValue(i,O,U);if(N.push({id:H,timestamp:U,value:G,version:D.version,type:D.type}),--b<=0)break}}catch(D){rt.error("Error getting history entry",U,D)}for(let U=N.length;U>0;)w.send(N[--U]);N[0]&&(w.startTime=N[0].timestamp)}else if(!m.omitCurrent)for(let{key:N,value:U,version:F,localTime:D}of i.getRange({start:y??!1,end:y==null?void 0:[y,Bo.MAXIMUM_KEY],versions:!0}))U&&w.send({id:N,timestamp:D,value:U,version:F,type:"put"})}else{b&&!L&&(L=0);let N=this[Lr]?.localTime;if(N===pm&&(i.cache?.delete(y),this[Lr]=i.getEntry(y),rt.trace("re-retrieved record",N,this[Lr]?.localTime),N=this[Lr]?.localTime),rt.trace("Subscription from",L,"from",y,N),L<N){let U=[],F=N;do{let D=u.get(F);if(D){m.omitCurrent=!0;let H=Ut(D),G=H.getValue(i,O,F);O&&(H.type="put"),U.push({id:y,value:G,timestamp:F,...H}),F=H.previousLocalTime}else break;b&&b--}while(F>L&&b!==0);for(let D=U.length;D>0;)w.send(U[--D]);w.startTime=N}!m.omitCurrent&&this.doesExist()&&w.send({id:y,timestamp:N,value:this,version:this[Bl],type:"put"})}return m.listener&&w.on("data",m.listener),w}doesExist(){return!!(this[fe]||this[Ml])}publish(m,O){this._writePublish(m,O)}_writePublish(m,O){let w=On(this[Ne]),y=this[Le]||null;ac(y);let b=this[Ne];w.addWrite({key:y,store:i,entry:this[Lr],nodeName:b?.nodeName,validate:()=>{b?.source||(w.checkOverloaded(),this.validate(m))},before:xe.publish?.bind(this,b,y,m),beforeIntermediate:Ee.publish?.bind(this,b,y,m),commit:(L,N,U)=>{N===void 0&&p&&!h&&Ch(),T(y,N?.value??null,N,N?.version||L,0,!0,b,N?.expiresAt,"message",!1,m)}})}validate(m,O){let w,y=a((b,L,N)=>{if(L.type&&b!=null)if(O&&b.__op__&&(b=b.value),L.properties){typeof b!="object"&&(w||(w=[])).push(`Value ${kn(b)} in property ${N} must be an object${L.type?" ("+L.type+")":""}`);let U=L.properties;for(let F=0,D=U.length;F<D;F++){let H=U[F],G=y(b[H.name],H,N+"."+H.name);G&&(b[H.name]=G)}if(L.sealed&&b!=null&&typeof b=="object")for(let F in b)U.find(D=>D.name===F)||(w||(w=[])).push(`Property ${F} is not allowed within object in property ${N}`)}else switch(L.type){case"Int":(typeof b!="number"||b>>0!==b)&&(w||(w=[])).push(`Value ${kn(b)} in property ${N} must be an integer (from -2147483648 to 2147483647)`);break;case"Long":(typeof b!="number"||!(Math.floor(b)===b&&Math.abs(b)<=9007199254740992))&&(w||(w=[])).push(`Value ${kn(b)} in property ${N} must be an integer (from -9007199254740992 to 9007199254740992)`);break;case"Float":typeof b!="number"&&(w||(w=[])).push(`Value ${kn(b)} in property ${N} must be a number`);break;case"ID":typeof b=="string"||b?.length>0&&b.every?.(U=>typeof U=="string")||(w||(w=[])).push(`Value ${kn(b)} in property ${N} must be a string, or an array of strings`);break;case"String":typeof b!="string"&&(w||(w=[])).push(`Value ${kn(b)} in property ${N} must be a string`);break;case"Boolean":typeof b!="boolean"&&(w||(w=[])).push(`Value ${kn(b)} in property ${N} must be a boolean`);break;case"Date":if(!(b instanceof Date)){if(typeof b=="string"||typeof b=="number")return new Date(b);(w||(w=[])).push(`Value ${kn(b)} in property ${N} must be a Date`)}break;case"BigInt":if(typeof b!="bigint"){if(typeof b=="string"||typeof b=="number")return BigInt(b);(w||(w=[])).push(`Value ${kn(b)} in property ${N} must be a bigint`)}break;case"Bytes":b instanceof Uint8Array||(w||(w=[])).push(`Value ${kn(b)} in property ${N} must be a Buffer or Uint8Array`);break;case"array":if(Array.isArray(b)){if(L.elements)for(let U=0,F=b.length;U<F;U++){let D=b[U],H=y(D,L.elements,N+"[*]");H&&(b[U]=H)}}else(w||(w=[])).push(`Value ${kn(b)} in property ${N} must be a Buffer or Uint8Array`);break}L.nullable===!1&&b==null&&(w||(w=[])).push(`Property ${N} is required (and not does not allow null values)`)},"validateValue");for(let b=0,L=S.length;b<L;b++){let N=S[b];if(!N.relationship&&(!O||N.name in m)){let U=y(m[N.name],N,N.name);U&&(m[N.name]=U)}}if(d)for(let b in m)S.find(L=>L.name===b)||(w||(w=[])).push(`Property ${b} is not allowed`);if(w)throw new rn.ClientError(w.join(". "))}getUpdatedTime(){return this[Bl]}wasLoadedFromSource(){return C?!!this[FA]:void 0}static async addAttributes(m){let O=S.slice(0);for(let w of m){if(!w.name)throw new rn.ClientError("Attribute name is required");if(w.name.match(/[`/]/))throw new rn.ClientError("Attribute names cannot include backticks or forward slashes");O.push(w)}return dt({table:s,database:c,schemaDefined:_,attributes:O}),Qe.indexingOperation}static async removeAttributes(m){let O=S.filter(w=>!m.includes(w.name));return dt({table:s,database:c,schemaDefined:_,attributes:O}),Qe.indexingOperation}static getRecordCount(m){let O=i.getStats().entryCount,w=5e3,y=1e3,b;O>w&&!m?.exactCount&&(b=y);let L=0;for(let{value:N}of i.getRange({start:!0,lazy:!0,limit:b}))N!=null&&L++;if(b){let N=L;L=0;for(let{value:Pe}of i.getRange({start:"\uFFFF",reverse:!0,lazy:!0,limit:b}))Pe!=null&&L++;let U=b*2,F=(L+N)/U,D=Math.pow((L-N+1)/b/2,2)+F*(1-F)/U,H=Math.max(Math.sqrt(D)*O,1),G=Math.round(F*O),se=Math.max(G-1.96*H,0),Se=Math.min(G+1.96*H,O),te=Math.pow(10,Math.round(Math.log10(H)));return te>G&&(te=te/10),L=Math.round(G/te)*te,{recordCount:L,estimatedRange:[Math.round(se),Math.round(Se)]}}return{recordCount:L}}static updatedAttributes(){zs=this.propertyResolvers={$id:(m,O,w)=>({value:w.key}),$updatedtime:(m,O,w)=>w.version,$record:(m,O,w)=>w?{value:m}:m};for(let m of this.attributes){m.resolve=null;let O=m.relationship;if(O)if(m.indexed&&console.error("A relationship property can not be directly indexed, (but you may want to index the foreign key attribute)"),aO=!0,O.to)m.elements?.definition?(zs[m.name]=m.resolve=(w,y,b)=>{let L=w[O.from?O.from:t],N=m.elements.definition.tableClass;return b?Ha({attribute:O.to,value:L},On(y).getReadTxn(),!1,N,!1).asArray:N.search([{attribute:O.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,O.from&&(m.resolve.from=O.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(O.from){let w=m.definition||m.elements?.definition;w?(zs[m.name]=m.resolve=(y,b,L)=>{let N=y[O.from];if(N!==void 0){if(m.elements){let U,F=N.map(D=>{let H=L?w.tableClass.primaryStore.getEntry(D,{transaction:On(b).getReadTxn()}):w.tableClass.get(D,b);return H?.then&&(U=!0),H});return O.filterMissing?U?Promise.all(F).then(D=>D.filter(gG)):F.filter(gG):U?Promise.all(F):F}return L?w.tableClass.primaryStore.getEntry(N,{transaction:On(b).getReadTxn()}):w.tableClass.get(N,b)}},m.set=(y,b)=>{if(Array.isArray(b)){let L=b.map(N=>N[Le]||N[w.tableClass.primaryKey]);y[O.from]=L}else{let L=b[Le]||b[w.tableClass.primaryKey];y[O.from]=L}},m.resolve.definition=m.definition||m.elements?.definition,m.resolve.from=O.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`)}th(this,this)}static async deleteHistory(m=0){let O;for(let{key:w,value:y}of u.getRange({start:0,end:m}))await vl(),Ut(y).tableId===n&&(O=u.remove(w));await O}static async*getHistory(m=0,O=1/0){for(let{key:w,value:y}of u.getRange({start:m,end:O})){await vl();let b=Ut(y);b.tableId===n&&(yield{id:b.recordId,localTime:w,version:b.version,type:b.type,value:b.getValue(i,!0,w),user:b.user})}}static async getHistoryOfRecord(m){let O=[];if(m==null)throw new Error("An id is required");let w=i.getEntry(m);if(!w)return O;let y=w.localTime;if(!y)throw new Error("The entry does not have a local audit time");let b=0;do{await vl();let L=u.get(y);if(L){let N=Ut(L);O.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(b<1e3&&y);return O.reverse()}static cleanup(){j?.remove()}}Qe.updatedAttributes();let Rq=Qe.prototype;return Rq[Gie]=!0,E&&Qe.setTTLExpiration(E/1e3),Q&&Aq(),Qe;function jl(K,m,O){let w;for(let y in r){let b=r[y],L=b.isIndexing,N=O?.[y],U=m?.[y];if(N===U&&!L)continue;w=!0;let F=b.indexNulls,D=(0,Hl.getIndexedValues)(N,F),H=(0,Hl.getIndexedValues)(U,F);if(H?.length>0){let G=new Set(H);if(D=D?D.filter(se=>{if(G.has(se))G.delete(se);else return!0}):[],H=Array.from(G),(H.length>0||D.length>0)&&hG){let se=H.concat(D).map(Se=>({key:Se,value:K}));b.prefetch(se,SG)}for(let se=0,Se=H.length;se<Se;se++)b.remove(H[se],K)}else D?.length>0&&hG&&b.prefetch(D.map(G=>({key:G,value:K})),SG);if(D)for(let G=0,se=D.length;G<se;G++)b.put(D[G],K)}return w}a(jl,"updateIndices");function ac(K){switch(typeof K){case"number":return!0;case"string":if(K.length<659)return!0;if(K.length>pG)throw new Error("Primary key size is too large: "+K.length);break;case"object":if(K===null)return!0;break;case"bigint":if(K<2n**64n&&K>-(2n**64n))return!0;break;default:throw new Error("Invalid primary key type: "+typeof K)}if((0,Bo.writeKey)(K,Fie,0)>pG)throw new Error("Primary key size is too large: "+K.length);return!0}a(ac,"checkValidId");function Nh(K,m,O,w,y){let b=a(()=>{if(m?.transaction?.stale&&(m.transaction.stale=!1),O.transaction?.isDone)return y(null,K);let L=i.getEntry(K,O);return L&&m&&(L?.version>(m.lastModified||0)&&(m.lastModified=L.version),L?.localTime&&!m.lastRefreshed&&(m.lastRefreshed=L.localTime)),y(L,K)},"whenPrefetched");return w?b():ue>0?(ue--,b()):new Promise((L,N)=>{ue===0?(ue--,i.prefetch([K],()=>{U(),F()})):(z.push(K),ae.push(F),z.length>gq&&(ue--,U()));function U(){if(z.length>0){let D=ae;i.prefetch(z,()=>{ue===-1?U():ue++;for(let H of D)H()}),z=[],ae=[],de>2&&de--}else ue=de,de<Tq&&de++}a(U,"prefetch");function F(){try{L(b())}catch(D){N(D)}}a(F,"load")})}a(Nh,"loadLocalRecord");function Xl(K){if(!K?.role)return;let m=K.role.permission;if(m.super_user)return kie;let O=m[c],w,y=O?.tables;if(y)return y[s];if(c==="data"&&(w=m[s])&&!w.tables)return w}a(Xl,"getTablePermissions");function Ih(K,m,O,w){if(C){let y;if(O.noCache?y=!0:(m?(!m.value||m.metadataFlags&(Pl|Ul)||m.expiresAt&&m.expiresAt<Date.now())&&(y=!0):y=!0,Wr(!y,"cache-hit",s)),y){let b=uO(K,m,O).then(L=>(L?.value?.[fe]&&rt.error("Can not assign a record with a record property"),O&&(L?.version>(O.lastModified||0)&&(O.lastModified=L.version),O.lastRefreshed=Date.now()),L));if(O?.onlyIfCached||m?.value&&w?.allowStaleWhileRevalidate?.(m,K)){if(b.catch(L=>rt.warn(L)),O?.onlyIfCached&&!w.doesExist())throw new rn.ServerError("Entry is not cached",504);return}else return b}}}a(Ih,"ensureLoadedFromSource");function On(K){let m=K?.transaction;if(m){if(!m.lmdbDb)return m.lmdbDb=i,m;do{if(m.lmdbDb?.path===i.path)return m;let O=m.next;if(!O)return m=m.next=new to,m.lmdbDb=i,m;m=O}while(!0)}else return new _d}a(On,"txnForContext");function wh(K,m,O){if(!K)return;bh=K;let w=K.value||K.deref?.()||(bh=i.getEntry(K.key))?.value;if(typeof m=="object"){let b=zs,L=w;for(let N=0,U=m.length;N<U;N++){let F=m[N],D=b?.[F];L=D&&L?D(L,O,!0)?.value:L?.[F],b=D?.definition?.tableClass?.propertyResolvers}return L}let y=zs[m];return y?y(w,O):w[m]}a(wh,"getAttributeValue");function cO(K,m,O,w,y){let b=y?.length,L={transaction:w,lazy:b>0||typeof m=="string"||m?.length<4,alwaysPrefetch:!0},N;function U(F,D){let H=F?.value;if(!H)return Uo.SKIP;for(let G=0;G<b;G++)if(!N?.includes(G)&&!y[G](H,F))return Uo.SKIP;return D!==void 0&&(F.key=D),F}if(a(U,"processEntry"),b>0||!K.hasEntries){let F=K.map(D=>{if(N=null,typeof D=="object"&&D?.key!==void 0)return b>0?U(D):D;if(D==null)return Uo.SKIP;for(let H=0;H<b;H++){let se=y[H].idFilter;if(se){if(!se(D))return Uo.SKIP;N||(N=[]),N.push(H)}}return Nh(D,O,L,!1,U)});return Array.isArray(K)&&(F=F.filter(D=>D!==Uo.SKIP)),F.hasEntries=!0,F}return K}a(cO,"transformToEntries");async function uO(K,m,O){let w=m?.metadataFlags,y=m?.version,b,L;if(!i.attemptLock(K,y,()=>{clearTimeout(L);let D=i.getEntry(K);!D||!D.value||D.metadataFlags&(Pl|Ul)?b(uO(K,i.getEntry(K),O)):b(D)}))return new Promise(D=>{b=D,L=setTimeout(()=>{i.unlock(K,y)},xie)});let N=m?.value,U={requestContext:O,replacingRecord:N,replacingVersion:y,source:null,resourceCache:O?.resourceCache},F=O?.responseHeaders;return new Promise((D,H)=>{let G;VA(Xe(U,async se=>{let Se=performance.now(),te,Pe,ce;try{for(let Te of Qe.sources)if(Te.get&&(!Te.get.reliesOnPrototype||Te.prototype.get)&&(U.source=Te,te=await Te.get(K,U),te))break;ce=w&Pl;let re=U.lastModified||ce&&y;Pe=ce||re>y||!N,re||(re=(0,Hl.getNextMonotonicTime)());let X=performance.now()-Se;if(pr(X,"cache-resolution",s),F&&Eg(F,"Server-Timing",`cache-resolve;dur=${X.toFixed(2)}`,!0),se.timestamp=re,E&&!U.expiresAt&&(U.expiresAt=Date.now()+E),te){if(typeof te!="object")throw new Error("Only objects can be cached and stored in tables");typeof te.toJSON=="function"&&(te=te.toJSON()),t&&te[t]!==K&&(te[t]=K)}G=!0,D({version:re,value:te})}catch(re){re.message+=` while resolving record ${K} for ${s}`,N&&((re.code==="ECONNRESET"||re.code==="ECONNREFUSED"||re.code==="EAI_AGAIN")&&!O?.mustRevalidate||O?.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)")):H(re),U.transaction.abort();return}if(O?.noCacheStore){U.transaction.abort();return}On(U).addWrite({key:K,store:i,entry:m,nodeName:"source",commit:(re,X)=>{if(X?.version!==y)return;let Te=jl(K,N,te);te?(Ee.put?.(U,K,te),T(K,te,X,re,0,h&&Pe||null,U,U.expiresAt,"put",!!ce)):(Ee.delete?.(U,K),h||p?T(K,null,X,re,0,h&&Pe||null,U,0,"delete",!!ce):i.remove(K,y))}})}),()=>{i.unlock(K,y)},se=>{i.unlock(K,y),G&&rt.error("Error committing cache update",se)})})}a(uO,"getFromSource");function Ch(){if(Pt!==zl&&(zl=Pt,(0,vo.getWorkerIndex)()===(0,vo.getWorkerCount)()-1)){if(Jl&&clearTimeout(Jl),!Pt)return;let K=new Date;K.setMonth(0),K.setDate(1),K.setHours(0),K.setMinutes(0),K.setSeconds(0);let m=Math.ceil((Date.now()-K.getTime())/Pt)*Pt+K.getTime(),O=a(w=>{rt.trace(`Scheduled next cleanup scan at ${new Date(w)}ms`),Jl=setTimeout(()=>v=v.then(async()=>{if(O(Math.max(w+Pt,Date.now())),i.rootStore.status!=="open"){clearTimeout(Jl);return}let y=50,b=new Array(y),L=0;rt.trace(`Starting cleanup scan for ${s}`);try{let N=0;for(let{key:U,value:F,version:D,expiresAt:H}of i.getRange({start:!1,snapshot:!1,versions:!0,lazy:!0})){let G;F===null&&!h&&D+Hie<Date.now()?G=i.remove(U,D):H&&H+f<Date.now()&&(G=Qe.evict(U,F,D),N++),G&&(await b[L],b[L]=G.catch(se=>{rt.error("Cleanup error",se)}),++L>=y&&(L=0)),await vl()}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");O(m)}}a(Ch,"scheduleCleanup");function lO(){j=u?.addDeleteRemovalCallback(n,K=>{let m=i.getEntry(K);m?.value===null&&i.remove(K,m.version)})}a(lO,"addDeleteRemoval");function Aq(){(0,vo.getWorkerIndex)()===0&&setInterval(async()=>{if(!yh){yh=!0;try{let K=Q.name,m=r[K];if(!m)throw new Error(`expiresAt attribute ${Q} must be indexed`);for(let O of m.getRange({start:!0,values:!1,end:Date.now(),snapshot:!1})){for(let w of m.getValues(O)){let y=i.getEntry(w);y?.value?y.value[K]<Date.now()&&Qe.evict(w,y.value,y.version):i.ifVersion(w,y?.version,()=>m.remove(O,w))}await vl()}}catch(K){rt.error("Error in evicting old records",K)}finally{yh=!1}}},Bie).unref()}a(Aq,"runRecordExpirationEviction")}function kA(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 SG(){}function Vie(e){AG=e}function sh(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:($ie.test(e)||(e+="Z"),new Date(e)):new Date(+e):!r||r==="Any"?(0,oh.autoCast)(e):e}function TG(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 VA(e,t,r){return e?.then?e.then(t,r):t(e)}function ih(e,t){e[Lr]=t,e[fe]=t?.value??null,e[Bl]=t?.version}function gG(e){return e!=null}function kn(e){try{return JSON.stringify(e)}catch{return e}}var Vn,Uo,Hl,RG,ql,rn,xl,Gl,rt,Bo,vo,oh,vie,AG,Bie,Hie,hG,xie,Bl,Gie,Lr,Ml,mG,qie,FA,rc,Pl,Ul,Fie,pG,kie,uTe,$ie,vl,_E=Ae(()=>{Vn=B(P()),Uo=require("lmdb"),Hl=B(vr()),RG=require("lodash");Nn();aS();ql=B(Z());EG();rn=B(ne()),xl=B(bs()),Gl=B(Mn());Oe();jf();rt=B($());Ed();ro();Bo=require("ordered-binary"),vo=B(Je());ti();oh=B(J());Cc();ws();QE();Qu();vie=new Uint8Array(9);vie[8]=192;Bie=6e4,Hie=864e5;ql.initSync();hG=ql.get(Vn.CONFIG_PARAMS.STORAGE_PREFETCHWRITES),xie=1e4,Bl=Symbol.for("version"),Gie=Symbol.for("incremental-update"),Lr=Symbol("entry"),Ml=Symbol("is-saving"),mG=1,qie=2,FA=Symbol("loaded-from-source"),rc={isNotification:!0,ensureLoaded:!1},Pl=1,Ul=8,Fie=Buffer.allocUnsafeSlow(8192),pG=1978,kie={read:!0,insert:!0,update:!0,delete:!0,isSuperUser:!0},uTe=(0,oh.convertToMS)(ql.get(Vn.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE))||864e5;a(ah,"makeTable");a(kA,"attributesAsObject");a(SG,"noop");a(Vie,"setServerUtilities");$ie=/[+-][0-9]{2}:[0-9]{2}|[a-zA-Z]$/;a(sh,"coerceType");a(TG,"isDescendantId");vl=a(()=>new Promise(setImmediate),"rest");a(VA,"when");a(ih,"updateResource");a(gG,"exists");a(kn,"stringify")});var Fe={};qe(Fe,{database:()=>nu,databases:()=>it,dropDatabase:()=>dS,dropTableMeta:()=>zie,getDatabases:()=>hr,getDefaultCompression:()=>Sf,getTables:()=>Yie,onUpdatedTable:()=>XR,readMetaDb:()=>Fl,resetDatabases:()=>Fu,table:()=>dt,tables:()=>Br});function Yie(){return dh||hr(),Br||{}}function hr(){if(dh)return it;dh=!0,ic=new Map;let e=(0,mt.getHdbBasePath)()&&(0,nt.join)((0,mt.getHdbBasePath)(),Mt.DATABASES_DIR_NAME),t=(0,mt.get)(Mt.CONFIG_PARAMS.DATABASES)||{};if(process.env.SCHEMAS_DATA_PATH&&(t.data={path:process.env.SCHEMAS_DATA_PATH}),e=process.env.STORAGE_PATH||(0,mt.get)(Mt.CONFIG_PARAMS.STORAGE_PATH)||e&&((0,nn.existsSync)(e)?e:(0,nt.join)((0,mt.getHdbBasePath)(),Mt.LEGACY_DATABASES_DIR_NAME)),!!e){if((0,nn.existsSync)(e))for(let r of(0,nn.readdirSync)(e,{withFileTypes:!0})){let n=(0,nt.basename)(r.name,".mdb");r.isFile()&&(0,nt.extname)(r.name).toLowerCase()===".mdb"&&!t[n]?.path&&Fl((0,nt.join)(e,r.name),null,n)}if((0,nn.existsSync)((0,sc.getBaseSchemaPath)())){for(let r of(0,nn.readdirSync)((0,sc.getBaseSchemaPath)(),{withFileTypes:!0}))if(!r.isFile()){let n=(0,nt.join)((0,sc.getBaseSchemaPath)(),r.name),s=(0,nt.join)((0,sc.getTransactionAuditStoreBasePath)(),r.name);for(let i of(0,nn.readdirSync)(n,{withFileTypes:!0}))if(i.isFile()&&(0,nt.extname)(i.name).toLowerCase()===".mdb"){let o=(0,nt.join)(s,i.name);Fl((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,nn.existsSync)(s))for(let o of(0,nn.readdirSync)(s,{withFileTypes:!0}))o.isFile()&&(0,nt.extname)(o.name).toLowerCase()===".mdb"&&Fl((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],u=(0,nt.join)(c.path,(0,nt.basename)(o+".mdb"));(0,nn.existsSync)(u)&&Fl(u,o,r,null,!0)}}for(let r in it){let n=ic.get(r);if(n){let s=it[r];r.includes("delete")&&An.trace(`defined tables ${Array.from(n.keys())}`);for(let i in s)n.has(i)||(An.trace(`delete table class ${i}`),delete s[i])}else if(delete it[r],r==="data"){for(let s in Br)delete Br[s];delete Br[Eh]}}return ic=null,it}}function Fu(){dh=!1;for(let[,e]of Ui)e.needsDeletion=!0;hr();for(let[e,t]of Ui)t.needsDeletion&&!e.endsWith("system.mdb")&&(t.close(),Ui.delete(e));return it}function Fl(e,t,r=KA,n,s){let i=new $A.default(e,!1);try{let o=Ui.get(e);o?o.needsDeletion=!1:(o=(0,uh.open)(i),Ui.set(e,o));let c=new Ho.default(!1),u=o.dbisDb||(o.dbisDb=o.openDB(ch.INTERNAL_DBIS_NAME,c)),_=o.auditStore;_||(n?(0,nn.existsSync)(n)&&(i.path=n,_=(0,uh.open)(i),_.isLegacy=!0):_=WE(o));let l=NG(r),d=l[Eh],E=new Map;for(let{key:f,value:h}of u.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 z of p)if(z.is_hash_attribute||z.isPrimaryKey){S=z;break}if(!S){An.fatal(`Unable to find a primary key attribute on table ${f}, with attributes: ${JSON.stringify(p)}`);continue}}let T=l[f],A={},R=[],C,x,v=typeof S.audit=="boolean"?S.audit:(0,mt.get)(Mt.CONFIG_PARAMS.LOGGING_AUDITLOG),k=S.trackDeletes,M=S.expiration,Q=S.eviction,j=S.sealed;if(T)A=T.indices,R=T.attributes,T.schemaVersion++;else{C=S.tableId,C?C>=(u.get(nc)||0)&&u.putSync(nc,C+1):(S.tableId=C=u.get(nc),C||(C=1),u.putSync(nc,C+1),u.putSync(S.key,S));let z=new Ho.default(!S.is_hash_attribute,S.is_hash_attribute);if(z.compression=S.compression,z.compression){let ae=(0,mt.get)(Mt.CONFIG_PARAMS.STORAGE_COMPRESSION_THRESHOLD)||yG;z.compression.threshold=ae}x=p_(o.openDB(S.key,z)),x.rootStore=o,x.tableId=C}for(let z of p){z.attribute=z.name;try{if(!z.is_hash_attribute&&(z.indexed||z.attribute&&!z.name)){if(!A[z.name]){let ue=new Ho.default(!z.is_hash_attribute,z.is_hash_attribute);A[z.name]=o.openDB(z.key,ue),A[z.name].indexNulls=z.indexNulls}let ae=R.find(ue=>ue.name===z.name);ae?R.splice(R.indexOf(ae),1,z):R.push(z)}}catch(ae){An.error("Error trying to update attribute",z,R,A,ae)}}if(!T){T=IG(l,f,ah({primaryStore:x,auditStore:_,audit:v,sealed:j,expirationMS:M&&M*1e3,evictionMS:Q&&Q*1e3,trackDeletes:k,tableName:f,tableId:C,primaryKey:S.name,databasePath:s?r+"/"+f:r,databaseName:r,indices:A,attributes:p,schemaDefined:S.schemaDefined,dbisDB:u})),T.schemaVersion=1;for(let z of WA)z(T)}}return o}catch(o){throw o.message+=` opening database ${e}`,o}}function NG(e){let t=it[e];if(t||(e==="data"?t=it[e]=Br:e==="system"?Object.defineProperty(it,"system",{value:t=Object.create(null),configurable:!0}):t=it[e]=Object.create(null)),ic&&!ic.has(e)){let r=new Set;t[Eh]=r,ic.set(e,r)}return t}function IG(e,t,r){return e[t]=r,r}function nu({database:e,table:t}){e||(e=KA),hr();let r=NG(e),n=(0,nt.join)((0,mt.getHdbBasePath)(),Mt.DATABASES_DIR_NAME),s=(0,mt.get)(Mt.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,mt.get)(Mt.CONFIG_PARAMS.STORAGE_PATH)||((0,nn.existsSync)(n)?n:(0,nt.join)((0,mt.getHdbBasePath)(),Mt.LEGACY_DATABASES_DIR_NAME));let o=(0,nt.join)(n,(i?t:e)+".mdb"),c=Ui.get(o);if(!c){let u=new $A.default(o,!1);c=(0,uh.open)(u),Ui.set(o,c)}return c}async function dS(e){if(!it[e])throw new Error("Schema does not exist");let t=it[e];for(let r in t){let s=t[r].primaryStore.rootStore;Ui.delete(s.path),s.status==="open"&&(await s.close(),await fh.remove(s.path))}if(e==="data"){for(let r in Br)delete Br[r];delete Br[Eh]}delete it[e]}function dt({table:e,database:t,expiration:r,eviction:n,scanInterval:s,attributes:i,audit:o,sealed:c,trackDeletes:u,schemaDefined:_,origin:l}){t||(t=KA);let d=nu({database:t,table:e}),E=it[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 A=new Ho.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 R,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=WE(d)),p=i.find(ae=>ae.isPrimaryKey)||{},h=p.name,p.is_hash_attribute=!0,p.schemaDefined=_,p.compression=Sf(),u&&(p.trackDeletes=!0),o=p.audit=typeof o=="boolean"?o:(0,mt.get)(Mt.CONFIG_PARAMS.LOGGING_AUDITLOG),r&&(p.expiration=r),n&&(p.eviction=n),typeof c=="boolean"&&(p.sealed=c),l&&(p.origins?p.origins.includes(l)||p.origins.push(l):p.origins=[l]),An.trace(`${e} table loading, opening primary store`);let Q=new Ho.default(!1,!0);Q.compression=p.compression;let j=e+"/",z=p_(d.openDB(j,Q));z.rootStore=d,T=d.dbisDb=d.openDB(ch.INTERNAL_DBIS_NAME,A),z.tableId=T.get(nc),z.tableId||(z.tableId=1),T.putSync(nc,z.tableId+1),p.tableId=z.tableId,f=IG(E,e,ah({primaryStore:z,auditStore:M,audit:o,sealed:c,trackDeletes:u,expirationMS:r&&r*1e3,evictionMS:n&&n*1e3,primaryKey:h,tableName:e,tableId:z.tableId,databasePath:t,databaseName:t,indices:{},attributes:i,schemaDefined:_,dbisDB:T})),f.schemaVersion=1,R=!0,k(),T.put(j,p)}S=f.indices,T=T||(d.dbisDb=d.openDB(ch.INTERNAL_DBIS_NAME,A)),f.dbisDB=T;let x=[];for(let{key:M,value:Q}of T.getRange({start:!0})){let[j,z]=M.toString().split("/");if(z===""&&(z=Q.name),z){if(j!==e)continue}else z=j;if(!i.find(ue=>ue.name===z)?.indexed&&Q.indexed&&!Q.isPrimaryKey){k(),R=!0,T.remove(M);let ue=f.indices[j];ue&&x.push(ue)}}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),R=!0,k(),T.put(Q,ae)}continue}j?.attribute&&!j.name&&(j.indexed=!0);let z=!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 Ho.default(!0,!1),ue=d.openDB(Q,ae);(z||j.indexingPID&&j.indexingPID!==process.pid||j.restartNumber<kl.workerData?.restartNumber)&&(R=!0,k(),j=T.get(Q),(z||j.indexingPID&&j.indexingPID!==process.pid||j.restartNumber<kl.workerData?.restartNumber)&&(R=!0,M.indexNulls===void 0&&(M.indexNulls=!0),f.primaryStore.getStats().entryCount>0&&(M.lastIndexedKey=j?.lastIndexedKey||!1,M.indexingPID=process.pid,ue.isIndexing=!0,Object.defineProperty(M,"dbi",{value:ue}),v.push(M))),T.put(Q,M)),j?.indexNulls&&M.indexNulls===void 0&&(M.indexNulls=!0),ue.indexNulls=M.indexNulls,S[M.name]=ue}else z&&(R=!0,k(),T.put(Q,M))}}finally{C&&C()}if(R&&(f.schemaVersion++,f.updatedAttributes()),An.trace(`${e} table loading, running index`),v.length>0||x.length>0?f.indexingOperation=Qie(f,v,x):R&&lh.signalSchemaChange(new _h.SchemaEventMsg(process.pid,"schema-change",f.databaseName,f.tableName)),f.origin=l,R)for(let M of WA)M(f,l!=="cluster");return(r||n||s)&&f.setTTLExpiration({expiration:r,eviction:n,scanInterval:s}),An.trace(`${e} table loaded`),f;function k(){C||d.transactionSync(()=>({then(M){C=M}}))}a(k,"startTxn")}async function Qie(e,t,r){try{let n=e.schemaVersion;await lh.signalSchemaChange(new _h.SchemaEventMsg(process.pid,"schema-change",e.databaseName,e.tableName));let s;for(let u of r)s=u.drop();let i,o=0,c=t.length;if(await new Promise(u=>setImmediate(u)),c>0){let u=0;for(let{key:_,value:l,version:d}of e.primaryStore.getRange({start:t[0].lastIndexedKey,lazy:c<4,versions:!0,snapshot:!1}))if(l){if(u++,s=e.primaryStore.ifVersion(_,d,()=>{for(let E=0;E<c;E++){let f=t[E],h=f.name,p=(0,OG.getIndexedValues)(l[h]);if(p)for(let S=0,T=p.length;S<T;S++)f.dbi.put(p[S],_)}}),s.then(()=>u--,E=>{u--,An.error(E)}),kl.workerData&&kl.workerData.restartNumber!==bG.restartNumber&&(i=!0),++o%100===0||i){for(let E of t)E.lastIndexedKey=_,e.dbisDB.put(E.key,E);if(i)return}u>Kie?await s:u>Wie&&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 lh.signalSchemaChange(new _h.SchemaEventMsg(process.pid,"indexing-finished",e.databaseName,e.tableName))}catch(n){An.error("Error in indexing",n)}}function zie({table:e,database:t}){let r=nu({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 XR(e){WA.push(e)}function Sf(){let e=(0,mt.get)(Mt.CONFIG_PARAMS.STORAGE_COMPRESSION),t=(0,mt.get)(Mt.CONFIG_PARAMS.STORAGE_COMPRESSION_DICTIONARY),r=(0,mt.get)(Mt.CONFIG_PARAMS.STORAGE_COMPRESSION_THRESHOLD)||yG,n={startingOffset:32};return t&&(n.dictionary=fh.readFileSync(t)),r&&(n.threshold=r),e&&n}var mt,ch,uh,nt,nn,sc,Ho,$A,Mt,fh,YA,OG,lh,_h,kl,An,bG,KA,Eh,yG,Br,it,nc,WA,dh,Ui,ic,Kie,Wie,Oe=Ae(()=>{mt=B(Z()),ch=B(_t()),uh=require("lmdb"),nt=require("path"),nn=require("fs"),sc=B(ze());_E();Ho=B(Dc()),$A=B(Lc()),Mt=B(P()),fh=B(require("fs-extra")),YA=require("../index"),OG=B(vr()),lh=B(bs()),_h=B(Mn()),kl=require("worker_threads"),An=B($()),bG=B(Je());ti();Cc();KA="data",Eh=Symbol("defined-tables"),yG=((0,mt.get)(Mt.CONFIG_PARAMS.STORAGE_PAGESIZE)||4096)-60;(0,mt.initSync)();Br=Object.create(null),it=Object.create(null);(0,YA._assignPackageExport)("databases",it);(0,YA._assignPackageExport)("tables",Br);nc=Symbol.for("next-table-id"),WA=[],Ui=new Map;a(Yie,"getTables");a(hr,"getDatabases");a(Fu,"resetDatabases");a(Fl,"readMetaDb");a(NG,"ensureDB");a(IG,"setTable");a(nu,"database");a(dS,"dropDatabase");a(dt,"table");Kie=1e3,Wie=10;a(Qie,"runIndexing");a(zie,"dropTableMeta");a(XR,"onUpdatedTable");a(Sf,"getDefaultCompression")});var J=g((STe,FG)=>{"use strict";var vi=require("path"),MG=require("fs-extra"),Mr=$(),wG=require("fs-extra"),hh=require("os"),Jie=require("net"),jie=require("recursive-iterator"),lt=P(),Xie=VO(),CG=require("papaparse"),mh=require("moment"),{inspect:Zie}=require("util"),DG=require("is-number"),pTe=require("lodash"),eoe=require("minimist"),toe=require("https"),roe=require("http"),{hdb_errors:ph}=ne(),noe=/^((\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)))$/,PG=require("util").promisify(setTimeout),soe=100,ioe=5,ooe="",aoe=4,LG={true:!0,TRUE:!0,FALSE:!1,false:!1,undefined:null,null:null,NULL:null,NaN:NaN};FG.exports={isEmpty:sn,isEmptyOrZeroLength:hs,arrayHasEmptyValues:loe,arrayHasEmptyOrZeroLengthValues:_oe,buildFolderPath:doe,isBoolean:UG,errorizeMessage:coe,stripFileExtension:Eoe,autoCast:hoe,autoCastJSON:vG,autoCastJSONDeep:zA,removeDir:moe,compareVersions:poe,isCompatibleDataVersion:Soe,escapeRawValue:Toe,unescapeValue:goe,stringifyProps:Roe,timeoutPromise:Ooe,isClusterOperation:yoe,getClusterUser:Ioe,checkGlobalSchemaTable:Noe,getHomeDir:HG,getPropsFilePath:Aoe,promisifyPapaParse:woe,removeBOM:xG,createEventPromise:Coe,checkProcessRunning:Doe,checkSchemaTableExist:Loe,checkSchemaExists:GG,checkTableExists:qG,getStartOfTomorrowInSeconds:Moe,getLimitKey:Poe,isObject:foe,isNotEmptyAndHasValue:uoe,autoCasterIsNumberCheck:BG,backtickASTSchemaItems:Uoe,isPortTaken:boe,createForkArgs:voe,autoCastBoolean:Boe,async_set_timeout:PG,getTableHashAttribute:Hoe,doesSchemaExist:xoe,doesTableExist:Goe,stringifyObj:qoe,ms_to_time:Foe,changeExtension:koe,getEnvCliRootPath:JA,noBootFile:Voe,httpRequest:$oe,transformReq:Yoe,convertToMS:Koe,PACKAGE_ROOT:lt.PACKAGE_ROOT};function coe(e){return e instanceof Error?e:new Error(e)}a(coe,"errorizeMessage");function sn(e){return e==null}a(sn,"isEmpty");function uoe(e){return!sn(e)&&(e||e===0||e===""||UG(e))}a(uoe,"isNotEmptyAndHasValue");function hs(e){return sn(e)||e.length===0||e.size===0}a(hs,"isEmptyOrZeroLength");function loe(e){if(sn(e))return!0;for(let t=0;t<e.length;t++)if(sn(e[t]))return!0;return!1}a(loe,"arrayHasEmptyValues");function _oe(e){if(hs(e))return!0;for(let t=0;t<e.length;t++)if(hs(e[t]))return!0;return!1}a(_oe,"arrayHasEmptyOrZeroLengthValues");function doe(...e){try{return e.join(vi.sep)}catch{console.error(e)}}a(doe,"buildFolderPath");function UG(e){return sn(e)?!1:e===!0||e===!1}a(UG,"isBoolean");function foe(e){return sn(e)?!1:typeof e=="object"}a(foe,"isObject");function Eoe(e){return hs(e)?ooe:e.slice(0,-aoe)}a(Eoe,"stripFileExtension");function hoe(e){return sn(e)||e===""||typeof e!="string"?e:LG[e]!==void 0?LG[e]:BG(e)===!0?Number(e):noe.test(e)?new Date(e):e}a(hoe,"autoCast");function vG(e){if(typeof e=="string"&&(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")))try{return JSON.parse(e)}catch{}return e}a(vG,"autoCastJSON");function zA(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=zA(n);s!==n&&(e[t]=s)}else for(let t in e){let r=e[t],n=zA(r);n!==r&&(e[t]=n)}return e}else return vG(e)}a(zA,"autoCastJSONDeep");function BG(e){if(e.startsWith("0.")&&DG(e))return!0;let t=e.toUpperCase().includes("E");return!!((e!=="0"&&e.startsWith("0"))===!1&&t===!1&&DG(e))}a(BG,"autoCasterIsNumberCheck");async function moe(e){if(hs(e))throw new Error(`Directory path: ${e} does not exist`);try{await wG.emptyDir(e),await wG.remove(e)}catch(t){throw Mr.error(`Error removing files in ${e} -- ${t}`),t}}a(moe,"removeDir");function poe(e,t){if(hs(e)){Mr.info("Invalid current version sent as parameter.");return}if(hs(t)){Mr.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("."),u=Math.min(o.length,c.length);for(let _=0;_<u;_++)if(r=parseInt(o[_],10)-parseInt(c[_],10),r)return r;return o.length-c.length}a(poe,"compareVersions");function Soe(e,t,r=!1){let n=e.toString().split("."),s=t.toString().split(".");return n[0]===s[0]&&(!r||n[1]===s[1])}a(Soe,"isCompatibleDataVersion");function Toe(e){if(sn(e))return e;let t=String(e);return t==="."?lt.UNICODE_PERIOD:t===".."?lt.UNICODE_PERIOD+lt.UNICODE_PERIOD:t.replace(lt.FORWARD_SLASH_REGEX,lt.UNICODE_FORWARD_SLASH)}a(Toe,"escapeRawValue");function goe(e){if(sn(e))return e;let t=String(e);return t===lt.UNICODE_PERIOD?".":t===lt.UNICODE_PERIOD+lt.UNICODE_PERIOD?"..":String(e).replace(lt.ESCAPED_FORWARD_SLASH_REGEX,"/")}a(goe,"unescapeValue");function Roe(e,t){if(sn(e))return Mr.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+hh.EOL}!hs(n)&&n[0]===";"?r+=" "+n+s+hh.EOL:hs(n)||(r+=n+"="+s+hh.EOL)}catch{Mr.error(`Found bad property during upgrade with key ${n} and value: ${s}`)}}),r}a(Roe,"stringifyProps");function HG(){let e;try{e=hh.homedir()}catch{e=process.env.HOME}return e||(e="~/"),e}a(HG,"getHomeDir");function Aoe(){let e=vi.join(HG(),lt.HDB_HOME_DIR_NAME,lt.BOOT_PROPS_FILE_NAME);return MG.existsSync(e)||(e=vi.join(__dirname,"../","hdb_boot_properties.file")),e}a(Aoe,"getPropsFilePath");function Ooe(e,t){let r,n;return n=new Promise(function(s){r=setTimeout(function(){s(t)},e)}),{promise:n,cancel:function(){clearTimeout(r)}}}a(Ooe,"timeoutPromise");async function boe(e){if(!e)throw new Error("Invalid port passed as parameter");return new Promise((t,r)=>{let n=Jie.createServer().once("error",s=>{s.code==="EADDRINUSE"?t(!0):r(s)}).once("listening",()=>n.once("close",()=>t(!1)).close()).listen(e)})}a(boe,"isPortTaken");function yoe(e){try{return lt.CLUSTER_OPERATIONS[e.toLowerCase()]!==void 0}catch(t){Mr.error(`Error checking operation against cluster ops ${t}`)}return!1}a(yoe,"isClusterOperation");function Noe(e,t){let r=(Oe(),ie(Fe)).getDatabases();if(!r[e])return ph.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e);if(!r[e][t])return ph.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(Noe,"checkGlobalSchemaTable");function Ioe(e,t){if(sn(t)){Mr.warn("No CLUSTERING_USER defined, clustering disabled");return}if(sn(e)||hs(e)){Mr.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){Mr.error(`unable to find cluster_user due to: ${n.message}`);return}if(r===void 0){Mr.warn(`CLUSTERING_USER: ${t} not found or is not active.`);return}return r}a(Ioe,"getClusterUser");function woe(){CG.parsePromise=function(e,t,r){return new Promise(function(n,s){CG.parse(e,{header:!0,transformHeader:xG,chunk:t.bind(null,s),skipEmptyLines:!0,transform:r,dynamicTyping:!1,error:s,complete:n})})}}a(woe,"promisifyPapaParse");function xG(e){if(typeof e!="string")throw new TypeError(`Expected a string, got ${typeof e}`);return e.charCodeAt(0)===65279?e.slice(1):e}a(xG,"removeBOM");function Coe(e,t,r){return new Promise(n=>{t.once(e,s=>{let i=r;Mr.info(`Got cluster status event response: ${Zie(s)}`);try{i.cancel()}catch{Mr.error("Error trying to cancel timeout.")}n(s)})})}a(Coe,"createEventPromise");async function Doe(e){let t=!0,r=0;do await PG(soe*r++),(await Xie.findPs(e)).length>0&&(t=!1);while(t&&r<ioe);if(t)throw new Error(`process ${e} was not started`)}a(Doe,"checkProcessRunning");function Loe(e,t){let r=GG(e);if(r)return r;let n=qG(e,t);if(n)return n}a(Loe,"checkSchemaTableExist");function GG(e){let{getDatabases:t}=(Oe(),ie(Fe));if(!t()[e])return ph.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}a(GG,"checkSchemaExists");function qG(e,t){let{getDatabases:r}=(Oe(),ie(Fe));if(!r()[e][t])return ph.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(qG,"checkTableExists");function Moe(){let e=mh().utc().add(1,lt.MOMENT_DAYS_TAG).startOf(lt.MOMENT_DAYS_TAG).unix(),t=mh().utc().unix();return e-t}a(Moe,"getStartOfTomorrowInSeconds");function Poe(){return mh().utc().format("DD-MM-YYYY")}a(Poe,"getLimitKey");function Uoe(e){try{let t=new jie(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){Mr.error("Got an error back ticking items."),Mr.error(t)}}a(Uoe,"backtickASTSchemaItems");function voe(e){return[e]}a(voe,"createForkArgs");function Boe(e){return e===!0||typeof e=="string"&&e.toLowerCase()==="true"}a(Boe,"autoCastBoolean");function Hoe(e,t){let{getDatabases:r}=(Oe(),ie(Fe)),n=r()[e]?.[t];return n?.primaryKey||n?.hash_attribute}a(Hoe,"getTableHashAttribute");function xoe(e){let{getDatabases:t}=(Oe(),ie(Fe));return t()[e]!==void 0}a(xoe,"doesSchemaExist");function Goe(e,t){let{getDatabases:r}=(Oe(),ie(Fe));return r()[e]?.[t]!==void 0}a(Goe,"doesTableExist");function qoe(e){try{return JSON.stringify(e)}catch{return e}}a(qoe,"stringifyObj");function Foe(e){let t=mh.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(Foe,"ms_to_time");function koe(e,t){let r=vi.basename(e,vi.extname(e));return vi.join(vi.dirname(e),r+t)}a(koe,"changeExtension");function JA(){if(process.env[lt.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return process.env[lt.CONFIG_PARAMS.ROOTPATH.toUpperCase()];let e=eoe(process.argv);if(e[lt.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return e[lt.CONFIG_PARAMS.ROOTPATH.toUpperCase()]}a(JA,"getEnvCliRootPath");var QA;function Voe(){if(QA)return QA;let e=JA();if(JA()&&MG.pathExistsSync(vi.join(e,lt.HDB_CONFIG_FILE)))return QA=!0,!0}a(Voe,"noBootFile");function $oe(e,t){let r;return e.protocol==="http:"?r=roe:r=toe,new Promise((n,s)=>{let i=r.request(e,o=>{o.setEncoding("utf8");let c={body:"",headers:o.headers};o.on("data",u=>{c.body+=u}),o.on("end",()=>{n(c)})});i.on("error",o=>{s(o)}),i.write(JSON.stringify(t)),i.end()})}a($oe,"httpRequest");function Yoe(e){if(!e.schema&&!e.database){e.schema=lt.DEFAULT_DATABASE_NAME;return}e.database&&(e.schema=e.database)}a(Yoe,"transformReq");function Koe(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(Koe,"convertToMS")});var Z=g((gTe,KG)=>{"use strict";var jA=require("fs-extra"),xo=require("path"),kG=require("os"),Woe=require("properties-reader"),$l=$(),Vl=J(),le=P(),Sh=fr(),Qoe="Error initializing environment manager",Th="BOOT_PROPS_FILE_PATH",VG=!1,zoe={[le.HDB_SETTINGS_NAMES.INSTALL_USER]:!0,[le.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY]:!0,[le.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]:!0,BOOT_PROPS_FILE_PATH:!0},Ws={};KG.exports={BOOT_PROPS_FILE_PATH:Th,getHdbBasePath:Joe,setHdbBasePath:joe,get:$G,initSync:Zoe,setProperty:Me,initTestEnvironment:tae,setCloneVar:eae};function Joe(){return Ws[le.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]}a(Joe,"getHdbBasePath");function joe(e){Ws[le.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=e}a(joe,"setHdbBasePath");function $G(e){let t=Sh.getConfigValue(e);return t===void 0?Ws[e]:t}a($G,"get");function Me(e,t){zoe[e]&&(Ws[e]=t),Sh.updateConfigObject(e,t)}a(Me,"setProperty");function Xoe(){let e;try{e=Vl.getPropsFilePath(),jA.accessSync(e,jA.constants.F_OK|jA.constants.R_OK),VG=!0;let t=Woe(e);return Ws[le.HDB_SETTINGS_NAMES.INSTALL_USER]=t.get(le.HDB_SETTINGS_NAMES.INSTALL_USER),Ws[le.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY]=t.get(le.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY),Ws[Th]=e,!0}catch{return $l.trace(`Environment manager found no properties file at ${e}`),!1}}a(Xoe,"doesPropFileExist");function Zoe(e=!1){try{(VG||Xoe()||Vl.noBootFile())&&!YG&&(Sh.initConfig(e),Ws[le.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=Sh.getConfigValue(le.HDB_SETTINGS_NAMES.HDB_ROOT_KEY))}catch(t){$l.error(Qoe),$l.error(t),console.error(t),process.exit(1)}}a(Zoe,"initSync");var YG=!1;function eae(e){YG=e}a(eae,"setCloneVar");function tae(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,u=xo.join(__dirname,"../../","unitTests");Ws[Th]=xo.join(u,"hdb_boot_properties.file"),Me(le.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY,xo.join(u,"settings.test")),Me(le.HDB_SETTINGS_NAMES.INSTALL_USER,kG.userInfo()?kG.userInfo().username:void 0),Me(le.HDB_SETTINGS_NAMES.LOG_LEVEL_KEY,"debug"),Me(le.HDB_SETTINGS_NAMES.LOG_PATH_KEY,xo.join(u,"envDir","log")),Me(le.HDB_SETTINGS_NAMES.LOG_DAILY_ROTATE_KEY,!1),Me(le.HDB_SETTINGS_NAMES.CLUSTERING_ENABLED_KEY,!0),Me(le.HDB_SETTINGS_NAMES.CLUSTERING_NODE_NAME_KEY,"1231412de213"),Me(le.HDB_SETTINGS_NAMES.HDB_ROOT_KEY,xo.join(u,"envDir")),Me(le.CONFIG_PARAMS.STORAGE_PATH,xo.join(u,"envDir")),s&&(Me(le.CONFIG_PARAMS.HTTP_SECUREPORT,$G(le.CONFIG_PARAMS.HTTP_PORT)),Me(le.CONFIG_PARAMS.HTTP_PORT,null)),Me(le.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HTTPS,!!s),Me(le.HDB_SETTINGS_NAMES.SERVER_PORT_KEY,9925),Me(le.HDB_SETTINGS_NAMES.CORS_ENABLED_KEY,Vl.isEmpty(i)?!1:i),Me(le.CONFIG_PARAMS.HTTP_CORS,Vl.isEmpty(i)?!1:i),Me(le.HDB_SETTINGS_NAMES.MAX_CUSTOM_FUNCTION_PROCESSES,2),Me(le.HDB_SETTINGS_NAMES.MAX_HDB_PROCESSES,4),Me(le.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_PORT_KEY,9926),Me(le.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_ENABLED_KEY,!0),Me(le.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY,xo.resolve(__dirname,"../../unitTests/server/fastifyRoutes/custom_functions")),Me(le.HDB_SETTINGS_NAMES.LOCAL_STUDIO_ON,Vl.isEmpty(c)?!1:c),o&&(Me("CORS_ACCESSLIST",o),Me(le.CONFIG_PARAMS.HTTP_CORSACCESSLIST,o)),n&&(Me(le.HDB_SETTINGS_NAMES.SERVER_TIMEOUT_KEY,n),Me(le.CONFIG_PARAMS.HTTP_TIMEOUT,n)),t&&(Me(le.HDB_SETTINGS_NAMES.SERVER_KEEP_ALIVE_TIMEOUT_KEY,t),Me(le.CONFIG_PARAMS.HTTP_KEEPALIVETIMEOUT,t)),r&&(Me(le.HDB_SETTINGS_NAMES.SERVER_HEADERS_TIMEOUT_KEY,r),Me(le.CONFIG_PARAMS.HTTP_HEADERSTIMEOUT,r))}catch(t){let r=`Error reading in HDB environment variables from path ${Th}. Please check your boot props and settings files`;$l.fatal(r),$l.error(t)}}a(tae,"initTestEnvironment")});var jG=g((ATe,JG)=>{"use strict";var zG=require("joi"),{string:Yl,boolean:WG,array:rae}=zG.types(),QG=P(),nae=je();JG.exports=sae;function sae(e){let t=zG.object({operation:Yl.valid(QG.OPERATIONS_ENUM.ADD_NODE,QG.OPERATIONS_ENUM.UPDATE_NODE).required(),node_name:Yl.required(),subscriptions:rae.items({schema:Yl.required(),table:Yl.optional(),hash_attribute:Yl.optional(),subscribe:WG.required(),publish:WG.required()}).min(1).required()});return nae.validateBySchema(e,t)}a(sae,"updateRemoteSourceValidator")});var Kl=g((bTe,XG)=>{"use strict";var XA=class{static{a(this,"UpdateRemoteResponseObject")}constructor(t,r,n=void 0){this.status=t,this.message=r,this.system_info=n}};XG.exports=XA});var rq=g((NTe,tq)=>{"use strict";var iae=jG(),Qs=$(),ZA=ke(),oae=P(),eO=dn(),Go=ot(),ZG=Tu(),aae=cd(),{Node:cae,NodeSubscription:eq}=pi(),tO=Kl(),rO=J(),uae=Z(),{cloneDeep:lae}=require("lodash"),{broadcast:_ae}=Je();tq.exports=dae;async function dae(e){try{let t=iae(e);if(t)return Qs.error(`Validation error in updateRemoteSource: ${t.message}`),new tO(ZA.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,t.message);let{subscriptions:r,node_name:n,system_info:s}=e,i=[],o=lae(await eO.getNodeRecord(n)),c=!rO.isEmptyOrZeroLength(o);o=c?o[0]:o,c&&Qs.trace(`Existing record found for ${n}, updating records subscriptions`);for(let _=0,l=r.length;_<l;_++){let d=r[_],E=d.schema,f=d.table;if(!rO.doesSchemaExist(E)){Qs.trace(`updateRemoteSource creating schema: ${E}`);try{await ZG.createSchema({operation:"create_schema",schema:E})}catch(h){Qs.error(h)}}if(f&&!rO.doesTableExist(E,f)){let h=new aae(E,f,d.hash_attribute);d.attributes&&(h.attributes=d.attributes),Qs.trace(`updateRemoteSource creating table: ${f} in schema: ${E} with attributes: ${JSON.stringify(d.attributes)}`);try{await ZG.createTable(h)}catch(p){Qs.error(p)}}if(Qs.trace(`Creating local stream for ${E}.${f}`),await Go.createLocalTableStream(E,f),c?(await Go.updateConsumerIterator(E,f,n,"stop"),await Go.updateRemoteConsumer(d,n),d.subscribe===!0&&await Go.updateConsumerIterator(E,f,n,"start")):(await Go.updateRemoteConsumer(d,n),d.subscribe===!0?await Go.updateConsumerIterator(E,f,n,"start"):await Go.updateConsumerIterator(E,f,n,"stop")),c){let h=!1;for(let p=0,S=o.subscriptions.length;p<S;p++){let T=o.subscriptions[p];if(T.schema===E&&T.table===f){T.publish=d.publish,T.subscribe=d.subscribe,h=!0;break}}h||o.subscriptions.push(new eq(E,f,d.publish,d.subscribe))}else i.push(new eq(E,f,d.publish,d.subscribe))}c||(o=new cae(n,i,void 0),Qs.trace(`No record found for ${n}, creating a new one`));let u=Object.create({});return Object.assign(u,o),u.system_info=s,await eO.upsertNodeRecord(u),_ae({type:"nats_update"}),new tO(ZA.UPDATE_REMOTE_RESPONSE_STATUSES.SUCCESS,`Node ${uae.get(oae.CONFIG_PARAMS.CLUSTERING_NODENAME)} successfully updated remote source`,await eO.getSystemInfo())}catch(t){Qs.error(t);let r=t.message?t.message:t;return new tO(ZA.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,r)}}a(dae,"updateRemoteSource")});var oq=g((wTe,iq)=>{"use strict";var sq=require("joi"),{string:nq}=sq.types(),fae=P(),Eae=je();iq.exports=hae;function hae(e){let t=sq.object({operation:nq.valid(fae.OPERATIONS_ENUM.REMOVE_NODE).required(),node_name:nq.required()});return Eae.validateBySchema(e,t)}a(hae,"removeRemoteSourceValidator")});var uq=g((DTe,cq)=>{"use strict";var mae=oq(),gh=$(),Rh=ke(),nO=P(),pae=dn(),Sae=J(),aq=ot(),Tae=Z(),Ah=Kl(),{NodeSubscription:gae}=pi(),Rae=oa(),Aae=oi(),{broadcast:Oae}=Je(),bae=Tae.get(nO.CONFIG_PARAMS.CLUSTERING_NODENAME);cq.exports=yae;async function yae(e){try{let t=mae(e);if(t)return gh.error(`Validation error in removeRemoteSource: ${t.message}`),new Ah(Rh.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,t.message);let r=e.node_name,n=await pae.getNodeRecord(r);if(Sae.isEmptyOrZeroLength(n)){let i=`No record found for node '${r}'`;return gh.error(i),new Ah(Rh.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,i)}n=n[0];for(let i=0,o=n.subscriptions.length;i<o;i++){let c=n.subscriptions[i];gh.trace(`remove remote source removing subscription: ${c.schema}.${c.table} for node: ${r}`);let u=new gae(c.schema,c.table,!1,!1);await aq.updateConsumerIterator(c.schema,c.table,r,"stop"),await aq.updateRemoteConsumer(u,r)}let s=new Rae(nO.SYSTEM_SCHEMA_NAME,nO.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[r]);return await Aae.deleteRecord(s),Oae({type:"nats_update"}),new Ah(Rh.UPDATE_REMOTE_RESPONSE_STATUSES.SUCCESS,`Node ${bae} successfully removed node '${r}'.`)}catch(t){gh.error(t);let r=t.message?t.message:t;return new Ah(Rh.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,r)}}a(yae,"removeRemoteSource")});var fq=g((MTe,dq)=>{"use strict";var Oh=$(),Wl=P(),lq=ke(),sO=Z(),Nae=J(),_q=Kl(),Iae=dn(),wae=Gd(),Cae=qr();dq.exports=Dae;async function Dae(e){try{Oh.trace("getRemoteSourceConfig called");let t=process.uptime()*1e3,r=Nae.ms_to_time(t),n=new Lae(sO.get(Wl.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),sO.get(Wl.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_PORT)??sO.get(Wl.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_SECUREPORT),r,await Iae.getSystemInfo());try{let s={name:e.node_name,system_info:e.system_info},i=new wae(Wl.SYSTEM_SCHEMA_NAME,Wl.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[s]);await Cae.update(i)}catch(s){Oh.error("Get remote config encountered an error updating system info for node:",e.node_name,s)}return Oh.trace("getRemoteSourceConfig response:",n),new _q(lq.UPDATE_REMOTE_RESPONSE_STATUSES.SUCCESS,n)}catch(t){Oh.error(t);let r=t.message?t.message:t;return new _q(lq.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,r)}}a(Dae,"getRemoteSourceConfig");function Lae(e,t,r,n){this.uptime=r,this.ports={clustering:e,operations_api:t},this.system_info=n}a(Lae,"ConfigResponseObject")});var pq=g((UTe,mq)=>{"use strict";var Eq=Z();Eq.initSync();var hq=ot(),Ql=$(),oc=P(),iO=ke(),Mae=rq(),Pae=uq(),Uae=fq(),vae=Kl(),{encode:Bae,decode:Hae}=require("msgpackr"),xae=Os(),Gae=As(),qae=require("util"),Fae=P(),{isMainThread:kae,parentPort:Vae}=require("worker_threads");Je();var $ae=qae.promisify(xae.setSchemaDataToGlobal),oO=Eq.get(oc.CONFIG_PARAMS.CLUSTERING_NODENAME);mq.exports=Yae;async function Yae(){try{Ql.notify("Starting reply service."),await $ae();let e=await hq.getConnection(),t=`${oO}.__request__`,r=e.subscribe(t,{queue:oO});await Kae(r)}catch(e){Ql.error(e)}}a(Yae,"initialize");async function Kae(e){for await(let t of e){let r=Hae(t.data),n;switch(r.operation){case oc.OPERATIONS_ENUM.ADD_NODE:case oc.OPERATIONS_ENUM.UPDATE_NODE:n=await Mae(r);break;case oc.OPERATIONS_ENUM.REMOVE_NODE:n=await Pae(r);break;case oc.OPERATIONS_ENUM.CLUSTER_STATUS:n=await Uae(r);break;case oc.OPERATIONS_ENUM.DESCRIBE_ALL:n=await Wae();break;default:let s=`node '${oO}' reply service received unrecognized request operation`;Ql.error(s),n=new vae(iO.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,s)}Ql.trace(n),t.respond(Bae(n))}}a(Kae,"handleRequest");async function Wae(){try{return{status:iO.UPDATE_REMOTE_RESPONSE_STATUSES.SUCCESS,message:await Gae.describeAll()}}catch(e){return Ql.error(e),{status:iO.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,message:e.message}}}a(Wae,"getRemoteDescribeAll");kae||Vae.on("message",async e=>{let{type:t}=e;t===Fae.ITC_EVENT_TYPES.SHUTDOWN&&hq.closeConnection()})});var Qae=pq();(async()=>{try{await Qae()}catch(e){console.error("Error launching Nats reply service."),console.error(e)}})();
|
|
31
|
+
`))}},25).unref()}o.close?.(()=>{if(He.get(_t.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET)&&wl()==0)try{Jx(He.get(_t.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(sH||process.env.DEV_MODE)try{require("inspector").close()}catch(i){Pt.info("Could not close debugger",i)}}}).ref();let e=[];if(jx&&!Pse)for(let t in Es){let r=Es[t];if(isNaN(t)&&wl()==0){Ase(t)&&Jx(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=He.get(_t.CONFIG_PARAMS.HTTP_THREADRANGE);if(n){let i=typeof n=="string"?n.split("-"):n,o=wl();if(o<i[0]||o>i[1])continue}let s;try{s=jx(+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(()=>{Il?.postMessage({type:_t.ITC_EVENT_TYPES.CHILD_STARTED})})})}a(iH,"startServers");rA||iH();function iA(e,t,r){let n=e?.read?e:new mse({fd:e,readable:!0,writable:!0,allowHalfOpen:!0}),s=Es[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=Es[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(iA,"deliverSocket");var Xx=new Map;function Bse(e){let{port:t,event:r,data:n,requestId:s}=e,i;switch(i=Xx.get(s),r){case"connection":i=iA(void 0,t),Xx.set(s,i),i.write=(c,u,_)=>(Il.postMessage({requestId:s,event:"data",data:c.toString("latin1")}),_&&_(),!0),i.end=(c,u,_)=>(Il.postMessage({requestId:s,event:"end",data:c?.toString("latin1")}),_&&_(),!0);let o=i.destroy;i.destroy=()=>{o.call(i),Il.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(Bse,"proxyRequest");function oA(e,t,r=!0){!+t&&t!==He.get(_t.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET)&&(t=parseInt(He.get(_t.CONFIG_PARAMS.HTTP_PORT),10));let n=Es[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",Zx),s.on("unhandled",(i,o)=>{e.cantCleanupProperly&&(n.cantCleanupProperly=!0),e.emit("request",i,o)}),n.lastServer=e}else Es[t]=e;e.on("unhandled",Zx)}a(oA,"registerServer");function oH(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=[],He.get(_t.CONFIG_PARAMS.HTTP_PORT)!=null&&t.push({port:He.get(_t.CONFIG_PARAMS.HTTP_PORT),secure:He.get(_t.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HTTPS)}),He.get(_t.CONFIG_PARAMS.HTTP_SECUREPORT)!=null&&t.push({port:He.get(_t.CONFIG_PARAMS.HTTP_SECUREPORT),secure:!0})),e?.isOperationsServer&&He.get(_t.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET)&&t.push({port:He.get(_t.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET),secure:!1}),t}a(oH,"getPorts");function aA(e,t){for(let{port:r,secure:n}of oH(t))aH(r,n,t?.isOperationsServer),typeof e=="function"?nA[t?.runFirst?"unshift":"push"]({listener:e,port:t?.port||r}):(e.isSecure=n,oA(e,r,!1)),UE[r]=sA(nA,r),Use=sA(vse,r)}a(aA,"httpServer");function aH(e,t,r){if(!$s[e]){let n=r?"operationsApi_network":"http",s={noDelay:!0,keepAliveTimeout:He.get(n+"_keepAliveTimeout"),headersTimeout:He.get(n+"_headersTimeout"),requestTimeout:He.get(n+"_timeout")},i=He.get(n+"_mtls"),o=He.get(n+"_mtls_required");if(t){n=r?"operationsApi_":"";let u=He.get(n+"tls");Object.assign(s,{allowHTTP1:!0,rejectUnauthorized:!!o,requestCert:!!i,ticketKeys:eH(),maxHeaderSize:He.get(_t.CONFIG_PARAMS.HTTP_MAXHEADERSIZE),SNICallback:cA(u)})}let c=Cse();$s[e]=(t?gse:Sse)(s,async(u,_)=>{try{let d=performance.now(),E=new rH(u,_);r&&(E.isOperationsServer=!0);let f=await UE[e](E);if(!f){if(E._nodeResponse.statusCode)return;f=cH(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 x of f.headers||[])_.setHeader(x[0],x[1]);return u.baseRequest=E,_.baseResponse=f,$s[e].emit("unhandled",u,_)}let h=f.status||200,p=performance.now(),S=p-d,T=f.body,R;if(!f.handlesHeaders){let x=f.headers||new tH;T?T.length>=0&&(typeof T=="string"?x.set("Content-Length",Buffer.byteLength(T)):x.set("Content-Length",T.length),R=!0):(x.set("Content-Length","0"),R=!0);let v=`hdb;dur=${S.toFixed(2)}`;f.wasCacheMiss&&(v+=", miss"),Ise(x,"Server-Timing",v,!0),_.writeHead(h,x&&(x[Symbol.iterator]?Array.from(x):x)),R&&_.end(T)}let b=E.handlerPath,C=E.method;if(Nl(S,"duration",b,C,f.wasCacheMiss==null?void 0:f.wasCacheMiss?"cache-miss":"cache-hit"),wse(h<400,"success",b,C),!R)if(T?.pipe){T.pipe(_),T.destroy&&_.on("close",()=>{T.destroy()});let x=0;T.on("data",v=>{x+=v.length}),T.on("end",()=>{Nl(performance.now()-p,"transfer",b,C),Nl(x,"bytes-sent",b,C)})}else T?.then?T.then(x=>{_.end(x)},l):_.end(T)}catch(d){l(d)}function l(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(l,"onError")}),i&&($s[e].mtlsConfig=i),t&&($s[e].on("secureConnection",u=>{u._parent.startTime&&Nl(performance.now()-u._parent.startTime,"tls-handshake",e),Nl(u.isSessionReused(),"tls-reused",e)}),$s[e].isSecure=!0,s.SNICallback(null,(u,_)=>{try{Ja=_,_&&$s[e].setSecureContext(_.options)}finally{Ja=null}})),oA($s[e],e)}return $s[e]}a(aH,"getHTTPServer");function sA(e,t){let r=cH;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(sA,"makeCallbackChain");function cH(e){return e.user&&(e._nodeRequest.user=e.user),{status:-1,body:"Not found",headers:new tH}}a(cH,"unhandled");function xse(e,t){aA(e,{requestOnly:!0,...t})}a(xse,"onRequest");function Hse(e,t){let r;if(t.securePort){let n=Object.assign({},He.get("tls"));t.mtls?.certificateAuthority&&(n.certificateAuthority=t.mtls.certificateAuthority);let s={noDelay:!0,rejectUnauthorized:!!t.mtls?.required,requestCert:!!t.mtls,SNICallback:cA(n)};r=yse(s,e),s.SNICallback(null,(i,o)=>{try{Ja=o,o&&r.setSecureContext(o.options)}finally{Ja=null}}),Es[t.securePort]=r}return t.port&&(r=pse({noDelay:!0},e),Es[t.port]=r),r}a(Hse,"onSocket");Object.defineProperty(Tse.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 Gse(e,t){let r;for(let{port:n,secure:s}of oH(t)){PE[n]||(PE[n]=new Ose({server:r=aH(n,s)}),PE[n].on("connection",async(c,u)=>{try{let _=new rH(u);_.isWebSocket=!0;let l=UE[n](_),d=u.headers["sec-websocket-protocol"]||"",E=eA[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,_,l))}if(f)return}for(let f=0;f<E.length;f++){let h=E[f];h.protocol||h.listener(c,_,l)}}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=eA[n];o||(o=eA[n]=[]),o.push({listener:e,protocol:i}),UE[n]=sA(nA,n)}return r}a(Gse,"onWebSocket");function Zx(e,t){t.writeHead(404),t.end(`Not found
|
|
32
|
+
`)}a(Zx,"defaultNotFound");function tA(e){return e.startsWith("-----BEGIN")?e:Rse(e)}a(tA,"readPEM");function cA(e){let t=[];for(let i=0;e[i];i++)t.push(e[i]);t.length||t.push(e);let r=new Map,n,s=!1;for(let i of t){let o=tA(i.privateKey),c=tA(i.certificate),u=i.certificateAuthority&&tA(i.certificateAuthority);if(!o||!c)throw new Error("Missing private key or certificate for secure server");let _={ciphers:i.ciphers,ca:u,ticketKeys:eH()},l=bse(_);l.options=_,_.instantiatedContext=l,l.context.setCert(c),l.context.setKey(o,void 0),_.cert=c,_.key=o,l.certStart=c.slice(0,100).toString(),n||(n=l);let d=new Dse(c),E=i.hostname??i.host??i.hostnames??i.hosts??(d.subjectAltName?d.subjectAltName.split(",").map(f=>{let h=f.indexOf(":");return f.slice(h+1)}):[d.subject.match(/CN=(.*)/)?.[1]]);Array.isArray(E)||(E=[E]);for(let f of E)f?(f[0]==="*"&&(s=!0,f=f.slice(1)),r.has(f)||r.set(f,l)):Pt.error("No hostname found for certificate at",i.certificate)}return(i,o)=>{let c=i;for(;;){let u=r.get(c);if(u)return Pt.debug("Found certificate for",i,u.certStart),o(null,u);if(s&&c){let _=c.indexOf(".",1);_<0?c="":c=c.slice(_)}else break}Pt.debug("No certificate found to match",i,"using the first certificate"),o(null,n)}}a(cA,"createSNICallback")});async function fH({clientId:e,user:t,clean:r,will:n,keepalive:s}){let i;if(e&&!r){let o=await lA.get(e,{returnNonexistent:!0});i=new fA(e,t,o),o&&(i.sessionWasPresent=!0)}else{if(e){let o=await lA.get(e);o&&o.delete()}i=new xE(e,t)}return n&&(n.id=e,n.user={username:t?.username},Cl.put(n)),s&&(i.keepalive=s,i.receivedPacket()),i}function _A(){return BE++,BE>65500&&(BE=1),BE}function dA(e,t,r){let{topic:n,retain:s}=e;e.data=t,e.async=!0,r.authorize=!0;let i=Oi.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 Ze(r,()=>s?t===void 0?o.delete(e,r):o.put(e,e.data,r):o.publish(e,e.data,r))}var lH,Li,_H,dH,lA,Cl,BE,xE,fA,EH=Re(()=>{Ae();zu();lH=B(vr()),Li=B($());ro();_H=B(We()),dH=B(uH());lr();lA=Et({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"}]}}]}),Cl=Et({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,_H.getWorkerIndex)()===0&&(async()=>{await dH.when_components_loaded,await new Promise(e=>setTimeout(e,2e3));for await(let e of Cl.search({})){let t=e.data,r=Object.assign({},e);r.user?.username&&(r.user=await at.getUser(r.user.username)),Ze(r,()=>{try{dA(r,t,r)}catch{(0,Li.warn)("Failed to publish will",t)}Cl.delete(e.id,r)})}})();a(fH,"getSession");BE=1;a(_A,"getNextMessageId");xE=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("?"),u,_;if(c>-1?(u=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 l=this.subscriptions.find(T=>T.topic===s),d;l?(d=i>0,l.end(),this.subscriptions.splice(this.subscriptions.indexOf(l),1)):d=i===2;let E={search:u,async:!0,user:this.user,startTime:o,omitCurrent:d,url:""};o&&(0,Li.trace)("Resuming subscription from",s,"from",o);let f=Oi.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 F=v.id;if(!Array.isArray(F)||C&&F.length!==R.length)return!1;for(let M=0;M<R.length;M++)if(R[M]!=="+"&&R[M]!==F[M])return!1;return!0},"filter"));let x=R.indexOf("+");E.url="/"+(x>-1?R.slice(0,x):R).concat("").join("/")}}let h=f.path,p=f.Resource,S=await Ze(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=_A());let x=b.id;Array.isArray(x)&&(x=Ia(x)),x==null&&(x=""),this.listener(h+"/"+x,b.value,C,t)}catch(C){(0,Li.warn)(C)}})(),R});return S.topic=s,S.qos=t.qos,this.subscriptions.push(S),S}resume(){}needsAcknowledge(t){let r=_A();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 dA(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();Ze(r,async()=>{try{if(!t){let n=await Cl.get(this.sessionId);n?.doesExist()&&await dA(n,n.data,r)}}finally{await Cl.delete(this.sessionId)}}).catch(n=>{(0,Li.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(dA,"publish");fA=class extends xE{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=_A(),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,Li.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,lH.getNextMonotonicTime)()),(0,Li.trace)("Added durable subscription",t.topic,r),{qos:t.qos,topic:t.topic,startTime:r}}),lA.put(this.sessionRecord)}}});var hA={};Fe(hA,{bypassAuth:()=>qse,start:()=>Fse});function qse(){TH=!0}function Fse({server:e,port:t,network:r,webSocket:n,securePort:s,requireAuthentication:i}){e.mqtt||(e.mqtt={requireAuthentication:i,sessions:new Set,events:new SH.EventEmitter},e.mqtt.events.on("error",()=>{}));let o=e.mqtt,c,u=r?.mtls;return n&&(c=e.ws((_,l,d)=>{if(_.protocol==="mqtt"){o.events.emit("connection",_),jt.debug("Received WebSocket connection for MQTT from",_._socket.remoteAddress);let{onMessage:E,onClose:f}=mH(_,(h,p)=>{if(_.send(h),p&&_._socket.writableNeedDrain)return new Promise(S=>this._socket.once("drain",S))},l,Promise.resolve(d).then(()=>l?.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 l;if(o.events.emit("connection",_),jt.debug(`Received ${_.getCertificate?"SSL":"TCP"} connection for MQTT from ${_.remoteAddress}`),u){if(_.authorized)try{let f=u.user;if(f!==null){(f===void 0||f==="Common Name"||f==="CN")&&(f=_.getPeerCertificate().subject.CN);try{l=await e.getUser(f,null,null),(0,ja.get)(Xt.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)&&GE.notify({username:l?.username,status:Xt.AUTH_AUDIT_STATUS.SUCCESS,type:Xt.AUTH_AUDIT_TYPES.AUTHENTICATION,auth_strategy:"MQTT mTLS",remote_address:_.remoteAddress})}catch(h){throw(0,ja.get)(Xt.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGFAILED)&&GE.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(u.required)return jt.info(`Unauthorized connection attempt, no authorized client certificate provided, error: ${_.authorizationError}`),_.end()}!l&&TH&&_.remoteAddress.includes("127.0.0.1")&&(l=await(0,pH.getSuperUser)(),jt.debug("Auto-authorizing local connection",l?.username));let{onMessage:d,onClose:E}=mH(_,f=>_.write(f),null,l,o);_.on("data",d),_.on("close",E),_.on("error",f=>{jt.info("Socket error",f)})},{port:t,securePort:s,mtls:u})),c}function mH(e,t,r,n,s){hH||(hH=!0,du(d=>{HE>0&&d.push({metric:"mqtt-connections",connections:HE,byThread:!0})}));let i;HE++;let o,c={protocolVersion:4},u=(0,qE.parser)({protocolVersion:5});function _(d){u.parse(d)}a(_,"onMessage");function l(){HE--,i||(i=!0,o?.disconnect?.(),s.events.emit("disconnected",o,e),s.sessions.delete(o),Wr(!1,"connection","mqtt","disconnect"),jt.debug("MQTT connection was closed",e.remoteAddress))}return a(l,"onClose"),u.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;Sr(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 at.getUser(d.username,d.password.toString(),r),(0,ja.get)(Xt.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)&&GE.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,ja.get)(Xt.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGFAILED)&&GE.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),Wr(!1,"connection","mqtt","connect"),p({cmd:"connack",reasonCode:4,returnCode:134})}if(!n&&s.requireAuthentication)return s.events.emit("auth-failed",d,e),Wr(!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=Oo(r?.headers.get?.("content-type")));d.will.data=d.will.payload?.length>0?M(d.will.payload):void 0,delete d.will.payload}o=fH({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),Wr(!1,"connection","mqtt","connect"),p({cmd:"connack",reasonCode:M.code||5,returnCode:M.code||128})}s.events.emit("connected",o,e),Wr(!0,"connection","mqtt","connect"),p({cmd:"connack",sessionPresent:o.sessionWasPresent,reasonCode:0,returnCode:0}),o.setListener((M,Q,J,j)=>{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:j.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=Oo(r?.headers.get?.("content-type"))),v=(d.payload?.length||0)>0?C(d.payload):void 0,F;try{F=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:F===!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),Wr(!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,qE.generate)(R,c);t(C),Sr(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 To(R,r)}a(T,"serialize")}),u.on("error",d=>{jt.warn("MQTT parsing error, closing connection:",d.message),e?.destroy?e.destroy():e?.terminate()}),{onMessage:_,onClose:l}}var qE,pH,ja,Xt,EA,SH,GE,jt,TH,hH,HE,gH=Re(()=>{qE=require("mqtt-packet");EH();pH=B(ln());Ca();Cs();lr();ja=B(Z()),Xt=B(P()),EA=B($()),SH=require("events"),GE=(0,EA.loggerWithTag)("auth-event"),jt=(0,EA.loggerWithTag)("mqtt"),TH=(0,ja.get)(Xt.CONFIG_PARAMS.AUTHENTICATION_AUTHORIZELOCAL)??process.env.DEV_MODE;a(qse,"bypassAuth");a(Fse,"start");HE=0;a(mH,"onSocket")});var Bf={};Fe(Bf,{component_errors:()=>Za,loadComponent:()=>FE,loadComponentDirectories:()=>CH,setErrorReporter:()=>Yse});function CH(e,t){t&&(pA=t),e&&(SA=e);let r=[];if((0,tt.existsSync)(mA)){let s=(0,tt.readdirSync)(mA,{withFileTypes:!0});for(let i of s){if(!i.isDirectory()&&!i.isSymbolicLink())continue;let o=i.name,c=(0,st.join)(mA,o);r.push(FE(c,pA,"hdb",!1))}}let n=process.env.RUN_HDB_APP;return n&&r.push(FE(n,pA,n,!1,null,process.env.DEV_MODE)),Promise.all(r).then(()=>{wH=!0})}function Yse(e){Dl=e}async function FE(e,t,r,n,s,i){let o=(0,tt.realpathSync)(e);if(!AH.has(o)){AH.set(o,!0),s&&(SA=s);try{let c;n&&(Za=new Map);let u=(0,st.join)(e,n?"harperdb-config.yaml":"config.yaml");(0,tt.existsSync)(u)?c=n?(0,IH.getConfigObj)():(0,OH.parseDocument)((0,tt.readFileSync)(u,"utf8"),{simpleKeys:!0}).toJSON():c=TA;let _=(0,st.join)(e,"node_modules","harperdb");try{Lo.isMainThread&&(n||(0,tt.existsSync)(_)&&(0,tt.realpathSync)(tc.PACKAGE_ROOT)!==(0,tt.realpathSync)(_))&&((0,tt.rmSync)(_,{recursive:!0,force:!0}),(0,tt.existsSync)((0,st.join)(e,"node_modules"))||(0,tt.mkdirSync)((0,st.join)(e,"node_modules")),(0,tt.symlinkSync)(tc.PACKAGE_ROOT,_,"dir"))}catch(E){Xa.default.error("Error symlinking harperdb module",E)}let l=[],d=n;for(let E in c){let f=c[E];if(Za.set(n?E:(0,st.basename)(e),!1),!f)continue;let h,p=f.package;try{if(p){let C=e,x;for(;!(0,tt.existsSync)(x=(0,st.join)(C,"node_modules",E));)if(C=(0,st.dirname)(C),C.length<(0,NH.getHdbBasePath)().length){x=null;break}if(x)h=await FE(x,t,r,!1),d=!0;else throw new Error(`Unable to find package ${E}:${p}`)}else h=$se[E];if(!h)continue;l.push(h);let S=a(C=>(C.origin=r,Et(C)),"ensureTable"),T=f.network||(f.port||f.securePort)&&f,R=T?.securePort||T?.https&&T.port,b=!T?.https&&T?.port;if(Lo.isMainThread&&(h=await h.startOnMainThread?.({server:at,ensureTable:S,port:b,securePort:R,resources:t,...f})||h,n&&T))for(let C of[b,R])try{if(+C&&!RH.includes(C)){let x=gA.get(tc.CONFIG_PARAMS.HTTP_SESSIONAFFINITY);x&&Xa.default.warn("Session affinity is not recommended and may cause memory leaks"),(x||!IE)&&(RH.push(C),vx(C,x))}}catch(x){console.error("Error listening on socket",C,x,E)}if(t.isWorker&&(h=await h.start?.({server:at,ensureTable:S,port:b,securePort:R,resources:t,...f})||h),SA.set(h,!0),(h.handleFile||h.handleDirectory)&&f.files){if(f.files.includes(".."))throw(0,yH.handleHDBError)("Can not reference parent directories");let C=(0,st.join)(e,f.files).replace(/\\/g,"/"),x=C.indexOf("/*");if(x>-1&&f.files!==TA[E]?.files&&!(0,tt.existsSync)(C.slice(0,x)))throw new Error(`The path '${C.slice(0,x)}' does not exist and cannot be used as the base of the resolved 'files' path value '${f.files}'`);let v=(0,st.basename)(e),F=f.path||"/";F=F.startsWith("/")?F:F.startsWith("./")?"/"+v+F.slice(2):F==="."?"/"+v:"/"+v+"/"+F;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,st.join)(e,ae)}else(J=C.indexOf("/*"))>-1&&(Q=C.slice(0,J+1),M=(0,st.relative)(e,Q));let j=!1;if(Lo.isMainThread&&h.setupDirectory&&(j=await h.setupDirectory?.(F,Q,t)),t.isWorker&&h.handleDirectory&&(j=await h.handleDirectory?.(F,Q,t)),j)continue;for(let ae of await(0,bH.default)(C,{onlyFiles:!1,objectMode:!0})){let{path:ce,dirent:ge}=ae;d=!0;let Ge=(0,st.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=F+(F.endsWith("/")?"":"/")+Ge;try{if(ge.isFile()){let ve=await Vse(ce);Lo.isMainThread&&await h.setupFile?.(ve,Ne,ce,t),t.isWorker&&await h.handleFile?.(ve,Ne,ce,t)}else Lo.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}`,Dl?.(ve),((0,ec.getWorkerIndex)()===0?console:Xa.default).error(ve),t.set(f.path||"/",new Ll(ve)),Za.set(n?E:(0,st.basename)(e),ve.message)}}}}catch(S){S.message=`Could not load component '${E}' for application '${(0,st.basename)(e)}' due to: ${S.message}`,Dl?.(S),((0,ec.getWorkerIndex)()===0?console:Xa.default).error(S),t.set(f.path||"/",new Ll(S),null,!0),Za.set(n?E:(0,st.basename)(e),S.message)}}if(Lo.isMainThread&&!wH&&i&&(0,ec.watchDir)(e,async()=>CH()),c.extensionModule)return await E_((0,st.join)(e,c.extensionModule));if(!d&&t.isWorker){let E=`${e} did not load any modules, resources, or files, is this a valid component?`;Dl?.(new Error(E)),((0,ec.getWorkerIndex)()===0?console:Xa.default).error(E),Za.set((0,st.basename)(e),E)}}catch(c){console.error(`Could not load application directory ${e}`,c),c.message=`Could not load application due to ${c.message}`,Dl?.(c),t.set("",new Ll(c))}}}var tt,st,Lo,OH,gA,tc,bH,ec,Xa,yH,NH,kse,IH,Vse,mA,SA,wH,pA,Za,$se,TA,RH,AH,Dl,Ll,xf=Re(()=>{tt=require("fs"),st=require("path"),Lo=require("worker_threads"),OH=require("yaml"),gA=B(Z()),tc=B(P());gb();bb();yb();P0();bx();Dx();bH=B(require("fast-glob")),ec=B(We()),Xa=B($());zh();lr();yH=B(ne());Nn();Ae();Bx();NH=B(Z()),kse=B(Fx());wf();zx();gH();IH=B(Er());wE();({readFile:Vse}=tt.promises),mA=gA.get(tc.CONFIG_PARAMS.COMPONENTSROOT),SA=new Map,Za=new Map;a(CH,"loadComponentDirectories");$se={REST:tE,rest:tE,graphqlSchema:Qh,jsResource:jh,fastifyRoutes:xR,login:Zh,static:HR,operationsApi:kse,customFunctions:{},http:{},clustering:XR,authentication:ju,mqtt:hA},TA={rest:!0,graphqlSchema:{files:"*.graphql"},jsResource:{files:"resources.js"},fastifyRoutes:{files:"routes/*.js",path:"."}};Object.defineProperty(TA,"static",{value:{files:"web/**"}});RH=[],AH=new Map;a(Yse,"setErrorReporter");a(FE,"loadComponent");Ll=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 uA=g((wSe,LH)=>{var{isMainThread:DH}=require("worker_threads"),{getTables:Kse}=(Ae(),ie(ke)),{loadComponentDirectories:Wse,loadComponent:Qse}=(xf(),ie(Bf)),{resetResources:zse}=(zu(),ie(kU)),Jse=Sg(),jse=Er(),{dirname:Xse}=require("path"),{getConnection:Zse}=ut(),eie=Z(),tie=P(),RA=new Map;async function rie(e=!1){!DH&&eie.get(tie.CONFIG_PARAMS.CLUSTERING_ENABLED)&&Zse();try{DH&&await Jse()}catch(n){console.error(n)}let t=zse();Kse(),t.isWorker=e,await Qse(Xse(jse.getConfigFilePath()),t,"hdb",!0,RA),await Wse(RA,t);let r=[];for(let[n]of RA)n.ready&&r.push(n.ready());r.length>0&&await Promise.all(r)}a(rie,"loadRootComponents");LH.exports.loadRootComponents=rie});var We=g((DSe,Pi)=>{"use strict";var{Worker:nie,MessageChannel:sie,parentPort:hs,isMainThread:NA,threadId:iie,workerData:Ys}=require("worker_threads"),{PACKAGE_ROOT:oie}=P(),{join:vH,isAbsolute:aie,extname:cie}=require("path"),{server:BH}=(lr(),ie(xi)),{watch:uie,readdir:lie}=require("fs/promises"),{totalmem:MH}=require("os"),Ml=P(),xH=Z(),Ks=$(),{randomBytes:_ie}=require("crypto"),{_assignPackageExport:die}=require("../index"),fie=P(),PH=1024*1024,Mi=[],Tn=[],Eie=50,IA=1e4,hie="restart",HH="request_thread_info",GH="resource_report",qH="thread_info",FH="added-port",mie="ack",AA;die("threads",Tn);Pi.exports={startWorker:OA,restartWorkers:CA,shutdownWorkers:Rie,workers:Mi,setMonitorListener:Cie,onMessageFromWorkers:Aie,onMessageByType:QH,broadcast:bie,broadcastWithAcknowledgement:Nie,setChildListenerByType:gie,getWorkerIndex:kH,getWorkerCount:VH,getTicketKeys:YH,setMainIsWorker:Sie,setTerminateTimeout:pie,restartNumber:Ys?.restartNumber||1};Tn.onMessageByType=QH;Tn.sendToThread=function(e,t){if(!t?.type)throw new Error("A message with a type must be provided");let r=Tn.find(n=>n.threadId===e);if(r)return r.postMessage(t),!0};var wA;function pie(e){IA=e}a(pie,"setTerminateTimeout");function kH(){return Ys?Ys.workerIndex:wA?0:void 0}a(kH,"getWorkerIndex");function VH(){return Ys?Ys.workerCount:wA?1:void 0}a(VH,"getWorkerCount");function Sie(e){wA=e}a(Sie,"setMainIsWorker");var $H=1,kE;function YH(){return kE||(kE=NA?_ie(48):Ys.ticketKeys,kE)}a(YH,"getTicketKeys");Object.defineProperty(BH,"workerIndex",{get(){return kH()}});Object.defineProperty(BH,"workerCount",{get(){return VH()}});var KH={[HH](e,t){Iie(t)},[GH](e,t){wie(t,e)}};function OA(e,t={}){let r=process.constrainedMemory?.()||MH();r=Math.min(r,MH(),2e4*PH);let n=xH.get(Ml.CONFIG_PARAMS.THREADS_MAXHEAPMEMORY)??Math.max(Math.floor(r/PH/(10+(t.threadCount||1)/4)),512),s=Math.min(Math.max(n>>6,16),64),i=[],o=[];for(let u of Tn){let _=new sie;_.existingPort=u,i.push(_),o.push(_.port2)}cie(e)||(e+=".js");let c=new nie(aie(e)?e:vH(oie,e),Object.assign({resourceLimits:{maxOldGenerationSizeMb:n,maxYoungGenerationSizeMb:s},execArgv:["--enable-source-maps"],argv:process.argv.slice(2),workerData:{addPorts:o,addThreadIds:i.map(u=>u.existingPort.threadId),workerIndex:t.workerIndex,workerCount:$H=t.threadCount,name:t.name,restartNumber:Pi.exports.restartNumber,ticketKeys:YH()},transferList:o},t));for(let{port1:u,existingPort:_}of i)_.postMessage({type:FH,port:u,threadId:c.threadId},[u]);return $E(c,!0),c.unexpectedRestarts=t.unexpectedRestarts||0,c.startCopy=()=>OA(e,t),c.on("error",u=>{Ks.error(`Worker index ${t.workerIndex} error:`,u)}),c.on("exit",u=>{Mi.splice(Mi.indexOf(c),1),!c.wasShutdown&&t.autoRestart!==!1&&(c.unexpectedRestarts<Eie?(t.unexpectedRestarts=c.unexpectedRestarts+1,OA(e,t)):Ks.error(`Thread has been restarted ${c.restarts} times and will not be restarted`))}),c.on("message",u=>{KH[u.type]?.(u,c)}),Mi.push(c),Lie(),t.onStarted&&t.onStarted(c),c.name=t.name,c}a(OA,"startWorker");var Tie=[Ml.THREAD_TYPES.HTTP];async function CA(e=null,t=Math.max($H>3,1),r=!0){if(NA){if(r){let{loadRootComponents:o}=uA();await o()}Pi.exports.restartNumber++,t<1&&(t=t*Mi.length);let n=[],s=[];for(let o of Mi.slice(0)){if(e&&o.name!==e||o.wasShutdown)continue;Ks.trace("sending shutdown request to ",o.threadId),o.postMessage({restartNumber:Pi.exports.restartNumber,type:Ml.ITC_EVENT_TYPES.SHUTDOWN}),o.wasShutdown=!0,o.emit("shutdown",{});let c=Tie.indexOf(o.name)>-1,u=new Promise(_=>{let l=setTimeout(()=>o.terminate(),IA*2).unref();o.on("exit",()=>{clearTimeout(l),n.splice(n.indexOf(u)),!c&&r&&o.startCopy(),_()})});if(n.push(u),c&&r){let _=o.startCopy(),l=new Promise(d=>{let E=a(f=>{f.type===fie.ITC_EVENT_TYPES.CHILD_STARTED&&(Ks.trace("Worker has started",_.threadId),d(),s.splice(s.indexOf(l)),_.off("message",E))},"startListener");Ks.trace("Waiting for worker to start",_.threadId),_.on("message",E)});s.push(l),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}=Wu();r&&(e==="http"||!e)&&xH.get(Ml.CONFIG_PARAMS.CLUSTERING_ENABLED)&&await i({service:"clustering"})}else hs.postMessage({type:hie,workerType:e})}a(CA,"restartWorkers");function gie(e,t){KH[e]=t}a(gie,"setChildListenerByType");function Rie(e){return CA(e,1/0,!1)}a(Rie,"shutdownWorkers");var WH=[];function Aie(e){WH.push(e)}a(Aie,"onMessageFromWorkers");var bA=new Map;function QH(e,t){let r=bA.get(e);r||bA.set(e,r=[]),r.push(t)}a(QH,"onMessageByType");var Oie=10;async function bie(e){let t=0;for(let r of Tn)try{r.postMessage(e),t++>Oie&&(t=0,await new Promise(setImmediate))}catch(n){Ks.error("Unable to send message to worker",n)}}a(bie,"broadcast");var VE=new Map,yie=1;function Nie(e){return new Promise(t=>{let r=0;for(let n of Tn)try{let s=yie++,i=a(()=>{VE.delete(s),--r===0&&t(),n!==hs&&--n.refCount===0&&n.unref()},"ack_handler");i.port=n,n.ref(),n.refCount=(n.refCount||0)+1,VE.set(e.requestId=s,i),n.hasAckCloseListener||(n.hasAckCloseListener=!0,n.on(n.close?"close":"exit",()=>{for(let[,o]of VE)o.port===n&&o()})),n.postMessage(e),r++}catch(s){Ks.error("Unable to send message to worker",s)}r===0&&t()})}a(Nie,"broadcastWithAcknowledgement");function Iie(e){e.postMessage({type:qH,workers:zH()})}a(Iie,"sendThreadInfo");function zH(){let e=Date.now();return Mi.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(zH,"getChildWorkerInfo");function wie(e,t){e.resources=t,e.resources.updated=Date.now()}a(wie,"recordResourceReport");var yA;function Cie(e){yA=e}a(Cie,"setMonitorListener");var Die=1e3,UH=!1;function Lie(){UH||(UH=!0,setInterval(()=>{for(let e of Mi){let t=e.performance.eventLoopUtilization(),r;e.lastTotalELU?r=e.performance.eventLoopUtilization(t,e.lastTotalELU):r=t,e.lastTotalELU=t,e.recentELU=r}yA&&yA()},Die).unref())}a(Lie,"startMonitoring");var Mie=1e3;if(hs){$E(hs);for(let e=0,t=Ys.addPorts.length;e<t;e++){let r=Ys.addPorts[e];r.threadId=Ys.addThreadIds[e],$E(r)}setInterval(()=>{let e=process.memoryUsage();hs.postMessage({type:GH,heapTotal:e.heapTotal,heapUsed:e.heapUsed,external:e.external,arrayBuffers:e.arrayBuffers})},Mie).unref(),AA=a(()=>new Promise((e,t)=>{hs.on("message",r),hs.postMessage({type:HH});function r(n){n.type===qH&&(hs.off("message",r),e(n.workers))}a(r,"receiveThreadInfo")}),"getThreadInfo")}else AA=zH;Pi.exports.getThreadInfo=AA;function $E(e,t){Tn.push(e),e.on("message",r=>{if(r.type===FH)r.port.threadId=r.threadId,$E(r.port);else if(r.type===mie){let n=VE.get(r.id);n&&n()}else{for(let s of WH)s(r,e);let n=bA.get(r.type);if(n)for(let s of n)try{s(r,e)}catch(i){Ks.error(i)}}}).on("close",()=>{Tn.splice(Tn.indexOf(e),1)}).on("exit",()=>{Tn.splice(Tn.indexOf(e),1)}),t?e.refCount=100:e.unref()}a($E,"addPort");if(NA){let e,t,r=new Set,n=a(async(s,i)=>{i&&(e=i);for(let o of await lie(s,{withFileTypes:!0}))o.isDirectory()&&o.name!=="node_modules"&&n(vH(s,o.name));try{for await(let{filename:o}of uie(s,{persistent:!1}))r.add(o),t&&clearTimeout(t),t=setTimeout(async()=>{e&&await e(),await CA(),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");Pi.exports.watchDir=n,process.env.WATCH_DIR&&n(process.env.WATCH_DIR)}else hs.on("message",async e=>{let{type:t}=e;t===Ml.ITC_EVENT_TYPES.SHUTDOWN&&(Pi.exports.restartNumber=e.restartNumber,hs.unref(),setTimeout(()=>{Ks.warn("Thread did not voluntarily terminate",iie),process.exit(0)},IA).unref())})});var MC={};Fe(MC,{AUDIT_STORE_OPTIONS:()=>gf,createAuditEntry:()=>T_,openAuditStore:()=>QE,readAuditEntry:()=>vt,setAuditRetention:()=>Uie,transactionKeyEncoder:()=>sG});function QE(e){let t=e.auditStore=e.openDB(tG.AUDIT_STORE_NAME,gf);t.rootStore=e;let r=[];t.addDeleteRemovalCallback=function(i,o){return r[i]=o,{remove(){delete r[i]}}};let n=null;function s(i=YE){clearTimeout(n),n=setTimeout(async()=>{if(t.rootStore.status==="closed"||t.rootStore.status==="closing")return;let o=0,c;try{for(let{key:u,value:_}of t.getRange({start:0,snapshot:!1,end:Date.now()-DA})){if((_[0]&15)===PA){let l=vt(_),d=l.tableId;r[d]?.(l.recordId)}if(c=t.remove(u),await new Promise(setImmediate),++o>=Pie){i=10;break}}await c}finally{o===0&&(i=Math.min(i<<1,DA/10)),s(i)}},i).unref()}return a(s,"scheduleAuditCleanup"),t.scheduleAuditCleanup=s,(0,WE.getWorkerIndex)()===(0,WE.getWorkerCount)()-1&&s(YE),t}function Uie(e,t=YE){DA=e,YE=t}function T_(e,t,r,n,s,i,o){let c=iG[i];if(!c)throw new Error(`Invalid audit entry type ${i}`);let u=1;n&&(n>1?rc.setFloat64(0,n):gn.set(hm),u=9),E(0),E(t),d(r),rc.setFloat64(u,e),u+=8,s?d(s):gn[u++]=0,gn[n?8:0]=c;let l=gn.subarray(0,u);if(o)return Buffer.concat([l,o]);return l;function d(f){let h=u;u+=1,u=(0,nc.writeKey)(f,gn,u);let p=u-h-1;p>127?p>16383?(vA.error("Key or username was too large for audit entry",f),u=h+1,gn[h]=0):(gn.copyWithin(h+2,h+1,u),rc.setUint16(h,p|32768),u++):gn[h]=p}function E(f){f<128?gn[u++]=f:f<16384?(rc.setUint16(u,f|32768),u+=2):f<1056964608?(rc.setUint32(u,f|3221225472),u+=4):(gn[u]=255,rc.setUint32(u+1,f),u+=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,u=t.position+=o,_=t.readFloat64();o=t.readInt();let l=t.position,d=t.position+=o;return{type:iG[n&7],tableId:i,get recordId(){return eG(e,c,u)},version:_,previousLocalTime:r,get user(){return d>l?eG(e,l,d):void 0},getValue(E,f,h){if(n&LA||n&MA&&!f)return E.decoder.decode(e.subarray(t.position));if(n&MA&&h)return BA(E.getEntry(this.recordId),h,E)}}}catch(t){return vA.error("Reading audit entry error",t,e),{}}}function eG(e,t,r){let n=e.subarray(t,r);return(0,nc.readKey)(n,0,r-t)}var nc,KE,tG,rG,WE,nG,vA,gn,rc,sG,gf,DA,Pie,YE,LA,MA,JH,PA,jH,XH,ZH,iG,UA,ti=Re(()=>{nc=require("ordered-binary"),KE=B(Z()),tG=B(ft()),rG=B(P()),WE=B(We()),nG=B(z());Lc();vA=B($());zE();(0,KE.initSync)();gn=Buffer.alloc(1024),rc=new DataView(gn.buffer,gn.byteOffset,1024),sG={writeKey(e,t,r){return e===Dc?(t.set(Dc,r),r+8):typeof e=="number"?((t.dataView||(t.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength))).setFloat64(r,e),r+8):(0,nc.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,nc.readKey)(e,t,r)}},gf={encoding:"binary",keyEncoder:sG},DA=(0,nG.convertToMS)((0,KE.get)(rG.CONFIG_PARAMS.LOGGING_AUDITRETENTION))||86400*3,Pie=1e3,YE=1e4;a(QE,"openAuditStore");a(Uie,"setAuditRetention");LA=16,MA=32,JH=1,PA=2,jH=3,XH=4,ZH=5,iG={put:JH|LA,[JH]:"put",delete:PA,[PA]:"delete",message:jH|LA,[jH]:"message",invalidate:XH,[XH]:"invalidate",patch:ZH|MA,[ZH]:"patch"};a(T_,"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(eG,"readKeySafely")});var xA={};Fe(xA,{add:()=>JE,applyReverse:()=>oG,getRecordAtTime:()=>BA,rebuildUpdateBefore:()=>jE});function JE(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 jE(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,JE(r,n,s)}}else r||(r={}),r[n]=e[n];return r}function oG(e,t){for(let r in t){let n=t[r];if(n?.__op__){let s=vie[n.__op__]?.reverse;if(s)s(e,r,{value:n.value});else throw new Error(`Unsupported operation ${n.__op__}`)}else e[r]=aG}}function BA(e,t,r){let n=r.rootStore.auditStore,s=Object.assign({},e.value),i=e.localTime;for(;i>t;){let u=n.get(i),_=vt(u);switch(_.type){case"put":s=_.getValue(r);break;case"patch":oG(s,_.getValue(r));break;case"delete":s=null}i=_.previousLocalTime}let o={},c=0;for(let u in s)s[u]===aG&&(o[u]=!0,c++);for(;c>0&&i>0;){let u=n.get(i),_=vt(u),l;switch(_.type){case"put":l=_.getValue(r);break;case"patch":l=_.getValue(r);break}for(let d in l)o[d]&&(s[d]=l[d],o[d]=!1,c--);i=_.previousLocalTime}if(c>0)for(let u in o)s[u]=null;return s}var vie,aG,zE=Re(()=>{ti();a(JE,"add");JE.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)};vie={add:JE};a(jE,"rebuildUpdateBefore");a(oG,"applyReverse");aG={};a(BA,"getRecordAtTime")});function Zr(e){return e[Nt]||(e[Nt]=Object.create(null))}function rh(e,t){let r=e.prototype,n={},s=t.attributes||t.properties||[];for(let o of s){let c=o.name,u,_;if(o.resolve)_={get(){return o.resolve(this,this[be])},set(l){return o.set(this,l)},configurable:!0};else{switch(o.type){case"String":u=a(function(l){if(!(typeof l=="string"||l==null&&o.nullable!==!1))throw new Rn.ClientError(`${c} must be a string, attempt to assign ${l}`);Zr(this)[c]=l},"set");break;case"ID":u=a(function(l){if(!(typeof l=="string"||l?.length>0&&l.every?.(d=>typeof d=="string")||l==null&&o.nullable!==!1))throw new Rn.ClientError(`${c} must be a string, attempt to assign ${l}`);Zr(this)[c]=l},"set");break;case"Float":case"Number":u=a(function(l){let d=l?.__op__?l.value:l;if(!(typeof d=="number"||l==null&&o.nullable!==!1))throw new Rn.ClientError(`${c} must be a number, attempt to assign ${d}`);Zr(this)[c]=l},"set");break;case"Int":u=a(function(l){let d=l?.__op__?l.value:l;if(!(d>>0===d||l==null&&o.nullable!==!1))if(typeof d=="number"&&Math.abs((d>>0)-d)<=1)d=Math.round(d),l?.__op__?l.value=d:l=d;else throw new Rn.ClientError(`${c} must be an integer between -2147483648 and 2147483647, attempt to assign ${l}`);Zr(this)[c]=l},"set");break;case"Long":u=a(function(l){let d=l?.__op__?l.value:l;if(!(Math.round(d)===l&&Math.abs(d)<=9007199254740992||l==null&&o.nullable!==!1))if(typeof d=="number"&&Math.abs(d)<=9007199254740992)d=Math.round(d),l?.__op__?l.value=d:l=d;else throw new Rn.ClientError(`${c} must be an integer between -9007199254740992 and 9007199254740992, attempt to assign ${l}`);Zr(this)[c]=l},"set");break;case"BigInt":u=a(function(l){let d=l?.__op__?l.value:l;if(!(typeof d=="bigint"||l==null&&o.nullable!==!1))if(typeof d=="string"||typeof d=="number")d=BigInt(d),l?.__op__?l.value=d:l=d;else throw new Rn.ClientError(`${c} must be a number, attempt to assign ${l}`);Zr(this)[c]=l},"set");break;case"Boolean":u=a(function(l){if(!(typeof l=="boolean"||l==null&&o.nullable!==!1))throw new Rn.ClientError(`${c} must be a boolean, attempt to assign ${l}`);Zr(this)[c]=l},"set");break;case"Date":u=a(function(l){if(!(l instanceof Date||l==null&&o.nullable!==!1))if(typeof l=="string"||typeof l=="number")l=new Date(l);else throw new Rn.ClientError(`${c} must be a Date, attempt to assign ${l}`);Zr(this)[c]=l},"set");break;case"Bytes":u=a(function(l){if(!(l instanceof Uint8Array||l==null&&o.nullable!==!1))throw new Rn.ClientError(`${c} must be a Buffer or Uint8Array, attempt to assign ${l}`);Zr(this)[c]=l},"set");break;case"Any":case void 0:u=a(function(l){Zr(this)[c]=l},"set");break;default:u=a(function(l){if(!(typeof l=="object"||l==null&&o.nullable!==!1))throw new Rn.ClientError(`${c} must be an object, attempt to assign ${l}`);Zr(this)[c]=l},"set")}_={get(){let l=this[Nt];if(l&&c in l){let E=l[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=uG(d,o);if(E)return l||(l=this[Nt]=Object.create(null)),l[c]=E}return d},set:u,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 u=this[Nt];return u?.[o]!==void 0?u[o]:this[de]?.[o]}),i("set",function(o,c){let u=n[o];if(u)return u.set.call(this,c);if(t.sealed)throw new Rn.ClientError("Can not add a property to a sealed table schema");Zr(this)[o]=c}),i("deleteProperty",function(o){Zr(this)[o]=void 0}),i("toJSON",function(){let o=this[Nt],c;for(let _ in o){c||(c=Object.assign({},this[de]));let l=o[_];if(l?.__op__){let d=c[_];l=l.update(d)}c[_]=l}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 uG(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}},rh(r,t)),new r(e)):new XE(e);case Array:let n=new eh(e.length);n[de]=e;for(let s=0,i=e.length;s<i;s++){let o=e[s];o&&typeof o=="object"&&(o=uG(o,t?.elements)),n[s]=o}return n;default:return e}}function md(e){let t=e[Nt],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=md(i);r[s]=i}return Object.keys(e).length>0&&(r||(r=Object.assign({},e[de])),Object.assign(r,e)),r||e[de]}function Po(e,t=e[Nt]){let r;if(cG.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=Po(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=xA[s?.__op__];if(i)i(r,n,s);else throw new Error("Invalid CRDT operation "+s.__op__);continue}else s=Po(s);r[n]=s}return r?Object.freeze(r):cG.call(e,de)?e[de]:e}function ZE(e){let t=e[de];if(t===void 0)return!0;if(e.constructor===Array){if(!t||e[Mo]||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(ZE(i))return!0}else return!0}}else{let r=e[Nt];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(ZE(s))return!0}else return!0}else return!0}}return!1}var Rn,Nt,XE,cG,Mo,eh,th,pd=Re(()=>{Nn();Rn=B(ne());zE();Nt=Symbol("own-data");a(Zr,"getChanges");a(rh,"assignTrackedAccessors");a(uG,"trackObject");XE=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}};rh(XE,{});a(md,"collapseData");cG=Object.prototype.hasOwnProperty;a(Po,"deepFreeze");a(ZE,"hasChanges");Mo=Symbol.for("has-array-changes"),eh=class extends Array{static{a(this,"TrackedArray")}[Mo];constructor(t){super(t)}splice(...t){return this[Mo]=!0,super.splice(...t)}push(...t){return this[Mo]=!0,super.push(...t)}pop(){return this[Mo]=!0,super.pop()}unshift(...t){return this[Mo]=!0,super.unshift(...t)}shift(){return this[Mo]=!0,super.shift()}};eh.prototype.constructor=Array;th=class{constructor(t){this.value=t}static{a(this,"Addition")}__op__="add";update(t){return(+t||0)+this.value}}});var qp={};Fe(qp,{CONTEXT:()=>be,ID_PROPERTY:()=>Le,IS_COLLECTION:()=>kn,RECORD_PROPERTY:()=>de,Resource:()=>$t,snake_case:()=>xie,transformForSelect:()=>sh});function xie(e){return e[0].toLowerCase()+e.slice(1).replace(/[a-z][A-Z][a-z]/g,t=>t[0]+"_"+t.slice(1))}function lG(e,t){if(Pl=!1,e==="")return null;if(e=e.slice(1),e.indexOf("/")===-1)return e===""?(Pl=!0,null):(e.startsWith("$")&&(e=parseInt(e,36)),t.coerceId(decodeURIComponent(e)));let r=e.split("/"),n=new GA;for(let s=0;s<r.length;s++){let i=r[s];if(!i&&s===r.length-1){Pl=!0;break}n[s]=t.coerceId(decodeURIComponent(i))}return n}function en(e,t){n.reliesOnPrototype=!0;let r=t.hasContent;return n;function n(s,i,o){let c,u,_,l;if(r?(o?(l=i,o=o[be]||o):i?typeof s=="object"&&s&&(!Array.isArray(s)||typeof s[0]=="object")?(l=s,c=l[this.primaryKey]??null,o=i[be]||i):l=i:(l=s,c=l[Le]??l[this.primaryKey]??null),c==null&&(_=!0)):i?o=i[be]||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(u=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]),u.slice&&(u=u.slice(c.length,u.length),u.length===0&&(u=null,_=!1)))}else{if(typeof(c=s.url)=="string"){let f=c.indexOf("?");if(f>-1){let p=this.parseQuery(c.slice(f+1));u?u=Object.assign(p,u):u=p,c=c.slice(0,f)}let h=this.parsePath(c,o,u);h?.id!==void 0?(h.query&&(u?u=Object.assign(h.query,u):u=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(u?.ensureLoaded!=null||u?.async||_?(d=Object.assign({},t),u?.ensureLoaded!=null&&(d.ensureLoaded=u.ensureLoaded),u?.async&&(d.async=u.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 Ze(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,u,o):t.type==="update"?f.doesExist?.()===!1?f.allowCreate(o.user,l,o):f.allowUpdate(o.user,l,o):t.type==="create"?f.allowCreate(o.user,l,o):f.allowDelete(o.user,u,o);if(h?.then)return h.then(p=>{if(!p)throw new nh(o.user);return typeof l?.then=="function"?l.then(S=>e(f,u,o,S)):e(f,u,o,l)});if(!h)throw new nh(o.user)}return typeof l?.then=="function"?l.then(h=>e(f,u,o,h)):e(f,u,o,l)}a(E,"authorizeActionOnResource")}}function tn(e,t){let r=new fG.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 HA(e,t,r){let n=e[de];if(n){let s=e[Nt];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 sh(e,t){let r=t?.propertyResolvers,n=t[be],s;if(typeof e=="string")return a(function o(c){return c.then?c.then(o):Array.isArray(c)?c.map(o):HA(c,r,n)(e)},"transform");if(typeof e=="object"){if(e.asArray)return a(function c(u){if(u.then)return u.then(c);if(Array.isArray(u))return u.map(c);let _=[],l=i(HA(u,r,n));for(let d of e)_.push(l(d));return _},"transform");let o=e.forceNulls;return a(function c(u){if(u.then)return u.then(c);if(Array.isArray(u))return u.map(E=>E&&typeof E=="object"?c(E):E);let _={},l=i(HA(u,r,n)),d;for(let E of e){let f=l(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 u=s[c.name];if(!u){let l=r[c.name]?.definition?.tableClass;u=s[c.name]=sh(c.select||c,l)}let _=o(c.name);return u(_)}else return o(c);else return c}}a(i,"handleProperty")}var _G,dG,fG,be,Le,kn,de,Bie,$t,nh,Pl,GA,Nn=Re(()=>{_G=require("crypto");bc();dG=require("../index"),fG=B(ne());pd();ro();Zf();be=Symbol.for("context"),Le=Symbol.for("primary-key"),kn=Symbol("is-collection"),de=Symbol("stored-record"),Bie={json:"application/json",cbor:"application/cbor",msgpack:"application/x-msgpack",csv:"text/csv"},$t=class{static{a(this,"Resource")}static transactions;[be];constructor(t,r){this[Le]=t;let n=r?.[be];this[be]=n!==void 0?n:r||null}static get=en(function(t,r,n,s){let i=t.get?.(r);if(i?.then)return i.then(o);return o(i);function o(c){let u;if((u=r?.select)&&c!=null&&!c.selectApplied){let _=sh(u,t.constructor);return typeof c?.map=="function"?c.map(_):_(c)}return c}},{type:"read",letItLinger:!0,ensureLoaded:!0,async:!0});static put=en(function(t,r,n,s){if(Array.isArray(s)&&t[kn]){let i=[],o=n.authorize;for(let c of s){let u=t.constructor,_=u.getResource(c[u.primaryKey],n,{async:!0});_.then?i.push(_.then(l=>l.put(c,n))):i.push(_.put(c,n))}return Promise.all(i)}return t.put?t.put(s,r):tn(t,"put")},{hasContent:!0,type:"update"});static patch=en(function(t,r,n,s){return t.patch?t.patch(s,r):tn(t,"patch")},{hasContent:!0,type:"update"});static delete=en(function(t,r,n,s){return t.delete?t.delete(r):tn(t,"delete")},{hasContent:!1,type:"delete"});static getNewId(){return(0,_G.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={}),Ze(n,()=>{let i=new this(s,n),o=i.update?i.update(r,!0):tn(i,"update");return n.newLocation=s,n.createdResource=!0,o?.then?o.then(()=>s):s})}static invalidate=en(function(t,r,n,s){return t.invalidate?t.invalidate(r):tn(t,"delete")},{hasContent:!1,type:"update"});static post=en(function(t,r,n,s){return t[Le]!=null&&t.update?.(),t.post(s,r)},{hasContent:!0,type:"create"});static connect=en(function(t,r,n,s){return t.connect?t.connect(s,r):tn(t,"connect")},{hasContent:!0,type:"read"});static subscribe=en(function(t,r,n,s){return t.subscribe?t.subscribe(r):tn(t,"subscribe")},{type:"read"});static publish=en(function(t,r,n,s){return t[Le]!=null&&t.update?.(),t.publish?t.publish(s,r):tn(t,"publish")},{hasContent:!0,type:"create"});static search=en(function(t,r,n,s){let i=t.search?t.search(r):tn(t,"search"),o=n.select;if(o&&n.hasOwnProperty("select")&&i!=null&&!i.selectApplied){let c=sh(o,t.constructor);return i.map(c)}return i},{type:"read"});static query=en(function(t,r,n,s){return t.search?t.search(s,r):tn(t,"search")},{hasContent:!0,type:"read"});static copy=en(function(t,r,n,s){return t.copy?t.copy(s,r):tn(t,"copy")},{type:"create"});static move=en(function(t,r,n,s){return t.move?t.move(s,r):tn(t,"move")},{type:"delete"});post(t){if(this[kn])return this.constructor.create(this[Le],t,this[be]);tn(this,"post")}static isCollection(t){return t?.[kn]}static coerceId(t){return t}static parseQuery(t){return Xf(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&&Bie[o];if(c)r.headers.set("accept",c);else if(n)n.property=o;else return{query:{property:o},id:lG(t,this),isCollection:Pl}}let i=lG(t,this);return Pl?{id:i,isCollection:!0}:i}static getResource(t,r,n){let s,i=r[be],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 u;if(i.resourceCache?u=i.resourceCache:u=i.resourceCache=[],u.asMap){let _=u.asMap.get(t);if(s=_?.find(l=>l.constructor===c),s)return s;_||u.asMap.set(t,_=[]),_.push(s=new c(t,i))}else{if(s=u.find(_=>_[Le]===t&&_.constructor===c),s)return s;if(u.push(s=new c(t,i)),u.length>10){let _=new Map;for(let l of u){let d=l[Le],E=_.get(d);E?E.push(l):_.set(d,[l])}i.resourceCache.length=0,i.resourceCache.asMap=_}}}else s=new c(t,i);return o&&(s[kn]=!0),s}subscribe(t){return new yn}connect(t){return t?.subscribe!==!1?this.subscribe?.(t):new yn}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[be]}};$t.prototype[be]=null;(0,dG._assignPackageExport)("Resource",$t);a(xie,"snake_case");nh=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(lG,"pathToId");GA=class extends Array{static{a(this,"MulitPartId")}toString(){return this.join("/")}};a(en,"transactional");a(tn,"missingMethod");a(HA,"selectFromObject");a(sh,"transformForSelect")});function mG(e,t,r,n,s){let i=e.primaryStore.env.path,o=e.primaryStore.tableId,c;s?.crossThreads===!1?(c=hG,Hie(e.primaryStore,e.auditStore)):(c=EG,e.primaryStore.env.hasSubscriptionCommitListener||(e.primaryStore.env.hasSubscriptionCommitListener=!0,e.primaryStore.on("committed",()=>{pG(EG[i])})));let u=c[i]||(c[i]=[]);u.auditStore=e.auditStore,u.lastTxnTime==null&&(u.lastTxnTime=Date.now());let _=u[o];_||(_=u[o]=new Map,_.envs=u,_.tableId=o,_.store=e.primaryStore),t=Ia(t);let l=new FA(r);l.startTime=n;let d=_.get(t);return d?d.push(l):(_.set(t,d=[l]),d.tables=_,d.key=t),l.subscriptions=d,l}function pG(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,u,_=Ia(i.recordId),l=0;do{let d=o.get(_);if(d){for(let f of d)if(!(l>0&&!(f.includeDescendants&&!(f.onlyChildren&&l>1)))){if(f.startTime>=n){(0,qA.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,qA.info)(h)}}}if(_==null)break;let E=_.lastIndexOf?.("/",_.length-2);E>-1?_=_.slice(0,E):_=null,l++}while(!0)}if(r)for(let n of r)n.txnInProgress=null,n.listener(null,{type:"end_txn"},e.lastTxnTime,!0)}function Hie(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 u=hG[s];if(!u)return;let _=a(()=>{r.threadLocalWrites||(r.threadLocalWrites=new Float64Array(r.getUserSharedBuffer("last-thread-local-write",new ArrayBuffer(8)))),u.txnTime=r.threadLocalWrites[0]||Date.now(),pG(u),r.threadLocalWrites[0]=u.lastTxnTime,r.unlock("thread-local-writes")},"acquiredLock");r.attemptLock("thread-local-writes",_)&&_()})}}var qA,EG,hG,FA,SG=Re(()=>{qA=B($());bc();zu();ti();EG=Object.create(null),hG=Object.create(null);a(mG,"addSubscription");FA=class extends yn{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(pG,"notifyFromTransactionData");a(Hie,"listenToCommits")});var gR={};Fe(gR,{coerceType:()=>ih,makeTable:()=>ch,setServerUtilities:()=>Wie,updateResource:()=>oh});function ch(e){let{primaryKey:t,indices:r,tableId:n,tableName:s,primaryStore:i,databasePath:o,databaseName:c,auditStore:u,schemaDefined:_,dbisDB:l,sealed:d}=e,{expirationMS:E,evictionMS:f,audit:h,trackDeletes:p}=e,{attributes:S}=e;S||(S=[]);let T=Sm(i,n,u),R=0,b,C,x={},v=Promise.resolve(),F,M,Q;for(let K of S)(K.assignCreatedTime||K.name==="__createdtime__")&&(F=K),(K.assignUpdatedTime||K.name==="__updatedtime__")&&(M=K),K.expiresAt&&(Q=K),K.isPrimaryKey&&(x=K);let J,j=[],ae=[],ce=1,ge=2,Ge={},Ne={},ve=864e5,Xl,Zl,zs,cO=!1,bh,yh,Aq=i.getRange({start:!1,end:!1}).constructor,Oq=10,bq=6;h&&_O();class Je extends $t{static name=s;static primaryStore=i;static auditStore=u;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=F;static updatedTimeProperty=M;static propertyResolvers;static sources=[];static get expirationMS(){return E}static dbisDB=l;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(U=>U[L]&&(!U[L].reliesOnPrototype||U.prototype[L])),N.length>0)if(N.length===1){let U=N[0];return(k,D,H)=>{if(k?.source!==U)return U[L](D,H,k)}}else return(U,k,D)=>{let H=[];for(let G of N){if(U?.source===G)break;H.push(G[L](k,D,U))}return Promise.all(H)}},"getApplyToIntermediateSource"),y=this.sources[this.sources.length-1],O=a(L=>{if(y[L]&&(!y[L].reliesOnPrototype||y.prototype[L]))return(N,U,k)=>{if(!N?.source)return y[L](U,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(U,k)=>{let D=U.value,H=U.table?ct[c][U.table]:Je;if(c===$n.SYSTEM_SCHEMA_NAME&&(U.table===$n.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME||U.table===$n.SYSTEM_TABLE_NAMES.USER_TABLE_NAME)&&(L=!0),U.id===void 0&&(U.id=D[H.primaryKey],U.id===void 0))throw new Error("Replication message without an id "+JSON.stringify(U));U.source=m;let G=await H.getResource(U.id,k,sc);switch(U.type){case"put":return G._writeUpdate(D,!0,sc);case"patch":return G._writeUpdate(D,!1,sc);case"delete":return G._writeDelete(sc);case"publish":return G._writePublish(D,sc);case"invalidate":return G.invalidate(sc);default:it.error("Unknown operation",U.type,U.id)}},"writeUpdate");try{let U=m.subscribe;U&&p==null&&(p=!0);let k=m.subscribeOnThisThread?m.subscribeOnThisThread((0,vo.getWorkerIndex)()):(0,vo.getWorkerIndex)()===0,D=U&&k&&await m.subscribe?.({crossThreads:!1,inTransactionUpdates:!0,supportsTransactions:!0,omitCurrent:!0});if(D){let H;for await(let G of D)try{if(!(G.type==="transaction"?G.writes[0]:G)){it.error("Bad subscription event",G);continue}if(G.source=m,H)if(G.beginTxn)H.resolve();else{N(G,H);continue}if(G.type==="end_txn")continue;let me=Ze(G,()=>{if(G.type==="transaction"){let te=[];for(let Pe of G.writes)try{te.push(N(Pe,G))}catch(ue){throw ue.message+=" writing "+JSON.stringify(Pe)+" of event "+JSON.stringify(G),ue}return Promise.all(te)}else if(G.type==="define_schema"){let te=this.attributes.slice(0),Pe;for(let ue of G.attributes)te.find(qe=>qe.name===ue.name)||(te.push(ue),Pe=!0);Pe&&(Et({table:s,database:c,attributes:te,origin:"cluster"}),ql.signalSchemaChange(new Fl.SchemaEventMsg(process.pid,$n.OPERATIONS_ENUM.CREATE_TABLE,c,s)))}else return G.beginTxn?(H=G,N(G,G),new Promise(te=>{H.resolve=te})):N(G,G)});L&&(await me,ql.signalUserChange(new Fl.UserEventMsg(process.pid))),G.onCommit&&(me?.then?me.then(G.onCommit):G.onCommit())}catch(se){it.error("error in subscription handler",se)}}}catch(U){it.error(U)}})(),this}static getResource(m,A,w){let y=super.getResource(m,A,w);if(m!=null){uc(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=On(A),N=L.getReadTxn();if(N?.isDone)throw new Error("You can not read from a transaction that has already been committed/aborted");return Nh(m,A,{transaction:N},O,U=>{if(U?oh(y,U):y[de]=null,A.onlyIfCached&&A.noCacheStore){if(!y.doesExist())throw new rn.ServerError("Entry is not cached",504)}else if(w?.ensureLoaded){let k=Ih(m,U,A,y);if(k)return L?.disregardReadTxn(),y[kA]=!0,$A(k,D=>(oh(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=Ih(this[Le],this[Lr],this[be]);if(m)return this[kA]=!0,$A(m,A=>{this[Lr]=A,this[de]=A.value,this[Hl]=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,Ch()}static enableAuditing(m=!0){h=m,m&&_O(),Je.audit=m}static coerceId(m){return m===""?null:ih(m,x)}static async dropTable(){if(delete ct[c][s],c===o){for(let m of S)l.remove(Je.tableName+"/"+m.name),r[m.name]?.drop();l.remove(Je.tableName+"/"),i.drop(),await l.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));ql.signalSchemaChange(new Fl.SchemaEventMsg(process.pid,$n.OPERATIONS_ENUM.DROP_TABLE,c,s))}get(m){if(typeof m=="string")return this.getProperty(m);if(this[kn])return this.search(m);if(this[Le]===null){if(m?.conditions)return this.search(m);let A=Je.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[be]?.returnNonexistent)return this}allowRead(m,A){let w=t_(m);if(w?.read){if(w.isSuperUser)return!0;let y=w.attribute_permissions,O=A?.select;if(y?.length>0||cO&&O){if(A||(A={}),O){let L=y?.length>0&&VA(y,"read");A.select=O.map(N=>{let U=N.name||N;if(!L||L[U]){let k=zs[U]?.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&&!zs[L.attribute_name]).map(L=>L.attribute_name);return A}else return!0}}allowUpdate(m,A){let w=t_(m);if(w?.update){let y=w.attribute_permissions;if(y?.length>0){let O=VA(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[kn]){let w=t_(m);if(w?.insert){let y=w.attribute_permissions;if(y?.length>0){let O=VA(y,"insert");for(let L in A)if(!O[L])return!1}else return!0}}else return this.allowUpdate(m,{})}allowDelete(m){return t_(m)?.delete}update(m,A){if(!On(this[be]))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[Nt]=m):(y=this[Nt],y&&(m=Object.assign(y,m)),this[Nt]=y=m)),this._writeUpdate(this[Nt],A),this}addTo(m,A){if(typeof A=="number"||typeof A=="bigint")this[Ul]===gG?this.set(m,(+this.getProperty(m)||0)+A):(this[Ul]||this.update(),this.set(m,new th(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[Lr]}invalidate(m){let A=this[be],w=this[Le];uc(w),On(this[be]).addWrite({key:w,store:i,invalidated:!0,entry:this[Lr],nodeName:this[be]?.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 U in r)N||(N={}),N[U]=this.getProperty(U);T(w,N,this[Lr],O,vl,h,this[be],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,Bl,null,null,0,null,!0)}return i.ifVersion(m,w,()=>{e_(m,A,null)}),h?T(m,null,O,w,Bl,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,NG.operation(m,A)}put(m){this.update(m,!0)}patch(m){this.update(m,!1)}_writeUpdate(m,A,w){let y=this[be],O=On(y),L=this[Le];uc(L);let N=this[Lr];this[Ul]=A?gG:$ie;let U={key:L,store:i,entry:N,nodeName:y?.nodeName,validate:k=>{m||(m=this[Nt]),A||m&&ZE(this[Nt]===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),F&&(N?.value?m[F.name]=N?.value[F.name]:m[F.name]=F.type==="Date"?new Date(k):F.type==="String"?new Date(k).toISOString():k),m=Po(m))):O.removeWrite(U)},before:A?Ge.put?()=>Ge.put(y,L,m):null:Ge.patch?()=>Ge.patch(y,L,m):Ge.put?()=>Ge.put(y,L,Po(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,Po(this)):null,commit:(k,D,H)=>{if(H){if(y&&D?.version>(y.lastModified||0)&&(y.lastModified=D.version),this[Lr]=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[Nt]=void 0,this[Hl]=k;let G=D?.value,se=m;if(this[Ul]=0,D?.version>=k)if(h){let ue=D.localTime,qe=D.version;for(;se&&(ue>k||qe>=k&&ue>0);){let re=u.get(ue);if(!re)break;let X=vt(re);if(qe=X.version,qe>k){if(X.type==="patch"){let pe=X.getValue(i);se=jE(se,pe)}else if(X.type==="put"||X.type==="delete")return}else if(qe===k)return;ue=X.previousLocalTime}}else{if(A)return;se=jE(se,G)}let me;if(A?me=se:(this[de]=G,me=A?se:Po(this,se)),this[de]=me,me?.[de])throw new Error("Can not assign a record to a record, check for circular references");let te;A||(te=m),e_(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,te)}};O.addWrite(U)}async delete(m){if(typeof m=="string")return this.deleteProperty(m);if(this[kn]){for await(let A of this.search(m))(await Je.getResource(A[t],this.getContext(),{ensureLoaded:!1}))._writeDelete(m);return}return this[de]?this._writeDelete(m):!1}_writeDelete(m){let A=On(this[be]),w=this[Le];uc(w);let y=this[be];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 U=L?.value;N&&(y&&L?.version>(y.lastModified||0)&&(y.lastModified=L.version),oh(this,L)),!(L?.version>O)&&(e_(this[Le],U),it.trace("Write delete entry",w,O),h||p?(T(w,null,this[Lr],O,0,h,this[be],0,"delete"),h||Ch()):i.remove(this[Le]))}}),!0}search(m){let A=this[be],w=On(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(X,pe){let Be;switch(pe){case"and":case void 0:if(X.length<1)throw new Error('An "and" operator requires at least one condition');Be=!0;break;case"or":if(X.length<2)throw new Error('An "or" operator requires at least two conditions');break;default:throw new Error("Invalid operator "+pe)}let Yn=Be&&{},Js;for(let Ke of X){if(Ke.conditions){Ke.conditions=N(Ke.conditions,Ke.operator);continue}let kt=Ke[0]??Ke.attribute,on=kt==null?x:qs(S,kt);if(on){if(Be){let Kn=Hn(kt),Vt=Yn[Kn];Vt?(Vt.push(Ke),Js=!0):Yn[Kn]=[Ke]}(on.type||Kg[Ke.comparator])&&(Ke[1]===void 0?Ke.value=k(Ke.value,on):Ke[1]=k(Ke[1],on))}else if(kt!=null)throw(0,rn.handleHDBError)(new Error,`${kt} is not a defined attribute`,404)}if(m.enforceExecutionOrder)return X;if(Js)for(let Ke in Yn){let kt=Yn[Ke],on=kt.length;if(on>1)for(let Kn=0;Kn<on;Kn++){let Vt=kt[Kn];if(Vt.comparator==="ge"||Vt.comparator==="greater_than_equal")for(let js=0;js<on;js++){let qo=kt[js];(qo.comparator==="le"||qo.comparator==="less_than_equal")&&(Vt.comparator="between",Vt.value=[Vt.value,qo.value],X.splice(X.indexOf(qo),1))}if(Vt.comparator==="equals"||!Vt.comparator){for(let js=0;js<on;js++)if(js!==Kn){let qo=kt[js];X.splice(X.indexOf(qo),1)}break}}}return X}a(N,"prepareConditions");function U(X,pe){if(m.enforceExecutionOrder)return X;for(let Be of X)Be.conditions&&(Be.conditions=U(Be.conditions,Be.operator));return X.length>1&&pe!=="or"?(0,yG.sortBy)(X,jf(Je)):X}a(U,"orderConditions");function k(X,pe){return Array.isArray(X)?X.map(Be=>ih(Be,pe)):ih(X,pe)}a(k,"coerceTypedValues");let D=m.operator;(y.length>0||D)&&(y=N(y,D));let H=typeof m.sort=="object"&&m.sort,G;if(H&&D!=="or"){let X=H.attribute;if(O=y.find(pe=>Hn(pe.attribute)===Hn(X)),!O){let pe=qs(S,X);if(!pe)throw(0,rn.handleHDBError)(new Error,`${Array.isArray(X)?X.join("."):X} is not a defined attribute`,404);if(pe.indexed)O={attribute:X,comparator:"sort"},y.push(O);else if(y.length===0&&!m.allowFullScan)throw(0,rn.handleHDBError)(new Error,`${Array.isArray(X)?X.join("."):X} is not indexed and not combined with any other conditions`,404)}O&&(O.descending=!!H.descending)}y=U(y,D),H&&(O&&y[0]===O?H.next&&(G={dbOrderedAttribute:H.attribute,attribute:H.next.attribute,descending:H.next.descending,next:H.next.next}):(O&&y.splice(y.indexOf(O),1),G=H));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(),te=Wg(y,D,Je,me,m,A,(X,pe)=>uO(X,se,A,me,pe),L),Pe=m.ensureLoaded!==!1;G||(te=re(te));let ue=Je.transformEntryForSelect(se,A,me,L,Pe,!0),qe=Je.transformToOrderedSelect(te,se,G,me,A,ue);function re(X){return m.offset||m.limit!==void 0?X.slice(m.offset,m.limit!==void 0?(m.offset||0)+m.limit:void 0):X}return a(re,"applyOffset"),G&&(qe=re(qe)),qe.onDone=()=>{qe.onDone=null,w.doneReadTxn()},qe.selectApplied=!0,qe.getColumns=()=>{if(se){let X=[];for(let pe of se)pe==="*"?X.push(...S.map(Be=>Be.name)):X.push(pe.name||pe);return X}return S.map(X=>X.name)},qe}static transformToOrderedSelect(m,A,w,y,O,L){let N=new Aq;if(w){m=uO(m,A,y,O,null);let U;N.iterate=function(){let D,H=m[Symbol.asyncIterator]?m[Symbol.asyncIterator]():m[Symbol.iterator](),G,se=w.dbOrderedAttribute,me,te,Pe=!0;function ue(re){let X=re.next&&ue(re.next),pe=re.descending;return(Be,Yn)=>{let Js=wh(Be,re.attribute,y),Ke=wh(Yn,re.attribute,y),kt=pe?(0,Bo.compareKeys)(Ke,Js):(0,Bo.compareKeys)(Js,Ke);return kt===0?X?.(Be,Yn)||0:kt}}a(ue,"createComparator");let qe=ue(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)};U=[],me&&U.push(me);do if(re=await H.next(),re.done){if(G=!0,U.length)break;return N.onDone&&N.onDone(),re}else{let X=re.value;if(X?.then&&(X=await X),se){let pe=wh(X,se,y);if(Pe)Pe=!1,te=pe;else if(pe!==te){te=pe,me=X;break}}U.push(X)}while(!0);return w.isGrouped,U.sort(qe),D=U[Symbol.iterator](),re=D.next(),re.done?(N.onDone&&N.onDone(),re):{value:await L.call(this,re.value)}},return(){N.onDone&&N.onDone(),H.return()},throw(){N.onDone&&N.onDone(),H.throw()}}};let k=a(D=>{if(typeof A=="object"&&Array.isArray(D.attribute))for(let H=0;H<A.length;H++){let G=A[H],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[H]=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(H=>(A?.transaction?.stale&&(A.transaction.stale=!1),H?.key??H),"transform");return m===t?D:m.asArray?H=>[D(H)]:H=>({[t]:D(H)})}let N;O&&C&&!m?.every(D=>{let H;return typeof D=="object"?H=D.name:H=D,r[H]||H===t})&&(N=!0);let U,k=a(function(D){let H;if(A?.transaction?.stale&&(A.transaction.stale=!1),D!=null){if(bh=D,H=D.value||D.deref?.(),!H&&(D.key===void 0||D.deref)){if(D=Nh(D.key??D,A,{transaction:w,lazy:m?.length<4},this.isSync,G=>G),D?.then)return D.then(k.bind(this));H=D?.value}if(N&&(D.metadataFlags&(vl|Bl)||D.expiresAt&&D.expiresAt<Date.now())){let G=Ih(D.key??D,D,A);if(G?.then)return G.then(k)}}if(H==null)return L?Uo.SKIP:H;if(m&&!(m[0]==="*"&&m.length===1)){let G,se=a((te,Pe)=>{let ue;typeof te=="object"?ue=te.name:ue=te;let qe=zs?.[ue],re;if(qe){let X=y?.[ue];if(X)if(X.hasMappings){let Be=qe.from?H[qe.from]:Hn(D.key);re=X.get(Be),re||(re=[])}else re=X.fromRecord?.(H);else re=qe(H,A,D);let pe=a(Be=>{if(Be&&typeof Be=="object"){let Yn=qe.definition?.tableClass||Je;U||(U={});let Js=U[ue]||(U[ue]=Yn.transformEntryForSelect(ue===te?null:te.select||(Array.isArray(te)?te:null),A,w,X,O));if(Array.isArray(Be)){let Ke=[],kt=Yn.transformToOrderedSelect(Be,te.select,typeof te.sort=="object"&&te.sort,A,w,Js)[this.isSync?Symbol.iterator:Symbol.asyncIterator](),on=a(Vt=>{for(;!Vt.done;){if(Vt?.then)return Vt.then(on);Ke.push(Vt.value),Vt=kt.next()}Pe(Ke,ue)},"nextValue"),Kn=on(kt.next());Kn&&(G||(G=[]),G.push(Kn));return}else if(Be=Js.call(this,Be),Be?.then){G||(G=[]),G.push(Be.then(Ke=>Pe(Ke,ue)));return}}Pe(Be,ue)},"handleResolvedValue");re?.then?(G||(G=[]),G.push(re.then(pe))):pe(re);return}else re=H[ue],re&&typeof re=="object"&&ue!==te&&(re=Je.transformEntryForSelect(te.select||te,A,w,null)({value:re}));Pe(re,ue)},"selectAttribute"),me;if(typeof m=="string")se(m,te=>{me=te});else if(Array.isArray(m))if(m.asArray)me=[],m.forEach((te,Pe)=>{te==="*"?m[Pe]=H:se(te,ue=>me[Pe]=ue)});else{me={};let te=m.forceNulls;for(let Pe of m)if(Pe==="*")for(let ue in H)me[ue]=H[ue];else se(Pe,(ue,qe)=>{ue===void 0&&te&&(ue=null),me[qe]=ue})}else throw new rn.ClientError("Invalid select"+m);return G?Promise.all(G).then(()=>me):me}return H},"transform");return k}async subscribe(m){if(!u)throw new Error("Can not subscribe to a table without an audit log");h||Et({table:s,database:c,schemaDefined:_,attributes:S,audit:!0}),m||(m={});let A=!m.rawEvents,w=mG(Je,this[Le]??null,function(N,U,k,D){try{let H=U.getValue?.(i,A);if(!H&&U.type==="patch"&&A){let G=i.getEntry(N);G?.version===U.version?H=G.value:H=U.getValue?.(i,!0,k),U.type="put"}this.send({id:N,timestamp:k,value:H,version:U.version,type:U.type,beginTxn:D})}catch(H){it.error(H)}},m.startTime||0,m);this[kn]&&(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[kn]){if(L){if(O)throw new rn.ClientError("startTime and previousCount can not be combined for a table level subscription");for(let{key:N,value:U}of u.getRange({start:L,exclusiveStart:!0})){let k=vt(U);if(k.tableId!==n)continue;let D=k.recordId;if(y==null||OG(y,D)){let H=k.getValue(i,A,N);w.send({id:D,timestamp:N,value:H,version:k.version,type:k.type})}w.startTime=N}}else if(O){let N=[];for(let{key:U,value:k}of u.getRange({start:"z",end:!1,reverse:!0}))try{let D=vt(k);if(D.tableId!==n)continue;let H=D.recordId;if(y==null||OG(y,H)){let G=D.getValue(i,A,U);if(N.push({id:H,timestamp:U,value:G,version:D.version,type:D.type}),--O<=0)break}}catch(D){it.error("Error getting history entry",U,D)}for(let U=N.length;U>0;)w.send(N[--U]);N[0]&&(w.startTime=N[0].timestamp)}else if(!m.omitCurrent)for(let{key:N,value:U,version:k,localTime:D}of i.getRange({start:y??!1,end:y==null?void 0:[y,Bo.MAXIMUM_KEY],versions:!0}))U&&w.send({id:N,timestamp:D,value:U,version:k,type:"put"})}else{O&&!L&&(L=0);let N=this[Lr]?.localTime;if(N===pm&&(i.cache?.delete(y),this[Lr]=i.getEntry(y),it.trace("re-retrieved record",N,this[Lr]?.localTime),N=this[Lr]?.localTime),it.trace("Subscription from",L,"from",y,N),L<N){let U=[],k=N;do{let D=u.get(k);if(D){m.omitCurrent=!0;let H=vt(D),G=H.getValue(i,A,k);A&&(H.type="put"),U.push({id:y,value:G,timestamp:k,...H}),k=H.previousLocalTime}else break;O&&O--}while(k>L&&O!==0);for(let D=U.length;D>0;)w.send(U[--D]);w.startTime=N}!m.omitCurrent&&this.doesExist()&&w.send({id:y,timestamp:N,value:this[de],version:this[Hl],type:"put"})}return m.listener&&w.on("data",m.listener),w}doesExist(){return!!(this[de]||this[Ul])}publish(m,A){this._writePublish(m,A)}_writePublish(m,A){let w=On(this[be]),y=this[Le]||null;uc(y);let O=this[be];w.addWrite({key:y,store:i,entry:this[Lr],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,U)=>{N===void 0&&p&&!h&&Ch(),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 ${Vn(O)} in property ${N} must be an object${L.type?" ("+L.type+")":""}`);let U=L.properties;for(let k=0,D=U.length;k<D;k++){let H=U[k],G=y(O[H.name],H,N+"."+H.name);G&&(O[H.name]=G)}if(L.sealed&&O!=null&&typeof O=="object")for(let k in O)U.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 ${Vn(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 ${Vn(O)} in property ${N} must be an integer (from -9007199254740992 to 9007199254740992)`);break;case"Float":typeof O!="number"&&(w||(w=[])).push(`Value ${Vn(O)} in property ${N} must be a number`);break;case"ID":typeof O=="string"||O?.length>0&&O.every?.(U=>typeof U=="string")||(w||(w=[])).push(`Value ${Vn(O)} in property ${N} must be a string, or an array of strings`);break;case"String":typeof O!="string"&&(w||(w=[])).push(`Value ${Vn(O)} in property ${N} must be a string`);break;case"Boolean":typeof O!="boolean"&&(w||(w=[])).push(`Value ${Vn(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 ${Vn(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 ${Vn(O)} in property ${N} must be a bigint`)}break;case"Bytes":O instanceof Uint8Array||(w||(w=[])).push(`Value ${Vn(O)} in property ${N} must be a Buffer or Uint8Array`);break;case"array":if(Array.isArray(O)){if(L.elements)for(let U=0,k=O.length;U<k;U++){let D=O[U],H=y(D,L.elements,N+"[*]");H&&(O[U]=H)}}else(w||(w=[])).push(`Value ${Vn(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 U=y(m[N.name],N,N.name);U&&(m[N.name]=U)}}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 rn.ClientError(w.join(". "))}getUpdatedTime(){return this[Hl]}wasLoadedFromSource(){return C?!!this[kA]:void 0}static async addAttributes(m){let A=S.slice(0);for(let w of m){if(!w.name)throw new rn.ClientError("Attribute name is required");if(w.name.match(/[`/]/))throw new rn.ClientError("Attribute names cannot include backticks or forward slashes");A.push(w)}return Et({table:s,database:c,schemaDefined:_,attributes:A}),Je.indexingOperation}static async removeAttributes(m){let A=S.filter(w=>!m.includes(w.name));return Et({table:s,database:c,schemaDefined:_,attributes:A}),Je.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 U=O*2,k=(L+N)/U,D=Math.pow((L-N+1)/O/2,2)+k*(1-k)/U,H=Math.max(Math.sqrt(D)*A,1),G=Math.round(k*A),se=Math.max(G-1.96*H,0),me=Math.min(G+1.96*H,A),te=Math.pow(10,Math.round(Math.log10(H)));return te>G&&(te=te/10),L=Math.round(G/te)*te,{recordCount:L,estimatedRange:[Math.round(se),Math.round(me)]}}return{recordCount:L}}static updatedAttributes(){zs=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)"),cO=!0,A.to)m.elements?.definition?(zs[m.name]=m.resolve=(w,y,O)=>{let L=w[A.from?A.from:t],N=m.elements.definition.tableClass;return O?Ha({attribute:A.to,value:L},On(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?(zs[m.name]=m.resolve=(y,O,L)=>{let N=y[A.from];if(N!==void 0){if(m.elements){let U,k=N.map(D=>{let H=L?w.tableClass.primaryStore.getEntry(D,{transaction:On(O).getReadTxn()}):w.tableClass.get(D,O);return H?.then&&(U=!0),H});return A.filterMissing?U?Promise.all(k).then(D=>D.filter(bG)):k.filter(bG):U?Promise.all(k):k}return L?w.tableClass.primaryStore.getEntry(N,{transaction:On(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`)}rh(this,this)}static async deleteHistory(m=0){let A;for(let{key:w,value:y}of u.getRange({start:0,end:m}))await xl(),vt(y).tableId===n&&(A=u.remove(w));await A}static async*getHistory(m=0,A=1/0){for(let{key:w,value:y}of u.getRange({start:m,end:A})){await xl();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 xl();let L=u.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()}}Je.updatedAttributes();let yq=Je.prototype;return yq[Vie]=!0,E&&Je.setTTLExpiration(E/1e3),Q&&Nq(),Je;function e_(K,m,A){let w;for(let y in r){let O=r[y],L=O.isIndexing,N=A?.[y],U=m?.[y];if(N===U&&!L)continue;w=!0;let k=O.indexNulls,D=(0,Gl.getIndexedValues)(N,k),H=(0,Gl.getIndexedValues)(U,k);if(H?.length>0){let G=new Set(H);if(D=D?D.filter(se=>{if(G.has(se))G.delete(se);else return!0}):[],H=Array.from(G),(H.length>0||D.length>0)&&TG){let se=H.concat(D).map(me=>({key:me,value:K}));O.prefetch(se,AG)}for(let se=0,me=H.length;se<me;se++)O.remove(H[se],K)}else D?.length>0&&TG&&O.prefetch(D.map(G=>({key:G,value:K})),AG);if(D)for(let G=0,se=D.length;G<se;G++)O.put(D[G],K)}return w}a(e_,"updateIndices");function uc(K){switch(typeof K){case"number":return!0;case"string":if(K.length<659)return!0;if(K.length>RG)throw new Error("Primary key size is too large: "+K.length);break;case"object":if(K===null)return!0;break;case"bigint":if(K<2n**64n&&K>-(2n**64n))return!0;break;default:throw new Error("Invalid primary key type: "+typeof K)}if((0,Bo.writeKey)(K,Yie,0)>RG)throw new Error("Primary key size is too large: "+K.length);return!0}a(uc,"checkValidId");function Nh(K,m,A,w,y){let O=a(()=>{if(m?.transaction?.stale&&(m.transaction.stale=!1),A.transaction?.isDone)return y(null,K);let L=i.getEntry(K,A);return L&&m&&(L?.version>(m.lastModified||0)&&(m.lastModified=L.version),L?.localTime&&!m.lastRefreshed&&(m.lastRefreshed=L.localTime)),y(L,K)},"whenPrefetched");return w?O():ce>0?(ce--,O()):new Promise((L,N)=>{ce===0?(ce--,i.prefetch([K],()=>{U(),k()})):(j.push(K),ae.push(k),j.length>bq&&(ce--,U()));function U(){if(j.length>0){let D=ae;i.prefetch(j,()=>{ce===-1?U():ce++;for(let H of D)H()}),j=[],ae=[],ge>2&&ge--}else ce=ge,ge<Oq&&ge++}a(U,"prefetch");function k(){try{L(O())}catch(D){N(D)}}a(k,"load")})}a(Nh,"loadLocalRecord");function t_(K){if(!K?.role)return;let m=K.role.permission;if(m.super_user)return Kie;let A=m[c],w,y=A?.tables;if(y)return y[s];if(c==="data"&&(w=m[s])&&!w.tables)return w}a(t_,"getTablePermissions");function Ih(K,m,A,w){if(C){let y;if(A.noCache?y=!0:(m?(!m.value||m.metadataFlags&(vl|Bl)||m.expiresAt&&m.expiresAt<Date.now())&&(y=!0):y=!0,Wr(!y,"cache-hit",s)),y){let O=lO(K,m,A).then(L=>(L?.value?.[de]&&it.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,K)){if(O.catch(L=>it.warn(L)),A?.onlyIfCached&&!w.doesExist())throw new rn.ServerError("Entry is not cached",504);return}else return O}}}a(Ih,"ensureLoadedFromSource");function On(K){let m=K?.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 to,m.lmdbDb=i,m;m=A}while(!0)}else return new Ed}a(On,"txnForContext");function wh(K,m,A){if(!K)return;bh=K;let w=K.value||K.deref?.()||(bh=i.getEntry(K.key))?.value;if(typeof m=="object"){let O=zs,L=w;for(let N=0,U=m.length;N<U;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=zs[m];return y?y(w,A):w[m]}a(wh,"getAttributeValue");function uO(K,m,A,w,y){let O=y?.length,L={transaction:w,lazy:O>0||typeof m=="string"||m?.length<4,alwaysPrefetch:!0},N;function U(k,D){let H=k?.value;if(!H)return Uo.SKIP;for(let G=0;G<O;G++)if(!N?.includes(G)&&!y[G](H,k))return Uo.SKIP;return D!==void 0&&(k.key=D),k}if(a(U,"processEntry"),O>0||!K.hasEntries){let k=K.map(D=>{if(N=null,typeof D=="object"&&D?.key!==void 0)return O>0?U(D):D;if(D==null)return Uo.SKIP;for(let H=0;H<O;H++){let se=y[H].idFilter;if(se){if(!se(D))return Uo.SKIP;N||(N=[]),N.push(H)}}return Nh(D,A,L,!1,U)});return Array.isArray(K)&&(k=k.filter(D=>D!==Uo.SKIP)),k.hasEntries=!0,k}return K}a(uO,"transformToEntries");async function lO(K,m,A){let w=m?.metadataFlags,y=m?.version,O,L;if(!i.attemptLock(K,y,()=>{clearTimeout(L);let D=i.getEntry(K);!D||!D.value||D.metadataFlags&(vl|Bl)?O(lO(K,i.getEntry(K),A)):O(D)}))return new Promise(D=>{O=D,L=setTimeout(()=>{i.unlock(K,y)},kie)});let N=m?.value,U={requestContext:A,replacingRecord:N,replacingVersion:y,noCacheStore:!1,source:null,resourceCache:A?.resourceCache},k=A?.responseHeaders;return new Promise((D,H)=>{let G;$A(Ze(U,async se=>{let me=performance.now(),te,Pe,ue;try{for(let pe of Je.sources)if(pe.get&&(!pe.get.reliesOnPrototype||pe.prototype.get)&&(U.source=pe,te=await pe.get(K,U),te))break;ue=w&vl;let re=U.lastModified||ue&&y;Pe=ue||re>y||!N,re||(re=(0,Gl.getNextMonotonicTime)());let X=performance.now()-me;if(Sr(X,"cache-resolution",s),k&&hg(k,"Server-Timing",`cache-resolve;dur=${X.toFixed(2)}`,!0),se.timestamp=re,E&&!U.expiresAt&&(U.expiresAt=Date.now()+E),te){if(typeof te!="object")throw new Error("Only objects can be cached and stored in tables");typeof te.toJSON=="function"&&(te=te.toJSON()),t&&te[t]!==K&&(te[t]=K)}G=!0,D({version:re,value:te})}catch(re){re.message+=` while resolving record ${K} 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}),it.trace(re.message,"(returned stale record)")):H(re),U.transaction.abort();return}if(A?.noCacheStore||U.noCacheStore){U.transaction.abort();return}On(U).addWrite({key:K,store:i,entry:m,nodeName:"source",commit:(re,X)=>{if(X?.version!==y)return;let pe=e_(K,N,te);te?(Ne.put?.(U,K,te),T(K,te,X,re,0,h&&Pe||null,U,U.expiresAt,"put",!!ue)):(Ne.delete?.(U,K),h||p?T(K,null,X,re,0,h&&Pe||null,U,0,"delete",!!ue):i.remove(K,y))}})}),()=>{i.unlock(K,y)},se=>{i.unlock(K,y),G&&it.error("Error committing cache update",se)})})}a(lO,"getFromSource");function Ch(){if(ve!==Xl&&(Xl=ve,(0,vo.getWorkerIndex)()===(0,vo.getWorkerCount)()-1)){if(Zl&&clearTimeout(Zl),!ve)return;let K=new Date;K.setMonth(0),K.setDate(1),K.setHours(0),K.setMinutes(0),K.setSeconds(0);let m=Math.ceil((Date.now()-K.getTime())/ve)*ve+K.getTime(),A=a(w=>{it.trace(`Scheduled next cleanup scan at ${new Date(w)}ms`),Zl=setTimeout(()=>v=v.then(async()=>{if(A(Math.max(w+ve,Date.now())),i.rootStore.status!=="open"){clearTimeout(Zl);return}let y=50,O=new Array(y),L=0;it.trace(`Starting cleanup scan for ${s}`);try{let N=0;for(let{key:U,value:k,version:D,expiresAt:H}of i.getRange({start:!1,snapshot:!1,versions:!0,lazy:!0})){let G;k===null&&!h&&D+Fie<Date.now()?G=i.remove(U,D):H&&H+f<Date.now()&&(G=Je.evict(U,k,D),N++),G&&(await O[L],O[L]=G.catch(se=>{it.error("Cleanup error",se)}),++L>=y&&(L=0)),await xl()}it.trace(`Finished cleanup scan for ${s}, evicted ${N} entries`)}catch(N){it.trace(`Error in cleanup scan for ${s}:`,N)}}),Math.min(w-Date.now(),2147483647)).unref()},"startNextTimer");A(m)}}a(Ch,"scheduleCleanup");function _O(){J=u?.addDeleteRemovalCallback(n,K=>{let m=i.getEntry(K);m?.value===null&&i.remove(K,m.version)})}a(_O,"addDeleteRemoval");function Nq(){(0,vo.getWorkerIndex)()===0&&setInterval(async()=>{if(!yh){yh=!0;try{let K=Q.name,m=r[K];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[K]<Date.now()&&Je.evict(w,y.value,y.version):i.ifVersion(w,y?.version,()=>m.remove(A,w))}await xl()}}catch(K){it.error("Error in evicting old records",K)}finally{yh=!1}}},qie).unref()}a(Nq,"runRecordExpirationEviction")}function VA(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 AG(){}function Wie(e){NG=e}function ih(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:(Qie.test(e)||(e+="Z"),new Date(e)):new Date(+e):!r||r==="Any"?(0,ah.autoCast)(e):e}function OG(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 $A(e,t,r){return e?.then?e.then(t,r):t(e)}function oh(e,t){e[Lr]=t,e[de]=t?.value??null,e[Hl]=t?.version}function bG(e){return e!=null}function Vn(e){try{return JSON.stringify(e)}catch{return e}}var $n,Uo,Gl,yG,kl,rn,ql,Fl,it,Bo,vo,ah,Gie,NG,qie,Fie,TG,kie,Hl,Vie,Lr,Ul,gG,$ie,kA,sc,vl,Bl,Yie,RG,Kie,ETe,Qie,xl,fE=Re(()=>{$n=B(P()),Uo=require("lmdb"),Gl=B(vr()),yG=require("lodash");Nn();aS();kl=B(Z());SG();rn=B(ne()),ql=B(ys()),Fl=B(Mn());Ae();Zf();it=B($());pd();ro();Bo=require("ordered-binary"),vo=B(We());ti();ah=B(z());Lc();Cs();zE();Ju();Gie=new Uint8Array(9);Gie[8]=192;qie=6e4,Fie=864e5;kl.initSync();TG=kl.get($n.CONFIG_PARAMS.STORAGE_PREFETCHWRITES),kie=1e4,Hl=Symbol.for("version"),Vie=Symbol.for("incremental-update"),Lr=Symbol("entry"),Ul=Symbol("is-saving"),gG=1,$ie=2,kA=Symbol("loaded-from-source"),sc={isNotification:!0,ensureLoaded:!1},vl=1,Bl=8,Yie=Buffer.allocUnsafeSlow(8192),RG=1978,Kie={read:!0,insert:!0,update:!0,delete:!0,isSuperUser:!0},ETe=(0,ah.convertToMS)(kl.get($n.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE))||864e5;a(ch,"makeTable");a(VA,"attributesAsObject");a(AG,"noop");a(Wie,"setServerUtilities");Qie=/[+-][0-9]{2}:[0-9]{2}|[a-zA-Z]$/;a(ih,"coerceType");a(OG,"isDescendantId");xl=a(()=>new Promise(setImmediate),"rest");a($A,"when");a(oh,"updateResource");a(bG,"exists");a(Vn,"stringify")});var ke={};Fe(ke,{database:()=>ca,databases:()=>ct,dropDatabase:()=>dS,dropTableMeta:()=>Zie,getDatabases:()=>mr,getDefaultCompression:()=>Rf,getTables:()=>zie,onUpdatedTable:()=>ZR,readMetaDb:()=>Vl,resetDatabases:()=>ku,table:()=>Et,tables:()=>Br});function zie(){return fh||mr(),Br||{}}function mr(){if(fh)return ct;fh=!0,ac=new Map;let e=(0,St.getHdbBasePath)()&&(0,ot.join)((0,St.getHdbBasePath)(),Ut.DATABASES_DIR_NAME),t=(0,St.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,St.get)(Ut.CONFIG_PARAMS.STORAGE_PATH)||e&&((0,nn.existsSync)(e)?e:(0,ot.join)((0,St.getHdbBasePath)(),Ut.LEGACY_DATABASES_DIR_NAME)),!!e){if((0,nn.existsSync)(e))for(let r of(0,nn.readdirSync)(e,{withFileTypes:!0})){let n=(0,ot.basename)(r.name,".mdb");r.isFile()&&(0,ot.extname)(r.name).toLowerCase()===".mdb"&&!t[n]?.path&&Vl((0,ot.join)(e,r.name),null,n)}if((0,nn.existsSync)((0,oc.getBaseSchemaPath)())){for(let r of(0,nn.readdirSync)((0,oc.getBaseSchemaPath)(),{withFileTypes:!0}))if(!r.isFile()){let n=(0,ot.join)((0,oc.getBaseSchemaPath)(),r.name),s=(0,ot.join)((0,oc.getTransactionAuditStoreBasePath)(),r.name);for(let i of(0,nn.readdirSync)(n,{withFileTypes:!0}))if(i.isFile()&&(0,ot.extname)(i.name).toLowerCase()===".mdb"){let o=(0,ot.join)(s,i.name);Vl((0,ot.join)(n,i.name),(0,ot.basename)(i.name,".mdb"),r.name,o,!0)}}}if(t)for(let r in t){let n=t[r],s=n.path;if((0,nn.existsSync)(s))for(let o of(0,nn.readdirSync)(s,{withFileTypes:!0}))o.isFile()&&(0,ot.extname)(o.name).toLowerCase()===".mdb"&&Vl((0,ot.join)(s,o.name),(0,ot.basename)(o.name,".mdb"),r);let i=n.tables;if(i)for(let o in i){let c=i[o],u=(0,ot.join)(c.path,(0,ot.basename)(o+".mdb"));(0,nn.existsSync)(u)&&Vl(u,o,r,null,!0)}}for(let r in ct){let n=ac.get(r);if(n){let s=ct[r];r.includes("delete")&&An.trace(`defined tables ${Array.from(n.keys())}`);for(let i in s)n.has(i)||(An.trace(`delete table class ${i}`),delete s[i])}else if(delete ct[r],r==="data"){for(let s in Br)delete Br[s];delete Br[Eh]}}return ac=null,ct}}function ku(){fh=!1;for(let[,e]of Ui)e.needsDeletion=!0;mr();for(let[e,t]of Ui)t.needsDeletion&&!e.endsWith("system.mdb")&&(t.close(),Ui.delete(e));return ct}function Vl(e,t,r=WA,n,s){let i=new YA.default(e,!1);try{let o=Ui.get(e);o?o.needsDeletion=!1:(o=(0,lh.open)(i),Ui.set(e,o));let c=new xo.default(!1),u=o.dbisDb||(o.dbisDb=o.openDB(uh.INTERNAL_DBIS_NAME,c)),_=o.auditStore;_||(n?(0,nn.existsSync)(n)&&(i.path=n,_=(0,lh.open)(i),_.isLegacy=!0):_=QE(o));let l=DG(r),d=l[Eh],E=new Map;for(let{key:f,value:h}of u.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 j of p)if(j.is_hash_attribute||j.isPrimaryKey){S=j;break}if(!S){An.fatal(`Unable to find a primary key attribute on table ${f}, with attributes: ${JSON.stringify(p)}`);continue}}let T=l[f],R={},b=[],C,x,v=typeof S.audit=="boolean"?S.audit:(0,St.get)(Ut.CONFIG_PARAMS.LOGGING_AUDITLOG),F=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>=(u.get(ic)||0)&&u.putSync(ic,C+1):(S.tableId=C=u.get(ic),C||(C=1),u.putSync(ic,C+1),u.putSync(S.key,S));let j=new xo.default(!S.is_hash_attribute,S.is_hash_attribute);if(j.compression=S.compression,j.compression){let ae=(0,St.get)(Ut.CONFIG_PARAMS.STORAGE_COMPRESSION_THRESHOLD)||CG;j.compression.threshold=ae}x=g_(o.openDB(S.key,j)),x.rootStore=o,x.tableId=C}for(let j of p){j.attribute=j.name;try{if(!j.is_hash_attribute&&(j.indexed||j.attribute&&!j.name)){if(!R[j.name]){let ce=new xo.default(!j.is_hash_attribute,j.is_hash_attribute);R[j.name]=o.openDB(j.key,ce),R[j.name].indexNulls=j.indexNulls}let ae=b.find(ce=>ce.name===j.name);ae?b.splice(b.indexOf(ae),1,j):b.push(j)}}catch(ae){An.error("Error trying to update attribute",j,b,R,ae)}}if(!T){T=LG(l,f,ch({primaryStore:x,auditStore:_,audit:v,sealed:J,expirationMS:M&&M*1e3,evictionMS:Q&&Q*1e3,trackDeletes:F,tableName:f,tableId:C,primaryKey:S.name,databasePath:s?r+"/"+f:r,databaseName:r,indices:R,attributes:p,schemaDefined:S.schemaDefined,dbisDB:u})),T.schemaVersion=1;for(let j of QA)j(T)}}return o}catch(o){throw o.message+=` opening database ${e}`,o}}function DG(e){let t=ct[e];if(t||(e==="data"?t=ct[e]=Br:e==="system"?Object.defineProperty(ct,"system",{value:t=Object.create(null),configurable:!0}):t=ct[e]=Object.create(null)),ac&&!ac.has(e)){let r=new Set;t[Eh]=r,ac.set(e,r)}return t}function LG(e,t,r){return e[t]=r,r}function ca({database:e,table:t}){e||(e=WA),mr();let r=DG(e),n=(0,ot.join)((0,St.getHdbBasePath)(),Ut.DATABASES_DIR_NAME),s=(0,St.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,St.get)(Ut.CONFIG_PARAMS.STORAGE_PATH)||((0,nn.existsSync)(n)?n:(0,ot.join)((0,St.getHdbBasePath)(),Ut.LEGACY_DATABASES_DIR_NAME));let o=(0,ot.join)(n,(i?t:e)+".mdb"),c=Ui.get(o);if(!c){let u=new YA.default(o,!1);c=(0,lh.open)(u),Ui.set(o,c)}return c}async function dS(e){if(!ct[e])throw new Error("Schema does not exist");let t=ct[e],r;for(let n in t)r=t[n].primaryStore.rootStore,Ui.delete(r.path),r.status==="open"&&(await r.close(),await $l.remove(r.path));if(r||(r=ca({database:e,table:null}),r.status==="open"&&(await r.close(),await $l.remove(r.path))),e==="data"){for(let n in Br)delete Br[n];delete Br[Eh]}delete ct[e]}function Et({table:e,database:t,expiration:r,eviction:n,scanInterval:s,attributes:i,audit:o,sealed:c,trackDeletes:u,schemaDefined:_,origin:l}){t||(t=WA);let d=ca({database:t,table:e}),E=ct[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 xo.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=QE(d)),p=i.find(ae=>ae.isPrimaryKey)||{},h=p.name,p.is_hash_attribute=!0,p.schemaDefined=_,p.compression=Rf(),u&&(p.trackDeletes=!0),o=p.audit=typeof o=="boolean"?o:(0,St.get)(Ut.CONFIG_PARAMS.LOGGING_AUDITLOG),r&&(p.expiration=r),n&&(p.eviction=n),typeof c=="boolean"&&(p.sealed=c),l&&(p.origins?p.origins.includes(l)||p.origins.push(l):p.origins=[l]),An.trace(`${e} table loading, opening primary store`);let Q=new xo.default(!1,!0);Q.compression=p.compression;let J=e+"/",j=g_(d.openDB(J,Q));j.rootStore=d,T=d.dbisDb=d.openDB(uh.INTERNAL_DBIS_NAME,R),j.tableId=T.get(ic),j.tableId||(j.tableId=1),T.putSync(ic,j.tableId+1),p.tableId=j.tableId,f=LG(E,e,ch({primaryStore:j,auditStore:M,audit:o,sealed:c,trackDeletes:u,expirationMS:r&&r*1e3,evictionMS:n&&n*1e3,primaryKey:h,tableName:e,tableId:j.tableId,databasePath:t,databaseName:t,indices:{},attributes:i,schemaDefined:_,dbisDB:T})),f.schemaVersion=1,b=!0,F(),T.put(J,p)}S=f.indices,T=T||(d.dbisDb=d.openDB(uh.INTERNAL_DBIS_NAME,R)),f.dbisDB=T;let x=[];for(let{key:M,value:Q}of T.getRange({start:!0})){let[J,j]=M.toString().split("/");if(j===""&&(j=Q.name),j){if(J!==e)continue}else j=J;if(!i.find(ce=>ce.name===j)?.indexed&&Q.indexed&&!Q.isPrimaryKey){F(),b=!0,T.remove(M);let ce=f.indices[J];ce&&x.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,F(),T.put(Q,ae)}continue}J?.attribute&&!J.name&&(J.indexed=!0);let j=!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 xo.default(!0,!1),ce=d.openDB(Q,ae);(j||J.indexingPID&&J.indexingPID!==process.pid||J.restartNumber<Yl.workerData?.restartNumber)&&(b=!0,F(),J=T.get(Q),(j||J.indexingPID&&J.indexingPID!==process.pid||J.restartNumber<Yl.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 j&&(b=!0,F(),T.put(Q,M))}}finally{C&&C()}if(b&&(f.schemaVersion++,f.updatedAttributes()),An.trace(`${e} table loading, running index`),v.length>0||x.length>0?f.indexingOperation=Xie(f,v,x):b&&_h.signalSchemaChange(new dh.SchemaEventMsg(process.pid,"schema-change",f.databaseName,f.tableName)),f.origin=l,b)for(let M of QA)M(f,l!=="cluster");return(r||n||s)&&f.setTTLExpiration({expiration:r,eviction:n,scanInterval:s}),An.trace(`${e} table loaded`),f;function F(){C||d.transactionSync(()=>({then(M){C=M}}))}a(F,"startTxn")}async function Xie(e,t,r){try{let n=e.schemaVersion;await _h.signalSchemaChange(new dh.SchemaEventMsg(process.pid,"schema-change",e.databaseName,e.tableName));let s;for(let u of r)s=u.drop();let i,o=0,c=t.length;if(await new Promise(u=>setImmediate(u)),c>0){let u=0;for(let{key:_,value:l,version:d}of e.primaryStore.getRange({start:t[0].lastIndexedKey,lazy:c<4,versions:!0,snapshot:!1}))if(l){if(u++,s=e.primaryStore.ifVersion(_,d,()=>{for(let E=0;E<c;E++){let f=t[E],h=f.name,p=(0,IG.getIndexedValues)(l[h]);if(p)for(let S=0,T=p.length;S<T;S++)f.dbi.put(p[S],_)}}),s.then(()=>u--,E=>{u--,An.error(E)}),Yl.workerData&&Yl.workerData.restartNumber!==wG.restartNumber&&(i=!0),++o%100===0||i){for(let E of t)E.lastIndexedKey=_,e.dbisDB.put(E.key,E);if(i)return}u>Jie?await s:u>jie&&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 _h.signalSchemaChange(new dh.SchemaEventMsg(process.pid,"indexing-finished",e.databaseName,e.tableName))}catch(n){An.error("Error in indexing",n)}}function Zie({table:e,database:t}){let r=ca({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 ZR(e){QA.push(e)}function Rf(){let e=(0,St.get)(Ut.CONFIG_PARAMS.STORAGE_COMPRESSION),t=(0,St.get)(Ut.CONFIG_PARAMS.STORAGE_COMPRESSION_DICTIONARY),r=(0,St.get)(Ut.CONFIG_PARAMS.STORAGE_COMPRESSION_THRESHOLD)||CG,n={startingOffset:32};return t&&(n.dictionary=$l.readFileSync(t)),r&&(n.threshold=r),e&&n}var St,uh,lh,ot,nn,oc,xo,YA,Ut,$l,KA,IG,_h,dh,Yl,An,wG,WA,Eh,CG,Br,ct,ic,QA,fh,Ui,ac,Jie,jie,Ae=Re(()=>{St=B(Z()),uh=B(ft()),lh=require("lmdb"),ot=require("path"),nn=require("fs"),oc=B(je());fE();xo=B(Mc()),YA=B(Pc()),Ut=B(P()),$l=B(require("fs-extra")),KA=require("../index"),IG=B(vr()),_h=B(ys()),dh=B(Mn()),Yl=require("worker_threads"),An=B($()),wG=B(We());ti();Lc();WA="data",Eh=Symbol("defined-tables"),CG=((0,St.get)(Ut.CONFIG_PARAMS.STORAGE_PAGESIZE)||4096)-60;(0,St.initSync)();Br=Object.create(null),ct=Object.create(null);(0,KA._assignPackageExport)("databases",ct);(0,KA._assignPackageExport)("tables",Br);ic=Symbol.for("next-table-id"),QA=[],Ui=new Map;a(zie,"getTables");a(mr,"getDatabases");a(ku,"resetDatabases");a(Vl,"readMetaDb");a(DG,"ensureDB");a(LG,"setTable");a(ca,"database");a(dS,"dropDatabase");a(Et,"table");Jie=1e3,jie=10;a(Xie,"runIndexing");a(Zie,"dropTableMeta");a(ZR,"onUpdatedTable");a(Rf,"getDefaultCompression")});var z=g((OTe,YG)=>{"use strict";var vi=require("path"),BG=require("fs-extra"),Mr=$(),MG=require("fs-extra"),hh=require("os"),eoe=require("net"),toe=require("recursive-iterator"),dt=P(),roe=$O(),PG=require("papaparse"),mh=require("moment"),{inspect:noe}=require("util"),UG=require("is-number"),ATe=require("lodash"),soe=require("minimist"),ioe=require("https"),ooe=require("http"),{hdb_errors:ph}=ne(),aoe=/^((\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)))$/,xG=require("util").promisify(setTimeout),coe=100,uoe=5,loe="",_oe=4,vG={true:!0,TRUE:!0,FALSE:!1,false:!1,undefined:null,null:null,NULL:null,NaN:NaN};YG.exports={isEmpty:sn,isEmptyOrZeroLength:ms,arrayHasEmptyValues:Eoe,arrayHasEmptyOrZeroLengthValues:hoe,buildFolderPath:moe,isBoolean:HG,errorizeMessage:doe,stripFileExtension:Soe,autoCast:Toe,autoCastJSON:GG,autoCastJSONDeep:JA,removeDir:goe,compareVersions:Roe,isCompatibleDataVersion:Aoe,escapeRawValue:Ooe,unescapeValue:boe,stringifyProps:yoe,timeoutPromise:Ioe,isClusterOperation:Coe,getClusterUser:Loe,checkGlobalSchemaTable:Doe,getHomeDir:FG,getPropsFilePath:Noe,promisifyPapaParse:Moe,removeBOM:kG,createEventPromise:Poe,checkProcessRunning:Uoe,checkSchemaTableExist:voe,checkSchemaExists:VG,checkTableExists:$G,getStartOfTomorrowInSeconds:Boe,getLimitKey:xoe,isObject:poe,isNotEmptyAndHasValue:foe,autoCasterIsNumberCheck:qG,backtickASTSchemaItems:Hoe,isPortTaken:woe,createForkArgs:Goe,autoCastBoolean:qoe,async_set_timeout:xG,getTableHashAttribute:Foe,doesSchemaExist:koe,doesTableExist:Voe,stringifyObj:$oe,ms_to_time:Yoe,changeExtension:Koe,getEnvCliRootPath:jA,noBootFile:Woe,httpRequest:Qoe,transformReq:zoe,convertToMS:Joe,PACKAGE_ROOT:dt.PACKAGE_ROOT};function doe(e){return e instanceof Error?e:new Error(e)}a(doe,"errorizeMessage");function sn(e){return e==null}a(sn,"isEmpty");function foe(e){return!sn(e)&&(e||e===0||e===""||HG(e))}a(foe,"isNotEmptyAndHasValue");function ms(e){return sn(e)||e.length===0||e.size===0}a(ms,"isEmptyOrZeroLength");function Eoe(e){if(sn(e))return!0;for(let t=0;t<e.length;t++)if(sn(e[t]))return!0;return!1}a(Eoe,"arrayHasEmptyValues");function hoe(e){if(ms(e))return!0;for(let t=0;t<e.length;t++)if(ms(e[t]))return!0;return!1}a(hoe,"arrayHasEmptyOrZeroLengthValues");function moe(...e){try{return e.join(vi.sep)}catch{console.error(e)}}a(moe,"buildFolderPath");function HG(e){return sn(e)?!1:e===!0||e===!1}a(HG,"isBoolean");function poe(e){return sn(e)?!1:typeof e=="object"}a(poe,"isObject");function Soe(e){return ms(e)?loe:e.slice(0,-_oe)}a(Soe,"stripFileExtension");function Toe(e){return sn(e)||e===""||typeof e!="string"?e:vG[e]!==void 0?vG[e]:qG(e)===!0?Number(e):aoe.test(e)?new Date(e):e}a(Toe,"autoCast");function GG(e){if(typeof e=="string"&&(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")))try{return JSON.parse(e)}catch{}return e}a(GG,"autoCastJSON");function JA(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=JA(n);s!==n&&(e[t]=s)}else for(let t in e){let r=e[t],n=JA(r);n!==r&&(e[t]=n)}return e}else return GG(e)}a(JA,"autoCastJSONDeep");function qG(e){if(e.startsWith("0.")&&UG(e))return!0;let t=e.toUpperCase().includes("E");return!!((e!=="0"&&e.startsWith("0"))===!1&&t===!1&&UG(e))}a(qG,"autoCasterIsNumberCheck");async function goe(e){if(ms(e))throw new Error(`Directory path: ${e} does not exist`);try{await MG.emptyDir(e),await MG.remove(e)}catch(t){throw Mr.error(`Error removing files in ${e} -- ${t}`),t}}a(goe,"removeDir");function Roe(e,t){if(ms(e)){Mr.info("Invalid current version sent as parameter.");return}if(ms(t)){Mr.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("."),u=Math.min(o.length,c.length);for(let _=0;_<u;_++)if(r=parseInt(o[_],10)-parseInt(c[_],10),r)return r;return o.length-c.length}a(Roe,"compareVersions");function Aoe(e,t,r=!1){let n=e.toString().split("."),s=t.toString().split(".");return n[0]===s[0]&&(!r||n[1]===s[1])}a(Aoe,"isCompatibleDataVersion");function Ooe(e){if(sn(e))return e;let t=String(e);return t==="."?dt.UNICODE_PERIOD:t===".."?dt.UNICODE_PERIOD+dt.UNICODE_PERIOD:t.replace(dt.FORWARD_SLASH_REGEX,dt.UNICODE_FORWARD_SLASH)}a(Ooe,"escapeRawValue");function boe(e){if(sn(e))return e;let t=String(e);return t===dt.UNICODE_PERIOD?".":t===dt.UNICODE_PERIOD+dt.UNICODE_PERIOD?"..":String(e).replace(dt.ESCAPED_FORWARD_SLASH_REGEX,"/")}a(boe,"unescapeValue");function yoe(e,t){if(sn(e))return Mr.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+hh.EOL}!ms(n)&&n[0]===";"?r+=" "+n+s+hh.EOL:ms(n)||(r+=n+"="+s+hh.EOL)}catch{Mr.error(`Found bad property during upgrade with key ${n} and value: ${s}`)}}),r}a(yoe,"stringifyProps");function FG(){let e;try{e=hh.homedir()}catch{e=process.env.HOME}return e||(e="~/"),e}a(FG,"getHomeDir");function Noe(){let e=vi.join(FG(),dt.HDB_HOME_DIR_NAME,dt.BOOT_PROPS_FILE_NAME);return BG.existsSync(e)||(e=vi.join(__dirname,"../","hdb_boot_properties.file")),e}a(Noe,"getPropsFilePath");function Ioe(e,t){let r,n;return n=new Promise(function(s){r=setTimeout(function(){s(t)},e)}),{promise:n,cancel:function(){clearTimeout(r)}}}a(Ioe,"timeoutPromise");async function woe(e){if(!e)throw new Error("Invalid port passed as parameter");return new Promise((t,r)=>{let n=eoe.createServer().once("error",s=>{s.code==="EADDRINUSE"?t(!0):r(s)}).once("listening",()=>n.once("close",()=>t(!1)).close()).listen(e)})}a(woe,"isPortTaken");function Coe(e){try{return dt.CLUSTER_OPERATIONS[e.toLowerCase()]!==void 0}catch(t){Mr.error(`Error checking operation against cluster ops ${t}`)}return!1}a(Coe,"isClusterOperation");function Doe(e,t){let r=(Ae(),ie(ke)).getDatabases();if(!r[e])return ph.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e);if(!r[e][t])return ph.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(Doe,"checkGlobalSchemaTable");function Loe(e,t){if(sn(t)){Mr.warn("No CLUSTERING_USER defined, clustering disabled");return}if(sn(e)||ms(e)){Mr.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){Mr.error(`unable to find cluster_user due to: ${n.message}`);return}if(r===void 0){Mr.warn(`CLUSTERING_USER: ${t} not found or is not active.`);return}return r}a(Loe,"getClusterUser");function Moe(){PG.parsePromise=function(e,t,r){return new Promise(function(n,s){PG.parse(e,{header:!0,transformHeader:kG,chunk:t.bind(null,s),skipEmptyLines:!0,transform:r,dynamicTyping:!1,error:s,complete:n})})}}a(Moe,"promisifyPapaParse");function kG(e){if(typeof e!="string")throw new TypeError(`Expected a string, got ${typeof e}`);return e.charCodeAt(0)===65279?e.slice(1):e}a(kG,"removeBOM");function Poe(e,t,r){return new Promise(n=>{t.once(e,s=>{let i=r;Mr.info(`Got cluster status event response: ${noe(s)}`);try{i.cancel()}catch{Mr.error("Error trying to cancel timeout.")}n(s)})})}a(Poe,"createEventPromise");async function Uoe(e){let t=!0,r=0;do await xG(coe*r++),(await roe.findPs(e)).length>0&&(t=!1);while(t&&r<uoe);if(t)throw new Error(`process ${e} was not started`)}a(Uoe,"checkProcessRunning");function voe(e,t){let r=VG(e);if(r)return r;let n=$G(e,t);if(n)return n}a(voe,"checkSchemaTableExist");function VG(e){let{getDatabases:t}=(Ae(),ie(ke));if(!t()[e])return ph.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}a(VG,"checkSchemaExists");function $G(e,t){let{getDatabases:r}=(Ae(),ie(ke));if(!r()[e][t])return ph.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a($G,"checkTableExists");function Boe(){let e=mh().utc().add(1,dt.MOMENT_DAYS_TAG).startOf(dt.MOMENT_DAYS_TAG).unix(),t=mh().utc().unix();return e-t}a(Boe,"getStartOfTomorrowInSeconds");function xoe(){return mh().utc().format("DD-MM-YYYY")}a(xoe,"getLimitKey");function Hoe(e){try{let t=new toe(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){Mr.error("Got an error back ticking items."),Mr.error(t)}}a(Hoe,"backtickASTSchemaItems");function Goe(e){return[e]}a(Goe,"createForkArgs");function qoe(e){return e===!0||typeof e=="string"&&e.toLowerCase()==="true"}a(qoe,"autoCastBoolean");function Foe(e,t){let{getDatabases:r}=(Ae(),ie(ke)),n=r()[e]?.[t];return n?.primaryKey||n?.hash_attribute}a(Foe,"getTableHashAttribute");function koe(e){let{getDatabases:t}=(Ae(),ie(ke));return t()[e]!==void 0}a(koe,"doesSchemaExist");function Voe(e,t){let{getDatabases:r}=(Ae(),ie(ke));return r()[e]?.[t]!==void 0}a(Voe,"doesTableExist");function $oe(e){try{return JSON.stringify(e)}catch{return e}}a($oe,"stringifyObj");function Yoe(e){let t=mh.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(Yoe,"ms_to_time");function Koe(e,t){let r=vi.basename(e,vi.extname(e));return vi.join(vi.dirname(e),r+t)}a(Koe,"changeExtension");function jA(){if(process.env[dt.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return process.env[dt.CONFIG_PARAMS.ROOTPATH.toUpperCase()];let e=soe(process.argv);if(e[dt.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return e[dt.CONFIG_PARAMS.ROOTPATH.toUpperCase()]}a(jA,"getEnvCliRootPath");var zA;function Woe(){if(zA)return zA;let e=jA();if(jA()&&BG.pathExistsSync(vi.join(e,dt.HDB_CONFIG_FILE)))return zA=!0,!0}a(Woe,"noBootFile");function Qoe(e,t){let r;return e.protocol==="http:"?r=ooe:r=ioe,new Promise((n,s)=>{let i=r.request(e,o=>{o.setEncoding("utf8");let c={body:"",headers:o.headers};o.on("data",u=>{c.body+=u}),o.on("end",()=>{n(c)})});i.on("error",o=>{s(o)}),i.write(JSON.stringify(t)),i.end()})}a(Qoe,"httpRequest");function zoe(e){if(!e.schema&&!e.database){e.schema=dt.DEFAULT_DATABASE_NAME;return}e.database&&(e.schema=e.database)}a(zoe,"transformReq");function Joe(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(Joe,"convertToMS")});var Z=g((yTe,JG)=>{"use strict";var XA=require("fs-extra"),Ho=require("path"),KG=require("os"),joe=require("properties-reader"),Wl=$(),Kl=z(),le=P(),Sh=Er(),Xoe="Error initializing environment manager",Th="BOOT_PROPS_FILE_PATH",WG=!1,Zoe={[le.HDB_SETTINGS_NAMES.INSTALL_USER]:!0,[le.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY]:!0,[le.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]:!0,BOOT_PROPS_FILE_PATH:!0},Ws={};JG.exports={BOOT_PROPS_FILE_PATH:Th,getHdbBasePath:eae,setHdbBasePath:tae,get:QG,initSync:nae,setProperty:Me,initTestEnvironment:iae,setCloneVar:sae};function eae(){return Ws[le.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]}a(eae,"getHdbBasePath");function tae(e){Ws[le.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=e}a(tae,"setHdbBasePath");function QG(e){let t=Sh.getConfigValue(e);return t===void 0?Ws[e]:t}a(QG,"get");function Me(e,t){Zoe[e]&&(Ws[e]=t),Sh.updateConfigObject(e,t)}a(Me,"setProperty");function rae(){let e;try{e=Kl.getPropsFilePath(),XA.accessSync(e,XA.constants.F_OK|XA.constants.R_OK),WG=!0;let t=joe(e);return Ws[le.HDB_SETTINGS_NAMES.INSTALL_USER]=t.get(le.HDB_SETTINGS_NAMES.INSTALL_USER),Ws[le.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY]=t.get(le.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY),Ws[Th]=e,!0}catch{return Wl.trace(`Environment manager found no properties file at ${e}`),!1}}a(rae,"doesPropFileExist");function nae(e=!1){try{(WG||rae()||Kl.noBootFile())&&!zG&&(Sh.initConfig(e),Ws[le.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=Sh.getConfigValue(le.HDB_SETTINGS_NAMES.HDB_ROOT_KEY))}catch(t){Wl.error(Xoe),Wl.error(t),console.error(t),process.exit(1)}}a(nae,"initSync");var zG=!1;function sae(e){zG=e}a(sae,"setCloneVar");function iae(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,u=Ho.join(__dirname,"../../","unitTests");Ws[Th]=Ho.join(u,"hdb_boot_properties.file"),Me(le.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY,Ho.join(u,"settings.test")),Me(le.HDB_SETTINGS_NAMES.INSTALL_USER,KG.userInfo()?KG.userInfo().username:void 0),Me(le.HDB_SETTINGS_NAMES.LOG_LEVEL_KEY,"debug"),Me(le.HDB_SETTINGS_NAMES.LOG_PATH_KEY,Ho.join(u,"envDir","log")),Me(le.HDB_SETTINGS_NAMES.LOG_DAILY_ROTATE_KEY,!1),Me(le.HDB_SETTINGS_NAMES.CLUSTERING_ENABLED_KEY,!0),Me(le.HDB_SETTINGS_NAMES.CLUSTERING_NODE_NAME_KEY,"1231412de213"),Me(le.HDB_SETTINGS_NAMES.HDB_ROOT_KEY,Ho.join(u,"envDir")),Me(le.CONFIG_PARAMS.STORAGE_PATH,Ho.join(u,"envDir")),s&&(Me(le.CONFIG_PARAMS.HTTP_SECUREPORT,QG(le.CONFIG_PARAMS.HTTP_PORT)),Me(le.CONFIG_PARAMS.HTTP_PORT,null)),Me(le.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HTTPS,!!s),Me(le.HDB_SETTINGS_NAMES.SERVER_PORT_KEY,9925),Me(le.HDB_SETTINGS_NAMES.CORS_ENABLED_KEY,Kl.isEmpty(i)?!1:i),Me(le.CONFIG_PARAMS.HTTP_CORS,Kl.isEmpty(i)?!1:i),Me(le.HDB_SETTINGS_NAMES.MAX_CUSTOM_FUNCTION_PROCESSES,2),Me(le.HDB_SETTINGS_NAMES.MAX_HDB_PROCESSES,4),Me(le.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_PORT_KEY,9926),Me(le.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_ENABLED_KEY,!0),Me(le.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY,Ho.resolve(__dirname,"../../unitTests/server/fastifyRoutes/custom_functions")),Me(le.HDB_SETTINGS_NAMES.LOCAL_STUDIO_ON,Kl.isEmpty(c)?!1:c),o&&(Me("CORS_ACCESSLIST",o),Me(le.CONFIG_PARAMS.HTTP_CORSACCESSLIST,o)),n&&(Me(le.HDB_SETTINGS_NAMES.SERVER_TIMEOUT_KEY,n),Me(le.CONFIG_PARAMS.HTTP_TIMEOUT,n)),t&&(Me(le.HDB_SETTINGS_NAMES.SERVER_KEEP_ALIVE_TIMEOUT_KEY,t),Me(le.CONFIG_PARAMS.HTTP_KEEPALIVETIMEOUT,t)),r&&(Me(le.HDB_SETTINGS_NAMES.SERVER_HEADERS_TIMEOUT_KEY,r),Me(le.CONFIG_PARAMS.HTTP_HEADERSTIMEOUT,r))}catch(t){let r=`Error reading in HDB environment variables from path ${Th}. Please check your boot props and settings files`;Wl.fatal(r),Wl.error(t)}}a(iae,"initTestEnvironment")});var tq=g((ITe,eq)=>{"use strict";var ZG=require("joi"),{string:Ql,boolean:jG,array:oae}=ZG.types(),XG=P(),aae=Xe();eq.exports=cae;function cae(e){let t=ZG.object({operation:Ql.valid(XG.OPERATIONS_ENUM.ADD_NODE,XG.OPERATIONS_ENUM.UPDATE_NODE).required(),node_name:Ql.required(),subscriptions:oae.items({schema:Ql.required(),table:Ql.optional(),hash_attribute:Ql.optional(),subscribe:jG.required(),publish:jG.required()}).min(1).required()});return aae.validateBySchema(e,t)}a(cae,"updateRemoteSourceValidator")});var zl=g((CTe,rq)=>{"use strict";var ZA=class{static{a(this,"UpdateRemoteResponseObject")}constructor(t,r,n=void 0){this.status=t,this.message=r,this.system_info=n}};rq.exports=ZA});var oq=g((LTe,iq)=>{"use strict";var uae=tq(),Qs=$(),eO=Ve(),lae=P(),tO=dn(),Go=ut(),nq=gu(),_ae=_d(),{Node:dae,NodeSubscription:sq}=pi(),rO=zl(),nO=z(),fae=Z(),{cloneDeep:Eae}=require("lodash"),{broadcast:hae}=We();iq.exports=mae;async function mae(e){try{let t=uae(e);if(t)return Qs.error(`Validation error in updateRemoteSource: ${t.message}`),new rO(eO.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,t.message);let{subscriptions:r,node_name:n,system_info:s}=e,i=[],o=Eae(await tO.getNodeRecord(n)),c=!nO.isEmptyOrZeroLength(o);o=c?o[0]:o,c&&Qs.trace(`Existing record found for ${n}, updating records subscriptions`);for(let _=0,l=r.length;_<l;_++){let d=r[_],E=d.schema,f=d.table;if(!nO.doesSchemaExist(E)){Qs.trace(`updateRemoteSource creating schema: ${E}`);try{await nq.createSchema({operation:"create_schema",schema:E})}catch(h){Qs.error(h)}}if(f&&!nO.doesTableExist(E,f)){let h=new _ae(E,f,d.hash_attribute);d.attributes&&(h.attributes=d.attributes),Qs.trace(`updateRemoteSource creating table: ${f} in schema: ${E} with attributes: ${JSON.stringify(d.attributes)}`);try{await nq.createTable(h)}catch(p){Qs.error(p)}}if(Qs.trace(`Creating local stream for ${E}.${f}`),await Go.createLocalTableStream(E,f),c?(await Go.updateConsumerIterator(E,f,n,"stop"),await Go.updateRemoteConsumer(d,n),d.subscribe===!0&&await Go.updateConsumerIterator(E,f,n,"start")):(await Go.updateRemoteConsumer(d,n),d.subscribe===!0?await Go.updateConsumerIterator(E,f,n,"start"):await Go.updateConsumerIterator(E,f,n,"stop")),c){let h=!1;for(let p=0,S=o.subscriptions.length;p<S;p++){let T=o.subscriptions[p];if(T.schema===E&&T.table===f){T.publish=d.publish,T.subscribe=d.subscribe,h=!0;break}}h||o.subscriptions.push(new sq(E,f,d.publish,d.subscribe))}else i.push(new sq(E,f,d.publish,d.subscribe))}c||(o=new dae(n,i,void 0),Qs.trace(`No record found for ${n}, creating a new one`));let u=Object.create({});return Object.assign(u,o),u.system_info=s,await tO.upsertNodeRecord(u),hae({type:"nats_update"}),new rO(eO.UPDATE_REMOTE_RESPONSE_STATUSES.SUCCESS,`Node ${fae.get(lae.CONFIG_PARAMS.CLUSTERING_NODENAME)} successfully updated remote source`,await tO.getSystemInfo())}catch(t){Qs.error(t);let r=t.message?t.message:t;return new rO(eO.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,r)}}a(mae,"updateRemoteSource")});var lq=g((PTe,uq)=>{"use strict";var cq=require("joi"),{string:aq}=cq.types(),pae=P(),Sae=Xe();uq.exports=Tae;function Tae(e){let t=cq.object({operation:aq.valid(pae.OPERATIONS_ENUM.REMOVE_NODE).required(),node_name:aq.required()});return Sae.validateBySchema(e,t)}a(Tae,"removeRemoteSourceValidator")});var fq=g((vTe,dq)=>{"use strict";var gae=lq(),gh=$(),Rh=Ve(),sO=P(),Rae=dn(),Aae=z(),_q=ut(),Oae=Z(),Ah=zl(),{NodeSubscription:bae}=pi(),yae=oa(),Nae=oi(),{broadcast:Iae}=We(),wae=Oae.get(sO.CONFIG_PARAMS.CLUSTERING_NODENAME);dq.exports=Cae;async function Cae(e){try{let t=gae(e);if(t)return gh.error(`Validation error in removeRemoteSource: ${t.message}`),new Ah(Rh.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,t.message);let r=e.node_name,n=await Rae.getNodeRecord(r);if(Aae.isEmptyOrZeroLength(n)){let i=`No record found for node '${r}'`;return gh.error(i),new Ah(Rh.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,i)}n=n[0];for(let i=0,o=n.subscriptions.length;i<o;i++){let c=n.subscriptions[i];gh.trace(`remove remote source removing subscription: ${c.schema}.${c.table} for node: ${r}`);let u=new bae(c.schema,c.table,!1,!1);await _q.updateConsumerIterator(c.schema,c.table,r,"stop"),await _q.updateRemoteConsumer(u,r)}let s=new yae(sO.SYSTEM_SCHEMA_NAME,sO.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[r]);return await Nae.deleteRecord(s),Iae({type:"nats_update"}),new Ah(Rh.UPDATE_REMOTE_RESPONSE_STATUSES.SUCCESS,`Node ${wae} successfully removed node '${r}'.`)}catch(t){gh.error(t);let r=t.message?t.message:t;return new Ah(Rh.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,r)}}a(Cae,"removeRemoteSource")});var pq=g((xTe,mq)=>{"use strict";var Oh=$(),Jl=P(),Eq=Ve(),iO=Z(),Dae=z(),hq=zl(),Lae=dn(),Mae=kd(),Pae=qr();mq.exports=Uae;async function Uae(e){try{Oh.trace("getRemoteSourceConfig called");let t=process.uptime()*1e3,r=Dae.ms_to_time(t),n=new vae(iO.get(Jl.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),iO.get(Jl.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_PORT)??iO.get(Jl.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_SECUREPORT),r,await Lae.getSystemInfo());try{let s={name:e.node_name,system_info:e.system_info},i=new Mae(Jl.SYSTEM_SCHEMA_NAME,Jl.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[s]);await Pae.update(i)}catch(s){Oh.error("Get remote config encountered an error updating system info for node:",e.node_name,s)}return Oh.trace("getRemoteSourceConfig response:",n),new hq(Eq.UPDATE_REMOTE_RESPONSE_STATUSES.SUCCESS,n)}catch(t){Oh.error(t);let r=t.message?t.message:t;return new hq(Eq.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,r)}}a(Uae,"getRemoteSourceConfig");function vae(e,t,r,n){this.uptime=r,this.ports={clustering:e,operations_api:t},this.system_info=n}a(vae,"ConfigResponseObject")});var Rq=g((GTe,gq)=>{"use strict";var Sq=Z();Sq.initSync();var Tq=ut(),jl=$(),cc=P(),oO=Ve(),Bae=oq(),xae=fq(),Hae=pq(),Gae=zl(),{encode:qae,decode:Fae}=require("msgpackr"),kae=bs(),Vae=Os(),$ae=require("util"),Yae=P(),{isMainThread:Kae,parentPort:Wae}=require("worker_threads");We();var Qae=$ae.promisify(kae.setSchemaDataToGlobal),aO=Sq.get(cc.CONFIG_PARAMS.CLUSTERING_NODENAME);gq.exports=zae;async function zae(){try{jl.notify("Starting reply service."),await Qae();let e=await Tq.getConnection(),t=`${aO}.__request__`,r=e.subscribe(t,{queue:aO});await Jae(r)}catch(e){jl.error(e)}}a(zae,"initialize");async function Jae(e){for await(let t of e){let r=Fae(t.data),n;switch(r.operation){case cc.OPERATIONS_ENUM.ADD_NODE:case cc.OPERATIONS_ENUM.UPDATE_NODE:n=await Bae(r);break;case cc.OPERATIONS_ENUM.REMOVE_NODE:n=await xae(r);break;case cc.OPERATIONS_ENUM.CLUSTER_STATUS:n=await Hae(r);break;case cc.OPERATIONS_ENUM.DESCRIBE_ALL:n=await jae();break;default:let s=`node '${aO}' reply service received unrecognized request operation`;jl.error(s),n=new Gae(oO.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,s)}jl.trace(n),t.respond(qae(n))}}a(Jae,"handleRequest");async function jae(){try{return{status:oO.UPDATE_REMOTE_RESPONSE_STATUSES.SUCCESS,message:await Vae.describeAll()}}catch(e){return jl.error(e),{status:oO.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,message:e.message}}}a(jae,"getRemoteDescribeAll");Kae||Wae.on("message",async e=>{let{type:t}=e;t===Yae.ITC_EVENT_TYPES.SHUTDOWN&&Tq.closeConnection()})});var Xae=Rq();(async()=>{try{await Xae()}catch(e){console.error("Error launching Nats reply service."),console.error(e)}})();
|