harperdb 4.0.4 → 4.0.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/bin/harperdb.js +18 -18
- package/launchServiceScripts/launchCustomFunctions.js +11 -11
- package/launchServiceScripts/launchHarperDB.js +11 -11
- package/launchServiceScripts/launchInstallNATSServer.js +2 -2
- package/launchServiceScripts/launchNatsIngestService.js +11 -11
- package/launchServiceScripts/launchNatsReplyService.js +6 -6
- package/launchServiceScripts/launchUpdateNodes4-0-0.js +6 -6
- package/package.json +1 -1
- package/server/ipc/hdbIpcServer.js +5 -5
- package/server/jobs/jobProcess.js +11 -11
- package/utility/scripts/restartHdb.js +6 -6
|
@@ -1,14 +1,14 @@
|
|
|
1
|
-
"use strict";var Tb=Object.defineProperty;var a=(e,t)=>Tb(e,"name",{value:t,configurable:!0});var S=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var is=S((M1,mb)=>{mb.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_temp:{hash_attribute:"id",name:"hdb_temp",schema:"system",attributes:[{attribute:"id"}]}}});var T=S((P1,sh)=>{"use strict";var $e=require("path"),Rb=require("fs");function Ab(){let e=__dirname;for(;!Rb.existsSync($e.join(e,"package.json"));){let t=$e.dirname(e);if(t===e)throw new Error("Could not find package root");e=t}return e}a(Ab,"getHDBPackageRoot");var Gt=Ab(),Yd="js",xn=Yd,Ob="harperdb-config.yaml",pb="defaultConfig.yaml",Nb="hdb",Kd=`hdbServer.${xn}`,Qd=`customFunctionsServer.${xn}`,Wd=`hdbIpcServer.${xn}`,gb=`restartHdb.${xn}`,X_="HarperDB",da="Custom Functions",ha="Clustering Hub",Sa="Clustering Leaf",z_="Clustering Ingest Service",j_="Clustering Reply Service",Ib="foreground.pid",Z_={HDB:X_,IPC:"IPC",CLUSTERING_HUB:ha,CLUSTERING_LEAF:Sa,CLUSTERING_INGEST_SERVICE:z_,CLUSTERING_REPLY_SERVICE:j_,CUSTOM_FUNCTIONS:da,RESTART_HDB:"Restart HDB",INSTALL:"Install",RUN:"Run",STOP:"Stop",UPGRADE:"Upgrade",REGISTER:"Register",JOB:"Job",PM2_LOGROTATE:"pm2-logrotate",CLUSTERING_UPGRADE_4_0_0:"Upgrade-4-0-0"},bb={HDB:"hdb.log",IPC:"ipc.log",CLUSTERING_HUB:"clustering_hub.log",CLUSTERING_LEAF:"clustering_leaf.log",CLUSTERING_INGEST_SERVICE:"clustering_ingest_service.log",CLUSTERING_REPLY_SERVICE:"clustering_reply_service.log",CUSTOM_FUNCTIONS:"custom_functions.log",INSTALL:"install.log",CLI:"cli.log",PM2:"pm2.log",CLUSTERING_UPGRADE:"clustering_upgrade.log",JOBS:"jobs.log"},Cb={NOTIFY:"notify",FATAL:"fatal",ERROR:"error",WARN:"warn",INFO:"info",DEBUG:"debug",TRACE:"trace"},wb={harperdb:X_,ipc:"IPC","clustering hub":ha,"clustering leaf":Sa,"clustering ingest service":z_,"clustering reply service":j_,"custom functions":da,custom_functions:da,"pm2-logrotate":Z_.PM2_LOGROTATE,logrotate:Z_.PM2_LOGROTATE,clustering:"clustering","clustering config":"clustering config"},Lb={CLUSTERING_HUB_PROC_DESCRIPTOR:ha,CLUSTERING_LEAF_PROC_DESCRIPTOR:Sa,CLUSTERING_INGEST_PROC_DESCRIPTOR:z_,CLUSTERING_REPLY_SERVICE_DESCRIPTOR:j_},Ea={HDB:$e.join(Gt,"server/harperdb"),IPC:$e.join(Gt,"server/ipc"),CUSTOM_FUNCTIONS:$e.join(Gt,"server/customFunctions"),CLUSTERING_HUB:$e.join(Gt,"server/nats"),CLUSTERING_LEAF:$e.join(Gt,"server/nats")},Ub={HDB:$e.join(Ea.HDB,Kd),IPC:$e.join(Ea.IPC,Wd),CUSTOM_FUNCTIONS:$e.join(Ea.CUSTOM_FUNCTIONS,Qd)},yb={HDB:$e.join(Gt,"launchServiceScripts/launchHarperDB.js"),CUSTOM_FUNCTIONS:$e.join(Gt,"launchServiceScripts/launchCustomFunctions.js"),NATS_INGEST_SERVICE:$e.join(Gt,"launchServiceScripts/launchNatsIngestService.js"),NATS_REPLY_SERVICE:$e.join(Gt,"launchServiceScripts/launchNatsReplyService.js"),NODES_UPGRADE_4_0_0:$e.resolve(Gt,"launchServiceScripts/launchUpdateNodes4-0-0.js")},Db={SUPER_USER:"super_user",CLUSTER_USER:"cluster_user"},Jd="support@harperdb.io",Mb="customer-success@harperdb.io",Zd=1,Pb=4141,Xd="https://harperdbhelp.zendesk.com/hc/en-us/requests/new",Bb="https://www.harperdb.io/product",vb=`For support, please submit a request at ${Xd} or contact ${Jd}`,zd=`For license support, please contact ${Mb}`,Hb="None of the specified records were found.",Gb="hash attribute not found",qb=`Your current license only supports ${Zd} role. ${zd}`,Fb="Your current license only supports 3 connections to a node.",Vb="127.0.0.1",kb=1,xb=/^\.$/,$b=/^\.\.$/,Yb="U+002E",Kb=/\//g,Qb="U+002F",Wb=/U\+002F/g,Jb=/^U\+002E$/,Zb=/^U\+002EU\+002E$/,Xb="d",zb=999999,jb="*",eC="--max-old-space-size=",tC="system",rC="__hdb_hash",sC=".harperdb",nC=".hdb",iC="keys",aC="hdb_boot_properties.file",oC=".updateConfig.json",cC="SIGTSTP",_C=24,uC=6e4,lC=448,EC="blob",dC="trash",hC="schema",SC="transactions",fC=".count",TC="id",mC="install_log.log",RC="run_log.log",AC="PROCESS_NAME",OC={SETTINGS_PATH_KEY:"settings_path"},jd=require("lodash"),pC={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",CLUSTERING_PORT:"CLUSTERING_PORT",HDB_ROOT:"HDB_ROOT",SERVER_PORT:"SERVER_PORT",NODE_NAME:"NODE_NAME",CLUSTERING:"CLUSTERING"},NC={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},gC={DATA_VERSION:"data_version",UPGRADE_VERSION:"upgrade_version"},IC={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"},bC={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"},ht="hdb_internal:",CC={CREATE_SCHEMA:ht+"create_schema",CREATE_TABLE:ht+"create_table",CREATE_ATTRIBUTE:ht+"create_attribute",ADD_USER:ht+"add_user",ALTER_USER:ht+"alter_user",DROP_USER:ht+"drop_user",HDB_NODES:ht+"hdb_nodes",HDB_USERS:ht+"hdb_users",HDB_WORKERS:ht+"hdb_workers",CATCHUP:ht+"catchup",SCHEMA_CATCHUP:ht+"schema_catchup",WORKER_ROOM:ht+"cluster_workers"},wC={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"},LC="060493.ks",UC=".license",yC={CREATED:"CREATED",IN_PROGRESS:"IN_PROGRESS",COMPLETE:"COMPLETE",ERROR:"ERROR"},g={INSERT:"insert",UPDATE:"update",UPSERT:"upsert",SEARCH_BY_CONDITIONS:"search_by_conditions",SEARCH_BY_HASH:"search_by_hash",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_TABLE:"create_table",CREATE_ATTRIBUTE:"create_attribute",DROP_SCHEMA:"drop_schema",DROP_TABLE:"drop_table",DESCRIBE_SCHEMA:"describe_schema",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",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",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",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",DROP_CUSTOM_FUNCTION:"drop_custom_function",ADD_CUSTOM_FUNCTION_PROJECT:"add_custom_function_project",DROP_CUSTOM_FUNCTION_PROJECT:"drop_custom_function_project",PACKAGE_CUSTOM_FUNCTION_PROJECT:"package_custom_function_project",DEPLOY_CUSTOM_FUNCTION_PROJECT:"deploy_custom_function_project",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"},DC={CSV:".csv",JSON:".json"},MC={AWS_ACCESS_KEY:"aws_access_key_id",AWS_SECRET:"aws_secret_access_key",AWS_BUCKET:"bucket",AWS_FILE_KEY:"key"},PC={SELECT:"select",INSERT:"insert",UPDATE:"update",DELETE:"delete"},Dr={};Dr[g.CREATE_SCHEMA]=g.CREATE_SCHEMA;Dr[g.CREATE_TABLE]=g.CREATE_TABLE;Dr[g.CREATE_ATTRIBUTE]=g.CREATE_ATTRIBUTE;Dr[g.INSERT]=g.INSERT;Dr[g.UPDATE]=g.UPDATE;Dr[g.UPSERT]=g.UPSERT;Dr[g.DELETE]=g.DELETE;var J=Object.create(null);J[g.DESCRIBE_ALL]=g.DESCRIBE_ALL;J[g.DESCRIBE_TABLE]=g.DESCRIBE_TABLE;J[g.DESCRIBE_SCHEMA]=g.DESCRIBE_SCHEMA;J[g.READ_LOG]=g.READ_LOG;J[g.ADD_NODE]=g.ADD_NODE;J[g.LIST_USERS]=g.LIST_USERS;J[g.LIST_ROLES]=g.LIST_ROLES;J[g.USER_INFO]=g.USER_INFO;J[g.SQL]=g.SQL;J[g.GET_JOB]=g.GET_JOB;J[g.SEARCH_JOBS_BY_START_DATE]=g.SEARCH_JOBS_BY_START_DATE;J[g.DELETE_FILES_BEFORE]=g.DELETE_FILES_BEFORE;J[g.EXPORT_LOCAL]=g.EXPORT_LOCAL;J[g.EXPORT_TO_S3]=g.EXPORT_TO_S3;J[g.CLUSTER_STATUS]=g.CLUSTER_STATUS;J[g.REMOVE_NODE]=g.REMOVE_NODE;J[g.RESTART]=g.RESTART;J[g.CUSTOM_FUNCTIONS_STATUS]=g.CUSTOM_FUNCTIONS_STATUS;J[g.GET_CUSTOM_FUNCTIONS]=g.GET_CUSTOM_FUNCTIONS;J[g.GET_CUSTOM_FUNCTION]=g.GET_CUSTOM_FUNCTION;J[g.SET_CUSTOM_FUNCTION]=g.SET_CUSTOM_FUNCTION;J[g.DROP_CUSTOM_FUNCTION]=g.DROP_CUSTOM_FUNCTION;J[g.ADD_CUSTOM_FUNCTION_PROJECT]=g.ADD_CUSTOM_FUNCTION_PROJECT;J[g.DROP_CUSTOM_FUNCTION_PROJECT]=g.DROP_CUSTOM_FUNCTION_PROJECT;J[g.PACKAGE_CUSTOM_FUNCTION_PROJECT]=g.PACKAGE_CUSTOM_FUNCTION_PROJECT;J[g.DEPLOY_CUSTOM_FUNCTION_PROJECT]=g.DEPLOY_CUSTOM_FUNCTION_PROJECT;var BC={RUN:"run",INSTALL:"install",REGISTER:"register",STOP:"stop",RESTART:"restart",VERSION:"version",UPGRADE:"upgrade"},vC={point:"point",lineString:"lineString",multiLineString:"multiLineString",multiPoint:"multiPoint",multiPolygon:"multiPolygon",polygon:"polygon"},eh={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",IPC_SERVER_PORT:"IPC_SERVER_PORT",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"},HC=jd.invert(eh),f={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_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",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",HTTP_THREADS:"http_threads",IPC_NETWORK_PORT:"ipc_network_port",LOCALSTUDIO_ENABLED:"localStudio_enabled",LOGGING_FILE:"logging_file",LOGGING_LEVEL:"logging_level",LOGGING_ROOT:"logging_root",LOGGING_ROTATION_COMPRESS:"logging_rotation_compress",LOGGING_ROTATION_DATEFORMAT:"logging_rotation_dateFormat",LOGGING_ROTATION_MAXSIZE:"logging_rotation_maxSize",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",LOGGING_STDSTREAMS:"logging_stdStreams",LOGGING_AUDITLOG:"logging_auditLog",OPERATIONSAPI_AUTHENTICATION_OPERATIONTOKENTIMEOUT:"operationsApi_authentication_operationTokenTimeout",OPERATIONSAPI_AUTHENTICATION_REFRESHTOKENTIMEOUT:"operationsApi_authentication_refreshTokenTimeout",OPERATIONSAPI_FOREGROUND:"operationsApi_foreground",OPERATIONSAPI_TLS_CERTIFICATE:"operationsApi_tls_certificate",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_TLS_PRIVATEKEY:"operationsApi_tls_privateKey",OPERATIONSAPI_TLS_CERT_AUTH:"operationsApi_tls_certificateAuthority",OPERATIONSAPI_NETWORK_TIMEOUT:"operationsApi_network_timeout",OPERATIONSAPI_NODEENV:"operationsApi_nodeEnv",ROOTPATH:"rootPath",STORAGE_WRITEASYNC:"storage_writeAsync",STORAGE_OVERLAPPINGSYNC:"storage_overlappingSync"},GC={hdb_root_key:f.ROOTPATH,hdb_root:f.ROOTPATH,server_port_key:f.OPERATIONSAPI_NETWORK_PORT,server_port:f.OPERATIONSAPI_NETWORK_PORT,cert_key:f.OPERATIONSAPI_TLS_CERTIFICATE,certificate:f.OPERATIONSAPI_TLS_CERTIFICATE,private_key_key:f.OPERATIONSAPI_TLS_PRIVATEKEY,private_key:f.OPERATIONSAPI_TLS_PRIVATEKEY,http_secure_enabled_key:f.OPERATIONSAPI_NETWORK_HTTPS,https_on:f.OPERATIONSAPI_NETWORK_HTTPS,cors_enabled_key:f.OPERATIONSAPI_NETWORK_CORS,cors_on:f.OPERATIONSAPI_NETWORK_CORS,cors_whitelist_key:f.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_whitelist:f.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_accesslist_key:f.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_accesslist:f.OPERATIONSAPI_NETWORK_CORSACCESSLIST,log_level_key:f.LOGGING_LEVEL,log_level:f.LOGGING_LEVEL,log_path_key:f.LOGGING_ROOT,log_path:f.LOGGING_ROOT,log_daily_rotate:f.LOGGING_ROTATION_ROTATE,log_rotate:f.LOGGING_ROTATION_ROTATE,log_rotate_max_size:f.LOGGING_ROTATION_MAXSIZE,log_rotate_retain:f.LOGGING_ROTATION_RETAIN,log_rotate_compress:f.LOGGING_ROTATION_COMPRESS,log_rotate_date_format:f.LOGGING_ROTATION_DATEFORMAT,log_rotate_rotate_module:f.LOGGING_ROTATION_ROTATEMODULE,log_rotate_worker_interval:f.LOGGING_ROTATION_WORKERINTERVAL,log_rotate_rotate_interval:f.LOGGING_ROTATION_ROTATEINTERVAL,log_rotate_timezone:f.LOGGING_ROTATION_TIMEZONE,props_env_key:f.OPERATIONSAPI_NODEENV,node_env:f.OPERATIONSAPI_NODEENV,clustering_node_name_key:f.CLUSTERING_NODENAME,node_name:f.CLUSTERING_NODENAME,clustering_enabled_key:f.CLUSTERING_ENABLED,clustering:f.CLUSTERING_ENABLED,max_http_threads:f.HTTP_THREADS,max_hdb_processes:f.HTTP_THREADS,server_timeout_key:f.OPERATIONSAPI_NETWORK_TIMEOUT,server_timeout_ms:f.OPERATIONSAPI_NETWORK_TIMEOUT,server_keep_alive_timeout_key:f.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT,server_keep_alive_timeout:f.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT,server_headers_timeout_key:f.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT,server_headers_timeout:f.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT,disable_transaction_log_key:f.LOGGING_AUDITLOG,disable_transaction_log:f.LOGGING_AUDITLOG,operation_token_timeout_key:f.OPERATIONSAPI_AUTHENTICATION_OPERATIONTOKENTIMEOUT,operation_token_timeout:f.OPERATIONSAPI_AUTHENTICATION_OPERATIONTOKENTIMEOUT,refresh_token_timeout_key:f.OPERATIONSAPI_AUTHENTICATION_REFRESHTOKENTIMEOUT,refresh_token_timeout:f.OPERATIONSAPI_AUTHENTICATION_REFRESHTOKENTIMEOUT,ipc_server_port:f.IPC_NETWORK_PORT,custom_functions_enabled_key:f.CUSTOMFUNCTIONS_ENABLED,custom_functions:f.CUSTOMFUNCTIONS_ENABLED,custom_functions_port_key:f.CUSTOMFUNCTIONS_NETWORK_PORT,custom_functions_port:f.CUSTOMFUNCTIONS_NETWORK_PORT,custom_functions_directory_key:f.CUSTOMFUNCTIONS_ROOT,custom_functions_directory:f.CUSTOMFUNCTIONS_ROOT,max_custom_function_processes:f.HTTP_THREADS,log_to_file:f.LOGGING_FILE,log_to_stdstreams:f.LOGGING_STDSTREAMS,run_in_foreground:f.OPERATIONSAPI_FOREGROUND,local_studio_on:f.LOCALSTUDIO_ENABLED,clustering_port:f.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT,clustering_user:f.CLUSTERING_USER,clustering_enabled:f.CLUSTERING_ENABLED,clustering_hubserver_cluster_name:f.CLUSTERING_HUBSERVER_CLUSTER_NAME,clustering_hubserver_cluster_network_port:f.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT,clustering_hubserver_cluster_network_routes:f.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,clustering_hubserver_leafnodes_network_port:f.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT,clustering_hubserver_network_port:f.CLUSTERING_HUBSERVER_NETWORK_PORT,clustering_leafserver_network_port:f.CLUSTERING_LEAFSERVER_NETWORK_PORT,clustering_leafserver_network_routes:f.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,clustering_nodename:f.CLUSTERING_NODENAME,clustering_tls_certificate:f.CLUSTERING_TLS_CERTIFICATE,clustering_tls_privatekey:f.CLUSTERING_TLS_PRIVATEKEY,clustering_tls_certificateauthority:f.CLUSTERING_TLS_CERT_AUTH,clustering_tls_insecure:f.CLUSTERING_TLS_INSECURE,customfunctions_enabled:f.CUSTOMFUNCTIONS_ENABLED,customfunctions_network_port:f.CUSTOMFUNCTIONS_NETWORK_PORT,customfunctions_tls_certificate:f.CUSTOMFUNCTIONS_TLS_CERTIFICATE,customfunctions_network_cors:f.CUSTOMFUNCTIONS_NETWORK_CORS,customfunctions_network_corsaccesslist:f.CUSTOMFUNCTIONS_NETWORK_CORSACCESSLIST,customfunctions_network_headerstimeout:f.CUSTOMFUNCTIONS_NETWORK_HEADERSTIMEOUT,customfunctions_network_https:f.CUSTOMFUNCTIONS_NETWORK_HTTPS,customfunctions_network_keepalivetimeout:f.CUSTOMFUNCTIONS_NETWORK_KEEPALIVETIMEOUT,customfunctions_tls_privatekey:f.CUSTOMFUNCTIONS_TLS_PRIVATEKEY,customfunctions_tls_certificateauthority:f.CUSTOMFUNCTIONS_TLS_CERT_AUTH,customfunctions_network_timeout:f.CUSTOMFUNCTIONS_NETWORK_TIMEOUT,customfunctions_nodeenv:f.CUSTOMFUNCTIONS_NODEENV,http_threads:f.HTTP_THREADS,customfunctions_processes:f.HTTP_THREADS,customfunctions_root:f.CUSTOMFUNCTIONS_ROOT,ipc_network_port:f.IPC_NETWORK_PORT,localstudio_enabled:f.LOCALSTUDIO_ENABLED,logging_file:f.LOGGING_FILE,logging_level:f.LOGGING_LEVEL,logging_root:f.LOGGING_ROOT,logging_rotation_compress:f.LOGGING_ROTATION_COMPRESS,logging_rotation_dateformat:f.LOGGING_ROTATION_DATEFORMAT,logging_rotation_maxsize:f.LOGGING_ROTATION_MAXSIZE,logging_rotation_retain:f.LOGGING_ROTATION_RETAIN,logging_rotation_rotate:f.LOGGING_ROTATION_ROTATE,logging_rotation_rotateinterval:f.LOGGING_ROTATION_ROTATEINTERVAL,logging_rotation_rotatemodule:f.LOGGING_ROTATION_ROTATEMODULE,logging_rotation_timezone:f.LOGGING_ROTATION_TIMEZONE,logging_rotation_workerinterval:f.LOGGING_ROTATION_WORKERINTERVAL,logging_stdstreams:f.LOGGING_STDSTREAMS,logging_auditlog:f.LOGGING_AUDITLOG,operationsapi_authentication_operationtokentimeout:f.OPERATIONSAPI_AUTHENTICATION_OPERATIONTOKENTIMEOUT,operationsapi_authentication_refreshtokentimeout:f.OPERATIONSAPI_AUTHENTICATION_REFRESHTOKENTIMEOUT,operationsapi_foreground:f.OPERATIONSAPI_FOREGROUND,operationsapi_tls_certificate:f.OPERATIONSAPI_TLS_CERTIFICATE,operationsapi_network_cors:f.OPERATIONSAPI_NETWORK_CORS,operationsapi_network_corsaccesslist:f.OPERATIONSAPI_NETWORK_CORSACCESSLIST,operationsapi_network_headerstimeout:f.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT,operationsapi_network_https:f.OPERATIONSAPI_NETWORK_HTTPS,operationsapi_network_keepalivetimeout:f.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT,operationsapi_network_port:f.OPERATIONSAPI_NETWORK_PORT,operationsapi_tls_privatekey:f.OPERATIONSAPI_TLS_PRIVATEKEY,operationsapi_network_timeout:f.OPERATIONSAPI_NETWORK_TIMEOUT,operationsapi_nodeenv:f.OPERATIONSAPI_NODEENV,operationsapi_root:f.ROOTPATH,rootpath:f.ROOTPATH,storage_writeasync:f.STORAGE_WRITEASYNC,storage_overlappingsync:f.STORAGE_OVERLAPPINGSYNC},qC={csv_file_load:"csv_file_load",csv_data_load:g.CSV_DATA_LOAD,csv_url_load:g.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"},FC={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"},VC={BIDIRECTIONAL:"BIDIRECTIONAL",OUTBOUND:"OUTBOUND",INBOUND:"INBOUND"},kC={FILE_SYSTEM:"fs",LMDB:"lmdb"},xC={API_CALL_DEFAULT:1e4,VERSION_DEFAULT:"2.2.0"},$C={DEVELOPMENT:8192,DEFAULT:512},YC={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"},KC={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"},QC={ENOENT:"ENOENT",EACCES:"EACCES"},th={CREATED_TIME:"__createdtime__",UPDATED_TIME:"__updatedtime__"},WC="__clustering__",JC=Object.values(th),ZC=15984864e5,rh={LESS:"<",LESS_OR_EQ:"<=",GREATER:">",GREATER_OR_EQ:">=",BETWEEN:"..."},XC=jd.invert(rh),zC={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"},jC=111,ew=`\r
|
|
2
|
-
`,
|
|
3
|
-
`}a(
|
|
4
|
-
`).slice(1)){n=n.trim();let[i]=n.split(" ",1),o=n.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,s])=>({pid:Number.parseInt(r,10),name:ww.basename(s.comm),cmd:s.args,ppid:Number.parseInt(s.ppid,10),uid:Number.parseInt(s.uid,10),cpu:Number.parseFloat(s["%cpu"]),memory:Number.parseFloat(s["%mem"])}))}a(Dw,"findPs")});var Ye=S((G1,Th)=>{"use strict";var Mw="__dbis__",Pw="__environment_name__",Bw="__dbi_defintion__",vw={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"},Hw=["__createdtime__","__updatedtime__"],Gw="\uFFFF",fh={TIMESTAMP:"timestamp",HASH_VALUE:"hash_value",USER_NAME:"user_name"},qw=Object.values(fh);Th.exports={INTERNAL_DBIS_NAME:Mw,DBI_DEFINITION_NAME:Bw,SEARCH_TYPES:vw,TIMESTAMP_NAMES:Hw,MAX_SEARCH_KEY_LENGTH:256,ENVIRONMENT_NAME_KEY:Pw,TRANSACTIONS_DBI_NAMES_ENUM:fh,TRANSACTIONS_DBIS:qw,OVERFLOW_MARKER:Gw}});var Ke=S((q1,bh)=>{"use strict";var mh=T(),Rh=Ye(),Ah={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},Oh=a(e=>`${e} Check logs and try again.`,"CHECK_LOGS_WRAPPER"),ph={500:Oh("There was an error processing your request."),400:"Invalid request"},Fw=ph[Ah.INTERNAL_SERVER_ERROR],Vw={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.`},kw={CONFIG_VALIDATION:e=>`HarperDB config file validation error: ${e}`},xw={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"},$w={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_ARRAY:"ids must be an array",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 ${Rh.INTERNAL_DBIS_NAME}`,CANNOT_DROP_INTERNAL_DBIS_NAME:`cannot drop a dbi named ${Rh.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"},Yw={ATTR_NAME_LENGTH_ERR:e=>`transaction aborted due to attribute name ${e} being too long. Attribute names cannot be longer than ${mh.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 ${mh.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"},Nh={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"},Kw={DEFAULT_INVALID_REQUEST:"Invalid request",OP_AUTH_PERMS_ERROR:"This operation is not authorized due to role restrictions and/or invalid schema 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' schema, tables and records are used internally by HarperDB and cannot be updated or removed."},Qw={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 schema metadata for '${e}'`,SCHEMA_TABLE_PERM_ERROR:(e,t)=>`Your role does not have permission to view schema.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`},Ww={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=>`Schema '${e}' does not exist`,SCHEMA_EXISTS_ERR:e=>`Schema '${e}' already exists`,TABLE_EXISTS_ERR:(e,t)=>`Table '${t}' already exists in schema '${e}'`,SCHEMA_REQUIRED_ERR:"schema is required",TABLE_NOT_FOUND:(e,t)=>`Table '${e}.${t}' does not exist`,TABLE_REQUIRED_ERR:"table is required"},Jw={OUTER_JOIN_TRANSLATION_ERROR:"There was an error translating the final SQL outer join data."},Zw={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`},gh={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.`},Ih={INVALID_IPC_DATA_TYPE:"Invalid IPC event data type, must be an object",MISSING_TYPE:"IPC event missing 'type'",MISSING_MSG:"IPC event missing 'message'",MISSING_ORIGIN:"IPC event message missing 'originator' property",INVALID_EVENT:e=>`IPC server received invalid event type: ${e}`},Xw={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 customFunctions enabled to true in hdb/harperdb-config.yaml file."},zw={CLUSTERING_NOT_ENABLED:"Clustering must be enabled to perform this operation."},jw={...Nh,...xw,...Vw,...Kw,...Qw,...Ww,...Jw,...Zw,...Yw,...gh,...Ih,...Xw,...zw,...kw};bh.exports={CHECK_LOGS_WRAPPER:Oh,HDB_ERROR_MSGS:jw,DEFAULT_ERROR_MSGS:ph,DEFAULT_ERROR_RESP:Fw,HTTP_STATUS_CODES:Ah,LMDB_ERRORS_ENUM:$w,AUTHENTICATION_ERROR_MSGS:Nh,VALIDATION_ERROR_MSGS:gh,IPC_ERRORS:Ih}});var D=S((F1,Lh)=>{"use strict";var Qs=Ke(),eL=I(),tL=T(),$n=class extends Error{constructor(t,r,s,n,i){super(),Error.captureStackTrace(this,Ch),this.http_resp_code=s||Qs.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR,this.http_resp_msg=r||(Qs.DEFAULT_ERROR_MSGS[s]?Qs.DEFAULT_ERROR_MSGS[s]:Qs.DEFAULT_ERROR_MSGS[Qs.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR]),this.message=t.message?t.message:this.http_resp_msg,this.type=t.name,typeof this.message!="string"&&(this.stack=t.stack),i&&eL[n](i)}};a($n,"HdbError");function Ch(e,t,r,s=tL.LOG_LEVELS.ERROR,n=null,i=!1){if(wh(e))return e;let o=new $n(e,t,r,s,n);return i&&delete o.stack,o}a(Ch,"handleHDBError");function wh(e){return e.__proto__.constructor.name===$n.name}a(wh,"isHDBError");Lh.exports={isHDBError:wh,handleHDBError:Ch,hdb_errors:Qs}});var b=S((k1,$h)=>{"use strict";var au=require("path"),rL=require("fs-extra"),Ie=I(),Uh=require("fs-extra"),sL=require("truncate-utf8-bytes"),Yn=require("os"),nL=require("net"),iL=require("recursive-iterator"),Ue=T(),Bh=Sh(),yh=require("papaparse"),ma=require("moment"),{inspect:aL}=require("util"),Dh=require("is-number"),V1=require("lodash"),{hdb_errors:Ra}=D(),vh=require("util").promisify(setTimeout),oL=100,cL=5,_L="",uL=4,Mh=255,Ph={true:!0,false:!1,undefined:null,null:null,NaN:NaN};$h.exports={isEmpty:St,isEmptyOrZeroLength:Xt,arrayHasEmptyValues:dL,arrayHasEmptyOrZeroLengthValues:hL,buildFolderPath:SL,isBoolean:Hh,errorizeMessage:lL,stripFileExtension:TL,autoCast:mL,autoCastJSONDeep:ou,removeDir:AL,compareVersions:OL,isCompatibleDataVersion:pL,escapeRawValue:qh,unescapeValue:NL,stringifyProps:gL,valueConverter:IL,timeoutPromise:CL,isClusterOperation:LL,getClusterUser:DL,sendTransactionToSocketCluster:UL,checkGlobalSchemaTable:yL,getHomeDir:Fh,getPropsFilePath:bL,promisifyPapaParse:ML,removeBOM:Vh,createEventPromise:PL,checkProcessRunning:BL,checkSchemaTableExist:vL,checkSchemaExists:kh,checkTableExists:xh,getStartOfTomorrowInSeconds:HL,getLimitKey:GL,isObject:fL,isNotEmptyAndHasValue:EL,autoCasterIsNumberCheck:Gh,backtickASTSchemaItems:qL,isPortTaken:wL,stopProcess:FL,createForkArgs:VL,autoCastBoolean:kL,async_set_timeout:vh,getTableHashAttribute:xL,doesSchemaExist:$L,doesTableExist:YL,stringifyObj:KL,ms_to_time:QL,PACKAGE_ROOT:Ue.PACKAGE_ROOT};function lL(e){return e instanceof Error?e:new Error(e)}a(lL,"errorizeMessage");function St(e){return e==null}a(St,"isEmpty");function EL(e){return!St(e)&&(e||e===0||e===""||Hh(e))}a(EL,"isNotEmptyAndHasValue");function Xt(e){return St(e)||e.length===0||e.size===0}a(Xt,"isEmptyOrZeroLength");function dL(e){if(St(e))return!0;for(let t=0;t<e.length;t++)if(St(e[t]))return!0;return!1}a(dL,"arrayHasEmptyValues");function hL(e){if(Xt(e))return!0;for(let t=0;t<e.length;t++)if(Xt(e[t]))return!0;return!1}a(hL,"arrayHasEmptyOrZeroLengthValues");function SL(...e){try{return e.join(au.sep)}catch{console.error(e)}}a(SL,"buildFolderPath");function Hh(e){return St(e)?!1:e===!0||e===!1}a(Hh,"isBoolean");function fL(e){return St(e)?!1:typeof e=="object"}a(fL,"isObject");function TL(e){return Xt(e)?_L:e.slice(0,-uL)}a(TL,"stripFileExtension");function mL(e){return St(e)||e===""||typeof e!="string"?e:Ph[e]!==void 0?Ph[e]:Gh(e)===!0?Number(e):e}a(mL,"autoCast");function RL(e){if(typeof e=="string"&&(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")))try{return JSON.parse(e)}catch{}return e}a(RL,"autoCastJSON");function ou(e){if(e&&typeof e=="object"){if(Array.isArray(e))for(let t=0,r=e.length;t<r;t++){let s=e[t],n=ou(s);n!==s&&(e[t]=n)}else for(let t in e){let r=e[t],s=ou(r);s!==r&&(e[t]=s)}return e}else return RL(e)}a(ou,"autoCastJSONDeep");function Gh(e){if(e.startsWith("0.")&&Dh(e))return!0;let t=e.toUpperCase().includes("E");return!!((e!=="0"&&e.startsWith("0"))===!1&&t===!1&&Dh(e))}a(Gh,"autoCasterIsNumberCheck");async function AL(e){if(Xt(e))throw new Error(`Directory path: ${e} does not exist`);try{await Uh.emptyDir(e),await Uh.remove(e)}catch(t){throw Ie.error(`Error removing files in ${e} -- ${t}`),t}}a(AL,"removeDir");function OL(e,t){if(Xt(e)){Ie.info("Invalid current version sent as parameter.");return}if(Xt(t)){Ie.info("Invalid upgrade version sent as parameter.");return}let r,s=/(\.0+)+$/,n=e.version?e.version:e,i=t.version?t.version:t,o=n.replace(s,"").split("."),c=i.replace(s,"").split("."),_=Math.min(o.length,c.length);for(let u=0;u<_;u++)if(r=parseInt(o[u],10)-parseInt(c[u],10),r)return r;return o.length-c.length}a(OL,"compareVersions");function pL(e,t,r=!1){let s=e.toString().split("."),n=t.toString().split(".");return s[0]===n[0]&&(!r||s[1]===n[1])}a(pL,"isCompatibleDataVersion");function qh(e){if(St(e))return e;let t=String(e);return t==="."?Ue.UNICODE_PERIOD:t===".."?Ue.UNICODE_PERIOD+Ue.UNICODE_PERIOD:t.replace(Ue.FORWARD_SLASH_REGEX,Ue.UNICODE_FORWARD_SLASH)}a(qh,"escapeRawValue");function NL(e){if(St(e))return e;let t=String(e);return t===Ue.UNICODE_PERIOD?".":t===Ue.UNICODE_PERIOD+Ue.UNICODE_PERIOD?"..":String(e).replace(Ue.ESCAPED_FORWARD_SLASH_REGEX,"/")}a(NL,"unescapeValue");function gL(e,t){if(St(e))return Ie.info("Properties object is null"),"";let r="";return e.each(function(s,n){try{if(t&&t[s]){let i=t[s];for(let o of i)r+=";"+o+Yn.EOL}!Xt(s)&&s[0]===";"?r+=" "+s+n+Yn.EOL:Xt(s)||(r+=s+"="+n+Yn.EOL)}catch{Ie.error(`Found bad property during upgrade with key ${s} and value: ${n}`)}}),r}a(gL,"stringifyProps");function IL(e){let t;try{t=typeof e=="object"?JSON.stringify(e):e}catch(n){Ie.error(n),t=e}let r=String(qh(t)),s=Buffer.byteLength(r)>Mh?sL(r,Mh)+"/blob":r;return{value:t,value_stripped:r,value_path:s}}a(IL,"valueConverter");function Fh(){let e;try{e=Yn.homedir()}catch{e=process.env.HOME}return e||(e="~/"),e}a(Fh,"getHomeDir");function bL(){let e=au.join(Fh(),Ue.HDB_HOME_DIR_NAME,Ue.BOOT_PROPS_FILE_NAME);return rL.existsSync(e)||(e=au.join(__dirname,"../","hdb_boot_properties.file")),e}a(bL,"getPropsFilePath");function CL(e,t){let r,s;return s=new Promise(function(n){r=setTimeout(function(){n(t)},e)}),{promise:s,cancel:function(){clearTimeout(r)}}}a(CL,"timeoutPromise");async function wL(e){if(!e)throw new Error("Invalid port passed as parameter");return new Promise((t,r)=>{let s=nL.createServer().once("error",n=>{n.code==="EADDRINUSE"?t(!0):r(n)}).once("listening",()=>s.once("close",()=>t(!1)).close()).listen(e)})}a(wL,"isPortTaken");function LL(e){try{return Ue.CLUSTER_OPERATIONS[e.toLowerCase()]!==void 0}catch(t){Ie.error(`Error checking operation against cluster ops ${t}`)}return!1}a(LL,"isClusterOperation");function UL(e,t,r){if(global.hdb_socket_client!==void 0){Ie.trace(`Sending transaction to channel: ${e}`);let{hdb_user:s,hdb_auth_header:n,...i}=t;i.__originator||(i.__originator={}),i.__transacted=!0,r&&(i.__originator[r]=Ue.ORIGINATOR_SET_VALUE),global.hdb_socket_client.publish(e,i)}}a(UL,"sendTransactionToSocketCluster");function yL(e,t){if(!global.hdb_schema[e])return Ra.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e);if(!global.hdb_schema[e]||!global.hdb_schema[e][t])return Ra.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(yL,"checkGlobalSchemaTable");function DL(e,t){if(St(t)){Ie.warn("No CLUSTERING_USER defined, clustering disabled");return}if(St(e)||Xt(e)){Ie.warn("No users to search.");return}let r;try{let s=e.get(t);s&&s.role.permission.cluster_user===!0&&s.active===!0&&(r=s)}catch(s){Ie.error(`unable to find cluster_user due to: ${s.message}`);return}if(r===void 0){Ie.warn(`CLUSTERING_USER: ${t} not found or is not active.`);return}return r}a(DL,"getClusterUser");function ML(){yh.parsePromise=function(e,t){return new Promise(function(r,s){yh.parse(e,{header:!0,transformHeader:Vh,chunk:t.bind(null,s),skipEmptyLines:!0,dynamicTyping:!0,error:s,complete:r})})}}a(ML,"promisifyPapaParse");function Vh(e){if(typeof e!="string")throw new TypeError(`Expected a string, got ${typeof e}`);return e.charCodeAt(0)===65279?e.slice(1):e}a(Vh,"removeBOM");function PL(e,t,r){return new Promise(s=>{t.once(e,n=>{let i=r;Ie.info(`Got cluster status event response: ${aL(n)}`);try{i.cancel()}catch{Ie.error("Error trying to cancel timeout.")}s(n)})})}a(PL,"createEventPromise");async function BL(e){let t=!0,r=0;do await vh(oL*r++),(await Bh.findPs(e)).length>0&&(t=!1);while(t&&r<cL);if(t)throw new Error(`process ${e} was not started`)}a(BL,"checkProcessRunning");function vL(e,t){let r=kh(e);if(r)return r;let s=xh(e,t);if(s)return s}a(vL,"checkSchemaTableExist");function kh(e){if(!global.hdb_schema[e])return Ra.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}a(kh,"checkSchemaExists");function xh(e,t){if(!global.hdb_schema[e][t])return Ra.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(xh,"checkTableExists");function HL(){let e=ma().utc().add(1,Ue.MOMENT_DAYS_TAG).startOf(Ue.MOMENT_DAYS_TAG).unix(),t=ma().utc().unix();return e-t}a(HL,"getStartOfTomorrowInSeconds");function GL(){return ma().utc().format("DD-MM-YYYY")}a(GL,"getLimitKey");function qL(e){try{let t=new iL(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){Ie.error("Got an error back ticking items."),Ie.error(t)}}a(qL,"backtickASTSchemaItems");async function FL(e){let t=Yn.userInfo();(await Bh.findPs(e)).forEach(s=>{(t.uid==0||s.uid==t.uid)&&(process.kill(s.pid),Ie.trace(`Following process was killed by stopProcess: ${s.cmd}`))})}a(FL,"stopProcess");function VL(e){return[e]}a(VL,"createForkArgs");function kL(e){return e===!0||typeof e=="string"&&e.toLowerCase()==="true"}a(kL,"autoCastBoolean");function xL(e,t){return global.hdb_schema?.[e]?.[t]?.hash_attribute}a(xL,"getTableHashAttribute");function $L(e){return global?.hdb_schema?.[e]!==void 0}a($L,"doesSchemaExist");function YL(e,t){return global?.hdb_schema?.[e]?.[t]!==void 0}a(YL,"doesTableExist");function KL(e){try{return JSON.stringify(e)}catch{return e}}a(KL,"stringifyObj");function QL(e){let t=ma.duration(e),r=t.seconds()>0?t.seconds()+"s":"",s=t.minutes()>0?t.minutes()+"m ":"",n=t.hours()>0?t.hours()+"h ":"",i=t.days()>0?t.days()+"d ":"";return(t.years()>0?t.years()+"y ":"")+i+n+s+r}a(QL,"ms_to_time")});var sS=S(($1,rS)=>{"use strict";var cu=require("recursive-iterator"),WL=require("alasql"),_u=require("clone"),Yh=b(),{handleHDBError:Kh,hdb_errors:JL}=D(),{HDB_ERROR_MSGS:Qh,HTTP_STATUS_CODES:Wh}=JL,ZL=["DISTINCT_ARRAY"],Jh=Symbol("validateTables"),uu=Symbol("validateTable"),x1=Symbol("getAllColumns"),Zh=Symbol("validateAllColumns"),Aa=Symbol("findColumn"),Xh=Symbol("validateOrderBy"),Kn=Symbol("validateSegment"),lu=Symbol("validateColumn"),zh=Symbol("setColumnsForTable"),jh=Symbol("checkColumnsForAsterisk"),eS=Symbol("validateGroupBy"),tS=Symbol("hasColumns"),Oa=class{constructor(t){this.statement=t,this.attributes=[]}validate(){if(!this.statement)throw new Error("invalid sql statement");this[Jh](),this[jh](),this[Zh]()}[Jh](){if(this[tS]()){if(!this.statement.from||this.statement.from.length===0)throw"no from clause";this.statement.from.forEach(t=>{this[uu](t)}),this.statement.joins&&this.statement.joins.forEach(t=>{t.table.as=t.as,this[uu](t.table)})}}[tS](){let t=!1,r=new cu(this.statement);for(let{node:s,path:n}of r)if(s&&s.columnid){t=!0;break}return t}[uu](t){if(!t.databaseid)throw`schema not defined for table ${t.tableid}`;if(!global.hdb_schema[t.databaseid])throw Kh(new Error,Qh.SCHEMA_NOT_FOUND(t.databaseid),Wh.NOT_FOUND);if(!global.hdb_schema[t.databaseid][t.tableid])throw Kh(new Error,Qh.TABLE_NOT_FOUND(t.databaseid,t.tableid),Wh.NOT_FOUND);global.hdb_schema[t.databaseid][t.tableid].attributes.forEach(s=>{let n=_u(s);n.table=_u(t),this.attributes.push(n)})}[Aa](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)}[jh](){let t=new cu(this.statement.columns);for(let{node:r,path:s}of t)r&&r.columnid==="*"&&s.indexOf("expression")<0&&this[zh](r.tableid)}[zh](t){this.attributes.forEach(r=>{(!t||t&&(r.table.tableid===t||r.table.as===t))&&this.statement.columns.push(new WL.yy.Column({columnid:r.attribute,tableid:r.table.as?r.table.as:r.table.tableid}))})}[Zh](){this[Kn](this.statement.columns,!1),this[Kn](this.statement.joins,!1),this[Kn](this.statement.where,!1),this[eS](this.statement.group,!1),this[Kn](this.statement.order,!0)}[Kn](t,r){if(!t)return;let s=new cu(t),n=[];for(let{node:i,path:o}of s)!Yh.isEmpty(i)&&!Yh.isEmpty(i.columnid)&&i.columnid!=="*"&&(r?this[Xh](i):n.push(this[lu](i)));return n}[eS](t){if(!t)return;let r=[];if(this.statement.columns.forEach(s=>{if(!(s.funcid&&ZL.indexOf(s.funcid.toUpperCase())>=0)){if(!s.aggregatorid&&!s.columnid){let n=_u(s);delete n.as,r.push(n)}else if(s.columnid){let n=this[Aa](s)[0];n&&r.push(n)}}}),this.statement.group.forEach(s=>{let n=null;if(!s.columnid)r.forEach((i,o)=>{if(i.toString()===s.toString()){n=i,r.splice(o,1);return}});else{let i=this[Aa](s);if(!i||i.length===0)throw`unknown column '${s.toString()}' in group by`;if(i.length>1)throw`ambiguously defined column '${s.toString()}' in group by`;r.forEach((o,c)=>{if(o.attribute===i[0].attribute&&o.table.tableid===i[0].table.tableid){n=o,r.splice(c,1);return}})}if(!n)throw`group by column '${s.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`}[Xh](t){let r=this.statement.columns.filter(s=>s.as===t.columnid);if(r.length>1)throw`ambiguous column reference ${(t.tableid?t.tableid+".":"")+t.columnid} in order by`;r.length===0&&this[lu](t)}[lu](t){let r=this[Aa](t),s=(t.tableid?t.tableid+".":"")+t.columnid;if(r.length===0)throw`unknown column ${s}`;if(r.length>1)throw`ambiguous column reference ${s}`;return r[0]}};a(Oa,"SelectValidator");rS.exports=Oa});var Eu=S((Y1,nS)=>{"use strict";var pa=class{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")}};a(pa,"BridgeMethods");nS.exports=pa});var _s=S((W1,cS)=>{"use strict";var iS=Ke().LMDB_ERRORS_ENUM,K1=require("lmdb"),XL=Ye(),Q1=require("buffer").Buffer,zL=require("microtime"),{OVERFLOW_MARKER:aS,MAX_SEARCH_KEY_LENGTH:Na}=XL,oS=["number","string","symbol","boolean","bigint"];function jL(e){if(!e)throw new Error(iS.ENV_REQUIRED);if(e.constructor.name!=="LMDBStore")throw new Error(iS.INVALID_ENVIRONMENT)}a(jL,"validateEnv");function eU(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(eU,"stringifyData");function tU(e){return e instanceof Date?e.valueOf():e}a(tU,"convertKeyValueToWrite");function rU(e){if(e==null)return;if(oS.includes(typeof e))return e.length>Na?[e.slice(0,Na)+aS]:[e];let t;if(Array.isArray(e)){t=[];for(let r=0,s=e.length;r<s;r++){let n=e[r];oS.includes(typeof n)&&(n.length>Na?t.push(n.slice(0,Na)+aS):t.push(n))}}return t}a(rU,"getIndexedValues");function sU(){let e=zL.now().toString(),t=e.length-3;return Number(e.slice(0,t)+"."+e.slice(t))}a(sU,"getMicroTime");cS.exports={validateEnv:jL,stringifyData:eU,convertKeyValueToWrite:tU,getMicroTime:sU,getIndexedValues:rU}});var uS=S((J1,_S)=>{"use strict";var ga=class{constructor(t=!1,r=!1){this.dup_sort=t,this.is_hash_attribute=r,this.useVersions=r}};a(ga,"DBIDefinition");_S.exports=ga});var ES=S((Z1,lS)=>{"use strict";var Ia=class{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={validated:!0},this.randomAccessStructure=!0,this.freezeData=!0)}};a(Ia,"OpenDBIObject");lS.exports=Ia});var hS=S((X1,dS)=>{"use strict";var ba=class{constructor(t,r,s,n,i=!1,o=!1,c=void 0){this.path=t,this.mapSize=r,this.maxDbs=s,this.maxReaders=n,this.sharedStructuresKey=Symbol.for("structures"),this.readOnly=i,this.trackMetrics=!0,this.noSync=o,c!==void 0&&(this.overlappingSync=c)}};a(ba,"OpenEnvironmentObject");dS.exports=ba});var fS=S((z1,SS)=>{"use strict";var nU={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,String.fromCharCode(13,10)),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,String.fromCharCode(13,10))},iU="certificate.pem",aU="privateKey.pem",oU="ca.pem";SS.exports={CERTIFICATE_VALUES:nU,CERTIFICATE_PEM_NAME:iU,PRIVATEKEY_PEM_NAME:aU,CA_PEM_NAME:oU}});var de=S((j1,TS)=>{"use strict";var st=require("validate.js");st.validators.type=function(e,t,r,s){return e===null||typeof e>"u"||st.validators.type.checks[t](e)?null:` must be a '${t}' value`};st.validators.type.checks={Object:function(e){return st.isObject(e)&&!st.isArray(e)},Array:st.isArray,Integer:st.isInteger,Number:st.isNumber,String:st.isString,Date:st.isDate,Boolean:function(e){return typeof e=="boolean"}};st.validators.hasValidFileExt=function(e,t){return!st.isString(e)||e===""||t.filter(r=>e.endsWith(r)).length>0?null:`must include one of the following valid file extensions - '${t.join("', '")}'`};TS.exports={validateObject:cU,validateObjectAsync:_U,validateBySchema:uU};function cU(e,t){if(!e||!t)return new Error("validateObject parameters were null");let r=st(e,t,{format:"flat"});return r?new Error(r):null}a(cU,"validateObject");async function _U(e,t){if(!e||!t)return new Error("validateObject parameters were null");try{await st.async(e,t,{format:"flat"})}catch(r){let s=r.join(",");return new Error(s)}return null}a(_U,"validateObjectAsync");function uU(e,t){let r=t.validate(e,{allowUnknown:!0,abortEarly:!1,errors:{wrap:{label:"'"}}});if(r.error)return new Error(r.error.message)}a(uU,"validateBySchema")});var hu=S((eJ,RS)=>{"use strict";var lU=require("fs-extra"),F=require("joi"),EU=require("os"),{boolean:ye,string:dr,number:zt,array:du}=F.types(),qt=require("path"),dU=I(),Ca=b(),hr=fS(),hU=de(),Er="keys",SU=hr.CERTIFICATE_PEM_NAME,fU=hr.PRIVATEKEY_PEM_NAME,TU=hr.CA_PEM_NAME,mU=hr.CERTIFICATE_PEM_NAME,RU=hr.PRIVATEKEY_PEM_NAME,AU=hr.CA_PEM_NAME,OU=hr.CERTIFICATE_PEM_NAME,pU=hr.PRIVATEKEY_PEM_NAME,NU=hr.CA_PEM_NAME,gU="log",IU="custom_functions",bU="Invalid logging.rotation.maxSize unit. Available units are G, M or K",CU="Invalid logging.rotation.maxSize value. Value should be a number followed by unit e.g. '10M'",wU="rootPath config parameter is undefined",LU="clustering.enabled config parameter is undefined",Pr=zt.min(0).required(),wa=du.items({host:dr.required(),port:Pr}).empty(null),nt;RS.exports={configValidator:UU,routesValidator:BU,route_constraints:wa};function UU(e){if(nt=e.rootPath,Ca.isEmpty(nt))throw wU;let t=ye.required(),r=F.valid("production","development").required(),s=zt.min(1).max(1e3).empty(null).default(PU),n=dr.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path").empty(null).default(mS),i=F.custom(DU).messages({"any.custom":"{:#label} {:#error}"}).empty(null).default(mS),o=dr.pattern(/^[^\s.,*>]+$/).messages({"string.pattern.base":"{:#label} invalid, must not contain ., * or >"}).empty(null),c=e.clustering?.enabled;if(Ca.isEmpty(c))throw LU;let _;return c===!0?_=F.object({enabled:t,hubServer:F.object({cluster:F.object({name:F.required().empty(null),network:F.object({port:Pr,routes:wa}).required()}).required(),leafNodes:F.object({network:F.object({port:Pr}).required()}).required(),network:F.object({port:Pr}).required()}).required(),leafServer:F.object({network:F.object({port:Pr,routes:wa}).required()}).required(),nodeName:o,tls:F.object({certificate:i,certificateAuthority:i,privateKey:i,insecure:ye.required()}),user:F.string().required()}).required():_=F.object({enabled:t,tls:F.object({certificate:i,certificateAuthority:i,privateKey:i,insecure:ye.required()})}).required(),F.object({clustering:_,customFunctions:F.object({enabled:t,network:F.object({cors:ye.required(),corsAccessList:du.required(),headersTimeout:zt.min(1).required(),https:ye.required(),keepAliveTimeout:zt.min(1).required(),port:Pr,timeout:zt.min(1).required()}),nodeEnv:r,root:n,tls:F.object({certificate:i,certificateAuthority:i,privateKey:i})}).required(),ipc:F.object({network:F.object({port:Pr})}).required(),localStudio:F.object({enabled:t}).required(),logging:F.object({file:ye.required(),level:F.valid("notify","fatal","error","warn","info","debug","trace"),rotation:F.object({compress:ye.required(),dateFormat:dr.required(),maxSize:dr.custom(MU).required(),retain:zt.min(0).required(),rotate:ye.required(),rotateInterval:dr.required(),rotateModule:ye.required(),timezone:dr.required(),workerInterval:zt.min(1).required()}).required(),root:n,stdStreams:ye.required(),auditLog:ye.required()}).required(),operationsApi:F.object({authentication:F.object({operationTokenTimeout:F.required(),refreshTokenTimeout:F.required()}).required(),foreground:ye.required(),network:F.object({cors:ye.required(),corsAccessList:du.required(),headersTimeout:zt.min(1).required(),https:ye.required(),keepAliveTimeout:zt.min(1).required(),port:Pr,timeout:zt.min(1).required()}).required(),nodeEnv:r,tls:F.object({certificate:i,certificateAuthority:i,privateKey:i})}).required(),rootPath:dr.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path").required(),http:F.object({threads:s}).required(),storage:F.object({writeAsync:ye.required(),overlappingSync:ye.optional()}).required()}).validate(e,{allowUnknown:!0,abortEarly:!1,errors:{wrap:{label:"'"}}})}a(UU,"configValidator");function yU(e){return lU.existsSync(e)?null:`Specified path ${e} does not exist.`}a(yU,"doesPathExist");function DU(e,t){F.assert(e,dr.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+\.pem+$/).messages({"string.pattern.base":"must be a valid directory path and specify a .pem file"}));let r=yU(e);if(r)return t.message(r)}a(DU,"validatePemFile");function MU(e,t){let r=e.slice(-1);if(r!=="G"&&r!=="M"&&r!=="K")return t.message(bU);let s=e.slice(0,-1);if(isNaN(parseInt(s)))return t.message(CU)}a(MU,"validateRotationMaxSize");function PU(e,t){let r=t.state.path.join("."),s=EU.cpus().length,n=s-1;return n<=2&&(n=2),dU.info(`Detected ${s} cores on this machine, defaulting ${r} to ${n}`),n}a(PU,"setDefaultThreads");function mS(e,t){if(!Ca.isEmpty(t.original))return t.original;let r=t.state.path.join(".");if(Ca.isEmpty(nt))throw new Error(`Error setting default root for: ${r}. HDB root is not defined`);switch(r){case"customFunctions.root":return qt.join(nt,IU);case"logging.root":return qt.join(nt,gU);case"operationsApi.tls.certificate":return qt.join(nt,Er,SU);case"operationsApi.tls.privateKey":return qt.join(nt,Er,fU);case"operationsApi.tls.certificateAuthority":return qt.join(nt,Er,TU);case"customFunctions.tls.certificate":return qt.join(nt,Er,mU);case"customFunctions.tls.privateKey":return qt.join(nt,Er,RU);case"customFunctions.tls.certificateAuthority":return qt.join(nt,Er,AU);case"clustering.tls.certificate":return qt.join(nt,Er,OU);case"clustering.tls.privateKey":return qt.join(nt,Er,pU);case"clustering.tls.certificateAuthority":return qt.join(nt,Er,NU);default:throw new Error(`Error setting default root for config parameter: ${r}. Unrecognized config parameter`)}}a(mS,"setDefaultRoot");function BU(e){let t=F.object({routes:wa});return hU.validateBySchema({routes:e},t)}a(BU,"routesValidator")});var Sr=S((tJ,bS)=>{"use strict";var re=T(),It=b(),Qe=I(),{configValidator:vU,routesValidator:AS}=hu(),Ft=require("fs-extra"),HU=require("yaml"),Ws=require("path"),GU=require("is-number"),ya=require("properties-reader"),qU=require("lodash"),{handleHDBError:FU}=D(),{HTTP_STATUS_CODES:VU,HDB_ERROR_MSGS:La}=Ke(),{PACKAGE_ROOT:kU}=T(),xU="Unable to get config value because config is uninitialized",$U="Config successfully initialized",YU="Error backing up config file",KU="Empty parameter sent to getConfigValue",OS=Ws.join(kU,"config","yaml",re.HDB_DEFAULT_CONFIG_FILE),QU="Configuration successfully set. You must restart HarperDB for new config settings to take effect.",Ua,it;bS.exports={createConfigFile:WU,getDefaultConfig:JU,getConfigValue:pS,initConfig:NS,flattenConfig:us,updateConfigValue:gS,updateConfigObject:ZU,getConfiguration:XU,setConfiguration:zU,readConfigFile:Tu,getClusteringRoutes:jU,initOldConfig:IS,getConfigFromFile:ey};function WU(e){let t=Js(OS);Ua=us(t.toJSON());for(let i in e){let o=re.CONFIG_PARAM_MAP[i.toLowerCase()];if(o!==void 0){let c=o.split("_"),_=Su(o,e[i]);try{t.setIn([...c],_)}catch(u){Qe.error(u)}}}fu(t);let r=t.toJSON();it=us(r);let s=t.getIn(["rootPath"]),n=Ws.join(s,re.HDB_CONFIG_FILE);Ft.createFileSync(n),Ft.writeFileSync(n,String(t)),Qe.trace(`Config file written to ${n}`)}a(WU,"createConfigFile");function JU(e){if(Ua===void 0){let r=Js(OS);Ua=us(r.toJSON())}let t=re.CONFIG_PARAM_MAP[e.toLowerCase()];if(t!==void 0)return Ua[t.toLowerCase()]}a(JU,"getDefaultConfig");function pS(e){if(It.isEmpty(e)){Qe.error(KU);return}if(it===void 0){Qe.trace(xU);return}let t=re.CONFIG_PARAM_MAP[e.toLowerCase()];if(t!==void 0)return it[t.toLowerCase()]}a(pS,"getConfigValue");function NS(e=!1){if(it===void 0||e){let t=It.getPropsFilePath();try{Ft.accessSync(t,Ft.constants.F_OK|Ft.constants.R_OK)}catch(o){throw Qe.error(o),new Error(`HarperDB properties file at path ${t} does not exist`)}let s=ya(t).get(re.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY),n;if(s.includes("config/settings.js"))try{IS(s);return}catch(o){if(o.code!==re.NODE_ERROR_CODES.ENOENT)throw o}try{n=Js(s)}catch(o){if(o.code===re.NODE_ERROR_CODES.ENOENT){Qe.trace(`HarperDB config file not found at ${s}.
|
|
5
|
-
This can occur during early stages of install where the config file has not yet been created`);return}else throw Qe.error(o),new Error(`Error reading HarperDB config file at ${s}`)}fu(n);let i=n.toJSON();it=us(i),Qe.trace($U)}}a(NS,"initConfig");function fu(e){let t=e.toJSON(),r=vU(t);if(r.error)throw La.CONFIG_VALIDATION(r.error.message);e.setIn(["http","threads"],r.value.http.threads),e.setIn(["customFunctions","root"],r.value.customFunctions.root),e.setIn(["logging","root"],r.value.logging.root),e.setIn(["operationsApi","tls","certificate"],r.value.operationsApi.tls.certificate),e.setIn(["operationsApi","tls","privateKey"],r.value.operationsApi.tls.privateKey),e.setIn(["operationsApi","tls","certificateAuthority"],r.value.operationsApi.tls.certificateAuthority),e.setIn(["customFunctions","tls","certificate"],r.value.customFunctions.tls.certificate),e.setIn(["customFunctions","tls","privateKey"],r.value.customFunctions.tls.privateKey),e.setIn(["customFunctions","tls","certificateAuthority"],r.value.customFunctions.tls.certificateAuthority),e.setIn(["clustering","tls","certificate"],r.value.clustering.tls.certificate),e.setIn(["clustering","tls","privateKey"],r.value.clustering.tls.privateKey),e.setIn(["clustering","tls","certificateAuthority"],r.value.clustering.tls.certificateAuthority)}a(fu,"validateConfig");function ZU(e,t){it===void 0&&(it={});let r=re.CONFIG_PARAM_MAP[e.toLowerCase()];if(r===void 0){Qe.trace(`Unable to update config object because config param '${e}' does not exist`);return}it[r.toLowerCase()]=t}a(ZU,"updateConfigObject");function gS(e,t,r=void 0,s=!1,n=!1){it===void 0&&NS();let i=pS(re.CONFIG_PARAM_MAP.hdb_root),o=Ws.join(i,re.HDB_CONFIG_FILE),c=Js(o);if(r===void 0){let l=re.CONFIG_PARAM_MAP[e.toLowerCase()];if(l===void 0)throw new Error(`Unable to update config, unrecognized config parameter: ${e}`);let E=l.split("_"),d=Su(l,t);c.setIn([...E],d)}else for(let l in r){let E=re.CONFIG_PARAM_MAP[l.toLowerCase()];if(E!==void 0){let d=E.split("_"),h=Su(E,r[l]);try{c.setIn([...d],h)}catch(m){Qe.error(m)}}}fu(c);let _=c.getIn(["rootPath"]),u=Ws.join(_,re.HDB_CONFIG_FILE);if(s===!0)try{let l=Ws.join(_,"backup",`${re.HDB_CONFIG_FILE}.bak`);Ft.copySync(o,l),Qe.trace(`Config file: ${o} backed up to: ${l}`)}catch(l){Qe.error(YU),Qe.error(l)}Ft.writeFileSync(u,String(c)),n&&(it=us(c.toJSON())),Qe.trace(`Config parameter: ${e} updated with value: ${t}`)}a(gS,"updateConfigValue");function us(e){let t={};for(let r in e)if(!!e.hasOwnProperty(r))if(typeof e[r]=="object"&&e[r]!==null&&!Array.isArray(e[r])){let s=us(e[r]);for(let n in s)!s.hasOwnProperty(n)||(t[r.toLowerCase()+"_"+n]=s[n])}else t[r.toLowerCase()]=e[r];return t}a(us,"flattenConfig");function Su(e,t){if(e===re.CONFIG_PARAMS.CLUSTERING_NODENAME||e===re.CONFIG_PARAMS.CLUSTERING_USER){if(!isNaN(t))return t.toString();if(typeof t=="string"&&t.toLowerCase()==="true"||typeof t=="string"&&t.toLowerCase()==="false")return t}else{if(GU(t))return parseFloat(t);if(t===!0||t===!1||Array.isArray(t)||It.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 It.autoCast(t)}a(Su,"castConfigValue");function XU(){let e=It.getPropsFilePath(),r=ya(e).get(re.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY);return Js(r).toJSON()}a(XU,"getConfiguration");async function zU(e){let{operation:t,hdb_user:r,hdb_auth_header:s,...n}=e;try{return gS(void 0,void 0,n,!0),QU}catch(i){throw typeof i=="string"||i instanceof String?FU(i,i,VU.BAD_REQUEST,void 0,void 0,!0):i}}a(zU,"setConfiguration");function Tu(){let e=It.getPropsFilePath();try{Ft.accessSync(e,Ft.constants.F_OK|Ft.constants.R_OK)}catch(n){throw Qe.error(n),new Error(`HarperDB properties file at path ${e} does not exist`)}let r=ya(e).get(re.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY);return Js(r).toJSON()}a(Tu,"readConfigFile");function Js(e){return HU.parseDocument(Ft.readFileSync(e,"utf8"),{simpleKeys:!0})}a(Js,"parseYamlDoc");function jU(){let e=Tu(),t=e?.clustering?.hubServer?.cluster?.network?.routes;t=It.isEmptyOrZeroLength(t)?[]:t;let r=AS(t);if(r)throw La.CONFIG_VALIDATION(r.message);let s=e?.clustering?.leafServer?.network?.routes;s=It.isEmptyOrZeroLength(s)?[]:s;let n=AS(s);if(n)throw La.CONFIG_VALIDATION(n.message);if(!It.isEmptyOrZeroLength(s)&&!It.isEmptyOrZeroLength(t)){let i=t.filter(o=>s.some(c=>c.host===o.host&&c.port===o.port));if(!It.isEmptyOrZeroLength(i)){let o=`Duplicate hub and leaf routes found ${JSON.stringify(i)}`;throw La.CONFIG_VALIDATION(o)}}return{hub_routes:t,leaf_routes:s}}a(jU,"getClusteringRoutes");function IS(e){let t=ya(e);it={};for(let r in re.CONFIG_PARAM_MAP){let s=t.get(r.toUpperCase());if(It.isEmpty(s)||typeof s=="string"&&s.trim().length===0)continue;let n=re.CONFIG_PARAM_MAP[r].toLowerCase();n===re.CONFIG_PARAMS.LOGGING_ROOT?it[n]=Ws.dirname(s):it[n]=s}return it}a(IS,"initOldConfig");function ey(e){let t=Tu();return qU.get(t,e.replaceAll("_","."))}a(ey,"getConfigFromFile")});var Y=S((rJ,wS)=>{"use strict";var mu=require("fs-extra"),jt=require("path"),ty=require("os"),ry=require("properties-reader"),Qn=I(),Zs=b(),M=T(),Da=Sr(),sy="Error initializing environment manager",Ma="BOOT_PROPS_FILE_PATH",CS=!1,ny={[M.HDB_SETTINGS_NAMES.INSTALL_USER]:!0,[M.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY]:!0,[M.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]:!0,BOOT_PROPS_FILE_PATH:!0},fr={};wS.exports={BOOT_PROPS_FILE_PATH:Ma,getHdbBasePath:iy,setHdbBasePath:ay,get:oy,initSync:_y,setProperty:$,initTestEnvironment:uy};function iy(){return fr[M.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]}a(iy,"getHdbBasePath");function ay(e){fr[M.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=e}a(ay,"setHdbBasePath");function oy(e){let t=Da.getConfigValue(e);return t===void 0?fr[e]:t}a(oy,"get");function $(e,t){ny[e]&&(fr[e]=t),Da.updateConfigObject(e,t)}a($,"setProperty");function cy(){let e;try{e=Zs.getPropsFilePath(),mu.accessSync(e,mu.constants.F_OK|mu.constants.R_OK),CS=!0;let t=ry(e);return fr[M.HDB_SETTINGS_NAMES.INSTALL_USER]=t.get(M.HDB_SETTINGS_NAMES.INSTALL_USER),fr[M.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY]=t.get(M.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY),fr[Ma]=e,!0}catch{return Qn.trace(`Environment manager found no properties file at ${e}`),!1}}a(cy,"doesPropFileExist");function _y(e=!1){try{(CS||cy())&&(Da.initConfig(e),fr[M.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=Da.getConfigValue(M.HDB_SETTINGS_NAMES.HDB_ROOT_KEY))}catch(t){Qn.error(sy),Qn.error(t),console.error(t),process.exit(1)}}a(_y,"initSync");function uy(e={}){try{let{keep_alive_timeout:t,headers_timeout:r,server_timeout:s,https_enabled:n,cors_enabled:i,cors_accesslist:o,local_studio_on:c}=e,_=jt.join(__dirname,"../../","unitTests");fr[Ma]=jt.join(_,"hdb_boot_properties.file"),$(M.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY,jt.join(_,"settings.test")),$(M.HDB_SETTINGS_NAMES.INSTALL_USER,ty.userInfo().username),$(M.HDB_SETTINGS_NAMES.PRIVATE_KEY_KEY,jt.join(_,"envDir","utility","keys","privateKey.pem")),$(M.HDB_SETTINGS_NAMES.CERT_KEY,jt.join(_,"envDir","utility","keys","certificate.pem")),$(M.CONFIG_PARAMS.CUSTOMFUNCTIONS_TLS_PRIVATEKEY,jt.join(_,"envDir","utility","keys","privateKey.pem")),$(M.CONFIG_PARAMS.CUSTOMFUNCTIONS_TLS_CERTIFICATE,jt.join(_,"envDir","utility","keys","certificate.pem")),$(M.HDB_SETTINGS_NAMES.LOG_LEVEL_KEY,"debug"),$(M.HDB_SETTINGS_NAMES.LOG_PATH_KEY,jt.join(_,"envDir","log")),$(M.HDB_SETTINGS_NAMES.LOG_DAILY_ROTATE_KEY,!1),$(M.HDB_SETTINGS_NAMES.CLUSTERING_ENABLED_KEY,!0),$(M.HDB_SETTINGS_NAMES.CLUSTERING_NODE_NAME_KEY,"1231412de213"),$(M.HDB_SETTINGS_NAMES.HDB_ROOT_KEY,jt.join(_,"envDir")),$(M.HDB_SETTINGS_NAMES.HTTP_SECURE_ENABLED_KEY,Zs.isEmpty(n)?!0:n),$(M.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HTTPS,Zs.isEmpty(n)?!0:n),$(M.HDB_SETTINGS_NAMES.SERVER_PORT_KEY,9925),$(M.HDB_SETTINGS_NAMES.CORS_ENABLED_KEY,Zs.isEmpty(i)?!1:i),$(M.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_CORS,Zs.isEmpty(i)?!1:i),$(M.HDB_SETTINGS_NAMES.IPC_SERVER_PORT,9383),$(M.HDB_SETTINGS_NAMES.MAX_CUSTOM_FUNCTION_PROCESSES,2),$(M.HDB_SETTINGS_NAMES.MAX_HDB_PROCESSES,4),$(M.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_PORT_KEY,9926),$(M.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_ENABLED_KEY,!0),$(M.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY,jt.resolve(__dirname,"../../unitTests/server/customFunctions/custom_functions")),$(M.HDB_SETTINGS_NAMES.LOCAL_STUDIO_ON,Zs.isEmpty(c)?!1:c),o&&($("CORS_ACCESSLIST",o),$(M.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_CORSACCESSLIST,o)),s&&($(M.HDB_SETTINGS_NAMES.SERVER_TIMEOUT_KEY,s),$(M.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_TIMEOUT,s)),t&&($(M.HDB_SETTINGS_NAMES.SERVER_KEEP_ALIVE_TIMEOUT_KEY,t),$(M.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_KEEPALIVETIMEOUT,t)),r&&($(M.HDB_SETTINGS_NAMES.SERVER_HEADERS_TIMEOUT_KEY,r),$(M.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HEADERSTIMEOUT,r))}catch(t){let r=`Error reading in HDB environment variables from path ${Ma}. Please check your boot props and settings files`;Qn.fatal(r),Qn.error(t)}}a(uy,"initTestEnvironment")});var Z=S((nJ,FS)=>{"use strict";var Ru=require("lmdb"),bt=require("fs-extra"),Vt=require("path"),Ba=_s(),LS=I(),De=Ke().LMDB_ERRORS_ENUM,va=uS(),Au=ES(),US=hS(),Br=Ye(),sJ=T(),Wn=Y();Wn.initSync();var yS=Wn.get("STORAGE_WRITEASYNC")===!0||Wn.get("STORAGE_WRITEASYNC")==="true"||Wn.get("STORAGE_WRITEASYNC")==="TRUE",DS=Wn.get("STORAGE_OVERLAPPINGSYNC"),MS=1024*1024*1024,PS=1e4,BS=1e3,kt=Br.INTERNAL_DBIS_NAME,vS=Br.DBI_DEFINITION_NAME,ly="data.mdb",Ey="lock.mdb",Jn=".mdb",dy="-lock",Pa=class{constructor(t,r,s=!1){this.dbi=Ct(t,r),this.key_type=this.dbi[Br.DBI_DEFINITION_NAME].key_type,this.is_hash_attribute=this.dbi[Br.DBI_DEFINITION_NAME].is_hash_attribute,this.txn=t.beginTxn({readOnly:s===!1}),this.cursor=new Ru.Cursor(this.txn,this.dbi)}close(){this.cursor.close(),this.txn.abort()}commit(){this.cursor.close(),this.txn.commit()}};a(Pa,"TransactionCursor");function Ou(e,t){if(e===void 0)throw new Error(De.BASE_PATH_REQUIRED);if(t===void 0)throw new Error(De.ENV_NAME_REQUIRED)}a(Ou,"pathEnvNameValidation");async function pu(e,t,r=!0){try{await bt.access(e)}catch(s){throw s.code==="ENOENT"?new Error(De.INVALID_BASE_PATH):s}try{let s=Vt.join(e,t+Jn);return await bt.access(s,bt.constants.R_OK|bt.constants.F_OK),s}catch(s){if(s.code==="ENOENT")if(r)try{return await bt.access(Vt.join(e,t,ly),bt.constants.R_OK|bt.constants.F_OK),Vt.join(e,t)}catch(n){if(n.code==="ENOENT")throw new Error(De.INVALID_ENVIRONMENT)}else throw new Error(De.INVALID_ENVIRONMENT);throw s}}a(pu,"validateEnvironmentPath");function Ha(e,t){if(Ba.validateEnv(e),t===void 0)throw new Error(De.DBI_NAME_REQUIRED)}a(Ha,"validateEnvDBIName");async function hy(e,t,r=!1,s=!1){Ou(e,t),t=t.toString();try{return await pu(e,t,s),Nu(e,t,r)}catch(n){if(n.message===De.INVALID_ENVIRONMENT){let i=Vt.join(e,t);await bt.mkdirp(s?i:e);let o=new US(s?i:i+Jn,MS,PS,BS,!1,yS,DS),c=Ru.open(o);c.dbis=Object.create(null);let _=new Au(!1);c.openDB(kt,_),global.lmdb_map===void 0&&(global.lmdb_map=Object.create(null));let u=gu(e,t,r);return c[Br.ENVIRONMENT_NAME_KEY]=u,global.lmdb_map[u]=c,c}throw n}}a(hy,"createEnvironment");async function Sy(e,t,r,s=!0){let n=await Nu(e,t);if(r===void 0)throw new Error(De.DESTINATION_PATH_REQUIRED);try{await bt.access(Vt.dirname(r))}catch(i){throw i.code==="ENOENT"?new Error(De.INVALID_DESTINATION_PATH):i}await n.backup(r,s)}a(Sy,"copyEnvironment");async function Nu(e,t,r=!1){Ou(e,t),t=t.toString();let s=gu(e,t,r);if(global.lmdb_map===void 0&&(global.lmdb_map=Object.create(null)),global.lmdb_map[s]!==void 0)return global.lmdb_map[s];let n=await pu(e,t),i=Vt.join(e,t+Jn),o=n!=i,c=new US(n,MS,PS,BS,o,yS,DS),_=Ru.open(c);_.dbis=Object.create(null);let u=GS(_);for(let l=0;l<u.length;l++)Ct(_,u[l]);return _[Br.ENVIRONMENT_NAME_KEY]=s,global.lmdb_map[s]=_,_}a(Nu,"openEnvironment");async function fy(e,t,r=!1){Ou(e,t),t=t.toString();let s=Vt.join(e,t+Jn),n=await pu(e,t);if(global.lmdb_map!==void 0){let i=gu(e,t,r);if(global.lmdb_map[i]){let o=global.lmdb_map[i];await HS(o),delete global.lmdb_map[i]}}await bt.remove(n),await bt.remove(n===s?n+dy:Vt.join(Vt.dirname(n),Ey))}a(fy,"deleteEnvironment");async function HS(e){Ba.validateEnv(e);let t=e[Br.ENVIRONMENT_NAME_KEY];await e.close(),t!==void 0&&global.lmdb_map!==void 0&&delete global.lmdb_map[t]}a(HS,"closeEnvironment");function gu(e,t,r=!1){let n=`${Vt.basename(e)}.${t}`;return r===!0&&(n=`txn.${n}`),n}a(gu,"getCachedEnvironmentName");function Ty(e){Ba.validateEnv(e);let t=Object.create(null),r=Ct(e,kt);for(let{key:s,value:n}of r.getRange({start:!1}))if(s!==kt)try{t[s]=Object.assign(new va,n)}catch{LS.warn(`an internal error occurred: unable to parse DBI Definition for ${s}`)}return t}a(Ty,"listDBIDefinitions");function GS(e){Ba.validateEnv(e);let t=[],r=Ct(e,kt);for(let{key:s}of r.getRange({start:!1}))s!==kt&&t.push(s);return t}a(GS,"listDBIs");function my(e,t){let s=Ct(e,kt).getEntry(t),n=new va;if(s!==void 0){try{n=Object.assign(n,s.value)}catch{LS.warn(`an internal error occurred: unable to parse DBI Definition for ${s}`)}return n}}a(my,"getDBIDefinition");function qS(e,t,r,s=!1){if(Ha(e,t),t=t.toString(),t===kt)throw new Error(De.CANNOT_CREATE_INTERNAL_DBIS_NAME);try{return Ct(e,t)}catch(n){if(n.message===De.DBI_DOES_NOT_EXIST){let i=new Au(r,s===!0),o=e.openDB(t,i),c=new va(r===!0,s);return o[vS]=c,Ct(e,kt).putSync(t,c),e.dbis[t]=o,o}throw n}}a(qS,"createDBI");function Ct(e,t){if(Ha(e,t),t=t.toString(),e.dbis[t]!==void 0)return e.dbis[t];let r;if(t!==kt?r=my(e,t):r=new va,r===void 0)throw new Error(De.DBI_DOES_NOT_EXIST);let s;try{let n=new Au(r.dup_sort,r.useVersions);if(s=e.openDB(t,n),s.db===void 0)throw new Error("MDB_NOTFOUND")}catch(n){throw n.message.includes("MDB_NOTFOUND")===!0?new Error(De.DBI_DOES_NOT_EXIST):n}return s[vS]=r,e.dbis[t]=s,s}a(Ct,"openDBI");function Ry(e,t){Ha(e,t),t=t.toString();let r=Ct(e,t),s=r.getStats();return r[Br.DBI_DEFINITION_NAME].is_hash_attribute&&s.entryCount>0&&s.entryCount--,s}a(Ry,"statDBI");async function Ay(e,t){try{let r=Vt.join(e,t+Jn);return(await bt.stat(r)).size}catch{throw new Error(De.INVALID_ENVIRONMENT)}}a(Ay,"environmentDataSize");function Oy(e,t){if(Ha(e,t),t=t.toString(),t===kt)throw new Error(De.CANNOT_DROP_INTERNAL_DBIS_NAME);Ct(e,t).dropSync(),e.dbis!==void 0&&delete e.dbis[t],Ct(e,kt).removeSync(t)}a(Oy,"dropDBI");function py(e,t,r){for(let s=0;s<r.length;s++){let n=r[s];if(!e.dbis[n])try{Ct(e,n)}catch(i){if(i.message===De.DBI_DOES_NOT_EXIST)qS(e,n,n!==t,n===t);else throw i}}}a(py,"initializeDBIs");FS.exports={openDBI:Ct,openEnvironment:Nu,createEnvironment:hy,listDBIs:GS,listDBIDefinitions:Ty,createDBI:qS,dropDBI:Oy,statDBI:Ry,deleteEnvironment:fy,initializeDBIs:py,TransactionCursor:Pa,environmentDataSize:Ay,copyEnvironment:Sy,closeEnvironment:HS}});var kS=S((iJ,VS)=>{"use strict";var Ga=class{constructor(t=[],r=[],s=void 0){this.written_hashes=t,this.skipped_hashes=r,this.txn_time=s}};a(Ga,"InsertRecordsResponseObject");VS.exports=Ga});var $S=S((aJ,xS)=>{"use strict";var qa=class{constructor(t=[],r=[],s=void 0,n=[]){this.written_hashes=t,this.skipped_hashes=r,this.txn_time=s,this.original_records=n}};a(qa,"UpdateRecordsResponseObject");xS.exports=qa});var KS=S((oJ,YS)=>{"use strict";var Fa=class{constructor(t=[],r=void 0,s=[]){this.written_hashes=t,this.txn_time=r,this.original_records=s}};a(Fa,"UpsertRecordsResponseObject");YS.exports=Fa});var Xs=S((lJ,WS)=>{"use strict";var Ny=Z(),gy=kS(),Iy=$S(),by=KS(),Xn=_s(),Zn=Ke().LMDB_ERRORS_ENUM,Cy=Ye(),vr=T(),wy=b(),Ly=require("uuid"),cJ=require("lmdb"),{handleHDBError:Uy,hdb_errors:yy}=D(),{OVERFLOW_MARKER:_J,MAX_SEARCH_KEY_LENGTH:uJ}=Cy,Iu=vr.TIME_STAMP_NAMES_ENUM.CREATED_TIME,ls=vr.TIME_STAMP_NAMES_ENUM.UPDATED_TIME;async function Dy(e,t,r,s,n=!0){Lu(e,t,r,s),bu(e,t,r);let i=new gy,o=[],c=[];for(let _=0;_<s.length;_++){let u=s[_];QS(u,!0,n);let l=My(e,t,r,u),E=u[t];o.push(l),c.push(E)}return Cu(o,c,s,i)}a(Dy,"insertRecords");function My(e,t,r,s){let n=s[t];return e.dbis[t].ifNoExists(n,()=>{for(let i=0;i<r.length;i++){let o=r[i];if(o===t||s.hasOwnProperty(o)===!1)continue;let c=s[o];if(typeof c=="function"){let u=c([[{}]]);Array.isArray(u)&&(c=u[0][vr.FUNC_VAL],s[o]=c)}let _=Xn.getIndexedValues(c);if(_)for(let u=0,l=_.length;u<l;u++)e.dbis[o].put(_[u],n)}e.dbis[t].put(n,s,s[ls])})}a(My,"insertRecord");function Py(e,t=[]){let r=0;for(let s=0;s<t.length;s++){let n=t[s];e.splice(n-r,1),r++}}a(Py,"removeSkippedRecords");function QS(e,t,r=!0){let s=Date.now();(r===!0||!Number.isInteger(e[ls]))&&(e[ls]=s),t===!0?(r===!0||!Number.isInteger(e[Iu]))&&(e[Iu]=s):delete e[Iu]}a(QS,"setTimestamps");function bu(e,t,r){r.indexOf(vr.TIME_STAMP_NAMES_ENUM.CREATED_TIME)<0&&r.push(vr.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.indexOf(vr.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)<0&&r.push(vr.TIME_STAMP_NAMES_ENUM.UPDATED_TIME),Ny.initializeDBIs(e,t,r)}a(bu,"initializeTransaction");async function By(e,t,r,s,n=!0){Lu(e,t,r,s),bu(e,t,r);let i=new Iy,o=[],c=[],_=[];for(let u=0;u<s.length;u++){let l=s[u],E=l[t],d;try{d=wu(e,t,l,E,i,!0,n)}catch{i.skipped_hashes.push(E),o.push(u);continue}c.push(d),_.push(E)}return Cu(c,_,s,i,o)}a(By,"updateRecords");async function vy(e,t,r,s,n=!0){try{Lu(e,t,r,s)}catch(_){throw Uy(_,_.message,yy.HTTP_STATUS_CODES.BAD_REQUEST)}bu(e,t,r);let i=new by,o=[],c=[];for(let _=0;_<s.length;_++){let u=s[_],l;wy.isEmpty(u[t])?(l=Ly.v4(),u[t]=l):l=u[t];let E=wu(e,t,u,l,i,!1,n);o.push(E),c.push(l)}return Cu(o,c,s,i)}a(vy,"upsertRecords");async function Cu(e,t,r,s,n=[]){let i=await Promise.all(e);for(let o=0,c=i.length;o<c;o++)i[o]===!0?s.written_hashes.push(t[o]):(s.skipped_hashes.push(t[o]),n.push(o));return s.txn_time=Xn.getMicroTime(),Py(r,n),s}a(Cu,"finalizeWrite");function wu(e,t,r,s,n,i=!1,o=!0){let c=e.dbis[t],_=c.getEntry(s),u=_?.value,l=u;if(!u){if(i)return!1;u={}}if(QS(r,!l,o),Number.isInteger(r[ls])&&u[ls]>r[ls])return!1;l&&n.original_records.push(u);let E,d=a(()=>{for(let m in r){if(!r.hasOwnProperty(m)||m===t)continue;let R=r[m],w=e.dbis[m];if(w===void 0)continue;let L=u[m];if(typeof R=="function"){let z=R([[u]]);Array.isArray(z)&&(R=z[0][vr.FUNC_VAL],r[m]=R)}if(R===L)continue;let B=Xn.getIndexedValues(L);if(B)for(let z=0,V=B.length;z<V;z++)w.remove(B[z],s);if(B=Xn.getIndexedValues(R),B)for(let z=0,V=B.length;z<V;z++)w.put(B[z],s)}let h=Object.assign({},u,r);c.put(s,h,h[ls])},"do_put");return _?E=c.ifVersion(s,_.version,d):E=c.ifNoExists(s,d),E.then(h=>h?!0:wu(e,t,r,s,n,i,o))}a(wu,"updateUpsertRecord");function Hy(e,t,r){if(Xn.validateEnv(e),t===void 0)throw new Error(Zn.HASH_ATTRIBUTE_REQUIRED);if(!Array.isArray(r))throw r===void 0?new Error(Zn.WRITE_ATTRIBUTES_REQUIRED):new Error(Zn.WRITE_ATTRIBUTES_MUST_BE_ARRAY)}a(Hy,"validateBasic");function Lu(e,t,r,s){if(Hy(e,t,r),!Array.isArray(s))throw s===void 0?new Error(Zn.RECORDS_REQUIRED):new Error(Zn.RECORDS_MUST_BE_ARRAY)}a(Lu,"validateWrite");WS.exports={insertRecords:Dy,updateRecords:By,upsertRecords:vy}});var te=S((EJ,ZS)=>{"use strict";var Uu=T(),zs=Y(),yu=require("path");zs.initSync();var Va,ka,xa;function JS(){if(Va!==void 0)return Va;if(zs.getHdbBasePath()!==void 0)return Va=yu.join(zs.getHdbBasePath(),Uu.SCHEMA_DIR_NAME),Va}a(JS,"getBaseSchemaPath");function Gy(){if(ka!==void 0)return ka;if(zs.getHdbBasePath()!==void 0)return ka=yu.join(JS(),Uu.SYSTEM_SCHEMA_NAME),ka}a(Gy,"getSystemSchemaPath");function qy(){if(xa!==void 0)return xa;if(zs.getHdbBasePath()!==void 0)return xa=yu.join(zs.getHdbBasePath(),Uu.TRANSACTIONS_DIR_NAME),xa}a(qy,"getTransactionAuditStorePath");ZS.exports={getBaseSchemaPath:JS,getSystemSchemaPath:Gy,getTransactionAuditStorePath:qy}});var Tr=S((dJ,jS)=>{"use strict";var zS=b(),XS=T(),Ya=/^[\x20-\x2E|\x30-\x5F|\x61-\x7E]*$/,Du=require("joi"),$a={schema_format:{pattern:Ya,message:"names cannot include backticks or forward slashes"},schema_length:{maximum:250,tooLong:"cannot exceed 250 characters"}},Fy=Du.alternatives(Du.string().min(1).max($a.schema_length.maximum).pattern(Ya).messages({"string.pattern.base":"{:#label} "+$a.schema_format.message}),Du.number()).required();function Vy(e,t){return t?typeof t!="string"?`'${e}' must be a string`:t.length?t.length>$a.schema_length.maximum?`'${e}' maximum of 250 characters`:Ya.test(t)?"":`'${e}' has illegal characters`:`'${e}' must be at least one character`:`'${e}' is required`}a(Vy,"checkValidTable");function ky(e,t){return zS.doesSchemaExist(e)?e:t.message(`Schema '${e}' does not exist`)}a(ky,"validateSchemaExists");function xy(e,t){let r=t.state.ancestors[0].schema;return zS.doesTableExist(r,e)?e:t.message(`Table '${e}' does not exist`)}a(xy,"validateTableExists");function $y(e,t){return e.toLowerCase()===XS.SYSTEM_SCHEMA_NAME?t.message(`'subscriptions[${t.state.path[1]}]' invalid schema name, '${XS.SYSTEM_SCHEMA_NAME}' name is reserved`):e}a($y,"validateSchemaName");jS.exports={common_validators:$a,schema_regex:Ya,hdb_schema_table:Fy,validateSchemaExists:ky,validateTableExists:xy,validateSchemaName:$y,checkValidTable:Vy}});var Ka=S((hJ,ef)=>{var{common_validators:Hr}=Tr(),zn=de(),xt="is required",X={schema:{presence:!0,format:Hr.schema_format,length:Hr.schema_length},table:{presence:!0,format:Hr.schema_format,length:Hr.schema_length},attribute:{presence:!0,format:Hr.schema_format,length:Hr.schema_length},hash_attribute:{presence:!0,format:Hr.schema_format,length:Hr.schema_length}};function jn(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(jn,"makeAttributesStrings");function Yy(e){return e=jn(e),X.schema.presence={message:xt},X.table.presence=!1,X.attribute.presence=!1,X.hash_attribute.presence=!1,zn.validateObject(e,X)}a(Yy,"schema_object");function Ky(e){return e=jn(e),X.schema.presence={message:xt},X.table.presence={message:xt},X.attribute.presence=!1,X.hash_attribute.presence=!1,zn.validateObject(e,X)}a(Ky,"table_object");function Qy(e){return e=jn(e),X.schema.presence={message:xt},X.table.presence={message:xt},X.attribute.presence=!1,X.hash_attribute.presence={message:xt},zn.validateObject(e,X)}a(Qy,"create_table_object");function Wy(e){return e=jn(e),X.schema.presence={message:xt},X.table.presence={message:xt},X.attribute.presence={message:xt},X.hash_attribute.presence=!1,zn.validateObject(e,X)}a(Wy,"attribute_object");function Jy(e){return e=jn(e),X.schema.presence={message:xt},X.table.presence={message:xt},X.attribute.presence=!1,X.hash_attribute.presence=!1,zn.validateObject(e,X)}a(Jy,"describe_table");function Zy(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(Zy,"validateTableResidence");ef.exports={schema_object:Yy,create_table_object:Qy,table_object:Ky,attribute_object:Wy,describe_table:Jy,validateTableResidence:Zy}});var rf=S((SJ,tf)=>{"use strict";var Xy=require("uuid"),Qa=class{constructor(t,r,s,n){this.schema=t,this.table=r,this.attribute=s,this.id=n||Xy.v4(),this.schema_table=`${this.schema}.${this.table}`}};a(Qa,"CreateAttributeObject");tf.exports=Qa});var Ja=S((fJ,sf)=>{"use strict";var zy=rf(),Wa=class extends zy{constructor(t,r,s,n,i=!0,o=!1){super(t,r,s,n),this.dup_sort=i,this.is_hash_attribute=o}};a(Wa,"LMDBCreateAttributeObject");sf.exports=Wa});var af=S((TJ,nf)=>{"use strict";nf.exports=eD;var jy="inserted";function eD(e,t,r,s){let n={message:`${e} ${t.length} of ${r.records.length} records`,skipped_hashes:s};return e===jy?(n.inserted_hashes=t,n):(n.update_hashes=t,n)}a(eD,"returnObject")});var Za=S((mJ,cf)=>{"use strict";var tD=T(),Mu=Z(),rD=Xs(),{getSystemSchemaPath:sD,getBaseSchemaPath:nD}=te(),iD=require("path"),aD=is(),oD=Ka(),cD=Ja(),_D=af(),{handleHDBError:uD,hdb_errors:lD}=D(),ED=b(),Pu=aD.hdb_attribute,of=[];for(let e=0;e<Pu.attributes.length;e++)of.push(Pu.attributes[e].attribute);var dD="inserted";cf.exports=hD;async function hD(e){let t=oD.attribute_object(e);if(t)throw uD(new Error,t.message,lD.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0);e.is_hash_attribute=e.is_hash_attribute=="true",e.dup_sort=ED.isEmpty(e.dup_sort)||e.dup_sort=="true";let r=[];if(global.hdb_schema[e.schema]&&global.hdb_schema[e.schema][e.table]&&(r=global.hdb_schema[e.schema][e.table].attributes),Array.isArray(r)&&r.length>0){for(let n of r)if(n.attribute===e.attribute)throw new Error(`attribute '${n.attribute}' already exists in ${e.schema}.${e.table}`)}let s=new cD(e.schema,e.table,e.attribute,e.id);try{let n=await Mu.openEnvironment(iD.join(nD(),e.schema.toString()),e.table);if(n.dbis[e.attribute]!==void 0)throw new Error(`attribute '${e.attribute}' already exists in ${e.schema}.${e.table}`);Mu.createDBI(n,e.attribute,e.dup_sort,e.is_hash_attribute);let i=await Mu.openEnvironment(sD(),tD.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME),{written_hashes:o,skipped_hashes:c}=await rD.insertRecords(i,Pu.hash_attribute,of,[s]);return _D(dD,o,{records:[s]},c)}catch(n){throw n}}a(hD,"lmdbCreateAttribute")});var vu=S((RJ,uf)=>{var{hdb_schema_table:_f}=Tr(),SD=de(),Bu=require("joi"),fD={undefined:"undefined",null:"null"},TD=a((e,t)=>{let r=Object.keys(e),s=r.length,n;for(let i=0;i<s;i++){let o=r[i];(!o||o.length===0||fD[o]!==void 0)&&(n===void 0?n=`Invalid attribute name: '${o}'`:n+=`. Invalid attribute name: '${o}'`)}return n?t.message(n):e},"custom_records_val"),mD=Bu.object({schema:_f,table:_f,records:Bu.array().items(Bu.object().custom(TD)).required()});uf.exports=function(e){return SD.validateBySchema(e,mD)}});var Xa=S((OJ,Ef)=>{"use strict";var mr=b(),lf=I(),AJ=vu();Ef.exports=RD;function RD(e){if(mr.isEmpty(e))throw new Error("invalid update parameters defined.");if(mr.isEmptyOrZeroLength(e.schema))throw new Error("invalid schema specified.");if(mr.isEmptyOrZeroLength(e.table))throw new Error("invalid table specified.");if(!Array.isArray(e.records))throw new Error("records must be an array");let t=global.hdb_schema[e.schema][e.table];if(mr.isEmpty(t))throw new Error(`could not retrieve schema:${e.schema} and table ${e.table}`);let r=t.hash_attribute,s=new Set,n={},i=!1;return e.operation==="update"&&(i=!0),e.records.forEach(o=>{if(i&&mr.isEmptyOrZeroLength(o[r]))throw lf.error("a valid hash attribute must be provided with update record:",o),new Error("a valid hash attribute must be provided with update record, check log for more info");if(!mr.isEmptyOrZeroLength(o[r])&&(o[r]==="null"||o[r]==="undefined"))throw lf.error(`a valid hash value must be provided with ${e.operation} record:`,o),new Error(`Invalid hash value: '${o[r]}' is not a valid hash attribute value, check log for more info`);!mr.isEmpty(o[r])&&o[r]!==""&&s.has(mr.autoCast(o[r]))&&(o.skip=!0),s.add(mr.autoCast(o[r]));for(let c in o)n[c]=1}),n[r]=1,{schema_table:t,hashes:Array.from(s),attributes:Object.keys(n)}}a(RD,"insertUpdateValidate")});var ei=S((pJ,df)=>{"use strict";var AD=T().OPERATIONS_ENUM,za=class{constructor(t,r,s,n,i=void 0){this.operation=AD.INSERT,this.schema=t,this.table=r,this.hash_attribute=s,this.records=n,this.__origin=i}};a(za,"InsertObject");df.exports=za});var eo=S((gJ,hf)=>{"use strict";var NJ=ei(),ja=T(),Gu=b(),Hu=I(),OD=require("uuid"),{handleHDBError:ti,hdb_errors:pD}=D(),{HDB_ERROR_MSGS:ri,HTTP_STATUS_CODES:si}=pD;hf.exports=ND;function ND(e,t,r){for(let n=0;n<t.length;n++)gD(t[n]);let{records:s}=e;for(let n=0;n<s.length;n++){let i=s[n];ID(i,r,e.operation)}}a(ND,"processRows");function gD(e){if(Buffer.byteLength(String(e))>ja.INSERT_MODULE_ENUM.MAX_CHARACTER_SIZE)throw ti(new Error,ri.ATTR_NAME_LENGTH_ERR(e),si.BAD_REQUEST,void 0,void 0,!0);if(Gu.isEmptyOrZeroLength(e)||Gu.isEmpty(e.trim()))throw ti(new Error,ri.ATTR_NAME_NULLISH_ERR,si.BAD_REQUEST,void 0,void 0,!0)}a(gD,"validateAttribute");function ID(e,t,r){if(!e.hasOwnProperty(t)||Gu.isEmptyOrZeroLength(e[t])){if(r===ja.OPERATIONS_ENUM.INSERT||r===ja.OPERATIONS_ENUM.UPSERT){e[t]=OD.v4();return}throw Hu.error("Update transaction aborted due to record with no hash value:",e),ti(new Error,ri.RECORD_MISSING_HASH_ERR,si.BAD_REQUEST,void 0,void 0,!0)}if(Buffer.byteLength(String(e[t]))>ja.INSERT_MODULE_ENUM.MAX_CHARACTER_SIZE)throw Hu.error(e),ti(new Error,ri.HASH_VAL_LENGTH_ERR,si.BAD_REQUEST,void 0,void 0,!0);if(isNaN(e[t])&&e[t].includes("/"))throw Hu.error(e),ti(new Error,ri.INVALID_FORWARD_SLASH_IN_HASH_ERR,si.BAD_REQUEST,void 0,void 0,!0)}a(ID,"validateHash")});var ff=S((IJ,Sf)=>{"use strict";var to=class{constructor(t,r){this.type=t,this.message=r}};a(to,"IPCEventObject");Sf.exports=to});var Gr=S((bJ,Tf)=>{"use strict";var bD=I(),qu=b(),CD=T(),{IPC_ERRORS:ni}=Ke();Tf.exports={sendIpcEvent:wD,validateEvent:LD,SchemaEventMsg:UD,UserEventMsg:yD};function wD(e){global.hdb_ipc?global.hdb_ipc.emitToServer(e):bD.warn("Tried to send event:",e,"to HDB IPC client but it does not exist")}a(wD,"sendIpcEvent");function LD(e){if(typeof e!="object")return ni.INVALID_IPC_DATA_TYPE;if(!e.hasOwnProperty("type")||qu.isEmpty(e.type))return ni.MISSING_TYPE;if(!e.hasOwnProperty("message")||qu.isEmpty(e.message))return ni.MISSING_MSG;if(!e.message.hasOwnProperty("originator")||qu.isEmpty(e.message.originator))return ni.MISSING_ORIGIN;if(CD.IPC_EVENT_TYPES[e.type.toUpperCase()]===void 0)return ni.INVALID_EVENT(e.type)}a(LD,"validateEvent");function UD(e,t,r,s=void 0,n=void 0){this.originator=e,this.operation=t,this.schema=r,this.table=s,this.attribute=n}a(UD,"SchemaEventMsg");function yD(e){this.originator=e}a(yD,"UserEventMsg")});var js=S((wJ,Of)=>{"use strict";var mf=T(),CJ=b(),ro=I(),Rf=ff(),{sendIpcEvent:Af}=Gr();function DD(e){try{ro.trace("signalSchemaChange called with message:",e);let t=new Rf(mf.IPC_EVENT_TYPES.SCHEMA,e);Af(t)}catch(t){ro.error(t)}}a(DD,"signalSchemaChange");function MD(e){try{ro.trace("signalUserChange called with message:",e);let t=new Rf(mf.IPC_EVENT_TYPES.USER,e);Af(t)}catch(t){ro.error(t)}}a(MD,"signalUserChange");Of.exports={signalSchemaChange:DD,signalUserChange:MD}});var so=S((LJ,Nf)=>{"use strict";var pf=b(),PD=T(),BD=I(),vD=Za(),HD=Ja(),GD=js(),{SchemaEventMsg:qD}=Gr(),FD="already exists in";Nf.exports=VD;async function VD(e,t,r){try{if(pf.isEmptyOrZeroLength(r))return r;let s=[];pf.isEmptyOrZeroLength(t.attributes)||t.attributes.forEach(i=>{s.push(i.attribute)});let n=r.filter(i=>s.indexOf(i)<0);return n.length===0||await Promise.all(n.map(async i=>{await kD(e,t.schema,t.name,i)})),n}catch(s){throw s}}a(VD,"lmdbCheckForNewAttributes");async function kD(e,t,r,s){let n=new HD(t,r,s,void 0,!0);e&&(n.hdb_auth_header=e);try{await xD(n)}catch(i){if(typeof i=="object"&&i.message!==void 0&&i.message.includes(FD))BD.warn(`attribute ${t}.${r}.${s} already exists`);else throw i}}a(kD,"createNewAttribute");async function xD(e){let t;try{return t=await vD(e),GD.signalSchemaChange(new qD(process.pid,PD.OPERATIONS_ENUM.CREATE_ATTRIBUTE,e.schema,e.table,e.attribute)),t}catch(r){throw r}}a(xD,"createAttribute")});var en=S((UJ,gf)=>{"use strict";var no=class{constructor(t,r,s,n,i=void 0){this.operation=t,this.user_name=r,this.timestamp=s,this.hash_values=n,this.origin=i}};a(no,"LMDBTransactionObject");gf.exports=no});var bf=S((yJ,If)=>{"use strict";var $D=en(),YD=T().OPERATIONS_ENUM,io=class extends $D{constructor(t,r,s,n,i=void 0){super(YD.INSERT,r,s,n,i),this.records=t}};a(io,"LMDBInsertTransactionObject");If.exports=io});var wf=S((DJ,Cf)=>{"use strict";var KD=en(),QD=T().OPERATIONS_ENUM,ao=class extends KD{constructor(t,r,s,n,i,o=void 0){super(QD.UPDATE,s,n,i,o),this.records=t,this.original_records=r}};a(ao,"LMDBUpdateTransactionObject");Cf.exports=ao});var Uf=S((MJ,Lf)=>{"use strict";var WD=en(),JD=T().OPERATIONS_ENUM,oo=class extends WD{constructor(t,r,s,n,i,o=void 0){super(JD.UPSERT,s,n,i,o),this.records=t,this.original_records=r}};a(oo,"LMDBUpsertTransactionObject");Lf.exports=oo});var Df=S((PJ,yf)=>{"use strict";var ZD=en(),XD=T().OPERATIONS_ENUM,co=class extends ZD{constructor(t,r,s,n,i=void 0){super(XD.DELETE,s,n,t,i),this.original_records=r}};a(co,"LMDBDeleteTransactionObject");yf.exports=co});var ii=S((BJ,vf)=>{"use strict";var zD=require("path"),Mf=Z(),jD=bf(),eM=wf(),tM=Uf(),rM=Df(),tn=Ye(),Pf=b(),{CONFIG_PARAMS:sM}=T(),Bf=Y();Bf.initSync();var _o=T().OPERATIONS_ENUM,{getTransactionAuditStorePath:nM}=te();vf.exports=iM;async function iM(e,t){if(Bf.get(sM.LOGGING_AUDITLOG)===!1)return;let r=zD.join(nM(),e.schema.toString()),s=await Mf.openEnvironment(r,e.table,!0),n=aM(e,t);if(!(n===void 0||n.hash_values.length===0)&&s!==void 0){Mf.initializeDBIs(s,tn.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,tn.TRANSACTIONS_DBIS);try{let i=n.timestamp;return await s.dbis[tn.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP].ifNoExists(i,()=>{s.dbis[tn.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP].put(i,n),Pf.isEmpty(n.user_name)||s.dbis[tn.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].put(n.user_name,i);for(let o=0;o<n.hash_values.length;o++)s.dbis[tn.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE].put(n.hash_values[o],i)})}catch(i){throw i}}}a(iM,"writeTransaction");function aM(e,t){let r=Pf.isEmpty(e.hdb_user)?void 0:e.hdb_user.username;if(e.operation===_o.INSERT)return new jD(e.records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===_o.UPDATE)return new eM(e.records,t.original_records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===_o.UPSERT)return new tM(e.records,t.original_records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===_o.DELETE)return new rM(t.deleted,t.original_records,r,t.txn_time,e.__origin)}a(aM,"createTransactionObject")});var Fu=S((HJ,Hf)=>{"use strict";var oM=Xa(),vJ=ei(),rn=T(),cM=eo(),_M=Xs().insertRecords,uM=Z(),lM=require("path"),EM=I(),dM=so(),{getBaseSchemaPath:hM}=te(),SM=ii();Hf.exports=fM;async function fM(e){try{let{schema_table:t,attributes:r}=oM(e);cM(e,r,t.hash_attribute),e.schema!==rn.SYSTEM_SCHEMA_NAME&&(r.includes(rn.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||r.push(rn.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.includes(rn.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||r.push(rn.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let s=await dM(e.hdb_auth_header,t,r),n=lM.join(hM(),e.schema.toString()),i=await uM.openEnvironment(n,e.table),o=await _M(i,t.hash_attribute,r,e.records,e[rn.CLUSTERING_FLAG]!==!0);try{await SM(e,o)}catch(c){EM.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:s,txn_time:o.txn_time}}catch(t){throw t}}a(fM,"lmdbCreateRecords")});var Ff=S((GJ,qf)=>{"use strict";var Gf=T(),TM=Fu(),mM=ei(),RM=require("fs-extra"),AM=require("path"),{getBaseSchemaPath:OM}=te();qf.exports=pM;async function pM(e){let t=[{name:e.schema,createddate:Date.now()}],r=new mM(Gf.SYSTEM_SCHEMA_NAME,Gf.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,void 0,t);await TM(r),await RM.mkdirp(AM.join(OM(),e.schema.toString()))}a(pM,"lmdbCreateSchema")});var kf=S((qJ,Vf)=>{"use strict";var uo=class{constructor(t=[],r=[],s=void 0,n=[]){this.deleted=t,this.skipped=r,this.txn_time=s,this.original_records=n}};a(uo,"DeleteRecordsResponseObject");Vf.exports=uo});var xu=S((xJ,Yf)=>{"use strict";var xf=Z(),Vu=_s(),ku=Ke().LMDB_ERRORS_ENUM,NM=Ye(),$f=I(),FJ=b(),gM=require("lmdb"),IM=kf(),{OVERFLOW_MARKER:VJ,MAX_SEARCH_KEY_LENGTH:kJ}=NM;async function bM(e,t,r){if(Vu.validateEnv(e),t===void 0)throw new Error(ku.HASH_ATTRIBUTE_REQUIRED);if(!Array.isArray(r))throw r===void 0?new Error(ku.IDS_REQUIRED):new Error(ku.IDS_MUST_BE_ARRAY);try{let s=xf.listDBIs(e);xf.initializeDBIs(e,t,s);let n=new IM,i,o=[],c=[];for(let E=0,d=r.length;E<d;E++)try{i=r[E];let h=e.dbis[t].get(i);if(!h){n.skipped.push(i);continue}let m=e.dbis[t].ifVersion(i,gM.IF_EXISTS,()=>{e.dbis[t].remove(i);for(let R=0;R<s.length;R++){let w=s[R];if(!h.hasOwnProperty(w)||w===t)continue;let L=e.dbis[w],B=h[w];if(B!=null)try{let z=Vu.getIndexedValues(B);if(z)for(let V=0,W=z.length;V<W;V++)L.remove(z[V],i)}catch{$f.warn(`cannot delete from attribute: ${w}, ${B}:${i}`)}}});o.push(m),c.push(i),n.original_records.push(h)}catch(h){$f.warn(h),n.skipped.push(i)}let _=[],u=await Promise.all(o);for(let E=0,d=u.length;E<d;E++)u[E]===!0?n.deleted.push(c[E]):(n.skipped.push(c[E]),_.push(E));let l=0;for(let E=0;E<_.length;E++){let d=_[E];n.original_records.splice(d-l,1),l++}return n.txn_time=Vu.getMicroTime(),n}catch(s){throw s}}a(bM,"deleteRecords");Yf.exports={deleteRecords:bM}});var ai=S(($J,Qf)=>{"use strict";var sn=b(),CM=xu(),wM=Z(),LM=require("path"),{getBaseSchemaPath:UM}=te(),yM=ii(),DM=I();Qf.exports=MM;async function MM(e,t=!0){let s=global.hdb_schema[e.schema][e.table].hash_attribute;if(sn.isEmpty(s))throw new Error(`could not retrieve hash attribute for schema:${e.schema} and table ${e.table}`);try{if(sn.isEmptyOrZeroLength(e.hash_values)&&!sn.isEmptyOrZeroLength(e.records)){e.hash_values=[];for(let c=0;c<e.records.length;c++){let _=e.records[c][s];sn.isEmpty(_)||e.hash_values.push(_)}}if(sn.isEmptyOrZeroLength(e.hash_values))return Kf([],[]);if(!Array.isArray(e.hash_values))throw new Error("hash_values must be an array");if(sn.isEmptyOrZeroLength(e.records)){e.records=[];for(let c=0;c<e.hash_values.length;c++)e.records[c]={[s]:e.hash_values[c]}}let n=LM.join(UM(),e.schema.toString()),i=await wM.openEnvironment(n,e.table),o=await CM.deleteRecords(i,s,e.hash_values);try{t===!0&&await yM(e,o)}catch(c){DM.error(`unable to write transaction due to ${c.message}`)}return Kf(o.deleted,o.skipped,o.txn_time)}catch(n){throw n}}a(MM,"lmdbDeleteRecords");function Kf(e,t,r){let s=e.length+t.length,n=s===1?"record":"records";return{message:`${e.length} of ${s} ${n} successfully deleted`,deleted_hashes:e,skipped_hashes:t,txn_time:r}}a(Kf,"createDeleteResponse")});var Yu=S((KJ,Wf)=>{"use strict";var PM=T(),YJ=_s();function $u(e,t){let r=Object.create(null);if(t.length===1&&PM.SEARCH_WILDCARDS.indexOf(t[0])>=0)Object.assign(r,e);else for(let s=0;s<t.length;s++){let n=t[s],i=e[n];r[n]=i===void 0?null:i}return r}a($u,"parseRow");function BM(e,t,r,s){let n=$u(r,e);s.push(n)}a(BM,"searchAll");function vM(e,t,r,s){let n=$u(r,e);s[t]=n}a(vM,"searchAllToMap");function HM(e,t,r){r[e]===void 0&&(r[e]=[]),r[e].push(t)}a(HM,"iterateDBI");function Es(e,t,r,s,n){let i=Object.create(null);i[n]=e;let o;s===n?o=e:(o=t,s!==void 0&&(i[s]=o)),r[0].push(o),r[1].push(i)}a(Es,"pushResults");function GM(e,t,r,s,n,i){t.toString().endsWith(e)&&Es(t,r,s,n,i)}a(GM,"endsWith");function qM(e,t,r,s,n,i){t.toString().includes(e)&&Es(t,r,s,n,i)}a(qM,"contains");function FM(e,t,r,s,n,i){t>e&&Es(t,r,s,n,i)}a(FM,"greaterThanCompare");function VM(e,t,r,s,n,i){t>=e&&Es(t,r,s,n,i)}a(VM,"greaterThanEqualCompare");function kM(e,t,r,s,n,i){t<e&&Es(t,r,s,n,i)}a(kM,"lessThanCompare");function xM(e,t,r,s,n,i){t<=e&&Es(t,r,s,n,i)}a(xM,"lessThanEqualCompare");Wf.exports={parseRow:$u,searchAll:BM,searchAllToMap:vM,iterateDBI:HM,endsWith:GM,contains:qM,greaterThanCompare:FM,greaterThanEqualCompare:VM,lessThanCompare:kM,lessThanEqualCompare:xM,pushResults:Es}});var nn=S((JJ,eT)=>{"use strict";var wt=Z(),$M=I(),ft=_s(),qr=Ye(),ce=Ke().LMDB_ERRORS_ENUM,QJ=b(),YM=T(),$t=Yu(),WJ=require("lmdb"),{OVERFLOW_MARKER:Jf,MAX_SEARCH_KEY_LENGTH:KM}=qr,oi={lazy:!0};function Zf(e,t,r,s,n=!1,i=void 0,o=void 0){let c=Object.create(null),_=wt.openDBI(e,r);_[qr.DBI_DEFINITION_NAME].is_hash_attribute&&(t=r);let u=Ku(e,t,r);for(let{key:l,value:E}of _.getRange({start:n?void 0:!1,end:n?!1:void 0,limit:i,offset:o,reverse:n}))s(u(l,E),E,c,t,r);return c}a(Zf,"iterateFullIndex");function ci(e,t,r,s,n,i=!1,o=void 0,c=void 0,_=!1,u=!1){let l=[[],[]],E=wt.openDBI(e,r),d=Ku(e,t,r);E[qr.DBI_DEFINITION_NAME].is_hash_attribute&&(t=r);let h=i===!0?s:n,m=i===!0?n:s,R=i===!0?!_:!u,w=i===!0?u:_;for(let{key:L,value:B}of E.getRange({start:m,end:h,reverse:i,limit:o,offset:c,inclusiveEnd:R,exclusiveStart:w}))$t.pushResults(d(L,B),B,l,t,r);return l}a(ci,"iterateRangeBetween");function Ku(e,t,r){let s;return function(n,i){if(typeof n=="string"&&n.endsWith(Jf)){if(!s)if(t)s=wt.openDBI(e,t);else{let c=wt.listDBIs(e);for(let _=0,u=c.length;_<u&&(s=wt.openDBI(e,c[_]),!s[qr.DBI_DEFINITION_NAME].is_hash_attribute);_++);}n=s.get(i,oi)[r]}return n}}a(Ku,"getOverflowCheck");function QM(e,t,r,s=!1,n=void 0,i=void 0){if(ft.validateEnv(e),t===void 0)throw new Error(ce.HASH_ATTRIBUTE_REQUIRED);lo(r),r=_i(e,r);let o=[],c=wt.openDBI(e,t);for(let{key:_,value:u}of c.getRange({start:s?void 0:!1,end:s?!1:void 0,limit:n,offset:i,reverse:s}))$t.searchAll(r,_,u,o);return o}a(QM,"searchAll");function WM(e,t,r,s=!1,n=void 0,i=void 0){if(ft.validateEnv(e),t===void 0)throw new Error(ce.HASH_ATTRIBUTE_REQUIRED);return lo(r),r=_i(e,r),Zf(e,t,t,$t.searchAllToMap.bind(null,r),s,n,i)}a(WM,"searchAllToMap");function JM(e,t,r=!1,s=void 0,n=void 0){if(ft.validateEnv(e),t===void 0)throw new Error(ce.ATTRIBUTE_REQUIRED);return Zf(e,void 0,t,$t.iterateDBI,r,s,n)}a(JM,"iterateDBI");function ZM(e,t){if(ft.validateEnv(e),t===void 0)throw new Error(ce.HASH_ATTRIBUTE_REQUIRED);return wt.statDBI(e,t).entryCount}a(ZM,"countAll");function XM(e,t,r,s,n=!1,i=void 0,o=void 0){Fr(e,r,s);let c=wt.openDBI(e,r);s=ft.convertKeyValueToWrite(s);let _=[[],[]];if(c[qr.DBI_DEFINITION_NAME].is_hash_attribute){t=r;let u=c.get(s,oi);u!==void 0&&$t.pushResults(s,u,_,t,r)}else for(let u of c.getValues(s,{reverse:n,limit:i,offset:o}))$t.pushResults(s,u,_,t,r);return _}a(XM,"equals");function zM(e,t,r){return Fr(e,t,r),wt.openDBI(e,t).getValuesCount(r)}a(zM,"count");function jM(e,t,r,s,n=!1,i=void 0,o=void 0){Fr(e,r,s);let c=[[],[]],_=wt.openDBI(e,r);_[qr.DBI_DEFINITION_NAME].is_hash_attribute&&(t=r),s=ft.convertKeyValueToWrite(s);let u=!0;if(typeof s=="number"&&(u=!1),n===!0){let l;for(let E of _.getKeys({start:s}))if(!E.startsWith(s)){l=E;break}l!==void 0&&(Number.isInteger(o)?o++:i++);for(let{key:E,value:d}of _.getRange({start:l,end:void 0,reverse:n,limit:i,offset:o}))if(E!==l){if(E.toString().startsWith(s))$t.pushResults(E,d,c,t,r);else if(u===!0)break}}else for(let{key:l,value:E}of _.getRange({start:s,reverse:n,limit:i,offset:o}))if(l.toString().startsWith(s))$t.pushResults(l,E,c,t,r);else if(u===!0)break;return c}a(jM,"startsWith");function eP(e,t,r,s,n=!1,i=void 0,o=void 0){return Xf(e,t,r,s,n,i,o,!0)}a(eP,"endsWith");function Xf(e,t,r,s,n=!1,i=void 0,o=void 0,c=!1){Fr(e,r,s);let _=[[],[]],u=wt.openDBI(e,r);u[qr.DBI_DEFINITION_NAME].is_hash_attribute&&(t=r);let l=Ku(e,t,r);o=Number.isInteger(o)?o:0;for(let d of u.getKeys({end:n?!1:void 0,reverse:n})){if(i===0)break;let h=d.toString();if(h.endsWith(Jf))for(let m of u.getValues(d)){let R=l(d,m);(c?R.endsWith(s):R.includes(s))&&E(R,m)}else if(c?h.endsWith(s):h.includes(s))if(u[qr.DBI_DEFINITION_NAME].is_hash_attribute)E(d,d);else for(let m of u.getValues(d))E(d,m)}function E(d,h){if(o>0){o--;return}i!==0&&($t.pushResults(d,h,_,t,r),i--)}return a(E,"found_match"),_}a(Xf,"contains");function tP(e,t,r,s,n=!1,i=void 0,o=void 0){Fr(e,r,s);let c=typeof s,_;return c==="string"?_="\uFFFF":c==="number"?_=1/0:c==="boolean"&&(_=!0),ci(e,t,r,s,_,n,i,o,!0,!1)}a(tP,"greaterThan");function rP(e,t,r,s,n=!1,i=void 0,o=void 0){Fr(e,r,s);let c=typeof s,_;return c==="string"?_="\uFFFF":c==="number"?_=1/0:c==="boolean"&&(_=!0),ci(e,t,r,s,_,n,i,o,!1,!1)}a(rP,"greaterThanEqual");function sP(e,t,r,s,n=!1,i=void 0,o=void 0){Fr(e,r,s);let c=typeof s,_;return c==="string"?_="\0":c==="number"?_=-1/0:c==="boolean"&&(_=!1),ci(e,t,r,_,s,n,i,o,!1,!0)}a(sP,"lessThan");function nP(e,t,r,s,n=!1,i=void 0,o=void 0){Fr(e,r,s);let c=typeof s,_;return c==="string"?_="\0":c==="number"?_=-1/0:c==="boolean"&&(_=!1),ci(e,t,r,_,s,n,i,o,!1,!1)}a(nP,"lessThanEqual");function iP(e,t,r,s,n,i=!1,o=void 0,c=void 0){if(ft.validateEnv(e),r===void 0)throw new Error(ce.ATTRIBUTE_REQUIRED);if(s===void 0)throw new Error(ce.START_VALUE_REQUIRED);if(n===void 0)throw new Error(ce.END_VALUE_REQUIRED);if(s=ft.convertKeyValueToWrite(s),n=ft.convertKeyValueToWrite(n),s>n)throw new Error(ce.END_VALUE_MUST_BE_GREATER_THAN_START_VALUE);return ci(e,t,r,s,n,i,o,c)}a(iP,"between");function aP(e,t,r,s){if(ft.validateEnv(e),t===void 0)throw new Error(ce.HASH_ATTRIBUTE_REQUIRED);if(lo(r),r=_i(e,r),s===void 0)throw new Error(ce.ID_REQUIRED);let n=null,i=e.dbis[t].get(s,r.length<3?oi:void 0);return i&&(n=$t.parseRow(i,r)),n}a(aP,"searchByHash");function oP(e,t,r){if(ft.validateEnv(e),t===void 0)throw new Error(ce.HASH_ATTRIBUTE_REQUIRED);if(r===void 0)throw new Error(ce.ID_REQUIRED);let s=!0;return e.dbis[t].get(r,oi)===void 0&&(s=!1),s}a(oP,"checkHashExists");function cP(e,t,r,s,n=[]){jf(e,t,r,s,n);let i=zf(e,t,r,s,n);return Object.values(i)}a(cP,"batchSearchByHash");function _P(e,t,r,s,n=[]){return jf(e,t,r,s,n),zf(e,t,r,s,n)}a(_P,"batchSearchByHashToMap");function zf(e,t,r,s,n=[]){r=_i(e,r);let i=Object.create(null),o=r.length<3?oi:void 0;for(let c=0;c<s.length;c++){let _=s[c];try{let u=e.dbis[t].get(_,o);if(u){let l=$t.parseRow(u,r);i[_]=l}else n.push(_)}catch(u){throw $M.warn(u),u}}return i}a(zf,"batchHashSearch");function jf(e,t,r,s,n){if(ft.validateEnv(e),t===void 0)throw new Error(ce.HASH_ATTRIBUTE_REQUIRED);if(lo(r),!Array.isArray(s))throw s===void 0?new Error(ce.IDS_REQUIRED):new Error(ce.IDS_MUST_BE_ARRAY);Array.isArray(n)||(n=[])}a(jf,"initializeBatchSearchByHash");function lo(e){if(!Array.isArray(e))throw e===void 0?new Error(ce.FETCH_ATTRIBUTES_REQUIRED):new Error(ce.FETCH_ATTRIBUTES_MUST_BE_ARRAY)}a(lo,"validateFetchAttributes");function Fr(e,t,r){if(ft.validateEnv(e),t===void 0)throw new Error(ce.ATTRIBUTE_REQUIRED);if(r===void 0)throw new Error(ce.SEARCH_VALUE_REQUIRED);if(r?.length>KM)throw new Error(ce.SEARCH_VALUE_TOO_LARGE)}a(Fr,"validateComparisonFunctions");function _i(e,t){return t.length===1&&YM.SEARCH_WILDCARDS.indexOf(t[0])>=0&&(t=wt.listDBIs(e)),t}a(_i,"setGetWholeRowAttributes");eT.exports={searchAll:QM,searchAllToMap:WM,count:zM,countAll:ZM,equals:XM,startsWith:jM,endsWith:eP,contains:Xf,searchByHash:aP,setGetWholeRowAttributes:_i,batchSearchByHash:cP,batchSearchByHashToMap:_P,checkHashExists:oP,iterateDBI:JM,greaterThan:tP,greaterThanEqual:rP,lessThan:sP,lessThanEqual:nP,between:iP}});var ui=S((XJ,nT)=>{var tT=require("lodash"),rT=de(),Q=require("joi"),uP=b(),{hdb_schema_table:Yt,checkValidTable:sT}=Tr(),{handleHDBError:lP,hdb_errors:EP}=D(),{HTTP_STATUS_CODES:dP}=EP,ZJ=Q.object({schema:Yt,table:Yt,hash_values:Q.array().min(1).items(Q.alternatives(Q.string(),Q.number())).required(),get_attributes:Q.array().min(1).items(Yt).required()}),hP=Q.object({schema:Yt,table:Yt,search_attribute:Yt,search_value:Q.any().required(),get_attributes:Q.array().min(1).items(Yt).required(),desc:Q.bool(),limit:Q.number().integer().min(1),offset:Q.number().integer().min(0)}),SP=Q.object({schema:Yt,table:Yt,operator:Q.string().valid("and","or").default("and").lowercase(),offset:Q.number().integer().min(0),limit:Q.number().integer().min(1),get_attributes:Q.array().min(1).items(Yt).required(),conditions:Q.array().min(1).items(Q.object({search_attribute:Yt,search_type:Q.string().valid("equals","contains","starts_with","ends_with","greater_than","greater_than_equal","less_than","less_than_equal","between").required(),search_value:Q.when("search_type",{switch:[{is:"equals",then:Q.any()},{is:"between",then:Q.array().items(Q.alternatives([Q.string(),Q.number()])).length(2)}],otherwise:Q.alternatives(Q.string(),Q.number())}).required()})).required()});nT.exports=function(e,t){let r=null;switch(t){case"value":r=rT.validateBySchema(e,hP);break;case"hashes":let i=function(o){n?n+=". "+o:n=o};var s=i;a(i,"addError");let n;i(sT("schema",e.schema)),i(sT("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"),n&&(r=new Error(n.trim()));break;case"conditions":r=rT.validateBySchema(e,SP);break;default:throw new Error(`Error validating search, unknown type: ${t}`)}if(!r&&e.schema!=="system"){let n=uP.checkGlobalSchemaTable(e.schema,e.table);if(n)return lP(new Error,n,dP.NOT_FOUND);let o=global.hdb_schema[e.schema][e.table].attributes,c=[...e.get_attributes];if(t==="value"&&c.push(e.search_attribute),t==="conditions")for(let u=0,l=e.conditions.length;u<l;u++){let E=e.conditions[u];c.push(E.search_attribute)}let _=tT.filter(c,u=>u!=="*"&&u.attribute!=="*"&&!tT.some(o,l=>l===u||l.attribute===u||l.attribute===u.attribute));if(_&&_.length>0){let u=_.join(", ");return u=u.replace(/,([^,]*)$/," and$1"),new Error(`unknown attribute '${u}'`)}}return r}});var Qu=S((zJ,iT)=>{"use strict";var fP=Z(),TP=ui(),mP=require("path"),{getBaseSchemaPath:RP}=te();iT.exports=AP;function AP(e){let t=TP(e,"hashes");if(t)throw t;let r=mP.join(RP(),e.schema.toString());return fP.openEnvironment(r,e.table)}a(AP,"initialize")});var Wu=S((jJ,aT)=>{"use strict";var OP=nn(),pP=Qu();aT.exports=NP;async function NP(e){try{let t=await pP(e),r=global.hdb_schema[e.schema][e.table];return OP.batchSearchByHashToMap(t,r.hash_attribute,e.get_attributes,e.hash_values)}catch(t){throw t}}a(NP,"lmdbGetDataByHash")});var ds=S((eZ,oT)=>{"use strict";var Eo=class{constructor(t,r,s,n){this.schema=t,this.table=r,this.hash_values=s,this.get_attributes=n}};a(Eo,"SearchByHashObject");oT.exports=Eo});var _T=S((rZ,cT)=>{"use strict";var tZ=ds(),gP=nn(),IP=Qu();cT.exports=bP;async function bP(e){try{let t=await IP(e),r=global.hdb_schema[e.schema][e.table];return gP.batchSearchByHash(t,r.hash_attribute,e.get_attributes,e.hash_values)}catch(t){throw t}}a(bP,"lmdbSearchByHash")});var Kt=S((sZ,uT)=>{"use strict";var ho=class{constructor(t,r,s,n,i,o,c,_=!1,u=void 0,l=void 0){this.schema=t,this.table=r,this.search_attribute=s,this.search_value=n,this.hash_attribute=i,this.get_attributes=o,this.end_value=c,this.reverse=_,this.limit=u,this.offset=l}};a(ho,"SearchObject");uT.exports=ho});var So=S((nZ,ST)=>{"use strict";var We=nn(),CP=Z(),wP=require("path"),LP=b(),U=Ye(),hs=T(),{getBaseSchemaPath:UP}=te(),yP=is(),lT=Ke().LMDB_ERRORS_ENUM,{compareKeys:an}=require("ordered-binary"),Rr=hs.SEARCH_WILDCARDS;async function DP(e,t,r){let s;e.schema===hs.SYSTEM_SCHEMA_NAME?s=yP[e.table]:s=global.hdb_schema[e.schema][e.table];let n=hT(e,s.hash_attribute,r,t);return ET(e,n,s.hash_attribute,r)}a(DP,"prepSearch");async function ET(e,t,r,s){let n=wP.join(UP(),e.schema.toString()),i=await CP.openEnvironment(n,e.table),o=dT(i,e,t,r);if([U.SEARCH_TYPES.BATCH_SEARCH_BY_HASH,U.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP,U.SEARCH_TYPES.SEARCH_ALL,U.SEARCH_TYPES.SEARCH_ALL_TO_MAP].indexOf(t)>=0)return o;if(BP(e,r)===!1)return s===!0?PP(o):o[1];let _=o[0];return s===!0?We.batchSearchByHashToMap(i,r,e.get_attributes,_):We.batchSearchByHash(i,r,e.get_attributes,_)}a(ET,"executeSearch");function dT(e,t,r,s){let n,i=s;t.get_attributes.indexOf(s)<0&&(i=void 0);let{reverse:o,limit:c,offset:_}=t;switch(o=typeof o=="boolean"?o:!1,c=Number.isInteger(c)?c:void 0,_=Number.isInteger(_)?_:void 0,r){case U.SEARCH_TYPES.EQUALS:n=We.equals(e,i,t.search_attribute,t.search_value,o,c,_);break;case U.SEARCH_TYPES.CONTAINS:n=We.contains(e,i,t.search_attribute,t.search_value,o,c,_);break;case U.SEARCH_TYPES.ENDS_WITH:case U.SEARCH_TYPES._ENDS_WITH:n=We.endsWith(e,i,t.search_attribute,t.search_value,o,c,_);break;case U.SEARCH_TYPES.STARTS_WITH:case U.SEARCH_TYPES._STARTS_WITH:n=We.startsWith(e,i,t.search_attribute,t.search_value,o,c,_);break;case U.SEARCH_TYPES.BATCH_SEARCH_BY_HASH:return We.batchSearchByHash(e,t.search_attribute,t.get_attributes,[t.search_value]);case U.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP:return We.batchSearchByHashToMap(e,t.search_attribute,t.get_attributes,[t.search_value]);case U.SEARCH_TYPES.SEARCH_ALL:return We.searchAll(e,s,t.get_attributes,o,c,_);case U.SEARCH_TYPES.SEARCH_ALL_TO_MAP:return We.searchAllToMap(e,s,t.get_attributes,o,c,_);case U.SEARCH_TYPES.BETWEEN:n=We.between(e,i,t.search_attribute,t.search_value,t.end_value,o,c,_);break;case U.SEARCH_TYPES.GREATER_THAN:case U.SEARCH_TYPES._GREATER_THAN:n=We.greaterThan(e,i,t.search_attribute,t.search_value,o,c,_);break;case U.SEARCH_TYPES.GREATER_THAN_EQUAL:case U.SEARCH_TYPES._GREATER_THAN_EQUAL:n=We.greaterThanEqual(e,i,t.search_attribute,t.search_value,o,c,_);break;case U.SEARCH_TYPES.LESS_THAN:case U.SEARCH_TYPES._LESS_THAN:n=We.lessThan(e,i,t.search_attribute,t.search_value,o,c,_);break;case U.SEARCH_TYPES.LESS_THAN_EQUAL:case U.SEARCH_TYPES._LESS_THAN_EQUAL:n=We.lessThanEqual(e,i,t.search_attribute,t.search_value,o,c,_);break;default:return Object.create(null)}return n}a(dT,"searchByType");function MP(e){let t=e.search_type,r=e.search_attribute,s=e.search_value;switch(t){case U.SEARCH_TYPES.EQUALS:return n=>n[r]===s;case U.SEARCH_TYPES.CONTAINS:return n=>typeof n[r]=="string"&&n[r].includes(s);case U.SEARCH_TYPES.ENDS_WITH:case U.SEARCH_TYPES._ENDS_WITH:return n=>typeof n[r]=="string"&&n[r].endsWith(s);case U.SEARCH_TYPES.STARTS_WITH:case U.SEARCH_TYPES._STARTS_WITH:return n=>typeof n[r]=="string"&&n[r].startsWith(s);case U.SEARCH_TYPES.BETWEEN:return n=>{let i=n[r];return an(i,s[0])>=0&&an(i,s[1])<=0};case U.SEARCH_TYPES.GREATER_THAN:case U.SEARCH_TYPES._GREATER_THAN:return n=>an(n[r],s)>0;case U.SEARCH_TYPES.GREATER_THAN_EQUAL:case U.SEARCH_TYPES._GREATER_THAN_EQUAL:return n=>an(n[r],s)>=0;case U.SEARCH_TYPES.LESS_THAN:case U.SEARCH_TYPES._LESS_THAN:return n=>an(n[r],s)<0;case U.SEARCH_TYPES.LESS_THAN_EQUAL:case U.SEARCH_TYPES._LESS_THAN_EQUAL:return n=>an(n[r],s)<=0;default:return Object.create(null)}}a(MP,"filterByType");function PP(e){let t=Object.create(null);for(let r=0,s=e[0].length;r<s;r++)t[e[0][r]]=e[1][r];return t}a(PP,"createMapFromArrays");function BP(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 s=!1;for(let n=0;n<e.get_attributes.length;n++)if(r.indexOf(e.get_attributes[n])<0){s=!0;break}return s}a(BP,"checkToFetchMore");function hT(e,t,r,s){if(LP.isEmpty(s)){let n=e.search_value;typeof n=="object"?n=JSON.stringify(n):n=n.toString();let i=n.charAt(0),o=n.charAt(n.length-1),c=!1;if(e.search_attribute===t&&(c=!0),Rr.indexOf(n)>-1)return r===!0?U.SEARCH_TYPES.SEARCH_ALL_TO_MAP:U.SEARCH_TYPES.SEARCH_ALL;if(n.indexOf(Rr[0])<0&&n.indexOf(Rr[1])<0)return c===!0?r===!0?U.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP:U.SEARCH_TYPES.BATCH_SEARCH_BY_HASH:U.SEARCH_TYPES.EQUALS;if(Rr.indexOf(i)>=0&&Rr.indexOf(o)>=0)return e.search_value=e.search_value.slice(1,-1),U.SEARCH_TYPES.CONTAINS;if(Rr.indexOf(i)>=0)return e.search_value=e.search_value.substr(1),U.SEARCH_TYPES.ENDS_WITH;if(Rr.indexOf(o)>=0)return e.search_value=e.search_value.slice(0,-1),U.SEARCH_TYPES.STARTS_WITH;if(n.includes(Rr[0])||n.includes(Rr[1]))return U.SEARCH_TYPES.EQUALS;throw new Error(lT.UNKNOWN_SEARCH_TYPE)}else switch(s){case hs.VALUE_SEARCH_COMPARATORS.BETWEEN:return U.SEARCH_TYPES.BETWEEN;case hs.VALUE_SEARCH_COMPARATORS.GREATER:return U.SEARCH_TYPES.GREATER_THAN;case hs.VALUE_SEARCH_COMPARATORS.GREATER_OR_EQ:return U.SEARCH_TYPES.GREATER_THAN_EQUAL;case hs.VALUE_SEARCH_COMPARATORS.LESS:return U.SEARCH_TYPES.LESS_THAN;case hs.VALUE_SEARCH_COMPARATORS.LESS_OR_EQ:return U.SEARCH_TYPES.LESS_THAN_EQUAL;default:throw new Error(lT.UNKNOWN_SEARCH_TYPE)}}a(hT,"createSearchTypeFromSearchObject");ST.exports={executeSearch:ET,createSearchTypeFromSearchObject:hT,prepSearch:DP,searchByType:dT,filterByType:MP}});var TT=S((aZ,fT)=>{"use strict";var iZ=Kt(),vP=ui(),HP=b(),GP=T(),qP=So();fT.exports=FP;async function FP(e,t){if(!HP.isEmpty(t)&&GP.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[t]===void 0)throw new Error(`Value search comparator - ${t} - is not valid`);let s=vP(e,"value");if(s)throw s;let n=!0;try{return await qP.prepSearch(e,t,n)}catch(i){throw i}}a(FP,"lmdbGetDataByValue")});var on=S((cZ,mT)=>{"use strict";var oZ=Kt(),VP=ui(),kP=b(),xP=T(),$P=So();mT.exports=YP;async function YP(e,t){if(!kP.isEmpty(t)&&xP.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[t]===void 0)throw new Error(`Value search comparator - ${t} - is not valid`);let s=VP(e,"value");if(s)throw s;let n=!1;try{return await $P.prepSearch(e,t,n)}catch(i){throw i}}a(YP,"lmdbSearchByValue")});var AT=S((uZ,RT)=>{"use strict";var _Z=Ye(),fo=class{constructor(t,r,s,n,i=void 0,o=void 0,c="and"){this.schema=t,this.table=r,this.get_attributes=s,this.limit=i,this.offset=o,this.conditions=n,this.operator=c}};a(fo,"SearchByConditionsObject");var To=class{constructor(t,r,s){this.search_attribute=t,this.search_type=r,this.search_value=s}};a(To,"SearchCondition");var mo=class{constructor(t,r){this.attribute=t,this.desc=r}};a(mo,"SortAttribute");RT.exports={SearchByConditionsObject:fo,SearchCondition:To,SortAttribute:mo}});var bT=S((EZ,IT)=>{"use strict";var lZ=AT().SearchByConditionsObject,KP=Kt(),QP=ui(),Ju=nn(),Ro=Ye(),gT=So(),WP=Yu(),OT=require("lodash"),{getBaseSchemaPath:JP}=te(),ZP=require("path"),XP=Z(),{handleHDBError:pT,hdb_errors:zP}=D(),{HTTP_STATUS_CODES:jP}=zP,eB=1e8,tB={lazy:!0};IT.exports=rB;async function rB(e){try{let t=QP(e,"conditions");if(t)throw pT(t,t.message,jP.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=ZP.join(JP(),e.schema.toString()),s=await XP.openEnvironment(r,e.table),n=global.hdb_schema[e.schema][e.table],i=OT.sortBy(e.conditions,o=>{if(o.estimated_count===void 0){let c=o.search_type;c===Ro.SEARCH_TYPES.EQUALS?o.estimated_count=Ju.count(s,o.search_attribute,o.search_value):c===Ro.SEARCH_TYPES.CONTAINS||c===Ro.SEARCH_TYPES.ENDS_WITH?o.estimated_count=1/0:o.estimated_count=eB}return o.estimated_count});if(!e.operator||e.operator.toLowerCase()==="and"){let[o]=await NT(s,e,i[0],n.hash_attribute),c=s.dbis[n.hash_attribute],_=i.slice(1).map(gT.filterByType),u=_.length,l=[],E=Ju.setGetWholeRowAttributes(s,e.get_attributes),d=e.offset>-1?e.offset:0,h=e.limit>-1?e.limit:1/0;e:for(let m of o){let R=c.get(m,tB);for(let w=0;w<u;w++)if(!_[w](R))continue e;if(d>0){d--;continue}if(h<=0)break;h--,l.push(WP.parseRow(R,E))}return l}else{let o=[],c=[];for(let _ of i){let[u]=await NT(s,e,_,n.hash_attribute);c.push(u)}if(o=OT.union(...c),e.limit>0||e.offset>0){let _=Number.isInteger(e.limit)?e.limit:o.length;o=o.splice(e.offset,_)}return Ju.batchSearchByHash(s,n.hash_attribute,e.get_attributes,o)}}catch(t){throw pT(t)}}a(rB,"lmdbSearchByConditions");async function NT(e,t,r,s){let n=new KP(t.schema,t.table,void 0,void 0,s,t.get_attributes),i=r.search_type;return n.search_attribute=r.search_attribute,i===Ro.SEARCH_TYPES.BETWEEN?(n.search_value=r.search_value[0],n.end_value=r.search_value[1]):n.search_value=r.search_value,gT.searchByType(e,n,i,s)}a(NT,"executeConditionSearch")});var li=S((dZ,CT)=>{"use strict";var sB=T().OPERATIONS_ENUM,Ao=class{constructor(t,r,s,n=void 0){this.operation=sB.DELETE,this.schema=t,this.table=r,this.hash_values=s,this.__origin=n}};a(Ao,"DeleteObject");CT.exports=Ao});var Zu=S((hZ,wT)=>{"use strict";var Oo=class{constructor(t,r,s){this.schema=t,this.table=r,this.attribute=s}};a(Oo,"DropAttributeObject");wT.exports=Oo});var zu=S((fZ,LT)=>{"use strict";var nB=Kt(),iB=li(),SZ=Zu(),er=T(),aB=b(),Xu=Z(),oB=is(),cB=on(),_B=ai(),{getBaseSchemaPath:uB}=te(),lB=require("path");LT.exports=EB;async function EB(e,t=!0){let r;e.schema===er.SYSTEM_SCHEMA_NAME?r=oB[e.table]:r=global.hdb_schema[e.schema][e.table];let s=await hB(e),n=lB.join(uB(),e.schema.toString()),i=await Xu.openEnvironment(n,e.table);return t===!0&&await dB(e,i,r.hash_attribute),Xu.dropDBI(i,e.attribute),s}a(EB,"lmdbDropAttribute");async function dB(e,t,r){let s=Xu.openDBI(t,r),n,i=e.attribute;for(let{key:o,value:c,version:_}of s.getRange({start:!1,versions:!0})){let u={};for(let l in c)l!==i&&(u[l]=c[l]);n=t.dbis[r].put(o,u,_)}await n}a(dB,"removeAttributeFromAllObjects");async function hB(e){let t=new nB(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,er.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ATTRIBUTE_KEY]),s=(await cB(t)).filter(o=>o[er.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ATTRIBUTE_KEY]===e.attribute);if(aB.isEmptyOrZeroLength(s))throw new Error(`Attribute '${e.attribute}' was not found in '${e.schema}.${e.table}'`);let n=s.map(o=>o[er.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),i=new iB(er.SYSTEM_SCHEMA_NAME,er.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,n);return _B(i)}a(hB,"dropAttributeFromSystem")});var MT=S((TZ,DT)=>{"use strict";var SB=zu(),fB=Zu(),UT=b(),yT=I(),TB=Ke().LMDB_ERRORS_ENUM;DT.exports=mB;async function mB(e){if(UT.isEmpty(global.hdb_schema[e.schema])||UT.isEmpty(global.hdb_schema[e.schema][e.table]))throw new Error(`unknown schema:${e.schema} and table ${e.table}`);let t=global.hdb_schema[e.schema][e.table],r;try{for(let s=0;s<t.attributes.length;s++){r=t.attributes[s].attribute;let n=new fB(e.schema,e.table,r);try{await SB(n,!1)}catch(i){i.message!==TB.DBI_DOES_NOT_EXIST&&yT.error(`unable to drop attribute ${e.schema}.${e.table}.${r}:`+i)}}}catch(s){throw yT.error(`Error dropping attribute ${r}`),s}}a(mB,"lmdbDropAllAttributes")});var ju=S((RZ,kT)=>{"use strict";var GT=Kt(),qT=li(),FT=on(),VT=ai(),mZ=MT(),at=T(),PT=b(),BT=Z(),{getBaseSchemaPath:RB,getTransactionAuditStorePath:AB}=te(),vT=require("path"),HT=I();kT.exports=OB;async function OB(e){try{if(PT.isEmpty(global.hdb_schema[e.schema])||PT.isEmpty(global.hdb_schema[e.schema][e.table]))throw new Error(`unknown schema:${e.schema} and table ${e.table}`);await pB(e),await NB(e);let t=vT.join(RB(),e.schema.toString());try{await BT.deleteEnvironment(t,e.table)}catch(r){if(r.message==="invalid environment")HT.warn(`cannot delete environment for ${e.schema}.${e.table}, environment not found`);else throw r}try{let r=vT.join(AB(),e.schema.toString());await BT.deleteEnvironment(r,e.table,!0)}catch(r){if(r.message==="invalid environment")HT.warn(`cannot delete environment for ${e.schema}.${e.table}, environment not found`);else throw r}}catch(t){throw t}}a(OB,"lmdbDropTable");async function pB(e){let t=new GT(at.SYSTEM_SCHEMA_NAME,at.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,at.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_TABLE_KEY,`${e.schema}.${e.table}`,void 0,[at.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),r=await FT(t),s=[];for(let i=0;i<r.length;i++){let o=r[i];s.push(o.id)}if(s.length===0)return;let n=new qT(at.SYSTEM_SCHEMA_NAME,at.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,s);await VT(n)}a(pB,"deleteAttributesFromSystem");async function NB(e){let t=new GT(at.SYSTEM_SCHEMA_NAME,at.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,at.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY,e.table,void 0,[at.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY,at.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_KEY,at.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),r,s;try{r=await FT(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&&(s=o)}if(!s)throw new Error(`${e.schema}.${e.table} was not found`);let n=new qT(at.SYSTEM_SCHEMA_NAME,at.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,[s.id]);try{await VT(n)}catch(i){throw i}}a(NB,"dropTableFromSystem")});var $T=S((OZ,xT)=>{"use strict";var gB=require("fs-extra"),IB=Kt(),bB=ds(),CB=li(),wB=ju(),LB=ai(),UB=Wu(),yB=on(),Ar=T(),AZ=b(),DB=require("path"),{getBaseSchemaPath:MB}=te(),{handleHDBError:PB,hdb_errors:BB}=D(),{HDB_ERROR_MSGS:vB,HTTP_STATUS_CODES:HB}=BB;xT.exports=GB;async function GB(e){let t;try{t=await qB(e.schema);let r=new IB(Ar.SYSTEM_SCHEMA_NAME,Ar.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,Ar.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_KEY,t,void 0,[Ar.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY]),s=await yB(r);for(let o=0;o<s.length;o++){let c={schema:t,table:s[o].name};try{await wB(c)}catch(_){if(_.message!=="invalid environment")throw _}}let n=new CB(Ar.SYSTEM_SCHEMA_NAME,Ar.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,[t]);await LB(n);let i=DB.join(MB(),t.toString());await gB.remove(i)}catch(r){throw r}}a(GB,"lmdbDropSchema");async function qB(e){let t=new bB(Ar.SYSTEM_SCHEMA_NAME,Ar.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,[e],[Ar.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY]),r,s;try{r=await UB(t)}catch(n){throw n}for(let n in r)r[n].name===e&&(s=e);if(!s)throw PB(new Error,vB.SCHEMA_NOT_FOUND(e),HB.NOT_FOUND,void 0,void 0,!0);return s}a(qB,"validateDropSchema")});var el=S((pZ,YT)=>{"use strict";var po=class{constructor(t,r,s){this.schema=t,this.table=r,this.hash_attribute=s}};a(po,"CreateTableObject");YT.exports=po});var QT=S((gZ,KT)=>{"use strict";var FB=require("path"),VB=require("fs-extra"),No=Z(),{getTransactionAuditStorePath:kB}=te(),tl=Ye(),NZ=el();KT.exports=xB;async function xB(e){let t;try{let r=FB.join(kB(),e.schema.toString());await VB.mkdirp(r),t=await No.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{No.createDBI(t,tl.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,!1,!0),No.createDBI(t,tl.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE,!0,!1),No.createDBI(t,tl.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(xB,"createTransactionsAuditEnvironment")});var XT=S((IZ,ZT)=>{"use strict";var rl=T(),WT=Z(),$B=Xs(),YB=require("path"),{getSystemSchemaPath:KB,getBaseSchemaPath:QB}=te(),WB=is(),JB=Za(),sl=Ja(),ZB=I(),XB=QT(),il=WB.hdb_table,JT=[];for(let e=0;e<il.attributes.length;e++)JT.push(il.attributes[e].attribute);ZT.exports=zB;async function zB(e,t){let r=YB.join(QB(),t.schema.toString()),s=new sl(t.schema,t.table,rl.TIME_STAMP_NAMES_ENUM.CREATED_TIME,void 0,!0),n=new sl(t.schema,t.table,rl.TIME_STAMP_NAMES_ENUM.UPDATED_TIME,void 0,!0),i=new sl(t.schema,t.table,t.hash_attribute,void 0,!1,!0);try{if(await WT.createEnvironment(r,t.table),e!==void 0){let o=await WT.openEnvironment(KB(),rl.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME);await $B.insertRecords(o,il.hash_attribute,JT,[e]),await nl(s),await nl(n),await nl(i)}await XB(t)}catch(o){throw o}}a(zB,"lmdbCreateTable");async function nl(e){try{await JB(e)}catch(t){ZB.warn(`failed to create attribute ${e.attribute} due to ${t.message}`)}}a(nl,"createAttribute")});var jT=S((bZ,zT)=>{"use strict";var jB=Xa(),ev=eo(),tv=so(),cn=T(),rv=Xs().updateRecords,sv=Z(),nv=require("path"),{getBaseSchemaPath:iv}=te(),av=ii(),ov=I();zT.exports=cv;async function cv(e){try{let{schema_table:t,attributes:r}=jB(e);ev(e,r,t.hash_attribute),e.schema!==cn.SYSTEM_SCHEMA_NAME&&(r.includes(cn.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||r.push(cn.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.includes(cn.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||r.push(cn.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let s=await tv(e.hdb_auth_header,t,r),n=nv.join(iv(),e.schema.toString()),i=await sv.openEnvironment(n,e.table),o=await rv(i,t.hash_attribute,r,e.records,e[cn.CLUSTERING_FLAG]!==!0);try{await av(e,o)}catch(c){ov.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:s,txn_time:o.txn_time}}catch(t){throw t}}a(cv,"lmdbUpdateRecords")});var tm=S((CZ,em)=>{"use strict";var _v=T().OPERATIONS_ENUM,go=class{constructor(t,r,s,n=void 0){this.operation=_v.UPSERT,this.schema=t,this.table=r,this.records=s,this.__origin=n}};a(go,"UpsertObject");em.exports=go});var sm=S((LZ,rm)=>{"use strict";var wZ=tm(),uv=Xa(),lv=eo(),Ev=so(),_n=T(),dv=Xs().upsertRecords,hv=Z(),Sv=require("path"),{getBaseSchemaPath:fv}=te(),Tv=ii(),mv=I(),{handleHDBError:Rv,hdb_errors:Av}=D();rm.exports=Ov;async function Ov(e){let t;try{t=uv(e)}catch(_){throw Rv(_,_.message,Av.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0)}let{schema_table:r,attributes:s}=t;lv(e,s,r.hash_attribute),e.schema!==_n.SYSTEM_SCHEMA_NAME&&(s.includes(_n.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||s.push(_n.TIME_STAMP_NAMES_ENUM.CREATED_TIME),s.includes(_n.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||s.push(_n.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let n=await Ev(e.hdb_auth_header,r,s),i=Sv.join(fv(),e.schema.toString()),o=await hv.openEnvironment(i,e.table),c=await dv(o,r.hash_attribute,s,e.records,e[_n.CLUSTERING_FLAG]!==!0);try{await Tv(e,c)}catch(_){mv.error(`unable to write transaction due to ${_.message}`)}return{written_hashes:c.written_hashes,schema_table:r,new_attributes:n,txn_time:c.txn_time}}a(Ov,"lmdbUpsertRecords")});var _m=S((UZ,cm)=>{"use strict";var pv=Kt(),nm=b(),im=I(),Nv=on(),am=T(),gv=xu().deleteRecords,Iv=Z(),bv=require("path"),{getBaseSchemaPath:Cv}=te(),{promisify:wv}=require("util"),Lv=wv(setTimeout),om=1e4,Uv=10;cm.exports=yv;async function yv(e){let t=global.hdb_schema[e.schema][e.table].hash_attribute;if(nm.isEmptyOrZeroLength(t))throw new Error(`Could not retrieve hash attribute for schema: ${e.schema} table: ${e.table}`);let r=Date.parse(e.date),s;try{let n=new pv(e.schema,e.table,am.TIME_STAMP_NAMES_ENUM.CREATED_TIME,r,void 0,[t]);s=await Nv(n,am.VALUE_SEARCH_COMPARATORS.LESS)}catch(n){throw im.error(`Error searching for date: ${e.date} in schema: ${e.schema} table: ${e.table}`),n}return nm.isEmptyOrZeroLength(s)?(im.trace("No records found to delete"),{message:"No records found to delete"}):await Dv(e,s,t)}a(yv,"lmdbDeleteRecordsBefore");async function Dv(e,t,r){let s=bv.join(Cv(),e.schema.toString()),n=await Iv.openEnvironment(s,e.table),i={message:"",deleted_hashes:[],skipped_hashes:[]};for(let o=0,c=t.length;o<c;o+=om){let _=t.slice(o,o+om),u=[];for(let l=0,E=_.length;l<E;l++)u.push(_[l][r]);try{let l=await gv(n,r,u);i.deleted_hashes=i.deleted_hashes.concat(l.deleted),i.skipped_hashes=i.skipped_hashes.concat(l.skipped)}catch(l){throw l}await Lv(Uv)}return i.message=`${i.deleted_hashes.length} of ${i.deleted_hashes.length+i.skipped_hashes.length} records successfully deleted`,i}a(Dv,"chunkDeletes")});var lm=S((yZ,um)=>{"use strict";var Io=class{constructor(t,r,s){this.schema=t,this.table=r,this.timestamp=s}};a(Io,"DeleteBeforeObject");um.exports=Io});var dm=S((DZ,Em)=>{"use strict";var bo=class{constructor(t=void 0,r=void 0,s=0){this.start_timestamp=t,this.end_timestamp=r,this.transactions_deleted=s}};a(bo,"DeleteAuditLogsBeforeResults");Em.exports=bo});var fm=S((PZ,Sm)=>{"use strict";var al=Z(),{getTransactionAuditStorePath:Mv}=te(),MZ=lm(),Pv=require("path"),Ei=Ye(),Bv=b(),hm=dm(),vv=require("util").promisify,Hv=vv(setTimeout),Gv=1e4,qv=100;Sm.exports=Fv;async function Fv(e){let t=Pv.join(Mv(),e.schema),r=await al.openEnvironment(t,e.table,!0),s=al.listDBIs(r);al.initializeDBIs(r,Ei.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,s);let n,i=new hm;do n=await Vv(r,e.timestamp),i.start_timestamp===void 0&&(i.start_timestamp=n.start_timestamp),n.end_timestamp!==void 0&&(i.end_timestamp=n.end_timestamp),i.transactions_deleted+=n.transactions_deleted,await Hv(qv);while(n.transactions_deleted>0);return i}a(Fv,"deleteAuditLogsBefore");async function Vv(e,t){let r=new hm;try{let s=e.dbis[Ei.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP],n;for(let{key:i,value:o}of s.getRange({start:!1})){if(i>=t)break;r.start_timestamp===void 0&&(r.start_timestamp=i),n=s.remove(i);let c=o[Ei.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME];Bv.isEmpty(c)||(n=e.dbis[Ei.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].remove(c,i));for(let _=0;_<o.hash_values.length;_++)n=e.dbis[Ei.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE].remove(o.hash_values[_],i);if(r.transactions_deleted++,r.end_timestamp=i,r.transactions_deleted>Gv)break}return await n,r}catch(s){throw s}}a(Vv,"deleteTransactions")});var Nm=S((BZ,pm)=>{"use strict";var ol=Z(),un=Ye(),Tm=_s(),cl=T(),mm=b(),{getTransactionAuditStorePath:kv}=te(),xv=require("path"),$v=nn(),Co=en(),Yv=I();pm.exports=Kv;async function Kv(e){let t=xv.join(kv(),e.schema),r=await ol.openEnvironment(t,e.table,!0),s=ol.listDBIs(r);ol.initializeDBIs(r,un.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,s);let n;switch(e.search_type){case cl.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.TIMESTAMP:return Rm(r,e.search_values);case cl.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.HASH_VALUE:return n=global.hdb_schema[e.schema][e.table].hash_attribute,Wv(r,e.search_values,n);case cl.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.USERNAME:return Qv(r,e.search_values);default:return Rm(r)}}a(Kv,"readAuditLog");function Rm(e,t=[0,Tm.getMicroTime()]){mm.isEmpty(t[0])&&(t[0]=0),mm.isEmpty(t[1])&&(t[1]=Tm.getMicroTime());let r=[];try{let s=e.dbis[un.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP],n;for(let i of s.getKeys({start:t[1]}))if(i!==t[1]){n=i;break}for(let{value:i}of s.getRange({start:t[0],end:n})){let o=Object.assign(new Co,i);r.push(o)}return r}catch(s){throw s}}a(Rm,"searchTransactionsByTimestamp");function Qv(e,t=[]){let r=new Map;for(let s=0;s<t.length;s++){let n=t[s],i=[];for(let o of e.dbis[un.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].getValues(n))i.push(o);r.set(n,Om(e,i))}return Object.fromEntries(r)}a(Qv,"searchTransactionsByUsername");function Wv(e,t,r){let s=new Map;for(let c=0,_=t.length;c<_;c++){let u=t[c],l=$v.equals(e,un.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,un.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE,u);for(let E=0,d=l[0].length;E<d;E++){let h=l[0][E],m=Number(h);s.has(m)?s.get(m).push(u.toString()):s.set(m,[u.toString()])}}let n=Array.from(s.keys()),i=Om(e,n),o=new Map;for(let c=0;c<i.length;c++){let _=i[c],u=_.timestamp,l=s.get(u);Am(_,"records",r,l,o),Am(_,"original_records",r,l,o)}return Object.fromEntries(o)}a(Wv,"searchTransactionsByHashValues");function Am(e,t,r,s,n){let i=e.timestamp;if(e[t])for(let o=0;o<e[t].length;o++){let c=e[t][o],_=c[r].toString();if(s.indexOf(_)>=0)if(n.has(_)){let u=n.get(_),l=u[u.length-1];if(l.timestamp===i)l[t]=[c];else{let E=new Co(e.operation,e.user_name,i,void 0);E[t]=[c],u.push(E)}}else{let u=new Co(e.operation,e.user_name,i,void 0);u[t]=[c],n.set(_,[u])}}}a(Am,"loopRecords");function Om(e,t){let r=[];try{let s=e.dbis[un.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP];for(let n=0;n<t.length;n++)try{let i=s.get(t[n]);if(i){let o=Object.assign(new Co,i);r.push(o)}}catch(i){Yv.warn(i)}return r}catch(s){throw s}}a(Om,"batchSearchTransactions")});var Im=S((vZ,gm)=>{"use strict";var Jv=require("path"),{getBaseSchemaPath:Zv}=te(),Xv=Z();gm.exports={writeTransaction:zv};async function zv(e,t,r){let s=Jv.join(Zv(),e);return(await Xv.openEnvironment(s,t)).transaction(r)}a(zv,"writeTransaction")});var Cm=S((HZ,bm)=>{"use strict";var jv=require("path"),{getBaseSchemaPath:eH}=te(),tH=Z();bm.exports={flush:rH};async function rH(e,t){let r=jv.join(eH(),e.toString());return(await tH.openEnvironment(r,t.toString())).flushed}a(rH,"flush")});var Lm=S((GZ,wm)=>{"use strict";var Re=I(),{handleHDBError:sH}=D(),nH=Eu(),iH=Za(),aH=Fu(),oH=Ff(),cH=ai(),_H=Wu(),uH=_T(),lH=TT(),EH=on(),dH=bT(),hH=$T(),SH=XT(),fH=jT(),TH=sm(),mH=_m(),RH=fm(),AH=ju(),OH=zu(),pH=Nm(),NH=Im(),gH=Cm(),wo=class extends nH{async searchByConditions(t){try{return dH(t)}catch(r){throw Re.error(r),r}}async getDataByHash(t){try{return await _H(t)}catch(r){throw Re.error(r),r}}async searchByHash(t){try{return await uH(t)}catch(r){throw Re.error(r),r}}async getDataByValue(t,r){try{return await lH(t,r)}catch(s){throw Re.error(s),s}}async searchByValue(t){try{return await EH(t)}catch(r){throw Re.error(r),r}}async createSchema(t){try{return await oH(t)}catch(r){throw Re.error(r),r}}async dropSchema(t){try{return await hH(t)}catch(r){throw Re.error(r),r}}async createTable(t,r){try{return await SH(t,r)}catch(s){throw Re.error(s),s}}async dropTable(t){try{return await AH(t)}catch(r){throw Re.error(r),r}}async createAttribute(t){try{return await iH(t)}catch(r){throw Re.error(r),r}}async createRecords(t){try{return await aH(t)}catch(r){throw Re.error(r),r}}async updateRecords(t){try{return await fH(t)}catch(r){throw Re.error(r),r}}async upsertRecords(t){try{return await TH(t)}catch(r){throw sH(r,null,null,Re.ERR,r)}}async deleteRecords(t){try{return await cH(t)}catch(r){throw Re.error(r),r}}async deleteRecordsBefore(t){try{return await mH(t)}catch(r){throw Re.error(r),r}}async dropAttribute(t){try{return await OH(t)}catch(r){throw Re.error(r),r}}async deleteAuditLogsBefore(t){try{return await RH(t)}catch(r){throw Re.error(r),r}}async readAuditLog(t){try{return await pH(t)}catch(r){throw Re.error(r),r}}writeTransaction(t,r,s){return NH.writeTransaction(t,r,s)}flush(t,r){return gH.flush(t,r)}};a(wo,"LMDBBridge");wm.exports=wo});var Or=S((qZ,ym)=>{"use strict";var IH=Lm(),bH=Eu(),CH=Y();CH.initSync();var Um;function wH(){return Um instanceof bH?Um:new IH}a(wH,"getBridge");ym.exports=wH()});var Bm=S((FZ,Pm)=>{"use strict";var Dm=require("lodash"),di=require("mathjs"),LH=require("jsonata"),Mm=b();Pm.exports={distinct_array:e=>Array.isArray(e)&&e.length>1?Dm.uniqWith(e,Dm.isEqual):e,searchJSON:UH,mad:hi.bind(null,di.mad),mean:hi.bind(null,di.mean),mode:hi.bind(null,di.mode),prod:hi.bind(null,di.prod),median:hi.bind(null,di.median)};function hi(e,t,r,s){return s===1?t==null?[]:[t]:s===2?(t!=null&&r.push(t),r):r!=null&&r.length>0?e(r):null}a(hi,"aggregateFunction");function UH(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(Mm.isEmpty(this.__ala__.res)&&(this.__ala__.res={}),Mm.isEmpty(this.__ala__.res[r])){let s=LH(e);this.__ala__.res[r]=s}return this.__ala__.res[r].evaluate(t)}a(UH,"searchJSON")});var Hm=S((VZ,vm)=>{"use strict";var he=require("moment"),_l="YYYY-MM-DDTHH:mm:ss.SSSZZ";he.suppressDeprecationWarnings=!0;vm.exports={current_date:()=>he().utc().format("YYYY-MM-DD"),current_time:()=>he().utc().format("HH:mm:ss.SSS"),extract:(e,t)=>{switch(t.toLowerCase()){case"year":return he(e).utc().format("YYYY");case"month":return he(e).utc().format("MM");case"day":return he(e).utc().format("DD");case"hour":return he(e).utc().format("HH");case"minute":return he(e).utc().format("mm");case"second":return he(e).utc().format("ss");case"millisecond":return he(e).utc().format("SSS");default:break}},date:e=>he(e).utc().format(_l),date_format:(e,t)=>he(e).utc().format(t),date_add:(e,t,r)=>he(e).utc().add(t,r).valueOf(),date_sub:(e,t,r)=>he(e).utc().subtract(t,r).valueOf(),date_diff:(e,t,r)=>{let s=he(e).utc(),n=he(t).utc();return r?s.diff(n,r,!0):s.diff(n)},now:()=>he().utc().valueOf(),get_server_time:()=>he().format(_l),offset_utc:(e,t)=>he(e).utc().utcOffset(t).format(_l)}});var Vm=S((kZ,Fm)=>{"use strict";var yH=require("@turf/area"),DH=require("@turf/length"),MH=require("@turf/circle"),PH=require("@turf/difference"),BH=require("@turf/distance"),vH=require("@turf/boolean-contains"),HH=require("@turf/boolean-equal"),GH=require("@turf/boolean-disjoint"),qH=require("@turf/helpers"),Gm=T(),k=b();Fm.exports={geoArea:FH,geoLength:VH,geoCircle:kH,geoDifference:xH,geoDistance:qm,geoNear:$H,geoContains:YH,geoEqual:KH,geoCrosses:QH,geoConvert:WH};var ul="geo1 is required",ll="geo2 is required";function FH(e){if(k.isEmpty(e))throw new Error("geoJSON is required");return typeof e=="string"&&(e=k.autoCast(e)),yH.default(e)}a(FH,"geoArea");function VH(e,t){if(k.isEmpty(e))throw new Error("geoJSON is required");return typeof e=="string"&&(e=k.autoCast(e)),DH.default(e,{units:t||"kilometers"})}a(VH,"geoLength");function kH(e,t,r){if(k.isEmpty(e))throw new Error("point is required");if(k.isEmpty(t))throw new Error("radius is required");return typeof e=="string"&&(e=k.autoCast(e)),MH.default(e,t,{units:r||"kilometers"})}a(kH,"geoCircle");function xH(e,t){if(k.isEmpty(e))throw new Error("poly1 is required");if(k.isEmpty(t))throw new Error("poly2 is required");return typeof e=="string"&&(e=k.autoCast(e)),typeof t=="string"&&(t=k.autoCast(t)),PH(e,t)}a(xH,"geoDifference");function qm(e,t,r){if(k.isEmpty(e))throw new Error("point1 is required");if(k.isEmpty(t))throw new Error("point2 is required");return typeof e=="string"&&(e=k.autoCast(e)),typeof t=="string"&&(t=k.autoCast(t)),BH.default(e,t,{units:r||"kilometers"})}a(qm,"geoDistance");function $H(e,t,r,s){if(k.isEmpty(e))throw new Error("point1 is required");if(k.isEmpty(t))throw new Error("point2 is required");if(k.isEmpty(r))throw new Error("distance is required");if(typeof e=="string"&&(e=k.autoCast(e)),typeof t=="string"&&(t=k.autoCast(t)),isNaN(r))throw new Error("distance must be a number");return qm(e,t,s)<=r}a($H,"geoNear");function YH(e,t){if(k.isEmpty(e))throw new Error(ul);if(k.isEmpty(e))throw new Error(ll);return typeof e=="string"&&(e=k.autoCast(e)),typeof t=="string"&&(t=k.autoCast(t)),vH.default(e,t)}a(YH,"geoContains");function KH(e,t){if(k.isEmpty(e))throw new Error(ul);if(k.isEmpty(e))throw new Error(ll);return typeof e=="string"&&(e=k.autoCast(e)),typeof t=="string"&&(t=k.autoCast(t)),HH.default(e,t)}a(KH,"geoEqual");function QH(e,t){if(k.isEmpty(e))throw new Error(ul);if(k.isEmpty(e))throw new Error(ll);return typeof e=="string"&&(e=k.autoCast(e)),typeof t=="string"&&(t=k.autoCast(t)),!GH.default(e,t)}a(QH,"geoCrosses");function WH(e,t,r){if(k.isEmptyOrZeroLength(e))throw new Error("coordinates is required");if(k.isEmpty(t))throw new Error("geo_type is required");if(k.isEmpty(Gm.GEO_CONVERSION_ENUM[t]))throw new Error(`geo_type of ${t} is invalid please use one of the following types: ${Object.keys(Gm.GEO_CONVERSION_ENUM).join(",")}`);return qH[t](e,r)}a(WH,"geoConvert")});var Lo=S((xZ,km)=>{var Ss=Bm(),Tt=Hm(),tr=Vm();km.exports=e=>{e.aggr.mad=e.aggr.MAD=Ss.mad,e.aggr.mean=e.aggr.MEAN=Ss.mean,e.aggr.mode=e.aggr.MODE=Ss.mode,e.aggr.prod=e.aggr.PROD=Ss.prod,e.aggr.median=e.aggr.MEDIAN=Ss.median,e.fn.distinct_array=e.fn.DISTINCT_ARRAY=Ss.distinct_array,e.fn.search_json=e.fn.SEARCH_JSON=Ss.searchJSON,e.fn.__ala__=e,e.fn.current_date=e.fn.CURRENT_DATE=Tt.current_date,e.fn.current_time=e.fn.CURRENT_TIME=Tt.current_time,e.fn.extract=e.fn.EXTRACT=Tt.extract,e.fn.date=e.fn.DATE=Tt.date,e.fn.date_format=e.fn.DATE_FORMAT=Tt.date_format,e.fn.date_add=e.fn.DATE_ADD=Tt.date_add,e.fn.date_sub=e.fn.DATE_SUB=Tt.date_sub,e.fn.date_diff=e.fn.DATE_DIFF=e.fn.datediff=e.fn.DATEDIFF=Tt.date_diff,e.fn.now=e.fn.NOW=Tt.now,e.fn.offset_utc=e.fn.OFFSET_UTC=Tt.offset_utc,e.fn.get_server_time=e.fn.GET_SERVER_TIME=Tt.get_server_time,e.fn.getdate=e.fn.GETDATE=Tt.now,e.fn.current_timestamp=e.fn.CURRENT_TIMESTAMP=Tt.now,e.fn.geoarea=e.fn.GEOAREA=e.fn.geoArea=tr.geoArea,e.fn.geocircle=e.fn.GEOCIRCLE=e.fn.geoCircle=tr.geoCircle,e.fn.geocontains=e.fn.GEOCONTAINS=e.fn.geoContains=tr.geoContains,e.fn.geoconvert=e.fn.GEOCONVERT=e.fn.geoConvert=tr.geoConvert,e.fn.geocrosses=e.fn.GEOCROSSES=e.fn.geoCrosses=tr.geoCrosses,e.fn.geodifference=e.fn.GEODIFFERENCE=e.fn.geoDifference=tr.geoDifference,e.fn.geodistance=e.fn.GEODISTANCE=e.fn.geoDistance=tr.geoDistance,e.fn.geoequal=e.fn.GEOEQUAL=e.fn.geoEqual=tr.geoEqual,e.fn.geolength=e.fn.GEOLENGTH=e.fn.geoLength=tr.geoLength,e.fn.geonear=e.fn.GEONEAR=e.fn.geoNear=tr.geoNear}});var Ym=S(($Z,$m)=>{"use strict";var Si=require("lodash"),Me=require("alasql");Me.options.cache=!1;var JH=Lo(),xm=require("clone"),Uo=require("recursive-iterator"),v=I(),G=b(),ln=Or(),ZH=T(),{hdb_errors:XH}=D(),zH="IS NULL",fi="There was a problem performing this search. Please check the logs and try again.";JH(Me);var yo=class{constructor(t,r){if(G.isEmpty(t))throw v.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(),G.backtickASTSchemaItems(this.statement)}async search(){let t;try{let s=await this._checkEmptySQL();if(!G.isEmptyOrZeroLength(s))return v.trace("No results returned from checkEmptySQL SQLSearch method."),s}catch(s){throw v.error("Error thrown from checkEmptySQL in SQLSearch class method search."),v.error(s),new Error(fi)}try{let s=await this._getFetchAttributeValues();if(s)return s}catch(s){throw v.error("Error thrown from getFetchAttributeValues in SQLSearch class method search."),v.error(s),new Error(fi)}if(Object.keys(this.data).length===0)return v.trace('SQLSearch class field: "data" is empty.'),[];let r;try{r=await this._processJoins()}catch(s){throw v.error("Error thrown from processJoins in SQLSearch class method search."),v.error(s),new Error(fi)}try{await this._getFinalAttributeData(r.existing_attributes,r.joined_length)}catch(s){throw v.error("Error thrown from getFinalAttributeData in SQLSearch class method search."),v.error(s),new Error(fi)}try{return t=await this._finalSQL(),t}catch(s){throw v.error("Error thrown from finalSQL in SQLSearch class method search."),v.error(s),new Error(fi)}}_getColumns(){let t=new Uo(this.statement);for(let{node:r,path:s}of t)r&&r.columnid&&(this.columns[s[0]]||(this.columns[s[0]]=[]),this.columns[s[0]].push(xm(r)))}_getTables(){let t=[];this.all_table_attributes.forEach(r=>{t.push(r.table)}),this.tables=Si.uniqBy(t,r=>[r.databaseid,r.tableid,r.as].join()),this.tables.forEach(r=>{let s=`${r.databaseid}_${r.as?r.as:r.tableid}`;this.data[s]={},this.data[s].__hash_name=global.hdb_schema[r.databaseid][r.tableid].hash_attribute,this.data[s].__merged_data={},this.data[s].__merged_attributes=[],this.data[s].__merged_attr_map={}})}_conditionsToFetchAttributeValues(){if(G.isEmpty(this.statement.where)){v.trace('AST "where" statement is empty.');return}let t=!1;for(let{node:r}of new Uo(this.statement.where))if(r&&r.op&&r.op==="OR"&&(t=!0),!G.isEmpty(r)&&r.right)if(G.isNotEmptyAndHasValue(r.right.value)){let s=G.autoCast(r.right.value);[!0,!1].indexOf(s)>=0?r.right=new Me.yy.LogicValue({value:s}):r.right instanceof Me.yy.StringValue&&!G.isEmpty(s)&&G.autoCasterIsNumberCheck(s.toString())&&(r.right=new Me.yy.NumValue({value:s}))}else Array.isArray(r.right)&&r.right.forEach((s,n)=>{let i=G.autoCast(s.value);[!0,!1].indexOf(i)>=0?r.right[n]=new Me.yy.LogicValue({value:i}):s instanceof Me.yy.StringValue&&G.autoCasterIsNumberCheck(i.toString())&&(r.right[n]=new Me.yy.NumValue({value:i}))});if(t){v.trace('Where clause contains "OR", exact match search not performed on attributes.');return}for(let{node:r}of new Uo(this.statement.where))if(r&&r.left&&r.right&&(r.left.columnid||r.right.value)&&r.op){let s=new Set,n=r.left.columnid?r.left:r.right,i=this._findColumn(n);if(!i)continue;let o=[i.table.databaseid,i.table.tableid,i.attribute].join("/");if(!G.isEmpty(ZH.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[r.op])){if(G.isEmpty(this.comparator_search_values[o])&&(this.comparator_search_values[o]={ignore:!1,comparators:[]}),!this.comparator_search_values[o].ignore){if(G.isEmptyOrZeroLength(r.left.columnid)||G.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(G.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"=":!G.isEmpty(r.right.value)||!G.isEmpty(r.left.value)?s.add(G.isEmpty(r.right.value)?r.left.value:r.right.value):c=!0;break;case"IN":let _=Array.isArray(r.right)?r.right:r.left;for(let u=0;u<_.length;u++)if(_[u].value)s.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,...s])}}}_setAliasesForColumns(){if(G.isEmptyOrZeroLength(this.all_table_attributes)&&G.isEmptyOrZeroLength(this.statement.from)&&G.isEmptyOrZeroLength(this.columns.columns))return;let t=[],r={};this.statement.columns.forEach((s,n)=>{if(s.columnid==="*"){t.push(n);return}if(s.aggregatorid&&(this.has_aggregator=!0),!s.aggregatorid&&!s.funcid)if(s.as_orig=s.as?s.as:s.columnid,this.statement.joins)if(r[s.as_orig]>=0){let i=r[s.as_orig]+1;s.as=`[${s.as_orig+i}]`,r[s.as_orig]=i}else s.as=`[${s.as_orig}]`,r[s.as_orig]=0;else s.as=`[${s.as_orig}]`;!s.aggregatorid&&s.funcid&&s.args&&(s.as_orig=s.as?s.as:s.toString().replace(/'/g,'"'),s.as=`[${s.as_orig}]`),s.aggregatorid&&s.expression.columnid!=="*"&&(s.as_orig=s.as?s.as:s.expression.tableid?`${s.aggregatorid}(${s.expression.tableid}.${s.expression.columnid})`:`${s.aggregatorid}(${s.expression.columnid})`,s.as=`[${s.as_orig}]`)}),this.statement.columns.length>1&&t.length>0&&Si.pullAt(this.statement.columns,t)}_findColumn(t){let r=this.all_table_attributes.filter(s=>{if(t.columnid_orig&&t.tableid_orig)return(s.table.as===t.tableid_orig||s.table.tableid===t.tableid_orig)&&s.attribute===t.columnid_orig;if(t.tableid)return(s.table.as===t.tableid||s.table.tableid===t.tableid)&&s.attribute===t.columnid;let n=t.columnid_orig?t.columnid_orig:t.columnid;return s.attribute===n});if(G.isEmptyOrZeroLength(r)){let s=this.columns.columns.filter(n=>n.as?t.columnid===n.as:!1);G.isEmptyOrZeroLength(s)||(r=this.all_table_attributes.filter(n=>n.attribute===s[0].columnid&&s[0].tableid&&s[0].tableid===(n.table.as?n.table.as:n.table.tableid)))}return r[0]}async _checkEmptySQL(){let t=[];if(G.isEmptyOrZeroLength(this.all_table_attributes)&&!G.isEmptyOrZeroLength(this.columns.columns))return t;if(G.isEmptyOrZeroLength(this.all_table_attributes)&&G.isEmptyOrZeroLength(this.statement.from))try{let r=this._buildSQL(!1);t=await Me.promise(r)}catch(r){throw v.error("Error thrown from AlaSQL in SQLSearch class method checkEmptySQL."),v.error(r),new Error("There was a problem with the SQL statement")}return t}_addFetchColumns(t){t&&t.length>0&&t.forEach(r=>{let s=this._findColumn(r);s&&this.fetch_attributes.push(xm(s))})}_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,s,n){let i=this.data[t].__merged_attr_map[s];this.data[t].__merged_data[r].splice(i,1,n)}async _getFetchAttributeValues(){if(G.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(zH)>-1&&this.tables.forEach(n=>{let i={columnid:global.hdb_schema[n.databaseid][n.tableid].hash_attribute,tableid:n.tableid};this._addFetchColumns([i])}),this.statement.order&&(this._updateOrderByToAliases(),this._addNonAggregatorsToFetchColumns()),this.fetch_attributes=Si.uniqBy(this.fetch_attributes,n=>[n.table.databaseid,n.table.as?n.table.as:n.table.tableid,n.attribute].join()),r)return await this._simpleSQLQuery();let s=this.fetch_attributes.reduce((n,i)=>{let o=`${i.table.databaseid}_${i.table.as?i.table.as:i.table.tableid}`,c=this.data[o].__hash_name;return n[o]||(n[o]=[],n[o].push(null),this._addColumnToMergedAttributes(o,c)),i.attribute!==c&&(n[o].push(null),this._addColumnToMergedAttributes(o,i.attribute)),n},{});for(let n of this.fetch_attributes){let i=`${n.table.databaseid}_${n.table.as?n.table.as:n.table.tableid}`,o=this.data[i].__hash_name,c={schema:n.table.databaseid,table:n.table.tableid,get_attributes:[n.attribute]},_=!1,u=[n.table.databaseid,n.table.tableid,n.attribute].join("/");if(n.attribute===o&&(_=!0),!G.isEmpty(this.exact_search_values[u])&&!this.exact_search_values[u].ignore&&!G.isEmptyOrZeroLength(this.exact_search_values[u].values))if(_)try{c.hash_values=Array.from(this.exact_search_values[u].values);let l=await ln.getDataByHash(c);for(let E of c.hash_values)E in l&&!this.data[i].__merged_data[E]&&(this.data[i].__merged_data[E]=[...s[i]],this._setMergedHashAttribute(i,E))}catch(l){v.error("Error thrown from getDataByHash function in SQLSearch class method getFetchAttributeValues exact match."),v.error(l)}else try{c.search_attribute=n.attribute,await Promise.all(Array.from(this.exact_search_values[u].values).map(async l=>{let E=Object.assign({},c);E.search_value=l;let d=await ln.getDataByValue(E);for(let h in d)this.data[i].__merged_data[h]?this._updateMergedAttribute(i,h,n.attribute,d[h][n.attribute]):(this.data[i].__merged_data[h]=[...s[i]],this._updateMergedAttribute(i,h,n.attribute,d[h][n.attribute]),this._setMergedHashAttribute(i,G.autoCast(h)))}))}catch(l){v.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues exact match."),v.error(l)}else if(!G.isEmpty(this.comparator_search_values[u])&&!this.comparator_search_values[u].ignore&&!G.isEmptyOrZeroLength(this.comparator_search_values[u].comparators))try{let l=this.comparator_search_values[u].comparators;for(let E=0,d=l.length;E<d;E++){let h=l[E];c.search_attribute=h.attribute,c.search_value=h.search_value;let m=await ln.getDataByValue(c,h.operation);if(_)for(let R in m)this.data[i].__merged_data[R]||(this.data[i].__merged_data[R]=[...s[i]],this._setMergedHashAttribute(i,G.autoCast(R)));else for(let R in m)this.data[i].__merged_data[R]?this._updateMergedAttribute(i,R,n.attribute,m[R][n.attribute]):(this.data[i].__merged_data[R]=[...s[i]],this._updateMergedAttribute(i,R,n.attribute,m[R][n.attribute]),this._setMergedHashAttribute(i,G.autoCast(R)))}}catch(l){v.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues comparator search values."),v.error(l)}else try{c.search_attribute=n.attribute,c.search_value="*";let l=await ln.getDataByValue(c);if(_)for(let E in l)this.data[i].__merged_data[E]||(this.data[i].__merged_data[E]=[...s[i]],this._setMergedHashAttribute(i,G.autoCast(E)));else for(let E in l)this.data[i].__merged_data[E]?this._updateMergedAttribute(i,E,n.attribute,l[E][n.attribute]):(this.data[i].__merged_data[E]=[...s[i]],this._updateMergedAttribute(i,E,n.attribute,l[E][n.attribute]),this._setMergedHashAttribute(i,G.autoCast(E)))}catch(l){v.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues no comparator search values."),v.error(l)}}}_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 Me.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(n=>{let i=n.aggregatorid?n.expression:n,o=n.aggregatorid?n.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 s=r[0];if(t.is_func=!!s.funcid,t.is_aggregator=!!s.aggregatorid,s.as)if(s.as&&!t.expression.tableid)t.expression.columnid=s.as,t.expression.columnid_orig=s.as_orig;else{let n=new Me.yy.Column;n.columnid=s.as,n.columnid_orig=s.as_orig,t.expression=n}else{t.initial_select_column=Object.assign(new Me.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 n=t.is_func?new Me.yy.FuncValue:new Me.yy.Column;t.initial_select_column=Object.assign(n,s)}})}_addNonAggregatorsToFetchColumns(){let r=this.statement.order.filter(s=>!s.is_aggregator&&!s.is_ordinal).map(s=>s.is_func?{columnid:s.initial_select_column.args.filter(i=>!!i.columnid_orig)[0].columnid_orig}:{columnid:s.expression.columnid_orig});this._addFetchColumns(r)}async _processJoins(){let t=[],r=[],s=this.statement.from[0],n=[s],i=["? "+(s.as?" AS "+s.as:s.tableid)];t.push(Object.values(this.data[`${s.databaseid_orig}_${s.as?s.as_orig:s.tableid_orig}`].__merged_data)),this.statement.joins&&this.statement.joins.forEach(h=>{h.joinmode&&h.joinmode!=="INNER"&&(this.has_outer_join=!0),n.push(h.table);let m=h.joinmode+" JOIN ? AS "+(h.as?h.as:h.table.tableid);h.on&&(m+=" ON "+h.on.toString()),i.push(m),t.push(Object.values(this.data[`${h.table.databaseid_orig}_${h.table.as?h.table.as_orig:h.table.tableid_orig}`].__merged_data))});let o=[],c={};n.forEach(h=>{let m=this.data[`${h.databaseid_orig}_${h.as?h.as_orig:h.tableid_orig}`].__hash_name,R=h.as?h.as_orig:h.tableid_orig;o.push({key:`'${R}.${m}'`,schema:h.databaseid_orig,table:h.as?h.as_orig:h.tableid_orig,keys:new Set}),r.push(`${h.as?h.as:h.tableid}.\`${m}\` AS "${R}.${m}"`),c[h.as?h.as_orig:h.tableid_orig]=this.data[`${h.databaseid_orig}_${h.as?h.as_orig:h.tableid_orig}`].__merged_attributes});let _=this.statement.where?"WHERE "+this.statement.where:"",u="";this.statement.order&&!this.has_ordinal&&!this.has_aggregator&&!this.statement.group&&this.statement.limit&&(u="ORDER BY "+this.statement.order.toString(),this.statement.order.forEach(h=>{h.is_func?r.push(h.initial_select_column.toString()):h.initial_select_column.tableid?r.push(`${h.initial_select_column.tableid}.${h.initial_select_column.columnid} AS ${h.expression.columnid}`):r.push(`${h.initial_select_column.columnid} AS ${h.expression.columnid}`)}));let l="",E="";!this.has_aggregator&&!this.statement.group&&!this.has_ordinal&&(l=this.statement.limit?"LIMIT "+this.statement.limit:"",E=this.statement.offset?"OFFSET "+this.statement.offset:"");let d=[];try{let h=`SELECT ${r.join(", ")} FROM ${i.join(" ")} ${_} ${u} ${l} ${E}`,m=this._convertColumnsToIndexes(h,n);d=await Me.promise(m,t),t=null}catch(h){throw v.error("Error thrown from AlaSQL in SQLSearch class method processJoins."),v.error(h),new Error("There was a problem processing the data.")}if(d&&d.length>0){for(let h=0,m=d.length;h<m;h++){let R=d[h];o.forEach(w=>{R[w.key]!==null&&R[w.key]!==void 0&&w.keys.add(R[w.key])})}o.forEach(h=>{let m=Object.keys(this.data[`${h.schema}_${h.table}`].__merged_data),R=Si.difference(m,[...h.keys].map(w=>w.toString()));for(let w=0,L=R.length;w<L;w++){let B=R[w];delete this.data[`${h.schema}_${h.table}`].__merged_data[B]}})}return{existing_attributes:c,joined_length:d?d.length:0}}async _getFinalAttributeData(t,r){if(r===0)return;let s=[],n=new Uo(this.columns);for(let{node:i}of n)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)&&s.push(o)}}s=Si.uniqBy(s,i=>[i.table.databaseid,i.table.as?i.table.as:i.table.tableid,i.attribute].join());try{await this._getData(s)}catch(i){v.error("Error thrown from getData in SQLSearch class method getFinalAttributeData."),v.error(i)}}async _getData(t){try{let r=t.reduce((s,n)=>{let i=`${n.table.databaseid}_${n.table.as?n.table.as:n.table.tableid}`;return s[i]?s[i].columns.push(n.attribute):s[i]={schema:n.table.databaseid,table:n.table.tableid,columns:[n.attribute]},s},{});for(let s in r){let n=r[s],i=this.data[s].__merged_data,o=[];for(let l in i)o.push(i[l][0]);this.data[s].__merged_attributes.push(...n.columns);let c={schema:n.schema,table:n.table,hash_values:o,get_attributes:n.columns},_=await ln.getDataByHash(c),u=n.columns.length;for(let l=0,E=o.length;l<E;l++){let d=o[l],h=_[d];for(let m=0;m<u;m++){let R=n.columns[m],w=h[R]===void 0?null:h[R];this.data[s].__merged_data[d].push(w)}}}}catch(r){throw v.error("Error thrown from getDataByHash function in SQLSearch class method getData."),v.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(n=>{n.as=n.as?n.as:n.table.tableid,t.push(Object.values(this.data[`${n.table.databaseid_orig}_${n.table.as?n.table.as_orig:n.table.tableid_orig}`].__merged_data)),n.table.databaseid="",n.table.tableid="?"}),this.statement.order&&this.statement.order.forEach(n=>{if(n.is_ordinal)return;this.statement.columns.filter(o=>{let c=o.aggregatorid?o.expression:o,_=o.aggregatorid?o.as_orig:c.as_orig;return n.expression.tableid?c.columnid_orig===n.expression.columnid_orig&&c.tableid_orig===n.expression.tableid_orig:c.columnid_orig===n.expression.columnid_orig||n.expression.columnid_orig===_}).length===0&&(n.expression.columnid=n.initial_select_column.columnid)}),!this.has_aggregator&&!this.statement.group&&!this.has_ordinal&&(this.statement.limit&&delete this.statement.limit,this.statement.offset&&delete this.statement.offset);let s;try{let n=this._buildSQL();v.trace(`Final SQL: ${n}`),s=await Me.promise(n,t),this.has_outer_join&&(s=this._translateUndefinedValues(s)),v.trace(`Final AlaSQL results data included ${s.length} rows`)}catch(n){throw v.error("Error thrown from AlaSQL in SQLSearch class method finalSQL."),v.error(n),new Error("There was a problem running the generated sql.")}return s}_translateUndefinedValues(t){try{let r=[];for(let s of t){let n=Object.create(null);Object.keys(s).forEach(i=>{s[i]===void 0?n[i]=null:n[i]=s[i]}),r.push(n)}return r}catch(r){return v.error(XH.HDB_ERROR_MSGS.OUTER_JOIN_TRANSLATION_ERROR),v.trace(r.stack),t}}_buildSQL(t=!0){let r=this.statement.toString();return this.statement.columns.forEach(s=>{if(s.funcid&&s.as){let n=s.toString().replace(" AS "+s.as,"");r=r.replace(s.toString(),n)}}),t===!0?this._convertColumnsToIndexes(r,this.tables):r}_convertColumnsToIndexes(t,r){let s=t,n={};r.forEach(i=>{i.databaseid_orig?n[`${i.databaseid_orig}_${i.as?i.as_orig:i.tableid_orig}`]=i.as?i.as:i.tableid:n[`${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 _=n[i],u=new RegExp(`${_}.\`${o}\``,"g"),l=`${_}.[${c}]`;s=s.replace(u,l)});for(let i in this.data)this.data[i].__merged_attributes.forEach((o,c)=>{let _=new RegExp(`\`${o}\``,"g"),u=`[${c}]`;s=s.replace(_,u)});return s}async _simpleSQLQuery(){let t=this.statement.columns.reduce((s,n)=>(n.as_orig&&n.as_orig!=n.columnid_orig?s[n.columnid_orig]=n.as_orig:s[n.columnid_orig]||(s[n.columnid_orig]=n.columnid_orig),s),{}),r=this.fetch_attributes.reduce((s,n)=>{let i=`${n.table.databaseid}_${n.table.as?n.table.as:n.table.tableid}`;return s[i]||(s[i]={}),s[i][t[n.attribute]]=null,s},{});for(let s of this.fetch_attributes){let n=`${s.table.databaseid}_${s.table.as?s.table.as:s.table.tableid}`,i={schema:s.table.databaseid,table:s.table.tableid,get_attributes:[s.attribute]};try{i.search_attribute=s.attribute,i.search_value="*";let o=await ln.getDataByValue(i);for(let c in o)this.data[n].__merged_data[c]||(this.data[n].__merged_data[c]=Object.assign({},r[n])),this.data[n].__merged_data[c][t[s.attribute]]=o[c][s.attribute]}catch(o){v.error("There was an error when processing this SQL operation. Check your logs"),v.error(o)}}return Object.values(Object.values(this.data)[0].__merged_data)}};a(yo,"SQLSearch");$m.exports=yo});var mt=S((YZ,Qm)=>{"use strict";var jH=sS();Qm.exports={searchByConditions:sG,searchByHash:nG,searchByValue:iG,search:aG};var El=Or(),Km=require("util"),eG=Km.callbackify(El.searchByHash),tG=Km.callbackify(El.searchByValue),rG=Ym();async function sG(e){return El.searchByConditions(e)}a(sG,"searchByConditions");function nG(e,t){try{eG(e,(r,s)=>{if(r){t(r);return}t(null,s)})}catch(r){return t(r)}}a(nG,"searchByHash");function iG(e,t){try{e.hasOwnProperty("desc")===!0&&(e.reverse=e.desc),tG(e,(r,s)=>{if(r){t(r);return}t(null,s)})}catch(r){return t(r)}}a(iG,"searchByValue");function aG(e,t){try{let r=new jH(e);r.validate(),new rG(r.statement,r.attributes).search().then(n=>{t(null,n)}).catch(n=>{t(n,null)})}catch(r){return t(r)}}a(aG,"search")});var Vr=S((KZ,Xm)=>{"use strict";var Ti=require("crypto"),Jm="aes-256-cbc",oG=32,cG=16,dl=64,Zm=32,_G=dl+Zm,Wm=new Map;Xm.exports={encrypt:uG,decrypt:lG,createNatsTableStreamName:EG};function uG(e){let t=Ti.randomBytes(oG),r=Ti.randomBytes(cG),s=Ti.createCipheriv(Jm,Buffer.from(t),r),n=s.update(e);n=Buffer.concat([n,s.final()]);let i=t.toString("hex"),o=r.toString("hex"),c=n.toString("hex");return i+o+c}a(uG,"encrypt");function lG(e){let t=e.substr(0,dl),r=e.substr(dl,Zm),s=e.substr(_G,e.length),n=Buffer.from(r,"hex"),i=Buffer.from(s,"hex"),o=Ti.createDecipheriv(Jm,Buffer.from(t,"hex"),n),c=o.update(i);return c=Buffer.concat([c,o.final()]),c.toString()}a(lG,"decrypt");function EG(e,t){let r=`${e}.${t}`,s=Wm.get(r);return s||(s=Ti.createHash("md5").update(`${e}.${t}`).digest("hex"),Wm.set(r,s)),s}a(EG,"createNatsTableStreamName")});var fs=S((QZ,nR)=>{"use strict";var jm=mt(),kr=I(),eR=Ka(),dG=require("lodash"),hG=require("path"),SG=Vr(),hl=b(),{promisify:tR}=require("util"),j=T(),{handleHDBError:Do,hdb_errors:fG}=D(),{HDB_ERROR_MSGS:Mo,HTTP_STATUS_CODES:rR}=fG,TG=Y();TG.initSync();var zm=Z(),mG=te(),mi=tR(jm.searchByValue),RG=tR(jm.searchByHash),En="name",sR="hash_attribute",Sl="schema",AG="schema_table",OG="attribute";nR.exports={describeAll:pG,describeTable:Po,describeSchema:gG};async function pG(e){try{let t=hl.isEmptyOrZeroLength(e),r,s;t||(r=e.hdb_user.role.permission,s=r.super_user||r.cluster_user);let n={schema:j.SYSTEM_SCHEMA_NAME,table:j.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,search_attribute:En,search_value:j.WILDCARD_SEARCH_VALUE,get_attributes:[En]},i=await mi(n);if(hl.isEmptyOrZeroLength(i))return{};let o={},c={};for(let d in i)o[i[d].name]=!0,!t&&!s&&(c[i[d].name]=r[i[d].name].describe);let _={schema:j.SYSTEM_SCHEMA_NAME,table:j.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,search_attribute:j.ID_ATTRIBUTE_STRING,search_value:j.WILDCARD_SEARCH_VALUE,get_attributes:[sR,j.ID_ATTRIBUTE_STRING,En,Sl]},u=await mi(_),l=[];for(let d of u)try{let h;if(t||s)h=await Po({schema:d.schema,table:d.name});else if(r&&r[d.schema].describe&&r[d.schema].tables[d.name].describe){let m=r[d.schema].tables[d.name].attribute_permissions;h=await Po({schema:d.schema,table:d.name},m)}h&&l.push(h)}catch(h){kr.error(h)}let E={};for(let d in l)t||s?(E[l[d].schema]==null&&(E[l[d].schema]={}),E[l[d].schema][l[d].name]=l[d],o[l[d].schema]&&delete o[l[d].schema]):c[l[d].schema]&&(E[l[d].schema]==null&&(E[l[d].schema]={}),E[l[d].schema][l[d].name]=l[d],o[l[d].schema]&&delete o[l[d].schema]);for(let d in o)t||s?E[d]={}:c[d]&&(E[d]={});return E}catch(t){return kr.error("Got an error in describeAll"),kr.error(t),Do(new Error,Mo.DESCRIBE_ALL_ERR)}}a(pG,"describeAll");async function Po(e,t){let{schema:r,table:s}=e;r=r.toString(),s=s.toString();let n=t;e.hdb_user&&!e.hdb_user.role.permission.super_user&&(n=e.hdb_user.role.permission[r].tables[s].attribute_permissions);let i={},o=eR.describe_table(e);if(o)throw o;if(r===j.SYSTEM_SCHEMA_NAME)return global.hdb_schema[j.SYSTEM_SCHEMA_NAME][s];let c={schema:j.SYSTEM_SCHEMA_NAME,table:j.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,hash_attribute:j.SYSTEM_TABLE_HASH_ATTRIBUTES.TABLE_TABLE_HASH_ATTRIBUTE,search_attribute:En,search_value:s,hash_values:[],get_attributes:[j.WILDCARD_SEARCH_VALUE]},_=await mi(c);if(!_||_.length===0)throw Do(new Error,Mo.TABLE_NOT_FOUND(e.schema,e.table),rR.NOT_FOUND);for await(let u of _)try{if(u.schema!==r)continue;if(i=u,!i.hash_attribute)throw Do(new Error,Mo.INVALID_TABLE_ERR(i));let l={schema:j.SYSTEM_SCHEMA_NAME,table:j.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,hash_attribute:j.SYSTEM_TABLE_HASH_ATTRIBUTES.ATTRIBUTE_TABLE_HASH_ATTRIBUTE,search_attribute:AG,search_value:r+"."+s,get_attributes:[OG]},E=await mi(l);E=dG.uniqBy(E,d=>d.attribute),n&&n.length>0&&(E=NG(n)),i.attributes=E,i.clustering_stream_name=SG.createNatsTableStreamName(u.schema,u.name);try{let d=hG.join(mG.getBaseSchemaPath(),i.schema.toString()),h=await zm.openEnvironment(d,i.name),m=zm.statDBI(h,i.hash_attribute);i.record_count=m.entryCount}catch(d){kr.warn(`unable to stat table dbi due to ${d}`)}}catch(l){kr.error(`There was an error getting attributes for table '${u.name}'`),kr.error(l)}return i}a(Po,"descTable");function NG(e){return e.reduce((t,r)=>(r.describe&&t.push({attribute:r.attribute_name}),t),[])}a(NG,"getAttrsByPerms");async function gG(e){let t=eR.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 s=e.schema.toString(),n={schema:j.SYSTEM_SCHEMA_NAME,table:j.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,hash_attribute:j.SYSTEM_TABLE_HASH_ATTRIBUTES.TABLE_TABLE_HASH_ATTRIBUTE,search_attribute:Sl,search_value:s,hash_values:[],get_attributes:[sR,j.ID_ATTRIBUTE_STRING,En,Sl]},i=await mi(n);if(i&&i.length<1){let o={schema:j.SYSTEM_SCHEMA_NAME,table:j.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,hash_attribute:j.SYSTEM_TABLE_HASH_ATTRIBUTES.SCHEMA_TABLE_HASH_ATTRIBUTE,hash_values:[s],get_attributes:[En]},c=await RG(o);if(c&&c.length<1)throw Do(new Error,Mo.SCHEMA_NOT_FOUND(e.schema),rR.NOT_FOUND);return{}}else{let o={};return await Promise.all(i.map(async c=>{try{let _;if(r&&r.tables[c.name]&&(_=r.tables[c.name]),hl.isEmpty(_)||_.describe){let u=await Po({schema:e.schema,table:c.name},_?_.attribute_permissions:null);u&&(o[u.name]=u)}}catch(_){kr.error(`Error describing schema table '${e.schema}.${c}'`),kr.error(_)}})),o}}a(gG,"describeSchema")});var xr=S((ZZ,_R)=>{var WZ=require("async"),dn=is(),JZ=I(),{callbackify:oR,promisify:IG}=require("util");_R.exports={setSchemaDataToGlobal:iR,getTableSchema:wG,getSystemSchema:UG,setSchemaDataToGlobalAsync:IG(iR)};var cR=fs(),bG=oR(cR.describeAll),CG=oR(cR.describeTable);function iR(e){bG(null,(t,r)=>{if(t){e(t);return}r.system||(r.system=dn),global.hdb_schema=r,e(null,null)})}a(iR,"setSchemaDataToGlobal");function aR(e,t){return e==="system"?dn[t]:global.hdb_schema[e][t]}a(aR,"returnSchema");function wG(e,t,r){!global.hdb_schema||!global.hdb_schema[e]||!global.hdb_schema[e][t]?LG(e,t,s=>{if(s)return r(s);if(!global.hdb_schema[e])return r(`schema ${e} does not exist`);if(!global.hdb_schema[e]||!global.hdb_schema[e][t])return r(`table ${e}.${t} does not exist`);r(null,aR(e,t))}):r(null,aR(e,t))}a(wG,"getTableSchema");function LG(e,t,r){let s={table:t,schema:e};if(e==="system"){global.hdb_schema?global.hdb_schema.system=dn:global.hdb_schema={system:dn},r();return}CG(s,(n,i)=>{if(n){r(n);return}if(!i.schema&&!i.name){r();return}global.hdb_schema||(global.hdb_schema={system:dn}),global.hdb_schema[e]||(global.hdb_schema[e]={}),global.hdb_schema[e][t]=i,r()})}a(LG,"setTableDataToGlobal");function UG(){return dn}a(UG,"getSystemSchema")});var ER=S((XZ,lR)=>{"use strict";var fl=Z(),yG=I(),uR=Ke().LMDB_ERRORS_ENUM;lR.exports=DG;async function DG(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 fl.closeEnvironment(global.lmdb_map[o])}catch(c){if(c.message!==uR.ENV_REQUIRED)throw c}}break;case"drop_table":let s=`${e.schema}.${e.table}`,n=`txn.${s}`;try{await fl.closeEnvironment(global.lmdb_map[s]),await fl.closeEnvironment(global.lmdb_map[n])}catch(i){if(i.message!==uR.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){yG.error(t)}}a(DG,"cleanLMDBMap")});var Ut=S((zZ,SR)=>{"use strict";var vo=vu(),Lt=b(),MG=require("util"),Ho=Or(),PG=xr(),Tl=I(),{handleHDBError:$r,hdb_errors:BG}=D(),{HTTP_STATUS_CODES:Ts}=BG,vG=MG.promisify(PG.getTableSchema),HG="updated",dR="inserted",hR="upserted";SR.exports={insert:qG,update:FG,upsert:VG,validation:GG,flush:kG};async function GG(e){if(Lt.isEmpty(e))throw new Error("invalid update parameters defined.");if(Lt.isEmptyOrZeroLength(e.schema))throw new Error("invalid schema specified.");if(Lt.isEmptyOrZeroLength(e.table))throw new Error("invalid table specified.");let t=await vG(e.schema,e.table),r=vo(e);if(r)throw r;if(!Array.isArray(e.records))throw new Error("records must be an array");let s=t.hash_attribute,n=new Set,i={},o=!1;return e.operation==="update"&&(o=!0),e.records.forEach(c=>{if(o&&Lt.isEmptyOrZeroLength(c[s]))throw Tl.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(!Lt.isEmptyOrZeroLength(c[s])&&(c[s]==="null"||c[s]==="undefined"))throw Tl.error(`a valid hash value must be provided with ${e.operation} record:`,c),new Error(`"${c[s]}" is not a valid hash attribute value`);!Lt.isEmpty(c[s])&&c[s]!==""&&n.has(Lt.autoCast(c[s]))&&(c.skip=!0),n.add(Lt.autoCast(c[s]));for(let _ in c)i[_]=1}),i[s]=1,{schema_table:t,hashes:Array.from(n),attributes:Object.keys(i)}}a(GG,"validation");async function qG(e){if(e.operation!=="insert")throw new Error("invalid operation, must be insert");let t=vo(e);if(t)throw $r(new Error,t.message,Ts.BAD_REQUEST);let r=Lt.checkSchemaTableExist(e.schema,e.table);if(r)throw $r(new Error,r,Ts.BAD_REQUEST);try{let s=await Ho.createRecords(e);return Bo(dR,s.written_hashes,e,s.skipped_hashes,s.new_attributes,s.txn_time)}catch(s){throw s}}a(qG,"insertData");async function FG(e){if(e.operation!=="update")throw new Error("invalid operation, must be update");let t=vo(e);if(t)throw $r(new Error,t.message,Ts.BAD_REQUEST);let r=Lt.checkSchemaTableExist(e.schema,e.table);if(r)throw $r(new Error,r,Ts.BAD_REQUEST);try{let s=await Ho.updateRecords(e);return Lt.isEmpty(s.existing_rows)?Bo(HG,s.written_hashes,e,s.skipped_hashes,s.new_attributes,s.txn_time):Bo(s.update_action,[],e,s.hashes,void 0,s.txn_time)}catch(s){throw s}}a(FG,"updateData");async function VG(e){if(e.operation!=="upsert")throw $r(new Error,"invalid operation, must be upsert",Ts.INTERNAL_SERVER_ERROR);let t=vo(e);if(t)throw $r(new Error,t.message,Ts.BAD_REQUEST);let r=Lt.checkSchemaTableExist(e.schema,e.table);if(r)throw $r(new Error,r,Ts.BAD_REQUEST);try{let s=await Ho.upsertRecords(e);return Bo(hR,s.written_hashes,e,[],s.new_attributes,s.txn_time)}catch(s){let n=`There was an error during an upsert op: ${s}`;throw $r(s,null,null,Tl.ERR,n)}}a(VG,"upsertData");function Bo(e,t,r,s,n,i){let o={message:`${e} ${t.length} of ${t.length+s.length} records`,new_attributes:n,txn_time:i};return e===dR?(o.inserted_hashes=t,o.skipped_hashes=s,o):e===hR?(o.upserted_hashes=t,o):(o.update_hashes=t,o.skipped_hashes=s,o)}a(Bo,"returnObject");function kG(e){return Ho.flush(e.schema,e.table)}a(kG,"flush")});var Rl=S((jZ,mR)=>{var xG=de(),ml=require("joi"),{hdb_schema_table:fR}=Tr(),TR={schema:fR,table:fR},$G={date:ml.date().iso().required()},YG={timestamp:ml.date().timestamp().required().messages({"date.format":"'timestamp' is invalid"})};mR.exports=function(e,t){let r=t==="timestamp"?{...TR,...YG}:{...TR,...$G},s=ml.object(r);return xG.validateBySchema(e,s)}});var pR=S((eX,OR)=>{var KG=de(),RR=require("joi"),{hdb_schema_table:AR}=Tr(),QG=RR.object({schema:AR,table:AR,hash_values:RR.array().required()});OR.exports=function(e){return KG.validateBySchema(e,QG)}});var gR=S((tX,NR)=>{"use strict";var Go=class{constructor(t,r,s,n,i){this.operation=t,this.schema=r,this.table=s,this.hash_attribute=n,this.records=i}};a(Go,"InsertObject");var qo=class{constructor(t,r,s,n,i,o){this.schema=t,this.table=r,this.search_attribute=s,this.hash_attribute=n,this.get_attributes=i,this.search_value=o}};a(qo,"NoSQLSeachObject");var Fo=class{constructor(){this.message=void 0,this.deleted_hashes=[],this.skipped_hashes=[]}};a(Fo,"DeleteResponseObject");NR.exports={InsertObject:Go,NoSQLSeachObject:qo,DeleteResponseObject:Fo}});var Rs=S((rX,LR)=>{"use strict";var bR=Rl(),WG=pR(),Vo=b(),IR=require("moment"),CR=I(),{promisify:JG,callbackify:ZG}=require("util"),ms=T(),XG=xr(),Al=JG(XG.getTableSchema),Ol=Or(),{DeleteResponseObject:zG}=gR(),{handleHDBError:Yr,hdb_errors:jG}=D(),{HDB_ERROR_MSGS:ko,HTTP_STATUS_CODES:Kr}=jG,eq="records successfully deleted",tq=ZG(wR);LR.exports={delete:tq,deleteRecord:wR,deleteFilesBefore:rq,deleteAuditLogsBefore:sq};async function rq(e){let t=bR(e,"date");if(t)throw Yr(t,t.message,Kr.BAD_REQUEST,void 0,void 0,!0);if(!IR(e.date,IR.ISO_8601).isValid())throw Yr(new Error,ko.INVALID_DATE,Kr.BAD_REQUEST,ms.LOG_LEVELS.ERROR,ko.INVALID_DATE,!0);let s=Vo.checkSchemaTableExist(e.schema,e.table);if(s)throw Yr(new Error,s,Kr.NOT_FOUND,ms.LOG_LEVELS.ERROR,s,!0);try{let n=await Ol.deleteRecordsBefore(e);if(await Al(e.schema,e.table),CR.info(`Finished deleting files before ${e.date}`),n&&n.message)return n.message}catch(n){throw n}}a(rq,"deleteFilesBefore");async function sq(e){let t=bR(e,"timestamp");if(t)throw Yr(t,t.message,Kr.BAD_REQUEST,void 0,void 0,!0);if(isNaN(e.timestamp))throw Yr(new Error,ko.INVALID_VALUE("Timestamp"),Kr.BAD_REQUEST,ms.LOG_LEVELS.ERROR,ko.INVALID_VALUE("Timestamp"),!0);let r=Vo.checkSchemaTableExist(e.schema,e.table);if(r)throw Yr(new Error,r,Kr.NOT_FOUND,ms.LOG_LEVELS.ERROR,r,!0);try{let s=await Ol.deleteAuditLogsBefore(e);return await Al(e.schema,e.table),CR.info(`Finished deleting audit logs before ${e.timestamp}`),s}catch(s){throw s}}a(sq,"deleteAuditLogsBefore");async function wR(e){let t=WG(e);if(t)throw Yr(t,t.message,Kr.BAD_REQUEST,void 0,void 0,!0);let r=Vo.checkSchemaTableExist(e.schema,e.table);if(r)throw Yr(new Error,r,Kr.NOT_FOUND,ms.LOG_LEVELS.ERROR,r,!0);try{await Al(e.schema,e.table);let s=await Ol.deleteRecords(e);return Vo.isEmptyOrZeroLength(s.message)&&(s.message=`${s.deleted_hashes.length} of ${e.hash_values.length} ${eq}`),s}catch(s){if(s.message===ms.SEARCH_NOT_FOUND_MESSAGE){let n=new zG;return n.message=ms.SEARCH_NOT_FOUND_MESSAGE,n.skipped_hashes=e.hash_values.length,n.deleted_hashes=0,n}throw s}}a(wR,"deleteRecord")});var xo=S((sX,DR)=>{var nq=require("crypto"),UR=9;function iq(e){let t=oq(UR),r=yR(e+t);return t+r}a(iq,"createHash");function aq(e,t){let r=e.substr(0,UR),s=r+yR(t+r);return e===s}a(aq,"validateHash");function oq(e){let t="0123456789abcdefghijklmnopqurstuvwxyzABCDEFGHIJKLMNOPQURSTUVWXYZ",r=t.length,s="";for(let n=0;n<e;n++){let i=Math.floor(Math.random()*r);s+=t[i]}return s}a(oq,"generateSalt");function yR(e){return nq.createHash("md5").update(e).digest("hex")}a(yR,"md5");DR.exports={hash:iq,validate:aq}});var PR=S((nX,MR)=>{var pl=de(),Je={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 cq(e){return Je.password.presence=!0,Je.username.presence=!0,Je.role.presence=!0,Je.active.presence=!0,pl.validateObject(e,Je)}a(cq,"addUserValidation");function _q(e){return Je.password.presence=!1,Je.username.presence=!0,Je.role.presence=!1,Je.active.presence=!1,pl.validateObject(e,Je)}a(_q,"alterUserValidation");function uq(e){return Je.password.presence=!1,Je.username.presence=!0,Je.role.presence=!1,Je.active.presence=!1,pl.validateObject(e,Je)}a(uq,"dropUserValidation");MR.exports={addUserValidation:cq,alterUserValidation:_q,dropUserValidation:uq}});var _e=S((aX,vR)=>{"use strict";var{platform:iX}=require("os"),lq="nats-server.zip",Nl="nats-server",Eq=process.platform==="win32"?`${Nl}.exe`:Nl,gl="HDB",dq=/^[^\s.,*>]+$/,BR="__request__",hq=a(e=>`${e}.${BR}`,"REQUEST_SUBJECT"),Sq={HUB_SERVER:"hub.json",LEAF_SERVER:"leaf.json"},fq={HUB:"hub.pid",LEAF:"leaf.pid"},Tq={HUB:"-hub",LEAF:"-leaf",ADMIN:"-admin"},mq={stream_name:"__HARPERDB_WORK_QUEUE__",durable_name:"HDB_WORK_QUEUE",deliver_group:gl,deliver_subject:"__HDB__.WORKQUEUE"},Rq={stream_name:"__HARPERDB_SCHEMA_QUEUE__",durable_name:"HDB_SCHEMA_QUEUE",deliver_group:gl,deliver_subject:"HDB.SCHEMAQUEUE"},Aq={stream_name:"__HARPERDB_USER_QUEUE__",durable_name:"HDB_USER_QUEUE",deliver_group:gl,deliver_subject:"HDB.USERQUEUE"},Oq={SUCCESS:"success",ERROR:"error"},pq={OPEN:"open",CLOSED:"closed",NO_RESPONDERS:"NoResponders",TIMEOUT:"Timeout"},Nq={TXN:"txn",MSGID:"msgid"};vR.exports={NATS_SERVER_ZIP:lq,NATS_SERVER_NAME:Nl,NATS_BINARY_NAME:Eq,PID_FILES:fq,NATS_CONFIG_FILES:Sq,SERVER_SUFFIX:Tq,WORK_QUEUE_CONSUMER_NAMES:mq,SCHEMA_QUEUE_CONSUMER_NAMES:Rq,USER_QUEUE_CONSUMER_NAMES:Aq,NATS_TERM_CONSTRAINTS_RX:dq,REQUEST_SUFFIX:BR,UPDATE_REMOTE_RESPONSE_STATUSES:Oq,CLUSTER_STATUS_STATUSES:pq,REQUEST_SUBJECT:hq,SUBJECT_PREFIXES:Nq}});var GR=S((oX,HR)=>{"use strict";var Qr=T(),Ri=class{constructor(t=0,r=Qr.STORAGE_TYPES_ENUM.LMDB,s=Qr.LICENSE_VALUES.API_CALL_DEFAULT,n=Qr.RAM_ALLOCATION_ENUM.DEFAULT,i=Qr.LICENSE_VALUES.VERSION_DEFAULT,o){this.exp_date=t,this.storage_type=r,this.api_call=s,this.ram_allocation=n,this.version=i,this.fingerprint=o}};a(Ri,"BaseLicense");var $o=class extends Ri{constructor(t=0,r=Qr.STORAGE_TYPES_ENUM.LMDB,s=Qr.LICENSE_VALUES.API_CALL_DEFAULT,n=Qr.RAM_ALLOCATION_ENUM.DEFAULT,i=Qr.LICENSE_VALUES.VERSION_DEFAULT,o,c=!1){super(t,r,s,n,i,o),this.enterprise=c}};a($o,"ExtendedLicense");HR.exports={BaseLicense:Ri,ExtendedLicense:$o}});var Ai=S((cX,$R)=>{"use strict";var Sn=require("fs-extra"),qR=xo(),FR=require("crypto"),gq=require("moment"),Iq=require("uuid").v4,Ze=I(),bl=require("path"),bq=b(),Rt=T(),Cq=GR().ExtendedLicense,hn="invalid license key format",wq="061183",Lq="mofi25",Uq="aes-256-cbc",yq=16,Dq=32,VR=Y();VR.initSync();var Il;$R.exports={validateLicense:kR,generateFingerPrint:Pq,licenseSearch:xR,getLicense:Hq};function Cl(){return bl.join(VR.getHdbBasePath(),Rt.LICENSE_KEY_DIR_NAME,Rt.LICENSE_FILE_NAME)}a(Cl,"getLicenseDirPath");function Mq(){let e=Cl();return bl.join(e,Rt.LICENSE_FILE_NAME)}a(Mq,"getLicenseFilePath");function wl(){let e=Cl();return bl.join(e,Rt.REG_KEY_FILE_NAME)}a(wl,"getFingerPrintFilePath");async function Pq(){let e=wl();try{return await Sn.readFile(e,"utf8")}catch(t){if(t.code==="ENOENT")return await Bq();throw Ze.error(`Error writing fingerprint file to ${e}`),Ze.error(t),new Error("There was an error generating the fingerprint")}}a(Pq,"generateFingerPrint");async function Bq(){let e=Iq(),t=qR.hash(e),r=wl();try{await Sn.mkdirp(Cl()),await Sn.writeFile(r,t)}catch(s){if(s.code==="EEXIST")return t;throw Ze.error(`Error writing fingerprint file to ${r}`),Ze.error(s),new Error("There was an error generating the fingerprint")}return t}a(Bq,"writeFingerprint");function kR(e,t){let r={valid_license:!1,valid_date:!1,valid_machine:!1,exp_date:null,storage_type:Rt.STORAGE_TYPES_ENUM.LMDB,api_call:Rt.LICENSE_VALUES.API_CALL_DEFAULT,ram_allocation:Rt.RAM_ALLOCATION_ENUM.DEFAULT,version:Rt.LICENSE_VALUES.VERSION_DEFAULT};if(!e)return Ze.error("empty license key passed to validate."),r;let s=wl(),n=!1;try{n=Sn.statSync(s)}catch(i){Ze.error(i)}if(n){let i;try{i=Sn.readFileSync(s,"utf8")}catch{Ze.error("error validating this machine in the license"),r.valid_machine=!1;return}let o=e.split(Lq),c=o[1];c=Buffer.concat([Buffer.from(c)],yq);let _=Buffer.concat([Buffer.from(i)],Dq),u=FR.createDecipheriv(Uq,_,c);r.valid_date=!0,r.valid_license=!0,r.valid_machine=!0;let l=null;try{l=u.update(o[0],"hex","utf8"),l.trim(),l+=u.final("utf8")}catch{let h=vq(o[0],i);if(h)l=h;else throw r.valid_license=!1,r.valid_machine=!1,console.error(hn),Ze.error(hn),new Error(hn)}let E;if(isNaN(l))try{E=JSON.parse(l),r.api_call=E.api_call,r.version=E.version,r.storage_type=E.storage_type,r.exp_date=E.exp_date,isNaN(r.exp_date)&&(r.exp_date=new Date(r.exp_date).getTime()),E.ram_allocation&&(r.ram_allocation=E.ram_allocation)}catch{throw console.error(hn),Ze.error(hn),new Error(hn)}else r.exp_date=l;r.exp_date<gq().valueOf()&&(r.valid_date=!1),qR.validate(o[1],`${wq}${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||Ze.error("Invalid licence"),r}a(kR,"validateLicense");function vq(e,t){try{let r=FR.createDecipher("aes192",t),s=r.update(e,"hex","utf8");return s.trim(),s+=r.final("utf8"),s}catch{Ze.warn("Check old license failed")}}a(vq,"checkOldLicense");function xR(){let e=new Cq;e.api_call=0;let t=[];try{t=Sn.readFileSync(Mq(),"utf-8").split(Rt.NEW_LINE)}catch(r){r.code==="ENOENT"?Ze.info("no license file found"):Ze.error(`could not search for licenses due to: '${r.message}`)}for(let r=0;r<t.length;++r){let s=t[r];try{if(bq.isEmptyOrZeroLength(s))continue;let n=JSON.parse(s),i=kR(n.license_key,n.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.api_call+=i.api_call,e.ram_allocation=i.ram_allocation,e.storage_type=i.storage_type,e.enterprise=!0)}catch(n){Ze.error("There was an error parsing the license string."),Ze.error(n),e.api_call=Rt.LICENSE_VALUES.API_CALL_DEFAULT,e.ram_allocation=Rt.RAM_ALLOCATION_ENUM.DEFAULT,e.storage_type=Rt.STORAGE_TYPES_ENUM.LMDB,e.enterprise=!1}}return e.api_call===0&&(e.api_call=Rt.LICENSE_VALUES.API_CALL_DEFAULT),Il=e,e}a(xR,"licenseSearch");async function Hq(){return Il||await xR(),Il}a(Hq,"getLicense")});var Wr=S((_X,nA)=>{"use strict";var WR="username is required",JR="nothing to update, must supply active, role or password to update",ZR="password cannot be an empty string",XR="If role is specified, it cannot be empty.",zR="active must be true or false";nA.exports={addUser:Yq,alterUser:Kq,dropUser:Wq,userInfo:Jq,listUsers:Ko,listUsersExternal:Zq,setUsersToGlobal:Oi,findAndValidateUser:jq,getClusterUser:eF,USERNAME_REQUIRED:WR,ALTERUSER_NOTHING_TO_UPDATE:JR,EMPTY_PASSWORD:ZR,EMPTY_ROLE:XR,ACTIVE_BOOLEAN:zR};var jR=Ut(),Gq=Rs(),Ul=xo(),eA=PR(),tA=mt(),yl=js(),be=b(),rA=require("validate.js"),H=I(),{promisify:Dl}=require("util"),Ml=Vr(),As=T(),YR=_e(),qq=Sr(),Pl=Y(),Fq=Ai(),Vq=is(),{handleHDBError:rr,hdb_errors:kq}=D(),{HTTP_STATUS_CODES:sr,AUTHENTICATION_ERROR_MSGS:Ll,HDB_ERROR_MSGS:fn}=kq,{UserEventMsg:Bl}=Gr(),KR=require("lodash"),sA={username:!0,active:!0,role:!0,password:!0},QR=new Map,Yo=Dl(tA.searchByValue),xq=Dl(tA.searchByHash),$q=Dl(Gq.delete);async function Yq(e){let t=rA.cleanAttributes(e,sA),r=eA.addUserValidation(t);if(r)throw rr(new Error,r.message,sr.BAD_REQUEST,void 0,void 0,!0);let s={schema:"system",table:"hdb_role",search_attribute:"role",search_value:t.role,get_attributes:["id","permission","role"]},n;try{n=await Yo(s)}catch(u){throw H.error("There was an error searching for a role in add user"),H.error(u),u}if(!n||n.length<1)throw rr(new Error,fn.ROLE_NAME_NOT_FOUND(t.role),sr.NOT_FOUND,void 0,void 0,!0);if(n.length>1)throw rr(new Error,fn.DUP_ROLES_FOUND(t.role),sr.CONFLICT,void 0,void 0,!0);n[0].permission.cluster_user===!0&&(t.hash=Ml.encrypt(t.password)),t.password=Ul.hash(t.password),t.role=n[0].id;let i={operation:"insert",schema:"system",table:"hdb_user",records:[t]},o;try{o=await jR.insert(i)}catch(u){throw H.error("There was an error searching for a user."),H.error(u),u}H.debug(o);try{await Oi()}catch(u){throw H.error("Got an error setting users to global"),H.error(u),u}if(o.skipped_hashes.length===1)throw rr(new Error,fn.USER_ALREADY_EXISTS(t.username),sr.CONFLICT,void 0,void 0,!0);let c=Object.assign({},t);c.role=n[0];let _={user:null};return _.user=c,be.sendTransactionToSocketCluster(As.INTERNAL_SC_CHANNELS.ADD_USER,_,Pl.get(As.HDB_SETTINGS_NAMES.CLUSTERING_NODE_NAME_KEY)),yl.signalUserChange(new Bl(process.pid)),`${c.username} successfully added`}a(Yq,"addUser");async function Kq(e){let t=rA.cleanAttributes(e,sA);if(be.isEmptyOrZeroLength(t.username))throw new Error(WR);if(be.isEmptyOrZeroLength(t.password)&&be.isEmptyOrZeroLength(t.role)&&be.isEmptyOrZeroLength(t.active))throw new Error(JR);if(!be.isEmpty(t.password)&&be.isEmptyOrZeroLength(t.password.trim()))throw new Error(ZR);if(!be.isEmpty(t.active)&&!be.isBoolean(t.active))throw new Error(zR);let r=Qq(t.username);if(!be.isEmpty(t.password)&&!be.isEmptyOrZeroLength(t.password.trim())&&(r&&(t.hash=Ml.encrypt(t.password)),t.password=Ul.hash(t.password)),t.role==="")throw new Error(XR);if(t.role){let o={schema:"system",table:"hdb_role",search_attribute:"role",search_value:t.role,get_attributes:["*"]},c;try{c=await Yo(o)}catch(_){throw H.error("Got an error searching for a role."),H.error(_),_}if(!c||c.length===0){let _=fn.ALTER_USER_ROLE_NOT_FOUND(t.role);throw H.error(_),rr(new Error,_,sr.NOT_FOUND,void 0,void 0,!0)}if(c.length>1){let _=fn.ALTER_USER_DUP_ROLES(t.role);throw H.error(_),rr(new Error,_,sr.CONFLICT,void 0,void 0,!0)}t.role=c[0].id}let s={operation:"update",schema:"system",table:"hdb_user",records:[t]},n;try{n=await jR.update(s)}catch(o){throw H.error("Error during update."),H.error(o),o}try{await Oi()}catch(o){throw H.error("Got an error setting users to global"),H.error(o),o}let i={user:null};return i.user=t,be.sendTransactionToSocketCluster(As.INTERNAL_SC_CHANNELS.ALTER_USER,i,Pl.get(As.HDB_SETTINGS_NAMES.CLUSTERING_NODE_NAME_KEY)),yl.signalUserChange(new Bl(process.pid)),n}a(Kq,"alterUser");function Qq(e){let t=!1,r=global.hdb_users.get(e);return r&&r.role.permission.cluster_user===!0&&(t=!0),t}a(Qq,"isClusterUser");async function Wq(e){try{let t=eA.dropUserValidation(e);if(t)throw new Error(t);let r={table:"hdb_user",schema:"system",hash_values:[e.username]};if(be.isEmpty(global.hdb_users.get(e.username)))throw rr(new Error,fn.USER_NOT_EXIST(e.username),sr.NOT_FOUND,void 0,void 0,!0);let s;try{s=await $q(r)}catch(i){throw H.error("Got an error deleting a user."),H.error(i),i}H.debug(s);try{await Oi()}catch(i){throw H.error("Got an error setting users to global."),H.error(i),i}let n={user:null};return n.user=e,be.sendTransactionToSocketCluster(As.INTERNAL_SC_CHANNELS.DROP_USER,n,Pl.get(As.HDB_SETTINGS_NAMES.CLUSTERING_NODE_NAME_KEY)),yl.signalUserChange(new Bl(process.pid)),`${e.username} successfully deleted`}catch(t){throw t}}a(Wq,"dropUser");async function Jq(e){let t={};try{if(!e||!e.hdb_user)return"There was no user info in the body";t=e.hdb_user;let r={schema:"system",table:"hdb_role",hash_values:[t.role.id],get_attributes:["*"]},s;try{s=await xq(r)}catch(n){throw H.error("Got an error searching for a role."),H.error(n),n}t.role=s[0],delete t.password,delete t.refresh_token,delete t.hash}catch(r){throw H.error(r),r}return t}a(Jq,"userInfo");async function Zq(){let e;try{e=await Ko()}catch(t){throw H.error("Got an error listing users."),H.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(Zq,"listUsersExternal");async function Ko(){try{let e={schema:"system",table:"hdb_role",search_value:"*",search_attribute:"role",get_attributes:["*"]},t;try{t=KR.cloneDeep(await Yo(e))}catch(r){throw H.error("Got an error searching for roles."),H.error(r),r}if(!be.isEmptyOrZeroLength(t)){let r={};for(let o in t)r[t[o].id]=t[o];let s={schema:"system",table:"hdb_user",search_value:"*",search_attribute:"username",get_attributes:["*"]},n;try{n=KR.cloneDeep(await Yo(s))}catch(o){throw H.error("Got an error searching for users."),H.error(o),o}let i=new Map;for(let o in n){let c=n[o];c.role=r[n[o].role],Xq(c.role),i.set(c.username,c)}return(await Fq.getLicense()).enterprise?i:zq(i)}}catch(e){throw H.error("got an error listing users"),H.error(e),be.errorizeMessage(e)}return null}a(Ko,"listUsers");function Xq(e){try{if(!e){H.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(Vq)){let r={read:!!e.permission.super_user,insert:!1,update:!1,delete:!1,attribute_permissions:[]};e.permission.system.tables[t]=r}}catch(t){H.error("Got an error trying to set system permissions."),H.error(t)}}a(Xq,"appendSystemTablesToRole");function zq(e){try{if(H.info("No enterprise license found. System is limited to 1 clustering role and 1 user role"),!e)return new Map;let t=Object.create(null),r=new Map;e.forEach((n,i)=>{n.role.permission.cluster_user===void 0||n.role.permission.cluster_user===!1?n.role.permission.super_user===!0&&(t[n.role.id]||(t[n.role.id]=new Map),t[n.role.id].set(i,n)):r.set(i,n)});let s={role:void 0,count:0};return Object.keys(t).forEach(n=>{let i=t[n];i.size>=s.count&&(s.role=n,s.count=i.size)}),s.role===void 0?(H.error("No roles found with active users. This is bad."),new Map):(r=new Map([...r,...t[s.role]]),r)}catch(t){return H.error("error filtering users."),H.error(t),new Map}}a(zq,"nonEnterpriseFilter");async function Oi(){try{let e=await Ko();global.hdb_users=e}catch(e){throw H.error(e),e}}a(Oi,"setUsersToGlobal");async function jq(e,t,r=!0){global.hdb_users||await Oi();let s=global.hdb_users.get(e);if(!s)throw rr(new Error,Ll.GENERIC_AUTH_FAIL,sr.UNAUTHORIZED,void 0,void 0,!0);if(s&&!s.active)throw rr(new Error,Ll.USER_INACTIVE,sr.UNAUTHORIZED,void 0,void 0,!0);let n={active:s.active,username:s.username};if(s.refresh_token&&(n.refresh_token=s.refresh_token),s.role&&(n.role=s.role),r===!0){if(QR.get(t)===s.password)return n;if(Ul.validate(s.password,t))QR.set(t,s.password);else throw rr(new Error,Ll.GENERIC_AUTH_FAIL,sr.UNAUTHORIZED,void 0,void 0,!0)}return n}a(jq,"findAndValidateUser");async function eF(){let e=await Ko(),t=qq.getConfigFromFile(As.CONFIG_PARAMS.CLUSTERING_USER),r=e.get(t);if(!be.isEmpty(r))return r.decrypt_hash=Ml.decrypt(r.hash),r.uri_encoded_d_hash=encodeURIComponent(r.decrypt_hash),r.uri_encoded_name=encodeURIComponent(r.username),r.sys_name=r.username+YR.SERVER_SUFFIX.ADMIN,r.sys_name_encoded=r.uri_encoded_name+YR.SERVER_SUFFIX.ADMIN,r}a(eF,"getClusterUser")});var _A=S((uX,cA)=>{"use strict";var Os=I(),Qo=T(),tF=ER(),iA=xr(),rF=fs(),sF=Wr(),{validateEvent:oA}=Gr(),nF={[Qo.IPC_EVENT_TYPES.SCHEMA]:iF,[Qo.IPC_EVENT_TYPES.USER]:oF};async function iF(e){let t=oA(e);if(t){Os.error(t);return}Os.trace(`IPC schemaHandler ${Qo.HDB_IPC_CLIENT_PREFIX}${process.pid} received schema event:`,e),await tF(e.message),await aF(e.message)}a(iF,"schemaHandler");async function aF(e){try{if(global.hdb_schema!==void 0&&typeof global.hdb_schema=="object"&&e.operation!==void 0)switch(e.operation){case"drop_schema":delete global.hdb_schema[e.schema];break;case"drop_table":global.hdb_schema[e.schema]!==void 0&&delete global.hdb_schema[e.schema][e.table];break;case"create_schema":global.hdb_schema[e.schema]===void 0&&(global.hdb_schema[e.schema]={});break;case"create_table":case"create_attribute":global.hdb_schema[e.schema]===void 0&&(global.hdb_schema[e.schema]={}),global.hdb_schema[e.schema][e.table]=await rF.describeTable({schema:e.schema,table:e.table});break;default:iA.setSchemaDataToGlobal(aA);break}else iA.setSchemaDataToGlobal(aA)}catch(t){Os.error(t)}}a(aF,"syncSchemaMetadata");function aA(e){e&&Os.error(e)}a(aA,"handleErrorCallback");async function oF(e){try{let t=oA(e);if(t){Os.error(t);return}Os.trace(`IPC userHandler ${Qo.HDB_IPC_CLIENT_PREFIX}${process.pid} received user event:`,e),await sF.setUsersToGlobal()}catch(t){Os.error(t)}}a(oF,"userHandler");cA.exports=nF});var Wo=S((lX,uA)=>{"use strict";var cF=Or();uA.exports={writeTransaction:_F};function _F(e,t,r){return cF.writeTransaction(e,t,r)}a(_F,"writeTransaction")});var vl=S((EX,uF)=>{uF.exports={name:"harperdb",version:"4.0.4",description:"HarperDB is a distributed SQL & NoSQL data platform focused on speed, flexibility, and ease of use.",keywords:["database","sql","nosql","api","distributed","cloud","enterprise","Fastify","NATS"],main:"harperdb.js",bin:{harperdb:"./bin/harperdb.js"},engines:{node:">=14.0.0","preferred-node":"18.13.0","go-lang":"1.19.3","nats-server":"2.9.8"},homepage:"https://www.harperdb.io/",bugs:"support@harperdb.io",author:{name:"HarperDB",email:"support@harperdb.io"},license:"See License in ./license/Community+Edition+and+Evaluation+End+User+License+Agreement.pdf",scripts:{submodules:"git submodule update --init --recursive",build:"eslint -c ./.eslintbuild bin/ data_layer/ security/ server/ sqlTranslator/ upgrade/ utility/ validation/",pretty:"eslint --fix bin/ data_layer/ security/ server/ sqlTranslator/ upgrade/ utility/ validation/",test:"rimraf ./.nyc_output/* && node utility/devops/register.js --reset_license --storage_type=lmdb && npm run cover:upgrade && npm run cover:nats && npm run cover:cfserver && npm run cover:lmdbbridge && npm run cover:lmdbutility && npm run cover:hdbserver && npm run cover:main && nyc merge .nyc_output coverage.json && node ./utility/devops/register.js --reset_license --storage_type=lmdb","cover:main":"cd bin/ && nyc --no-clean --reporter=lcovonly ../node_modules/mocha/bin/_mocha '../unitTests/**/*.js' --config '../unitTests/.mocharc-main.json'","cover:lmdbbridge":"cd bin/ && nyc --no-clean --reporter=lcovonly --retries 3 ../node_modules/mocha/bin/_mocha '../unitTests/data_layer/harperBridge/lmdbBridge/**/*.js' --parallel --config '../unitTests/.mocharc.json'","cover:lmdbutility":"cd bin/ && nyc --no-clean --reporter=lcovonly --retries 3 ../node_modules/mocha/bin/_mocha '../unitTests/utility/lmdb/**/*.js' --parallel --config '../unitTests/.mocharc.json'","cover:hdbserver":"cd bin/ && nyc --no-clean --reporter=lcovonly ../node_modules/mocha/bin/_mocha '../unitTests/server/harperdb/hdbServer-test.js' --parallel --config '../unitTests/.mocharc.json'","cover:cfserver":"npm run submodules && cd bin/ && nyc --no-clean --reporter=lcovonly ../node_modules/mocha/bin/_mocha '../unitTests/server/customFunctions/customFunctionsServer-test.js' --config '../unitTests/.mocharc.json'","cover:nats":"cd bin/ && nyc --no-clean --reporter=lcovonly ../node_modules/mocha/bin/_mocha '../unitTests/server/nats/**/*.js' --config '../unitTests/.mocharc.json'","cover:upgrade":"cd bin/ && nyc --no-clean --reporter=lcovonly ../node_modules/mocha/bin/_mocha '../unitTests/upgrade/**/*.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/data_layer/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:{"@fastify/accepts-serializer":"5.1.0","@fastify/autoload":"5.4.0","@fastify/compress":"6.1.1","@fastify/cors":"8.1.0","@fastify/static":"6.5.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:"1.7.4",async:"3.2.3","aws-sdk":"2.1096.0",chalk:"4.1.2","cli-progress":"3.10.0",clone:"2.1.2",esbuild:"^0.14.49","fast-glob":"3.2.11",fastify:"4.8.1","fastify-plugin":"4.2.1","fill-range":"7.0.1","fs-extra":"10.0.1","human-readable-ids":"1.0.4",inquirer:"8.2.2","is-number":"7.0.0",joi:"17.6.0",json2csv:"5.0.7",jsonata:"1.8.6",jsonwebtoken:"8.5.1",lmdb:"2.7.6",lodash:"4.17.21",mathjs:"10.4.0",microtime:"3.1.1",minimist:"1.2.6",mkcert:"1.5.0",moment:"2.29.4",msgpackr:"1.8.2",nats:"2.9.2",needle:"3.1.0","node-ipc":"9.1.4","node-stream-zip":"1.15.0","normalize-path":"^3.0.0",ora:"5.4.1","ordered-binary":"1.3.0",papaparse:"5.3.2",passport:"0.6.0","passport-http":"0.3.0","passport-local":"1.0.0",pino:"8.3.1",pm2:"5.2.0",prompt:"1.2.2","properties-reader":"2.2.0","recursive-iterator":"3.3.0",semver:"7.3.5","stream-chain":"2.2.5","stream-json":"1.7.4",systeminformation:"5.12.4","tar-fs":"2.1.1","truncate-utf8-bytes":"1.0.2",ulidx:"0.3.0",uuid:"9.0.0","validate.js":"0.11.1",yaml:"1.10.2"},devDependencies:{axios:"0.27.2",chai:"4.3.4","chai-integer":"0.1.0",eslint:"8.22.0","eslint-config-prettier":"8.3.0","eslint-plugin-prettier":"3.4.1","eslint-plugin-radar":"0.2.1","hook-std":"2.0.0","intercept-stdout":"0.1.2",mocha:"8.3.2","mocha-teamcity-reporter":"3.0.0","mock-require":"3.0.3","mock-stdin":"1.0.0",newman:"5.2.3","newman-reporter-html":"1.0.5","newman-reporter-htmlextra":"1.21.0","newman-reporter-teamcity":"0.1.11","node-fetch":"2.6.7",nyc:"15.1.0",prettier:"2.3.2",rewire:"5.0.0",rimraf:"3.0.2",sinon:"10.0.0","sinon-chai":"3.7.0"},overrides:{"eslint-plugin-radar":{eslint:"8.22.0"},"newman-reporter-html":{newman:"5.2.3"}}}});var ot=S((NX,UA)=>{"use strict";var nr=Y();nr.initSync();var lF=require("fs-extra"),EF=require("semver"),bi=require("path"),{monotonicFactory:dF}=require("ulidx"),hF=dF(),EA=require("util"),dA=require("child_process"),SF=EA.promisify(dA.exec),fF=dA.spawn,ee=_e(),se=T(),kl=b(),pr=I(),Jo=Vr(),TF=Wo(),pi=Sr(),{encode:ql,decode:hA}=require("msgpackr"),{isEmpty:ps}=kl,SA=Wr(),dX=ds(),mF=mt(),hX=EA.promisify(mF.searchByHash),{connect:RF,StorageType:fA,RetentionPolicy:TA,AckPolicy:mA,DeliverPolicy:Fl,NatsConnection:SX,JetStreamManager:fX,JetStreamClient:TX,StringCodec:mX,JSONCodec:AF,createInbox:xl,StreamSource:RX,headers:OF,toJsMsg:pF,nuid:AX,JetStreamOptions:OX,ErrorCode:lA,nanos:pX}=require("nats"),{PACKAGE_ROOT:NF}=T(),gF=vl(),RA=AF(),IF="clustering",bF=gF.engines[ee.NATS_SERVER_NAME],CF=bi.join(NF,"dependencies"),Vl=bi.join(CF,`${process.platform}-${process.arch}`,ee.NATS_BINARY_NAME),Hl,Gl,Ni,gi,Ii,Qt;UA.exports={runCommand:AA,checkNATSServerInstalled:wF,createConnection:$l,getConnection:Zo,getJetStreamManager:Tn,getJetStream:OA,getNATSReferences:yt,getServerList:UF,createLocalStream:Yl,listStreams:pA,deleteLocalStream:yF,getServerConfig:Ci,listRemoteStreams:DF,viewStream:MF,publishToStream:PF,createWorkQueueStream:BF,addSourceToWorkStream:NA,request:vF,removeSourceFromWorkStream:IA,reloadNATS:Kl,reloadNATSHub:HF,reloadNATSLeaf:GF,extractServerName:gA,requestErrorHandler:qF,updateWorkStream:FF,createLocalTableStream:CA,createTableStreams:VF,purgeTableStream:wA,purgeSchemaTableStreams:kF,getStreamInfo:xF,updateNodeNameLocalStreams:$F,closeConnection:LF};async function AA(e,t=void 0){let{stdout:r,stderr:s}=await SF(e,{cwd:t});if(s)throw new Error(s.replace(`
|
|
1
|
+
"use strict";var Eb=Object.defineProperty;var a=(e,t)=>Eb(e,"name",{value:t,configurable:!0});var S=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var ts=S((T1,db)=>{db.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_temp:{hash_attribute:"id",name:"hdb_temp",schema:"system",attributes:[{attribute:"id"}]}}});var T=S((m1,eh)=>{"use strict";var xe=require("path"),hb=require("fs");function Sb(){let e=__dirname;for(;!hb.existsSync(xe.join(e,"package.json"));){let t=xe.dirname(e);if(t===e)throw new Error("Could not find package root");e=t}return e}a(Sb,"getHDBPackageRoot");var Ht=Sb(),kd="js",Fn=kd,fb="harperdb-config.yaml",Tb="defaultConfig.yaml",mb="hdb",$d=`hdbServer.${Fn}`,xd=`customFunctionsServer.${Fn}`,Yd=`hdbIpcServer.${Fn}`,Rb=`restartHdb.${Fn}`,J_="HarperDB",la="Custom Functions",Ea="Clustering Hub",da="Clustering Leaf",X_="Clustering Ingest Service",Z_="Clustering Reply Service",Ab="foreground.pid",Q_={HDB:J_,IPC:"IPC",CLUSTERING_HUB:Ea,CLUSTERING_LEAF:da,CLUSTERING_INGEST_SERVICE:X_,CLUSTERING_REPLY_SERVICE:Z_,CUSTOM_FUNCTIONS:la,RESTART_HDB:"Restart HDB",INSTALL:"Install",RUN:"Run",STOP:"Stop",UPGRADE:"Upgrade",REGISTER:"Register",JOB:"Job",PM2_LOGROTATE:"pm2-logrotate",CLUSTERING_UPGRADE_4_0_0:"Upgrade-4-0-0"},Ob={HDB:"hdb.log",IPC:"ipc.log",CLUSTERING_HUB:"clustering_hub.log",CLUSTERING_LEAF:"clustering_leaf.log",CLUSTERING_INGEST_SERVICE:"clustering_ingest_service.log",CLUSTERING_REPLY_SERVICE:"clustering_reply_service.log",CUSTOM_FUNCTIONS:"custom_functions.log",INSTALL:"install.log",CLI:"cli.log",PM2:"pm2.log",CLUSTERING_UPGRADE:"clustering_upgrade.log",JOBS:"jobs.log"},pb={NOTIFY:"notify",FATAL:"fatal",ERROR:"error",WARN:"warn",INFO:"info",DEBUG:"debug",TRACE:"trace"},Nb={harperdb:J_,ipc:"IPC","clustering hub":Ea,"clustering leaf":da,"clustering ingest service":X_,"clustering reply service":Z_,"custom functions":la,custom_functions:la,"pm2-logrotate":Q_.PM2_LOGROTATE,logrotate:Q_.PM2_LOGROTATE,clustering:"clustering","clustering config":"clustering config"},gb={CLUSTERING_HUB_PROC_DESCRIPTOR:Ea,CLUSTERING_LEAF_PROC_DESCRIPTOR:da,CLUSTERING_INGEST_PROC_DESCRIPTOR:X_,CLUSTERING_REPLY_SERVICE_DESCRIPTOR:Z_},ua={HDB:xe.join(Ht,"server/harperdb"),IPC:xe.join(Ht,"server/ipc"),CUSTOM_FUNCTIONS:xe.join(Ht,"server/customFunctions"),CLUSTERING_HUB:xe.join(Ht,"server/nats"),CLUSTERING_LEAF:xe.join(Ht,"server/nats")},Ib={HDB:xe.join(ua.HDB,$d),IPC:xe.join(ua.IPC,Yd),CUSTOM_FUNCTIONS:xe.join(ua.CUSTOM_FUNCTIONS,xd)},bb={HDB:xe.join(Ht,"launchServiceScripts/launchHarperDB.js"),CUSTOM_FUNCTIONS:xe.join(Ht,"launchServiceScripts/launchCustomFunctions.js"),NATS_INGEST_SERVICE:xe.join(Ht,"launchServiceScripts/launchNatsIngestService.js"),NATS_REPLY_SERVICE:xe.join(Ht,"launchServiceScripts/launchNatsReplyService.js"),NODES_UPGRADE_4_0_0:xe.resolve(Ht,"launchServiceScripts/launchUpdateNodes4-0-0.js")},wb={SUPER_USER:"super_user",CLUSTER_USER:"cluster_user"},Kd="support@harperdb.io",Cb="customer-success@harperdb.io",Wd=1,Lb=4141,Qd="https://harperdbhelp.zendesk.com/hc/en-us/requests/new",Ub="https://www.harperdb.io/product",yb=`For support, please submit a request at ${Qd} or contact ${Kd}`,Jd=`For license support, please contact ${Cb}`,Db="None of the specified records were found.",Mb="hash attribute not found",Pb=`Your current license only supports ${Wd} role. ${Jd}`,Bb="Your current license only supports 3 connections to a node.",vb="127.0.0.1",Hb=1,qb=/^\.$/,Gb=/^\.\.$/,Fb="U+002E",Vb=/\//g,kb="U+002F",$b=/U\+002F/g,xb=/^U\+002E$/,Yb=/^U\+002EU\+002E$/,Kb="d",Wb=999999,Qb="*",Jb="--max-old-space-size=",Xb="system",Zb="__hdb_hash",zb=".harperdb",jb=".hdb",ew="keys",tw="hdb_boot_properties.file",rw=".updateConfig.json",sw="SIGTSTP",nw=24,iw=6e4,aw=448,ow="blob",cw="trash",_w="schema",uw="transactions",lw=".count",Ew="id",dw="install_log.log",hw="run_log.log",Sw="PROCESS_NAME",fw={SETTINGS_PATH_KEY:"settings_path"},Xd=require("lodash"),Tw={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",CLUSTERING_PORT:"CLUSTERING_PORT",HDB_ROOT:"HDB_ROOT",SERVER_PORT:"SERVER_PORT",NODE_NAME:"NODE_NAME",CLUSTERING:"CLUSTERING"},mw={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},Rw={DATA_VERSION:"data_version",UPGRADE_VERSION:"upgrade_version"},Aw={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"},Ow={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"},dt="hdb_internal:",pw={CREATE_SCHEMA:dt+"create_schema",CREATE_TABLE:dt+"create_table",CREATE_ATTRIBUTE:dt+"create_attribute",ADD_USER:dt+"add_user",ALTER_USER:dt+"alter_user",DROP_USER:dt+"drop_user",HDB_NODES:dt+"hdb_nodes",HDB_USERS:dt+"hdb_users",HDB_WORKERS:dt+"hdb_workers",CATCHUP:dt+"catchup",SCHEMA_CATCHUP:dt+"schema_catchup",WORKER_ROOM:dt+"cluster_workers"},Nw={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"},gw="060493.ks",Iw=".license",bw={CREATED:"CREATED",IN_PROGRESS:"IN_PROGRESS",COMPLETE:"COMPLETE",ERROR:"ERROR"},g={INSERT:"insert",UPDATE:"update",UPSERT:"upsert",SEARCH_BY_CONDITIONS:"search_by_conditions",SEARCH_BY_HASH:"search_by_hash",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_TABLE:"create_table",CREATE_ATTRIBUTE:"create_attribute",DROP_SCHEMA:"drop_schema",DROP_TABLE:"drop_table",DESCRIBE_SCHEMA:"describe_schema",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",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",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",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",DROP_CUSTOM_FUNCTION:"drop_custom_function",ADD_CUSTOM_FUNCTION_PROJECT:"add_custom_function_project",DROP_CUSTOM_FUNCTION_PROJECT:"drop_custom_function_project",PACKAGE_CUSTOM_FUNCTION_PROJECT:"package_custom_function_project",DEPLOY_CUSTOM_FUNCTION_PROJECT:"deploy_custom_function_project",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"},ww={CSV:".csv",JSON:".json"},Cw={AWS_ACCESS_KEY:"aws_access_key_id",AWS_SECRET:"aws_secret_access_key",AWS_BUCKET:"bucket",AWS_FILE_KEY:"key"},Lw={SELECT:"select",INSERT:"insert",UPDATE:"update",DELETE:"delete"},Cr={};Cr[g.CREATE_SCHEMA]=g.CREATE_SCHEMA;Cr[g.CREATE_TABLE]=g.CREATE_TABLE;Cr[g.CREATE_ATTRIBUTE]=g.CREATE_ATTRIBUTE;Cr[g.INSERT]=g.INSERT;Cr[g.UPDATE]=g.UPDATE;Cr[g.UPSERT]=g.UPSERT;Cr[g.DELETE]=g.DELETE;var J=Object.create(null);J[g.DESCRIBE_ALL]=g.DESCRIBE_ALL;J[g.DESCRIBE_TABLE]=g.DESCRIBE_TABLE;J[g.DESCRIBE_SCHEMA]=g.DESCRIBE_SCHEMA;J[g.READ_LOG]=g.READ_LOG;J[g.ADD_NODE]=g.ADD_NODE;J[g.LIST_USERS]=g.LIST_USERS;J[g.LIST_ROLES]=g.LIST_ROLES;J[g.USER_INFO]=g.USER_INFO;J[g.SQL]=g.SQL;J[g.GET_JOB]=g.GET_JOB;J[g.SEARCH_JOBS_BY_START_DATE]=g.SEARCH_JOBS_BY_START_DATE;J[g.DELETE_FILES_BEFORE]=g.DELETE_FILES_BEFORE;J[g.EXPORT_LOCAL]=g.EXPORT_LOCAL;J[g.EXPORT_TO_S3]=g.EXPORT_TO_S3;J[g.CLUSTER_STATUS]=g.CLUSTER_STATUS;J[g.REMOVE_NODE]=g.REMOVE_NODE;J[g.RESTART]=g.RESTART;J[g.CUSTOM_FUNCTIONS_STATUS]=g.CUSTOM_FUNCTIONS_STATUS;J[g.GET_CUSTOM_FUNCTIONS]=g.GET_CUSTOM_FUNCTIONS;J[g.GET_CUSTOM_FUNCTION]=g.GET_CUSTOM_FUNCTION;J[g.SET_CUSTOM_FUNCTION]=g.SET_CUSTOM_FUNCTION;J[g.DROP_CUSTOM_FUNCTION]=g.DROP_CUSTOM_FUNCTION;J[g.ADD_CUSTOM_FUNCTION_PROJECT]=g.ADD_CUSTOM_FUNCTION_PROJECT;J[g.DROP_CUSTOM_FUNCTION_PROJECT]=g.DROP_CUSTOM_FUNCTION_PROJECT;J[g.PACKAGE_CUSTOM_FUNCTION_PROJECT]=g.PACKAGE_CUSTOM_FUNCTION_PROJECT;J[g.DEPLOY_CUSTOM_FUNCTION_PROJECT]=g.DEPLOY_CUSTOM_FUNCTION_PROJECT;var Uw={RUN:"run",INSTALL:"install",REGISTER:"register",STOP:"stop",RESTART:"restart",VERSION:"version",UPGRADE:"upgrade"},yw={point:"point",lineString:"lineString",multiLineString:"multiLineString",multiPoint:"multiPoint",multiPolygon:"multiPolygon",polygon:"polygon"},Zd={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",IPC_SERVER_PORT:"IPC_SERVER_PORT",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"},Dw=Xd.invert(Zd),f={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_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",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",HTTP_THREADS:"http_threads",IPC_NETWORK_PORT:"ipc_network_port",LOCALSTUDIO_ENABLED:"localStudio_enabled",LOGGING_FILE:"logging_file",LOGGING_LEVEL:"logging_level",LOGGING_ROOT:"logging_root",LOGGING_ROTATION_COMPRESS:"logging_rotation_compress",LOGGING_ROTATION_DATEFORMAT:"logging_rotation_dateFormat",LOGGING_ROTATION_MAXSIZE:"logging_rotation_maxSize",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",LOGGING_STDSTREAMS:"logging_stdStreams",LOGGING_AUDITLOG:"logging_auditLog",OPERATIONSAPI_AUTHENTICATION_OPERATIONTOKENTIMEOUT:"operationsApi_authentication_operationTokenTimeout",OPERATIONSAPI_AUTHENTICATION_REFRESHTOKENTIMEOUT:"operationsApi_authentication_refreshTokenTimeout",OPERATIONSAPI_FOREGROUND:"operationsApi_foreground",OPERATIONSAPI_TLS_CERTIFICATE:"operationsApi_tls_certificate",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_TLS_PRIVATEKEY:"operationsApi_tls_privateKey",OPERATIONSAPI_TLS_CERT_AUTH:"operationsApi_tls_certificateAuthority",OPERATIONSAPI_NETWORK_TIMEOUT:"operationsApi_network_timeout",OPERATIONSAPI_NODEENV:"operationsApi_nodeEnv",ROOTPATH:"rootPath",STORAGE_WRITEASYNC:"storage_writeAsync",STORAGE_OVERLAPPINGSYNC:"storage_overlappingSync"},Mw={hdb_root_key:f.ROOTPATH,hdb_root:f.ROOTPATH,server_port_key:f.OPERATIONSAPI_NETWORK_PORT,server_port:f.OPERATIONSAPI_NETWORK_PORT,cert_key:f.OPERATIONSAPI_TLS_CERTIFICATE,certificate:f.OPERATIONSAPI_TLS_CERTIFICATE,private_key_key:f.OPERATIONSAPI_TLS_PRIVATEKEY,private_key:f.OPERATIONSAPI_TLS_PRIVATEKEY,http_secure_enabled_key:f.OPERATIONSAPI_NETWORK_HTTPS,https_on:f.OPERATIONSAPI_NETWORK_HTTPS,cors_enabled_key:f.OPERATIONSAPI_NETWORK_CORS,cors_on:f.OPERATIONSAPI_NETWORK_CORS,cors_whitelist_key:f.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_whitelist:f.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_accesslist_key:f.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_accesslist:f.OPERATIONSAPI_NETWORK_CORSACCESSLIST,log_level_key:f.LOGGING_LEVEL,log_level:f.LOGGING_LEVEL,log_path_key:f.LOGGING_ROOT,log_path:f.LOGGING_ROOT,log_daily_rotate:f.LOGGING_ROTATION_ROTATE,log_rotate:f.LOGGING_ROTATION_ROTATE,log_rotate_max_size:f.LOGGING_ROTATION_MAXSIZE,log_rotate_retain:f.LOGGING_ROTATION_RETAIN,log_rotate_compress:f.LOGGING_ROTATION_COMPRESS,log_rotate_date_format:f.LOGGING_ROTATION_DATEFORMAT,log_rotate_rotate_module:f.LOGGING_ROTATION_ROTATEMODULE,log_rotate_worker_interval:f.LOGGING_ROTATION_WORKERINTERVAL,log_rotate_rotate_interval:f.LOGGING_ROTATION_ROTATEINTERVAL,log_rotate_timezone:f.LOGGING_ROTATION_TIMEZONE,props_env_key:f.OPERATIONSAPI_NODEENV,node_env:f.OPERATIONSAPI_NODEENV,clustering_node_name_key:f.CLUSTERING_NODENAME,node_name:f.CLUSTERING_NODENAME,clustering_enabled_key:f.CLUSTERING_ENABLED,clustering:f.CLUSTERING_ENABLED,max_http_threads:f.HTTP_THREADS,max_hdb_processes:f.HTTP_THREADS,server_timeout_key:f.OPERATIONSAPI_NETWORK_TIMEOUT,server_timeout_ms:f.OPERATIONSAPI_NETWORK_TIMEOUT,server_keep_alive_timeout_key:f.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT,server_keep_alive_timeout:f.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT,server_headers_timeout_key:f.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT,server_headers_timeout:f.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT,disable_transaction_log_key:f.LOGGING_AUDITLOG,disable_transaction_log:f.LOGGING_AUDITLOG,operation_token_timeout_key:f.OPERATIONSAPI_AUTHENTICATION_OPERATIONTOKENTIMEOUT,operation_token_timeout:f.OPERATIONSAPI_AUTHENTICATION_OPERATIONTOKENTIMEOUT,refresh_token_timeout_key:f.OPERATIONSAPI_AUTHENTICATION_REFRESHTOKENTIMEOUT,refresh_token_timeout:f.OPERATIONSAPI_AUTHENTICATION_REFRESHTOKENTIMEOUT,ipc_server_port:f.IPC_NETWORK_PORT,custom_functions_enabled_key:f.CUSTOMFUNCTIONS_ENABLED,custom_functions:f.CUSTOMFUNCTIONS_ENABLED,custom_functions_port_key:f.CUSTOMFUNCTIONS_NETWORK_PORT,custom_functions_port:f.CUSTOMFUNCTIONS_NETWORK_PORT,custom_functions_directory_key:f.CUSTOMFUNCTIONS_ROOT,custom_functions_directory:f.CUSTOMFUNCTIONS_ROOT,max_custom_function_processes:f.HTTP_THREADS,log_to_file:f.LOGGING_FILE,log_to_stdstreams:f.LOGGING_STDSTREAMS,run_in_foreground:f.OPERATIONSAPI_FOREGROUND,local_studio_on:f.LOCALSTUDIO_ENABLED,clustering_port:f.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT,clustering_user:f.CLUSTERING_USER,clustering_enabled:f.CLUSTERING_ENABLED,clustering_hubserver_cluster_name:f.CLUSTERING_HUBSERVER_CLUSTER_NAME,clustering_hubserver_cluster_network_port:f.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT,clustering_hubserver_cluster_network_routes:f.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,clustering_hubserver_leafnodes_network_port:f.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT,clustering_hubserver_network_port:f.CLUSTERING_HUBSERVER_NETWORK_PORT,clustering_leafserver_network_port:f.CLUSTERING_LEAFSERVER_NETWORK_PORT,clustering_leafserver_network_routes:f.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,clustering_nodename:f.CLUSTERING_NODENAME,clustering_tls_certificate:f.CLUSTERING_TLS_CERTIFICATE,clustering_tls_privatekey:f.CLUSTERING_TLS_PRIVATEKEY,clustering_tls_certificateauthority:f.CLUSTERING_TLS_CERT_AUTH,clustering_tls_insecure:f.CLUSTERING_TLS_INSECURE,customfunctions_enabled:f.CUSTOMFUNCTIONS_ENABLED,customfunctions_network_port:f.CUSTOMFUNCTIONS_NETWORK_PORT,customfunctions_tls_certificate:f.CUSTOMFUNCTIONS_TLS_CERTIFICATE,customfunctions_network_cors:f.CUSTOMFUNCTIONS_NETWORK_CORS,customfunctions_network_corsaccesslist:f.CUSTOMFUNCTIONS_NETWORK_CORSACCESSLIST,customfunctions_network_headerstimeout:f.CUSTOMFUNCTIONS_NETWORK_HEADERSTIMEOUT,customfunctions_network_https:f.CUSTOMFUNCTIONS_NETWORK_HTTPS,customfunctions_network_keepalivetimeout:f.CUSTOMFUNCTIONS_NETWORK_KEEPALIVETIMEOUT,customfunctions_tls_privatekey:f.CUSTOMFUNCTIONS_TLS_PRIVATEKEY,customfunctions_tls_certificateauthority:f.CUSTOMFUNCTIONS_TLS_CERT_AUTH,customfunctions_network_timeout:f.CUSTOMFUNCTIONS_NETWORK_TIMEOUT,customfunctions_nodeenv:f.CUSTOMFUNCTIONS_NODEENV,http_threads:f.HTTP_THREADS,customfunctions_processes:f.HTTP_THREADS,customfunctions_root:f.CUSTOMFUNCTIONS_ROOT,ipc_network_port:f.IPC_NETWORK_PORT,localstudio_enabled:f.LOCALSTUDIO_ENABLED,logging_file:f.LOGGING_FILE,logging_level:f.LOGGING_LEVEL,logging_root:f.LOGGING_ROOT,logging_rotation_compress:f.LOGGING_ROTATION_COMPRESS,logging_rotation_dateformat:f.LOGGING_ROTATION_DATEFORMAT,logging_rotation_maxsize:f.LOGGING_ROTATION_MAXSIZE,logging_rotation_retain:f.LOGGING_ROTATION_RETAIN,logging_rotation_rotate:f.LOGGING_ROTATION_ROTATE,logging_rotation_rotateinterval:f.LOGGING_ROTATION_ROTATEINTERVAL,logging_rotation_rotatemodule:f.LOGGING_ROTATION_ROTATEMODULE,logging_rotation_timezone:f.LOGGING_ROTATION_TIMEZONE,logging_rotation_workerinterval:f.LOGGING_ROTATION_WORKERINTERVAL,logging_stdstreams:f.LOGGING_STDSTREAMS,logging_auditlog:f.LOGGING_AUDITLOG,operationsapi_authentication_operationtokentimeout:f.OPERATIONSAPI_AUTHENTICATION_OPERATIONTOKENTIMEOUT,operationsapi_authentication_refreshtokentimeout:f.OPERATIONSAPI_AUTHENTICATION_REFRESHTOKENTIMEOUT,operationsapi_foreground:f.OPERATIONSAPI_FOREGROUND,operationsapi_tls_certificate:f.OPERATIONSAPI_TLS_CERTIFICATE,operationsapi_network_cors:f.OPERATIONSAPI_NETWORK_CORS,operationsapi_network_corsaccesslist:f.OPERATIONSAPI_NETWORK_CORSACCESSLIST,operationsapi_network_headerstimeout:f.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT,operationsapi_network_https:f.OPERATIONSAPI_NETWORK_HTTPS,operationsapi_network_keepalivetimeout:f.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT,operationsapi_network_port:f.OPERATIONSAPI_NETWORK_PORT,operationsapi_tls_privatekey:f.OPERATIONSAPI_TLS_PRIVATEKEY,operationsapi_tls_certificateauthority:f.OPERATIONSAPI_TLS_CERT_AUTH,operationsapi_network_timeout:f.OPERATIONSAPI_NETWORK_TIMEOUT,operationsapi_nodeenv:f.OPERATIONSAPI_NODEENV,operationsapi_root:f.ROOTPATH,rootpath:f.ROOTPATH,storage_writeasync:f.STORAGE_WRITEASYNC,storage_overlappingsync:f.STORAGE_OVERLAPPINGSYNC},Pw={csv_file_load:"csv_file_load",csv_data_load:g.CSV_DATA_LOAD,csv_url_load:g.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"},Bw={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"},vw={BIDIRECTIONAL:"BIDIRECTIONAL",OUTBOUND:"OUTBOUND",INBOUND:"INBOUND"},Hw={FILE_SYSTEM:"fs",LMDB:"lmdb"},qw={API_CALL_DEFAULT:1e4,VERSION_DEFAULT:"2.2.0"},Gw={DEVELOPMENT:8192,DEFAULT:512},Fw={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"},Vw={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"},kw={ENOENT:"ENOENT",EACCES:"EACCES"},zd={CREATED_TIME:"__createdtime__",UPDATED_TIME:"__updatedtime__"},$w="__clustering__",xw=Object.values(zd),Yw=15984864e5,jd={LESS:"<",LESS_OR_EQ:"<=",GREATER:">",GREATER_OR_EQ:">=",BETWEEN:"..."},Kw=Xd.invert(jd),Ww={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"},Qw=111,Jw=`\r
|
|
2
|
+
`,Xw={READ:"read",INSERT:"insert",UPDATE:"update",DELETE:"delete"},Zw=["*","%"],zw="unauthorized_access",jw="func_val",eC={HASH_VALUE:"hash_value",TIMESTAMP:"timestamp",USERNAME:"username"},tC={JWT_PRIVATE_KEY_NAME:".jwtPrivate.key",JWT_PUBLIC_KEY_NAME:".jwtPublic.key",JWT_PASSPHRASE_NAME:".jwtPass"},rC="hdb_ipc_server",sC="hdb_ipc_client_",nC={RESTART:"restart",CHILD_STARTED:"child_started",CHILD_STOPPED:"child_stopped",SCHEMA:"schema",USER:"user",CLUSTER_STATUS_RESPONSE:"cluster_status_response",CLUSTER_STATUS_REQUEST:"cluster_status_request"},iC={HDB_CORE:"hdb_core",CUSTOM_FUNCTIONS:"custom_functions"},aC={STOPPED:"stopped",ONLINE:"online"},oC="3.x.x";eh.exports={LOCAL_HARPERDB_OPERATIONS:J,HDB_SUPPORT_ADDRESS:Kd,HDB_SUPPORT_URL:Qd,HDB_PRICING_URL:Ub,SUPPORT_HELP_MSG:yb,LICENSE_HELP_MSG:Jd,HDB_PROC_NAME:$d,HDB_PROC_DESCRIPTOR:J_,CLUSTERING_LEAF_PROC_DESCRIPTOR:da,CLUSTERING_HUB_PROC_DESCRIPTOR:Ea,SYSTEM_SCHEMA_NAME:Xb,HASH_FOLDER_NAME:Zb,HDB_HOME_DIR_NAME:zb,UPDATE_FILE_NAME:rw,LICENSE_KEY_DIR_NAME:ew,BOOT_PROPS_FILE_NAME:tw,JOB_TYPE_ENUM:Pw,JOB_STATUS_ENUM:bw,SYSTEM_TABLE_NAMES:Aw,SYSTEM_TABLE_HASH_ATTRIBUTES:Ow,OPERATIONS_ENUM:g,VALID_S3_FILE_TYPES:ww,S3_BUCKET_AUTH_KEYS:Cw,VALID_SQL_OPS_ENUM:Lw,GEO_CONVERSION_ENUM:yw,HDB_SETTINGS_NAMES:Zd,HDB_SETTINGS_NAMES_REVERSE_LOOKUP:Dw,SERVICE_ACTIONS_ENUM:Uw,CLUSTER_MESSAGE_TYPE_ENUM:Bw,CLUSTER_CONNECTION_DIRECTION_ENUM:vw,CLUSTER_EVENTS_DEFS_ENUM:Fw,PERIOD_REGEX:qb,DOUBLE_PERIOD_REGEX:Gb,UNICODE_PERIOD:Fb,FORWARD_SLASH_REGEX:Vb,UNICODE_FORWARD_SLASH:kb,ESCAPED_FORWARD_SLASH_REGEX:$b,ESCAPED_PERIOD_REGEX:xb,ESCAPED_DOUBLE_PERIOD_REGEX:Yb,REG_KEY_FILE_NAME:gw,RESTART_TIMEOUT_MS:iw,HDB_FILE_PERMISSIONS:aw,SCHEMA_DIR_NAME:_w,TRANSACTIONS_DIR_NAME:uw,LIMIT_COUNT_NAME:lw,ID_ATTRIBUTE_STRING:Ew,INSERT_MODULE_ENUM:mw,UPGRADE_JSON_FIELD_NAMES_ENUM:Rw,RESTART_CODE:sw,RESTART_CODE_NUM:nw,CLUSTER_OPERATIONS:Cr,SYSTEM_DEFAULT_ATTRIBUTE_NAMES:Nw,HDB_INTERNAL_SC_CHANNEL_PREFIX:dt,INTERNAL_SC_CHANNELS:pw,CLUSTERING_MESSAGE_TYPES:Ww,HDB_FILE_SUFFIX:jb,BLOB_FOLDER_NAME:ow,HDB_TRASH_DIR:cw,ORIGINATOR_SET_VALUE:Qw,LICENSE_VALUES:qw,RAM_ALLOCATION_ENUM:Gw,STORAGE_TYPES_ENUM:Hw,TIME_STAMP_NAMES_ENUM:zd,TIME_STAMP_NAMES:xw,PERMS_UPDATE_RELEASE_TIMESTAMP:Yw,SEARCH_NOT_FOUND_MESSAGE:Db,SEARCH_ATTRIBUTE_NOT_FOUND:Mb,LICENSE_ROLE_DENIED_RESPONSE:Pb,LICENSE_MAX_CONNS_REACHED:Bb,BASIC_LICENSE_MAX_NON_CU_ROLES:Wd,BASIC_LICENSE_CLUSTER_CONNECTION_LIMIT_WS_ERROR_CODE:Lb,VALUE_SEARCH_COMPARATORS:jd,VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP:Kw,LICENSE_FILE_NAME:Iw,WEBSOCKET_CLOSE_CODE_DESCRIPTION_LOOKUP:Vw,NEW_LINE:Jw,BASIC_LICENSE_MAX_CLUSTER_USER_ROLES:Hb,MOMENT_DAYS_TAG:Kb,API_TURNOVER_SEC:Wb,LOOPBACK:vb,CODE_EXTENSION:Fn,WILDCARD_SEARCH_VALUE:Qb,NODE_ERROR_CODES:kw,JAVASCRIPT_EXTENSION:kd,PERMS_CRUD_ENUM:Xw,UNAUTHORIZED_PERMISSION_NAME:zw,SEARCH_WILDCARDS:Zw,FUNC_VAL:jw,READ_AUDIT_LOG_SEARCH_TYPES_ENUM:eC,JWT_ENUM:tC,CLUSTERING_FLAG:$w,RUN_LOG:hw,INSTALL_LOG:dw,IPC_SERVER_MODULE:Yd,HDB_IPC_SERVER:rC,IPC_EVENT_TYPES:nC,HDB_IPC_CLIENT_PREFIX:sC,CUSTOM_FUNCTION_PROC_NAME:xd,CUSTOM_FUNCTION_PROC_DESCRIPTOR:la,SERVICES:iC,MEM_SETTING_KEY:Jb,HDB_RESTART_SCRIPT:Rb,PROCESS_DESCRIPTORS:Q_,SERVICE_SERVERS:Ib,SERVICE_SERVERS_CWD:ua,PROCESS_DESCRIPTORS_VALIDATE:Nb,LAUNCH_SERVICE_SCRIPTS:bb,LOG_LEVELS:pb,PROCESS_NAME_ENV_PROP:Sw,PROCESS_LOG_NAMES:Ob,PM2_PROCESS_STATUSES:aC,CONFIG_PARAM_MAP:Mw,CONFIG_PARAMS:f,HDB_CONFIG_FILE:fb,HDB_DEFAULT_CONFIG_FILE:Tb,ROLE_TYPES_ENUM:wb,BOOT_PROP_PARAMS:fw,INSTALL_PROMPTS:Tw,HDB_ROOT_DIR_NAME:mb,CLUSTERING_PROCESSES:gb,FOREGROUND_PID_FILE:Ab,PACKAGE_ROOT:Ht,PRE_4_0_0_VERSION:oC}});var z_=S((R1,sh)=>{"use strict";var th=require("minimist");sh.exports=cC;function cC(e=[],t=!1){if(!Array.isArray(e))return{};let r,s;t?(r=rh(process.env),s=rh(th(process.argv))):(r=process.env,s=th(process.argv));let n={};for(let i=0,o=e.length;i<o;i++){let c=e[i];s[c]!==void 0?n[c]=s[c].toString().trim():r[c]!==void 0&&(n[c]=r[c].toString().trim())}return n}a(cC,"assignCMDENVVariables");function rh(e){let t,r=Object.keys(e),s=r.length,n={};for(;s--;)t=r[s],n[t.toLowerCase()]=e[t];return n}a(rh,"objKeysToLowerCase")});var I=S((A1,uh)=>{"use strict";var rs=require("fs-extra"),ss=require("path"),ih=require("yaml"),ah=require("properties-reader"),me=T(),_C=z_(),uC=require("os"),{PACKAGE_ROOT:tu}=T(),rt={notify:7,fatal:6,error:5,warn:4,info:3,debug:2,trace:1},ha=ss.join(tu,"logs"),Lr=process.env.pm_id===void 0,lC=ss.join(tu,"config/yaml/",me.HDB_DEFAULT_CONFIG_FILE),ru=process.env.PROCESS_NAME===void 0?me.PROCESS_DESCRIPTORS.INSTALL:process.env.PROCESS_NAME,ks,Qt,cr,tt,j_,$s;$s===void 0&&oh();uh.exports={createLogFile:EC,notify:SC,fatal:fC,error:eu,warn:TC,info:dC,debug:hC,trace:_h,setLogLevel:RC,log_level:tt};function oh(){try{if($s===void 0){let e=mC();$s=ah(e),{level:tt,config_log_path:j_,to_file:Qt,to_stream:cr}=AC($s.get("settings_path"))}}catch(e){if($s=void 0,e.code===me.NODE_ERROR_CODES.ENOENT){let t=_C(Object.keys(me.CONFIG_PARAM_MAP),!0);for(let i in t){let o=me.CONFIG_PARAM_MAP[i];o&&o.toLowerCase();let c=t[i];if(o===me.CONFIG_PARAMS.LOGGING_LEVEL){tt=c;continue}if(o===me.CONFIG_PARAMS.LOGGING_STDSTREAMS){cr=c;continue}o===me.CONFIG_PARAMS.LOGGING_FILE&&(Qt=o)}let{default_level:r,default_to_file:s,default_to_stream:n}=OC();Qt=Qt===void 0?s:Qt,Qt=nh(Qt),cr=cr===void 0?n:cr,cr=nh(cr),tt=tt===void 0?r:tt,j_=ha;return}throw eu("Error initializing log settings"),eu(e),e}}a(oh,"initLogSettings");function EC(e,t){if(!Lr){_h("createLogFile should only be used if the process is not being managed by pm2");return}$s===void 0&&oh(),ru=t;let r;e===me.PROCESS_LOG_NAMES.INSTALL?r=ha:r=j_,Qt&&(ks=ss.join(r,e),rs.ensureFileSync(ks))}a(EC,"createLogFile");function ns(e,t){let r=new Date(Date.now()).toISOString(),s="",n=t.length,i=n-1;for(let o=0;o<n;o++){let c=t[o];c instanceof Error&&c.stack?s+=c.stack:typeof c=="object"?s+=JSON.stringify(c):s+=c,o<i&&(s+=" ")}return`{"process_name": "${ru}", "level": "${e}", "timestamp": "${r}", "message": "${s}"}
|
|
3
|
+
`}a(ns,"createLogRecord");function ch(e){ks===void 0&&(ru=me.PROCESS_DESCRIPTORS.INSTALL,rs.ensureDirSync(ha),ks=ss.join(ha,me.PROCESS_LOG_NAMES.INSTALL),rs.ensureFileSync(ks)),rs.appendFileSync(ks,e)}a(ch,"writeToLogFile");function Sa(e){Qt&&ch(e),cr&&process.stdout.write(e)}a(Sa,"nonPm2LogStdOut");function su(e){Qt&&ch(e),cr&&process.stderr.write(e)}a(su,"nonPm2LogStdErr");function dC(...e){if(rt[tt]<=rt.info){let t=ns("info",e);if(Lr){Sa(t);return}process.stdout.write(t)}}a(dC,"info");function _h(...e){if(rt[tt]<=rt.trace){let t=ns("trace",e);if(Lr){Sa(t);return}process.stdout.write(t)}}a(_h,"trace");function eu(...e){if(rt[tt]<=rt.error){let t=ns("error",e);if(Lr){su(t);return}process.stderr.write(t)}}a(eu,"error");function hC(...e){if(rt[tt]<=rt.debug){let t=ns("debug",e);if(Lr){Sa(t);return}process.stdout.write(t)}}a(hC,"debug");function SC(...e){if(rt[tt]<=rt.notify){let t=ns("notify",e);if(Lr){Sa(t);return}process.stdout.write(t)}}a(SC,"notify");function fC(...e){if(rt[tt]<=rt.fatal){let t=ns("fatal",e);if(Lr){su(t);return}process.stderr.write(t)}}a(fC,"fatal");function TC(...e){if(rt[tt]<=rt.warn){let t=ns("warn",e);if(Lr){su(t);return}process.stderr.write(t)}}a(TC,"warn");function mC(){let e;try{e=uC.homedir()}catch{e=process.env.HOME}e||(e="~/");let t=ss.join(e,me.HDB_HOME_DIR_NAME,me.BOOT_PROPS_FILE_NAME);return rs.existsSync(t)||(t=ss.join(tu,"utility/hdb_boot_properties.file")),t}a(mC,"getPropsFilePath");function RC(e){tt=e}a(RC,"setLogLevel");function nh(e){return e===!0||typeof e=="string"&&e.toLowerCase()==="true"}a(nh,"autoCastBoolean");function AC(e){try{if(e.includes("config/settings.js")){let o=ah(e);return{level:o.get(me.HDB_SETTINGS_NAMES.LOG_LEVEL_KEY),config_log_path:ss.dirname(o.get(me.HDB_SETTINGS_NAMES.LOG_PATH_KEY)),to_file:o.get(me.HDB_SETTINGS_NAMES.LOG_TO_FILE),to_stream:o.get(me.HDB_SETTINGS_NAMES.LOG_TO_STDSTREAMS)}}let t=ih.parseDocument(rs.readFileSync(e,"utf8")),r=t.getIn(["logging","level"]),s=t.getIn(["logging","root"]),n=t.getIn(["logging","file"]),i=t.getIn(["logging","stdStreams"]);return{level:r,config_log_path:s,to_file:n,to_stream:i}}catch(t){if(t.code===me.NODE_ERROR_CODES.ENOENT)throw t;console.error("Error accessing config file for logging"),console.error(t)}}a(AC,"getLogConfig");function OC(){try{let e=ih.parseDocument(rs.readFileSync(lC,"utf8")),t=e.getIn(["logging","level"]),r=e.getIn(["logging","file"]),s=e.getIn(["logging","stdStreams"]);return{default_level:t,default_to_file:r,default_to_stream:s}}catch(e){console.error("Error accessing default config file for logging"),console.error(e)}}a(OC,"getDefaultConfig")});var Eh=S((O1,lh)=>{"use strict";var pC=require("util"),NC=require("path"),gC=require("child_process"),IC=pC.promisify(gC.execFile),bC=1e3*1e3*10;lh.exports={findPs:wC};async function wC(e){let t={};try{await Promise.all(["comm","args","ppid","uid","%cpu","%mem"].map(async r=>{let{stdout:s}=await IC("ps",["wwxo",`pid,${r}`],{maxBuffer:bC});for(let n of s.trim().split(`
|
|
4
|
+
`).slice(1)){n=n.trim();let[i]=n.split(" ",1),o=n.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,s])=>({pid:Number.parseInt(r,10),name:NC.basename(s.comm),cmd:s.args,ppid:Number.parseInt(s.ppid,10),uid:Number.parseInt(s.uid,10),cpu:Number.parseFloat(s["%cpu"]),memory:Number.parseFloat(s["%mem"])}))}a(wC,"findPs")});var Ye=S((p1,hh)=>{"use strict";var CC="__dbis__",LC="__environment_name__",UC="__dbi_defintion__",yC={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"},DC=["__createdtime__","__updatedtime__"],MC="\uFFFF",dh={TIMESTAMP:"timestamp",HASH_VALUE:"hash_value",USER_NAME:"user_name"},PC=Object.values(dh);hh.exports={INTERNAL_DBIS_NAME:CC,DBI_DEFINITION_NAME:UC,SEARCH_TYPES:yC,TIMESTAMP_NAMES:DC,MAX_SEARCH_KEY_LENGTH:256,ENVIRONMENT_NAME_KEY:LC,TRANSACTIONS_DBI_NAMES_ENUM:dh,TRANSACTIONS_DBIS:PC,OVERFLOW_MARKER:MC}});var Ke=S((N1,Nh)=>{"use strict";var Sh=T(),fh=Ye(),Th={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},mh=a(e=>`${e} Check logs and try again.`,"CHECK_LOGS_WRAPPER"),Rh={500:mh("There was an error processing your request."),400:"Invalid request"},BC=Rh[Th.INTERNAL_SERVER_ERROR],vC={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.`},HC={CONFIG_VALIDATION:e=>`HarperDB config file validation error: ${e}`},qC={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"},GC={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_ARRAY:"ids must be an array",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 ${fh.INTERNAL_DBIS_NAME}`,CANNOT_DROP_INTERNAL_DBIS_NAME:`cannot drop a dbi named ${fh.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"},FC={ATTR_NAME_LENGTH_ERR:e=>`transaction aborted due to attribute name ${e} being too long. Attribute names cannot be longer than ${Sh.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 ${Sh.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"},Ah={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"},VC={DEFAULT_INVALID_REQUEST:"Invalid request",OP_AUTH_PERMS_ERROR:"This operation is not authorized due to role restrictions and/or invalid schema 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' schema, tables and records are used internally by HarperDB and cannot be updated or removed."},kC={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 schema metadata for '${e}'`,SCHEMA_TABLE_PERM_ERROR:(e,t)=>`Your role does not have permission to view schema.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`},$C={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=>`Schema '${e}' does not exist`,SCHEMA_EXISTS_ERR:e=>`Schema '${e}' already exists`,TABLE_EXISTS_ERR:(e,t)=>`Table '${t}' already exists in schema '${e}'`,SCHEMA_REQUIRED_ERR:"schema is required",TABLE_NOT_FOUND:(e,t)=>`Table '${e}.${t}' does not exist`,TABLE_REQUIRED_ERR:"table is required"},xC={OUTER_JOIN_TRANSLATION_ERROR:"There was an error translating the final SQL outer join data."},YC={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`},Oh={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.`},ph={INVALID_IPC_DATA_TYPE:"Invalid IPC event data type, must be an object",MISSING_TYPE:"IPC event missing 'type'",MISSING_MSG:"IPC event missing 'message'",MISSING_ORIGIN:"IPC event message missing 'originator' property",INVALID_EVENT:e=>`IPC server received invalid event type: ${e}`},KC={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 customFunctions enabled to true in hdb/harperdb-config.yaml file."},WC={CLUSTERING_NOT_ENABLED:"Clustering must be enabled to perform this operation."},QC={...Ah,...qC,...vC,...VC,...kC,...$C,...xC,...YC,...FC,...Oh,...ph,...KC,...WC,...HC};Nh.exports={CHECK_LOGS_WRAPPER:mh,HDB_ERROR_MSGS:QC,DEFAULT_ERROR_MSGS:Rh,DEFAULT_ERROR_RESP:BC,HTTP_STATUS_CODES:Th,LMDB_ERRORS_ENUM:GC,AUTHENTICATION_ERROR_MSGS:Ah,VALIDATION_ERROR_MSGS:Oh,IPC_ERRORS:ph}});var D=S((g1,bh)=>{"use strict";var xs=Ke(),JC=I(),XC=T(),Vn=class extends Error{constructor(t,r,s,n,i){super(),Error.captureStackTrace(this,gh),this.http_resp_code=s||xs.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR,this.http_resp_msg=r||(xs.DEFAULT_ERROR_MSGS[s]?xs.DEFAULT_ERROR_MSGS[s]:xs.DEFAULT_ERROR_MSGS[xs.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR]),this.message=t.message?t.message:this.http_resp_msg,this.type=t.name,typeof this.message!="string"&&(this.stack=t.stack),i&&JC[n](i)}};a(Vn,"HdbError");function gh(e,t,r,s=XC.LOG_LEVELS.ERROR,n=null,i=!1){if(Ih(e))return e;let o=new Vn(e,t,r,s,n);return i&&delete o.stack,o}a(gh,"handleHDBError");function Ih(e){return e.__proto__.constructor.name===Vn.name}a(Ih,"isHDBError");bh.exports={isHDBError:Ih,handleHDBError:gh,hdb_errors:xs}});var b=S((b1,Vh)=>{"use strict";var is=require("path"),ZC=require("fs-extra"),Ie=I(),wh=require("fs-extra"),zC=require("truncate-utf8-bytes"),kn=require("os"),jC=require("net"),eL=require("recursive-iterator"),Ue=T(),Dh=Eh(),Ch=require("papaparse"),fa=require("moment"),{inspect:tL}=require("util"),Lh=require("is-number"),I1=require("lodash"),{hdb_errors:Ta}=D(),Mh=require("util").promisify(setTimeout),rL=100,sL=5,nL="",iL=4,Uh=255,yh={true:!0,false:!1,undefined:null,null:null,NaN:NaN};Vh.exports={isEmpty:ht,isEmptyOrZeroLength:Jt,arrayHasEmptyValues:cL,arrayHasEmptyOrZeroLengthValues:_L,buildFolderPath:uL,isBoolean:Ph,errorizeMessage:aL,stripFileExtension:EL,autoCast:dL,autoCastJSONDeep:nu,removeDir:SL,compareVersions:fL,isCompatibleDataVersion:TL,escapeRawValue:vh,unescapeValue:mL,stringifyProps:RL,valueConverter:AL,timeoutPromise:pL,isClusterOperation:gL,getClusterUser:wL,sendTransactionToSocketCluster:IL,checkGlobalSchemaTable:bL,getHomeDir:Hh,getPropsFilePath:OL,promisifyPapaParse:CL,removeBOM:qh,createEventPromise:LL,checkProcessRunning:UL,checkSchemaTableExist:yL,checkSchemaExists:Gh,checkTableExists:Fh,getStartOfTomorrowInSeconds:DL,getLimitKey:ML,isObject:lL,isNotEmptyAndHasValue:oL,autoCasterIsNumberCheck:Bh,backtickASTSchemaItems:PL,isPortTaken:NL,stopProcess:BL,createForkArgs:vL,autoCastBoolean:HL,async_set_timeout:Mh,getTableHashAttribute:qL,doesSchemaExist:GL,doesTableExist:FL,stringifyObj:VL,ms_to_time:kL,changeExtension:$L,PACKAGE_ROOT:Ue.PACKAGE_ROOT};function aL(e){return e instanceof Error?e:new Error(e)}a(aL,"errorizeMessage");function ht(e){return e==null}a(ht,"isEmpty");function oL(e){return!ht(e)&&(e||e===0||e===""||Ph(e))}a(oL,"isNotEmptyAndHasValue");function Jt(e){return ht(e)||e.length===0||e.size===0}a(Jt,"isEmptyOrZeroLength");function cL(e){if(ht(e))return!0;for(let t=0;t<e.length;t++)if(ht(e[t]))return!0;return!1}a(cL,"arrayHasEmptyValues");function _L(e){if(Jt(e))return!0;for(let t=0;t<e.length;t++)if(Jt(e[t]))return!0;return!1}a(_L,"arrayHasEmptyOrZeroLengthValues");function uL(...e){try{return e.join(is.sep)}catch{console.error(e)}}a(uL,"buildFolderPath");function Ph(e){return ht(e)?!1:e===!0||e===!1}a(Ph,"isBoolean");function lL(e){return ht(e)?!1:typeof e=="object"}a(lL,"isObject");function EL(e){return Jt(e)?nL:e.slice(0,-iL)}a(EL,"stripFileExtension");function dL(e){return ht(e)||e===""||typeof e!="string"?e:yh[e]!==void 0?yh[e]:Bh(e)===!0?Number(e):e}a(dL,"autoCast");function hL(e){if(typeof e=="string"&&(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")))try{return JSON.parse(e)}catch{}return e}a(hL,"autoCastJSON");function nu(e){if(e&&typeof e=="object"){if(Array.isArray(e))for(let t=0,r=e.length;t<r;t++){let s=e[t],n=nu(s);n!==s&&(e[t]=n)}else for(let t in e){let r=e[t],s=nu(r);s!==r&&(e[t]=s)}return e}else return hL(e)}a(nu,"autoCastJSONDeep");function Bh(e){if(e.startsWith("0.")&&Lh(e))return!0;let t=e.toUpperCase().includes("E");return!!((e!=="0"&&e.startsWith("0"))===!1&&t===!1&&Lh(e))}a(Bh,"autoCasterIsNumberCheck");async function SL(e){if(Jt(e))throw new Error(`Directory path: ${e} does not exist`);try{await wh.emptyDir(e),await wh.remove(e)}catch(t){throw Ie.error(`Error removing files in ${e} -- ${t}`),t}}a(SL,"removeDir");function fL(e,t){if(Jt(e)){Ie.info("Invalid current version sent as parameter.");return}if(Jt(t)){Ie.info("Invalid upgrade version sent as parameter.");return}let r,s=/(\.0+)+$/,n=e.version?e.version:e,i=t.version?t.version:t,o=n.replace(s,"").split("."),c=i.replace(s,"").split("."),_=Math.min(o.length,c.length);for(let u=0;u<_;u++)if(r=parseInt(o[u],10)-parseInt(c[u],10),r)return r;return o.length-c.length}a(fL,"compareVersions");function TL(e,t,r=!1){let s=e.toString().split("."),n=t.toString().split(".");return s[0]===n[0]&&(!r||s[1]===n[1])}a(TL,"isCompatibleDataVersion");function vh(e){if(ht(e))return e;let t=String(e);return t==="."?Ue.UNICODE_PERIOD:t===".."?Ue.UNICODE_PERIOD+Ue.UNICODE_PERIOD:t.replace(Ue.FORWARD_SLASH_REGEX,Ue.UNICODE_FORWARD_SLASH)}a(vh,"escapeRawValue");function mL(e){if(ht(e))return e;let t=String(e);return t===Ue.UNICODE_PERIOD?".":t===Ue.UNICODE_PERIOD+Ue.UNICODE_PERIOD?"..":String(e).replace(Ue.ESCAPED_FORWARD_SLASH_REGEX,"/")}a(mL,"unescapeValue");function RL(e,t){if(ht(e))return Ie.info("Properties object is null"),"";let r="";return e.each(function(s,n){try{if(t&&t[s]){let i=t[s];for(let o of i)r+=";"+o+kn.EOL}!Jt(s)&&s[0]===";"?r+=" "+s+n+kn.EOL:Jt(s)||(r+=s+"="+n+kn.EOL)}catch{Ie.error(`Found bad property during upgrade with key ${s} and value: ${n}`)}}),r}a(RL,"stringifyProps");function AL(e){let t;try{t=typeof e=="object"?JSON.stringify(e):e}catch(n){Ie.error(n),t=e}let r=String(vh(t)),s=Buffer.byteLength(r)>Uh?zC(r,Uh)+"/blob":r;return{value:t,value_stripped:r,value_path:s}}a(AL,"valueConverter");function Hh(){let e;try{e=kn.homedir()}catch{e=process.env.HOME}return e||(e="~/"),e}a(Hh,"getHomeDir");function OL(){let e=is.join(Hh(),Ue.HDB_HOME_DIR_NAME,Ue.BOOT_PROPS_FILE_NAME);return ZC.existsSync(e)||(e=is.join(__dirname,"../","hdb_boot_properties.file")),e}a(OL,"getPropsFilePath");function pL(e,t){let r,s;return s=new Promise(function(n){r=setTimeout(function(){n(t)},e)}),{promise:s,cancel:function(){clearTimeout(r)}}}a(pL,"timeoutPromise");async function NL(e){if(!e)throw new Error("Invalid port passed as parameter");return new Promise((t,r)=>{let s=jC.createServer().once("error",n=>{n.code==="EADDRINUSE"?t(!0):r(n)}).once("listening",()=>s.once("close",()=>t(!1)).close()).listen(e)})}a(NL,"isPortTaken");function gL(e){try{return Ue.CLUSTER_OPERATIONS[e.toLowerCase()]!==void 0}catch(t){Ie.error(`Error checking operation against cluster ops ${t}`)}return!1}a(gL,"isClusterOperation");function IL(e,t,r){if(global.hdb_socket_client!==void 0){Ie.trace(`Sending transaction to channel: ${e}`);let{hdb_user:s,hdb_auth_header:n,...i}=t;i.__originator||(i.__originator={}),i.__transacted=!0,r&&(i.__originator[r]=Ue.ORIGINATOR_SET_VALUE),global.hdb_socket_client.publish(e,i)}}a(IL,"sendTransactionToSocketCluster");function bL(e,t){if(!global.hdb_schema[e])return Ta.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e);if(!global.hdb_schema[e]||!global.hdb_schema[e][t])return Ta.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(bL,"checkGlobalSchemaTable");function wL(e,t){if(ht(t)){Ie.warn("No CLUSTERING_USER defined, clustering disabled");return}if(ht(e)||Jt(e)){Ie.warn("No users to search.");return}let r;try{let s=e.get(t);s&&s.role.permission.cluster_user===!0&&s.active===!0&&(r=s)}catch(s){Ie.error(`unable to find cluster_user due to: ${s.message}`);return}if(r===void 0){Ie.warn(`CLUSTERING_USER: ${t} not found or is not active.`);return}return r}a(wL,"getClusterUser");function CL(){Ch.parsePromise=function(e,t){return new Promise(function(r,s){Ch.parse(e,{header:!0,transformHeader:qh,chunk:t.bind(null,s),skipEmptyLines:!0,dynamicTyping:!0,error:s,complete:r})})}}a(CL,"promisifyPapaParse");function qh(e){if(typeof e!="string")throw new TypeError(`Expected a string, got ${typeof e}`);return e.charCodeAt(0)===65279?e.slice(1):e}a(qh,"removeBOM");function LL(e,t,r){return new Promise(s=>{t.once(e,n=>{let i=r;Ie.info(`Got cluster status event response: ${tL(n)}`);try{i.cancel()}catch{Ie.error("Error trying to cancel timeout.")}s(n)})})}a(LL,"createEventPromise");async function UL(e){let t=!0,r=0;do await Mh(rL*r++),(await Dh.findPs(e)).length>0&&(t=!1);while(t&&r<sL);if(t)throw new Error(`process ${e} was not started`)}a(UL,"checkProcessRunning");function yL(e,t){let r=Gh(e);if(r)return r;let s=Fh(e,t);if(s)return s}a(yL,"checkSchemaTableExist");function Gh(e){if(!global.hdb_schema[e])return Ta.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}a(Gh,"checkSchemaExists");function Fh(e,t){if(!global.hdb_schema[e][t])return Ta.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(Fh,"checkTableExists");function DL(){let e=fa().utc().add(1,Ue.MOMENT_DAYS_TAG).startOf(Ue.MOMENT_DAYS_TAG).unix(),t=fa().utc().unix();return e-t}a(DL,"getStartOfTomorrowInSeconds");function ML(){return fa().utc().format("DD-MM-YYYY")}a(ML,"getLimitKey");function PL(e){try{let t=new eL(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){Ie.error("Got an error back ticking items."),Ie.error(t)}}a(PL,"backtickASTSchemaItems");async function BL(e){let t=kn.userInfo();(await Dh.findPs(e)).forEach(s=>{(t.uid==0||s.uid==t.uid)&&(process.kill(s.pid),Ie.trace(`Following process was killed by stopProcess: ${s.cmd}`))})}a(BL,"stopProcess");function vL(e){return[e]}a(vL,"createForkArgs");function HL(e){return e===!0||typeof e=="string"&&e.toLowerCase()==="true"}a(HL,"autoCastBoolean");function qL(e,t){return global.hdb_schema?.[e]?.[t]?.hash_attribute}a(qL,"getTableHashAttribute");function GL(e){return global?.hdb_schema?.[e]!==void 0}a(GL,"doesSchemaExist");function FL(e,t){return global?.hdb_schema?.[e]?.[t]!==void 0}a(FL,"doesTableExist");function VL(e){try{return JSON.stringify(e)}catch{return e}}a(VL,"stringifyObj");function kL(e){let t=fa.duration(e),r=t.seconds()>0?t.seconds()+"s":"",s=t.minutes()>0?t.minutes()+"m ":"",n=t.hours()>0?t.hours()+"h ":"",i=t.days()>0?t.days()+"d ":"";return(t.years()>0?t.years()+"y ":"")+i+n+s+r}a(kL,"ms_to_time");function $L(e,t){let r=is.basename(e,is.extname(e));return is.join(is.dirname(e),r+t)}a($L,"changeExtension")});var eS=S((C1,jh)=>{"use strict";var iu=require("recursive-iterator"),xL=require("alasql"),au=require("clone"),kh=b(),{handleHDBError:$h,hdb_errors:YL}=D(),{HDB_ERROR_MSGS:xh,HTTP_STATUS_CODES:Yh}=YL,KL=["DISTINCT_ARRAY"],Kh=Symbol("validateTables"),ou=Symbol("validateTable"),w1=Symbol("getAllColumns"),Wh=Symbol("validateAllColumns"),ma=Symbol("findColumn"),Qh=Symbol("validateOrderBy"),$n=Symbol("validateSegment"),cu=Symbol("validateColumn"),Jh=Symbol("setColumnsForTable"),Xh=Symbol("checkColumnsForAsterisk"),Zh=Symbol("validateGroupBy"),zh=Symbol("hasColumns"),Ra=class{constructor(t){this.statement=t,this.attributes=[]}validate(){if(!this.statement)throw new Error("invalid sql statement");this[Kh](),this[Xh](),this[Wh]()}[Kh](){if(this[zh]()){if(!this.statement.from||this.statement.from.length===0)throw"no from clause";this.statement.from.forEach(t=>{this[ou](t)}),this.statement.joins&&this.statement.joins.forEach(t=>{t.table.as=t.as,this[ou](t.table)})}}[zh](){let t=!1,r=new iu(this.statement);for(let{node:s,path:n}of r)if(s&&s.columnid){t=!0;break}return t}[ou](t){if(!t.databaseid)throw`schema not defined for table ${t.tableid}`;if(!global.hdb_schema[t.databaseid])throw $h(new Error,xh.SCHEMA_NOT_FOUND(t.databaseid),Yh.NOT_FOUND);if(!global.hdb_schema[t.databaseid][t.tableid])throw $h(new Error,xh.TABLE_NOT_FOUND(t.databaseid,t.tableid),Yh.NOT_FOUND);global.hdb_schema[t.databaseid][t.tableid].attributes.forEach(s=>{let n=au(s);n.table=au(t),this.attributes.push(n)})}[ma](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)}[Xh](){let t=new iu(this.statement.columns);for(let{node:r,path:s}of t)r&&r.columnid==="*"&&s.indexOf("expression")<0&&this[Jh](r.tableid)}[Jh](t){this.attributes.forEach(r=>{(!t||t&&(r.table.tableid===t||r.table.as===t))&&this.statement.columns.push(new xL.yy.Column({columnid:r.attribute,tableid:r.table.as?r.table.as:r.table.tableid}))})}[Wh](){this[$n](this.statement.columns,!1),this[$n](this.statement.joins,!1),this[$n](this.statement.where,!1),this[Zh](this.statement.group,!1),this[$n](this.statement.order,!0)}[$n](t,r){if(!t)return;let s=new iu(t),n=[];for(let{node:i,path:o}of s)!kh.isEmpty(i)&&!kh.isEmpty(i.columnid)&&i.columnid!=="*"&&(r?this[Qh](i):n.push(this[cu](i)));return n}[Zh](t){if(!t)return;let r=[];if(this.statement.columns.forEach(s=>{if(!(s.funcid&&KL.indexOf(s.funcid.toUpperCase())>=0)){if(!s.aggregatorid&&!s.columnid){let n=au(s);delete n.as,r.push(n)}else if(s.columnid){let n=this[ma](s)[0];n&&r.push(n)}}}),this.statement.group.forEach(s=>{let n=null;if(!s.columnid)r.forEach((i,o)=>{if(i.toString()===s.toString()){n=i,r.splice(o,1);return}});else{let i=this[ma](s);if(!i||i.length===0)throw`unknown column '${s.toString()}' in group by`;if(i.length>1)throw`ambiguously defined column '${s.toString()}' in group by`;r.forEach((o,c)=>{if(o.attribute===i[0].attribute&&o.table.tableid===i[0].table.tableid){n=o,r.splice(c,1);return}})}if(!n)throw`group by column '${s.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`}[Qh](t){let r=this.statement.columns.filter(s=>s.as===t.columnid);if(r.length>1)throw`ambiguous column reference ${(t.tableid?t.tableid+".":"")+t.columnid} in order by`;r.length===0&&this[cu](t)}[cu](t){let r=this[ma](t),s=(t.tableid?t.tableid+".":"")+t.columnid;if(r.length===0)throw`unknown column ${s}`;if(r.length>1)throw`ambiguous column reference ${s}`;return r[0]}};a(Ra,"SelectValidator");jh.exports=Ra});var _u=S((L1,tS)=>{"use strict";var Aa=class{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")}};a(Aa,"BridgeMethods");tS.exports=Aa});var as=S((D1,iS)=>{"use strict";var rS=Ke().LMDB_ERRORS_ENUM,U1=require("lmdb"),WL=Ye(),y1=require("buffer").Buffer,QL=require("microtime"),{OVERFLOW_MARKER:sS,MAX_SEARCH_KEY_LENGTH:Oa}=WL,nS=["number","string","symbol","boolean","bigint"];function JL(e){if(!e)throw new Error(rS.ENV_REQUIRED);if(e.constructor.name!=="LMDBStore")throw new Error(rS.INVALID_ENVIRONMENT)}a(JL,"validateEnv");function XL(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(XL,"stringifyData");function ZL(e){return e instanceof Date?e.valueOf():e}a(ZL,"convertKeyValueToWrite");function zL(e){if(e==null)return;if(nS.includes(typeof e))return e.length>Oa?[e.slice(0,Oa)+sS]:[e];let t;if(Array.isArray(e)){t=[];for(let r=0,s=e.length;r<s;r++){let n=e[r];nS.includes(typeof n)&&(n.length>Oa?t.push(n.slice(0,Oa)+sS):t.push(n))}}return t}a(zL,"getIndexedValues");function jL(){let e=QL.now().toString(),t=e.length-3;return Number(e.slice(0,t)+"."+e.slice(t))}a(jL,"getMicroTime");iS.exports={validateEnv:JL,stringifyData:XL,convertKeyValueToWrite:ZL,getMicroTime:jL,getIndexedValues:zL}});var oS=S((M1,aS)=>{"use strict";var pa=class{constructor(t=!1,r=!1){this.dup_sort=t,this.is_hash_attribute=r,this.useVersions=r}};a(pa,"DBIDefinition");aS.exports=pa});var _S=S((P1,cS)=>{"use strict";var Na=class{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={validated:!0},this.randomAccessStructure=!0,this.freezeData=!0)}};a(Na,"OpenDBIObject");cS.exports=Na});var lS=S((B1,uS)=>{"use strict";var ga=class{constructor(t,r,s,n,i=!1,o=!1,c=void 0){this.path=t,this.mapSize=r,this.maxDbs=s,this.maxReaders=n,this.sharedStructuresKey=Symbol.for("structures"),this.readOnly=i,this.trackMetrics=!0,this.noSync=o,c!==void 0&&(this.overlappingSync=c)}};a(ga,"OpenEnvironmentObject");uS.exports=ga});var de=S((v1,ES)=>{"use strict";var st=require("validate.js");st.validators.type=function(e,t,r,s){return e===null||typeof e>"u"||st.validators.type.checks[t](e)?null:` must be a '${t}' value`};st.validators.type.checks={Object:function(e){return st.isObject(e)&&!st.isArray(e)},Array:st.isArray,Integer:st.isInteger,Number:st.isNumber,String:st.isString,Date:st.isDate,Boolean:function(e){return typeof e=="boolean"}};st.validators.hasValidFileExt=function(e,t){return!st.isString(e)||e===""||t.filter(r=>e.endsWith(r)).length>0?null:`must include one of the following valid file extensions - '${t.join("', '")}'`};ES.exports={validateObject:eU,validateObjectAsync:tU,validateBySchema:rU};function eU(e,t){if(!e||!t)return new Error("validateObject parameters were null");let r=st(e,t,{format:"flat"});return r?new Error(r):null}a(eU,"validateObject");async function tU(e,t){if(!e||!t)return new Error("validateObject parameters were null");try{await st.async(e,t,{format:"flat"})}catch(r){let s=r.join(",");return new Error(s)}return null}a(tU,"validateObjectAsync");function rU(e,t){let r=t.validate(e,{allowUnknown:!0,abortEarly:!1,errors:{wrap:{label:"'"}}});if(r.error)return new Error(r.error.message)}a(rU,"validateBySchema")});var lu=S((H1,hS)=>{"use strict";var sU=require("fs-extra"),F=require("joi"),nU=require("os"),{boolean:ye,string:_r,number:Xt,array:uu}=F.types(),dS=require("path"),iU=I(),Ia=b(),aU=de(),oU="log",cU="custom_functions",_U="Invalid logging.rotation.maxSize unit. Available units are G, M or K",uU="Invalid logging.rotation.maxSize value. Value should be a number followed by unit e.g. '10M'",lU="rootPath config parameter is undefined",EU="clustering.enabled config parameter is undefined",Ur=Xt.min(0).required(),ba=uu.items({host:_r.required(),port:Ur}).empty(null),xn;hS.exports={configValidator:dU,routesValidator:RU,route_constraints:ba};function dU(e){if(xn=e.rootPath,Ia.isEmpty(xn))throw lU;let t=ye.required(),r=F.valid("production","development").required(),s=Xt.min(1).max(1e3).empty(null).default(TU),n=_r.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path").empty(null).default(mU),i=F.custom(SU).messages({"any.custom":"{:#label} {:#error}"}),o=_r.pattern(/^[^\s.,*>]+$/).messages({"string.pattern.base":"{:#label} invalid, must not contain ., * or >"}).empty(null),c=e.clustering?.enabled;if(Ia.isEmpty(c))throw EU;let _;return c===!0?_=F.object({enabled:t,hubServer:F.object({cluster:F.object({name:F.required().empty(null),network:F.object({port:Ur,routes:ba}).required()}).required(),leafNodes:F.object({network:F.object({port:Ur}).required()}).required(),network:F.object({port:Ur}).required()}).required(),leafServer:F.object({network:F.object({port:Ur,routes:ba}).required()}).required(),nodeName:o,tls:F.object({certificate:i,certificateAuthority:i,privateKey:i,insecure:ye.required()}),user:F.string().required()}).required():_=F.object({enabled:t,tls:F.object({certificate:i,certificateAuthority:i,privateKey:i,insecure:ye.required()})}).required(),F.object({clustering:_,customFunctions:F.object({enabled:t,network:F.object({cors:ye.required(),corsAccessList:uu.required(),headersTimeout:Xt.min(1).required(),https:ye.required(),keepAliveTimeout:Xt.min(1).required(),port:Ur,timeout:Xt.min(1).required()}),nodeEnv:r,root:n,tls:F.object({certificate:i,certificateAuthority:i,privateKey:i})}).required(),ipc:F.object({network:F.object({port:Ur})}).required(),localStudio:F.object({enabled:t}).required(),logging:F.object({file:ye.required(),level:F.valid("notify","fatal","error","warn","info","debug","trace"),rotation:F.object({compress:ye.required(),dateFormat:_r.required(),maxSize:_r.custom(fU).required(),retain:Xt.min(0).required(),rotate:ye.required(),rotateInterval:_r.required(),rotateModule:ye.required(),timezone:_r.required(),workerInterval:Xt.min(1).required()}).required(),root:n,stdStreams:ye.required(),auditLog:ye.required()}).required(),operationsApi:F.object({authentication:F.object({operationTokenTimeout:F.required(),refreshTokenTimeout:F.required()}).required(),foreground:ye.required(),network:F.object({cors:ye.required(),corsAccessList:uu.required(),headersTimeout:Xt.min(1).required(),https:ye.required(),keepAliveTimeout:Xt.min(1).required(),port:Ur,timeout:Xt.min(1).required()}).required(),nodeEnv:r,tls:F.object({certificate:i,certificateAuthority:i,privateKey:i})}).required(),rootPath:_r.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path").required(),http:F.object({threads:s}).required(),storage:F.object({writeAsync:ye.required(),overlappingSync:ye.optional()}).required()}).validate(e,{allowUnknown:!0,abortEarly:!1,errors:{wrap:{label:"'"}}})}a(dU,"configValidator");function hU(e){return sU.existsSync(e)?null:`Specified path ${e} does not exist.`}a(hU,"doesPathExist");function SU(e,t){if(e===null)return;F.assert(e,_r.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+\.pem+$/).messages({"string.pattern.base":"must be a valid directory path and specify a .pem file"}));let r=hU(e);return r?t.message(r):e}a(SU,"validatePemFile");function fU(e,t){let r=e.slice(-1);if(r!=="G"&&r!=="M"&&r!=="K")return t.message(_U);let s=e.slice(0,-1);if(isNaN(parseInt(s)))return t.message(uU)}a(fU,"validateRotationMaxSize");function TU(e,t){let r=t.state.path.join("."),s=nU.cpus().length,n=s-1;return n<=2&&(n=2),iU.info(`Detected ${s} cores on this machine, defaulting ${r} to ${n}`),n}a(TU,"setDefaultThreads");function mU(e,t){if(!Ia.isEmpty(t.original))return t.original;let r=t.state.path.join(".");if(Ia.isEmpty(xn))throw new Error(`Error setting default root for: ${r}. HDB root is not defined`);switch(r){case"customFunctions.root":return dS.join(xn,cU);case"logging.root":return dS.join(xn,oU);default:throw new Error(`Error setting default root for config parameter: ${r}. Unrecognized config parameter`)}}a(mU,"setDefaultRoot");function RU(e){let t=F.object({routes:ba});return aU.validateBySchema({routes:e},t)}a(RU,"routesValidator")});var ur=S((q1,OS)=>{"use strict";var re=T(),gt=b(),We=I(),{configValidator:AU,routesValidator:SS}=lu(),qt=require("fs-extra"),OU=require("yaml"),Ys=require("path"),pU=require("is-number"),La=require("properties-reader"),NU=require("lodash"),{handleHDBError:gU}=D(),{HTTP_STATUS_CODES:IU,HDB_ERROR_MSGS:wa}=Ke(),{PACKAGE_ROOT:bU}=T(),wU="Unable to get config value because config is uninitialized",CU="Config successfully initialized",LU="Error backing up config file",UU="Empty parameter sent to getConfigValue",fS=Ys.join(bU,"config","yaml",re.HDB_DEFAULT_CONFIG_FILE),yU="Configuration successfully set. You must restart HarperDB for new config settings to take effect.",Ca,nt;OS.exports={createConfigFile:DU,getDefaultConfig:MU,getConfigValue:TS,initConfig:mS,flattenConfig:os,updateConfigValue:RS,updateConfigObject:PU,getConfiguration:BU,setConfiguration:vU,readConfigFile:hu,getClusteringRoutes:HU,initOldConfig:AS,getConfigFromFile:qU};function DU(e){let t=Ks(fS);Ca=os(t.toJSON());for(let i in e){let o=re.CONFIG_PARAM_MAP[i.toLowerCase()];if(o!==void 0){let c=o.split("_"),_=Eu(o,e[i]);try{t.setIn([...c],_)}catch(u){We.error(u)}}}du(t);let r=t.toJSON();nt=os(r);let s=t.getIn(["rootPath"]),n=Ys.join(s,re.HDB_CONFIG_FILE);qt.createFileSync(n),qt.writeFileSync(n,String(t)),We.trace(`Config file written to ${n}`)}a(DU,"createConfigFile");function MU(e){if(Ca===void 0){let r=Ks(fS);Ca=os(r.toJSON())}let t=re.CONFIG_PARAM_MAP[e.toLowerCase()];if(t!==void 0)return Ca[t.toLowerCase()]}a(MU,"getDefaultConfig");function TS(e){if(gt.isEmpty(e)){We.error(UU);return}if(nt===void 0){We.trace(wU);return}let t=re.CONFIG_PARAM_MAP[e.toLowerCase()];if(t!==void 0)return nt[t.toLowerCase()]}a(TS,"getConfigValue");function mS(e=!1){if(nt===void 0||e){let t=gt.getPropsFilePath();try{qt.accessSync(t,qt.constants.F_OK|qt.constants.R_OK)}catch(o){throw We.error(o),new Error(`HarperDB properties file at path ${t} does not exist`)}let s=La(t).get(re.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY),n;if(s.includes("config/settings.js"))try{AS(s);return}catch(o){if(o.code!==re.NODE_ERROR_CODES.ENOENT)throw o}try{n=Ks(s)}catch(o){if(o.code===re.NODE_ERROR_CODES.ENOENT){We.trace(`HarperDB config file not found at ${s}.
|
|
5
|
+
This can occur during early stages of install where the config file has not yet been created`);return}else throw We.error(o),new Error(`Error reading HarperDB config file at ${s}`)}du(n);let i=n.toJSON();nt=os(i),We.trace(CU)}}a(mS,"initConfig");function du(e){let t=e.toJSON(),r=AU(t);if(r.error)throw wa.CONFIG_VALIDATION(r.error.message);e.setIn(["http","threads"],r.value.http.threads),e.setIn(["customFunctions","root"],r.value.customFunctions.root),e.setIn(["logging","root"],r.value.logging.root),e.setIn(["operationsApi","tls","certificate"],r.value.operationsApi.tls.certificate),e.setIn(["operationsApi","tls","privateKey"],r.value.operationsApi.tls.privateKey),e.setIn(["operationsApi","tls","certificateAuthority"],r.value.operationsApi.tls.certificateAuthority),e.setIn(["customFunctions","tls","certificate"],r.value.customFunctions.tls.certificate),e.setIn(["customFunctions","tls","privateKey"],r.value.customFunctions.tls.privateKey),e.setIn(["customFunctions","tls","certificateAuthority"],r.value.customFunctions.tls.certificateAuthority),e.setIn(["clustering","tls","certificate"],r.value.clustering.tls.certificate),e.setIn(["clustering","tls","privateKey"],r.value.clustering.tls.privateKey),e.setIn(["clustering","tls","certificateAuthority"],r.value.clustering.tls.certificateAuthority)}a(du,"validateConfig");function PU(e,t){nt===void 0&&(nt={});let r=re.CONFIG_PARAM_MAP[e.toLowerCase()];if(r===void 0){We.trace(`Unable to update config object because config param '${e}' does not exist`);return}nt[r.toLowerCase()]=t}a(PU,"updateConfigObject");function RS(e,t,r=void 0,s=!1,n=!1){nt===void 0&&mS();let i=TS(re.CONFIG_PARAM_MAP.hdb_root),o=Ys.join(i,re.HDB_CONFIG_FILE),c=Ks(o);if(r===void 0){let l=re.CONFIG_PARAM_MAP[e.toLowerCase()];if(l===void 0)throw new Error(`Unable to update config, unrecognized config parameter: ${e}`);let E=l.split("_"),d=Eu(l,t);c.setIn([...E],d)}else for(let l in r){let E=re.CONFIG_PARAM_MAP[l.toLowerCase()];if(E!==void 0){let d=E.split("_"),h=Eu(E,r[l]);try{c.setIn([...d],h)}catch(m){We.error(m)}}}du(c);let _=c.getIn(["rootPath"]),u=Ys.join(_,re.HDB_CONFIG_FILE);if(s===!0)try{let l=Ys.join(_,"backup",`${re.HDB_CONFIG_FILE}.bak`);qt.copySync(o,l),We.trace(`Config file: ${o} backed up to: ${l}`)}catch(l){We.error(LU),We.error(l)}qt.writeFileSync(u,String(c)),n&&(nt=os(c.toJSON())),We.trace(`Config parameter: ${e} updated with value: ${t}`)}a(RS,"updateConfigValue");function os(e){let t={};for(let r in e)if(!!e.hasOwnProperty(r))if(typeof e[r]=="object"&&e[r]!==null&&!Array.isArray(e[r])){let s=os(e[r]);for(let n in s)!s.hasOwnProperty(n)||(t[r.toLowerCase()+"_"+n]=s[n])}else t[r.toLowerCase()]=e[r];return t}a(os,"flattenConfig");function Eu(e,t){if(e===re.CONFIG_PARAMS.CLUSTERING_NODENAME||e===re.CONFIG_PARAMS.CLUSTERING_USER){if(!isNaN(t))return t.toString();if(typeof t=="string"&&t.toLowerCase()==="true"||typeof t=="string"&&t.toLowerCase()==="false")return t}else{if(pU(t))return parseFloat(t);if(t===!0||t===!1||Array.isArray(t)||gt.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 gt.autoCast(t)}a(Eu,"castConfigValue");function BU(){let e=gt.getPropsFilePath(),r=La(e).get(re.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY);return Ks(r).toJSON()}a(BU,"getConfiguration");async function vU(e){let{operation:t,hdb_user:r,hdb_auth_header:s,...n}=e;try{return RS(void 0,void 0,n,!0),yU}catch(i){throw typeof i=="string"||i instanceof String?gU(i,i,IU.BAD_REQUEST,void 0,void 0,!0):i}}a(vU,"setConfiguration");function hu(){let e=gt.getPropsFilePath();try{qt.accessSync(e,qt.constants.F_OK|qt.constants.R_OK)}catch(n){throw We.error(n),new Error(`HarperDB properties file at path ${e} does not exist`)}let r=La(e).get(re.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY);return Ks(r).toJSON()}a(hu,"readConfigFile");function Ks(e){return OU.parseDocument(qt.readFileSync(e,"utf8"),{simpleKeys:!0})}a(Ks,"parseYamlDoc");function HU(){let e=hu(),t=e?.clustering?.hubServer?.cluster?.network?.routes;t=gt.isEmptyOrZeroLength(t)?[]:t;let r=SS(t);if(r)throw wa.CONFIG_VALIDATION(r.message);let s=e?.clustering?.leafServer?.network?.routes;s=gt.isEmptyOrZeroLength(s)?[]:s;let n=SS(s);if(n)throw wa.CONFIG_VALIDATION(n.message);if(!gt.isEmptyOrZeroLength(s)&&!gt.isEmptyOrZeroLength(t)){let i=t.filter(o=>s.some(c=>c.host===o.host&&c.port===o.port));if(!gt.isEmptyOrZeroLength(i)){let o=`Duplicate hub and leaf routes found ${JSON.stringify(i)}`;throw wa.CONFIG_VALIDATION(o)}}return{hub_routes:t,leaf_routes:s}}a(HU,"getClusteringRoutes");function AS(e){let t=La(e);nt={};for(let r in re.CONFIG_PARAM_MAP){let s=t.get(r.toUpperCase());if(gt.isEmpty(s)||typeof s=="string"&&s.trim().length===0)continue;let n=re.CONFIG_PARAM_MAP[r].toLowerCase();n===re.CONFIG_PARAMS.LOGGING_ROOT?nt[n]=Ys.dirname(s):nt[n]=s}return nt}a(AS,"initOldConfig");function qU(e){let t=hu();return NU.get(t,e.replaceAll("_","."))}a(qU,"getConfigFromFile")});var Y=S((G1,NS)=>{"use strict";var Su=require("fs-extra"),Zt=require("path"),GU=require("os"),FU=require("properties-reader"),Yn=I(),Ws=b(),M=T(),Ua=ur(),VU="Error initializing environment manager",ya="BOOT_PROPS_FILE_PATH",pS=!1,kU={[M.HDB_SETTINGS_NAMES.INSTALL_USER]:!0,[M.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY]:!0,[M.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]:!0,BOOT_PROPS_FILE_PATH:!0},lr={};NS.exports={BOOT_PROPS_FILE_PATH:ya,getHdbBasePath:$U,setHdbBasePath:xU,get:YU,initSync:WU,setProperty:x,initTestEnvironment:QU};function $U(){return lr[M.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]}a($U,"getHdbBasePath");function xU(e){lr[M.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=e}a(xU,"setHdbBasePath");function YU(e){let t=Ua.getConfigValue(e);return t===void 0?lr[e]:t}a(YU,"get");function x(e,t){kU[e]&&(lr[e]=t),Ua.updateConfigObject(e,t)}a(x,"setProperty");function KU(){let e;try{e=Ws.getPropsFilePath(),Su.accessSync(e,Su.constants.F_OK|Su.constants.R_OK),pS=!0;let t=FU(e);return lr[M.HDB_SETTINGS_NAMES.INSTALL_USER]=t.get(M.HDB_SETTINGS_NAMES.INSTALL_USER),lr[M.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY]=t.get(M.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY),lr[ya]=e,!0}catch{return Yn.trace(`Environment manager found no properties file at ${e}`),!1}}a(KU,"doesPropFileExist");function WU(e=!1){try{(pS||KU())&&(Ua.initConfig(e),lr[M.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=Ua.getConfigValue(M.HDB_SETTINGS_NAMES.HDB_ROOT_KEY))}catch(t){Yn.error(VU),Yn.error(t),console.error(t),process.exit(1)}}a(WU,"initSync");function QU(e={}){try{let{keep_alive_timeout:t,headers_timeout:r,server_timeout:s,https_enabled:n,cors_enabled:i,cors_accesslist:o,local_studio_on:c}=e,_=Zt.join(__dirname,"../../","unitTests");lr[ya]=Zt.join(_,"hdb_boot_properties.file"),x(M.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY,Zt.join(_,"settings.test")),x(M.HDB_SETTINGS_NAMES.INSTALL_USER,GU.userInfo().username),x(M.HDB_SETTINGS_NAMES.PRIVATE_KEY_KEY,Zt.join(_,"envDir","utility","keys","privateKey.pem")),x(M.HDB_SETTINGS_NAMES.CERT_KEY,Zt.join(_,"envDir","utility","keys","certificate.pem")),x(M.CONFIG_PARAMS.CUSTOMFUNCTIONS_TLS_PRIVATEKEY,Zt.join(_,"envDir","utility","keys","privateKey.pem")),x(M.CONFIG_PARAMS.CUSTOMFUNCTIONS_TLS_CERTIFICATE,Zt.join(_,"envDir","utility","keys","certificate.pem")),x(M.HDB_SETTINGS_NAMES.LOG_LEVEL_KEY,"debug"),x(M.HDB_SETTINGS_NAMES.LOG_PATH_KEY,Zt.join(_,"envDir","log")),x(M.HDB_SETTINGS_NAMES.LOG_DAILY_ROTATE_KEY,!1),x(M.HDB_SETTINGS_NAMES.CLUSTERING_ENABLED_KEY,!0),x(M.HDB_SETTINGS_NAMES.CLUSTERING_NODE_NAME_KEY,"1231412de213"),x(M.HDB_SETTINGS_NAMES.HDB_ROOT_KEY,Zt.join(_,"envDir")),x(M.HDB_SETTINGS_NAMES.HTTP_SECURE_ENABLED_KEY,Ws.isEmpty(n)?!0:n),x(M.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HTTPS,Ws.isEmpty(n)?!0:n),x(M.HDB_SETTINGS_NAMES.SERVER_PORT_KEY,9925),x(M.HDB_SETTINGS_NAMES.CORS_ENABLED_KEY,Ws.isEmpty(i)?!1:i),x(M.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_CORS,Ws.isEmpty(i)?!1:i),x(M.HDB_SETTINGS_NAMES.IPC_SERVER_PORT,9383),x(M.HDB_SETTINGS_NAMES.MAX_CUSTOM_FUNCTION_PROCESSES,2),x(M.HDB_SETTINGS_NAMES.MAX_HDB_PROCESSES,4),x(M.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_PORT_KEY,9926),x(M.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_ENABLED_KEY,!0),x(M.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY,Zt.resolve(__dirname,"../../unitTests/server/customFunctions/custom_functions")),x(M.HDB_SETTINGS_NAMES.LOCAL_STUDIO_ON,Ws.isEmpty(c)?!1:c),o&&(x("CORS_ACCESSLIST",o),x(M.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_CORSACCESSLIST,o)),s&&(x(M.HDB_SETTINGS_NAMES.SERVER_TIMEOUT_KEY,s),x(M.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_TIMEOUT,s)),t&&(x(M.HDB_SETTINGS_NAMES.SERVER_KEEP_ALIVE_TIMEOUT_KEY,t),x(M.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_KEEPALIVETIMEOUT,t)),r&&(x(M.HDB_SETTINGS_NAMES.SERVER_HEADERS_TIMEOUT_KEY,r),x(M.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HEADERSTIMEOUT,r))}catch(t){let r=`Error reading in HDB environment variables from path ${ya}. Please check your boot props and settings files`;Yn.fatal(r),Yn.error(t)}}a(QU,"initTestEnvironment")});var X=S((V1,BS)=>{"use strict";var fu=require("lmdb"),It=require("fs-extra"),Gt=require("path"),Ma=as(),gS=I(),De=Ke().LMDB_ERRORS_ENUM,Pa=oS(),Tu=_S(),IS=lS(),yr=Ye(),F1=T(),Kn=Y();Kn.initSync();var bS=Kn.get("STORAGE_WRITEASYNC")===!0||Kn.get("STORAGE_WRITEASYNC")==="true"||Kn.get("STORAGE_WRITEASYNC")==="TRUE",wS=Kn.get("STORAGE_OVERLAPPINGSYNC"),CS=1024*1024*1024,LS=1e4,US=1e3,Ft=yr.INTERNAL_DBIS_NAME,yS=yr.DBI_DEFINITION_NAME,JU="data.mdb",XU="lock.mdb",Wn=".mdb",ZU="-lock",Da=class{constructor(t,r,s=!1){this.dbi=bt(t,r),this.key_type=this.dbi[yr.DBI_DEFINITION_NAME].key_type,this.is_hash_attribute=this.dbi[yr.DBI_DEFINITION_NAME].is_hash_attribute,this.txn=t.beginTxn({readOnly:s===!1}),this.cursor=new fu.Cursor(this.txn,this.dbi)}close(){this.cursor.close(),this.txn.abort()}commit(){this.cursor.close(),this.txn.commit()}};a(Da,"TransactionCursor");function mu(e,t){if(e===void 0)throw new Error(De.BASE_PATH_REQUIRED);if(t===void 0)throw new Error(De.ENV_NAME_REQUIRED)}a(mu,"pathEnvNameValidation");async function Ru(e,t,r=!0){try{await It.access(e)}catch(s){throw s.code==="ENOENT"?new Error(De.INVALID_BASE_PATH):s}try{let s=Gt.join(e,t+Wn);return await It.access(s,It.constants.R_OK|It.constants.F_OK),s}catch(s){if(s.code==="ENOENT")if(r)try{return await It.access(Gt.join(e,t,JU),It.constants.R_OK|It.constants.F_OK),Gt.join(e,t)}catch(n){if(n.code==="ENOENT")throw new Error(De.INVALID_ENVIRONMENT)}else throw new Error(De.INVALID_ENVIRONMENT);throw s}}a(Ru,"validateEnvironmentPath");function Ba(e,t){if(Ma.validateEnv(e),t===void 0)throw new Error(De.DBI_NAME_REQUIRED)}a(Ba,"validateEnvDBIName");async function zU(e,t,r=!1,s=!1){mu(e,t),t=t.toString();try{return await Ru(e,t,s),Au(e,t,r)}catch(n){if(n.message===De.INVALID_ENVIRONMENT){let i=Gt.join(e,t);await It.mkdirp(s?i:e);let o=new IS(s?i:i+Wn,CS,LS,US,!1,bS,wS),c=fu.open(o);c.dbis=Object.create(null);let _=new Tu(!1);c.openDB(Ft,_),global.lmdb_map===void 0&&(global.lmdb_map=Object.create(null));let u=Ou(e,t,r);return c[yr.ENVIRONMENT_NAME_KEY]=u,global.lmdb_map[u]=c,c}throw n}}a(zU,"createEnvironment");async function jU(e,t,r,s=!0){let n=await Au(e,t);if(r===void 0)throw new Error(De.DESTINATION_PATH_REQUIRED);try{await It.access(Gt.dirname(r))}catch(i){throw i.code==="ENOENT"?new Error(De.INVALID_DESTINATION_PATH):i}await n.backup(r,s)}a(jU,"copyEnvironment");async function Au(e,t,r=!1){mu(e,t),t=t.toString();let s=Ou(e,t,r);if(global.lmdb_map===void 0&&(global.lmdb_map=Object.create(null)),global.lmdb_map[s]!==void 0)return global.lmdb_map[s];let n=await Ru(e,t),i=Gt.join(e,t+Wn),o=n!=i,c=new IS(n,CS,LS,US,o,bS,wS),_=fu.open(c);_.dbis=Object.create(null);let u=MS(_);for(let l=0;l<u.length;l++)bt(_,u[l]);return _[yr.ENVIRONMENT_NAME_KEY]=s,global.lmdb_map[s]=_,_}a(Au,"openEnvironment");async function ey(e,t,r=!1){mu(e,t),t=t.toString();let s=Gt.join(e,t+Wn),n=await Ru(e,t);if(global.lmdb_map!==void 0){let i=Ou(e,t,r);if(global.lmdb_map[i]){let o=global.lmdb_map[i];await DS(o),delete global.lmdb_map[i]}}await It.remove(n),await It.remove(n===s?n+ZU:Gt.join(Gt.dirname(n),XU))}a(ey,"deleteEnvironment");async function DS(e){Ma.validateEnv(e);let t=e[yr.ENVIRONMENT_NAME_KEY];await e.close(),t!==void 0&&global.lmdb_map!==void 0&&delete global.lmdb_map[t]}a(DS,"closeEnvironment");function Ou(e,t,r=!1){let n=`${Gt.basename(e)}.${t}`;return r===!0&&(n=`txn.${n}`),n}a(Ou,"getCachedEnvironmentName");function ty(e){Ma.validateEnv(e);let t=Object.create(null),r=bt(e,Ft);for(let{key:s,value:n}of r.getRange({start:!1}))if(s!==Ft)try{t[s]=Object.assign(new Pa,n)}catch{gS.warn(`an internal error occurred: unable to parse DBI Definition for ${s}`)}return t}a(ty,"listDBIDefinitions");function MS(e){Ma.validateEnv(e);let t=[],r=bt(e,Ft);for(let{key:s}of r.getRange({start:!1}))s!==Ft&&t.push(s);return t}a(MS,"listDBIs");function ry(e,t){let s=bt(e,Ft).getEntry(t),n=new Pa;if(s!==void 0){try{n=Object.assign(n,s.value)}catch{gS.warn(`an internal error occurred: unable to parse DBI Definition for ${s}`)}return n}}a(ry,"getDBIDefinition");function PS(e,t,r,s=!1){if(Ba(e,t),t=t.toString(),t===Ft)throw new Error(De.CANNOT_CREATE_INTERNAL_DBIS_NAME);try{return bt(e,t)}catch(n){if(n.message===De.DBI_DOES_NOT_EXIST){let i=new Tu(r,s===!0),o=e.openDB(t,i),c=new Pa(r===!0,s);return o[yS]=c,bt(e,Ft).putSync(t,c),e.dbis[t]=o,o}throw n}}a(PS,"createDBI");function bt(e,t){if(Ba(e,t),t=t.toString(),e.dbis[t]!==void 0)return e.dbis[t];let r;if(t!==Ft?r=ry(e,t):r=new Pa,r===void 0)throw new Error(De.DBI_DOES_NOT_EXIST);let s;try{let n=new Tu(r.dup_sort,r.useVersions);if(s=e.openDB(t,n),s.db===void 0)throw new Error("MDB_NOTFOUND")}catch(n){throw n.message.includes("MDB_NOTFOUND")===!0?new Error(De.DBI_DOES_NOT_EXIST):n}return s[yS]=r,e.dbis[t]=s,s}a(bt,"openDBI");function sy(e,t){Ba(e,t),t=t.toString();let r=bt(e,t),s=r.getStats();return r[yr.DBI_DEFINITION_NAME].is_hash_attribute&&s.entryCount>0&&s.entryCount--,s}a(sy,"statDBI");async function ny(e,t){try{let r=Gt.join(e,t+Wn);return(await It.stat(r)).size}catch{throw new Error(De.INVALID_ENVIRONMENT)}}a(ny,"environmentDataSize");function iy(e,t){if(Ba(e,t),t=t.toString(),t===Ft)throw new Error(De.CANNOT_DROP_INTERNAL_DBIS_NAME);bt(e,t).dropSync(),e.dbis!==void 0&&delete e.dbis[t],bt(e,Ft).removeSync(t)}a(iy,"dropDBI");function ay(e,t,r){for(let s=0;s<r.length;s++){let n=r[s];if(!e.dbis[n])try{bt(e,n)}catch(i){if(i.message===De.DBI_DOES_NOT_EXIST)PS(e,n,n!==t,n===t);else throw i}}}a(ay,"initializeDBIs");BS.exports={openDBI:bt,openEnvironment:Au,createEnvironment:zU,listDBIs:MS,listDBIDefinitions:ty,createDBI:PS,dropDBI:iy,statDBI:sy,deleteEnvironment:ey,initializeDBIs:ay,TransactionCursor:Da,environmentDataSize:ny,copyEnvironment:jU,closeEnvironment:DS}});var HS=S((k1,vS)=>{"use strict";var va=class{constructor(t=[],r=[],s=void 0){this.written_hashes=t,this.skipped_hashes=r,this.txn_time=s}};a(va,"InsertRecordsResponseObject");vS.exports=va});var GS=S(($1,qS)=>{"use strict";var Ha=class{constructor(t=[],r=[],s=void 0,n=[]){this.written_hashes=t,this.skipped_hashes=r,this.txn_time=s,this.original_records=n}};a(Ha,"UpdateRecordsResponseObject");qS.exports=Ha});var VS=S((x1,FS)=>{"use strict";var qa=class{constructor(t=[],r=void 0,s=[]){this.written_hashes=t,this.txn_time=r,this.original_records=s}};a(qa,"UpsertRecordsResponseObject");FS.exports=qa});var Qs=S((Q1,$S)=>{"use strict";var oy=X(),cy=HS(),_y=GS(),uy=VS(),Jn=as(),Qn=Ke().LMDB_ERRORS_ENUM,ly=Ye(),Dr=T(),Ey=b(),dy=require("uuid"),Y1=require("lmdb"),{handleHDBError:hy,hdb_errors:Sy}=D(),{OVERFLOW_MARKER:K1,MAX_SEARCH_KEY_LENGTH:W1}=ly,pu=Dr.TIME_STAMP_NAMES_ENUM.CREATED_TIME,cs=Dr.TIME_STAMP_NAMES_ENUM.UPDATED_TIME;async function fy(e,t,r,s,n=!0){bu(e,t,r,s),Nu(e,t,r);let i=new cy,o=[],c=[];for(let _=0;_<s.length;_++){let u=s[_];kS(u,!0,n);let l=Ty(e,t,r,u),E=u[t];o.push(l),c.push(E)}return gu(o,c,s,i)}a(fy,"insertRecords");function Ty(e,t,r,s){let n=s[t];return e.dbis[t].ifNoExists(n,()=>{for(let i=0;i<r.length;i++){let o=r[i];if(o===t||s.hasOwnProperty(o)===!1)continue;let c=s[o];if(typeof c=="function"){let u=c([[{}]]);Array.isArray(u)&&(c=u[0][Dr.FUNC_VAL],s[o]=c)}let _=Jn.getIndexedValues(c);if(_)for(let u=0,l=_.length;u<l;u++)e.dbis[o].put(_[u],n)}e.dbis[t].put(n,s,s[cs])})}a(Ty,"insertRecord");function my(e,t=[]){let r=0;for(let s=0;s<t.length;s++){let n=t[s];e.splice(n-r,1),r++}}a(my,"removeSkippedRecords");function kS(e,t,r=!0){let s=Date.now();(r===!0||!Number.isInteger(e[cs]))&&(e[cs]=s),t===!0?(r===!0||!Number.isInteger(e[pu]))&&(e[pu]=s):delete e[pu]}a(kS,"setTimestamps");function Nu(e,t,r){r.indexOf(Dr.TIME_STAMP_NAMES_ENUM.CREATED_TIME)<0&&r.push(Dr.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.indexOf(Dr.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)<0&&r.push(Dr.TIME_STAMP_NAMES_ENUM.UPDATED_TIME),oy.initializeDBIs(e,t,r)}a(Nu,"initializeTransaction");async function Ry(e,t,r,s,n=!0){bu(e,t,r,s),Nu(e,t,r);let i=new _y,o=[],c=[],_=[];for(let u=0;u<s.length;u++){let l=s[u],E=l[t],d;try{d=Iu(e,t,l,E,i,!0,n)}catch{i.skipped_hashes.push(E),o.push(u);continue}c.push(d),_.push(E)}return gu(c,_,s,i,o)}a(Ry,"updateRecords");async function Ay(e,t,r,s,n=!0){try{bu(e,t,r,s)}catch(_){throw hy(_,_.message,Sy.HTTP_STATUS_CODES.BAD_REQUEST)}Nu(e,t,r);let i=new uy,o=[],c=[];for(let _=0;_<s.length;_++){let u=s[_],l;Ey.isEmpty(u[t])?(l=dy.v4(),u[t]=l):l=u[t];let E=Iu(e,t,u,l,i,!1,n);o.push(E),c.push(l)}return gu(o,c,s,i)}a(Ay,"upsertRecords");async function gu(e,t,r,s,n=[]){let i=await Promise.all(e);for(let o=0,c=i.length;o<c;o++)i[o]===!0?s.written_hashes.push(t[o]):(s.skipped_hashes.push(t[o]),n.push(o));return s.txn_time=Jn.getMicroTime(),my(r,n),s}a(gu,"finalizeWrite");function Iu(e,t,r,s,n,i=!1,o=!0){let c=e.dbis[t],_=c.getEntry(s),u=_?.value,l=u;if(!u){if(i)return!1;u={}}if(kS(r,!l,o),Number.isInteger(r[cs])&&u[cs]>r[cs])return!1;l&&n.original_records.push(u);let E,d=a(()=>{for(let m in r){if(!r.hasOwnProperty(m)||m===t)continue;let R=r[m],C=e.dbis[m];if(C===void 0)continue;let L=u[m];if(typeof R=="function"){let z=R([[u]]);Array.isArray(z)&&(R=z[0][Dr.FUNC_VAL],r[m]=R)}if(R===L)continue;let B=Jn.getIndexedValues(L);if(B)for(let z=0,V=B.length;z<V;z++)C.remove(B[z],s);if(B=Jn.getIndexedValues(R),B)for(let z=0,V=B.length;z<V;z++)C.put(B[z],s)}let h=Object.assign({},u,r);c.put(s,h,h[cs])},"do_put");return _?E=c.ifVersion(s,_.version,d):E=c.ifNoExists(s,d),E.then(h=>h?!0:Iu(e,t,r,s,n,i,o))}a(Iu,"updateUpsertRecord");function Oy(e,t,r){if(Jn.validateEnv(e),t===void 0)throw new Error(Qn.HASH_ATTRIBUTE_REQUIRED);if(!Array.isArray(r))throw r===void 0?new Error(Qn.WRITE_ATTRIBUTES_REQUIRED):new Error(Qn.WRITE_ATTRIBUTES_MUST_BE_ARRAY)}a(Oy,"validateBasic");function bu(e,t,r,s){if(Oy(e,t,r),!Array.isArray(s))throw s===void 0?new Error(Qn.RECORDS_REQUIRED):new Error(Qn.RECORDS_MUST_BE_ARRAY)}a(bu,"validateWrite");$S.exports={insertRecords:fy,updateRecords:Ry,upsertRecords:Ay}});var te=S((J1,YS)=>{"use strict";var wu=T(),Js=Y(),Cu=require("path");Js.initSync();var Ga,Fa,Va;function xS(){if(Ga!==void 0)return Ga;if(Js.getHdbBasePath()!==void 0)return Ga=Cu.join(Js.getHdbBasePath(),wu.SCHEMA_DIR_NAME),Ga}a(xS,"getBaseSchemaPath");function py(){if(Fa!==void 0)return Fa;if(Js.getHdbBasePath()!==void 0)return Fa=Cu.join(xS(),wu.SYSTEM_SCHEMA_NAME),Fa}a(py,"getSystemSchemaPath");function Ny(){if(Va!==void 0)return Va;if(Js.getHdbBasePath()!==void 0)return Va=Cu.join(Js.getHdbBasePath(),wu.TRANSACTIONS_DIR_NAME),Va}a(Ny,"getTransactionAuditStorePath");YS.exports={getBaseSchemaPath:xS,getSystemSchemaPath:py,getTransactionAuditStorePath:Ny}});var Er=S((X1,QS)=>{"use strict";var WS=b(),KS=T(),$a=/^[\x20-\x2E|\x30-\x5F|\x61-\x7E]*$/,Lu=require("joi"),ka={schema_format:{pattern:$a,message:"names cannot include backticks or forward slashes"},schema_length:{maximum:250,tooLong:"cannot exceed 250 characters"}},gy=Lu.alternatives(Lu.string().min(1).max(ka.schema_length.maximum).pattern($a).messages({"string.pattern.base":"{:#label} "+ka.schema_format.message}),Lu.number()).required();function Iy(e,t){return t?typeof t!="string"?`'${e}' must be a string`:t.length?t.length>ka.schema_length.maximum?`'${e}' maximum of 250 characters`:$a.test(t)?"":`'${e}' has illegal characters`:`'${e}' must be at least one character`:`'${e}' is required`}a(Iy,"checkValidTable");function by(e,t){return WS.doesSchemaExist(e)?e:t.message(`Schema '${e}' does not exist`)}a(by,"validateSchemaExists");function wy(e,t){let r=t.state.ancestors[0].schema;return WS.doesTableExist(r,e)?e:t.message(`Table '${e}' does not exist`)}a(wy,"validateTableExists");function Cy(e,t){return e.toLowerCase()===KS.SYSTEM_SCHEMA_NAME?t.message(`'subscriptions[${t.state.path[1]}]' invalid schema name, '${KS.SYSTEM_SCHEMA_NAME}' name is reserved`):e}a(Cy,"validateSchemaName");QS.exports={common_validators:ka,schema_regex:$a,hdb_schema_table:gy,validateSchemaExists:by,validateTableExists:wy,validateSchemaName:Cy,checkValidTable:Iy}});var xa=S((Z1,JS)=>{var{common_validators:Mr}=Er(),Xn=de(),Vt="is required",Z={schema:{presence:!0,format:Mr.schema_format,length:Mr.schema_length},table:{presence:!0,format:Mr.schema_format,length:Mr.schema_length},attribute:{presence:!0,format:Mr.schema_format,length:Mr.schema_length},hash_attribute:{presence:!0,format:Mr.schema_format,length:Mr.schema_length}};function Zn(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(Zn,"makeAttributesStrings");function Ly(e){return e=Zn(e),Z.schema.presence={message:Vt},Z.table.presence=!1,Z.attribute.presence=!1,Z.hash_attribute.presence=!1,Xn.validateObject(e,Z)}a(Ly,"schema_object");function Uy(e){return e=Zn(e),Z.schema.presence={message:Vt},Z.table.presence={message:Vt},Z.attribute.presence=!1,Z.hash_attribute.presence=!1,Xn.validateObject(e,Z)}a(Uy,"table_object");function yy(e){return e=Zn(e),Z.schema.presence={message:Vt},Z.table.presence={message:Vt},Z.attribute.presence=!1,Z.hash_attribute.presence={message:Vt},Xn.validateObject(e,Z)}a(yy,"create_table_object");function Dy(e){return e=Zn(e),Z.schema.presence={message:Vt},Z.table.presence={message:Vt},Z.attribute.presence={message:Vt},Z.hash_attribute.presence=!1,Xn.validateObject(e,Z)}a(Dy,"attribute_object");function My(e){return e=Zn(e),Z.schema.presence={message:Vt},Z.table.presence={message:Vt},Z.attribute.presence=!1,Z.hash_attribute.presence=!1,Xn.validateObject(e,Z)}a(My,"describe_table");function Py(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(Py,"validateTableResidence");JS.exports={schema_object:Ly,create_table_object:yy,table_object:Uy,attribute_object:Dy,describe_table:My,validateTableResidence:Py}});var ZS=S((z1,XS)=>{"use strict";var By=require("uuid"),Ya=class{constructor(t,r,s,n){this.schema=t,this.table=r,this.attribute=s,this.id=n||By.v4(),this.schema_table=`${this.schema}.${this.table}`}};a(Ya,"CreateAttributeObject");XS.exports=Ya});var Wa=S((j1,zS)=>{"use strict";var vy=ZS(),Ka=class extends vy{constructor(t,r,s,n,i=!0,o=!1){super(t,r,s,n),this.dup_sort=i,this.is_hash_attribute=o}};a(Ka,"LMDBCreateAttributeObject");zS.exports=Ka});var ef=S((eJ,jS)=>{"use strict";jS.exports=qy;var Hy="inserted";function qy(e,t,r,s){let n={message:`${e} ${t.length} of ${r.records.length} records`,skipped_hashes:s};return e===Hy?(n.inserted_hashes=t,n):(n.update_hashes=t,n)}a(qy,"returnObject")});var Qa=S((tJ,rf)=>{"use strict";var Gy=T(),Uu=X(),Fy=Qs(),{getSystemSchemaPath:Vy,getBaseSchemaPath:ky}=te(),$y=require("path"),xy=ts(),Yy=xa(),Ky=Wa(),Wy=ef(),{handleHDBError:Qy,hdb_errors:Jy}=D(),Xy=b(),yu=xy.hdb_attribute,tf=[];for(let e=0;e<yu.attributes.length;e++)tf.push(yu.attributes[e].attribute);var Zy="inserted";rf.exports=zy;async function zy(e){let t=Yy.attribute_object(e);if(t)throw Qy(new Error,t.message,Jy.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0);e.is_hash_attribute=e.is_hash_attribute=="true",e.dup_sort=Xy.isEmpty(e.dup_sort)||e.dup_sort=="true";let r=[];if(global.hdb_schema[e.schema]&&global.hdb_schema[e.schema][e.table]&&(r=global.hdb_schema[e.schema][e.table].attributes),Array.isArray(r)&&r.length>0){for(let n of r)if(n.attribute===e.attribute)throw new Error(`attribute '${n.attribute}' already exists in ${e.schema}.${e.table}`)}let s=new Ky(e.schema,e.table,e.attribute,e.id);try{let n=await Uu.openEnvironment($y.join(ky(),e.schema.toString()),e.table);if(n.dbis[e.attribute]!==void 0)throw new Error(`attribute '${e.attribute}' already exists in ${e.schema}.${e.table}`);Uu.createDBI(n,e.attribute,e.dup_sort,e.is_hash_attribute);let i=await Uu.openEnvironment(Vy(),Gy.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME),{written_hashes:o,skipped_hashes:c}=await Fy.insertRecords(i,yu.hash_attribute,tf,[s]);return Wy(Zy,o,{records:[s]},c)}catch(n){throw n}}a(zy,"lmdbCreateAttribute")});var Mu=S((rJ,nf)=>{var{hdb_schema_table:sf}=Er(),jy=de(),Du=require("joi"),eD={undefined:"undefined",null:"null"},tD=a((e,t)=>{let r=Object.keys(e),s=r.length,n;for(let i=0;i<s;i++){let o=r[i];(!o||o.length===0||eD[o]!==void 0)&&(n===void 0?n=`Invalid attribute name: '${o}'`:n+=`. Invalid attribute name: '${o}'`)}return n?t.message(n):e},"custom_records_val"),rD=Du.object({schema:sf,table:sf,records:Du.array().items(Du.object().custom(tD)).required()});nf.exports=function(e){return jy.validateBySchema(e,rD)}});var Ja=S((nJ,of)=>{"use strict";var dr=b(),af=I(),sJ=Mu();of.exports=sD;function sD(e){if(dr.isEmpty(e))throw new Error("invalid update parameters defined.");if(dr.isEmptyOrZeroLength(e.schema))throw new Error("invalid schema specified.");if(dr.isEmptyOrZeroLength(e.table))throw new Error("invalid table specified.");if(!Array.isArray(e.records))throw new Error("records must be an array");let t=global.hdb_schema[e.schema][e.table];if(dr.isEmpty(t))throw new Error(`could not retrieve schema:${e.schema} and table ${e.table}`);let r=t.hash_attribute,s=new Set,n={},i=!1;return e.operation==="update"&&(i=!0),e.records.forEach(o=>{if(i&&dr.isEmptyOrZeroLength(o[r]))throw af.error("a valid hash attribute must be provided with update record:",o),new Error("a valid hash attribute must be provided with update record, check log for more info");if(!dr.isEmptyOrZeroLength(o[r])&&(o[r]==="null"||o[r]==="undefined"))throw af.error(`a valid hash value must be provided with ${e.operation} record:`,o),new Error(`Invalid hash value: '${o[r]}' is not a valid hash attribute value, check log for more info`);!dr.isEmpty(o[r])&&o[r]!==""&&s.has(dr.autoCast(o[r]))&&(o.skip=!0),s.add(dr.autoCast(o[r]));for(let c in o)n[c]=1}),n[r]=1,{schema_table:t,hashes:Array.from(s),attributes:Object.keys(n)}}a(sD,"insertUpdateValidate")});var zn=S((iJ,cf)=>{"use strict";var nD=T().OPERATIONS_ENUM,Xa=class{constructor(t,r,s,n,i=void 0){this.operation=nD.INSERT,this.schema=t,this.table=r,this.hash_attribute=s,this.records=n,this.__origin=i}};a(Xa,"InsertObject");cf.exports=Xa});var za=S((oJ,_f)=>{"use strict";var aJ=zn(),Za=T(),Bu=b(),Pu=I(),iD=require("uuid"),{handleHDBError:jn,hdb_errors:aD}=D(),{HDB_ERROR_MSGS:ei,HTTP_STATUS_CODES:ti}=aD;_f.exports=oD;function oD(e,t,r){for(let n=0;n<t.length;n++)cD(t[n]);let{records:s}=e;for(let n=0;n<s.length;n++){let i=s[n];_D(i,r,e.operation)}}a(oD,"processRows");function cD(e){if(Buffer.byteLength(String(e))>Za.INSERT_MODULE_ENUM.MAX_CHARACTER_SIZE)throw jn(new Error,ei.ATTR_NAME_LENGTH_ERR(e),ti.BAD_REQUEST,void 0,void 0,!0);if(Bu.isEmptyOrZeroLength(e)||Bu.isEmpty(e.trim()))throw jn(new Error,ei.ATTR_NAME_NULLISH_ERR,ti.BAD_REQUEST,void 0,void 0,!0)}a(cD,"validateAttribute");function _D(e,t,r){if(!e.hasOwnProperty(t)||Bu.isEmptyOrZeroLength(e[t])){if(r===Za.OPERATIONS_ENUM.INSERT||r===Za.OPERATIONS_ENUM.UPSERT){e[t]=iD.v4();return}throw Pu.error("Update transaction aborted due to record with no hash value:",e),jn(new Error,ei.RECORD_MISSING_HASH_ERR,ti.BAD_REQUEST,void 0,void 0,!0)}if(Buffer.byteLength(String(e[t]))>Za.INSERT_MODULE_ENUM.MAX_CHARACTER_SIZE)throw Pu.error(e),jn(new Error,ei.HASH_VAL_LENGTH_ERR,ti.BAD_REQUEST,void 0,void 0,!0);if(isNaN(e[t])&&e[t].includes("/"))throw Pu.error(e),jn(new Error,ei.INVALID_FORWARD_SLASH_IN_HASH_ERR,ti.BAD_REQUEST,void 0,void 0,!0)}a(_D,"validateHash")});var lf=S((cJ,uf)=>{"use strict";var ja=class{constructor(t,r){this.type=t,this.message=r}};a(ja,"IPCEventObject");uf.exports=ja});var Pr=S((_J,Ef)=>{"use strict";var uD=I(),vu=b(),lD=T(),{IPC_ERRORS:ri}=Ke();Ef.exports={sendIpcEvent:ED,validateEvent:dD,SchemaEventMsg:hD,UserEventMsg:SD};function ED(e){global.hdb_ipc?global.hdb_ipc.emitToServer(e):uD.warn("Tried to send event:",e,"to HDB IPC client but it does not exist")}a(ED,"sendIpcEvent");function dD(e){if(typeof e!="object")return ri.INVALID_IPC_DATA_TYPE;if(!e.hasOwnProperty("type")||vu.isEmpty(e.type))return ri.MISSING_TYPE;if(!e.hasOwnProperty("message")||vu.isEmpty(e.message))return ri.MISSING_MSG;if(!e.message.hasOwnProperty("originator")||vu.isEmpty(e.message.originator))return ri.MISSING_ORIGIN;if(lD.IPC_EVENT_TYPES[e.type.toUpperCase()]===void 0)return ri.INVALID_EVENT(e.type)}a(dD,"validateEvent");function hD(e,t,r,s=void 0,n=void 0){this.originator=e,this.operation=t,this.schema=r,this.table=s,this.attribute=n}a(hD,"SchemaEventMsg");function SD(e){this.originator=e}a(SD,"UserEventMsg")});var Xs=S((lJ,ff)=>{"use strict";var df=T(),uJ=b(),eo=I(),hf=lf(),{sendIpcEvent:Sf}=Pr();function fD(e){try{eo.trace("signalSchemaChange called with message:",e);let t=new hf(df.IPC_EVENT_TYPES.SCHEMA,e);Sf(t)}catch(t){eo.error(t)}}a(fD,"signalSchemaChange");function TD(e){try{eo.trace("signalUserChange called with message:",e);let t=new hf(df.IPC_EVENT_TYPES.USER,e);Sf(t)}catch(t){eo.error(t)}}a(TD,"signalUserChange");ff.exports={signalSchemaChange:fD,signalUserChange:TD}});var to=S((EJ,mf)=>{"use strict";var Tf=b(),mD=T(),RD=I(),AD=Qa(),OD=Wa(),pD=Xs(),{SchemaEventMsg:ND}=Pr(),gD="already exists in";mf.exports=ID;async function ID(e,t,r){try{if(Tf.isEmptyOrZeroLength(r))return r;let s=[];Tf.isEmptyOrZeroLength(t.attributes)||t.attributes.forEach(i=>{s.push(i.attribute)});let n=r.filter(i=>s.indexOf(i)<0);return n.length===0||await Promise.all(n.map(async i=>{await bD(e,t.schema,t.name,i)})),n}catch(s){throw s}}a(ID,"lmdbCheckForNewAttributes");async function bD(e,t,r,s){let n=new OD(t,r,s,void 0,!0);e&&(n.hdb_auth_header=e);try{await wD(n)}catch(i){if(typeof i=="object"&&i.message!==void 0&&i.message.includes(gD))RD.warn(`attribute ${t}.${r}.${s} already exists`);else throw i}}a(bD,"createNewAttribute");async function wD(e){let t;try{return t=await AD(e),pD.signalSchemaChange(new ND(process.pid,mD.OPERATIONS_ENUM.CREATE_ATTRIBUTE,e.schema,e.table,e.attribute)),t}catch(r){throw r}}a(wD,"createAttribute")});var Zs=S((dJ,Rf)=>{"use strict";var ro=class{constructor(t,r,s,n,i=void 0){this.operation=t,this.user_name=r,this.timestamp=s,this.hash_values=n,this.origin=i}};a(ro,"LMDBTransactionObject");Rf.exports=ro});var Of=S((hJ,Af)=>{"use strict";var CD=Zs(),LD=T().OPERATIONS_ENUM,so=class extends CD{constructor(t,r,s,n,i=void 0){super(LD.INSERT,r,s,n,i),this.records=t}};a(so,"LMDBInsertTransactionObject");Af.exports=so});var Nf=S((SJ,pf)=>{"use strict";var UD=Zs(),yD=T().OPERATIONS_ENUM,no=class extends UD{constructor(t,r,s,n,i,o=void 0){super(yD.UPDATE,s,n,i,o),this.records=t,this.original_records=r}};a(no,"LMDBUpdateTransactionObject");pf.exports=no});var If=S((fJ,gf)=>{"use strict";var DD=Zs(),MD=T().OPERATIONS_ENUM,io=class extends DD{constructor(t,r,s,n,i,o=void 0){super(MD.UPSERT,s,n,i,o),this.records=t,this.original_records=r}};a(io,"LMDBUpsertTransactionObject");gf.exports=io});var wf=S((TJ,bf)=>{"use strict";var PD=Zs(),BD=T().OPERATIONS_ENUM,ao=class extends PD{constructor(t,r,s,n,i=void 0){super(BD.DELETE,s,n,t,i),this.original_records=r}};a(ao,"LMDBDeleteTransactionObject");bf.exports=ao});var si=S((mJ,yf)=>{"use strict";var vD=require("path"),Cf=X(),HD=Of(),qD=Nf(),GD=If(),FD=wf(),zs=Ye(),Lf=b(),{CONFIG_PARAMS:VD}=T(),Uf=Y();Uf.initSync();var oo=T().OPERATIONS_ENUM,{getTransactionAuditStorePath:kD}=te();yf.exports=$D;async function $D(e,t){if(Uf.get(VD.LOGGING_AUDITLOG)===!1)return;let r=vD.join(kD(),e.schema.toString()),s=await Cf.openEnvironment(r,e.table,!0),n=xD(e,t);if(!(n===void 0||n.hash_values.length===0)&&s!==void 0){Cf.initializeDBIs(s,zs.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,zs.TRANSACTIONS_DBIS);try{let i=n.timestamp;return await s.dbis[zs.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP].ifNoExists(i,()=>{s.dbis[zs.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP].put(i,n),Lf.isEmpty(n.user_name)||s.dbis[zs.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].put(n.user_name,i);for(let o=0;o<n.hash_values.length;o++)s.dbis[zs.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE].put(n.hash_values[o],i)})}catch(i){throw i}}}a($D,"writeTransaction");function xD(e,t){let r=Lf.isEmpty(e.hdb_user)?void 0:e.hdb_user.username;if(e.operation===oo.INSERT)return new HD(e.records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===oo.UPDATE)return new qD(e.records,t.original_records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===oo.UPSERT)return new GD(e.records,t.original_records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===oo.DELETE)return new FD(t.deleted,t.original_records,r,t.txn_time,e.__origin)}a(xD,"createTransactionObject")});var Hu=S((AJ,Df)=>{"use strict";var YD=Ja(),RJ=zn(),js=T(),KD=za(),WD=Qs().insertRecords,QD=X(),JD=require("path"),XD=I(),ZD=to(),{getBaseSchemaPath:zD}=te(),jD=si();Df.exports=eM;async function eM(e){try{let{schema_table:t,attributes:r}=YD(e);KD(e,r,t.hash_attribute),e.schema!==js.SYSTEM_SCHEMA_NAME&&(r.includes(js.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||r.push(js.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.includes(js.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||r.push(js.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let s=await ZD(e.hdb_auth_header,t,r),n=JD.join(zD(),e.schema.toString()),i=await QD.openEnvironment(n,e.table),o=await WD(i,t.hash_attribute,r,e.records,e[js.CLUSTERING_FLAG]!==!0);try{await jD(e,o)}catch(c){XD.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:s,txn_time:o.txn_time}}catch(t){throw t}}a(eM,"lmdbCreateRecords")});var Bf=S((OJ,Pf)=>{"use strict";var Mf=T(),tM=Hu(),rM=zn(),sM=require("fs-extra"),nM=require("path"),{getBaseSchemaPath:iM}=te();Pf.exports=aM;async function aM(e){let t=[{name:e.schema,createddate:Date.now()}],r=new rM(Mf.SYSTEM_SCHEMA_NAME,Mf.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,void 0,t);await tM(r),await sM.mkdirp(nM.join(iM(),e.schema.toString()))}a(aM,"lmdbCreateSchema")});var Hf=S((pJ,vf)=>{"use strict";var co=class{constructor(t=[],r=[],s=void 0,n=[]){this.deleted=t,this.skipped=r,this.txn_time=s,this.original_records=n}};a(co,"DeleteRecordsResponseObject");vf.exports=co});var Fu=S((bJ,Ff)=>{"use strict";var qf=X(),qu=as(),Gu=Ke().LMDB_ERRORS_ENUM,oM=Ye(),Gf=I(),NJ=b(),cM=require("lmdb"),_M=Hf(),{OVERFLOW_MARKER:gJ,MAX_SEARCH_KEY_LENGTH:IJ}=oM;async function uM(e,t,r){if(qu.validateEnv(e),t===void 0)throw new Error(Gu.HASH_ATTRIBUTE_REQUIRED);if(!Array.isArray(r))throw r===void 0?new Error(Gu.IDS_REQUIRED):new Error(Gu.IDS_MUST_BE_ARRAY);try{let s=qf.listDBIs(e);qf.initializeDBIs(e,t,s);let n=new _M,i,o=[],c=[];for(let E=0,d=r.length;E<d;E++)try{i=r[E];let h=e.dbis[t].get(i);if(!h){n.skipped.push(i);continue}let m=e.dbis[t].ifVersion(i,cM.IF_EXISTS,()=>{e.dbis[t].remove(i);for(let R=0;R<s.length;R++){let C=s[R];if(!h.hasOwnProperty(C)||C===t)continue;let L=e.dbis[C],B=h[C];if(B!=null)try{let z=qu.getIndexedValues(B);if(z)for(let V=0,Q=z.length;V<Q;V++)L.remove(z[V],i)}catch{Gf.warn(`cannot delete from attribute: ${C}, ${B}:${i}`)}}});o.push(m),c.push(i),n.original_records.push(h)}catch(h){Gf.warn(h),n.skipped.push(i)}let _=[],u=await Promise.all(o);for(let E=0,d=u.length;E<d;E++)u[E]===!0?n.deleted.push(c[E]):(n.skipped.push(c[E]),_.push(E));let l=0;for(let E=0;E<_.length;E++){let d=_[E];n.original_records.splice(d-l,1),l++}return n.txn_time=qu.getMicroTime(),n}catch(s){throw s}}a(uM,"deleteRecords");Ff.exports={deleteRecords:uM}});var ni=S((wJ,kf)=>{"use strict";var en=b(),lM=Fu(),EM=X(),dM=require("path"),{getBaseSchemaPath:hM}=te(),SM=si(),fM=I();kf.exports=TM;async function TM(e,t=!0){let s=global.hdb_schema[e.schema][e.table].hash_attribute;if(en.isEmpty(s))throw new Error(`could not retrieve hash attribute for schema:${e.schema} and table ${e.table}`);try{if(en.isEmptyOrZeroLength(e.hash_values)&&!en.isEmptyOrZeroLength(e.records)){e.hash_values=[];for(let c=0;c<e.records.length;c++){let _=e.records[c][s];en.isEmpty(_)||e.hash_values.push(_)}}if(en.isEmptyOrZeroLength(e.hash_values))return Vf([],[]);if(!Array.isArray(e.hash_values))throw new Error("hash_values must be an array");if(en.isEmptyOrZeroLength(e.records)){e.records=[];for(let c=0;c<e.hash_values.length;c++)e.records[c]={[s]:e.hash_values[c]}}let n=dM.join(hM(),e.schema.toString()),i=await EM.openEnvironment(n,e.table),o=await lM.deleteRecords(i,s,e.hash_values);try{t===!0&&await SM(e,o)}catch(c){fM.error(`unable to write transaction due to ${c.message}`)}return Vf(o.deleted,o.skipped,o.txn_time)}catch(n){throw n}}a(TM,"lmdbDeleteRecords");function Vf(e,t,r){let s=e.length+t.length,n=s===1?"record":"records";return{message:`${e.length} of ${s} ${n} successfully deleted`,deleted_hashes:e,skipped_hashes:t,txn_time:r}}a(Vf,"createDeleteResponse")});var ku=S((LJ,$f)=>{"use strict";var mM=T(),CJ=as();function Vu(e,t){let r=Object.create(null);if(t.length===1&&mM.SEARCH_WILDCARDS.indexOf(t[0])>=0)Object.assign(r,e);else for(let s=0;s<t.length;s++){let n=t[s],i=e[n];r[n]=i===void 0?null:i}return r}a(Vu,"parseRow");function RM(e,t,r,s){let n=Vu(r,e);s.push(n)}a(RM,"searchAll");function AM(e,t,r,s){let n=Vu(r,e);s[t]=n}a(AM,"searchAllToMap");function OM(e,t,r){r[e]===void 0&&(r[e]=[]),r[e].push(t)}a(OM,"iterateDBI");function _s(e,t,r,s,n){let i=Object.create(null);i[n]=e;let o;s===n?o=e:(o=t,s!==void 0&&(i[s]=o)),r[0].push(o),r[1].push(i)}a(_s,"pushResults");function pM(e,t,r,s,n,i){t.toString().endsWith(e)&&_s(t,r,s,n,i)}a(pM,"endsWith");function NM(e,t,r,s,n,i){t.toString().includes(e)&&_s(t,r,s,n,i)}a(NM,"contains");function gM(e,t,r,s,n,i){t>e&&_s(t,r,s,n,i)}a(gM,"greaterThanCompare");function IM(e,t,r,s,n,i){t>=e&&_s(t,r,s,n,i)}a(IM,"greaterThanEqualCompare");function bM(e,t,r,s,n,i){t<e&&_s(t,r,s,n,i)}a(bM,"lessThanCompare");function wM(e,t,r,s,n,i){t<=e&&_s(t,r,s,n,i)}a(wM,"lessThanEqualCompare");$f.exports={parseRow:Vu,searchAll:RM,searchAllToMap:AM,iterateDBI:OM,endsWith:pM,contains:NM,greaterThanCompare:gM,greaterThanEqualCompare:IM,lessThanCompare:bM,lessThanEqualCompare:wM,pushResults:_s}});var tn=S((DJ,Jf)=>{"use strict";var wt=X(),CM=I(),St=as(),Br=Ye(),ce=Ke().LMDB_ERRORS_ENUM,UJ=b(),LM=T(),kt=ku(),yJ=require("lmdb"),{OVERFLOW_MARKER:xf,MAX_SEARCH_KEY_LENGTH:UM}=Br,ii={lazy:!0};function Yf(e,t,r,s,n=!1,i=void 0,o=void 0){let c=Object.create(null),_=wt.openDBI(e,r);_[Br.DBI_DEFINITION_NAME].is_hash_attribute&&(t=r);let u=$u(e,t,r);for(let{key:l,value:E}of _.getRange({start:n?void 0:!1,end:n?!1:void 0,limit:i,offset:o,reverse:n}))s(u(l,E),E,c,t,r);return c}a(Yf,"iterateFullIndex");function ai(e,t,r,s,n,i=!1,o=void 0,c=void 0,_=!1,u=!1){let l=[[],[]],E=wt.openDBI(e,r),d=$u(e,t,r);E[Br.DBI_DEFINITION_NAME].is_hash_attribute&&(t=r);let h=i===!0?s:n,m=i===!0?n:s,R=i===!0?!_:!u,C=i===!0?u:_;for(let{key:L,value:B}of E.getRange({start:m,end:h,reverse:i,limit:o,offset:c,inclusiveEnd:R,exclusiveStart:C}))kt.pushResults(d(L,B),B,l,t,r);return l}a(ai,"iterateRangeBetween");function $u(e,t,r){let s;return function(n,i){if(typeof n=="string"&&n.endsWith(xf)){if(!s)if(t)s=wt.openDBI(e,t);else{let c=wt.listDBIs(e);for(let _=0,u=c.length;_<u&&(s=wt.openDBI(e,c[_]),!s[Br.DBI_DEFINITION_NAME].is_hash_attribute);_++);}n=s.get(i,ii)[r]}return n}}a($u,"getOverflowCheck");function yM(e,t,r,s=!1,n=void 0,i=void 0){if(St.validateEnv(e),t===void 0)throw new Error(ce.HASH_ATTRIBUTE_REQUIRED);_o(r),r=oi(e,r);let o=[],c=wt.openDBI(e,t);for(let{key:_,value:u}of c.getRange({start:s?void 0:!1,end:s?!1:void 0,limit:n,offset:i,reverse:s}))kt.searchAll(r,_,u,o);return o}a(yM,"searchAll");function DM(e,t,r,s=!1,n=void 0,i=void 0){if(St.validateEnv(e),t===void 0)throw new Error(ce.HASH_ATTRIBUTE_REQUIRED);return _o(r),r=oi(e,r),Yf(e,t,t,kt.searchAllToMap.bind(null,r),s,n,i)}a(DM,"searchAllToMap");function MM(e,t,r=!1,s=void 0,n=void 0){if(St.validateEnv(e),t===void 0)throw new Error(ce.ATTRIBUTE_REQUIRED);return Yf(e,void 0,t,kt.iterateDBI,r,s,n)}a(MM,"iterateDBI");function PM(e,t){if(St.validateEnv(e),t===void 0)throw new Error(ce.HASH_ATTRIBUTE_REQUIRED);return wt.statDBI(e,t).entryCount}a(PM,"countAll");function BM(e,t,r,s,n=!1,i=void 0,o=void 0){vr(e,r,s);let c=wt.openDBI(e,r);s=St.convertKeyValueToWrite(s);let _=[[],[]];if(c[Br.DBI_DEFINITION_NAME].is_hash_attribute){t=r;let u=c.get(s,ii);u!==void 0&&kt.pushResults(s,u,_,t,r)}else for(let u of c.getValues(s,{reverse:n,limit:i,offset:o}))kt.pushResults(s,u,_,t,r);return _}a(BM,"equals");function vM(e,t,r){return vr(e,t,r),wt.openDBI(e,t).getValuesCount(r)}a(vM,"count");function HM(e,t,r,s,n=!1,i=void 0,o=void 0){vr(e,r,s);let c=[[],[]],_=wt.openDBI(e,r);_[Br.DBI_DEFINITION_NAME].is_hash_attribute&&(t=r),s=St.convertKeyValueToWrite(s);let u=!0;if(typeof s=="number"&&(u=!1),n===!0){let l;for(let E of _.getKeys({start:s}))if(!E.startsWith(s)){l=E;break}l!==void 0&&(Number.isInteger(o)?o++:i++);for(let{key:E,value:d}of _.getRange({start:l,end:void 0,reverse:n,limit:i,offset:o}))if(E!==l){if(E.toString().startsWith(s))kt.pushResults(E,d,c,t,r);else if(u===!0)break}}else for(let{key:l,value:E}of _.getRange({start:s,reverse:n,limit:i,offset:o}))if(l.toString().startsWith(s))kt.pushResults(l,E,c,t,r);else if(u===!0)break;return c}a(HM,"startsWith");function qM(e,t,r,s,n=!1,i=void 0,o=void 0){return Kf(e,t,r,s,n,i,o,!0)}a(qM,"endsWith");function Kf(e,t,r,s,n=!1,i=void 0,o=void 0,c=!1){vr(e,r,s);let _=[[],[]],u=wt.openDBI(e,r);u[Br.DBI_DEFINITION_NAME].is_hash_attribute&&(t=r);let l=$u(e,t,r);o=Number.isInteger(o)?o:0;for(let d of u.getKeys({end:n?!1:void 0,reverse:n})){if(i===0)break;let h=d.toString();if(h.endsWith(xf))for(let m of u.getValues(d)){let R=l(d,m);(c?R.endsWith(s):R.includes(s))&&E(R,m)}else if(c?h.endsWith(s):h.includes(s))if(u[Br.DBI_DEFINITION_NAME].is_hash_attribute)E(d,d);else for(let m of u.getValues(d))E(d,m)}function E(d,h){if(o>0){o--;return}i!==0&&(kt.pushResults(d,h,_,t,r),i--)}return a(E,"found_match"),_}a(Kf,"contains");function GM(e,t,r,s,n=!1,i=void 0,o=void 0){vr(e,r,s);let c=typeof s,_;return c==="string"?_="\uFFFF":c==="number"?_=1/0:c==="boolean"&&(_=!0),ai(e,t,r,s,_,n,i,o,!0,!1)}a(GM,"greaterThan");function FM(e,t,r,s,n=!1,i=void 0,o=void 0){vr(e,r,s);let c=typeof s,_;return c==="string"?_="\uFFFF":c==="number"?_=1/0:c==="boolean"&&(_=!0),ai(e,t,r,s,_,n,i,o,!1,!1)}a(FM,"greaterThanEqual");function VM(e,t,r,s,n=!1,i=void 0,o=void 0){vr(e,r,s);let c=typeof s,_;return c==="string"?_="\0":c==="number"?_=-1/0:c==="boolean"&&(_=!1),ai(e,t,r,_,s,n,i,o,!1,!0)}a(VM,"lessThan");function kM(e,t,r,s,n=!1,i=void 0,o=void 0){vr(e,r,s);let c=typeof s,_;return c==="string"?_="\0":c==="number"?_=-1/0:c==="boolean"&&(_=!1),ai(e,t,r,_,s,n,i,o,!1,!1)}a(kM,"lessThanEqual");function $M(e,t,r,s,n,i=!1,o=void 0,c=void 0){if(St.validateEnv(e),r===void 0)throw new Error(ce.ATTRIBUTE_REQUIRED);if(s===void 0)throw new Error(ce.START_VALUE_REQUIRED);if(n===void 0)throw new Error(ce.END_VALUE_REQUIRED);if(s=St.convertKeyValueToWrite(s),n=St.convertKeyValueToWrite(n),s>n)throw new Error(ce.END_VALUE_MUST_BE_GREATER_THAN_START_VALUE);return ai(e,t,r,s,n,i,o,c)}a($M,"between");function xM(e,t,r,s){if(St.validateEnv(e),t===void 0)throw new Error(ce.HASH_ATTRIBUTE_REQUIRED);if(_o(r),r=oi(e,r),s===void 0)throw new Error(ce.ID_REQUIRED);let n=null,i=e.dbis[t].get(s,r.length<3?ii:void 0);return i&&(n=kt.parseRow(i,r)),n}a(xM,"searchByHash");function YM(e,t,r){if(St.validateEnv(e),t===void 0)throw new Error(ce.HASH_ATTRIBUTE_REQUIRED);if(r===void 0)throw new Error(ce.ID_REQUIRED);let s=!0;return e.dbis[t].get(r,ii)===void 0&&(s=!1),s}a(YM,"checkHashExists");function KM(e,t,r,s,n=[]){Qf(e,t,r,s,n);let i=Wf(e,t,r,s,n);return Object.values(i)}a(KM,"batchSearchByHash");function WM(e,t,r,s,n=[]){return Qf(e,t,r,s,n),Wf(e,t,r,s,n)}a(WM,"batchSearchByHashToMap");function Wf(e,t,r,s,n=[]){r=oi(e,r);let i=Object.create(null),o=r.length<3?ii:void 0;for(let c=0;c<s.length;c++){let _=s[c];try{let u=e.dbis[t].get(_,o);if(u){let l=kt.parseRow(u,r);i[_]=l}else n.push(_)}catch(u){throw CM.warn(u),u}}return i}a(Wf,"batchHashSearch");function Qf(e,t,r,s,n){if(St.validateEnv(e),t===void 0)throw new Error(ce.HASH_ATTRIBUTE_REQUIRED);if(_o(r),!Array.isArray(s))throw s===void 0?new Error(ce.IDS_REQUIRED):new Error(ce.IDS_MUST_BE_ARRAY);Array.isArray(n)||(n=[])}a(Qf,"initializeBatchSearchByHash");function _o(e){if(!Array.isArray(e))throw e===void 0?new Error(ce.FETCH_ATTRIBUTES_REQUIRED):new Error(ce.FETCH_ATTRIBUTES_MUST_BE_ARRAY)}a(_o,"validateFetchAttributes");function vr(e,t,r){if(St.validateEnv(e),t===void 0)throw new Error(ce.ATTRIBUTE_REQUIRED);if(r===void 0)throw new Error(ce.SEARCH_VALUE_REQUIRED);if(r?.length>UM)throw new Error(ce.SEARCH_VALUE_TOO_LARGE)}a(vr,"validateComparisonFunctions");function oi(e,t){return t.length===1&&LM.SEARCH_WILDCARDS.indexOf(t[0])>=0&&(t=wt.listDBIs(e)),t}a(oi,"setGetWholeRowAttributes");Jf.exports={searchAll:yM,searchAllToMap:DM,count:vM,countAll:PM,equals:BM,startsWith:HM,endsWith:qM,contains:Kf,searchByHash:xM,setGetWholeRowAttributes:oi,batchSearchByHash:KM,batchSearchByHashToMap:WM,checkHashExists:YM,iterateDBI:MM,greaterThan:GM,greaterThanEqual:FM,lessThan:VM,lessThanEqual:kM,between:$M}});var ci=S((PJ,jf)=>{var Xf=require("lodash"),Zf=de(),W=require("joi"),QM=b(),{hdb_schema_table:$t,checkValidTable:zf}=Er(),{handleHDBError:JM,hdb_errors:XM}=D(),{HTTP_STATUS_CODES:ZM}=XM,MJ=W.object({schema:$t,table:$t,hash_values:W.array().min(1).items(W.alternatives(W.string(),W.number())).required(),get_attributes:W.array().min(1).items($t).required()}),zM=W.object({schema:$t,table:$t,search_attribute:$t,search_value:W.any().required(),get_attributes:W.array().min(1).items($t).required(),desc:W.bool(),limit:W.number().integer().min(1),offset:W.number().integer().min(0)}),jM=W.object({schema:$t,table:$t,operator:W.string().valid("and","or").default("and").lowercase(),offset:W.number().integer().min(0),limit:W.number().integer().min(1),get_attributes:W.array().min(1).items($t).required(),conditions:W.array().min(1).items(W.object({search_attribute:$t,search_type:W.string().valid("equals","contains","starts_with","ends_with","greater_than","greater_than_equal","less_than","less_than_equal","between").required(),search_value:W.when("search_type",{switch:[{is:"equals",then:W.any()},{is:"between",then:W.array().items(W.alternatives([W.string(),W.number()])).length(2)}],otherwise:W.alternatives(W.string(),W.number())}).required()})).required()});jf.exports=function(e,t){let r=null;switch(t){case"value":r=Zf.validateBySchema(e,zM);break;case"hashes":let i=function(o){n?n+=". "+o:n=o};var s=i;a(i,"addError");let n;i(zf("schema",e.schema)),i(zf("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"),n&&(r=new Error(n.trim()));break;case"conditions":r=Zf.validateBySchema(e,jM);break;default:throw new Error(`Error validating search, unknown type: ${t}`)}if(!r&&e.schema!=="system"){let n=QM.checkGlobalSchemaTable(e.schema,e.table);if(n)return JM(new Error,n,ZM.NOT_FOUND);let o=global.hdb_schema[e.schema][e.table].attributes,c=[...e.get_attributes];if(t==="value"&&c.push(e.search_attribute),t==="conditions")for(let u=0,l=e.conditions.length;u<l;u++){let E=e.conditions[u];c.push(E.search_attribute)}let _=Xf.filter(c,u=>u!=="*"&&u.attribute!=="*"&&!Xf.some(o,l=>l===u||l.attribute===u||l.attribute===u.attribute));if(_&&_.length>0){let u=_.join(", ");return u=u.replace(/,([^,]*)$/," and$1"),new Error(`unknown attribute '${u}'`)}}return r}});var xu=S((BJ,eT)=>{"use strict";var eP=X(),tP=ci(),rP=require("path"),{getBaseSchemaPath:sP}=te();eT.exports=nP;function nP(e){let t=tP(e,"hashes");if(t)throw t;let r=rP.join(sP(),e.schema.toString());return eP.openEnvironment(r,e.table)}a(nP,"initialize")});var Yu=S((vJ,tT)=>{"use strict";var iP=tn(),aP=xu();tT.exports=oP;async function oP(e){try{let t=await aP(e),r=global.hdb_schema[e.schema][e.table];return iP.batchSearchByHashToMap(t,r.hash_attribute,e.get_attributes,e.hash_values)}catch(t){throw t}}a(oP,"lmdbGetDataByHash")});var us=S((HJ,rT)=>{"use strict";var uo=class{constructor(t,r,s,n){this.schema=t,this.table=r,this.hash_values=s,this.get_attributes=n}};a(uo,"SearchByHashObject");rT.exports=uo});var nT=S((GJ,sT)=>{"use strict";var qJ=us(),cP=tn(),_P=xu();sT.exports=uP;async function uP(e){try{let t=await _P(e),r=global.hdb_schema[e.schema][e.table];return cP.batchSearchByHash(t,r.hash_attribute,e.get_attributes,e.hash_values)}catch(t){throw t}}a(uP,"lmdbSearchByHash")});var xt=S((FJ,iT)=>{"use strict";var lo=class{constructor(t,r,s,n,i,o,c,_=!1,u=void 0,l=void 0){this.schema=t,this.table=r,this.search_attribute=s,this.search_value=n,this.hash_attribute=i,this.get_attributes=o,this.end_value=c,this.reverse=_,this.limit=u,this.offset=l}};a(lo,"SearchObject");iT.exports=lo});var Eo=S((VJ,uT)=>{"use strict";var Qe=tn(),lP=X(),EP=require("path"),dP=b(),U=Ye(),ls=T(),{getBaseSchemaPath:hP}=te(),SP=ts(),aT=Ke().LMDB_ERRORS_ENUM,{compareKeys:rn}=require("ordered-binary"),hr=ls.SEARCH_WILDCARDS;async function fP(e,t,r){let s;e.schema===ls.SYSTEM_SCHEMA_NAME?s=SP[e.table]:s=global.hdb_schema[e.schema][e.table];let n=_T(e,s.hash_attribute,r,t);return oT(e,n,s.hash_attribute,r)}a(fP,"prepSearch");async function oT(e,t,r,s){let n=EP.join(hP(),e.schema.toString()),i=await lP.openEnvironment(n,e.table),o=cT(i,e,t,r);if([U.SEARCH_TYPES.BATCH_SEARCH_BY_HASH,U.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP,U.SEARCH_TYPES.SEARCH_ALL,U.SEARCH_TYPES.SEARCH_ALL_TO_MAP].indexOf(t)>=0)return o;if(RP(e,r)===!1)return s===!0?mP(o):o[1];let _=o[0];return s===!0?Qe.batchSearchByHashToMap(i,r,e.get_attributes,_):Qe.batchSearchByHash(i,r,e.get_attributes,_)}a(oT,"executeSearch");function cT(e,t,r,s){let n,i=s;t.get_attributes.indexOf(s)<0&&(i=void 0);let{reverse:o,limit:c,offset:_}=t;switch(o=typeof o=="boolean"?o:!1,c=Number.isInteger(c)?c:void 0,_=Number.isInteger(_)?_:void 0,r){case U.SEARCH_TYPES.EQUALS:n=Qe.equals(e,i,t.search_attribute,t.search_value,o,c,_);break;case U.SEARCH_TYPES.CONTAINS:n=Qe.contains(e,i,t.search_attribute,t.search_value,o,c,_);break;case U.SEARCH_TYPES.ENDS_WITH:case U.SEARCH_TYPES._ENDS_WITH:n=Qe.endsWith(e,i,t.search_attribute,t.search_value,o,c,_);break;case U.SEARCH_TYPES.STARTS_WITH:case U.SEARCH_TYPES._STARTS_WITH:n=Qe.startsWith(e,i,t.search_attribute,t.search_value,o,c,_);break;case U.SEARCH_TYPES.BATCH_SEARCH_BY_HASH:return Qe.batchSearchByHash(e,t.search_attribute,t.get_attributes,[t.search_value]);case U.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP:return Qe.batchSearchByHashToMap(e,t.search_attribute,t.get_attributes,[t.search_value]);case U.SEARCH_TYPES.SEARCH_ALL:return Qe.searchAll(e,s,t.get_attributes,o,c,_);case U.SEARCH_TYPES.SEARCH_ALL_TO_MAP:return Qe.searchAllToMap(e,s,t.get_attributes,o,c,_);case U.SEARCH_TYPES.BETWEEN:n=Qe.between(e,i,t.search_attribute,t.search_value,t.end_value,o,c,_);break;case U.SEARCH_TYPES.GREATER_THAN:case U.SEARCH_TYPES._GREATER_THAN:n=Qe.greaterThan(e,i,t.search_attribute,t.search_value,o,c,_);break;case U.SEARCH_TYPES.GREATER_THAN_EQUAL:case U.SEARCH_TYPES._GREATER_THAN_EQUAL:n=Qe.greaterThanEqual(e,i,t.search_attribute,t.search_value,o,c,_);break;case U.SEARCH_TYPES.LESS_THAN:case U.SEARCH_TYPES._LESS_THAN:n=Qe.lessThan(e,i,t.search_attribute,t.search_value,o,c,_);break;case U.SEARCH_TYPES.LESS_THAN_EQUAL:case U.SEARCH_TYPES._LESS_THAN_EQUAL:n=Qe.lessThanEqual(e,i,t.search_attribute,t.search_value,o,c,_);break;default:return Object.create(null)}return n}a(cT,"searchByType");function TP(e){let t=e.search_type,r=e.search_attribute,s=e.search_value;switch(t){case U.SEARCH_TYPES.EQUALS:return n=>n[r]===s;case U.SEARCH_TYPES.CONTAINS:return n=>typeof n[r]=="string"&&n[r].includes(s);case U.SEARCH_TYPES.ENDS_WITH:case U.SEARCH_TYPES._ENDS_WITH:return n=>typeof n[r]=="string"&&n[r].endsWith(s);case U.SEARCH_TYPES.STARTS_WITH:case U.SEARCH_TYPES._STARTS_WITH:return n=>typeof n[r]=="string"&&n[r].startsWith(s);case U.SEARCH_TYPES.BETWEEN:return n=>{let i=n[r];return rn(i,s[0])>=0&&rn(i,s[1])<=0};case U.SEARCH_TYPES.GREATER_THAN:case U.SEARCH_TYPES._GREATER_THAN:return n=>rn(n[r],s)>0;case U.SEARCH_TYPES.GREATER_THAN_EQUAL:case U.SEARCH_TYPES._GREATER_THAN_EQUAL:return n=>rn(n[r],s)>=0;case U.SEARCH_TYPES.LESS_THAN:case U.SEARCH_TYPES._LESS_THAN:return n=>rn(n[r],s)<0;case U.SEARCH_TYPES.LESS_THAN_EQUAL:case U.SEARCH_TYPES._LESS_THAN_EQUAL:return n=>rn(n[r],s)<=0;default:return Object.create(null)}}a(TP,"filterByType");function mP(e){let t=Object.create(null);for(let r=0,s=e[0].length;r<s;r++)t[e[0][r]]=e[1][r];return t}a(mP,"createMapFromArrays");function RP(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 s=!1;for(let n=0;n<e.get_attributes.length;n++)if(r.indexOf(e.get_attributes[n])<0){s=!0;break}return s}a(RP,"checkToFetchMore");function _T(e,t,r,s){if(dP.isEmpty(s)){let n=e.search_value;typeof n=="object"?n=JSON.stringify(n):n=n.toString();let i=n.charAt(0),o=n.charAt(n.length-1),c=!1;if(e.search_attribute===t&&(c=!0),hr.indexOf(n)>-1)return r===!0?U.SEARCH_TYPES.SEARCH_ALL_TO_MAP:U.SEARCH_TYPES.SEARCH_ALL;if(n.indexOf(hr[0])<0&&n.indexOf(hr[1])<0)return c===!0?r===!0?U.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP:U.SEARCH_TYPES.BATCH_SEARCH_BY_HASH:U.SEARCH_TYPES.EQUALS;if(hr.indexOf(i)>=0&&hr.indexOf(o)>=0)return e.search_value=e.search_value.slice(1,-1),U.SEARCH_TYPES.CONTAINS;if(hr.indexOf(i)>=0)return e.search_value=e.search_value.substr(1),U.SEARCH_TYPES.ENDS_WITH;if(hr.indexOf(o)>=0)return e.search_value=e.search_value.slice(0,-1),U.SEARCH_TYPES.STARTS_WITH;if(n.includes(hr[0])||n.includes(hr[1]))return U.SEARCH_TYPES.EQUALS;throw new Error(aT.UNKNOWN_SEARCH_TYPE)}else switch(s){case ls.VALUE_SEARCH_COMPARATORS.BETWEEN:return U.SEARCH_TYPES.BETWEEN;case ls.VALUE_SEARCH_COMPARATORS.GREATER:return U.SEARCH_TYPES.GREATER_THAN;case ls.VALUE_SEARCH_COMPARATORS.GREATER_OR_EQ:return U.SEARCH_TYPES.GREATER_THAN_EQUAL;case ls.VALUE_SEARCH_COMPARATORS.LESS:return U.SEARCH_TYPES.LESS_THAN;case ls.VALUE_SEARCH_COMPARATORS.LESS_OR_EQ:return U.SEARCH_TYPES.LESS_THAN_EQUAL;default:throw new Error(aT.UNKNOWN_SEARCH_TYPE)}}a(_T,"createSearchTypeFromSearchObject");uT.exports={executeSearch:oT,createSearchTypeFromSearchObject:_T,prepSearch:fP,searchByType:cT,filterByType:TP}});var ET=S(($J,lT)=>{"use strict";var kJ=xt(),AP=ci(),OP=b(),pP=T(),NP=Eo();lT.exports=gP;async function gP(e,t){if(!OP.isEmpty(t)&&pP.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[t]===void 0)throw new Error(`Value search comparator - ${t} - is not valid`);let s=AP(e,"value");if(s)throw s;let n=!0;try{return await NP.prepSearch(e,t,n)}catch(i){throw i}}a(gP,"lmdbGetDataByValue")});var sn=S((YJ,dT)=>{"use strict";var xJ=xt(),IP=ci(),bP=b(),wP=T(),CP=Eo();dT.exports=LP;async function LP(e,t){if(!bP.isEmpty(t)&&wP.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[t]===void 0)throw new Error(`Value search comparator - ${t} - is not valid`);let s=IP(e,"value");if(s)throw s;let n=!1;try{return await CP.prepSearch(e,t,n)}catch(i){throw i}}a(LP,"lmdbSearchByValue")});var ST=S((WJ,hT)=>{"use strict";var KJ=Ye(),ho=class{constructor(t,r,s,n,i=void 0,o=void 0,c="and"){this.schema=t,this.table=r,this.get_attributes=s,this.limit=i,this.offset=o,this.conditions=n,this.operator=c}};a(ho,"SearchByConditionsObject");var So=class{constructor(t,r,s){this.search_attribute=t,this.search_type=r,this.search_value=s}};a(So,"SearchCondition");var fo=class{constructor(t,r){this.attribute=t,this.desc=r}};a(fo,"SortAttribute");hT.exports={SearchByConditionsObject:ho,SearchCondition:So,SortAttribute:fo}});var OT=S((JJ,AT)=>{"use strict";var QJ=ST().SearchByConditionsObject,UP=xt(),yP=ci(),Ku=tn(),To=Ye(),RT=Eo(),DP=ku(),fT=require("lodash"),{getBaseSchemaPath:MP}=te(),PP=require("path"),BP=X(),{handleHDBError:TT,hdb_errors:vP}=D(),{HTTP_STATUS_CODES:HP}=vP,qP=1e8,GP={lazy:!0};AT.exports=FP;async function FP(e){try{let t=yP(e,"conditions");if(t)throw TT(t,t.message,HP.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=PP.join(MP(),e.schema.toString()),s=await BP.openEnvironment(r,e.table),n=global.hdb_schema[e.schema][e.table],i=fT.sortBy(e.conditions,o=>{if(o.estimated_count===void 0){let c=o.search_type;c===To.SEARCH_TYPES.EQUALS?o.estimated_count=Ku.count(s,o.search_attribute,o.search_value):c===To.SEARCH_TYPES.CONTAINS||c===To.SEARCH_TYPES.ENDS_WITH?o.estimated_count=1/0:o.estimated_count=qP}return o.estimated_count});if(!e.operator||e.operator.toLowerCase()==="and"){let[o]=await mT(s,e,i[0],n.hash_attribute),c=s.dbis[n.hash_attribute],_=i.slice(1).map(RT.filterByType),u=_.length,l=[],E=Ku.setGetWholeRowAttributes(s,e.get_attributes),d=e.offset>-1?e.offset:0,h=e.limit>-1?e.limit:1/0;e:for(let m of o){let R=c.get(m,GP);for(let C=0;C<u;C++)if(!_[C](R))continue e;if(d>0){d--;continue}if(h<=0)break;h--,l.push(DP.parseRow(R,E))}return l}else{let o=[],c=[];for(let _ of i){let[u]=await mT(s,e,_,n.hash_attribute);c.push(u)}if(o=fT.union(...c),e.limit>0||e.offset>0){let _=Number.isInteger(e.limit)?e.limit:o.length;o=o.splice(e.offset,_)}return Ku.batchSearchByHash(s,n.hash_attribute,e.get_attributes,o)}}catch(t){throw TT(t)}}a(FP,"lmdbSearchByConditions");async function mT(e,t,r,s){let n=new UP(t.schema,t.table,void 0,void 0,s,t.get_attributes),i=r.search_type;return n.search_attribute=r.search_attribute,i===To.SEARCH_TYPES.BETWEEN?(n.search_value=r.search_value[0],n.end_value=r.search_value[1]):n.search_value=r.search_value,RT.searchByType(e,n,i,s)}a(mT,"executeConditionSearch")});var _i=S((XJ,pT)=>{"use strict";var VP=T().OPERATIONS_ENUM,mo=class{constructor(t,r,s,n=void 0){this.operation=VP.DELETE,this.schema=t,this.table=r,this.hash_values=s,this.__origin=n}};a(mo,"DeleteObject");pT.exports=mo});var Wu=S((ZJ,NT)=>{"use strict";var Ro=class{constructor(t,r,s){this.schema=t,this.table=r,this.attribute=s}};a(Ro,"DropAttributeObject");NT.exports=Ro});var Ju=S((jJ,gT)=>{"use strict";var kP=xt(),$P=_i(),zJ=Wu(),zt=T(),xP=b(),Qu=X(),YP=ts(),KP=sn(),WP=ni(),{getBaseSchemaPath:QP}=te(),JP=require("path");gT.exports=XP;async function XP(e,t=!0){let r;e.schema===zt.SYSTEM_SCHEMA_NAME?r=YP[e.table]:r=global.hdb_schema[e.schema][e.table];let s=await zP(e),n=JP.join(QP(),e.schema.toString()),i=await Qu.openEnvironment(n,e.table);return t===!0&&await ZP(e,i,r.hash_attribute),Qu.dropDBI(i,e.attribute),s}a(XP,"lmdbDropAttribute");async function ZP(e,t,r){let s=Qu.openDBI(t,r),n,i=e.attribute;for(let{key:o,value:c,version:_}of s.getRange({start:!1,versions:!0})){let u={};for(let l in c)l!==i&&(u[l]=c[l]);n=t.dbis[r].put(o,u,_)}await n}a(ZP,"removeAttributeFromAllObjects");async function zP(e){let t=new kP(zt.SYSTEM_SCHEMA_NAME,zt.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,zt.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_TABLE_KEY,`${e.schema}.${e.table}`,void 0,[zt.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY,zt.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ATTRIBUTE_KEY]),s=(await KP(t)).filter(o=>o[zt.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ATTRIBUTE_KEY]===e.attribute);if(xP.isEmptyOrZeroLength(s))throw new Error(`Attribute '${e.attribute}' was not found in '${e.schema}.${e.table}'`);let n=s.map(o=>o[zt.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),i=new $P(zt.SYSTEM_SCHEMA_NAME,zt.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,n);return WP(i)}a(zP,"dropAttributeFromSystem")});var CT=S((eX,wT)=>{"use strict";var jP=Ju(),eB=Wu(),IT=b(),bT=I(),tB=Ke().LMDB_ERRORS_ENUM;wT.exports=rB;async function rB(e){if(IT.isEmpty(global.hdb_schema[e.schema])||IT.isEmpty(global.hdb_schema[e.schema][e.table]))throw new Error(`unknown schema:${e.schema} and table ${e.table}`);let t=global.hdb_schema[e.schema][e.table],r;try{for(let s=0;s<t.attributes.length;s++){r=t.attributes[s].attribute;let n=new eB(e.schema,e.table,r);try{await jP(n,!1)}catch(i){i.message!==tB.DBI_DOES_NOT_EXIST&&bT.error(`unable to drop attribute ${e.schema}.${e.table}.${r}:`+i)}}}catch(s){throw bT.error(`Error dropping attribute ${r}`),s}}a(rB,"lmdbDropAllAttributes")});var Xu=S((rX,HT)=>{"use strict";var MT=xt(),PT=_i(),BT=sn(),vT=ni(),tX=CT(),it=T(),LT=b(),UT=X(),{getBaseSchemaPath:sB,getTransactionAuditStorePath:nB}=te(),yT=require("path"),DT=I();HT.exports=iB;async function iB(e){try{if(LT.isEmpty(global.hdb_schema[e.schema])||LT.isEmpty(global.hdb_schema[e.schema][e.table]))throw new Error(`unknown schema:${e.schema} and table ${e.table}`);await aB(e),await oB(e);let t=yT.join(sB(),e.schema.toString());try{await UT.deleteEnvironment(t,e.table)}catch(r){if(r.message==="invalid environment")DT.warn(`cannot delete environment for ${e.schema}.${e.table}, environment not found`);else throw r}try{let r=yT.join(nB(),e.schema.toString());await UT.deleteEnvironment(r,e.table,!0)}catch(r){if(r.message==="invalid environment")DT.warn(`cannot delete environment for ${e.schema}.${e.table}, environment not found`);else throw r}}catch(t){throw t}}a(iB,"lmdbDropTable");async function aB(e){let t=new MT(it.SYSTEM_SCHEMA_NAME,it.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,it.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_TABLE_KEY,`${e.schema}.${e.table}`,void 0,[it.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),r=await BT(t),s=[];for(let i=0;i<r.length;i++){let o=r[i];s.push(o.id)}if(s.length===0)return;let n=new PT(it.SYSTEM_SCHEMA_NAME,it.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,s);await vT(n)}a(aB,"deleteAttributesFromSystem");async function oB(e){let t=new MT(it.SYSTEM_SCHEMA_NAME,it.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,it.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY,e.table,void 0,[it.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY,it.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_KEY,it.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),r,s;try{r=await BT(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&&(s=o)}if(!s)throw new Error(`${e.schema}.${e.table} was not found`);let n=new PT(it.SYSTEM_SCHEMA_NAME,it.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,[s.id]);try{await vT(n)}catch(i){throw i}}a(oB,"dropTableFromSystem")});var GT=S((nX,qT)=>{"use strict";var cB=require("fs-extra"),_B=xt(),uB=us(),lB=_i(),EB=Xu(),dB=ni(),hB=Yu(),SB=sn(),Sr=T(),sX=b(),fB=require("path"),{getBaseSchemaPath:TB}=te(),{handleHDBError:mB,hdb_errors:RB}=D(),{HDB_ERROR_MSGS:AB,HTTP_STATUS_CODES:OB}=RB;qT.exports=pB;async function pB(e){let t;try{t=await NB(e.schema);let r=new _B(Sr.SYSTEM_SCHEMA_NAME,Sr.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,Sr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_KEY,t,void 0,[Sr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY]),s=await SB(r);for(let o=0;o<s.length;o++){let c={schema:t,table:s[o].name};try{await EB(c)}catch(_){if(_.message!=="invalid environment")throw _}}let n=new lB(Sr.SYSTEM_SCHEMA_NAME,Sr.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,[t]);await dB(n);let i=fB.join(TB(),t.toString());await cB.remove(i)}catch(r){throw r}}a(pB,"lmdbDropSchema");async function NB(e){let t=new uB(Sr.SYSTEM_SCHEMA_NAME,Sr.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,[e],[Sr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY]),r,s;try{r=await hB(t)}catch(n){throw n}for(let n in r)r[n].name===e&&(s=e);if(!s)throw mB(new Error,AB.SCHEMA_NOT_FOUND(e),OB.NOT_FOUND,void 0,void 0,!0);return s}a(NB,"validateDropSchema")});var Zu=S((iX,FT)=>{"use strict";var Ao=class{constructor(t,r,s){this.schema=t,this.table=r,this.hash_attribute=s}};a(Ao,"CreateTableObject");FT.exports=Ao});var kT=S((oX,VT)=>{"use strict";var gB=require("path"),IB=require("fs-extra"),Oo=X(),{getTransactionAuditStorePath:bB}=te(),zu=Ye(),aX=Zu();VT.exports=wB;async function wB(e){let t;try{let r=gB.join(bB(),e.schema.toString());await IB.mkdirp(r),t=await Oo.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{Oo.createDBI(t,zu.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,!1,!0),Oo.createDBI(t,zu.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE,!0,!1),Oo.createDBI(t,zu.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(wB,"createTransactionsAuditEnvironment")});var KT=S((cX,YT)=>{"use strict";var ju=T(),$T=X(),CB=Qs(),LB=require("path"),{getSystemSchemaPath:UB,getBaseSchemaPath:yB}=te(),DB=ts(),MB=Qa(),el=Wa(),PB=I(),BB=kT(),rl=DB.hdb_table,xT=[];for(let e=0;e<rl.attributes.length;e++)xT.push(rl.attributes[e].attribute);YT.exports=vB;async function vB(e,t){let r=LB.join(yB(),t.schema.toString()),s=new el(t.schema,t.table,ju.TIME_STAMP_NAMES_ENUM.CREATED_TIME,void 0,!0),n=new el(t.schema,t.table,ju.TIME_STAMP_NAMES_ENUM.UPDATED_TIME,void 0,!0),i=new el(t.schema,t.table,t.hash_attribute,void 0,!1,!0);try{if(await $T.createEnvironment(r,t.table),e!==void 0){let o=await $T.openEnvironment(UB(),ju.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME);await CB.insertRecords(o,rl.hash_attribute,xT,[e]),await tl(s),await tl(n),await tl(i)}await BB(t)}catch(o){throw o}}a(vB,"lmdbCreateTable");async function tl(e){try{await MB(e)}catch(t){PB.warn(`failed to create attribute ${e.attribute} due to ${t.message}`)}}a(tl,"createAttribute")});var QT=S((_X,WT)=>{"use strict";var HB=Ja(),qB=za(),GB=to(),nn=T(),FB=Qs().updateRecords,VB=X(),kB=require("path"),{getBaseSchemaPath:$B}=te(),xB=si(),YB=I();WT.exports=KB;async function KB(e){try{let{schema_table:t,attributes:r}=HB(e);qB(e,r,t.hash_attribute),e.schema!==nn.SYSTEM_SCHEMA_NAME&&(r.includes(nn.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||r.push(nn.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.includes(nn.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||r.push(nn.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let s=await GB(e.hdb_auth_header,t,r),n=kB.join($B(),e.schema.toString()),i=await VB.openEnvironment(n,e.table),o=await FB(i,t.hash_attribute,r,e.records,e[nn.CLUSTERING_FLAG]!==!0);try{await xB(e,o)}catch(c){YB.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:s,txn_time:o.txn_time}}catch(t){throw t}}a(KB,"lmdbUpdateRecords")});var XT=S((uX,JT)=>{"use strict";var WB=T().OPERATIONS_ENUM,po=class{constructor(t,r,s,n=void 0){this.operation=WB.UPSERT,this.schema=t,this.table=r,this.records=s,this.__origin=n}};a(po,"UpsertObject");JT.exports=po});var zT=S((EX,ZT)=>{"use strict";var lX=XT(),QB=Ja(),JB=za(),XB=to(),an=T(),ZB=Qs().upsertRecords,zB=X(),jB=require("path"),{getBaseSchemaPath:ev}=te(),tv=si(),rv=I(),{handleHDBError:sv,hdb_errors:nv}=D();ZT.exports=iv;async function iv(e){let t;try{t=QB(e)}catch(_){throw sv(_,_.message,nv.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0)}let{schema_table:r,attributes:s}=t;JB(e,s,r.hash_attribute),e.schema!==an.SYSTEM_SCHEMA_NAME&&(s.includes(an.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||s.push(an.TIME_STAMP_NAMES_ENUM.CREATED_TIME),s.includes(an.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||s.push(an.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let n=await XB(e.hdb_auth_header,r,s),i=jB.join(ev(),e.schema.toString()),o=await zB.openEnvironment(i,e.table),c=await ZB(o,r.hash_attribute,s,e.records,e[an.CLUSTERING_FLAG]!==!0);try{await tv(e,c)}catch(_){rv.error(`unable to write transaction due to ${_.message}`)}return{written_hashes:c.written_hashes,schema_table:r,new_attributes:n,txn_time:c.txn_time}}a(iv,"lmdbUpsertRecords")});var nm=S((dX,sm)=>{"use strict";var av=xt(),jT=b(),em=I(),ov=sn(),tm=T(),cv=Fu().deleteRecords,_v=X(),uv=require("path"),{getBaseSchemaPath:lv}=te(),{promisify:Ev}=require("util"),dv=Ev(setTimeout),rm=1e4,hv=10;sm.exports=Sv;async function Sv(e){let t=global.hdb_schema[e.schema][e.table].hash_attribute;if(jT.isEmptyOrZeroLength(t))throw new Error(`Could not retrieve hash attribute for schema: ${e.schema} table: ${e.table}`);let r=Date.parse(e.date),s;try{let n=new av(e.schema,e.table,tm.TIME_STAMP_NAMES_ENUM.CREATED_TIME,r,void 0,[t]);s=await ov(n,tm.VALUE_SEARCH_COMPARATORS.LESS)}catch(n){throw em.error(`Error searching for date: ${e.date} in schema: ${e.schema} table: ${e.table}`),n}return jT.isEmptyOrZeroLength(s)?(em.trace("No records found to delete"),{message:"No records found to delete"}):await fv(e,s,t)}a(Sv,"lmdbDeleteRecordsBefore");async function fv(e,t,r){let s=uv.join(lv(),e.schema.toString()),n=await _v.openEnvironment(s,e.table),i={message:"",deleted_hashes:[],skipped_hashes:[]};for(let o=0,c=t.length;o<c;o+=rm){let _=t.slice(o,o+rm),u=[];for(let l=0,E=_.length;l<E;l++)u.push(_[l][r]);try{let l=await cv(n,r,u);i.deleted_hashes=i.deleted_hashes.concat(l.deleted),i.skipped_hashes=i.skipped_hashes.concat(l.skipped)}catch(l){throw l}await dv(hv)}return i.message=`${i.deleted_hashes.length} of ${i.deleted_hashes.length+i.skipped_hashes.length} records successfully deleted`,i}a(fv,"chunkDeletes")});var am=S((hX,im)=>{"use strict";var No=class{constructor(t,r,s){this.schema=t,this.table=r,this.timestamp=s}};a(No,"DeleteBeforeObject");im.exports=No});var cm=S((SX,om)=>{"use strict";var go=class{constructor(t=void 0,r=void 0,s=0){this.start_timestamp=t,this.end_timestamp=r,this.transactions_deleted=s}};a(go,"DeleteAuditLogsBeforeResults");om.exports=go});var lm=S((TX,um)=>{"use strict";var sl=X(),{getTransactionAuditStorePath:Tv}=te(),fX=am(),mv=require("path"),ui=Ye(),Rv=b(),_m=cm(),Av=require("util").promisify,Ov=Av(setTimeout),pv=1e4,Nv=100;um.exports=gv;async function gv(e){let t=mv.join(Tv(),e.schema),r=await sl.openEnvironment(t,e.table,!0),s=sl.listDBIs(r);sl.initializeDBIs(r,ui.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,s);let n,i=new _m;do n=await Iv(r,e.timestamp),i.start_timestamp===void 0&&(i.start_timestamp=n.start_timestamp),n.end_timestamp!==void 0&&(i.end_timestamp=n.end_timestamp),i.transactions_deleted+=n.transactions_deleted,await Ov(Nv);while(n.transactions_deleted>0);return i}a(gv,"deleteAuditLogsBefore");async function Iv(e,t){let r=new _m;try{let s=e.dbis[ui.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP],n;for(let{key:i,value:o}of s.getRange({start:!1})){if(i>=t)break;r.start_timestamp===void 0&&(r.start_timestamp=i),n=s.remove(i);let c=o[ui.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME];Rv.isEmpty(c)||(n=e.dbis[ui.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].remove(c,i));for(let _=0;_<o.hash_values.length;_++)n=e.dbis[ui.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE].remove(o.hash_values[_],i);if(r.transactions_deleted++,r.end_timestamp=i,r.transactions_deleted>pv)break}return await n,r}catch(s){throw s}}a(Iv,"deleteTransactions")});var mm=S((mX,Tm)=>{"use strict";var nl=X(),on=Ye(),Em=as(),il=T(),dm=b(),{getTransactionAuditStorePath:bv}=te(),wv=require("path"),Cv=tn(),Io=Zs(),Lv=I();Tm.exports=Uv;async function Uv(e){let t=wv.join(bv(),e.schema),r=await nl.openEnvironment(t,e.table,!0),s=nl.listDBIs(r);nl.initializeDBIs(r,on.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,s);let n;switch(e.search_type){case il.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.TIMESTAMP:return hm(r,e.search_values);case il.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.HASH_VALUE:return n=global.hdb_schema[e.schema][e.table].hash_attribute,Dv(r,e.search_values,n);case il.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.USERNAME:return yv(r,e.search_values);default:return hm(r)}}a(Uv,"readAuditLog");function hm(e,t=[0,Em.getMicroTime()]){dm.isEmpty(t[0])&&(t[0]=0),dm.isEmpty(t[1])&&(t[1]=Em.getMicroTime());let r=[];try{let s=e.dbis[on.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP],n;for(let i of s.getKeys({start:t[1]}))if(i!==t[1]){n=i;break}for(let{value:i}of s.getRange({start:t[0],end:n})){let o=Object.assign(new Io,i);r.push(o)}return r}catch(s){throw s}}a(hm,"searchTransactionsByTimestamp");function yv(e,t=[]){let r=new Map;for(let s=0;s<t.length;s++){let n=t[s],i=[];for(let o of e.dbis[on.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].getValues(n))i.push(o);r.set(n,fm(e,i))}return Object.fromEntries(r)}a(yv,"searchTransactionsByUsername");function Dv(e,t,r){let s=new Map;for(let c=0,_=t.length;c<_;c++){let u=t[c],l=Cv.equals(e,on.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,on.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE,u);for(let E=0,d=l[0].length;E<d;E++){let h=l[0][E],m=Number(h);s.has(m)?s.get(m).push(u.toString()):s.set(m,[u.toString()])}}let n=Array.from(s.keys()),i=fm(e,n),o=new Map;for(let c=0;c<i.length;c++){let _=i[c],u=_.timestamp,l=s.get(u);Sm(_,"records",r,l,o),Sm(_,"original_records",r,l,o)}return Object.fromEntries(o)}a(Dv,"searchTransactionsByHashValues");function Sm(e,t,r,s,n){let i=e.timestamp;if(e[t])for(let o=0;o<e[t].length;o++){let c=e[t][o],_=c[r].toString();if(s.indexOf(_)>=0)if(n.has(_)){let u=n.get(_),l=u[u.length-1];if(l.timestamp===i)l[t]=[c];else{let E=new Io(e.operation,e.user_name,i,void 0);E[t]=[c],u.push(E)}}else{let u=new Io(e.operation,e.user_name,i,void 0);u[t]=[c],n.set(_,[u])}}}a(Sm,"loopRecords");function fm(e,t){let r=[];try{let s=e.dbis[on.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP];for(let n=0;n<t.length;n++)try{let i=s.get(t[n]);if(i){let o=Object.assign(new Io,i);r.push(o)}}catch(i){Lv.warn(i)}return r}catch(s){throw s}}a(fm,"batchSearchTransactions")});var Am=S((RX,Rm)=>{"use strict";var Mv=require("path"),{getBaseSchemaPath:Pv}=te(),Bv=X();Rm.exports={writeTransaction:vv};async function vv(e,t,r){let s=Mv.join(Pv(),e);return(await Bv.openEnvironment(s,t)).transaction(r)}a(vv,"writeTransaction")});var pm=S((AX,Om)=>{"use strict";var Hv=require("path"),{getBaseSchemaPath:qv}=te(),Gv=X();Om.exports={flush:Fv};async function Fv(e,t){let r=Hv.join(qv(),e.toString());return(await Gv.openEnvironment(r,t.toString())).flushed}a(Fv,"flush")});var gm=S((OX,Nm)=>{"use strict";var Re=I(),{handleHDBError:Vv}=D(),kv=_u(),$v=Qa(),xv=Hu(),Yv=Bf(),Kv=ni(),Wv=Yu(),Qv=nT(),Jv=ET(),Xv=sn(),Zv=OT(),zv=GT(),jv=KT(),eH=QT(),tH=zT(),rH=nm(),sH=lm(),nH=Xu(),iH=Ju(),aH=mm(),oH=Am(),cH=pm(),bo=class extends kv{async searchByConditions(t){try{return Zv(t)}catch(r){throw Re.error(r),r}}async getDataByHash(t){try{return await Wv(t)}catch(r){throw Re.error(r),r}}async searchByHash(t){try{return await Qv(t)}catch(r){throw Re.error(r),r}}async getDataByValue(t,r){try{return await Jv(t,r)}catch(s){throw Re.error(s),s}}async searchByValue(t){try{return await Xv(t)}catch(r){throw Re.error(r),r}}async createSchema(t){try{return await Yv(t)}catch(r){throw Re.error(r),r}}async dropSchema(t){try{return await zv(t)}catch(r){throw Re.error(r),r}}async createTable(t,r){try{return await jv(t,r)}catch(s){throw Re.error(s),s}}async dropTable(t){try{return await nH(t)}catch(r){throw Re.error(r),r}}async createAttribute(t){try{return await $v(t)}catch(r){throw Re.error(r),r}}async createRecords(t){try{return await xv(t)}catch(r){throw Re.error(r),r}}async updateRecords(t){try{return await eH(t)}catch(r){throw Re.error(r),r}}async upsertRecords(t){try{return await tH(t)}catch(r){throw Vv(r,null,null,Re.ERR,r)}}async deleteRecords(t){try{return await Kv(t)}catch(r){throw Re.error(r),r}}async deleteRecordsBefore(t){try{return await rH(t)}catch(r){throw Re.error(r),r}}async dropAttribute(t){try{return await iH(t)}catch(r){throw Re.error(r),r}}async deleteAuditLogsBefore(t){try{return await sH(t)}catch(r){throw Re.error(r),r}}async readAuditLog(t){try{return await aH(t)}catch(r){throw Re.error(r),r}}writeTransaction(t,r,s){return oH.writeTransaction(t,r,s)}flush(t,r){return cH.flush(t,r)}};a(bo,"LMDBBridge");Nm.exports=bo});var fr=S((pX,bm)=>{"use strict";var _H=gm(),uH=_u(),lH=Y();lH.initSync();var Im;function EH(){return Im instanceof uH?Im:new _H}a(EH,"getBridge");bm.exports=EH()});var Um=S((NX,Lm)=>{"use strict";var wm=require("lodash"),li=require("mathjs"),dH=require("jsonata"),Cm=b();Lm.exports={distinct_array:e=>Array.isArray(e)&&e.length>1?wm.uniqWith(e,wm.isEqual):e,searchJSON:hH,mad:Ei.bind(null,li.mad),mean:Ei.bind(null,li.mean),mode:Ei.bind(null,li.mode),prod:Ei.bind(null,li.prod),median:Ei.bind(null,li.median)};function Ei(e,t,r,s){return s===1?t==null?[]:[t]:s===2?(t!=null&&r.push(t),r):r!=null&&r.length>0?e(r):null}a(Ei,"aggregateFunction");function hH(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(Cm.isEmpty(this.__ala__.res)&&(this.__ala__.res={}),Cm.isEmpty(this.__ala__.res[r])){let s=dH(e);this.__ala__.res[r]=s}return this.__ala__.res[r].evaluate(t)}a(hH,"searchJSON")});var Dm=S((gX,ym)=>{"use strict";var he=require("moment"),al="YYYY-MM-DDTHH:mm:ss.SSSZZ";he.suppressDeprecationWarnings=!0;ym.exports={current_date:()=>he().utc().format("YYYY-MM-DD"),current_time:()=>he().utc().format("HH:mm:ss.SSS"),extract:(e,t)=>{switch(t.toLowerCase()){case"year":return he(e).utc().format("YYYY");case"month":return he(e).utc().format("MM");case"day":return he(e).utc().format("DD");case"hour":return he(e).utc().format("HH");case"minute":return he(e).utc().format("mm");case"second":return he(e).utc().format("ss");case"millisecond":return he(e).utc().format("SSS");default:break}},date:e=>he(e).utc().format(al),date_format:(e,t)=>he(e).utc().format(t),date_add:(e,t,r)=>he(e).utc().add(t,r).valueOf(),date_sub:(e,t,r)=>he(e).utc().subtract(t,r).valueOf(),date_diff:(e,t,r)=>{let s=he(e).utc(),n=he(t).utc();return r?s.diff(n,r,!0):s.diff(n)},now:()=>he().utc().valueOf(),get_server_time:()=>he().format(al),offset_utc:(e,t)=>he(e).utc().utcOffset(t).format(al)}});var vm=S((IX,Bm)=>{"use strict";var SH=require("@turf/area"),fH=require("@turf/length"),TH=require("@turf/circle"),mH=require("@turf/difference"),RH=require("@turf/distance"),AH=require("@turf/boolean-contains"),OH=require("@turf/boolean-equal"),pH=require("@turf/boolean-disjoint"),NH=require("@turf/helpers"),Mm=T(),k=b();Bm.exports={geoArea:gH,geoLength:IH,geoCircle:bH,geoDifference:wH,geoDistance:Pm,geoNear:CH,geoContains:LH,geoEqual:UH,geoCrosses:yH,geoConvert:DH};var ol="geo1 is required",cl="geo2 is required";function gH(e){if(k.isEmpty(e))throw new Error("geoJSON is required");return typeof e=="string"&&(e=k.autoCast(e)),SH.default(e)}a(gH,"geoArea");function IH(e,t){if(k.isEmpty(e))throw new Error("geoJSON is required");return typeof e=="string"&&(e=k.autoCast(e)),fH.default(e,{units:t||"kilometers"})}a(IH,"geoLength");function bH(e,t,r){if(k.isEmpty(e))throw new Error("point is required");if(k.isEmpty(t))throw new Error("radius is required");return typeof e=="string"&&(e=k.autoCast(e)),TH.default(e,t,{units:r||"kilometers"})}a(bH,"geoCircle");function wH(e,t){if(k.isEmpty(e))throw new Error("poly1 is required");if(k.isEmpty(t))throw new Error("poly2 is required");return typeof e=="string"&&(e=k.autoCast(e)),typeof t=="string"&&(t=k.autoCast(t)),mH(e,t)}a(wH,"geoDifference");function Pm(e,t,r){if(k.isEmpty(e))throw new Error("point1 is required");if(k.isEmpty(t))throw new Error("point2 is required");return typeof e=="string"&&(e=k.autoCast(e)),typeof t=="string"&&(t=k.autoCast(t)),RH.default(e,t,{units:r||"kilometers"})}a(Pm,"geoDistance");function CH(e,t,r,s){if(k.isEmpty(e))throw new Error("point1 is required");if(k.isEmpty(t))throw new Error("point2 is required");if(k.isEmpty(r))throw new Error("distance is required");if(typeof e=="string"&&(e=k.autoCast(e)),typeof t=="string"&&(t=k.autoCast(t)),isNaN(r))throw new Error("distance must be a number");return Pm(e,t,s)<=r}a(CH,"geoNear");function LH(e,t){if(k.isEmpty(e))throw new Error(ol);if(k.isEmpty(e))throw new Error(cl);return typeof e=="string"&&(e=k.autoCast(e)),typeof t=="string"&&(t=k.autoCast(t)),AH.default(e,t)}a(LH,"geoContains");function UH(e,t){if(k.isEmpty(e))throw new Error(ol);if(k.isEmpty(e))throw new Error(cl);return typeof e=="string"&&(e=k.autoCast(e)),typeof t=="string"&&(t=k.autoCast(t)),OH.default(e,t)}a(UH,"geoEqual");function yH(e,t){if(k.isEmpty(e))throw new Error(ol);if(k.isEmpty(e))throw new Error(cl);return typeof e=="string"&&(e=k.autoCast(e)),typeof t=="string"&&(t=k.autoCast(t)),!pH.default(e,t)}a(yH,"geoCrosses");function DH(e,t,r){if(k.isEmptyOrZeroLength(e))throw new Error("coordinates is required");if(k.isEmpty(t))throw new Error("geo_type is required");if(k.isEmpty(Mm.GEO_CONVERSION_ENUM[t]))throw new Error(`geo_type of ${t} is invalid please use one of the following types: ${Object.keys(Mm.GEO_CONVERSION_ENUM).join(",")}`);return NH[t](e,r)}a(DH,"geoConvert")});var wo=S((bX,Hm)=>{var Es=Um(),ft=Dm(),jt=vm();Hm.exports=e=>{e.aggr.mad=e.aggr.MAD=Es.mad,e.aggr.mean=e.aggr.MEAN=Es.mean,e.aggr.mode=e.aggr.MODE=Es.mode,e.aggr.prod=e.aggr.PROD=Es.prod,e.aggr.median=e.aggr.MEDIAN=Es.median,e.fn.distinct_array=e.fn.DISTINCT_ARRAY=Es.distinct_array,e.fn.search_json=e.fn.SEARCH_JSON=Es.searchJSON,e.fn.__ala__=e,e.fn.current_date=e.fn.CURRENT_DATE=ft.current_date,e.fn.current_time=e.fn.CURRENT_TIME=ft.current_time,e.fn.extract=e.fn.EXTRACT=ft.extract,e.fn.date=e.fn.DATE=ft.date,e.fn.date_format=e.fn.DATE_FORMAT=ft.date_format,e.fn.date_add=e.fn.DATE_ADD=ft.date_add,e.fn.date_sub=e.fn.DATE_SUB=ft.date_sub,e.fn.date_diff=e.fn.DATE_DIFF=e.fn.datediff=e.fn.DATEDIFF=ft.date_diff,e.fn.now=e.fn.NOW=ft.now,e.fn.offset_utc=e.fn.OFFSET_UTC=ft.offset_utc,e.fn.get_server_time=e.fn.GET_SERVER_TIME=ft.get_server_time,e.fn.getdate=e.fn.GETDATE=ft.now,e.fn.current_timestamp=e.fn.CURRENT_TIMESTAMP=ft.now,e.fn.geoarea=e.fn.GEOAREA=e.fn.geoArea=jt.geoArea,e.fn.geocircle=e.fn.GEOCIRCLE=e.fn.geoCircle=jt.geoCircle,e.fn.geocontains=e.fn.GEOCONTAINS=e.fn.geoContains=jt.geoContains,e.fn.geoconvert=e.fn.GEOCONVERT=e.fn.geoConvert=jt.geoConvert,e.fn.geocrosses=e.fn.GEOCROSSES=e.fn.geoCrosses=jt.geoCrosses,e.fn.geodifference=e.fn.GEODIFFERENCE=e.fn.geoDifference=jt.geoDifference,e.fn.geodistance=e.fn.GEODISTANCE=e.fn.geoDistance=jt.geoDistance,e.fn.geoequal=e.fn.GEOEQUAL=e.fn.geoEqual=jt.geoEqual,e.fn.geolength=e.fn.GEOLENGTH=e.fn.geoLength=jt.geoLength,e.fn.geonear=e.fn.GEONEAR=e.fn.geoNear=jt.geoNear}});var Fm=S((wX,Gm)=>{"use strict";var di=require("lodash"),Me=require("alasql");Me.options.cache=!1;var MH=wo(),qm=require("clone"),Co=require("recursive-iterator"),v=I(),q=b(),cn=fr(),PH=T(),{hdb_errors:BH}=D(),vH="IS NULL",hi="There was a problem performing this search. Please check the logs and try again.";MH(Me);var Lo=class{constructor(t,r){if(q.isEmpty(t))throw v.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(),q.backtickASTSchemaItems(this.statement)}async search(){let t;try{let s=await this._checkEmptySQL();if(!q.isEmptyOrZeroLength(s))return v.trace("No results returned from checkEmptySQL SQLSearch method."),s}catch(s){throw v.error("Error thrown from checkEmptySQL in SQLSearch class method search."),v.error(s),new Error(hi)}try{let s=await this._getFetchAttributeValues();if(s)return s}catch(s){throw v.error("Error thrown from getFetchAttributeValues in SQLSearch class method search."),v.error(s),new Error(hi)}if(Object.keys(this.data).length===0)return v.trace('SQLSearch class field: "data" is empty.'),[];let r;try{r=await this._processJoins()}catch(s){throw v.error("Error thrown from processJoins in SQLSearch class method search."),v.error(s),new Error(hi)}try{await this._getFinalAttributeData(r.existing_attributes,r.joined_length)}catch(s){throw v.error("Error thrown from getFinalAttributeData in SQLSearch class method search."),v.error(s),new Error(hi)}try{return t=await this._finalSQL(),t}catch(s){throw v.error("Error thrown from finalSQL in SQLSearch class method search."),v.error(s),new Error(hi)}}_getColumns(){let t=new Co(this.statement);for(let{node:r,path:s}of t)r&&r.columnid&&(this.columns[s[0]]||(this.columns[s[0]]=[]),this.columns[s[0]].push(qm(r)))}_getTables(){let t=[];this.all_table_attributes.forEach(r=>{t.push(r.table)}),this.tables=di.uniqBy(t,r=>[r.databaseid,r.tableid,r.as].join()),this.tables.forEach(r=>{let s=`${r.databaseid}_${r.as?r.as:r.tableid}`;this.data[s]={},this.data[s].__hash_name=global.hdb_schema[r.databaseid][r.tableid].hash_attribute,this.data[s].__merged_data={},this.data[s].__merged_attributes=[],this.data[s].__merged_attr_map={}})}_conditionsToFetchAttributeValues(){if(q.isEmpty(this.statement.where)){v.trace('AST "where" statement is empty.');return}let t=!1;for(let{node:r}of new Co(this.statement.where))if(r&&r.op&&r.op==="OR"&&(t=!0),!q.isEmpty(r)&&r.right)if(q.isNotEmptyAndHasValue(r.right.value)){let s=q.autoCast(r.right.value);[!0,!1].indexOf(s)>=0?r.right=new Me.yy.LogicValue({value:s}):r.right instanceof Me.yy.StringValue&&!q.isEmpty(s)&&q.autoCasterIsNumberCheck(s.toString())&&(r.right=new Me.yy.NumValue({value:s}))}else Array.isArray(r.right)&&r.right.forEach((s,n)=>{let i=q.autoCast(s.value);[!0,!1].indexOf(i)>=0?r.right[n]=new Me.yy.LogicValue({value:i}):s instanceof Me.yy.StringValue&&q.autoCasterIsNumberCheck(i.toString())&&(r.right[n]=new Me.yy.NumValue({value:i}))});if(t){v.trace('Where clause contains "OR", exact match search not performed on attributes.');return}for(let{node:r}of new Co(this.statement.where))if(r&&r.left&&r.right&&(r.left.columnid||r.right.value)&&r.op){let s=new Set,n=r.left.columnid?r.left:r.right,i=this._findColumn(n);if(!i)continue;let o=[i.table.databaseid,i.table.tableid,i.attribute].join("/");if(!q.isEmpty(PH.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[r.op])){if(q.isEmpty(this.comparator_search_values[o])&&(this.comparator_search_values[o]={ignore:!1,comparators:[]}),!this.comparator_search_values[o].ignore){if(q.isEmptyOrZeroLength(r.left.columnid)||q.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(q.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"=":!q.isEmpty(r.right.value)||!q.isEmpty(r.left.value)?s.add(q.isEmpty(r.right.value)?r.left.value:r.right.value):c=!0;break;case"IN":let _=Array.isArray(r.right)?r.right:r.left;for(let u=0;u<_.length;u++)if(_[u].value)s.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,...s])}}}_setAliasesForColumns(){if(q.isEmptyOrZeroLength(this.all_table_attributes)&&q.isEmptyOrZeroLength(this.statement.from)&&q.isEmptyOrZeroLength(this.columns.columns))return;let t=[],r={};this.statement.columns.forEach((s,n)=>{if(s.columnid==="*"){t.push(n);return}if(s.aggregatorid&&(this.has_aggregator=!0),!s.aggregatorid&&!s.funcid)if(s.as_orig=s.as?s.as:s.columnid,this.statement.joins)if(r[s.as_orig]>=0){let i=r[s.as_orig]+1;s.as=`[${s.as_orig+i}]`,r[s.as_orig]=i}else s.as=`[${s.as_orig}]`,r[s.as_orig]=0;else s.as=`[${s.as_orig}]`;!s.aggregatorid&&s.funcid&&s.args&&(s.as_orig=s.as?s.as:s.toString().replace(/'/g,'"'),s.as=`[${s.as_orig}]`),s.aggregatorid&&s.expression.columnid!=="*"&&(s.as_orig=s.as?s.as:s.expression.tableid?`${s.aggregatorid}(${s.expression.tableid}.${s.expression.columnid})`:`${s.aggregatorid}(${s.expression.columnid})`,s.as=`[${s.as_orig}]`)}),this.statement.columns.length>1&&t.length>0&&di.pullAt(this.statement.columns,t)}_findColumn(t){let r=this.all_table_attributes.filter(s=>{if(t.columnid_orig&&t.tableid_orig)return(s.table.as===t.tableid_orig||s.table.tableid===t.tableid_orig)&&s.attribute===t.columnid_orig;if(t.tableid)return(s.table.as===t.tableid||s.table.tableid===t.tableid)&&s.attribute===t.columnid;let n=t.columnid_orig?t.columnid_orig:t.columnid;return s.attribute===n});if(q.isEmptyOrZeroLength(r)){let s=this.columns.columns.filter(n=>n.as?t.columnid===n.as:!1);q.isEmptyOrZeroLength(s)||(r=this.all_table_attributes.filter(n=>n.attribute===s[0].columnid&&s[0].tableid&&s[0].tableid===(n.table.as?n.table.as:n.table.tableid)))}return r[0]}async _checkEmptySQL(){let t=[];if(q.isEmptyOrZeroLength(this.all_table_attributes)&&!q.isEmptyOrZeroLength(this.columns.columns))return t;if(q.isEmptyOrZeroLength(this.all_table_attributes)&&q.isEmptyOrZeroLength(this.statement.from))try{let r=this._buildSQL(!1);t=await Me.promise(r)}catch(r){throw v.error("Error thrown from AlaSQL in SQLSearch class method checkEmptySQL."),v.error(r),new Error("There was a problem with the SQL statement")}return t}_addFetchColumns(t){t&&t.length>0&&t.forEach(r=>{let s=this._findColumn(r);s&&this.fetch_attributes.push(qm(s))})}_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,s,n){let i=this.data[t].__merged_attr_map[s];this.data[t].__merged_data[r].splice(i,1,n)}async _getFetchAttributeValues(){if(q.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(vH)>-1&&this.tables.forEach(n=>{let i={columnid:global.hdb_schema[n.databaseid][n.tableid].hash_attribute,tableid:n.tableid};this._addFetchColumns([i])}),this.statement.order&&(this._updateOrderByToAliases(),this._addNonAggregatorsToFetchColumns()),this.fetch_attributes=di.uniqBy(this.fetch_attributes,n=>[n.table.databaseid,n.table.as?n.table.as:n.table.tableid,n.attribute].join()),r)return await this._simpleSQLQuery();let s=this.fetch_attributes.reduce((n,i)=>{let o=`${i.table.databaseid}_${i.table.as?i.table.as:i.table.tableid}`,c=this.data[o].__hash_name;return n[o]||(n[o]=[],n[o].push(null),this._addColumnToMergedAttributes(o,c)),i.attribute!==c&&(n[o].push(null),this._addColumnToMergedAttributes(o,i.attribute)),n},{});for(let n of this.fetch_attributes){let i=`${n.table.databaseid}_${n.table.as?n.table.as:n.table.tableid}`,o=this.data[i].__hash_name,c={schema:n.table.databaseid,table:n.table.tableid,get_attributes:[n.attribute]},_=!1,u=[n.table.databaseid,n.table.tableid,n.attribute].join("/");if(n.attribute===o&&(_=!0),!q.isEmpty(this.exact_search_values[u])&&!this.exact_search_values[u].ignore&&!q.isEmptyOrZeroLength(this.exact_search_values[u].values))if(_)try{c.hash_values=Array.from(this.exact_search_values[u].values);let l=await cn.getDataByHash(c);for(let E of c.hash_values)E in l&&!this.data[i].__merged_data[E]&&(this.data[i].__merged_data[E]=[...s[i]],this._setMergedHashAttribute(i,E))}catch(l){v.error("Error thrown from getDataByHash function in SQLSearch class method getFetchAttributeValues exact match."),v.error(l)}else try{c.search_attribute=n.attribute,await Promise.all(Array.from(this.exact_search_values[u].values).map(async l=>{let E=Object.assign({},c);E.search_value=l;let d=await cn.getDataByValue(E);for(let h in d)this.data[i].__merged_data[h]?this._updateMergedAttribute(i,h,n.attribute,d[h][n.attribute]):(this.data[i].__merged_data[h]=[...s[i]],this._updateMergedAttribute(i,h,n.attribute,d[h][n.attribute]),this._setMergedHashAttribute(i,q.autoCast(h)))}))}catch(l){v.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues exact match."),v.error(l)}else if(!q.isEmpty(this.comparator_search_values[u])&&!this.comparator_search_values[u].ignore&&!q.isEmptyOrZeroLength(this.comparator_search_values[u].comparators))try{let l=this.comparator_search_values[u].comparators;for(let E=0,d=l.length;E<d;E++){let h=l[E];c.search_attribute=h.attribute,c.search_value=h.search_value;let m=await cn.getDataByValue(c,h.operation);if(_)for(let R in m)this.data[i].__merged_data[R]||(this.data[i].__merged_data[R]=[...s[i]],this._setMergedHashAttribute(i,q.autoCast(R)));else for(let R in m)this.data[i].__merged_data[R]?this._updateMergedAttribute(i,R,n.attribute,m[R][n.attribute]):(this.data[i].__merged_data[R]=[...s[i]],this._updateMergedAttribute(i,R,n.attribute,m[R][n.attribute]),this._setMergedHashAttribute(i,q.autoCast(R)))}}catch(l){v.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues comparator search values."),v.error(l)}else try{c.search_attribute=n.attribute,c.search_value="*";let l=await cn.getDataByValue(c);if(_)for(let E in l)this.data[i].__merged_data[E]||(this.data[i].__merged_data[E]=[...s[i]],this._setMergedHashAttribute(i,q.autoCast(E)));else for(let E in l)this.data[i].__merged_data[E]?this._updateMergedAttribute(i,E,n.attribute,l[E][n.attribute]):(this.data[i].__merged_data[E]=[...s[i]],this._updateMergedAttribute(i,E,n.attribute,l[E][n.attribute]),this._setMergedHashAttribute(i,q.autoCast(E)))}catch(l){v.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues no comparator search values."),v.error(l)}}}_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 Me.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(n=>{let i=n.aggregatorid?n.expression:n,o=n.aggregatorid?n.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 s=r[0];if(t.is_func=!!s.funcid,t.is_aggregator=!!s.aggregatorid,s.as)if(s.as&&!t.expression.tableid)t.expression.columnid=s.as,t.expression.columnid_orig=s.as_orig;else{let n=new Me.yy.Column;n.columnid=s.as,n.columnid_orig=s.as_orig,t.expression=n}else{t.initial_select_column=Object.assign(new Me.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 n=t.is_func?new Me.yy.FuncValue:new Me.yy.Column;t.initial_select_column=Object.assign(n,s)}})}_addNonAggregatorsToFetchColumns(){let r=this.statement.order.filter(s=>!s.is_aggregator&&!s.is_ordinal).map(s=>s.is_func?{columnid:s.initial_select_column.args.filter(i=>!!i.columnid_orig)[0].columnid_orig}:{columnid:s.expression.columnid_orig});this._addFetchColumns(r)}async _processJoins(){let t=[],r=[],s=this.statement.from[0],n=[s],i=["? "+(s.as?" AS "+s.as:s.tableid)];t.push(Object.values(this.data[`${s.databaseid_orig}_${s.as?s.as_orig:s.tableid_orig}`].__merged_data)),this.statement.joins&&this.statement.joins.forEach(h=>{h.joinmode&&h.joinmode!=="INNER"&&(this.has_outer_join=!0),n.push(h.table);let m=h.joinmode+" JOIN ? AS "+(h.as?h.as:h.table.tableid);h.on&&(m+=" ON "+h.on.toString()),i.push(m),t.push(Object.values(this.data[`${h.table.databaseid_orig}_${h.table.as?h.table.as_orig:h.table.tableid_orig}`].__merged_data))});let o=[],c={};n.forEach(h=>{let m=this.data[`${h.databaseid_orig}_${h.as?h.as_orig:h.tableid_orig}`].__hash_name,R=h.as?h.as_orig:h.tableid_orig;o.push({key:`'${R}.${m}'`,schema:h.databaseid_orig,table:h.as?h.as_orig:h.tableid_orig,keys:new Set}),r.push(`${h.as?h.as:h.tableid}.\`${m}\` AS "${R}.${m}"`),c[h.as?h.as_orig:h.tableid_orig]=this.data[`${h.databaseid_orig}_${h.as?h.as_orig:h.tableid_orig}`].__merged_attributes});let _=this.statement.where?"WHERE "+this.statement.where:"",u="";this.statement.order&&!this.has_ordinal&&!this.has_aggregator&&!this.statement.group&&this.statement.limit&&(u="ORDER BY "+this.statement.order.toString(),this.statement.order.forEach(h=>{h.is_func?r.push(h.initial_select_column.toString()):h.initial_select_column.tableid?r.push(`${h.initial_select_column.tableid}.${h.initial_select_column.columnid} AS ${h.expression.columnid}`):r.push(`${h.initial_select_column.columnid} AS ${h.expression.columnid}`)}));let l="",E="";!this.has_aggregator&&!this.statement.group&&!this.has_ordinal&&(l=this.statement.limit?"LIMIT "+this.statement.limit:"",E=this.statement.offset?"OFFSET "+this.statement.offset:"");let d=[];try{let h=`SELECT ${r.join(", ")} FROM ${i.join(" ")} ${_} ${u} ${l} ${E}`,m=this._convertColumnsToIndexes(h,n);d=await Me.promise(m,t),t=null}catch(h){throw v.error("Error thrown from AlaSQL in SQLSearch class method processJoins."),v.error(h),new Error("There was a problem processing the data.")}if(d&&d.length>0){for(let h=0,m=d.length;h<m;h++){let R=d[h];o.forEach(C=>{R[C.key]!==null&&R[C.key]!==void 0&&C.keys.add(R[C.key])})}o.forEach(h=>{let m=Object.keys(this.data[`${h.schema}_${h.table}`].__merged_data),R=di.difference(m,[...h.keys].map(C=>C.toString()));for(let C=0,L=R.length;C<L;C++){let B=R[C];delete this.data[`${h.schema}_${h.table}`].__merged_data[B]}})}return{existing_attributes:c,joined_length:d?d.length:0}}async _getFinalAttributeData(t,r){if(r===0)return;let s=[],n=new Co(this.columns);for(let{node:i}of n)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)&&s.push(o)}}s=di.uniqBy(s,i=>[i.table.databaseid,i.table.as?i.table.as:i.table.tableid,i.attribute].join());try{await this._getData(s)}catch(i){v.error("Error thrown from getData in SQLSearch class method getFinalAttributeData."),v.error(i)}}async _getData(t){try{let r=t.reduce((s,n)=>{let i=`${n.table.databaseid}_${n.table.as?n.table.as:n.table.tableid}`;return s[i]?s[i].columns.push(n.attribute):s[i]={schema:n.table.databaseid,table:n.table.tableid,columns:[n.attribute]},s},{});for(let s in r){let n=r[s],i=this.data[s].__merged_data,o=[];for(let l in i)o.push(i[l][0]);this.data[s].__merged_attributes.push(...n.columns);let c={schema:n.schema,table:n.table,hash_values:o,get_attributes:n.columns},_=await cn.getDataByHash(c),u=n.columns.length;for(let l=0,E=o.length;l<E;l++){let d=o[l],h=_[d];for(let m=0;m<u;m++){let R=n.columns[m],C=h[R]===void 0?null:h[R];this.data[s].__merged_data[d].push(C)}}}}catch(r){throw v.error("Error thrown from getDataByHash function in SQLSearch class method getData."),v.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(n=>{n.as=n.as?n.as:n.table.tableid,t.push(Object.values(this.data[`${n.table.databaseid_orig}_${n.table.as?n.table.as_orig:n.table.tableid_orig}`].__merged_data)),n.table.databaseid="",n.table.tableid="?"}),this.statement.order&&this.statement.order.forEach(n=>{if(n.is_ordinal)return;this.statement.columns.filter(o=>{let c=o.aggregatorid?o.expression:o,_=o.aggregatorid?o.as_orig:c.as_orig;return n.expression.tableid?c.columnid_orig===n.expression.columnid_orig&&c.tableid_orig===n.expression.tableid_orig:c.columnid_orig===n.expression.columnid_orig||n.expression.columnid_orig===_}).length===0&&(n.expression.columnid=n.initial_select_column.columnid)}),!this.has_aggregator&&!this.statement.group&&!this.has_ordinal&&(this.statement.limit&&delete this.statement.limit,this.statement.offset&&delete this.statement.offset);let s;try{let n=this._buildSQL();v.trace(`Final SQL: ${n}`),s=await Me.promise(n,t),this.has_outer_join&&(s=this._translateUndefinedValues(s)),v.trace(`Final AlaSQL results data included ${s.length} rows`)}catch(n){throw v.error("Error thrown from AlaSQL in SQLSearch class method finalSQL."),v.error(n),new Error("There was a problem running the generated sql.")}return s}_translateUndefinedValues(t){try{let r=[];for(let s of t){let n=Object.create(null);Object.keys(s).forEach(i=>{s[i]===void 0?n[i]=null:n[i]=s[i]}),r.push(n)}return r}catch(r){return v.error(BH.HDB_ERROR_MSGS.OUTER_JOIN_TRANSLATION_ERROR),v.trace(r.stack),t}}_buildSQL(t=!0){let r=this.statement.toString();return this.statement.columns.forEach(s=>{if(s.funcid&&s.as){let n=s.toString().replace(" AS "+s.as,"");r=r.replace(s.toString(),n)}}),t===!0?this._convertColumnsToIndexes(r,this.tables):r}_convertColumnsToIndexes(t,r){let s=t,n={};r.forEach(i=>{i.databaseid_orig?n[`${i.databaseid_orig}_${i.as?i.as_orig:i.tableid_orig}`]=i.as?i.as:i.tableid:n[`${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 _=n[i],u=new RegExp(`${_}.\`${o}\``,"g"),l=`${_}.[${c}]`;s=s.replace(u,l)});for(let i in this.data)this.data[i].__merged_attributes.forEach((o,c)=>{let _=new RegExp(`\`${o}\``,"g"),u=`[${c}]`;s=s.replace(_,u)});return s}async _simpleSQLQuery(){let t=this.statement.columns.reduce((s,n)=>(n.as_orig&&n.as_orig!=n.columnid_orig?s[n.columnid_orig]=n.as_orig:s[n.columnid_orig]||(s[n.columnid_orig]=n.columnid_orig),s),{}),r=this.fetch_attributes.reduce((s,n)=>{let i=`${n.table.databaseid}_${n.table.as?n.table.as:n.table.tableid}`;return s[i]||(s[i]={}),s[i][t[n.attribute]]=null,s},{});for(let s of this.fetch_attributes){let n=`${s.table.databaseid}_${s.table.as?s.table.as:s.table.tableid}`,i={schema:s.table.databaseid,table:s.table.tableid,get_attributes:[s.attribute]};try{i.search_attribute=s.attribute,i.search_value="*";let o=await cn.getDataByValue(i);for(let c in o)this.data[n].__merged_data[c]||(this.data[n].__merged_data[c]=Object.assign({},r[n])),this.data[n].__merged_data[c][t[s.attribute]]=o[c][s.attribute]}catch(o){v.error("There was an error when processing this SQL operation. Check your logs"),v.error(o)}}return Object.values(Object.values(this.data)[0].__merged_data)}};a(Lo,"SQLSearch");Gm.exports=Lo});var Tt=S((CX,km)=>{"use strict";var HH=eS();km.exports={searchByConditions:VH,searchByHash:kH,searchByValue:$H,search:xH};var _l=fr(),Vm=require("util"),qH=Vm.callbackify(_l.searchByHash),GH=Vm.callbackify(_l.searchByValue),FH=Fm();async function VH(e){return _l.searchByConditions(e)}a(VH,"searchByConditions");function kH(e,t){try{qH(e,(r,s)=>{if(r){t(r);return}t(null,s)})}catch(r){return t(r)}}a(kH,"searchByHash");function $H(e,t){try{e.hasOwnProperty("desc")===!0&&(e.reverse=e.desc),GH(e,(r,s)=>{if(r){t(r);return}t(null,s)})}catch(r){return t(r)}}a($H,"searchByValue");function xH(e,t){try{let r=new HH(e);r.validate(),new FH(r.statement,r.attributes).search().then(n=>{t(null,n)}).catch(n=>{t(n,null)})}catch(r){return t(r)}}a(xH,"search")});var Hr=S((LX,Km)=>{"use strict";var Si=require("crypto"),xm="aes-256-cbc",YH=32,KH=16,ul=64,Ym=32,WH=ul+Ym,$m=new Map;Km.exports={encrypt:QH,decrypt:JH,createNatsTableStreamName:XH};function QH(e){let t=Si.randomBytes(YH),r=Si.randomBytes(KH),s=Si.createCipheriv(xm,Buffer.from(t),r),n=s.update(e);n=Buffer.concat([n,s.final()]);let i=t.toString("hex"),o=r.toString("hex"),c=n.toString("hex");return i+o+c}a(QH,"encrypt");function JH(e){let t=e.substr(0,ul),r=e.substr(ul,Ym),s=e.substr(WH,e.length),n=Buffer.from(r,"hex"),i=Buffer.from(s,"hex"),o=Si.createDecipheriv(xm,Buffer.from(t,"hex"),n),c=o.update(i);return c=Buffer.concat([c,o.final()]),c.toString()}a(JH,"decrypt");function XH(e,t){let r=`${e}.${t}`,s=$m.get(r);return s||(s=Si.createHash("md5").update(`${e}.${t}`).digest("hex"),$m.set(r,s)),s}a(XH,"createNatsTableStreamName")});var ds=S((UX,jm)=>{"use strict";var Qm=Tt(),qr=I(),Jm=xa(),ZH=require("lodash"),zH=require("path"),jH=Hr(),ll=b(),{promisify:Xm}=require("util"),j=T(),{handleHDBError:Uo,hdb_errors:eq}=D(),{HDB_ERROR_MSGS:yo,HTTP_STATUS_CODES:Zm}=eq,tq=Y();tq.initSync();var Wm=X(),rq=te(),fi=Xm(Qm.searchByValue),sq=Xm(Qm.searchByHash),_n="name",zm="hash_attribute",El="schema",nq="schema_table",iq="attribute";jm.exports={describeAll:aq,describeTable:Do,describeSchema:cq};async function aq(e){try{let t=ll.isEmptyOrZeroLength(e),r,s;t||(r=e.hdb_user.role.permission,s=r.super_user||r.cluster_user);let n={schema:j.SYSTEM_SCHEMA_NAME,table:j.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,search_attribute:_n,search_value:j.WILDCARD_SEARCH_VALUE,get_attributes:[_n]},i=await fi(n);if(ll.isEmptyOrZeroLength(i))return{};let o={},c={};for(let d in i)o[i[d].name]=!0,!t&&!s&&(c[i[d].name]=r[i[d].name].describe);let _={schema:j.SYSTEM_SCHEMA_NAME,table:j.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,search_attribute:j.ID_ATTRIBUTE_STRING,search_value:j.WILDCARD_SEARCH_VALUE,get_attributes:[zm,j.ID_ATTRIBUTE_STRING,_n,El]},u=await fi(_),l=[];for(let d of u)try{let h;if(t||s)h=await Do({schema:d.schema,table:d.name});else if(r&&r[d.schema].describe&&r[d.schema].tables[d.name].describe){let m=r[d.schema].tables[d.name].attribute_permissions;h=await Do({schema:d.schema,table:d.name},m)}h&&l.push(h)}catch(h){qr.error(h)}let E={};for(let d in l)t||s?(E[l[d].schema]==null&&(E[l[d].schema]={}),E[l[d].schema][l[d].name]=l[d],o[l[d].schema]&&delete o[l[d].schema]):c[l[d].schema]&&(E[l[d].schema]==null&&(E[l[d].schema]={}),E[l[d].schema][l[d].name]=l[d],o[l[d].schema]&&delete o[l[d].schema]);for(let d in o)t||s?E[d]={}:c[d]&&(E[d]={});return E}catch(t){return qr.error("Got an error in describeAll"),qr.error(t),Uo(new Error,yo.DESCRIBE_ALL_ERR)}}a(aq,"describeAll");async function Do(e,t){let{schema:r,table:s}=e;r=r.toString(),s=s.toString();let n=t;e.hdb_user&&!e.hdb_user.role.permission.super_user&&(n=e.hdb_user.role.permission[r].tables[s].attribute_permissions);let i={},o=Jm.describe_table(e);if(o)throw o;if(r===j.SYSTEM_SCHEMA_NAME)return global.hdb_schema[j.SYSTEM_SCHEMA_NAME][s];let c={schema:j.SYSTEM_SCHEMA_NAME,table:j.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,hash_attribute:j.SYSTEM_TABLE_HASH_ATTRIBUTES.TABLE_TABLE_HASH_ATTRIBUTE,search_attribute:_n,search_value:s,hash_values:[],get_attributes:[j.WILDCARD_SEARCH_VALUE]},_=await fi(c);if(!_||_.length===0)throw Uo(new Error,yo.TABLE_NOT_FOUND(e.schema,e.table),Zm.NOT_FOUND);for await(let u of _)try{if(u.schema!==r)continue;if(i=u,!i.hash_attribute)throw Uo(new Error,yo.INVALID_TABLE_ERR(i));let l={schema:j.SYSTEM_SCHEMA_NAME,table:j.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,hash_attribute:j.SYSTEM_TABLE_HASH_ATTRIBUTES.ATTRIBUTE_TABLE_HASH_ATTRIBUTE,search_attribute:nq,search_value:r+"."+s,get_attributes:[iq]},E=await fi(l);E=ZH.uniqBy(E,d=>d.attribute),n&&n.length>0&&(E=oq(n)),i.attributes=E,i.clustering_stream_name=jH.createNatsTableStreamName(u.schema,u.name);try{let d=zH.join(rq.getBaseSchemaPath(),i.schema.toString()),h=await Wm.openEnvironment(d,i.name),m=Wm.statDBI(h,i.hash_attribute);i.record_count=m.entryCount}catch(d){qr.warn(`unable to stat table dbi due to ${d}`)}}catch(l){qr.error(`There was an error getting attributes for table '${u.name}'`),qr.error(l)}return i}a(Do,"descTable");function oq(e){return e.reduce((t,r)=>(r.describe&&t.push({attribute:r.attribute_name}),t),[])}a(oq,"getAttrsByPerms");async function cq(e){let t=Jm.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 s=e.schema.toString(),n={schema:j.SYSTEM_SCHEMA_NAME,table:j.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,hash_attribute:j.SYSTEM_TABLE_HASH_ATTRIBUTES.TABLE_TABLE_HASH_ATTRIBUTE,search_attribute:El,search_value:s,hash_values:[],get_attributes:[zm,j.ID_ATTRIBUTE_STRING,_n,El]},i=await fi(n);if(i&&i.length<1){let o={schema:j.SYSTEM_SCHEMA_NAME,table:j.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,hash_attribute:j.SYSTEM_TABLE_HASH_ATTRIBUTES.SCHEMA_TABLE_HASH_ATTRIBUTE,hash_values:[s],get_attributes:[_n]},c=await sq(o);if(c&&c.length<1)throw Uo(new Error,yo.SCHEMA_NOT_FOUND(e.schema),Zm.NOT_FOUND);return{}}else{let o={};return await Promise.all(i.map(async c=>{try{let _;if(r&&r.tables[c.name]&&(_=r.tables[c.name]),ll.isEmpty(_)||_.describe){let u=await Do({schema:e.schema,table:c.name},_?_.attribute_permissions:null);u&&(o[u.name]=u)}}catch(_){qr.error(`Error describing schema table '${e.schema}.${c}'`),qr.error(_)}})),o}}a(cq,"describeSchema")});var Gr=S((MX,nR)=>{var yX=require("async"),un=ts(),DX=I(),{callbackify:rR,promisify:_q}=require("util");nR.exports={setSchemaDataToGlobal:eR,getTableSchema:Eq,getSystemSchema:hq,setSchemaDataToGlobalAsync:_q(eR)};var sR=ds(),uq=rR(sR.describeAll),lq=rR(sR.describeTable);function eR(e){uq(null,(t,r)=>{if(t){e(t);return}r.system||(r.system=un),global.hdb_schema=r,e(null,null)})}a(eR,"setSchemaDataToGlobal");function tR(e,t){return e==="system"?un[t]:global.hdb_schema[e][t]}a(tR,"returnSchema");function Eq(e,t,r){!global.hdb_schema||!global.hdb_schema[e]||!global.hdb_schema[e][t]?dq(e,t,s=>{if(s)return r(s);if(!global.hdb_schema[e])return r(`schema ${e} does not exist`);if(!global.hdb_schema[e]||!global.hdb_schema[e][t])return r(`table ${e}.${t} does not exist`);r(null,tR(e,t))}):r(null,tR(e,t))}a(Eq,"getTableSchema");function dq(e,t,r){let s={table:t,schema:e};if(e==="system"){global.hdb_schema?global.hdb_schema.system=un:global.hdb_schema={system:un},r();return}lq(s,(n,i)=>{if(n){r(n);return}if(!i.schema&&!i.name){r();return}global.hdb_schema||(global.hdb_schema={system:un}),global.hdb_schema[e]||(global.hdb_schema[e]={}),global.hdb_schema[e][t]=i,r()})}a(dq,"setTableDataToGlobal");function hq(){return un}a(hq,"getSystemSchema")});var oR=S((PX,aR)=>{"use strict";var dl=X(),Sq=I(),iR=Ke().LMDB_ERRORS_ENUM;aR.exports=fq;async function fq(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 dl.closeEnvironment(global.lmdb_map[o])}catch(c){if(c.message!==iR.ENV_REQUIRED)throw c}}break;case"drop_table":let s=`${e.schema}.${e.table}`,n=`txn.${s}`;try{await dl.closeEnvironment(global.lmdb_map[s]),await dl.closeEnvironment(global.lmdb_map[n])}catch(i){if(i.message!==iR.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){Sq.error(t)}}a(fq,"cleanLMDBMap")});var Lt=S((BX,uR)=>{"use strict";var Po=Mu(),Ct=b(),Tq=require("util"),Bo=fr(),mq=Gr(),hl=I(),{handleHDBError:Fr,hdb_errors:Rq}=D(),{HTTP_STATUS_CODES:hs}=Rq,Aq=Tq.promisify(mq.getTableSchema),Oq="updated",cR="inserted",_R="upserted";uR.exports={insert:Nq,update:gq,upsert:Iq,validation:pq,flush:bq};async function pq(e){if(Ct.isEmpty(e))throw new Error("invalid update parameters defined.");if(Ct.isEmptyOrZeroLength(e.schema))throw new Error("invalid schema specified.");if(Ct.isEmptyOrZeroLength(e.table))throw new Error("invalid table specified.");let t=await Aq(e.schema,e.table),r=Po(e);if(r)throw r;if(!Array.isArray(e.records))throw new Error("records must be an array");let s=t.hash_attribute,n=new Set,i={},o=!1;return e.operation==="update"&&(o=!0),e.records.forEach(c=>{if(o&&Ct.isEmptyOrZeroLength(c[s]))throw hl.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(!Ct.isEmptyOrZeroLength(c[s])&&(c[s]==="null"||c[s]==="undefined"))throw hl.error(`a valid hash value must be provided with ${e.operation} record:`,c),new Error(`"${c[s]}" is not a valid hash attribute value`);!Ct.isEmpty(c[s])&&c[s]!==""&&n.has(Ct.autoCast(c[s]))&&(c.skip=!0),n.add(Ct.autoCast(c[s]));for(let _ in c)i[_]=1}),i[s]=1,{schema_table:t,hashes:Array.from(n),attributes:Object.keys(i)}}a(pq,"validation");async function Nq(e){if(e.operation!=="insert")throw new Error("invalid operation, must be insert");let t=Po(e);if(t)throw Fr(new Error,t.message,hs.BAD_REQUEST);let r=Ct.checkSchemaTableExist(e.schema,e.table);if(r)throw Fr(new Error,r,hs.BAD_REQUEST);try{let s=await Bo.createRecords(e);return Mo(cR,s.written_hashes,e,s.skipped_hashes,s.new_attributes,s.txn_time)}catch(s){throw s}}a(Nq,"insertData");async function gq(e){if(e.operation!=="update")throw new Error("invalid operation, must be update");let t=Po(e);if(t)throw Fr(new Error,t.message,hs.BAD_REQUEST);let r=Ct.checkSchemaTableExist(e.schema,e.table);if(r)throw Fr(new Error,r,hs.BAD_REQUEST);try{let s=await Bo.updateRecords(e);return Ct.isEmpty(s.existing_rows)?Mo(Oq,s.written_hashes,e,s.skipped_hashes,s.new_attributes,s.txn_time):Mo(s.update_action,[],e,s.hashes,void 0,s.txn_time)}catch(s){throw s}}a(gq,"updateData");async function Iq(e){if(e.operation!=="upsert")throw Fr(new Error,"invalid operation, must be upsert",hs.INTERNAL_SERVER_ERROR);let t=Po(e);if(t)throw Fr(new Error,t.message,hs.BAD_REQUEST);let r=Ct.checkSchemaTableExist(e.schema,e.table);if(r)throw Fr(new Error,r,hs.BAD_REQUEST);try{let s=await Bo.upsertRecords(e);return Mo(_R,s.written_hashes,e,[],s.new_attributes,s.txn_time)}catch(s){let n=`There was an error during an upsert op: ${s}`;throw Fr(s,null,null,hl.ERR,n)}}a(Iq,"upsertData");function Mo(e,t,r,s,n,i){let o={message:`${e} ${t.length} of ${t.length+s.length} records`,new_attributes:n,txn_time:i};return e===cR?(o.inserted_hashes=t,o.skipped_hashes=s,o):e===_R?(o.upserted_hashes=t,o):(o.update_hashes=t,o.skipped_hashes=s,o)}a(Mo,"returnObject");function bq(e){return Bo.flush(e.schema,e.table)}a(bq,"flush")});var fl=S((vX,dR)=>{var wq=de(),Sl=require("joi"),{hdb_schema_table:lR}=Er(),ER={schema:lR,table:lR},Cq={date:Sl.date().iso().required()},Lq={timestamp:Sl.date().timestamp().required().messages({"date.format":"'timestamp' is invalid"})};dR.exports=function(e,t){let r=t==="timestamp"?{...ER,...Lq}:{...ER,...Cq},s=Sl.object(r);return wq.validateBySchema(e,s)}});var TR=S((HX,fR)=>{var Uq=de(),hR=require("joi"),{hdb_schema_table:SR}=Er(),yq=hR.object({schema:SR,table:SR,hash_values:hR.array().required()});fR.exports=function(e){return Uq.validateBySchema(e,yq)}});var RR=S((qX,mR)=>{"use strict";var vo=class{constructor(t,r,s,n,i){this.operation=t,this.schema=r,this.table=s,this.hash_attribute=n,this.records=i}};a(vo,"InsertObject");var Ho=class{constructor(t,r,s,n,i,o){this.schema=t,this.table=r,this.search_attribute=s,this.hash_attribute=n,this.get_attributes=i,this.search_value=o}};a(Ho,"NoSQLSeachObject");var qo=class{constructor(){this.message=void 0,this.deleted_hashes=[],this.skipped_hashes=[]}};a(qo,"DeleteResponseObject");mR.exports={InsertObject:vo,NoSQLSeachObject:Ho,DeleteResponseObject:qo}});var fs=S((GX,gR)=>{"use strict";var OR=fl(),Dq=TR(),Go=b(),AR=require("moment"),pR=I(),{promisify:Mq,callbackify:Pq}=require("util"),Ss=T(),Bq=Gr(),Tl=Mq(Bq.getTableSchema),ml=fr(),{DeleteResponseObject:vq}=RR(),{handleHDBError:Vr,hdb_errors:Hq}=D(),{HDB_ERROR_MSGS:Fo,HTTP_STATUS_CODES:kr}=Hq,qq="records successfully deleted",Gq=Pq(NR);gR.exports={delete:Gq,deleteRecord:NR,deleteFilesBefore:Fq,deleteAuditLogsBefore:Vq};async function Fq(e){let t=OR(e,"date");if(t)throw Vr(t,t.message,kr.BAD_REQUEST,void 0,void 0,!0);if(!AR(e.date,AR.ISO_8601).isValid())throw Vr(new Error,Fo.INVALID_DATE,kr.BAD_REQUEST,Ss.LOG_LEVELS.ERROR,Fo.INVALID_DATE,!0);let s=Go.checkSchemaTableExist(e.schema,e.table);if(s)throw Vr(new Error,s,kr.NOT_FOUND,Ss.LOG_LEVELS.ERROR,s,!0);try{let n=await ml.deleteRecordsBefore(e);if(await Tl(e.schema,e.table),pR.info(`Finished deleting files before ${e.date}`),n&&n.message)return n.message}catch(n){throw n}}a(Fq,"deleteFilesBefore");async function Vq(e){let t=OR(e,"timestamp");if(t)throw Vr(t,t.message,kr.BAD_REQUEST,void 0,void 0,!0);if(isNaN(e.timestamp))throw Vr(new Error,Fo.INVALID_VALUE("Timestamp"),kr.BAD_REQUEST,Ss.LOG_LEVELS.ERROR,Fo.INVALID_VALUE("Timestamp"),!0);let r=Go.checkSchemaTableExist(e.schema,e.table);if(r)throw Vr(new Error,r,kr.NOT_FOUND,Ss.LOG_LEVELS.ERROR,r,!0);try{let s=await ml.deleteAuditLogsBefore(e);return await Tl(e.schema,e.table),pR.info(`Finished deleting audit logs before ${e.timestamp}`),s}catch(s){throw s}}a(Vq,"deleteAuditLogsBefore");async function NR(e){let t=Dq(e);if(t)throw Vr(t,t.message,kr.BAD_REQUEST,void 0,void 0,!0);let r=Go.checkSchemaTableExist(e.schema,e.table);if(r)throw Vr(new Error,r,kr.NOT_FOUND,Ss.LOG_LEVELS.ERROR,r,!0);try{await Tl(e.schema,e.table);let s=await ml.deleteRecords(e);return Go.isEmptyOrZeroLength(s.message)&&(s.message=`${s.deleted_hashes.length} of ${e.hash_values.length} ${qq}`),s}catch(s){if(s.message===Ss.SEARCH_NOT_FOUND_MESSAGE){let n=new vq;return n.message=Ss.SEARCH_NOT_FOUND_MESSAGE,n.skipped_hashes=e.hash_values.length,n.deleted_hashes=0,n}throw s}}a(NR,"deleteRecord")});var Vo=S((FX,wR)=>{var kq=require("crypto"),IR=9;function $q(e){let t=Yq(IR),r=bR(e+t);return t+r}a($q,"createHash");function xq(e,t){let r=e.substr(0,IR),s=r+bR(t+r);return e===s}a(xq,"validateHash");function Yq(e){let t="0123456789abcdefghijklmnopqurstuvwxyzABCDEFGHIJKLMNOPQURSTUVWXYZ",r=t.length,s="";for(let n=0;n<e;n++){let i=Math.floor(Math.random()*r);s+=t[i]}return s}a(Yq,"generateSalt");function bR(e){return kq.createHash("md5").update(e).digest("hex")}a(bR,"md5");wR.exports={hash:$q,validate:xq}});var LR=S((VX,CR)=>{var Rl=de(),Je={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 Kq(e){return Je.password.presence=!0,Je.username.presence=!0,Je.role.presence=!0,Je.active.presence=!0,Rl.validateObject(e,Je)}a(Kq,"addUserValidation");function Wq(e){return Je.password.presence=!1,Je.username.presence=!0,Je.role.presence=!1,Je.active.presence=!1,Rl.validateObject(e,Je)}a(Wq,"alterUserValidation");function Qq(e){return Je.password.presence=!1,Je.username.presence=!0,Je.role.presence=!1,Je.active.presence=!1,Rl.validateObject(e,Je)}a(Qq,"dropUserValidation");CR.exports={addUserValidation:Kq,alterUserValidation:Wq,dropUserValidation:Qq}});var _e=S(($X,yR)=>{"use strict";var{platform:kX}=require("os"),Jq="nats-server.zip",Al="nats-server",Xq=process.platform==="win32"?`${Al}.exe`:Al,Ol="HDB",Zq=/^[^\s.,*>]+$/,UR="__request__",zq=a(e=>`${e}.${UR}`,"REQUEST_SUBJECT"),jq={HUB_SERVER:"hub.json",LEAF_SERVER:"leaf.json"},eG={HUB:"hub.pid",LEAF:"leaf.pid"},tG={HUB:"-hub",LEAF:"-leaf",ADMIN:"-admin"},rG={stream_name:"__HARPERDB_WORK_QUEUE__",durable_name:"HDB_WORK_QUEUE",deliver_group:Ol,deliver_subject:"__HDB__.WORKQUEUE"},sG={stream_name:"__HARPERDB_SCHEMA_QUEUE__",durable_name:"HDB_SCHEMA_QUEUE",deliver_group:Ol,deliver_subject:"HDB.SCHEMAQUEUE"},nG={stream_name:"__HARPERDB_USER_QUEUE__",durable_name:"HDB_USER_QUEUE",deliver_group:Ol,deliver_subject:"HDB.USERQUEUE"},iG={SUCCESS:"success",ERROR:"error"},aG={OPEN:"open",CLOSED:"closed",NO_RESPONDERS:"NoResponders",TIMEOUT:"Timeout"},oG={TXN:"txn",MSGID:"msgid"};yR.exports={NATS_SERVER_ZIP:Jq,NATS_SERVER_NAME:Al,NATS_BINARY_NAME:Xq,PID_FILES:eG,NATS_CONFIG_FILES:jq,SERVER_SUFFIX:tG,WORK_QUEUE_CONSUMER_NAMES:rG,SCHEMA_QUEUE_CONSUMER_NAMES:sG,USER_QUEUE_CONSUMER_NAMES:nG,NATS_TERM_CONSTRAINTS_RX:Zq,REQUEST_SUFFIX:UR,UPDATE_REMOTE_RESPONSE_STATUSES:iG,CLUSTER_STATUS_STATUSES:aG,REQUEST_SUBJECT:zq,SUBJECT_PREFIXES:oG}});var MR=S((xX,DR)=>{"use strict";var $r=T(),Ti=class{constructor(t=0,r=$r.STORAGE_TYPES_ENUM.LMDB,s=$r.LICENSE_VALUES.API_CALL_DEFAULT,n=$r.RAM_ALLOCATION_ENUM.DEFAULT,i=$r.LICENSE_VALUES.VERSION_DEFAULT,o){this.exp_date=t,this.storage_type=r,this.api_call=s,this.ram_allocation=n,this.version=i,this.fingerprint=o}};a(Ti,"BaseLicense");var ko=class extends Ti{constructor(t=0,r=$r.STORAGE_TYPES_ENUM.LMDB,s=$r.LICENSE_VALUES.API_CALL_DEFAULT,n=$r.RAM_ALLOCATION_ENUM.DEFAULT,i=$r.LICENSE_VALUES.VERSION_DEFAULT,o,c=!1){super(t,r,s,n,i,o),this.enterprise=c}};a(ko,"ExtendedLicense");DR.exports={BaseLicense:Ti,ExtendedLicense:ko}});var mi=S((YX,GR)=>{"use strict";var En=require("fs-extra"),PR=Vo(),BR=require("crypto"),cG=require("moment"),_G=require("uuid").v4,Xe=I(),Nl=require("path"),uG=b(),mt=T(),lG=MR().ExtendedLicense,ln="invalid license key format",EG="061183",dG="mofi25",hG="aes-256-cbc",SG=16,fG=32,vR=Y();vR.initSync();var pl;GR.exports={validateLicense:HR,generateFingerPrint:mG,licenseSearch:qR,getLicense:OG};function gl(){return Nl.join(vR.getHdbBasePath(),mt.LICENSE_KEY_DIR_NAME,mt.LICENSE_FILE_NAME)}a(gl,"getLicenseDirPath");function TG(){let e=gl();return Nl.join(e,mt.LICENSE_FILE_NAME)}a(TG,"getLicenseFilePath");function Il(){let e=gl();return Nl.join(e,mt.REG_KEY_FILE_NAME)}a(Il,"getFingerPrintFilePath");async function mG(){let e=Il();try{return await En.readFile(e,"utf8")}catch(t){if(t.code==="ENOENT")return await RG();throw Xe.error(`Error writing fingerprint file to ${e}`),Xe.error(t),new Error("There was an error generating the fingerprint")}}a(mG,"generateFingerPrint");async function RG(){let e=_G(),t=PR.hash(e),r=Il();try{await En.mkdirp(gl()),await En.writeFile(r,t)}catch(s){if(s.code==="EEXIST")return t;throw Xe.error(`Error writing fingerprint file to ${r}`),Xe.error(s),new Error("There was an error generating the fingerprint")}return t}a(RG,"writeFingerprint");function HR(e,t){let r={valid_license:!1,valid_date:!1,valid_machine:!1,exp_date:null,storage_type:mt.STORAGE_TYPES_ENUM.LMDB,api_call:mt.LICENSE_VALUES.API_CALL_DEFAULT,ram_allocation:mt.RAM_ALLOCATION_ENUM.DEFAULT,version:mt.LICENSE_VALUES.VERSION_DEFAULT};if(!e)return Xe.error("empty license key passed to validate."),r;let s=Il(),n=!1;try{n=En.statSync(s)}catch(i){Xe.error(i)}if(n){let i;try{i=En.readFileSync(s,"utf8")}catch{Xe.error("error validating this machine in the license"),r.valid_machine=!1;return}let o=e.split(dG),c=o[1];c=Buffer.concat([Buffer.from(c)],SG);let _=Buffer.concat([Buffer.from(i)],fG),u=BR.createDecipheriv(hG,_,c);r.valid_date=!0,r.valid_license=!0,r.valid_machine=!0;let l=null;try{l=u.update(o[0],"hex","utf8"),l.trim(),l+=u.final("utf8")}catch{let h=AG(o[0],i);if(h)l=h;else throw r.valid_license=!1,r.valid_machine=!1,console.error(ln),Xe.error(ln),new Error(ln)}let E;if(isNaN(l))try{E=JSON.parse(l),r.api_call=E.api_call,r.version=E.version,r.storage_type=E.storage_type,r.exp_date=E.exp_date,isNaN(r.exp_date)&&(r.exp_date=new Date(r.exp_date).getTime()),E.ram_allocation&&(r.ram_allocation=E.ram_allocation)}catch{throw console.error(ln),Xe.error(ln),new Error(ln)}else r.exp_date=l;r.exp_date<cG().valueOf()&&(r.valid_date=!1),PR.validate(o[1],`${EG}${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||Xe.error("Invalid licence"),r}a(HR,"validateLicense");function AG(e,t){try{let r=BR.createDecipher("aes192",t),s=r.update(e,"hex","utf8");return s.trim(),s+=r.final("utf8"),s}catch{Xe.warn("Check old license failed")}}a(AG,"checkOldLicense");function qR(){let e=new lG;e.api_call=0;let t=[];try{t=En.readFileSync(TG(),"utf-8").split(mt.NEW_LINE)}catch(r){r.code==="ENOENT"?Xe.info("no license file found"):Xe.error(`could not search for licenses due to: '${r.message}`)}for(let r=0;r<t.length;++r){let s=t[r];try{if(uG.isEmptyOrZeroLength(s))continue;let n=JSON.parse(s),i=HR(n.license_key,n.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.api_call+=i.api_call,e.ram_allocation=i.ram_allocation,e.storage_type=i.storage_type,e.enterprise=!0)}catch(n){Xe.error("There was an error parsing the license string."),Xe.error(n),e.api_call=mt.LICENSE_VALUES.API_CALL_DEFAULT,e.ram_allocation=mt.RAM_ALLOCATION_ENUM.DEFAULT,e.storage_type=mt.STORAGE_TYPES_ENUM.LMDB,e.enterprise=!1}}return e.api_call===0&&(e.api_call=mt.LICENSE_VALUES.API_CALL_DEFAULT),pl=e,e}a(qR,"licenseSearch");async function OG(){return pl||await qR(),pl}a(OG,"getLicense")});var xr=S((KX,jR)=>{"use strict";var $R="username is required",xR="nothing to update, must supply active, role or password to update",YR="password cannot be an empty string",KR="If role is specified, it cannot be empty.",WR="active must be true or false";jR.exports={addUser:LG,alterUser:UG,dropUser:DG,userInfo:MG,listUsers:xo,listUsersExternal:PG,setUsersToGlobal:Ri,findAndValidateUser:HG,getClusterUser:qG,USERNAME_REQUIRED:$R,ALTERUSER_NOTHING_TO_UPDATE:xR,EMPTY_PASSWORD:YR,EMPTY_ROLE:KR,ACTIVE_BOOLEAN:WR};var QR=Lt(),pG=fs(),wl=Vo(),JR=LR(),XR=Tt(),Cl=Xs(),be=b(),ZR=require("validate.js"),H=I(),{promisify:Ll}=require("util"),Ul=Hr(),Ts=T(),FR=_e(),NG=ur(),yl=Y(),gG=mi(),IG=ts(),{handleHDBError:er,hdb_errors:bG}=D(),{HTTP_STATUS_CODES:tr,AUTHENTICATION_ERROR_MSGS:bl,HDB_ERROR_MSGS:dn}=bG,{UserEventMsg:Dl}=Pr(),VR=require("lodash"),zR={username:!0,active:!0,role:!0,password:!0},kR=new Map,$o=Ll(XR.searchByValue),wG=Ll(XR.searchByHash),CG=Ll(pG.delete);async function LG(e){let t=ZR.cleanAttributes(e,zR),r=JR.addUserValidation(t);if(r)throw er(new Error,r.message,tr.BAD_REQUEST,void 0,void 0,!0);let s={schema:"system",table:"hdb_role",search_attribute:"role",search_value:t.role,get_attributes:["id","permission","role"]},n;try{n=await $o(s)}catch(u){throw H.error("There was an error searching for a role in add user"),H.error(u),u}if(!n||n.length<1)throw er(new Error,dn.ROLE_NAME_NOT_FOUND(t.role),tr.NOT_FOUND,void 0,void 0,!0);if(n.length>1)throw er(new Error,dn.DUP_ROLES_FOUND(t.role),tr.CONFLICT,void 0,void 0,!0);n[0].permission.cluster_user===!0&&(t.hash=Ul.encrypt(t.password)),t.password=wl.hash(t.password),t.role=n[0].id;let i={operation:"insert",schema:"system",table:"hdb_user",records:[t]},o;try{o=await QR.insert(i)}catch(u){throw H.error("There was an error searching for a user."),H.error(u),u}H.debug(o);try{await Ri()}catch(u){throw H.error("Got an error setting users to global"),H.error(u),u}if(o.skipped_hashes.length===1)throw er(new Error,dn.USER_ALREADY_EXISTS(t.username),tr.CONFLICT,void 0,void 0,!0);let c=Object.assign({},t);c.role=n[0];let _={user:null};return _.user=c,be.sendTransactionToSocketCluster(Ts.INTERNAL_SC_CHANNELS.ADD_USER,_,yl.get(Ts.HDB_SETTINGS_NAMES.CLUSTERING_NODE_NAME_KEY)),Cl.signalUserChange(new Dl(process.pid)),`${c.username} successfully added`}a(LG,"addUser");async function UG(e){let t=ZR.cleanAttributes(e,zR);if(be.isEmptyOrZeroLength(t.username))throw new Error($R);if(be.isEmptyOrZeroLength(t.password)&&be.isEmptyOrZeroLength(t.role)&&be.isEmptyOrZeroLength(t.active))throw new Error(xR);if(!be.isEmpty(t.password)&&be.isEmptyOrZeroLength(t.password.trim()))throw new Error(YR);if(!be.isEmpty(t.active)&&!be.isBoolean(t.active))throw new Error(WR);let r=yG(t.username);if(!be.isEmpty(t.password)&&!be.isEmptyOrZeroLength(t.password.trim())&&(r&&(t.hash=Ul.encrypt(t.password)),t.password=wl.hash(t.password)),t.role==="")throw new Error(KR);if(t.role){let o={schema:"system",table:"hdb_role",search_attribute:"role",search_value:t.role,get_attributes:["*"]},c;try{c=await $o(o)}catch(_){throw H.error("Got an error searching for a role."),H.error(_),_}if(!c||c.length===0){let _=dn.ALTER_USER_ROLE_NOT_FOUND(t.role);throw H.error(_),er(new Error,_,tr.NOT_FOUND,void 0,void 0,!0)}if(c.length>1){let _=dn.ALTER_USER_DUP_ROLES(t.role);throw H.error(_),er(new Error,_,tr.CONFLICT,void 0,void 0,!0)}t.role=c[0].id}let s={operation:"update",schema:"system",table:"hdb_user",records:[t]},n;try{n=await QR.update(s)}catch(o){throw H.error("Error during update."),H.error(o),o}try{await Ri()}catch(o){throw H.error("Got an error setting users to global"),H.error(o),o}let i={user:null};return i.user=t,be.sendTransactionToSocketCluster(Ts.INTERNAL_SC_CHANNELS.ALTER_USER,i,yl.get(Ts.HDB_SETTINGS_NAMES.CLUSTERING_NODE_NAME_KEY)),Cl.signalUserChange(new Dl(process.pid)),n}a(UG,"alterUser");function yG(e){let t=!1,r=global.hdb_users.get(e);return r&&r.role.permission.cluster_user===!0&&(t=!0),t}a(yG,"isClusterUser");async function DG(e){try{let t=JR.dropUserValidation(e);if(t)throw new Error(t);let r={table:"hdb_user",schema:"system",hash_values:[e.username]};if(be.isEmpty(global.hdb_users.get(e.username)))throw er(new Error,dn.USER_NOT_EXIST(e.username),tr.NOT_FOUND,void 0,void 0,!0);let s;try{s=await CG(r)}catch(i){throw H.error("Got an error deleting a user."),H.error(i),i}H.debug(s);try{await Ri()}catch(i){throw H.error("Got an error setting users to global."),H.error(i),i}let n={user:null};return n.user=e,be.sendTransactionToSocketCluster(Ts.INTERNAL_SC_CHANNELS.DROP_USER,n,yl.get(Ts.HDB_SETTINGS_NAMES.CLUSTERING_NODE_NAME_KEY)),Cl.signalUserChange(new Dl(process.pid)),`${e.username} successfully deleted`}catch(t){throw t}}a(DG,"dropUser");async function MG(e){let t={};try{if(!e||!e.hdb_user)return"There was no user info in the body";t=e.hdb_user;let r={schema:"system",table:"hdb_role",hash_values:[t.role.id],get_attributes:["*"]},s;try{s=await wG(r)}catch(n){throw H.error("Got an error searching for a role."),H.error(n),n}t.role=s[0],delete t.password,delete t.refresh_token,delete t.hash}catch(r){throw H.error(r),r}return t}a(MG,"userInfo");async function PG(){let e;try{e=await xo()}catch(t){throw H.error("Got an error listing users."),H.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(PG,"listUsersExternal");async function xo(){try{let e={schema:"system",table:"hdb_role",search_value:"*",search_attribute:"role",get_attributes:["*"]},t;try{t=VR.cloneDeep(await $o(e))}catch(r){throw H.error("Got an error searching for roles."),H.error(r),r}if(!be.isEmptyOrZeroLength(t)){let r={};for(let o in t)r[t[o].id]=t[o];let s={schema:"system",table:"hdb_user",search_value:"*",search_attribute:"username",get_attributes:["*"]},n;try{n=VR.cloneDeep(await $o(s))}catch(o){throw H.error("Got an error searching for users."),H.error(o),o}let i=new Map;for(let o in n){let c=n[o];c.role=r[n[o].role],BG(c.role),i.set(c.username,c)}return(await gG.getLicense()).enterprise?i:vG(i)}}catch(e){throw H.error("got an error listing users"),H.error(e),be.errorizeMessage(e)}return null}a(xo,"listUsers");function BG(e){try{if(!e){H.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(IG)){let r={read:!!e.permission.super_user,insert:!1,update:!1,delete:!1,attribute_permissions:[]};e.permission.system.tables[t]=r}}catch(t){H.error("Got an error trying to set system permissions."),H.error(t)}}a(BG,"appendSystemTablesToRole");function vG(e){try{if(H.info("No enterprise license found. System is limited to 1 clustering role and 1 user role"),!e)return new Map;let t=Object.create(null),r=new Map;e.forEach((n,i)=>{n.role.permission.cluster_user===void 0||n.role.permission.cluster_user===!1?n.role.permission.super_user===!0&&(t[n.role.id]||(t[n.role.id]=new Map),t[n.role.id].set(i,n)):r.set(i,n)});let s={role:void 0,count:0};return Object.keys(t).forEach(n=>{let i=t[n];i.size>=s.count&&(s.role=n,s.count=i.size)}),s.role===void 0?(H.error("No roles found with active users. This is bad."),new Map):(r=new Map([...r,...t[s.role]]),r)}catch(t){return H.error("error filtering users."),H.error(t),new Map}}a(vG,"nonEnterpriseFilter");async function Ri(){try{let e=await xo();global.hdb_users=e}catch(e){throw H.error(e),e}}a(Ri,"setUsersToGlobal");async function HG(e,t,r=!0){global.hdb_users||await Ri();let s=global.hdb_users.get(e);if(!s)throw er(new Error,bl.GENERIC_AUTH_FAIL,tr.UNAUTHORIZED,void 0,void 0,!0);if(s&&!s.active)throw er(new Error,bl.USER_INACTIVE,tr.UNAUTHORIZED,void 0,void 0,!0);let n={active:s.active,username:s.username};if(s.refresh_token&&(n.refresh_token=s.refresh_token),s.role&&(n.role=s.role),r===!0){if(kR.get(t)===s.password)return n;if(wl.validate(s.password,t))kR.set(t,s.password);else throw er(new Error,bl.GENERIC_AUTH_FAIL,tr.UNAUTHORIZED,void 0,void 0,!0)}return n}a(HG,"findAndValidateUser");async function qG(){let e=await xo(),t=NG.getConfigFromFile(Ts.CONFIG_PARAMS.CLUSTERING_USER),r=e.get(t);if(!be.isEmpty(r))return r.decrypt_hash=Ul.decrypt(r.hash),r.uri_encoded_d_hash=encodeURIComponent(r.decrypt_hash),r.uri_encoded_name=encodeURIComponent(r.username),r.sys_name=r.username+FR.SERVER_SUFFIX.ADMIN,r.sys_name_encoded=r.uri_encoded_name+FR.SERVER_SUFFIX.ADMIN,r}a(qG,"getClusterUser")});var nA=S((WX,sA)=>{"use strict";var ms=I(),Yo=T(),GG=oR(),eA=Gr(),FG=ds(),VG=xr(),{validateEvent:rA}=Pr(),kG={[Yo.IPC_EVENT_TYPES.SCHEMA]:$G,[Yo.IPC_EVENT_TYPES.USER]:YG};async function $G(e){let t=rA(e);if(t){ms.error(t);return}ms.trace(`IPC schemaHandler ${Yo.HDB_IPC_CLIENT_PREFIX}${process.pid} received schema event:`,e),await GG(e.message),await xG(e.message)}a($G,"schemaHandler");async function xG(e){try{if(global.hdb_schema!==void 0&&typeof global.hdb_schema=="object"&&e.operation!==void 0)switch(e.operation){case"drop_schema":delete global.hdb_schema[e.schema];break;case"drop_table":global.hdb_schema[e.schema]!==void 0&&delete global.hdb_schema[e.schema][e.table];break;case"create_schema":global.hdb_schema[e.schema]===void 0&&(global.hdb_schema[e.schema]={});break;case"create_table":case"create_attribute":global.hdb_schema[e.schema]===void 0&&(global.hdb_schema[e.schema]={}),global.hdb_schema[e.schema][e.table]=await FG.describeTable({schema:e.schema,table:e.table});break;default:eA.setSchemaDataToGlobal(tA);break}else eA.setSchemaDataToGlobal(tA)}catch(t){ms.error(t)}}a(xG,"syncSchemaMetadata");function tA(e){e&&ms.error(e)}a(tA,"handleErrorCallback");async function YG(e){try{let t=rA(e);if(t){ms.error(t);return}ms.trace(`IPC userHandler ${Yo.HDB_IPC_CLIENT_PREFIX}${process.pid} received user event:`,e),await VG.setUsersToGlobal()}catch(t){ms.error(t)}}a(YG,"userHandler");sA.exports=kG});var Ko=S((QX,iA)=>{"use strict";var KG=fr();iA.exports={writeTransaction:WG};function WG(e,t,r){return KG.writeTransaction(e,t,r)}a(WG,"writeTransaction")});var Ml=S((JX,QG)=>{QG.exports={name:"harperdb",version:"4.0.5",description:"HarperDB is a distributed SQL & NoSQL data platform focused on speed, flexibility, and ease of use.",keywords:["database","sql","nosql","api","distributed","cloud","enterprise","Fastify","NATS"],main:"harperdb.js",bin:{harperdb:"./bin/harperdb.js"},engines:{node:">=14.0.0","preferred-node":"18.13.0","go-lang":"1.19.3","nats-server":"2.9.8"},homepage:"https://www.harperdb.io/",bugs:"support@harperdb.io",author:{name:"HarperDB",email:"support@harperdb.io"},license:"See License in ./license/Community+Edition+and+Evaluation+End+User+License+Agreement.pdf",scripts:{submodules:"git submodule update --init --recursive",build:"eslint -c ./.eslintbuild bin/ data_layer/ security/ server/ sqlTranslator/ upgrade/ utility/ validation/",pretty:"eslint --fix bin/ data_layer/ security/ server/ sqlTranslator/ upgrade/ utility/ validation/",test:"rimraf ./.nyc_output/* && node utility/devops/register.js --reset_license --storage_type=lmdb && npm run cover:upgrade && npm run cover:nats && npm run cover:cfserver && npm run cover:lmdbbridge && npm run cover:lmdbutility && npm run cover:hdbserver && npm run cover:main && nyc merge .nyc_output coverage.json && node ./utility/devops/register.js --reset_license --storage_type=lmdb","cover:main":"cd bin/ && nyc --no-clean --reporter=lcovonly ../node_modules/mocha/bin/_mocha '../unitTests/**/*.js' --config '../unitTests/.mocharc-main.json'","cover:lmdbbridge":"cd bin/ && nyc --no-clean --reporter=lcovonly --retries 3 ../node_modules/mocha/bin/_mocha '../unitTests/data_layer/harperBridge/lmdbBridge/**/*.js' --parallel --config '../unitTests/.mocharc.json'","cover:lmdbutility":"cd bin/ && nyc --no-clean --reporter=lcovonly --retries 3 ../node_modules/mocha/bin/_mocha '../unitTests/utility/lmdb/**/*.js' --parallel --config '../unitTests/.mocharc.json'","cover:hdbserver":"cd bin/ && nyc --no-clean --reporter=lcovonly ../node_modules/mocha/bin/_mocha '../unitTests/server/harperdb/hdbServer-test.js' --parallel --config '../unitTests/.mocharc.json'","cover:cfserver":"npm run submodules && cd bin/ && nyc --no-clean --reporter=lcovonly ../node_modules/mocha/bin/_mocha '../unitTests/server/customFunctions/customFunctionsServer-test.js' --config '../unitTests/.mocharc.json'","cover:nats":"cd bin/ && nyc --no-clean --reporter=lcovonly ../node_modules/mocha/bin/_mocha '../unitTests/server/nats/**/*.js' --config '../unitTests/.mocharc.json'","cover:upgrade":"cd bin/ && nyc --no-clean --reporter=lcovonly ../node_modules/mocha/bin/_mocha '../unitTests/upgrade/**/*.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/data_layer/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:{"@fastify/accepts-serializer":"5.1.0","@fastify/autoload":"5.4.0","@fastify/compress":"6.1.1","@fastify/cors":"8.1.0","@fastify/static":"6.5.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:"1.7.4",async:"3.2.3","aws-sdk":"2.1096.0",chalk:"4.1.2","cli-progress":"3.10.0",clone:"2.1.2",esbuild:"^0.14.49","fast-glob":"3.2.11",fastify:"4.8.1","fastify-plugin":"4.2.1","fill-range":"7.0.1","fs-extra":"10.0.1","human-readable-ids":"1.0.4",inquirer:"8.2.2","is-number":"7.0.0",joi:"17.6.0",json2csv:"5.0.7",jsonata:"1.8.6",jsonwebtoken:"8.5.1",lmdb:"2.7.6",lodash:"4.17.21",mathjs:"10.4.0",microtime:"3.1.1",minimist:"1.2.6",mkcert:"1.5.0",moment:"2.29.4",msgpackr:"1.8.2",nats:"2.9.2",needle:"3.1.0","node-ipc":"9.1.4","node-stream-zip":"1.15.0","normalize-path":"^3.0.0",ora:"5.4.1","ordered-binary":"1.3.0",papaparse:"5.3.2",passport:"0.6.0","passport-http":"0.3.0","passport-local":"1.0.0",pino:"8.3.1",pm2:"5.2.0",prompt:"1.2.2","properties-reader":"2.2.0","recursive-iterator":"3.3.0",semver:"7.3.5","stream-chain":"2.2.5","stream-json":"1.7.4",systeminformation:"5.12.4","tar-fs":"2.1.1","truncate-utf8-bytes":"1.0.2",ulidx:"0.3.0",uuid:"9.0.0","validate.js":"0.11.1",yaml:"1.10.2"},devDependencies:{axios:"0.27.2",chai:"4.3.4","chai-integer":"0.1.0",eslint:"8.22.0","eslint-config-prettier":"8.3.0","eslint-plugin-prettier":"3.4.1","eslint-plugin-radar":"0.2.1","hook-std":"2.0.0","intercept-stdout":"0.1.2",mocha:"8.3.2","mocha-teamcity-reporter":"3.0.0","mock-require":"3.0.3","mock-stdin":"1.0.0",newman:"5.2.3","newman-reporter-html":"1.0.5","newman-reporter-htmlextra":"1.21.0","newman-reporter-teamcity":"0.1.11","node-fetch":"2.6.7",nyc:"15.1.0",prettier:"2.3.2",rewire:"5.0.0",rimraf:"3.0.2",sinon:"10.0.0","sinon-chai":"3.7.0"},overrides:{"eslint-plugin-radar":{eslint:"8.22.0"},"newman-reporter-html":{newman:"5.2.3"}}}});var at=S((aZ,IA)=>{"use strict";var Tr=Y();Tr.initSync();var JG=require("fs-extra"),XG=require("semver"),gi=require("path"),{monotonicFactory:ZG}=require("ulidx"),zG=ZG(),oA=require("util"),cA=require("child_process"),jG=oA.promisify(cA.exec),eF=cA.spawn,ee=_e(),ie=T(),Gl=b(),mr=I(),Wo=Hr(),tF=Ko(),Ai=ur(),{encode:vl,decode:_A}=require("msgpackr"),{isEmpty:Rs}=Gl,uA=xr(),XX=us(),rF=Tt(),ZX=oA.promisify(rF.searchByHash),{connect:sF,StorageType:lA,RetentionPolicy:EA,AckPolicy:dA,DeliverPolicy:Hl,NatsConnection:zX,JetStreamManager:jX,JetStreamClient:eZ,StringCodec:tZ,JSONCodec:nF,createInbox:Fl,StreamSource:rZ,headers:iF,toJsMsg:aF,nuid:sZ,JetStreamOptions:nZ,ErrorCode:aA,nanos:iZ}=require("nats"),{PACKAGE_ROOT:oF}=T(),cF=Ml(),hA=nF(),_F="clustering",uF=cF.engines[ee.NATS_SERVER_NAME],lF=gi.join(oF,"dependencies"),ql=gi.join(lF,`${process.platform}-${process.arch}`,ee.NATS_BINARY_NAME),Pl,Bl,Oi,pi,Ni,Yt;IA.exports={runCommand:SA,checkNATSServerInstalled:EF,createConnection:Vl,getConnection:Qo,getJetStreamManager:hn,getJetStream:fA,getNATSReferences:Ut,getServerList:hF,createLocalStream:kl,listStreams:TA,deleteLocalStream:SF,getServerConfig:Ii,listRemoteStreams:fF,viewStream:TF,publishToStream:mF,createWorkQueueStream:RF,addSourceToWorkStream:mA,request:AF,removeSourceFromWorkStream:AA,reloadNATS:$l,reloadNATSHub:OF,reloadNATSLeaf:pF,extractServerName:RA,requestErrorHandler:NF,updateWorkStream:gF,createLocalTableStream:pA,createTableStreams:IF,purgeTableStream:NA,purgeSchemaTableStreams:bF,getStreamInfo:wF,updateNodeNameLocalStreams:CF,closeConnection:dF};async function SA(e,t=void 0){let{stdout:r,stderr:s}=await jG(e,{cwd:t});if(s)throw new Error(s.replace(`
|
|
6
6
|
`,""));return r.replace(`
|
|
7
|
-
`,"")}a(AA,"runCommand");async function wF(){try{await lF.access(Vl)}catch{return!1}let e=await AA(`${Vl} --version`,void 0),t=e.substring(e.lastIndexOf("v")+1,e.length);return EF.eq(t,bF)}a(wF,"checkNATSServerInstalled");async function $l(e,t,r,s=!0,n="127.0.0.1"){return RF({name:n,port:e,user:t,pass:r,maxReconnectAttempts:-1,waitOnFirstConnect:s,tls:{keyFile:nr.get(se.CONFIG_PARAMS.CLUSTERING_TLS_PRIVATEKEY),certFile:nr.get(se.CONFIG_PARAMS.CLUSTERING_TLS_CERTIFICATE),caFile:nr.get(se.CONFIG_PARAMS.CLUSTERING_TLS_CERT_AUTH),insecure:nr.get(se.CONFIG_PARAMS.CLUSTERING_TLS_INSECURE)}})}a($l,"createConnection");async function LF(){Qt&&(await Qt.close(),Qt=void 0)}a(LF,"closeConnection");async function Zo(){if(!Qt){let e=await SA.getClusterUser();if(ps(e))throw new Error("Unable to get nats connection. Cluster user is undefined.");let t=nr.get(se.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT);Qt=await $l(t,e.username,e.decrypt_hash)}return Qt}a(Zo,"getConnection");async function Tn(){if(gi)return gi;ps(Qt)&&await Zo();let{domain:e}=Ci(se.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);if(ps(e))throw new Error("Error getting JetStream domain. Unable to get JetStream manager.");return gi=await Qt.jetstreamManager({domain:e}),gi}a(Tn,"getJetStreamManager");async function OA(){if(Ii)return Ii;ps(Qt)&&await Zo();let{domain:e}=Ci(se.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);if(ps(e))throw new Error("Error getting JetStream domain. Unable to get JetStream manager.");return Ii=Qt.jetstream({domain:e}),Ii}a(OA,"getJetStream");async function yt(){let e=Qt||await Zo(),t=gi||await Tn(),r=Ii||await OA();return{connection:e,jsm:t,js:r}}a(yt,"getNATSReferences");async function UF(){let e=nr.get(se.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),{sys_name:t,decrypt_hash:r}=await SA.getClusterUser(),s=await $l(e,t,r),n=xl(),i=s.subscribe(n),o=[],c=(async()=>{for await(let _ of i)o.push(RA.decode(_.data))})();return await s.publish("$SYS.REQ.SERVER.PING.VARZ",void 0,{reply:n}),await s.flush(),await kl.async_set_timeout(50),await i.drain(),await s.close(),await c,o}a(UF,"getServerList");async function Yl(e,t){let{jsm:r}=await yt();await r.streams.add({name:e,storage:fA.File,retention:TA.Limits,subjects:t})}a(Yl,"createLocalStream");async function pA(){let{jsm:e}=await yt(),t=await e.streams.list().next(),r=[];return t.forEach(s=>{r.push(s)}),r}a(pA,"listStreams");async function yF(e){let{jsm:t}=await yt();await t.streams.delete(e)}a(yF,"deleteLocalStream");async function DF(e){let{connection:t}=await yt(),r=[],s=xl(),n=t.subscribe(s),i=(async()=>{for await(let o of n)r.push(RA.decode(o.data))})();return await t.publish(`$JS.${e}.API.STREAM.LIST`,void 0,{reply:s}),await t.flush(),await n.drain(),await i,r}a(DF,"listRemoteStreams");async function MF(e,t=void 0,r=void 0){let{jsm:s,connection:n}=await yt(),i=hF(),o=[],c={ack_policy:mA.None,durable_name:i,deliver_subject:i,deliver_policy:Fl.All};t&&(c.deliver_policy=Fl.StartTime,c.opt_start_time=new Date(t).toISOString());try{await s.consumers.add(e,c);let _={timeout:2e3};r&&(_.max=r);let u=await n.subscribe(i,_);for await(let l of u){let E=pF(l),d=hA(E.data),h={nats_timestamp:E.info.timestampNanos,nats_sequence:E.info.streamSequence,entry:d,originators:[]},m=[];if(E.headers){let R=E.headers.get("originators");R&&(m=R.split(","),h.originators=m)}o.push(h),u.getPending()===1&&E.info.pending===0&&u.stop()}return await s.consumers.delete(e,i),o}catch(_){if(await s.consumers.delete(e,i),_.code==="TIMEOUT")return o;throw _}}a(MF,"viewStream");async function PF(e,t,r=[],s=[]){pr.trace(`publishToStream called with subject: ${e}, stream: ${t}, entries:`,r,"originators:",s);let{connection:n,js:i}=await yt(),o=await Xo(),c=`${e}.${o}`,_=OF();s.push(o),_.append("originators",s.join());for(let u=0,l=r.length;u<l;u++)try{pr.trace(`publishToStream publishing to subject: ${c}, data:`,r[u]),await i.publish(c,ql(r[u]),{headers:_})}catch(E){if(E.code&&E.code.toString()==="503")pr.trace(`publishToStream creating stream: ${t}`),await Yl(t,[c]),await i.publish(c,ql(r[u]),{headers:_});else throw E}}a(PF,"publishToStream");function Ci(e){e=e.toLowerCase();let t=bi.join(nr.get(se.CONFIG_PARAMS.ROOTPATH),IF);if(e===se.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase())return ps(Gl)&&(Gl={port:pi.getConfigFromFile(se.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),server_name:pi.getConfigFromFile(se.CONFIG_PARAMS.CLUSTERING_NODENAME)+ee.SERVER_SUFFIX.HUB,config_file:ee.NATS_CONFIG_FILES.HUB_SERVER,pid_file_path:bi.join(t,ee.PID_FILES.HUB),hdb_nats_path:t}),Gl;if(e===se.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())return ps(Hl)&&(Hl={port:pi.getConfigFromFile(se.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),server_name:pi.getConfigFromFile(se.CONFIG_PARAMS.CLUSTERING_NODENAME)+ee.SERVER_SUFFIX.LEAF,config_file:ee.NATS_CONFIG_FILES.LEAF_SERVER,domain:pi.getConfigFromFile(se.CONFIG_PARAMS.CLUSTERING_NODENAME)+ee.SERVER_SUFFIX.LEAF,pid_file_path:bi.join(t,ee.PID_FILES.LEAF),hdb_nats_path:t}),Hl;pr.error(`Unable to get Nats server config. Unrecognized process: ${e}`)}a(Ci,"getServerConfig");async function BF(e){let{jsm:t}=await yt(),r=await Xo();try{await t.streams.add({name:e.stream_name,storage:fA.File,retention:TA.Workqueue,subjects:[`${ee.SUBJECT_PREFIXES.MSGID}.${r}`,`${ee.SUBJECT_PREFIXES.TXN}.${e.stream_name}.${r}`]})}catch(s){if(s.code!=="400")throw s}try{await t.consumers.info(e.stream_name,e.durable_name)}catch(s){if(s.code.toString()==="404")await t.consumers.add(e.stream_name,{ack_policy:mA.Explicit,deliver_subject:`${e.deliver_subject}.${r}`,durable_name:e.durable_name,deliver_policy:Fl.All,max_ack_pending:1e4,deliver_group:e.deliver_group,filter_subject:`${ee.SUBJECT_PREFIXES.TXN}.>`});else throw s}}a(BF,"createWorkQueueStream");async function NA(e,t,r){let{jsm:s}=await yt(),n=await s.streams.info(t),i=gA(s.prefix),o=r.start_time?r.start_time:new Date(Date.now()).toISOString(),{schema:c,table:_}=r,u=Jo.createNatsTableStreamName(c,_),l=i===e,E,d,h=!1;if(!Array.isArray(n.config.sources)||n.config.sources.length===0)n.config.sources=[];else for(let R=0,w=n.config.sources.length;R<w;R++)if(E=n.config.sources[R],d=R,l&&E.name===u||!l&&E.name===u&&E.external&&E.external.api===`$JS.${e}.API`){h=!0;break}if(h===!0){if(E.opt_start_time===o)return;await bA(c,_,E,t),n.config.sources.splice(d,1),await s.streams.update(t,n.config)}let m={name:u,opt_start_time:o,filter_subject:`${ee.SUBJECT_PREFIXES.TXN}.>`};l||(m.external={api:`$JS.${e}.API`,deliver:""}),n.config.sources.push(m),await s.streams.update(t,n.config)}a(NA,"addSourceToWorkStream");function gA(e){return e.split(".")[1]}a(gA,"extractServerName");async function IA(e,t,r){let{schema:s,table:n}=r,i=Jo.createNatsTableStreamName(s,n),{jsm:o}=await yt(),c=await o.streams.info(t);if(!Array.isArray(c.config.sources)||c.config.sources.length===0)return;let _=c.config.sources.length,u;for(;_--;)if(u=c.config.sources[_],u.name===i&&u.external.api===`$JS.${e}.API`){c.config.sources.splice(_,1);break}await o.streams.update(t,c.config),await bA(s,n,u,t)}a(IA,"removeSourceFromWorkStream");async function bA(e,t,r,s){let n=await Tn(),i;try{i=LA(e,t,r.external.api.split(".")[1]),await n.streams.purge(s,{filter:i})}catch{pr.error("Error purging source subject",i,"from work stream",s)}}a(bA,"purgeSourceFromWorkStream");async function vF(e,t,r=2e3,s=xl()){if(!kl.isObject(t))throw new Error("data param must be an object");let n=ql(t),{connection:i}=await yt(),o={timeout:r};s&&(o.reply=s,o.noMux=!0);let c=await i.request(e,n,o);return hA(c.data)}a(vF,"request");function Kl(e){return new Promise(async(t,r)=>{let s=fF(Vl,["--signal",`reload=${e}`],{cwd:__dirname}),n,i;s.on("error",o=>{r(o)}),s.stdout.on("data",o=>{i+=o.toString()}),s.stderr.on("data",o=>{n+=o.toString()}),s.stderr.on("close",o=>{n&&r(n),t(i)})})}a(Kl,"reloadNATS");async function HF(){let{pid_file_path:e}=Ci(se.PROCESS_DESCRIPTORS.CLUSTERING_HUB);await Kl(e)}a(HF,"reloadNATSHub");async function GF(){let{pid_file_path:e}=Ci(se.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);await Kl(e)}a(GF,"reloadNATSLeaf");function qF(e,t,r){let s;switch(e.code){case lA.NoResponders:s=`Unable to ${t}, node '${r}' is not listening.`;break;case lA.Timeout:s=`Unable to ${t}, node '${r}' is listening but did not respond.`;break;default:s=e.message;break}return s}a(qF,"requestErrorHandler");async function FF(e,t){let r=t+ee.SERVER_SUFFIX.LEAF;await TF.writeTransaction(se.SYSTEM_SCHEMA_NAME,se.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,async()=>{e.subscribe===!0?await NA(r,ee.WORK_QUEUE_CONSUMER_NAMES.stream_name,e):await IA(r,ee.WORK_QUEUE_CONSUMER_NAMES.stream_name,e)})}a(FF,"updateWorkStream");async function CA(e,t){let r=Jo.createNatsTableStreamName(e,t),s=await Xo(),n=LA(e,t,s);await Yl(r,[n])}a(CA,"createLocalTableStream");async function VF(e){for(let t=0,r=e.length;t<r;t++){let s=e[t].schema,n=e[t].table;await CA(s,n)}}a(VF,"createTableStreams");async function wA(e,t){if(nr.get(se.CONFIG_PARAMS.CLUSTERING_ENABLED))try{let r=Jo.createNatsTableStreamName(e,t),{jsm:s}=await yt();await s.streams.purge(r)}catch(r){if(r.message==="stream not found")pr.warn(r);else throw r}}a(wA,"purgeTableStream");async function kF(e,t){if(nr.get(se.CONFIG_PARAMS.CLUSTERING_ENABLED))for(let r=0,s=t.length;r<s;r++)await wA(e,t[r])}a(kF,"purgeSchemaTableStreams");async function xF(e){return(await Tn()).streams.info(e)}a(xF,"getStreamInfo");function LA(e,t,r){return`${ee.SUBJECT_PREFIXES.TXN}.${e}.${t}.${r}`}a(LA,"createSubjectName");async function Xo(){if(Ni)return Ni;if(Ni=(await Tn())?.nc?.info?.server_name,Ni===void 0)throw new Error("Unable to get jetstream manager server name");return Ni}a(Xo,"getJsmServerName");async function $F(){let e=await Tn(),t=await Xo(),r=await pA();for(let s of r){let n=s.config,i=n.subjects[0];if(!i)continue;let o=i.split(".");if(o[o.length-1]!==t){if(n.name===ee.SCHEMA_QUEUE_CONSUMER_NAMES.stream_name){let _=`${ee.SCHEMA_QUEUE_CONSUMER_NAMES.deliver_subject}.${t}`;pr.trace(`Updating stream subject name from: ${i} to: ${_}`),n.subjects[0]=_}else if(n.name===ee.WORK_QUEUE_CONSUMER_NAMES.stream_name){let _=`${ee.WORK_QUEUE_CONSUMER_NAMES.stream_name}.${t}`;pr.trace(`Updating stream subject name from: ${i} to: ${_}`),n.subjects[0]=_,await e.consumers.update(ee.WORK_QUEUE_CONSUMER_NAMES.stream_name,ee.WORK_QUEUE_CONSUMER_NAMES.durable_name,{deliver_subject:`${ee.WORK_QUEUE_CONSUMER_NAMES.deliver_subject}.${t}`})}else{let _=i.split(".");_[_.length-1]=t;let u=_.join(".");pr.trace(`Updating stream subject name from: ${i} to: ${u}`),n.subjects[0]=u}await e.streams.update(n.name,n)}}}a($F,"updateNodeNameLocalStreams")});var Ql=S((gX,yA)=>{"use strict";var zo=class{constructor(t,r,s){this.timestamp=t,this.user=r,this.node_name=s}};a(zo,"ClusteringOriginObject");yA.exports=zo});var Ns=S((IX,PA)=>{"use strict";var DA=b(),Li=Y(),ue=T(),Wl=_e(),mn=ot(),Se=I(),MA=Ql(),YF=Vr();Li.initSync();var Rn=Wl.SCHEMA_QUEUE_CONSUMER_NAMES.stream_name,wi=Wl.SCHEMA_QUEUE_CONSUMER_NAMES.deliver_subject;PA.exports={sendAttributeTransaction:ec,postOperationHandler:QF};async function ec(e,t,r=[]){if(!!Li.get(ue.CONFIG_PARAMS.CLUSTERING_ENABLED)&&!DA.isEmptyOrZeroLength(e.new_attributes)&&t.schema!==ue.SYSTEM_SCHEMA_NAME){let s=t.hdb_user?.username,n=Li.get(ue.CONFIG_PARAMS.CLUSTERING_NODENAME);for(let i of e.new_attributes){let o={operation:ue.OPERATIONS_ENUM.CREATE_ATTRIBUTE,schema:t.schema,table:t.table,attribute:i,__origin:new MA(e.txn_time,s,n)};Se.trace(`sendAttributeTransaction publishing ${Rn}`,o),await mn.publishToStream(wi,Rn,[o],r)}}}a(ec,"sendAttributeTransaction");async function jo(e,t,r,s=[]){if(e.schema===ue.SYSTEM_SCHEMA_NAME)return;let n=KF(e,t,r);n&&(Se.trace(`sendOperationTransaction publishing to schema ${e.schema} table ${e.table} following transaction:`,n),await mn.publishToStream(`${Wl.SUBJECT_PREFIXES.TXN}.${e.schema}.${e.table}`,YF.createNatsTableStreamName(e.schema,e.table),[n],s))}a(jo,"sendOperationTransaction");function KF(e,t,r){if(DA.isEmptyOrZeroLength(t))return null;let s={operation:e.operation,schema:e.schema,table:e.table,__origin:r};return e.operation===ue.OPERATIONS_ENUM.DELETE?s.hash_values=t:s.records=e.records,s}a(KF,"convertCRUDOperationToTransaction");async function QF(e,t,r=[]){if(!Li.get(ue.CONFIG_PARAMS.CLUSTERING_ENABLED))return;Se.trace(`postOperationHandler called for operation ${e.operation} on schema.table: ${e.schema}.${e.table}`);let s=e.hdb_user?.username,n=Li.get(ue.CONFIG_PARAMS.CLUSTERING_NODENAME),i=new MA(t.txn_time,s,n);switch(e.operation){case ue.OPERATIONS_ENUM.INSERT:try{await jo(e,t.inserted_hashes,i,r),await ec(t,e,r)}catch(o){Se.error("There was an error calling clustering postOperationHandler for insert."),Se.error(o)}break;case ue.OPERATIONS_ENUM.DELETE:try{await jo(e,t.deleted_hashes,i,r)}catch(o){Se.error("There was an error calling clustering postOperationHandler for delete."),Se.error(o)}break;case ue.OPERATIONS_ENUM.UPDATE:try{await jo(e,t.update_hashes,i,r),await ec(t,e,r)}catch(o){Se.error("There was an error calling clustering postOperationHandler for update."),Se.error(o)}break;case ue.OPERATIONS_ENUM.UPSERT:try{await jo(e,t.upserted_hashes,i,r),await ec(t,e,r)}catch(o){Se.error("There was an error calling clustering postOperationHandler for upsert."),Se.error(o)}break;case ue.OPERATIONS_ENUM.CREATE_SCHEMA:try{let o={operation:ue.OPERATIONS_ENUM.CREATE_SCHEMA,schema:e.schema,__origin:i};await mn.publishToStream(wi,Rn,[o],r)}catch(o){Se.error("There was an error calling clustering postOperationHandler for create_schema."),Se.error(o)}break;case ue.OPERATIONS_ENUM.CREATE_TABLE:try{let o={operation:ue.OPERATIONS_ENUM.CREATE_TABLE,schema:e.schema,table:e.table,hash_attribute:e.hash_attribute,__origin:i};await mn.publishToStream(wi,Rn,[o],r)}catch(o){Se.error("There was an error calling clustering postOperationHandler for create_table."),Se.error(o)}break;case ue.OPERATIONS_ENUM.CREATE_ATTRIBUTE:try{let o={operation:ue.OPERATIONS_ENUM.CREATE_ATTRIBUTE,schema:e.schema,table:e.table,attribute:e.attribute,__origin:i};await mn.publishToStream(wi,Rn,[o],r)}catch(o){Se.error("There was an error calling clustering postOperationHandler for create_attribute."),Se.error(o)}break;case ue.OPERATIONS_ENUM.CSV_DATA_LOAD:try{let o={operation:ue.OPERATIONS_ENUM.CSV_DATA_LOAD,schema:e.schema,table:e.table,attribute:e.attribute};await mn.publishToStream(wi,Rn,[o],r)}catch(o){Se.error("There was an error calling clustering postOperationHandler for csv_data_load."),Se.error(o)}break;default:break}return t}a(QF,"postOperationHandler")});var qA=S((bX,GA)=>{"use strict";var WF=mt(),JF=xr(),BA=I(),vA=Ut(),ZF=Wo(),XF=require("clone"),Zl=require("alasql"),zF=Lo(),HA=require("util"),jF=HA.promisify(JF.getTableSchema),e0=HA.promisify(WF.search),t0=T(),Jl=b(),r0=Ns();zF(Zl);GA.exports={update:n0};var s0="There was a problem performing this update. Please check the logs and try again.";async function n0({statement:e,hdb_user:t}){let r=await jF(e.table.databaseid,e.table.tableid),s=i0(e.columns);Jl.backtickASTSchemaItems(e);let{table:n,where:i}=e,o=XF(n),c=Jl.isEmpty(i)?"":` WHERE ${i.toString()}`,_=`SELECT ${r.hash_attribute} FROM ${n.toString()} ${c}`,u=Zl.parse(_).statements[0],l=await ZF.writeTransaction(r.schema,r.name,async()=>{let E=await e0(u),d=a0(s,E);return o0(o,d,t)});return await vA.flush({schema:r.schema,table:r.name}),l}a(n0,"update");function i0(e){try{let t={};return e.forEach(r=>{"value"in r.expression?t[r.column.columnid]=r.expression.value:t[r.column.columnid]=Zl.compile(`SELECT ${r.expression.toString()} AS [${t0.FUNC_VAL}] FROM ?`)}),t}catch(t){throw BA.error(t),new Error(s0)}}a(i0,"createUpdateRecord");function a0(e,t){return Jl.isEmptyOrZeroLength(t)?[]:t.map(r=>Object.assign(r,e))}a(a0,"buildUpdateRecords");async function o0(e,t,r){let s={operation:"update",schema:e.databaseid_orig,table:e.tableid_orig,records:t,hdb_user:r};try{let n=await vA.update(s);await r0.postOperationHandler(s,n);try{delete n.new_attributes,delete n.txn_time}catch(i){BA.error(`Error delete new_attributes from update response: ${i}`)}return n}catch(n){throw n}}a(o0,"updateRecords")});var VA=S((CX,FA)=>{var c0=require("alasql"),_0=mt(),u0=I(),l0=Or(),zl=require("util"),Xl=b(),E0=T(),d0=xr(),h0=Wo(),S0=Ns(),f0=Ut(),T0="record",m0="successfully deleted",R0=zl.callbackify(N0),A0=zl.promisify(_0.search),O0=zl.promisify(d0.getTableSchema);FA.exports={convertDelete:R0};function p0(e){return`${e.deleted_hashes.length} ${T0}${e.deleted_hashes.length===1?"":"s"} ${m0}`}a(p0,"generateReturnMessage");async function N0({statement:e,hdb_user:t}){let r=await O0(e.table.databaseid,e.table.tableid);Xl.backtickASTSchemaItems(e);let{table:s,where:n}=e,i=Xl.isEmpty(n)?"":` WHERE ${n.toString()}`,o=`SELECT ${r.hash_attribute} FROM ${s.toString()} ${i}`,c=c0.parse(o).statements[0],_={operation:E0.OPERATIONS_ENUM.DELETE,schema:s.databaseid_orig,table:s.tableid_orig,hdb_user:t};try{let u=await h0.writeTransaction(r.schema,r.name,async()=>(_.records=await A0(c),l0.deleteRecords(_)));return await f0.flush({schema:r.schema,table:r.name}),u.deleted_hashes.length>0&&await S0.postOperationHandler(_,u),Xl.isEmptyOrZeroLength(u.message)&&(u.message=p0(u)),delete u.txn_time,u}catch(u){throw u0.error(u),u.hdb_code?u.message:u}}a(N0,"convertDelete")});var $A=S((wX,xA)=>{"use strict";var eE=fs(),{hdb_errors:jl}=D();xA.exports={checkSchemaExists:kA,checkSchemaTableExists:g0,schema_describe:eE};async function kA(e){if(!global.hdb_schema[e])try{let t=await eE.describeSchema({schema:e});global.hdb_schema[e]=t}catch{return jl.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}}a(kA,"checkSchemaExists");async function g0(e,t){let r=await kA(e);if(r)return r;if(!global.hdb_schema[e][t])try{let s=await eE.describeTable({schema:e,table:t});if(!s||Object.keys(s).length===0)return jl.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t);global.hdb_schema[e][t]=s}catch{return jl.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}}a(g0,"checkSchemaTableExists")});var tc=S((UX,JA)=>{"use strict";var An=Ka(),gs=$A(),YA=I(),I0=require("uuid").v4,LX=require("clone"),pn=js(),Is=T(),b0=require("util"),bs=Or(),{handleHDBError:Pe,hdb_errors:C0}=D(),{HDB_ERROR_MSGS:On,HTTP_STATUS_CODES:Be}=C0,{SchemaEventMsg:Nn}=Gr(),KA=ot();JA.exports={createSchema:w0,createSchemaStructure:QA,createTable:L0,createTableStructure:WA,createAttribute:P0,dropSchema:U0,dropTable:y0,dropAttribute:D0};async function w0(e){try{let t=await QA(e);return pn.signalSchemaChange(new Nn(process.pid,e.operation,e.schema)),t}catch(t){throw t}}a(w0,"createSchema");async function QA(e){let t=An.schema_object(e);if(t)throw Pe(t,t.message,Be.BAD_REQUEST,void 0,void 0,!0);if(!await gs.checkSchemaExists(e.schema))throw Pe(new Error,On.SCHEMA_EXISTS_ERR(e.schema),Be.BAD_REQUEST,Is.LOG_LEVELS.ERROR,On.SCHEMA_EXISTS_ERR(e.schema),!0);try{return await bs.createSchema(e),`schema '${e.schema}' successfully created`}catch(r){throw r}}a(QA,"createSchemaStructure");async function L0(e){try{let t=await WA(e);return pn.signalSchemaChange(new Nn(process.pid,e.operation,e.schema,e.table)),t}catch(t){throw t}}a(L0,"createTable");async function WA(e){let t=An.create_table_object(e);if(t)throw Pe(t,t.message,Be.BAD_REQUEST,void 0,void 0,!0);An.validateTableResidence(e.residence);let r=await gs.checkSchemaExists(e.schema);if(r)throw Pe(new Error,r,Be.NOT_FOUND,Is.LOG_LEVELS.ERROR,r,!0);if(!await gs.checkSchemaTableExists(e.schema,e.table))throw Pe(new Error,On.TABLE_EXISTS_ERR(e.schema,e.table),Be.BAD_REQUEST,Is.LOG_LEVELS.ERROR,On.TABLE_EXISTS_ERR(e.schema,e.table),!0);let n={name:e.table,schema:e.schema,id:I0(),hash_attribute:e.hash_attribute};try{if(e.residence)if(global.clustering_on)n.residence=e.residence,await bs.createTable(n,e);else throw Pe(new Error,"Clustering does not appear to be enabled. Cannot insert table with property 'residence'.",Be.BAD_REQUEST);else await bs.createTable(n,e);return`table '${e.schema}.${e.table}' successfully created.`}catch(i){throw i}}a(WA,"createTableStructure");async function U0(e){let t=An.schema_object(e);if(t)throw Pe(t,t.message,Be.BAD_REQUEST,void 0,void 0,!0);let r=await gs.checkSchemaExists(e.schema);if(r)throw Pe(new Error,r,Be.NOT_FOUND,Is.LOG_LEVELS.ERROR,r,!0);let s=await gs.schema_describe.describeSchema({schema:e.schema});global.hdb_schema[e.schema]=s;let n=Object.keys(global.hdb_schema[e.schema]);return await bs.dropSchema(e),pn.signalSchemaChange(new Nn(process.pid,e.operation,e.schema)),delete global.hdb_schema[e.schema],await KA.purgeSchemaTableStreams(e.schema,n),`successfully deleted schema '${e.schema}'`}a(U0,"dropSchema");async function y0(e){let t=An.table_object(e);if(t)throw Pe(t,t.message,Be.BAD_REQUEST,void 0,void 0,!0);let r=await gs.checkSchemaTableExists(e.schema,e.table);if(r)throw Pe(new Error,r,Be.NOT_FOUND,Is.LOG_LEVELS.ERROR,r,!0);return await bs.dropTable(e),pn.signalSchemaChange(new Nn(process.pid,e.operation,e.schema,e.table)),await KA.purgeTableStream(e.schema,e.table),`successfully deleted table '${e.schema}.${e.table}'`}a(y0,"dropTable");async function D0(e){let t=An.attribute_object(e);if(t)throw Pe(t,t.message,Be.BAD_REQUEST,void 0,void 0,!0);let r=await gs.checkSchemaTableExists(e.schema,e.table);if(r)throw Pe(new Error,r,Be.NOT_FOUND,Is.LOG_LEVELS.ERROR,r,!0);if(e.attribute===global.hdb_schema[e.schema][e.table].hash_attribute)throw Pe(new Error,"You cannot drop a hash attribute",Be.BAD_REQUEST,void 0,void 0,!0);if(Is.TIME_STAMP_NAMES.indexOf(e.attribute)>=0)throw Pe(new Error,`cannot drop internal timestamp attribute: ${e.attribute}`,Be.BAD_REQUEST,void 0,void 0,!0);try{return await bs.dropAttribute(e),M0(e),pn.signalSchemaChange(new Nn(process.pid,e.operation,e.schema,e.table,e.attribute)),`successfully deleted attribute '${e.attribute}'`}catch(s){throw YA.error(`Got an error deleting attribute ${b0.inspect(e)}.`),s}}a(D0,"dropAttribute");function M0(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(M0,"dropAttributeFromGlobal");async function P0(e){if(!global.hdb_schema[e.schema])throw Pe(new Error,On.SCHEMA_NOT_FOUND(e.schema),Be.NOT_FOUND,void 0,void 0,!0);if(!global.hdb_schema[e.schema][e.table])throw Pe(new Error,On.TABLE_NOT_FOUND(e.schema,e.table),Be.NOT_FOUND,void 0,void 0,!0);try{return await bs.createAttribute(e),pn.signalSchemaChange(new Nn(process.pid,e.operation,e.schema,e.table,e.attribute)),`attribute '${e.schema}.${e.table}.${e.attribute}' successfully created.`}catch(t){throw YA.error(t),t}}a(P0,"createAttribute")});var XA=S((yX,ZA)=>{"use strict";var{OPERATIONS_ENUM:B0}=T(),rc=class{constructor(t,r,s=void 0,n=void 0){this.operation=B0.READ_AUDIT_LOG,this.schema=t,this.table=r,this.search_type=s,this.search_values=n}};a(rc,"ReadAuditLogObject");ZA.exports=rc});var tE=S((MX,rO)=>{"use strict";var v0=Or(),DX=XA(),sc=b(),nc=T(),H0=Y(),{handleHDBError:zA,hdb_errors:G0}=D(),{HDB_ERROR_MSGS:jA,HTTP_STATUS_CODES:eO}=G0,q0=Object.values(nc.READ_AUDIT_LOG_SEARCH_TYPES_ENUM),tO="To use this operation audit log must be enabled in harperdb-config.yaml";rO.exports=F0;async function F0(e){if(sc.isEmpty(e.schema))throw new Error(jA.SCHEMA_REQUIRED_ERR);if(sc.isEmpty(e.table))throw new Error(jA.TABLE_REQUIRED_ERR);if(!H0.get(nc.CONFIG_PARAMS.LOGGING_AUDITLOG))throw zA(new Error,tO,eO.BAD_REQUEST,nc.LOG_LEVELS.ERROR,tO,!0);let t=sc.checkSchemaTableExist(e.schema,e.table);if(t)throw zA(new Error,t,eO.NOT_FOUND,nc.LOG_LEVELS.ERROR,t,!0);if(!sc.isEmpty(e.search_type)&&q0.indexOf(e.search_type)<0)throw new Error(`Invalid search_type '${e.search_type}'`);return await v0.readAuditLog(e)}a(F0,"readAuditLog")});var cO=S((PX,oO)=>{var Jr=require("validate.js"),nO=de(),gn=T(),{handleHDBError:V0,hdb_errors:k0}=D(),{HDB_ERROR_MSGS:le,HTTP_STATUS_CODES:x0}=k0,rE=a(()=>({role:{presence:!0,format:"[\\w\\-\\_]+"},id:{presence:!0,format:"[\\w\\-\\_]+"},permission:{presence:!0}}),"constraintsTemplate"),$0={STRUCTURE_USER:"structure_user"},sO=Object.values(gn.ROLE_TYPES_ENUM),Y0="attribute_permissions",K0="attribute_name",{PERMS_CRUD_ENUM:In}=gn,Q0=[Y0,...Object.values(In)],iO=[In.READ,In.INSERT,In.UPDATE],W0=[K0,...iO];function J0(e){let t=rE();return t.role.presence=!0,t.id.presence=!1,t.permission.presence=!0,aO(e,t)}a(J0,"addRoleValidation");function Z0(e){let t=rE();return t.role.presence=!1,t.id.presence=!0,t.permission.presence=!0,aO(e,t)}a(Z0,"alterRoleValidation");function X0(e){let t=rE();return t.role.presence=!1,t.id.presence=!0,t.permission.presence=!1,nO.validateObject(e,t)}a(X0,"dropRoleValidation");var z0=["operation","role","id","permission","hdb_user","hdb_auth_header"];function aO(e,t){let r={main_permissions:[],schema_permissions:{}},s=Object.keys(e),n=[];for(let o=0,c=s.length;o<c;o++)z0.includes(s[o])||n.push(s[o]);n.length>0&&fe(le.INVALID_ROLE_JSON_KEYS(n),r);let i=nO.validateObject(e,t);if(i&&i.message.split(",").forEach(o=>{fe(o,r)}),e.permission){let o=j0(e);o&&fe(o,r),sO.forEach(c=>{e.permission[c]&&!Jr.isBoolean(e.permission[c])&&fe(le.SU_CU_ROLE_BOOLEAN_ERROR(c),r)})}for(let o in e.permission)if(sO.indexOf(o)<0){if(o===$0.STRUCTURE_USER){let _=e.permission[o];if(typeof _=="boolean")continue;if(Array.isArray(_)){for(let u=0,l=_.length;u<l;u++){let E=_[u];global.hdb_schema[E]||fe(le.SCHEMA_NOT_FOUND(E),r)}continue}fe(le.STRUCTURE_USER_ROLE_TYPE_ERROR(o),r);continue}let c=e.permission[o];if(!o||!global.hdb_schema[o]){fe(le.SCHEMA_NOT_FOUND(o),r);continue}if(c.tables)for(let _ in c.tables){let u=c.tables[_];if(!_||!global.hdb_schema[o][_]){fe(le.TABLE_NOT_FOUND(o,_),r);continue}if(Object.keys(u).forEach(l=>{Q0.includes(l)||fe(le.INVALID_PERM_KEY(l),r,o,_)}),Object.values(In).forEach(l=>{Jr.isDefined(u[l])?Jr.isBoolean(u[l])||fe(le.TABLE_PERM_NOT_BOOLEAN(l),r,o,_):fe(le.TABLE_PERM_MISSING(l),r,o,_)}),Jr.isDefined(u.attribute_permissions)){if(!Jr.isArray(u.attribute_permissions)){fe(le.ATTR_PERMS_NOT_ARRAY,r,o,_);continue}}else{fe(le.ATTR_PERMS_ARRAY_MISSING,r,o,_);continue}if(u.attribute_permissions){let l=global.hdb_schema[o][_].attributes.map(({attribute:d})=>d),E={read:!1,insert:!1,update:!1};for(let d in u.attribute_permissions){let h=u.attribute_permissions[d];if(Object.keys(h).forEach(R=>{!W0.includes(R)&&R!==In.DELETE&&fe(le.INVALID_ATTR_PERM_KEY(R),r,o,_)}),!Jr.isDefined(h.attribute_name)){fe(le.ATTR_PERM_MISSING_NAME,r,o,_);continue}let m=h.attribute_name;if(!l.includes(m)){fe(le.INVALID_ATTRIBUTE_IN_PERMS(m),r,o,_);continue}iO.forEach(R=>{Jr.isDefined(h[R])?Jr.isBoolean(h[R])||fe(le.ATTR_PERM_NOT_BOOLEAN(R,m),r,o,_):fe(le.ATTR_PERM_MISSING(R,m),r,o,_)}),!E.read&&h.read===!0&&(E.read=!0),!E.insert&&h.insert===!0&&(E.insert=!0),!E.update&&h.update===!0&&(E.update=!0)}if(u.read===!1&&E.read===!0||u.insert===!1&&E.insert===!0||u.update===!1&&E.update===!0){let d=`${o}.${_}`;fe(le.MISMATCHED_TABLE_ATTR_PERMS(d),r,o,_)}}}}return eV(r)}a(aO,"customValidate");oO.exports={addRoleValidation:J0,alterRoleValidation:Z0,dropRoleValidation:X0};function j0(e){let{operation:t,permission:r}=e;if(t===gn.OPERATIONS_ENUM.ADD_ROLE||t===gn.OPERATIONS_ENUM.ALTER_ROLE){let s=r.super_user===!0,n=r.cluster_user===!0;if(Object.keys(r).length>1&&(s||n)){if(n&&s)return le.SU_CU_ROLE_COMBINED_ERROR;{let o=r.super_user?gn.ROLE_TYPES_ENUM.SUPER_USER:gn.ROLE_TYPES_ENUM.CLUSTER_USER;return le.SU_CU_ROLE_NO_PERMS_ALLOWED(o)}}}return null}a(j0,"validateNoSUPerms");function eV(e){let{main_permissions:t,schema_permissions:r}=e;if(t.length>0||Object.keys(r).length>0){let s={error:le.ROLE_PERMS_ERROR,...e};return V0(new Error,s,x0.BAD_REQUEST)}else return null}a(eV,"generateRolePermResponse");function fe(e,t,r,s){if(!r)t.main_permissions.push(e);else{let n=s?r+"_"+s:r;t.schema_permissions[n]?t.schema_permissions[n].push(e):t.schema_permissions[n]=[e]}}a(fe,"addPermError")});var uE=S((BX,hO)=>{"use strict";var _O=Ut(),uO=mt(),tV=Rs(),iE=cO(),aE=js(),rV=require("uuid").v4,oE=require("util"),sV=Ai(),Nr=T(),lO=b(),cE=oE.promisify(uO.searchByValue),nV=oE.promisify(uO.searchByHash),iV=oE.promisify(tV.delete),aV=Kt(),oV=ds(),{hdb_errors:cV,handleHDBError:Ui}=D(),{HDB_ERROR_MSGS:EO,HTTP_STATUS_CODES:sE}=cV,{UserEventMsg:_E}=Gr();hO.exports={addRole:_V,alterRole:lV,dropRole:EV,listRoles:dO};function nE(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(nE,"scrubRoleDetails");async function _V(e){let t=iE.addRoleValidation(e);if(t)throw t;if(!(await sV.getLicense()).enterprise){let o=await dO();if(uV(e,o))throw new Error(`Your current license only supports ${Nr.BASIC_LICENSE_MAX_CLUSTER_USER_ROLES} cluster_user role. ${Nr.SUPPORT_HELP_MSG}`);if(o.length>=2)throw new Error(`Your current license only supports ${Nr.BASIC_LICENSE_MAX_NON_CU_ROLES+Nr.BASIC_LICENSE_MAX_CLUSTER_USER_ROLES} roles. ${Nr.SUPPORT_HELP_MSG}`)}e=nE(e);let s={schema:"system",table:"hdb_role",search_attribute:"role",search_value:e.role,hash_attribute:"id",get_attributes:["*"]},n;try{n=await cE(s)}catch(o){throw Ui(o)}if(n&&n.length>0)throw Ui(new Error,EO.ROLE_ALREADY_EXISTS(e.role),sE.CONFLICT,void 0,void 0,!0);e.id||(e.id=rV());let i={operation:"insert",schema:"system",table:"hdb_role",hash_attribute:"id",records:[e]};return await _O.insert(i),aE.signalUserChange(new _E(process.pid)),e=nE(e),e}a(_V,"addRole");function uV(e,t){let r=!1;if(e.permission.cluster_user===!0)for(let s=0;s<t.length;s++){let i=t[s].permission;if(!lO.isEmpty(i)&&i.cluster_user===!0)return!0}return r}a(uV,"checkClusterUserRole");async function lV(e){let t=iE.alterRoleValidation(e);if(t)throw t;e=nE(e);let r={operation:"update",schema:"system",table:"hdb_role",hash_attribute:"rolename",records:[e]};try{await _O.update(r)}catch(s){throw Ui(s)}return aE.signalUserChange(new _E(process.pid)),e}a(lV,"alterRole");async function EV(e){let t=iE.dropRoleValidation(e);if(t)throw Ui(new Error,t,sE.BAD_REQUEST,void 0,void 0,!0);let r=new oV(Nr.SYSTEM_SCHEMA_NAME,Nr.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME,[e.id],["role"]),s=await nV(r);if(s.length===0)throw Ui(new Error,EO.ROLE_NOT_FOUND,sE.NOT_FOUND,void 0,void 0,!0);let n=new aV(Nr.SYSTEM_SCHEMA_NAME,Nr.SYSTEM_TABLE_NAMES.USER_TABLE_NAME,"role",e.id,void 0,["username","active"]),i=await cE(n),o=!1;if(lO.isEmptyOrZeroLength(i)===!1){for(let _=0;_<i.length;_++)if(i[_].active===!0){o=!0;break}}if(o===!0)throw new Error(`Cannot drop role ${s[0].role} as it has active user(s) tied to this role`);let c={table:"hdb_role",schema:"system",hash_values:[e.id]};return await iV(c),aE.signalUserChange(new _E(process.pid)),`${s[0].role} successfully deleted`}a(EV,"dropRole");async function dO(){return cE({table:"hdb_role",schema:"system",hash_attribute:"id",search_attribute:"id",search_value:"*",get_attributes:["*"]})}a(dO,"listRoles")});var mO=S((vX,TO)=>{"use strict";var dV=Y(),Zr=require("joi"),hV=de(),SO=require("moment"),SV=require("fs-extra"),lE=require("path"),fV=require("lodash"),yi=T(),{LOG_LEVELS:Cs}=T(),TV="YYYY-MM-DD hh:mm:ss",mV=lE.resolve(__dirname,"../logs");TO.exports=function(e){return hV.validateBySchema(e,RV)};var RV=Zr.object({from:Zr.custom(fO),until:Zr.custom(fO),level:Zr.valid(Cs.NOTIFY,Cs.FATAL,Cs.ERROR,Cs.WARN,Cs.INFO,Cs.DEBUG,Cs.TRACE),order:Zr.valid("asc","desc"),limit:Zr.number().min(1),start:Zr.number().min(0),log_name:Zr.custom(AV)});function fO(e,t){if(SO(e,SO.ISO_8601).format(TV)==="Invalid date")return t.message(`'${t.state.path[0]}' date '${e}' is invalid.`)}a(fO,"validateDatetime");function AV(e,t){if(fV.invert(yi.PROCESS_LOG_NAMES)[e]===void 0)return t.message(`'log_name' '${e}' is invalid.`);let s=dV.get(yi.HDB_SETTINGS_NAMES.LOG_PATH_KEY),n=e===void 0?yi.PROCESS_LOG_NAMES.HDB:e,i=n===yi.PROCESS_LOG_NAMES.INSTALL?lE.join(mV,yi.PROCESS_LOG_NAMES.INSTALL):lE.join(s,n);return SV.existsSync(i)?null:t.message(`'log_name' '${e}' does not exist.`)}a(AV,"validateReadLogPath")});var dE=S((HX,AO)=>{"use strict";var ic=T(),RO=I(),OV=Y(),pV=mO(),EE=require("path"),NV=require("fs-extra"),gV=require("readline"),{once:IV}=require("events"),{handleHDBError:bV,hdb_errors:CV}=D(),{PACKAGE_ROOT:wV}=T(),LV=EE.join(wV,"logs"),UV=1e3;AO.exports=yV;async function yV(e){let t=pV(e);if(t)throw bV(t,t.message,CV.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0);let r=OV.get(ic.HDB_SETTINGS_NAMES.LOG_PATH_KEY),s=e.log_name===void 0?ic.PROCESS_LOG_NAMES.HDB:e.log_name,n=s===ic.PROCESS_LOG_NAMES.INSTALL?EE.join(LV,ic.PROCESS_LOG_NAMES.INSTALL):EE.join(r,s),i=NV.createReadStream(n);i.on("error",z=>{RO.error(z)});let o=gV.createInterface({input:i,crlfDelay:1/0}),c=e.level!==void 0,_=c?e.level:void 0,u=e.from!==void 0,l=u?new Date(e.from):void 0,E=e.until!==void 0,d=E?new Date(e.until):void 0,h=e.limit===void 0?UV:e.limit,m=e.order===void 0?void 0:e.order,R=e.start===void 0?0:e.start,w=R+h,L=0,B=[];return o.on("line",z=>{let V,W,ke,xe;try{V=JSON.parse(z)}catch(ua){RO.warn(ua.message);return}switch(!0){case(c&&u&&E):W=new Date(V.timestamp),ke=new Date(l),xe=new Date(d),V.level===_&&W>=ke&&W<=xe&&L<R?L++:V.level===_&&W>=ke&&W<=xe&&(zr(V,m,B),L++,L===w&&Xr(o));break;case(c&&u):W=new Date(V.timestamp),ke=new Date(l),V.level===_&&W>=ke&&L<R?L++:V.level===_&&W>=ke&&(zr(V,m,B),L++,L===w&&Xr(o));break;case(c&&E):W=new Date(V.timestamp),xe=new Date(d),V.level===_&&W<=xe&&L<R?L++:V.level===_&&W<=xe&&(zr(V,m,B),L++,L===w&&Xr(o));break;case(u&&E):W=new Date(V.timestamp),ke=new Date(l),xe=new Date(d),W>=ke&&W<=xe&&L<R?L++:W>=ke&&W<=xe&&(zr(V,m,B),L++,L===w&&Xr(o));break;case c:V.level===_&&L<R?L++:V.level===_&&(zr(V,m,B),L++,L===w&&Xr(o));break;case u:W=new Date(V.timestamp),ke=new Date(l),W>=ke&&L<R?L++:W>=ke&&L>=R&&(zr(V,m,B),L++,L===w&&Xr(o));break;case E:W=new Date(V.timestamp),xe=new Date(d),W<=xe&&L<R?L++:W<=xe&&L>=R&&(zr(V,m,B),L++,L===w&&Xr(o));break;default:L<R?L++:(zr(V,m,B),L++,L===w&&Xr(o))}}),await IV(o,"close"),B}a(yV,"readLog");function Xr(e){e.close(),e.removeAllListeners()}a(Xr,"endReadLine");function zr(e,t,r){t==="desc"?DV(e,r):t==="asc"?MV(e,r):r.push(e)}a(zr,"pushLineToResult");function DV(e,t){let r=new Date(e.timestamp),s=0,n=t.length;for(;s<n;){let i=s+n>>>1;new Date(t[i].timestamp)>r?s=i+1:n=i}t.splice(s,0,e)}a(DV,"insertDescending");function MV(e,t){let r=new Date(e.timestamp),s=0,n=t.length;for(;s<n;){let i=s+n>>>1;new Date(t[i].timestamp)<r?s=i+1:n=i}t.splice(s,0,e)}a(MV,"insertAscending")});var oc=S((FX,NO)=>{"use strict";var hE=require("joi"),{string:ac,boolean:OO,date:PV}=hE.types(),BV=de(),{validateSchemaExists:GX,validateTableExists:qX,validateSchemaName:vV}=Tr(),HV=T(),GV=_e(),qV=Y(),FV=ac.invalid(qV.get(HV.CONFIG_PARAMS.CLUSTERING_NODENAME)).pattern(GV.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(),pO={operation:ac.valid("add_node","update_node"),node_name:FV,subscriptions:hE.array().items({table:ac.required(),schema:ac.custom(vV).required(),subscribe:OO.required(),publish:OO.required().custom(kV),start_time:PV.iso()}).min(1).required()};function VV(e){return BV.validateBySchema(e,hE.object(pO))}a(VV,"addUpdateNodeValidator");function kV(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(kV,"checkForFalsy");NO.exports={addUpdateNodeValidator:VV,validation_schema:pO}});var IO=S((VX,gO)=>{var xV=de(),$V={user:{presence:!0},schema:{presence:!0},table:{presence:!0},operation:{presence:!0}};gO.exports=function(e){return xV.validateObject(e,$V)}});var SE=S((kX,bO)=>{"use strict";var YV=T().OPERATIONS_ENUM,cc=class{constructor(t,r,s,n=void 0){this.operation=YV.UPDATE,this.schema=t,this.table=r,this.records=s,this.__origin=n}};a(cc,"UpdateObject");bO.exports=cc});var wO=S((xX,CO)=>{"use strict";var KV={OPERATION:"operation",REFRESH:"refresh"},_c=class{constructor(t,r){this.operation_token=t,this.refresh_token=r}};a(_c,"JWTTokens");var uc=class{constructor(t,r,s){this.public_key=t,this.private_key=r,this.passphrase=s}};a(uc,"JWTRSAKeys");CO.exports={JWTTokens:_c,TOKEN_TYPE_ENUM:KV,JWTRSAKeys:uc}});var hc=S(($X,DO)=>{"use strict";var Mi=require("jsonwebtoken"),fE=require("fs-extra"),TE=b(),Dt=T(),{handleHDBError:ct,hdb_errors:QV}=D(),{HTTP_STATUS_CODES:_t,AUTHENTICATION_ERROR_MSGS:ut}=QV,Di=I(),LO=xo(),AE=Wr(),WV=Ut().update,JV=SE(),ZV=js(),{UserEventMsg:XV}=Gr(),jr=Y();jr.initSync();var mE=require("path"),{JWTTokens:zV,JWTRSAKeys:jV,TOKEN_TYPE_ENUM:lc}=wO(),ek=jr.get(Dt.HDB_SETTINGS_NAMES.OPERATION_TOKEN_TIMEOUT_KEY)?jr.get(Dt.HDB_SETTINGS_NAMES.OPERATION_TOKEN_TIMEOUT_KEY):"1d",tk=jr.get(Dt.HDB_SETTINGS_NAMES.REFRESH_TOKEN_TIMEOUT_KEY)?jr.get(Dt.HDB_SETTINGS_NAMES.REFRESH_TOKEN_TIMEOUT_KEY):"30d",Ec="RS256",RE;DO.exports={createTokens:rk,validateOperationToken:nk,refreshOperationToken:sk,validateRefreshToken:yO};async function rk(e){if(TE.isEmpty(e)||typeof e!="object")throw ct(new Error,ut.INVALID_AUTH_OBJECT,_t.BAD_REQUEST,void 0,void 0,!0);if(TE.isEmpty(e.username))throw ct(new Error,ut.USERNAME_REQUIRED,_t.BAD_REQUEST,void 0,void 0,!0);if(TE.isEmpty(e.password))throw ct(new Error,ut.PASSWORD_REQUIRED,_t.BAD_REQUEST,void 0,void 0,!0);let t;try{if(t=await AE.findAndValidateUser(e.username,e.password),!t)throw ct(new Error,ut.INVALID_CREDENTIALS,_t.UNAUTHORIZED,void 0,void 0,!0)}catch(d){throw Di.error(d),ct(new Error,ut.INVALID_CREDENTIALS,_t.UNAUTHORIZED,void 0,void 0,!0)}let r=await dc(),s=!1,n=!1;t.role&&t.role.permission&&(s=t.role.permission.super_user===!0,n=t.role.permission.cluster_user===!0);let i={username:e.username,super_user:s,cluster_user:n},o=await UO(i,r.private_key,r.passphrase),c=await Mi.sign(i,{key:r.private_key,passphrase:r.passphrase},{expiresIn:tk,algorithm:Ec,subject:lc.REFRESH}),_=LO.hash(c),u=new JV(Dt.SYSTEM_SCHEMA_NAME,Dt.SYSTEM_TABLE_NAMES.USER_TABLE_NAME,[{username:e.username,refresh_token:_}]),l,E;try{l=await WV(u)}catch(d){Di.error(d),E=d}if(E!==void 0||l.skipped_hashes.length>0)throw ct(new Error,ut.REFRESH_TOKEN_SAVE_FAILED,_t.INTERNAL_SERVER_ERROR);return ZV.signalUserChange(new XV(process.pid)),new zV(o,c)}a(rk,"createTokens");async function UO(e,t,r){return await Mi.sign(e,{key:t,passphrase:r},{expiresIn:ek,algorithm:Ec,subject:lc.OPERATION})}a(UO,"signOperationToken");async function dc(){if(RE===void 0)try{let e=mE.join(jr.getHdbBasePath(),Dt.LICENSE_KEY_DIR_NAME,Dt.JWT_ENUM.JWT_PASSPHRASE_NAME),t=mE.join(jr.getHdbBasePath(),Dt.LICENSE_KEY_DIR_NAME,Dt.JWT_ENUM.JWT_PRIVATE_KEY_NAME),r=mE.join(jr.getHdbBasePath(),Dt.LICENSE_KEY_DIR_NAME,Dt.JWT_ENUM.JWT_PUBLIC_KEY_NAME),s=(await fE.readFile(e)).toString(),n=(await fE.readFile(t)).toString(),i=(await fE.readFile(r)).toString();RE=new jV(i,n,s)}catch(e){throw Di.error(e),ct(new Error,ut.NO_ENCRYPTION_KEYS,_t.INTERNAL_SERVER_ERROR)}return RE}a(dc,"getJWTRSAKeys");async function sk(e){if(!e)throw ct(new Error,ut.INVALID_BODY,_t.BAD_REQUEST,void 0,void 0,!0);if(!e.refresh_token)throw ct(new Error,ut.REFRESH_TOKEN_REQUIRED,_t.BAD_REQUEST,void 0,void 0,!0);await yO(e.refresh_token);let t=await dc(),r=await Mi.decode(e.refresh_token);return{operation_token:await UO({username:r.username,super_user:r.super_user,cluster_user:r.cluster_user},t.private_key,t.passphrase)}}a(sk,"refreshOperationToken");async function nk(e){try{let t=await dc(),r=await Mi.verify(e,t.public_key,{algorithms:Ec,subject:lc.OPERATION});return await AE.findAndValidateUser(r.username,void 0,!1)}catch(t){throw Di.warn(t),t.name&&t.name==="TokenExpiredError"?ct(new Error,ut.TOKEN_EXPIRED,_t.FORBIDDEN):ct(new Error,ut.INVALID_TOKEN,_t.UNAUTHORIZED)}}a(nk,"validateOperationToken");async function yO(e){let t;try{let r=await dc(),s=await Mi.verify(e,r.public_key,{algorithms:Ec,subject:lc.REFRESH});t=await AE.findAndValidateUser(s.username,void 0,!1)}catch(r){throw Di.warn(r),r.name&&r.name==="TokenExpiredError"?ct(new Error,ut.TOKEN_EXPIRED,_t.FORBIDDEN):ct(new Error,ut.INVALID_TOKEN,_t.UNAUTHORIZED)}if(!LO.validate(t.refresh_token,e))throw ct(new Error,ut.INVALID_TOKEN,_t.UNAUTHORIZED);return t}a(yO,"validateRefreshToken")});var vO=S((KX,BO)=>{"use strict";var ik=IO(),bn=require("passport"),ak=require("passport-local").Strategy,ok=require("passport-http").BasicStrategy,ck=require("util"),_k=Wr(),PO=ck.callbackify(_k.findAndValidateUser),YX=Ke(),uk=T(),MO=hc();bn.use(new ak(function(e,t,r){PO(e,t,r)}));bn.use(new ok(function(e,t,r){PO(e,t,r)}));bn.serializeUser(function(e,t){t(null,e)});bn.deserializeUser(function(e,t){t(null,e)});function lk(e,t,r){let s,n;if(e.headers&&e.headers.authorization){let o=e.headers.authorization.split(" ");s=o[0],n=o[1]}function i(o,c){return o?r(o):c?r(null,c):r("User not found")}switch(a(i,"handleResponse"),s){case"Basic":bn.authenticate("basic",{session:!1},(o,c)=>{i(o,c)})(e,t,r);break;case"Bearer":e.body&&e.body.operation&&e.body.operation===uk.OPERATIONS_ENUM.REFRESH_OPERATION_TOKEN?MO.validateRefreshToken(n).then(o=>{e.body.refresh_token=n,r(null,o)}).catch(o=>{r(o)}):MO.validateOperationToken(n).then(o=>{r(null,o)}).catch(o=>{r(o)});break;default:bn.authenticate("local",{session:!1},function(o,c){i(o,c)})(e,t,r);break}}a(lk,"authorize");function Ek(e,t){let r=ik(e);if(r){t(r);return}let s={authorized:!0,messages:[]},n=e.user.role;if(!n||!n.permission)return t("Invalid role");let i=JSON.parse(n.permission);if(i.super_user)return t(null,s);if(!i[e.schema])return s.authorized=!1,s.messages.push(`Not authorized to access ${e.schema} schema`),t(null,s);if(!i[e.schema].tables[e.table])return s.authorized=!1,s.messages.push(`Not authorized to access ${e.table} table`),t(null,s);if(!i[e.schema].tables[e.table][e.operation])return s.authorized=!1,s.messages.push(`Not authorized to access ${e.operation} on ${e.table} table`),t(null,s);if(i[e.schema].tables[e.table].attribute_permissions&&!e.attributes)return s.authorized=!1,s.messages.push(`${e.schema}.${e.table} has attribute permissions. Missing attributes to validate`),t(null,s);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]&&(s.authorized=!1,s.messages.push(`Not authorized to ${e.operation} ${o[c].attribute_name} `))}return t(null,s)}a(Ek,"checkPermissions");BO.exports={authorize:lk,checkPermissions:Ek}});var Cn=S((QX,HO)=>{"use strict";var Sc=class{constructor(t,r,s){this.name=t,this.subscriptions=r,this.system_info=s}};a(Sc,"Node");var fc=class{constructor(t,r,s,n){this.schema=t,this.table=r,this.publish=s,this.subscribe=n}};a(fc,"NodeSubscription");HO.exports={Node:Sc,NodeSubscription:fc}});var qO=S((WX,GO)=>{"use strict";var dk=T().OPERATIONS_ENUM,Tc=class{constructor(t,r,s,n=void 0){this.operation=dk.UPSERT,this.schema=t,this.table=r,this.records=s,this.__origin=n}};a(Tc,"UpsertObject");GO.exports=Tc});var Pi=S((JX,FO)=>{"use strict";var mc=class{constructor(t,r,s,n){this.operation=t,this.node_name=r,this.subscriptions=s,this.system_info=n}};a(mc,"RemotePayloadObject");var Rc=class{constructor(t,r,s,n,i,o){this.schema=t,this.table=r,this.hash_attribute=s,this.publish=n,this.subscribe=i,this.start_time=o}};a(Rc,"RemotePayloadSubscription");FO.exports={RemotePayloadObject:mc,RemotePayloadSubscription:Rc}});var kO=S((ZX,VO)=>{"use strict";var Ac=class{constructor(t,r,s=0,n=0,i=0,o=0){this.schema=t,this.table=r,this.table_size=s,this.record_count=n,this.transaction_log_size=i,this.transaction_log_record_count=o}};a(Ac,"TableSizeObject");VO.exports=Ac});var KO=S((XX,YO)=>{"use strict";var hk=kO(),xO=require("path"),$O=te(),Sk=Ye(),wn=Z(),fk=I();YO.exports=Tk;async function Tk(e){let t=new hk;try{let r=xO.join($O.getBaseSchemaPath(),e.schema.toString()),s=await wn.openEnvironment(r,e.name),n=wn.statDBI(s,e.hash_attribute),i=xO.join($O.getTransactionAuditStorePath(),e.schema.toString()),o=await wn.openEnvironment(i,e.name,!0),c=wn.statDBI(o,Sk.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP),_=await wn.environmentDataSize(r,e.name),u=await wn.environmentDataSize(i,e.name);t.schema=e.schema,t.table=e.name,t.table_size=_,t.record_count=n.entryCount,t.transaction_log_size=u,t.transaction_log_record_count=c.entryCount}catch(r){fk.warn(`unable to stat table dbi due to ${r}`)}return t}a(Tk,"lmdbGetTableSize")});var WO=S((zX,QO)=>{"use strict";var mk=T(),Oc=class{constructor(t){this.operator=mk.OPERATIONS_ENUM.SYSTEM_INFORMATION,this.attributes=t}};a(Oc,"SystemInformationOperation");QO.exports=Oc});var ZO=S((jX,JO)=>{"use strict";var pc=class{constructor(t,r,s,n,i,o,c){this.system=t,this.time=r,this.cpu=s,this.memory=n,this.disk=i,this.network=o,this.harperdb_processes=c}};a(pc,"SystemInformationObject");JO.exports=pc});var gc=S((t3,XO)=>{"use strict";var ve=require("systeminformation"),Ln=I(),Rk=T(),Ak=KO(),Ok=fs(),pk=Y();pk.initSync();var e3=WO(),Nk=ZO(),Nc;XO.exports={getHDBProcessInfo:gE,getNetworkInfo:bE,getDiskInfo:IE,getMemoryInfo:NE,getCPUInfo:pE,getTimeInfo:OE,getSystemInformation:CE,systemInformation:gk,getTableSize:wE};function OE(){return ve.time()}a(OE,"getTimeInfo");async function pE(){try{let{family:e,model:t,stepping:r,revision:s,voltage:n,speedmin:i,speedmax:o,governor:c,socket:_,cache:u,...l}=await ve.cpu();l.cpu_speed=await ve.cpuCurrentSpeed();let{raw_currentload:E,raw_currentload_idle:d,raw_currentload_irq:h,raw_currentload_nice:m,raw_currentload_system:R,raw_currentload_user:w,cpus:L,...B}=await ve.currentLoad();return B.cpus=[],L.forEach(z=>{let{raw_load:V,raw_load_idle:W,raw_load_irq:ke,raw_load_nice:xe,raw_load_system:ua,raw_load_user:la,...yr}=z;B.cpus.push(yr)}),l.current_load=B,l}catch(e){return Ln.error(`error in getCPUInfo: ${e}`),{}}}a(pE,"getCPUInfo");async function NE(){try{let{buffers:e,cached:t,slab:r,buffcache:s,...n}=await ve.mem();return n}catch(e){return Ln.error(`error in getMemoryInfo: ${e}`),{}}}a(NE,"getMemoryInfo");async function gE(){let e={core:[],clustering:[]};try{return(await ve.processes()).list.forEach(r=>{r.params.includes(Rk.HDB_PROC_NAME)?e.core.push(r):r.params.includes("socketcluster")&&e.clustering.push(r)}),e}catch(t){return Ln.error(`error in getHDBProcessInfo: ${t}`),e}}a(gE,"getHDBProcessInfo");async function IE(){let e={};try{let{rIO_sec:t,wIO_sec:r,tIO_sec:s,ms:n,...i}=await ve.disksIO();e.io=i;let{rx_sec:o,tx_sec:c,wx_sec:_,...u}=await ve.fsStats();return e.read_write=u,e.size=await ve.fsSize(),e}catch(t){return Ln.error(`error in getDiskInfo: ${t}`),e}}a(IE,"getDiskInfo");async function bE(){let e={default_interface:null,latency:{},interfaces:[],stats:[],connections:[]};try{return e.default_interface=await ve.networkInterfaceDefault(),e.latency=await ve.inetChecksite("google.com"),(await ve.networkInterfaces()).forEach(s=>{let{internal:n,virtual:i,mtu:o,dhcp:c,dnsSuffix:_,ieee8021xAuth:u,ieee8021xState:l,carrier_changes:E,...d}=s;e.interfaces.push(d)}),(await ve.networkStats()).forEach(s=>{let{rx_sec:n,tx_sec:i,ms:o,...c}=s;e.stats.push(c)}),e.connections=await ve.networkConnections(),e}catch(t){return Ln.error(`error in getNetworkInfo: ${t}`),e}}a(bE,"getNetworkInfo");async function CE(){if(Nc!==void 0)return Nc;let e={};try{let{codepage:t,logofile:r,serial:s,build:n,servicepack:i,uefi:o,...c}=await ve.osInfo();e=c;let _=await ve.versions("node, npm");return e.node_version=_.node,e.npm_version=_.npm,Nc=e,Nc}catch(t){return Ln.error(`error in getSystemInformation: ${t}`),e}}a(CE,"getSystemInformation");async function wE(){let e=[],t=await Ok.describeAll();for(let r of Object.values(t))for(let s of Object.values(r))e.push(await Ak(s));return e}a(wE,"getTableSize");async function gk(e){let t=new Nk;if(!Array.isArray(e.attributes)||e.attributes.length===0)return t.system=await CE(),t.time=OE(),t.cpu=await pE(),t.memory=await NE(),t.disk=await IE(),t.network=await bE(),t.harperdb_processes=await gE(),t.table_size=await wE(),t;for(let r=0;r<e.attributes.length;r++)switch(e.attributes[r]){case"system":t.system=await CE();break;case"time":t.time=OE();break;case"cpu":t.cpu=await pE();break;case"memory":t.memory=await NE();break;case"disk":t.disk=await IE();break;case"network":t.network=await bE();break;case"harperdb_processes":t.harperdb_processes=await gE();break;case"table_size":t.table_size=await wE();break;default:break}return t}a(gk,"systemInformation")});var LE=S((n3,zO)=>{"use strict";var r3=require("fs-extra"),s3=I();zO.exports={version:Ik,printVersion:Ck,nodeVersion:bk};var es=vl();function Ik(){if(es)return es.version}a(Ik,"version");function bk(){if(es&&es.engines&&es.engines["preferred-node"])return es.engines["preferred-node"]}a(bk,"nodeVersion");function Ck(){es&&console.log(`HarperDB Version ${es.version}`)}a(Ck,"printVersion")});var Ls=S((o3,rp)=>{"use strict";var wk=Ut(),UE=b(),yE=require("util"),ws=T(),jO=Y();jO.initSync();var Lk=vO(),ep=mt(),{Node:i3,NodeSubscription:a3}=Cn(),Uk=ds(),yk=qO(),{RemotePayloadObject:Dk,RemotePayloadSubscription:Mk}=Pi(),{handleHDBError:Pk,hdb_errors:Bk}=D(),{HTTP_STATUS_CODES:vk,HDB_ERROR_MSGS:Hk}=Bk,Gk=Kt(),qk=gc(),Fk=LE(),Vk=yE.promisify(Lk.authorize),kk=yE.promisify(ep.searchByHash),xk=yE.promisify(ep.searchByValue);rp.exports={authHeaderToUser:$k,isEmpty:Yk,getNodeRecord:Kk,upsertNodeRecord:Qk,buildNodePayloads:Wk,checkClusteringEnabled:Jk,getAllNodeRecords:Zk,getSystemInfo:Xk,reverseSubscription:tp};async function $k(e){let t={headers:{authorization:e.hdb_auth_header}};return e.hdb_user=await Vk(t,null),e}a($k,"authHeaderToUser");function Yk(e){return e==null}a(Yk,"isEmpty");async function Kk(e){let t=new Uk(ws.SYSTEM_SCHEMA_NAME,ws.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[e],["*"]);return kk(t)}a(Kk,"getNodeRecord");async function Qk(e){let t=new yk(ws.SYSTEM_SCHEMA_NAME,ws.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[e]);return wk.upsert(t)}a(Qk,"upsertNodeRecord");function tp(e){if(UE.isEmpty(e.subscribe)||UE.isEmpty(e.publish))throw new Error("Received invalid subscription object");let{schema:t,table:r,hash_attribute:s}=e,n={schema:t,table:r,hash_attribute:s};return e.subscribe===!0&&e.publish===!1?(n.subscribe=!1,n.publish=!0):e.subscribe===!1&&e.publish===!0?(n.subscribe=!0,n.publish=!1):(n.subscribe=e.subscribe,n.publish=e.publish),n}a(tp,"reverseSubscription");function Wk(e,t,r,s){let n=[];for(let i=0,o=e.length;i<o;i++){let c=e[i],{schema:_,table:u}=c,l=UE.getTableHashAttribute(_,u),{subscribe:E,publish:d}=tp(c),h=new Mk(_,u,l,d,E,c.start_time);n.push(h)}return new Dk(r,t,n,s)}a(Wk,"buildNodePayloads");function Jk(){if(!jO.get(ws.CONFIG_PARAMS.CLUSTERING_ENABLED))throw Pk(new Error,Hk.CLUSTERING_NOT_ENABLED,vk.BAD_REQUEST,void 0,void 0,!0)}a(Jk,"checkClusteringEnabled");async function Zk(){let e=new Gk(ws.SYSTEM_SCHEMA_NAME,ws.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,"name","*",void 0,["*"]);return xk(e)}a(Zk,"getAllNodeRecords");async function Xk(){let e=await qk.getSystemInformation();return{hdb_version:Fk.version(),node_version:e.node_version,platform:e.platform}}a(Xk,"getSystemInfo")});var ME=S((c3,cp)=>{"use strict";var DE=ot(),sp=b(),np=_e(),zk=T(),Ic=I(),ip=tc(),jk=el(),{RemotePayloadObject:ex}=Pi(),{handleHDBError:ap,hdb_errors:tx}=D(),{HTTP_STATUS_CODES:op}=tx,{NodeSubscription:rx}=Cn();cp.exports=sx;async function sx(e,t){let r;try{r=await DE.request(`${t}.${np.REQUEST_SUFFIX}`,new ex(zk.OPERATIONS_ENUM.DESCRIBE_ALL,t,void 0,void 0)),Ic.trace("Response from remote describe all request:",r)}catch(o){Ic.error(`addNode received error from describe all request to remote node: ${o}`);let c=DE.requestErrorHandler(o,"add_node",t);throw ap(new Error,c,op.INTERNAL_SERVER_ERROR,"error",c)}if(r.status===np.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let o=`Error returned from remote node ${t}: ${r.message}`;throw ap(new Error,o,op.INTERNAL_SERVER_ERROR,"error",o)}let s=r.message,n=[],i=[];for(let o of e){let{schema:c,table:_}=o,u=sp.doesSchemaExist(c),l=s[c]!==void 0,E=sp.doesTableExist(c,_),d=s?.[c]?.[_]!==void 0;if(!u&&!l||!E&&!d){n.push(o);continue}if(!u&&l&&(Ic.trace(`addNode creating schema: ${c}`),await ip.createSchema({operation:"create_schema",schema:c})),!E&&d){Ic.trace(`addNode creating table: ${_} in schema: ${c}`);let m=new jk(c,_,s[c][_].hash_attribute);await ip.createTable(m)}await DE.createLocalTableStream(c,_);let h=new rx(c,_,o.publish,o.subscribe);h.start_time=o.start_time,i.push(h)}return{added:i,skipped:n}}a(sx,"reviewSubscriptions")});var wc=S((_3,lp)=>{"use strict";var{handleHDBError:bc,hdb_errors:nx}=D(),{HTTP_STATUS_CODES:Cc}=nx,{addUpdateNodeValidator:ix}=oc(),Bi=I(),up=T(),_p=_e(),ax=b(),PE=ot(),vi=Ls(),ox=Y(),cx=ME(),{Node:_x,NodeSubscription:ux}=Cn(),lx="Unable to create subscriptions due to schema and/or tables not existing on the local or remote node",Ex="Some subscriptions were unsuccessful due to schema and/or tables not existing on the local or remote node",dx=ox.get(up.CONFIG_PARAMS.CLUSTERING_NODENAME);lp.exports=hx;async function hx(e,t=!1){Bi.trace("addNode called with:",e),vi.checkClusteringEnabled();let r=ix(e);if(r)throw bc(r,r.message,Cc.BAD_REQUEST,void 0,void 0,!0);let s=e.node_name;if(!t){let E=await vi.getNodeRecord(s);if(!ax.isEmptyOrZeroLength(E))throw bc(new Error,`Node '${s}' has already been added, perform update_node to proceed.`,Cc.BAD_REQUEST,void 0,void 0,!0)}let{added:n,skipped:i}=await cx(e.subscriptions,s),o={message:void 0,added:n,skipped:i};if(n.length===0)return o.message=lx,o;let c=vi.buildNodePayloads(n,dx,up.OPERATIONS_ENUM.ADD_NODE,await vi.getSystemInfo());Bi.trace("addNode sending remote payload:",c);let _;try{_=await PE.request(`${s}.${_p.REQUEST_SUFFIX}`,c)}catch(E){Bi.error(`addNode received error from request: ${E}`);let d=PE.requestErrorHandler(E,"add_node",s);throw bc(new Error,d,Cc.INTERNAL_SERVER_ERROR,"error",d)}if(_.status===_p.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let E=`Error returned from remote node ${s}: ${_.message}`;throw bc(new Error,E,Cc.INTERNAL_SERVER_ERROR,"error",E)}Bi.trace(_);let u=[];for(let E=0,d=n.length;E<d;E++){let h=n[E];Bi.trace("Add node updating work stream for node:",s,"subscriptions:",h),await PE.updateWorkStream(h,s),n[E].start_time===void 0&&delete n[E].start_time,u.push(new ux(h.schema,h.table,h.publish,h.subscribe))}let l=new _x(s,u,_.system_info);return await vi.upsertNodeRecord(l),i.length>0?o.message=Ex:o.message=`Successfully added '${s}' to manifest`,o}a(hx,"addNode")});var vE=S((u3,hp)=>{"use strict";var{handleHDBError:Lc,hdb_errors:Sx}=D(),{HTTP_STATUS_CODES:Uc}=Sx,{addUpdateNodeValidator:fx}=oc(),Hi=I(),dp=T(),Ep=_e(),Tx=b(),BE=ot(),Gi=Ls(),mx=Y(),{cloneDeep:Rx}=require("lodash"),Ax=ME(),{NodeSubscription:Ox}=Cn(),px="Unable to update subscriptions due to schema and/or tables not existing on the local or remote node",Nx="Some subscriptions were unsuccessful due to schema and/or tables not existing on the local or remote node",gx=mx.get(dp.CONFIG_PARAMS.CLUSTERING_NODENAME);hp.exports=Ix;async function Ix(e){Hi.trace("updateNode called with:",e),Gi.checkClusteringEnabled();let t=fx(e);if(t)throw Lc(t,t.message,Uc.BAD_REQUEST,void 0,void 0,!0);let r=e.node_name,s=Rx(await Gi.getNodeRecord(r));if(Tx.isEmptyOrZeroLength(s))throw Lc(new Error,`Node '${r}' has not been added, perform add_node to proceed.`,Uc.BAD_REQUEST,void 0,void 0,!0);let{added:n,skipped:i}=await Ax(e.subscriptions,r),o={message:void 0,updated:n,skipped:i};if(n.length===0)return o.message=px,o;let c=Gi.buildNodePayloads(n,gx,dp.OPERATIONS_ENUM.UPDATE_NODE,await Gi.getSystemInfo());Hi.trace("updateNode sending remote payload:",c);let _;try{_=await BE.request(`${r}.${Ep.REQUEST_SUFFIX}`,c)}catch(u){Hi.error(`updateNode received error from request: ${u}`);let l=BE.requestErrorHandler(u,"update_node",r);throw Lc(new Error,l,Uc.INTERNAL_SERVER_ERROR,"error",l)}if(_.status===Ep.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let u=`Error returned from remote node ${r}: ${_.message}`;throw Lc(new Error,u,Uc.INTERNAL_SERVER_ERROR,"error",u)}Hi.trace(_);for(let u=0,l=n.length;u<l;u++){let E=n[u];Hi.trace(`updateNode updating work stream for node: ${r} subscription:`,E),await BE.updateWorkStream(E,r),n[u].start_time===void 0&&delete n[u].start_time}return await bx(s[0],n,_.system_info),i.length>0?o.message=Nx:o.message=`Successfully updated '${r}'`,o}a(Ix,"updateNode");async function bx(e,t,r){let s=e;for(let n=0,i=t.length;n<i;n++){let o=t[n],c=!1;for(let _=0,u=e.subscriptions.length;_<u;_++){let l=s.subscriptions[_];if(l.schema===o.schema&&l.table===o.table){l.publish=o.publish,l.subscribe=o.subscribe,c=!0;break}}c||s.subscriptions.push(new Ox(o.schema,o.table,o.publish,o.subscribe))}s.system_info=r,await Gi.upsertNodeRecord(s)}a(bx,"updateNodeTable")});var Rp=S((l3,mp)=>{"use strict";var Tp=require("joi"),{string:Sp}=Tp.types(),Cx=de(),fp=T(),wx=Y(),Lx=_e();mp.exports=Ux;function Ux(e){let t=Sp.invalid(wx.get(fp.CONFIG_PARAMS.CLUSTERING_NODENAME)).pattern(Lx.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=Tp.object({operation:Sp.valid(fp.OPERATIONS_ENUM.REMOVE_NODE).required(),node_name:t});return Cx.validateBySchema(e,r)}a(Ux,"removeNodeValidator")});var Dc=S((E3,Ip)=>{"use strict";var{handleHDBError:Ap,hdb_errors:yx}=D(),{HTTP_STATUS_CODES:Op}=yx,Dx=Rp(),qi=I(),pp=Ls(),Mx=b(),yc=T(),Np=_e(),gp=ot(),Px=Y(),{RemotePayloadObject:Bx}=Pi(),{NodeSubscription:vx}=Cn(),Hx=li(),Gx=Rs(),qx=Px.get(yc.CONFIG_PARAMS.CLUSTERING_NODENAME);Ip.exports=Fx;async function Fx(e){qi.trace("removeNode called with:",e),pp.checkClusteringEnabled();let t=Dx(e);if(t)throw Ap(t,t.message,Op.BAD_REQUEST,void 0,void 0,!0);let r=e.node_name,s=await pp.getNodeRecord(r);if(Mx.isEmptyOrZeroLength(s))throw Ap(new Error,`Node '${r}' was not found.`,Op.BAD_REQUEST,void 0,void 0,!0);s=s[0];let n=new Bx(yc.OPERATIONS_ENUM.REMOVE_NODE,qx,[]),i,o=!1;try{i=await gp.request(`${r}.${Np.REQUEST_SUFFIX}`,n),qi.trace("Remove node reply from remote node:",r,i)}catch(_){qi.error("removeNode received error from request:",_),o=!0}for(let _=0,u=s.subscriptions.length;_<u;_++){let l=s.subscriptions[_];qi.trace(`Remove node removing subscription: ${l.schema}.${l.table} for node: ${r}`);let E=new vx(l.schema,l.table,!1,!1);await gp.updateWorkStream(E,r)}let c=new Hx(yc.SYSTEM_SCHEMA_NAME,yc.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[r]);return await Gx.deleteRecord(c),i?.status===Np.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR||o?(qi.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(Fx,"removeNode")});var wp=S((d3,Cp)=>{"use strict";var bp=require("joi"),{string:Vx,array:kx}=bp.types(),xx=de(),$x=oc();Cp.exports=Yx;function Yx(e){let t=bp.object({operation:Vx.valid("configure_cluster").required(),connections:kx.items($x.validation_schema).required()});return xx.validateBySchema(e,t)}a(Yx,"configureClusterValidator")});var HE=S((h3,Mp)=>{"use strict";var Kx=T(),Mc=I(),Qx=b(),Wx=Dc(),Jx=wc(),Lp=Ls(),Zx=wp(),{handleHDBError:Up,hdb_errors:Xx}=D(),{HTTP_STATUS_CODES:yp}=Xx,zx="Configure cluster complete.",jx="Failed to configure the cluster. Check the logs for more details.",e$="Configure cluster was partially successful. Errors occurred when attempting to configure the following nodes. Check the logs for more details.";Mp.exports=t$;async function t$(e){Mc.trace("configure cluster called with:",e),Lp.checkClusteringEnabled();let t=Zx(e);if(t)throw Up(t,t.message,yp.BAD_REQUEST,void 0,void 0,!0);let r=await Lp.getAllNodeRecords(),s=[];for(let d=0,h=r.length;d<h;d++)s.push(Dp(Wx,{operation:Kx.OPERATIONS_ENUM.REMOVE_NODE,node_name:r[d].name},r[d].name));let n=await Promise.allSettled(s);Mc.trace("All results from configure_cluster remove node:",n);let i=[],o=e.connections.length;for(let d=0;d<o;d++){let h=e.connections[d];i.push(Dp(Jx,h,h.node_name))}let c=await Promise.allSettled(i);Mc.trace("All results from configure_cluster add node:",c);let _=[],u=[],l=!1,E=n.concat(c);for(let d=0,h=E.length;d<h;d++){let m=E[d];m.status==="rejected"&&(Mc.error(m.reason),_.includes(m.reason.node_name)||_.push(m.reason.node_name)),m.status==="fulfilled"&&(l=!0);let R=m?.value?.result;typeof R=="string"&&R.includes("Successfully removed")||m.status==="rejected"||u.push({node_name:m?.value?.node_name,subscriptions:m?.value?.result})}if(Qx.isEmptyOrZeroLength(_))return{message:zx,connections:u};if(l)return{message:e$,failed_nodes:_,connections:u};throw Up(new Error,jx,yp.INTERNAL_SERVER_ERROR,void 0,void 0,!0)}a(t$,"configureCluster");async function Dp(e,t,r){try{return{node_name:r,result:await e(t)}}catch(s){throw{node_name:r,error:s}}}a(Dp,"functionWrapper")});var FE=S((S3,qp)=>{"use strict";var qE=Ls(),r$=ot(),vp=Y(),Pc=T(),Us=_e(),s$=b(),GE=I(),{RemotePayloadObject:n$}=Pi(),{ErrorCode:Pp}=require("nats"),Bp=vp.get(Pc.CONFIG_PARAMS.CLUSTERING_ENABLED),Hp=vp.get(Pc.CONFIG_PARAMS.CLUSTERING_NODENAME);qp.exports={clusterStatus:i$,buildNodeStatus:Gp};async function i$(){let e={node_name:Hp,is_enabled:Bp,connections:[]};if(!Bp)return e;let t=await qE.getAllNodeRecords();if(s$.isEmptyOrZeroLength(t))return e;let r=[];for(let s=0,n=t.length;s<n;s++)r.push(Gp(t[s],e.connections));return await Promise.allSettled(r),e}a(i$,"clusterStatus");async function Gp(e,t){let r=e.name,s=new n$(Pc.OPERATIONS_ENUM.CLUSTER_STATUS,Hp,void 0,await qE.getSystemInfo()),n,i,o=Us.CLUSTER_STATUS_STATUSES.OPEN;try{let _=Date.now();n=await r$.request(Us.REQUEST_SUBJECT(r),s),i=Date.now()-_,n.status===Us.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR&&(o=Us.CLUSTER_STATUS_STATUSES.CLOSED,GE.error(`Error getting node status from ${r} `,n))}catch(_){GE.warn(`Error getting node status from ${r}`,_),_.code===Pp.NoResponders?o=Us.CLUSTER_STATUS_STATUSES.NO_RESPONDERS:_.code===Pp.Timeout?o=Us.CLUSTER_STATUS_STATUSES.TIMEOUT:o=Us.CLUSTER_STATUS_STATUSES.CLOSED}let c=new a$(r,o,n?.message?.ports?.clustering,n?.message?.ports?.operations_api,i,n?.message?.uptime,e.subscriptions,n?.message?.system_info);try{let _={name:r,system_info:n?.message?.system_info};e.system_info?.hdb_version!==Pc.PRE_4_0_0_VERSION&&await qE.upsertNodeRecord(_)}catch(_){GE.error("Cluster status encountered an error updating system info for node:",r,_)}t.push(c)}a(Gp,"buildNodeStatus");function a$(e,t,r,s,n,i,o,c){this.node_name=e,this.status=t,this.ports={clustering:r,operations_api:s},this.latency_ms=n,this.uptime=i,this.subscriptions=o,this.system_info=c}a(a$,"NodeStatusObject")});var xp=S((f3,kp)=>{"use strict";var VE=require("joi"),Fp=de(),{route_constraints:Vp}=hu();kp.exports={setRoutesValidator:o$,deleteRoutesValidator:c$};function o$(e){let t=VE.object({server:VE.valid("hub","leaf").required(),routes:Vp.required()});return Fp.validateBySchema(e,t)}a(o$,"setRoutesValidator");function c$(e){let t=VE.object({routes:Vp.required()});return Fp.validateBySchema(e,t)}a(c$,"deleteRoutesValidator")});var xE=S((T3,Qp)=>{"use strict";var ys=Sr(),kE=b(),Bc=T(),$p=xp(),{handleHDBError:Yp,hdb_errors:_$}=D(),{HTTP_STATUS_CODES:Kp}=_$,u$="cluster routes successfully set",l$="cluster routes successfully deleted";Qp.exports={setRoutes:E$,getRoutes:d$,deleteRoutes:h$};function E$(e){let t=$p.setRoutesValidator(e);if(t)throw Yp(t,t.message,Kp.BAD_REQUEST,void 0,void 0,!0);let r=ys.getClusteringRoutes(),s=e.server==="hub"?r.hub_routes:r.leaf_routes,n=e.server==="hub"?r.leaf_routes:r.hub_routes,i=[],o=[];for(let c=0,_=e.routes.length;c<_;c++){let u=e.routes[c];u.port=kE.autoCast(u.port);let l=s.some(d=>d.host===u.host&&d.port===u.port),E=n.some(d=>d.host===u.host&&d.port===u.port);l||E?i.push(u):(s.push(u),o.push(u))}return e.server==="hub"?ys.updateConfigValue(Bc.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,s):ys.updateConfigValue(Bc.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,s),{message:u$,set:o,skipped:i}}a(E$,"setRoutes");function d$(){let e=ys.getClusteringRoutes();return{hub:e.hub_routes,leaf:e.leaf_routes}}a(d$,"getRoutes");function h$(e){let t=$p.deleteRoutesValidator(e);if(t)throw Yp(t,t.message,Kp.BAD_REQUEST,void 0,void 0,!0);let r=ys.getClusteringRoutes(),s=r.hub_routes,n=r.leaf_routes,i=[],o=[],c=!1,_=!1;for(let u=0,l=e.routes.length;u<l;u++){let E=e.routes[u],d=!1;for(let h=0,m=s.length;h<m;h++){let R=s[h];if(E.host===R.host&&E.port===R.port){s.splice(h,1),d=!0,c=!0,i.push(E);break}}if(!d){let h=!0;for(let m=0,R=n.length;m<R;m++){let w=n[m];if(E.host===w.host&&E.port===w.port){n.splice(m,1),_=!0,h=!1,i.push(E);break}}h&&o.push(E)}}return c&&(s=kE.isEmptyOrZeroLength(s)?null:s,ys.updateConfigValue(Bc.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,s)),_&&(n=kE.isEmptyOrZeroLength(n)?null:n,ys.updateConfigValue(Bc.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,n)),{message:l$,deleted:i,skipped:o}}a(h$,"deleteRoutes")});var Jp=S((m3,Wp)=>{"use strict";var Fi=require("alasql"),Ds=require("recursive-iterator"),Wt=I(),S$=b(),Vi=T(),vc=class{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,T$(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(n=>Vi.SEARCH_WILDCARDS.includes(n.columnid));if(r.length===0)return this.ast;let s=this.ast.from[0].databaseid;return this.ast.columns=this.ast.columns.filter(n=>!Vi.SEARCH_WILDCARDS.includes(n.columnid)),r.forEach(n=>{let i=this.table_to_schema_lookup.has(n.tableid)?this.table_to_schema_lookup.get(n.tableid):s,o=this.table_lookup.has(n.tableid)?this.table_lookup.get(n.tableid):this.ast.from[0].tableid;if(t[i]&&t[i].tables[o]&&t[i].tables[o][Vi.PERMS_CRUD_ENUM.READ]){let c;t[i].tables[o].attribute_permissions.length>0?c=f$(t[i].tables[o].attribute_permissions):c=global.hdb_schema[i][o].attributes.map(u=>({attribute_name:u.attribute}));let _=this.affected_attributes.get(i).get(o).filter(u=>!Vi.SEARCH_WILDCARDS.includes(u));c.forEach(({attribute_name:u})=>{let l=new Fi.yy.Column({columnid:u});n.tableid&&(l.tableid=n.tableid),this.ast.columns.push(l),_.includes(u)||_.push(u)}),this.affected_attributes.get(i).set(o,_)}}),this.ast}};a(vc,"sql_statement_bucket");function f$(e){return e.filter(t=>t[Vi.PERMS_CRUD_ENUM.READ])}a(f$,"filterReadRestrictedAttrs");function T$(e,t,r,s,n){m$(e,t,r,s,n)}a(T$,"interpretAST");function ki(e,t,r,s,n){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),s&&!s.has(e.as)&&s.set(e.as,e.databaseid)),n)){let i=e.databaseid,o=e.tableid;e.as&&(o=e.as),n.set(o,i)}}a(ki,"addSchemaTableToMap");function m$(e,t,r,s,n){if(!e){Wt.info("getRecordAttributesAST: invalid SQL syntax tree");return}e instanceof Fi.yy.Insert?p$(e,t,r):e instanceof Fi.yy.Select?R$(e,t,r,s,n):e instanceof Fi.yy.Update?A$(e,t,r):e instanceof Fi.yy.Delete?O$(e,t,r):Wt.error("AST in getRecordAttributesAST() is not a valid SQL type.")}a(m$,"getRecordAttributesAST");function R$(e,t,r,s,n){if(!e){Wt.info("getSelectAttributes: invalid SQL syntax tree");return}if(!e.from||e.from[0]===void 0)return;let i=e.from[0].databaseid;if(S$.isEmptyOrZeroLength(i)){Wt.error("No schema specified");return}e.from.forEach(c=>{ki(c,t,r,s,n)}),e.joins&&e.joins.forEach(c=>{c.as&&(c.table.as=c.as),ki(c.table,t,r,s,n)});let o=new Ds(e.columns);for(let{node:c}of o)if(c&&c.columnid){let _=c.tableid,u=s.has(_)?s.get(_):i;if(_||(_=e.from[0].tableid),!t.get(u).has(_))if(r.has(_))_=r.get(_);else{Wt.info(`table specified as ${_} not found.`);return}t.get(u).get(_).indexOf(c.columnid)<0&&t.get(u).get(_).push(c.columnid)}if(e.where){let c=new Ds(e.where),_=e.from[0].tableid;for(let{node:u}of c)if(u&&u.columnid){let l=u.tableid?u.tableid:_;if(!t.get(i).has(l))if(r.has(l))l=r.get(l);else{Wt.info(`table specified as ${l} not found.`);continue}t.get(i).get(l).indexOf(u.columnid)<0&&t.get(i).get(l).push(u.columnid)}}if(e.joins&&e.joins.forEach(c=>{let _=new Ds(c.on);for(let{node:u}of _)if(u&&u.columnid){let l=u.tableid,E=n.get(l);if(!t.get(E).has(l))if(r.has(l))l=r.get(l);else{Wt.info(`table specified as ${l} not found.`);continue}t.get(E).get(l).indexOf(u.columnid)<0&&t.get(E).get(l).push(u.columnid)}}),e.order){let c=new Ds(e.order);for(let{node:_}of c)if(_&&_.columnid){let u=_.tableid,l=s.has(u)?s.get(u):i;if(u||(u=e.from[0].tableid),!t.get(l).has(u))if(r.has(u))u=r.get(u);else{Wt.info(`table specified as ${u} not found.`);return}t.get(l).get(u).indexOf(_.columnid)<0&&t.get(l).get(u).push(_.columnid)}}}a(R$,"getSelectAttributes");function A$(e,t,r){if(!e){Wt.info("getUpdateAttributes: invalid SQL syntax tree");return}let s=new Ds(e.columns),n=e.table.databaseid;ki(e.table,t,r);for(let{node:i}of s)i&&i.columnid&&$E(e.table.tableid,n,i.columnid,t,r)}a(A$,"getUpdateAttributes");function O$(e,t,r){if(!e){Wt.info("getDeleteAttributes: invalid SQL syntax tree");return}let s=new Ds(e.where),n=e.table.databaseid;ki(e.table,t,r);for(let{node:i}of s)i&&i.columnid&&$E(e.table.tableid,n,i.columnid,t,r)}a(O$,"getDeleteAttributes");function p$(e,t,r){if(!e){Wt.info("getInsertAttributes: invalid SQL syntax tree");return}let s=new Ds(e.columns),n=e.into.databaseid;ki(e.into,t,r);for(let{node:i}of s)i&&i.columnid&&$E(e.into.tableid,n,i.columnid,t,r)}a(p$,"getInsertAttributes");function $E(e,t,r,s,n){if(!s.get(t))return;let i=e;s.get(t).has(i)||(i=n.get(i)),s.get(t).get(i).push(r)}a($E,"pushAttribute");Wp.exports=vc});var zp=S((R3,Xp)=>{var N$=require("os"),Zp=Y();Xp.exports={checkPermission:g$};function g$(){if(N$.userInfo().username!==Zp.get("install_user"))throw new Error(`Error: Must execute as ${Zp.get("install_user")}`)}a(g$,"checkPermission")});var KE=S((A3,sN)=>{var Gc=Ai(),jp=require("chalk"),ir=I(),eN=zp(),tN=require("prompt"),{promisify:I$}=require("util"),Hc=T(),b$=require("fs-extra"),C$=require("path"),w$=b(),L$=LE(),rN=Y();rN.initSync();var U$=require("moment"),y$=I$(tN.get),D$=C$.join(rN.getHdbBasePath(),Hc.LICENSE_KEY_DIR_NAME,Hc.LICENSE_FILE_NAME,Hc.LICENSE_FILE_NAME);sN.exports={getFingerprint:P$,setLicense:M$,parseLicense:YE,register:B$,getRegistrationInfo:H$};async function M$(e){if(e&&e.key&&e.company){try{ir.info(`parsing license key: ${e.key} and `);let t=e.company.toString();await YE(e.key.trim(),t.trim())}catch(t){let r="There was an error parsing the license key.";throw ir.error(r),ir.error(t),new Error(r)}return"Wrote license key file. Registration successful."}throw new Error("Invalid key or company specified for license file.")}a(M$,"setLicense");async function P$(){try{eN.checkPermission()}catch(t){throw ir.error(t),new Error("You do not have permission to generate a fingerprint.")}let e={};try{e=await Gc.generateFingerPrint()}catch(t){let r="Error generating fingerprint.";throw ir.error(r),ir.error(t),new Error(r)}return e}a(P$,"getFingerprint");async function YE(e,t){if(!e||!t)throw new Error("Invalid entries for License Key and Customer Company");console.log("Validating license input...");let r=Gc.validateLicense(e,t);if(console.log("checking for valid license..."),!r.valid_license)throw new Error("Invalid license found.");if(console.log("checking valid license date..."),!r.valid_date)throw new Error("This License has expired.");if(console.log(`checking for valid machine license ${r.valid_machine}`),!r.valid_machine)throw new Error("This license is in use on another machine.");try{ir.info("writing license to disk"),await b$.writeFile(D$,JSON.stringify({license_key:e,company:t}))}catch(s){throw ir.error("Failed to write License"),s}return"Registration successful."}a(YE,"parseLicense");async function B$(){let e=await v$();return YE(e.HDB_LICENSE,e.CUSTOMER_COMPANY)}a(B$,"register");async function v$(){try{eN.checkPermission()}catch(s){return console.error(s.message)}let e=await Gc.generateFingerPrint(),t={properties:{CUSTOMER_COMPANY:{description:jp.magenta("[COMPANY] Please enter your company name"),required:!0},HDB_LICENSE:{description:jp.magenta(`[HDB_LICENSE] Your fingerprint is ${e} Please enter your license key`),required:!0}}};try{tN.start()}catch(s){ir.error(s)}let r;try{r=await y$(t)}catch(s){throw console.error("There was a problem prompting for registration input. Exiting."),s}return r}a(v$,"promptForRegistration");async function H$(){let e={registered:!1,version:null,storage_type:null,ram_allocation:null,license_expiration_date:null},t;try{t=await Gc.getLicense()}catch(r){throw ir.error(`There was an error when searching licenses due to: ${r.message}`),r}if(w$.isEmptyOrZeroLength(t))throw new Error("There were no licenses found.");if(e.registered=t.enterprise,e.version=L$.version(),e.storage_type=Hc.STORAGE_TYPES_ENUM.LMDB,e.ram_allocation=t.ram_allocation,isNaN(t.exp_date))e.license_expiration_date=t.enterprise?t.exp_date:null;else{let r=U$.utc(t.exp_date).format("YYYY-MM-DD");e.license_expiration_date=t.enterprise?r:null}return e}a(H$,"getRegistrationInfo")});var iN=S((O3,nN)=>{"use strict";var G$=_e(),qc=class{constructor(t,r,s,n,i,o,c,_,u,l,E,d,h){this.port=t,this.server_name=r+G$.SERVER_SUFFIX.HUB,this.pid_file=s,this.max_payload=1e7,this.jetstream={enabled:!1},this.tls={cert_file:n,key_file:i,ca_file:o,insecure:c},this.leafnodes={port:_,tls:{cert_file:n,key_file:i,ca_file:o,insecure:c}},this.cluster={name:u,port:l,routes:E,tls:{cert_file:n,key_file:i,ca_file:o,insecure:c}},this.accounts={SYS:{users:d},HDB:{users:h}},this.system_account="SYS"}};a(qc,"HubConfigObject");nN.exports=qc});var cN=S((p3,oN)=>{"use strict";var aN=_e(),Fc=class{constructor(t,r,s,n,i,o,c,_,u,l,E,d){this.port=t,this.server_name=r+aN.SERVER_SUFFIX.LEAF,this.pid_file=s,this.max_payload=1e7,this.jetstream={enabled:!0,store_dir:n,domain:r+aN.SERVER_SUFFIX.LEAF},this.tls={cert_file:u,key_file:l,ca_file:E,insecure:d},this.leafnodes={remotes:[{tls:{ca_file:E,insecure:d},urls:i,account:"SYS"},{tls:{ca_file:E,insecure:d},urls:o,account:"HDB"}]},this.accounts={SYS:{users:c},HDB:{users:_,jetstream:"enabled"}},this.system_account="SYS"}};a(Fc,"LeafConfigObject");oN.exports=Fc});var uN=S((N3,_N)=>{"use strict";var Vc=class{constructor(t,r){this.user=t,this.password=r}};a(Vc,"HdbUserObject");_N.exports=Vc});var EN=S((g3,lN)=>{"use strict";var q$=_e(),kc=class{constructor(t,r){this.user=t+q$.SERVER_SUFFIX.ADMIN,this.password=r}};a(kc,"SysUserObject");lN.exports=kc});var JE=S((I3,SN)=>{"use strict";var Un=require("path"),Kc=require("fs-extra"),F$=iN(),V$=cN(),k$=uN(),x$=EN(),QE=Wr(),Dn=b(),Mt=Sr(),Yc=T(),xc=_e(),{CONFIG_PARAMS:Ce}=Yc,Qc=I(),Wc=Y(),dN=Vr(),WE=ot(),yn="clustering",$$=1e4,hN=5;SN.exports={generateNatsConfig:Y$,removeNatsConfig:K$};async function Y$(e=!1,t=void 0){Wc.initSync();let r=Wc.get(Ce.ROOTPATH),s=Un.join(r,yn,xc.PID_FILES.HUB),n=Un.join(r,yn,xc.PID_FILES.LEAF),i=Un.join(r,yn,"leaf"),o=Un.join(r,yn,xc.NATS_CONFIG_FILES.HUB_SERVER),c=Un.join(r,yn,xc.NATS_CONFIG_FILES.LEAF_SERVER),_=Mt.getConfigFromFile(Ce.CLUSTERING_TLS_CERTIFICATE),u=Mt.getConfigFromFile(Ce.CLUSTERING_TLS_PRIVATEKEY),l=Mt.getConfigFromFile(Ce.CLUSTERING_TLS_CERT_AUTH),E=Mt.getConfigFromFile(Ce.CLUSTERING_TLS_INSECURE),d=Mt.getConfigFromFile(Ce.CLUSTERING_NODENAME),h=Mt.getConfigFromFile(Ce.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT);await WE.checkNATSServerInstalled()||Jc("nats-server dependency is either missing or the wrong version. Run 'npm install' to fix");let m=await QE.listUsers(),R=Mt.getConfigFromFile(Ce.CLUSTERING_USER),w=await QE.getClusterUser();(Dn.isEmpty(w)||w.active!==!0)&&Jc(`invalid cluster user '${R}'`),e||(await $c(Ce.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),await $c(Ce.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT),await $c(Ce.CLUSTERING_HUBSERVER_NETWORK_PORT),await $c(Ce.CLUSTERING_LEAFSERVER_NETWORK_PORT));let L=[],B=[];for(let[la,yr]of m.entries())yr.role.role===Yc.ROLE_TYPES_ENUM.CLUSTER_USER&&yr.active&&(L.push(new x$(yr.username,dN.decrypt(yr.hash))),B.push(new k$(yr.username,dN.decrypt(yr.hash))));let z=[],{hub_routes:V}=Mt.getClusteringRoutes();if(!Dn.isEmptyOrZeroLength(V))for(let la of V)z.push(`tls://${w.sys_name_encoded}:${w.uri_encoded_d_hash}@${la.host}:${la.port}`);let W=new F$(Mt.getConfigFromFile(Ce.CLUSTERING_HUBSERVER_NETWORK_PORT),d,s,_,u,l,E,h,Mt.getConfigFromFile(Ce.CLUSTERING_HUBSERVER_CLUSTER_NAME),Mt.getConfigFromFile(Ce.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),z,L,B);t=Dn.isEmpty(t)?void 0:t.toLowerCase(),(t===void 0||t===Yc.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase())&&(await Kc.writeJson(o,W),Qc.trace(`Hub server config written to ${o}`));let ke=`tls://${w.sys_name_encoded}:${w.uri_encoded_d_hash}@0.0.0.0:${h}`,xe=`tls://${w.uri_encoded_name}:${w.uri_encoded_d_hash}@0.0.0.0:${h}`,ua=new V$(Mt.getConfigFromFile(Ce.CLUSTERING_LEAFSERVER_NETWORK_PORT),d,n,i,[ke],[xe],L,B,_,u,l,E);(t===void 0||t===Yc.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())&&(await Kc.writeJson(c,ua),Qc.trace(`Leaf server config written to ${c}`))}a(Y$,"generateNatsConfig");async function $c(e){let t=Wc.get(e);Dn.isEmpty(t)&&Jc(`port undefined for '${e}'`),await Dn.isPortTaken(t)&&Jc(`'${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.`)}a($c,"isPortAvailable");function Jc(e){let t=`Error generating clustering config: ${e}`;Qc.error(t),console.error(t),process.exit(1)}a(Jc,"generateNatsConfigError");async function K$(e){let{port:t,config_file:r}=WE.getServerConfig(e),{username:s,decrypt_hash:n}=await QE.getClusterUser(),i=0,o=500;for(;i<hN;){try{let u=await WE.createConnection(t,s,n,!1);if(u.protocol.connected===!0){u.close();break}}catch(u){Qc.trace(`removeNatsConfig waiting for ${e}. Caught and swallowed error ${u}`)}if(i++,i>=hN)throw new Error(`removeNatsConfig timed out waiting to connect to ${e}`);await Dn.async_set_timeout(o*i)}let c="0".repeat($$),_=Un.join(Wc.get(Ce.ROOTPATH),yn,r);await Kc.writeFile(_,c),await Kc.remove(_)}a(K$,"removeNatsConfig")});var Xc=S((b3,pN)=>{"use strict";var ne=Y(),fN=Ai(),C=T(),ZE=_e(),Ae=require("path"),{PACKAGE_ROOT:Zc}=T(),Ee="/dev/null",Mn=Ae.join(Zc,"launchServiceScripts"),TN=Ae.join(Zc,"utility/scripts"),Q$=Ae.join(TN,C.HDB_RESTART_SCRIPT),mN=Ae.resolve(Zc,"dependencies",`${process.platform}-${process.arch}`,ZE.NATS_BINARY_NAME),He,Ge;function ar(){(He===void 0||Ge===void 0)&&(ne.initSync(),He=ne.get(C.HDB_SETTINGS_NAMES.LOG_TO_FILE),Ge=ne.get(C.HDB_SETTINGS_NAMES.LOG_PATH_KEY))}a(ar,"initLogConfig");function RN(){ar();let e=Ae.join(Ge,C.PROCESS_LOG_NAMES.IPC),t={name:C.PROCESS_DESCRIPTORS.IPC,exec_mode:"fork",env:{[C.PROCESS_NAME_ENV_PROP]:C.PROCESS_DESCRIPTORS.IPC},merge_logs:!0,out_file:e,error_file:e,instances:1,cwd:C.SERVICE_SERVERS_CWD.IPC};return He||(t.out_file=Ee,t.error_file=Ee),{...t,script:C.SERVICE_SERVERS.IPC}}a(RN,"generateIPCServerConfig");function AN(){ar(),ne.initSync(),He=ne.get(C.HDB_SETTINGS_NAMES.LOG_TO_FILE),Ge=ne.get(C.HDB_SETTINGS_NAMES.LOG_PATH_KEY);let e=Ae.join(Ge,C.PROCESS_LOG_NAMES.HDB),t=fN.licenseSearch(),r=t.ram_allocation?C.MEM_SETTING_KEY+t.ram_allocation:C.MEM_SETTING_KEY+C.RAM_ALLOCATION_ENUM.DEFAULT,s={name:C.PROCESS_DESCRIPTORS.HDB,script:C.LAUNCH_SERVICE_SCRIPTS.HDB,exec_mode:"cluster",env:{[C.PROCESS_NAME_ENV_PROP]:C.PROCESS_DESCRIPTORS.HDB},merge_logs:!0,out_file:e,error_file:e,instances:ne.get(C.CONFIG_PARAMS.HTTP_THREADS),node_args:r,cwd:Mn};return He||(s.out_file=Ee,s.error_file=Ee),s}a(AN,"generateHDBServerConfig");function ON(){ar(),ne.initSync(),He=ne.get(C.HDB_SETTINGS_NAMES.LOG_TO_FILE),Ge=ne.get(C.HDB_SETTINGS_NAMES.LOG_PATH_KEY);let e=Ae.join(Ge,C.PROCESS_LOG_NAMES.CUSTOM_FUNCTIONS),t=fN.licenseSearch(),r=t.ram_allocation?C.MEM_SETTING_KEY+t.ram_allocation:C.MEM_SETTING_KEY+C.RAM_ALLOCATION_ENUM.DEFAULT,s={name:C.PROCESS_DESCRIPTORS.CUSTOM_FUNCTIONS,script:C.LAUNCH_SERVICE_SCRIPTS.CUSTOM_FUNCTIONS,exec_mode:"cluster",env:{[C.PROCESS_NAME_ENV_PROP]:C.PROCESS_DESCRIPTORS.CUSTOM_FUNCTIONS},merge_logs:!0,out_file:e,error_file:e,instances:ne.get(C.CONFIG_PARAMS.HTTP_THREADS),node_args:r,cwd:Mn};return He||(s.out_file=Ee,s.error_file=Ee),s}a(ON,"generateCFServerConfig");function W$(){ar(),ne.initSync(),He=ne.get(C.HDB_SETTINGS_NAMES.LOG_TO_FILE),Ge=ne.get(C.HDB_SETTINGS_NAMES.LOG_PATH_KEY);let e=ne.get(C.CONFIG_PARAMS.ROOTPATH),t=Ae.join(e,"clustering",ZE.NATS_CONFIG_FILES.HUB_SERVER),r=Ae.join(Ge,C.PROCESS_LOG_NAMES.CLUSTERING_HUB),s={name:C.PROCESS_DESCRIPTORS.CLUSTERING_HUB,script:mN,args:`-c ${t}`,exec_mode:"fork",env:{[C.PROCESS_NAME_ENV_PROP]:C.PROCESS_DESCRIPTORS.CLUSTERING_HUB},merge_logs:!0,out_file:r,error_file:r,instances:1};return He||(s.out_file=Ee,s.error_file=Ee),s}a(W$,"generateNatsHubServerConfig");function J$(){ar(),ne.initSync(),He=ne.get(C.HDB_SETTINGS_NAMES.LOG_TO_FILE),Ge=ne.get(C.HDB_SETTINGS_NAMES.LOG_PATH_KEY);let e=ne.get(C.CONFIG_PARAMS.ROOTPATH),t=Ae.join(e,"clustering",ZE.NATS_CONFIG_FILES.LEAF_SERVER),r=Ae.join(Ge,C.PROCESS_LOG_NAMES.CLUSTERING_LEAF),s={name:C.PROCESS_DESCRIPTORS.CLUSTERING_LEAF,script:mN,args:`-c ${t}`,exec_mode:"fork",env:{[C.PROCESS_NAME_ENV_PROP]:C.PROCESS_DESCRIPTORS.CLUSTERING_LEAF},merge_logs:!0,out_file:r,error_file:r,instances:1};return He||(s.out_file=Ee,s.error_file=Ee),s}a(J$,"generateNatsLeafServerConfig");function Z$(){ar(),ne.initSync();let e=Ae.join(Ge,C.PROCESS_LOG_NAMES.CLUSTERING_INGEST_SERVICE),t={name:C.PROCESS_DESCRIPTORS.CLUSTERING_INGEST_SERVICE,script:C.LAUNCH_SERVICE_SCRIPTS.NATS_INGEST_SERVICE,exec_mode:"cluster",env:{[C.PROCESS_NAME_ENV_PROP]:C.PROCESS_DESCRIPTORS.CLUSTERING_INGEST_SERVICE},merge_logs:!0,out_file:e,error_file:e,instances:1,cwd:Mn};return He||(t.out_file=Ee,t.error_file=Ee),t}a(Z$,"generateNatsIngestServiceConfig");function X$(){ar(),ne.initSync();let e=Ae.join(Ge,C.PROCESS_LOG_NAMES.CLUSTERING_REPLY_SERVICE),t={name:C.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE,script:C.LAUNCH_SERVICE_SCRIPTS.NATS_REPLY_SERVICE,exec_mode:"cluster",env:{[C.PROCESS_NAME_ENV_PROP]:C.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE},merge_logs:!0,out_file:e,error_file:e,instances:1,cwd:Mn};return He||(t.out_file=Ee,t.error_file=Ee),t}a(X$,"generateNatsReplyServiceConfig");function z$(){ar(),ne.initSync();let e=Ae.join(Ge,C.PROCESS_LOG_NAMES.CLUSTERING_UPGRADE),t={name:C.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0,script:C.LAUNCH_SERVICE_SCRIPTS.NODES_UPGRADE_4_0_0,exec_mode:"fork",env:{[C.PROCESS_NAME_ENV_PROP]:C.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0},merge_logs:!0,out_file:e,error_file:e,instances:1,cwd:Mn,autorestart:!1};return He||(t.out_file=Ee,t.error_file=Ee),t}a(z$,"generateClusteringUpgradeV4ServiceConfig");function j$(){ar();let e=Ae.join(Ge,C.PROCESS_LOG_NAMES.PM2),t={name:C.PROCESS_DESCRIPTORS.RESTART_HDB,exec_mode:"fork",env:{[C.PROCESS_NAME_ENV_PROP]:C.PROCESS_DESCRIPTORS.RESTART_HDB},merge_logs:!0,out_file:e,error_file:e,instances:1,autorestart:!1,cwd:TN};return He||(t.out_file=Ee,t.error_file=Ee),{...t,script:Q$}}a(j$,"generateRestart");function eY(e){ar();let t=Ae.join(Ge,C.PROCESS_LOG_NAMES.JOBS),r=Ae.join(Zc,"server/jobs"),s={name:`JOB-${e}`,exec_mode:"fork",env:{[C.PROCESS_NAME_ENV_PROP]:`JOB-${e}`},merge_logs:!0,out_file:t,error_file:t,instances:1,cwd:Mn,autorestart:!1};return He||(s.out_file=Ee,s.error_file=Ee),{...s,script:Ae.join(r,"jobProcess.js")}}a(eY,"generateJobConfig");function tY(){return{apps:[RN(),AN(),ON()]}}a(tY,"generateAllServiceConfigs");pN.exports={generateAllServiceConfigs:tY,generateIPCServerConfig:RN,generateHDBServerConfig:AN,generateCFServerConfig:ON,generateRestart:j$,generateNatsHubServerConfig:W$,generateNatsLeafServerConfig:J$,generateNatsIngestServiceConfig:Z$,generateNatsReplyServiceConfig:X$,generateClusteringUpgradeV4ServiceConfig:z$,generateJobConfig:eY}});var $i=S((C3,MN)=>{"use strict";var P=T(),zc=b(),xi=JE(),jc=ot(),rY=_e(),x=require("pm2"),sY=require("fs-extra"),gr=Xc(),lt=Y(),Ir=I(),nY=Xc(),iY=Ls(),aY=require("util"),gN=aY.promisify(require("child_process").exec),IN=require("path");MN.exports={start:Ms,stop:t_,reload:CN,restart:wN,list:zE,describe:r_,connect:or,kill:UN,startAllServices:fY,startService:e_,getUniqueServicesList:jE,restartAllServices:TY,stopAllServices:mY,isServiceRegistered:yN,reloadStopStart:XE,restartHdb:LN,deleteProcess:hY,configureLogRotate:OY,startClustering:DN,isHdbRestartRunning:SY,isClusteringRunning:NY,stopClustering:pY,reloadClustering:gY};var{PACKAGE_ROOT:oY}=T(),cY="2.7.0",bN=IN.join(oY,"node_modules/pm2/bin/pm2"),_Y="Log rotate installed.",uY="Error installing log rotate.",lY="Log rotate updated.",EY="Error updating log rotate.",dY="The number of HarperDB processes running is different from the settings value. To restart and update the number HarperDB processes running you must stop and then start HarperDB";function or(){return new Promise((e,t)=>{x.connect((r,s)=>{r&&t(r),e(s)})})}a(or,"connect");function Ms(e){return new Promise(async(t,r)=>{try{await or()}catch(s){r(s)}x.start(e,(s,n)=>{s&&(x.disconnect(),r(s)),x.disconnect(),t(n)})})}a(Ms,"start");function t_(e){return new Promise(async(t,r)=>{try{await or()}catch(s){r(s)}x.stop(e,(s,n)=>{s&&(x.disconnect(),r(s)),x.delete(e,(i,o)=>{i&&(x.disconnect(),r(s)),x.disconnect(),t(o)})})})}a(t_,"stop");function CN(e){return new Promise(async(t,r)=>{try{await or()}catch(s){r(s)}x.reload(e,(s,n)=>{s&&(x.disconnect(),r(s)),x.disconnect(),t(n)})})}a(CN,"reload");function wN(e){return new Promise(async(t,r)=>{try{await or()}catch(s){r(s)}x.restart(e,(s,n)=>{s&&(x.disconnect(),r(s)),x.disconnect(),t(n)})})}a(wN,"restart");function hY(e){return new Promise(async(t,r)=>{try{await or()}catch(s){r(s)}x.delete(e,(s,n)=>{s&&(x.disconnect(),r(s)),x.disconnect(),t(n)})})}a(hY,"deleteProcess");async function LN(){await Ms(nY.generateRestart())}a(LN,"restartHdb");async function SY(){let e=await zE();for(let t in e)if(e[t].name===P.PROCESS_DESCRIPTORS.RESTART_HDB)return!0;return!1}a(SY,"isHdbRestartRunning");function zE(){return new Promise(async(e,t)=>{try{await or()}catch(r){t(r)}x.list((r,s)=>{r&&(x.disconnect(),t(r)),x.disconnect(),e(s)})})}a(zE,"list");function r_(e){return new Promise(async(t,r)=>{try{await or()}catch(s){r(s)}x.describe(e,(s,n)=>{s&&(x.disconnect(),r(s)),x.disconnect(),t(n)})})}a(r_,"describe");function UN(){return new Promise(async(e,t)=>{try{await or()}catch(r){t(r)}x.killDaemon((r,s)=>{r&&(x.disconnect(),t(r)),x.disconnect(),e(s)})})}a(UN,"kill");async function fY(){try{await DN(),await Ms(gr.generateAllServiceConfigs())}catch(e){throw x.disconnect(),e}}a(fY,"startAllServices");async function e_(e){try{let t;switch(e=e.toLowerCase(),e){case P.PROCESS_DESCRIPTORS.IPC.toLowerCase():t=gr.generateIPCServerConfig();break;case P.PROCESS_DESCRIPTORS.HDB.toLowerCase():t=gr.generateHDBServerConfig();break;case P.PROCESS_DESCRIPTORS.CUSTOM_FUNCTIONS.toLowerCase():t=gr.generateCFServerConfig();break;case P.PROCESS_DESCRIPTORS.CLUSTERING_INGEST_SERVICE.toLowerCase():t=gr.generateNatsIngestServiceConfig();break;case P.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE.toLowerCase():t=gr.generateNatsReplyServiceConfig();break;case P.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase():t=gr.generateNatsHubServerConfig(),await Ms(t),await xi.removeNatsConfig(e);return;case P.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase():t=gr.generateNatsLeafServerConfig(),await Ms(t),await xi.removeNatsConfig(e);return;case P.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0.toLowerCase():t=gr.generateClusteringUpgradeV4ServiceConfig();break;default:throw new Error(`Start service called with unknown service config: ${e}`)}await Ms(t)}catch(t){throw x.disconnect(),t}}a(e_,"startService");async function jE(){try{let e=await zE(),t={};for(let r=0,s=e.length;r<s;r++){let n=e[r];t[n.name]===void 0&&(t[n.name]={name:n.name,exec_mode:n.pm2_env.exec_mode})}return t}catch(e){throw x.disconnect(),e}}a(jE,"getUniqueServicesList");async function TY(e=[]){try{let t=!1,r=await jE();for(let s=0,n=Object.values(r).length;s<n;s++){let i=Object.values(r)[s],o=i.name;e.includes(o)||(i.exec_mode==="cluster_mode"?o===P.PROCESS_DESCRIPTORS.HDB?t=!0:await XE(o):await wN(o))}t&&await XE(P.PROCESS_DESCRIPTORS.HDB)}catch(t){throw x.disconnect(),t}}a(TY,"restartAllServices");async function mY(){try{let e=await jE();for(let t=0,r=Object.values(e).length;t<r;t++){let s=Object.values(e)[t];await t_(s.name)}if(await UN(),lt.get(P.CONFIG_PARAMS.OPERATIONSAPI_FOREGROUND)===!0){let t=(await sY.readFile(IN.join(lt.get(P.HDB_SETTINGS_NAMES.HDB_ROOT_KEY),P.FOREGROUND_PID_FILE))).toString();try{process.kill(t,"SIGTERM")}catch(r){Ir.warn(`Error terminating foreground process: ${r}`)}}}catch(e){throw x.disconnect(),e}}a(mY,"stopAllServices");async function yN(e){return!zc.isEmptyOrZeroLength(await r_(e))}a(yN,"isServiceRegistered");async function XE(e){let t=e===P.PROCESS_DESCRIPTORS.HDB?lt.get(P.HDB_SETTINGS_NAMES.MAX_HDB_PROCESSES):lt.get(P.HDB_SETTINGS_NAMES.MAX_CUSTOM_FUNCTION_PROCESSES),r=await r_(e),s=zc.isEmptyOrZeroLength(r)?0:r.length;t!==s?e===P.PROCESS_DESCRIPTORS.HDB?Ir.error(dY):(await t_(e),await e_(e)):e===P.PROCESS_DESCRIPTORS.HDB?await LN():await CN(e)}a(XE,"reloadStopStart");function RY(){return new Promise(async(e,t)=>{try{await or()}catch(r){t(r)}x.stop(P.PROCESS_DESCRIPTORS.PM2_LOGROTATE,(r,s)=>{r&&(x.disconnect(),t(r)),x.disconnect(),e(s)})})}a(RY,"stopLogrotate");async function AY(){let{stdout:e,stderr:t}=await gN(`${process.platform==="win32"?"node":""} ${bN} install pm2-logrotate@${cY}`);if(Ir.debug(`loadLogRotate stdout: ${e}`),t)throw Ir.error(uY),t;Ir.info(_Y)}a(AY,"installLogRotate");async function NN(){let e={max_size:lt.get(P.HDB_SETTINGS_NAMES.LOG_ROTATE_MAX_SIZE),retain:lt.get(P.HDB_SETTINGS_NAMES.LOG_ROTATE_RETAIN),compress:lt.get(P.HDB_SETTINGS_NAMES.LOG_ROTATE_COMPRESS),dateFormat:lt.get(P.HDB_SETTINGS_NAMES.LOG_ROTATE_DATE_FORMAT),rotateModule:lt.get(P.HDB_SETTINGS_NAMES.LOG_ROTATE_ROTATE_MODULE),workerInterval:lt.get(P.HDB_SETTINGS_NAMES.LOG_ROTATE_WORKER_INTERVAL),rotateInterval:lt.get(P.HDB_SETTINGS_NAMES.LOG_ROTATE_ROTATE_INTERVAL),TZ:lt.get(P.HDB_SETTINGS_NAMES.LOG_ROTATE_TIMEZONE)},t="";for(let n in e)t+=`${process.platform==="win32"?"node":""} ${bN} set pm2-logrotate:${n} ${e[n]}`,n!=="TZ"&&(t+=" && ");let{stdout:r,stderr:s}=await gN(t);if(Ir.debug(`updateLogRotateConfig stdout: ${r}`),s)throw Ir.error(EY),s;Ir.info(lY)}a(NN,"updateLogRotateConfig");async function OY(){lt.initSync();let e=zc.autoCastBoolean(lt.get(P.HDB_SETTINGS_NAMES.LOG_ROTATE)),t=await r_(P.PROCESS_DESCRIPTORS.PM2_LOGROTATE),r,s=!1;if(zc.isEmptyOrZeroLength(t)||(s=!0,r=t[0].pm2_env.status),e&&!s){await AY(),await NN();return}if(e&&s){await Ms(P.PROCESS_DESCRIPTORS.PM2_LOGROTATE),await NN();return}!e&&r===P.PM2_PROCESS_STATUSES.ONLINE&&await RY()}a(OY,"configureLogRotate");async function DN(){for(let t in P.CLUSTERING_PROCESSES){let r=P.CLUSTERING_PROCESSES[t];await e_(r)}await jc.createWorkQueueStream(rY.WORK_QUEUE_CONSUMER_NAMES),await jc.updateNodeNameLocalStreams();let e=await iY.getAllNodeRecords();for(let t=0,r=e.length;t<r;t++)if(e[t].system_info?.hdb_version===P.PRE_4_0_0_VERSION){Ir.info("Starting clustering upgrade 4.0.0 process"),await e_(P.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0);break}}a(DN,"startClustering");async function pY(){for(let e in P.CLUSTERING_PROCESSES){let t=P.CLUSTERING_PROCESSES[e];await t_(t)}}a(pY,"stopClustering");async function NY(){for(let e in P.CLUSTERING_PROCESSES){let t=P.CLUSTERING_PROCESSES[e];if(await yN(t)===!1)return!1}return!0}a(NY,"isClusteringRunning");async function gY(){await xi.generateNatsConfig(!0),await jc.reloadNATSHub(),await jc.reloadNATSLeaf(),await xi.removeNatsConfig(P.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase()),await xi.removeNatsConfig(P.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())}a(gY,"reloadClustering")});var nd=S((w3,GN)=>{"use strict";var y=T(),K=I(),s_=b(),IY=eu(),ed=JE(),sd=ot(),bY=_e(),BN=require("minimist"),{handleHDBError:td,hdb_errors:CY}=D(),Yi=Sr(),{HTTP_STATUS_CODES:rd}=CY,q,PN=`Restarting HarperDB. This may take up to ${y.RESTART_TIMEOUT_MS/1e3} seconds.`,Ps="HarperDB is currently restarting and must complete before another HarperDB restart can be initialized.",wY="Invalid service",LY="'service' is required",UY="Restarting all services",yY="Clustering is not enabled so cannot be restarted";GN.exports={stop:MY,restartProcesses:DY,restartService:vN};async function DY(){K.createLogFile(y.PROCESS_LOG_NAMES.CLI,y.PROCESS_DESCRIPTORS.STOP);try{q===void 0&&(q=$i());let e=IY(Object.keys(y.CONFIG_PARAM_MAP),!0);s_.isEmptyOrZeroLength(Object.keys(e))||Yi.updateConfigValue(void 0,void 0,e,!0,!0);let t=Yi.getConfigFromFile(y.CONFIG_PARAMS.CLUSTERING_ENABLED),r=Yi.getConfigFromFile(y.CONFIG_PARAMS.CUSTOMFUNCTIONS_ENABLED),s=BN(process.argv);if(!s_.isEmpty(s.service)){if(typeof s.service!="string"){let c=`Restart service argument expected a string but received: ${s.service}`;return K.error(c),c}let o=s.service.split(",");for(let c of o){let _=c.toLowerCase();if(_===y.HDB_PROC_DESCRIPTOR.toLowerCase()&&await q.isHdbRestartRunning()===!0){K.notify(Ps),console.error(Ps);continue}if(y.PROCESS_DESCRIPTORS_VALIDATE[_]===void 0){console.error(`Restart received unrecognized service command argument: ${_}`),K.error(`Restart received unrecognized service command argument: ${_}`);continue}let u=y.PROCESS_DESCRIPTORS_VALIDATE[_];if(console.log(`Restarting ${u}`),K.trace(`Restarting ${u}`),u===y.PROCESS_DESCRIPTORS.PM2_LOGROTATE)await q.configureLogRotate();else if(_.toLowerCase().includes("clustering"))await Pn(_);else if(await q.isServiceRegistered(u))u===y.PROCESS_DESCRIPTORS.CUSTOM_FUNCTIONS&&!r?(await q.stop(y.PROCESS_DESCRIPTORS.CUSTOM_FUNCTIONS),K.trace(`Stopping ${y.PROCESS_DESCRIPTORS.CUSTOM_FUNCTIONS}`)):await vN({service:u});else if(u===y.PROCESS_DESCRIPTORS.CUSTOM_FUNCTIONS)if(r)await q.startService(u),K.trace(`Starting ${u}`);else{let l=`${u} is not enabled in harperdb-config.yaml and cannot be restarted.`;K.error(l),console.log(l)}else await q.startService(u);K.notify(`${u} successfully restarted.`)}return}if(await q.isHdbRestartRunning()===!0)return K.notify(Ps),console.error(Ps),Ps;console.log(PN),t&&await HN();let n=await q.isServiceRegistered(y.PROCESS_DESCRIPTORS.CUSTOM_FUNCTIONS);r&&!n&&(await q.startService(y.PROCESS_DESCRIPTORS.CUSTOM_FUNCTIONS),K.trace(`Starting ${y.PROCESS_DESCRIPTORS.CUSTOM_FUNCTIONS}`));let i=[y.PROCESS_DESCRIPTORS.CLUSTERING_HUB,y.PROCESS_DESCRIPTORS.CLUSTERING_LEAF,y.PROCESS_DESCRIPTORS.CLUSTERING_INGEST_SERVICE,y.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE];return!r&&n&&(i.push(y.PROCESS_DESCRIPTORS.CUSTOM_FUNCTIONS),await q.stop(y.PROCESS_DESCRIPTORS.CUSTOM_FUNCTIONS),K.trace(`Stopping ${y.PROCESS_DESCRIPTORS.CUSTOM_FUNCTIONS}`)),await q.configureLogRotate(),K.notify(UY),await q.restartAllServices(i),PN}catch(e){let t=`There was an error restarting HarperDB. ${e}`;return K.error(t),t}}a(DY,"restartProcesses");async function vN(e){if(K.createLogFile(y.PROCESS_LOG_NAMES.CLI,y.PROCESS_DESCRIPTORS.STOP),q===void 0&&(q=$i()),s_.isEmpty(e.service))throw td(new Error,LY,rd.BAD_REQUEST,void 0,void 0,!0);let t=e.service.toLowerCase();if(y.PROCESS_DESCRIPTORS_VALIDATE[t]===void 0)throw td(new Error,wY,rd.BAD_REQUEST,void 0,void 0,!0);let r=Yi.getConfigFromFile(y.CONFIG_PARAMS.CUSTOMFUNCTIONS_ENABLED),s=y.PROCESS_DESCRIPTORS_VALIDATE[t];if(s===y.PROCESS_DESCRIPTORS.HDB){if(await q.isHdbRestartRunning()===!0)return K.notify(Ps),Ps;await q.reloadStopStart(s)}else if(s===y.PROCESS_DESCRIPTORS.PM2_LOGROTATE)await q.configureLogRotate();else if(s.toLowerCase().includes("clustering"))await Pn(s);else if(s===y.PROCESS_DESCRIPTORS.CUSTOM_FUNCTIONS||s===y.SERVICES.CUSTOM_FUNCTIONS){let i=await q.isServiceRegistered(s);if(r)i?(await q.reloadStopStart(s),K.trace(`Reloading ${s}`)):(await q.startService(s),K.trace(`Starting ${s}`));else if(!r&&i)await q.stop(s),K.trace(`Stopping ${s}`);else{let o=`${s} is not enabled in harperdb-config.yaml and cannot be restarted.`;throw K.error(o),td(new Error,o,rd.BAD_REQUEST,void 0,void 0,!0)}}else await q.restart(s);let n=`Restarting ${s}`;return K.notify(n),n}a(vN,"restartService");async function MY(){K.createLogFile(y.PROCESS_LOG_NAMES.CLI,y.PROCESS_DESCRIPTORS.STOP);try{q===void 0&&(q=$i());let e=BN(process.argv);if(s_.isEmpty(e.service))console.log("Stopping HarperDB."),await q.stopAllServices(),K.notify("HarperDB has stopped");else{if(typeof e.service!="string"){let r=`Stop service argument expected a string but received: ${e.service}`;K.error(r),console.log(r)}let t=e.service.split(",");for(let r of t){let s=r.toLowerCase();if(y.PROCESS_DESCRIPTORS_VALIDATE[s]===void 0){K.error(`Stop received unrecognized service command argument: ${s}`);continue}s==="clustering"?await q.stopClustering():await q.stop(y.PROCESS_DESCRIPTORS_VALIDATE[s]);let n=`${y.PROCESS_DESCRIPTORS_VALIDATE[s]} successfully stopped.`;K.notify(n),console.log(n)}}}catch(e){throw console.error(e),e}}a(MY,"stop");async function HN(){await Pn(y.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await Pn(y.PROCESS_DESCRIPTORS.CLUSTERING_LEAF),await Pn(y.PROCESS_DESCRIPTORS.CLUSTERING_INGEST_SERVICE),await Pn(y.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE),await sd.updateNodeNameLocalStreams(),await sd.closeConnection()}a(HN,"restartAllClusteringServices");async function Pn(e){e=y.PROCESS_DESCRIPTORS_VALIDATE[e.toLowerCase()];let t=Yi.getConfigFromFile(y.CONFIG_PARAMS.CLUSTERING_ENABLED),r=e==="clustering",s=e==="clustering config",n=r?void 0:await q.isServiceRegistered(e),i=r||s?await q.isClusteringRunning():void 0;switch(!0){case s:if(!i){K.error(yY);break}await q.reloadClustering();break;case(r&&i&&!t):await q.stopClustering();break;case(r&&!i&&t):await q.startClustering();break;case(r&&i&&t):await HN();break;case(r&&!i&&!t):K.error(`${e} is not enabled in harperdb-config.yaml and cannot be restarted.`);break;case(n&&!t):await q.stop(e),K.trace(`Stopping ${e}`);break;case(!n&&t):e!==y.PROCESS_DESCRIPTORS.CLUSTERING_INGEST_SERVICE&&e!==y.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE&&await ed.generateNatsConfig(!0,e),await q.startService(e),K.trace(`Starting ${e}`),e===y.PROCESS_DESCRIPTORS.CLUSTERING_LEAF&&await sd.createWorkQueueStream(bY.WORK_QUEUE_CONSUMER_NAMES);break;case(!n&&!t):K.error(`${e} is not enabled in harperdb-config.yaml and cannot be restarted.`);break;case(n&&t):e===y.PROCESS_DESCRIPTORS.CLUSTERING_INGEST_SERVICE||e===y.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE?await q.reload(e):(await ed.generateNatsConfig(!0,e),await q.restart(e),await ed.removeNatsConfig(e));break;default:K.error(`Error restarting ${e}`)}}a(Pn,"restartClustering")});var JN=S((U3,WN)=>{"use strict";var L3=require("lodash"),Xe=T(),{handleHDBError:qN,hdb_errors:PY}=D(),{HDB_ERROR_MSGS:BY,HTTP_STATUS_CODES:vY}=PY,id=I();WN.exports={getRolePermissions:GY};var Bs=Object.create(null),HY=a(e=>({key:e,perms:{}}),"perms_template_obj"),xN=a((e=!1)=>({describe:e,tables:{}}),"schema_perms_template"),$N=a((e=!1,t=!1,r=!1,s=!1)=>({[Xe.PERMS_CRUD_ENUM.READ]:e,[Xe.PERMS_CRUD_ENUM.INSERT]:t,[Xe.PERMS_CRUD_ENUM.UPDATE]:r,[Xe.PERMS_CRUD_ENUM.DELETE]:s}),"permissions_template"),ad=a((e=!1,t=!1,r=!1,s=!1,n=!1)=>({attribute_permissions:[],describe:e,...$N(t,r,s,n)}),"table_perms_template"),FN=a((e,t=$N())=>({attribute_name:e,describe:QN(t),[Ki]:t[Ki],[od]:t[od],[cd]:t[cd]}),"attr_perms_template"),VN=a((e,t=!1)=>({attribute_name:e,describe:t,[Ki]:t}),"timestamp_attr_perms_template"),{READ:Ki,INSERT:od,UPDATE:cd}=Xe.PERMS_CRUD_ENUM,YN=Object.values(Xe.PERMS_CRUD_ENUM),KN=[Ki,od,cd];function GY(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[Xe.SYSTEM_SCHEMA_NAME],t=e.role;let s=JSON.stringify([e.__updatedtime__,r]);if(Bs[t]&&Bs[t].key===s)return Bs[t].perms;let n=qY(e,r);return Bs[t]?Bs[t].key=s:Bs[t]=HY(s),Bs[t].perms=n,n}catch(r){if(!e[Xe.TIME_STAMP_NAMES_ENUM.UPDATED_TIME]||e[Xe.TIME_STAMP_NAMES_ENUM.UPDATED_TIME]<Xe.PERMS_UPDATE_RELEASE_TIMESTAMP){let s=`Role permissions for role '${t}' must be updated to align with new structure from the 2.2.0 release.`;throw id.error(s),id.debug(r),qN(new Error,BY.OUTDATED_PERMS_TRANSLATION_ERROR,vY.BAD_REQUEST)}else{let s=`There was an error while translating role permissions for role: ${t}.
|
|
8
|
-
${r.stack}`;throw id.error(s),qN(new Error)}}}a(GY,"getRolePermissions");function qY(e,t){let r=Object.create(null);r.super_user=!1;let s=e.permission;r[Xe.SYSTEM_SCHEMA_NAME]=s[Xe.SYSTEM_SCHEMA_NAME],r.structure_user=s.structure_user;let n=Array.isArray(e.permission.structure_user)||e.permission.structure_user===!0?e.permission.structure_user:[];return Object.keys(t).forEach(i=>{if(n===!0||n.indexOf(i)>-1){r[i]=FY(t[i]);return}r[i]=xN(),s[i]?Object.keys(t[i]).forEach(o=>{if(s[i].tables[o]){let c=s[i].tables[o],_=t[i][o],u=VY(c,_);r[i].describe||YN.forEach(l=>{u[l]&&(r[i].describe=!0)}),r[i].tables[o]=u}else r[i].tables[o]=ad()}):Object.keys(t[i]).forEach(o=>{r[i].tables[o]=ad()})}),r}a(qY,"translateRolePermissions");function FY(e){let t=xN(!0);return Object.keys(e).forEach(r=>{t.tables[r]=ad(!0,!0,!0,!0,!0)}),t}a(FY,"createStructureUserPermissions");function VY(e,t){let{attribute_permissions:r}=e;if(r.length>0){let n=Object.assign({},e);n.attribute_permissions=[];let i=r.reduce((u,l)=>{let{attribute_name:E}=l,d=l;return Xe.TIME_STAMP_NAMES.includes(E)&&(d=VN(E,l[Ki])),u[E]=d,u},{}),o=t[Xe.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_HASH_ATTRIBUTE_KEY],c=!!i[o],_=FN(o);return t.attributes.forEach(({attribute:u})=>{if(i[u]){let l=i[u];l.describe=QN(l),n.attribute_permissions.push(l),c||kY(l,_)}else if(u!==o){let l;Xe.TIME_STAMP_NAMES.includes(u)?l=VN(u):l=FN(u),n.attribute_permissions.push(l)}}),c||n.attribute_permissions.push(_),n.describe=kN(n),n}else return e.describe=kN(e),e}a(VY,"getTableAttrPerms");function kN(e){return YN.filter(t=>e[t]).length>0}a(kN,"getSchemaTableDescribePerm");function QN(e){return KN.filter(t=>e[t]).length>0}a(QN,"getAttributeDescribePerm");function kY(e,t){KN.forEach(r=>{e[r]&&!t[r]&&(t[r]=!0,t.describe=!0)})}a(kY,"checkForHashPerms")});var rg=S((y3,tg)=>{"use strict";var Te=require("joi"),ZN=require("fs-extra"),XN=require("path"),Bn=de(),zN=Y(),jN=T(),eg=I(),{hdb_errors:xY}=D(),{HDB_ERROR_MSGS:Et}=xY,ts=/^[a-zA-Z0-9-_]+$/;tg.exports={getDropCustomFunctionValidator:YY,setCustomFunctionValidator:KY,addCustomFunctionProjectValidator:QY,dropCustomFunctionProjectValidator:WY,packageCustomFunctionProjectValidator:JY,deployCustomFunctionProjectValidator:ZY};function Qi(e,t,r){try{let s=zN.get(jN.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY),n=XN.join(s,t);return ZN.existsSync(n)?e?t:r.message(Et.PROJECT_EXISTS):e?r.message(Et.NO_PROJECT):t}catch(s){return eg.error(s),r.message(Et.VALIDATION_ERR)}}a(Qi,"checkProjectExists");function $Y(e,t,r,s){try{let n=zN.get(jN.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY),i=XN.join(n,e,t,r+".js");return ZN.existsSync(i)?r:s.message(Et.NO_FILE)}catch(n){return eg.error(n),s.message(Et.VALIDATION_ERR)}}a($Y,"checkFileExists");function YY(e){let t=Te.object({project:Te.string().pattern(ts).custom(Qi.bind(null,!0)).required().messages({"string.pattern.base":Et.BAD_PROJECT_NAME}),type:Te.string().valid("helpers","routes").required(),file:Te.string().pattern(ts).custom($Y.bind(null,e.project,e.type)).required().messages({"string.pattern.base":Et.BAD_FILE_NAME})});return Bn.validateBySchema(e,t)}a(YY,"getDropCustomFunctionValidator");function KY(e){let t=Te.object({project:Te.string().pattern(ts).custom(Qi.bind(null,!0)).required().messages({"string.pattern.base":Et.BAD_PROJECT_NAME}),type:Te.string().valid("helpers","routes").required(),file:Te.string().pattern(ts).required().messages({"string.pattern.base":Et.BAD_FILE_NAME}),function_content:Te.string().required()});return Bn.validateBySchema(e,t)}a(KY,"setCustomFunctionValidator");function QY(e){let t=Te.object({project:Te.string().pattern(ts).custom(Qi.bind(null,!1)).required().messages({"string.pattern.base":Et.BAD_PROJECT_NAME})});return Bn.validateBySchema(e,t)}a(QY,"addCustomFunctionProjectValidator");function WY(e){let t=Te.object({project:Te.string().pattern(ts).custom(Qi.bind(null,!0)).required().messages({"string.pattern.base":Et.BAD_PROJECT_NAME})});return Bn.validateBySchema(e,t)}a(WY,"dropCustomFunctionProjectValidator");function JY(e){let t=Te.object({project:Te.string().pattern(ts).custom(Qi.bind(null,!0)).required().messages({"string.pattern.base":Et.BAD_PROJECT_NAME}),skip_node_modules:Te.boolean()});return Bn.validateBySchema(e,t)}a(JY,"packageCustomFunctionProjectValidator");function ZY(e){let t=Te.object({project:Te.string().pattern(ts).required().messages({"string.pattern.base":Et.BAD_PROJECT_NAME}),payload:Te.string().required().messages({"string.pattern.base":Et.BAD_PACKAGE})});return Bn.validateBySchema(e,t)}a(ZY,"deployCustomFunctionProjectValidator")});var ld=S((D3,ig)=>{"use strict";var we=require("fs-extra"),n_=require("fast-glob"),ie=require("path"),sg=require("tar-fs"),ng=require("uuid").v4,Wi=require("normalize-path"),vs=rg(),Le=I(),At=T(),Ot=Y(),{PACKAGE_ROOT:XY}=T(),{handleHDBError:ze,hdb_errors:zY}=D(),{HDB_ERROR_MSGS:rs,HTTP_STATUS_CODES:je}=zY,jY=ie.join(XY,"custom_function_template"),_d=ie.join(Ot.get(At.HDB_SETTINGS_NAMES.HDB_ROOT_KEY),"tmp");function ud(){let e=Ot.get(At.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_ENABLED_KEY);if(!(e==="true"||e===!0||e==="TRUE"))throw ze(new Error,rs.NOT_ENABLED,je.BAD_REQUEST,void 0,void 0,!0)}a(ud,"isCFEnabled");function eK(){Le.trace("getting custom api status");let e={};try{e={is_enabled:Ot.get(At.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_ENABLED_KEY),port:Ot.get(At.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_PORT_KEY),directory:Ot.get(At.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY)}}catch(t){throw ze(new Error,rs.FUNCTION_STATUS,je.INTERNAL_SERVER_ERROR,Le.ERR,t)}return e}a(eK,"customFunctionsStatus");function tK(){Le.trace("getting custom api endpoints");let e={},t=Ot.get(At.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY);try{n_.sync(Wi(`${t}/*`),{onlyDirectories:!0}).forEach(s=>{let n=s.split("/").pop();e[n]={routes:n_.sync(Wi(`${s}/routes/*.js`)).map(i=>i.split("/").pop().split(".js")[0]),helpers:n_.sync(Wi(`${s}/helpers/*.js`)).map(i=>i.split("/").pop().split(".js")[0]),static:we.existsSync(Wi(`${s}/static`))&&n_.sync(Wi(`${s}/static/**/*`)).length}})}catch(r){throw ze(new Error,rs.GET_FUNCTIONS,je.INTERNAL_SERVER_ERROR,Le.ERR,r)}return e}a(tK,"getCustomFunctions");function rK(e){e.project&&(e.project=ie.parse(e.project).name),e.file&&(e.file=ie.parse(e.file).name);let t=vs.getDropCustomFunctionValidator(e);if(t)throw ze(t,t.message,je.BAD_REQUEST);Le.trace("getting custom api endpoint file content");let r=Ot.get(At.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY),{project:s,type:n,file:i}=e,o=ie.join(r,s,n,i+".js");try{return we.readFileSync(o,{encoding:"utf8"})}catch(c){throw ze(new Error,rs.GET_FUNCTION,je.INTERNAL_SERVER_ERROR,Le.ERR,c)}}a(rK,"getCustomFunction");function sK(e){ud(),e.project&&(e.project=ie.parse(e.project).name),e.file&&(e.file=ie.parse(e.file).name);let t=vs.setCustomFunctionValidator(e);if(t)throw ze(t,t.message,je.BAD_REQUEST);Le.trace("setting custom function file content");let r=Ot.get(At.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY),{project:s,type:n,file:i,function_content:o}=e;try{return we.outputFileSync(ie.join(r,s,n,i+".js"),o),`Successfully updated custom function: ${i}.js`}catch(c){throw ze(new Error,rs.SET_FUNCTION,je.INTERNAL_SERVER_ERROR,Le.ERR,c)}}a(sK,"setCustomFunction");function nK(e){e.project&&(e.project=ie.parse(e.project).name),e.file&&(e.file=ie.parse(e.file).name);let t=vs.getDropCustomFunctionValidator(e);if(t)throw ze(t,t.message,je.BAD_REQUEST);Le.trace("dropping custom function file");let r=Ot.get(At.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY),{project:s,type:n,file:i}=e;try{return we.unlinkSync(ie.join(r,s,n,i+".js")),`Successfully deleted custom function: ${i}.js`}catch(o){throw ze(new Error,rs.DROP_FUNCTION,je.INTERNAL_SERVER_ERROR,Le.ERR,o)}}a(nK,"dropCustomFunction");function iK(e){ud(),e.project&&(e.project=ie.parse(e.project).name);let t=vs.addCustomFunctionProjectValidator(e);if(t)throw ze(t,t.message,je.BAD_REQUEST);Le.trace("adding custom function project");let r=Ot.get(At.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY),{project:s}=e;try{let n=ie.join(r,s);return we.mkdirSync(n,{recursive:!0}),we.copySync(jY,n),`Successfully created custom function project: ${s}`}catch(n){throw ze(new Error,rs.ADD_FUNCTION,je.INTERNAL_SERVER_ERROR,Le.ERR,n)}}a(iK,"addCustomFunctionProject");function aK(e){e.project&&(e.project=ie.parse(e.project).name);let t=vs.dropCustomFunctionProjectValidator(e);if(t)throw ze(t,t.message,je.BAD_REQUEST);Le.trace("dropping custom function project");let r=Ot.get(At.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY),{project:s}=e;try{let n=ie.join(r,s);return we.rmSync(n,{recursive:!0}),`Successfully deleted project: ${s}`}catch(n){throw ze(new Error,rs.DROP_FUNCTION_PROJECT,je.INTERNAL_SERVER_ERROR,Le.ERR,n)}}a(aK,"dropCustomFunctionProject");async function oK(e){e.project&&(e.project=ie.parse(e.project).name);let t=vs.packageCustomFunctionProjectValidator(e);if(t)throw ze(t,t.message,je.BAD_REQUEST);Le.trace("packaging custom function project");let r=Ot.get(At.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY),{project:s}=e,n=ie.join(r,s),i=ng();if(!we.existsSync(n)){let l=`Unable to locate custom function project: ${s}`;throw Le.error(l),l}we.ensureDirSync(_d);let c=ie.join(_d,`${i}.tar`),_={};(e.skip_node_modules===!0||e.skip_node_modules==="true")&&(_={ignore:l=>l.includes(ie.join(n,"node_modules"))}),sg.pack(n,_).pipe(we.createWriteStream(c)),await new Promise(l=>setTimeout(l,2e3));let u=we.readFileSync(c,{encoding:"base64"});return we.unlinkSync(c),{project:s,payload:u,file:c}}a(oK,"packageCustomFunctionProject");async function cK(e){ud(),e.project&&(e.project=ie.parse(e.project).name);let t=vs.deployCustomFunctionProjectValidator(e);if(t)throw ze(t,t.message,je.BAD_REQUEST);Le.trace("deploying custom function project");let r=Ot.get(At.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY),{project:s,payload:n,file:i}=e,o=ie.join(r,s);await we.ensureDir(o);let c,_;do c=ie.join(_d,ng()+".tar"),_=await we.pathExists(c);while(_);await we.outputFile(c,n,{encoding:"base64"});let u=we.createReadStream(c);return u.pipe(sg.extract(o)),await new Promise(l=>u.on("end",l)),await we.unlink(c),`Successfully deployed project: ${s}`}a(cK,"deployCustomFunctionProject");ig.exports={customFunctionsStatus:eK,getCustomFunctions:tK,getCustomFunction:rK,setCustomFunction:sK,dropCustomFunction:nK,addCustomFunctionProject:iK,dropCustomFunctionProject:aK,packageCustomFunctionProject:oK,deployCustomFunctionProject:cK}});var Ed=S((M3,og)=>{"use strict";var cr=require("joi"),ag=de();og.exports={readTransactionLogValidator:_K,deleteTransactionLogsBeforeValidator:uK};function _K(e){let t=cr.object({schema:cr.string().required(),table:cr.string().required(),from:cr.date().timestamp(),to:cr.date().timestamp(),limit:cr.number().min(1)});return ag.validateBySchema(e,t)}a(_K,"readTransactionLogValidator");function uK(e){let t=cr.object({schema:cr.string().required(),table:cr.string().required(),timestamp:cr.date().timestamp().required()});return ag.validateBySchema(e,t)}a(uK,"deleteTransactionLogsBeforeValidator")});var a_=S((P3,Eg)=>{"use strict";var dd=T(),i_=ot(),cg=b(),_g=Y(),ug=Vr(),{handleHDBError:vn,hdb_errors:lK}=D(),{HTTP_STATUS_CODES:Hn}=lK,{readTransactionLogValidator:EK,deleteTransactionLogsBeforeValidator:dK}=Ed(),lg="This operation relies on clustering and cannot run with it disable.",hK="Logs successfully deleted from transaction log.",SK="All logs successfully deleted from transaction log.";Eg.exports={readTransactionLog:fK,deleteTransactionLogsBefore:TK};async function fK(e){let t=EK(e);if(t)throw vn(t,t.message,Hn.BAD_REQUEST,void 0,void 0,!0);if(!_g.get(dd.CONFIG_PARAMS.CLUSTERING_ENABLED))throw vn(new Error,lg,Hn.NOT_FOUND,void 0,void 0,!0);let{schema:r,table:s}=e,n=cg.checkSchemaTableExist(r,s);if(n)throw vn(new Error,n,Hn.NOT_FOUND,void 0,void 0,!0);let i=ug.createNatsTableStreamName(r,s),o=await i_.viewStream(i,parseInt(e.from),e.limit),c=[];for(let _=0,u=o.length;_<u;_++){let l=o[_],E=Math.floor(l?.nats_timestamp/1e6);if(e.to&&E>e.to)break;let d={operation:l?.entry?.operation,user:l?.entry?.__origin?.user,timestamp:E,records:l?.entry?.records};l?.entry?.operation===dd.OPERATIONS_ENUM.DELETE&&(d.hash_values=l?.entry?.hash_values),c.push(d)}return c}a(fK,"readTransactionLog");async function TK(e){let t=dK(e);if(t)throw vn(t,t.message,Hn.BAD_REQUEST,void 0,void 0,!0);if(!_g.get(dd.CONFIG_PARAMS.CLUSTERING_ENABLED))throw vn(new Error,lg,Hn.NOT_FOUND,void 0,void 0,!0);let{schema:r,table:s,timestamp:n}=e,i=cg.checkSchemaTableExist(r,s);if(i)throw vn(new Error,i,Hn.NOT_FOUND,void 0,void 0,!0);let o=ug.createNatsTableStreamName(r,s),{jsm:c}=await i_.getNATSReferences(),_=await i_.getStreamInfo(o),u=new Date(_.state.first_ts).getTime();if(n<=u)return`No transactions exist before: ${n}`;let l=hK,E,d=new Date(_.state.last_ts).getTime();return n>d?(E=_.state.last_seq+1,l=SK):E=(await i_.viewStream(o,parseInt(n),1))[0].nats_sequence,await c.streams.purge(o,{seq:E}),l}a(TK,"deleteTransactionLogsBefore")});var Sd=S((B3,pg)=>{"use strict";var o_=require("joi"),c_=require("path"),dg=require("fs-extra"),{exec:mK}=require("child_process"),RK=require("util"),hg=RK.promisify(mK),AK=T(),{handleHDBError:Gn,hdb_errors:OK}=D(),{HTTP_STATUS_CODES:qn}=OK,Sg=Y(),pK=de(),__=I();Sg.initSync();var hd=Sg.get(AK.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY),fg="npm install --omit=dev --json",NK=`${fg} --dry-run`;pg.exports={installModules:gK,auditModules:IK};async function Tg(e,t=void 0){let{stdout:r,stderr:s}=await hg(e,{cwd:t});if(s)throw new Error(s.replace(`
|
|
7
|
+
`,"")}a(SA,"runCommand");async function EF(){try{await JG.access(ql)}catch{return!1}let e=await SA(`${ql} --version`,void 0),t=e.substring(e.lastIndexOf("v")+1,e.length);return XG.eq(t,uF)}a(EF,"checkNATSServerInstalled");async function Vl(e,t,r,s=!0,n="127.0.0.1"){return sF({name:n,port:e,user:t,pass:r,maxReconnectAttempts:-1,waitOnFirstConnect:s,tls:{keyFile:Tr.get(ie.CONFIG_PARAMS.CLUSTERING_TLS_PRIVATEKEY),certFile:Tr.get(ie.CONFIG_PARAMS.CLUSTERING_TLS_CERTIFICATE),caFile:Tr.get(ie.CONFIG_PARAMS.CLUSTERING_TLS_CERT_AUTH),rejectUnauthorized:!1}})}a(Vl,"createConnection");async function dF(){Yt&&(await Yt.close(),Yt=void 0)}a(dF,"closeConnection");async function Qo(){if(!Yt){let e=await uA.getClusterUser();if(Rs(e))throw new Error("Unable to get nats connection. Cluster user is undefined.");let t=Tr.get(ie.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT);Yt=await Vl(t,e.username,e.decrypt_hash)}return Yt}a(Qo,"getConnection");async function hn(){if(pi)return pi;Rs(Yt)&&await Qo();let{domain:e}=Ii(ie.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);if(Rs(e))throw new Error("Error getting JetStream domain. Unable to get JetStream manager.");return pi=await Yt.jetstreamManager({domain:e}),pi}a(hn,"getJetStreamManager");async function fA(){if(Ni)return Ni;Rs(Yt)&&await Qo();let{domain:e}=Ii(ie.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);if(Rs(e))throw new Error("Error getting JetStream domain. Unable to get JetStream manager.");return Ni=Yt.jetstream({domain:e}),Ni}a(fA,"getJetStream");async function Ut(){let e=Yt||await Qo(),t=pi||await hn(),r=Ni||await fA();return{connection:e,jsm:t,js:r}}a(Ut,"getNATSReferences");async function hF(){let e=Tr.get(ie.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),{sys_name:t,decrypt_hash:r}=await uA.getClusterUser(),s=await Vl(e,t,r),n=Fl(),i=s.subscribe(n),o=[],c=(async()=>{for await(let _ of i)o.push(hA.decode(_.data))})();return await s.publish("$SYS.REQ.SERVER.PING.VARZ",void 0,{reply:n}),await s.flush(),await Gl.async_set_timeout(50),await i.drain(),await s.close(),await c,o}a(hF,"getServerList");async function kl(e,t){let{jsm:r}=await Ut();await r.streams.add({name:e,storage:lA.File,retention:EA.Limits,subjects:t})}a(kl,"createLocalStream");async function TA(){let{jsm:e}=await Ut(),t=await e.streams.list().next(),r=[];return t.forEach(s=>{r.push(s)}),r}a(TA,"listStreams");async function SF(e){let{jsm:t}=await Ut();await t.streams.delete(e)}a(SF,"deleteLocalStream");async function fF(e){let{connection:t}=await Ut(),r=[],s=Fl(),n=t.subscribe(s),i=(async()=>{for await(let o of n)r.push(hA.decode(o.data))})();return await t.publish(`$JS.${e}.API.STREAM.LIST`,void 0,{reply:s}),await t.flush(),await n.drain(),await i,r}a(fF,"listRemoteStreams");async function TF(e,t=void 0,r=void 0){let{jsm:s,connection:n}=await Ut(),i=zG(),o=[],c={ack_policy:dA.None,durable_name:i,deliver_subject:i,deliver_policy:Hl.All};t&&(c.deliver_policy=Hl.StartTime,c.opt_start_time=new Date(t).toISOString());try{await s.consumers.add(e,c);let _={timeout:2e3};r&&(_.max=r);let u=await n.subscribe(i,_);for await(let l of u){let E=aF(l),d=_A(E.data),h={nats_timestamp:E.info.timestampNanos,nats_sequence:E.info.streamSequence,entry:d,originators:[]},m=[];if(E.headers){let R=E.headers.get("originators");R&&(m=R.split(","),h.originators=m)}o.push(h),u.getPending()===1&&E.info.pending===0&&u.stop()}return await s.consumers.delete(e,i),o}catch(_){if(await s.consumers.delete(e,i),_.code==="TIMEOUT")return o;throw _}}a(TF,"viewStream");async function mF(e,t,r=[],s=[]){mr.trace(`publishToStream called with subject: ${e}, stream: ${t}, entries:`,r,"originators:",s);let{connection:n,js:i}=await Ut(),o=await Jo(),c=`${e}.${o}`,_=iF();s.push(o),_.append("originators",s.join());for(let u=0,l=r.length;u<l;u++)try{mr.trace(`publishToStream publishing to subject: ${c}, data:`,r[u]),await i.publish(c,vl(r[u]),{headers:_})}catch(E){if(E.code&&E.code.toString()==="503")mr.trace(`publishToStream creating stream: ${t}`),await kl(t,[c]),await i.publish(c,vl(r[u]),{headers:_});else throw E}}a(mF,"publishToStream");function Ii(e){e=e.toLowerCase();let t=gi.join(Tr.get(ie.CONFIG_PARAMS.ROOTPATH),_F);if(e===ie.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase())return Rs(Bl)&&(Bl={port:Ai.getConfigFromFile(ie.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),server_name:Ai.getConfigFromFile(ie.CONFIG_PARAMS.CLUSTERING_NODENAME)+ee.SERVER_SUFFIX.HUB,config_file:ee.NATS_CONFIG_FILES.HUB_SERVER,pid_file_path:gi.join(t,ee.PID_FILES.HUB),hdb_nats_path:t}),Bl;if(e===ie.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())return Rs(Pl)&&(Pl={port:Ai.getConfigFromFile(ie.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),server_name:Ai.getConfigFromFile(ie.CONFIG_PARAMS.CLUSTERING_NODENAME)+ee.SERVER_SUFFIX.LEAF,config_file:ee.NATS_CONFIG_FILES.LEAF_SERVER,domain:Ai.getConfigFromFile(ie.CONFIG_PARAMS.CLUSTERING_NODENAME)+ee.SERVER_SUFFIX.LEAF,pid_file_path:gi.join(t,ee.PID_FILES.LEAF),hdb_nats_path:t}),Pl;mr.error(`Unable to get Nats server config. Unrecognized process: ${e}`)}a(Ii,"getServerConfig");async function RF(e){let{jsm:t}=await Ut(),r=await Jo();try{await t.streams.add({name:e.stream_name,storage:lA.File,retention:EA.Workqueue,subjects:[`${ee.SUBJECT_PREFIXES.MSGID}.${r}`,`${ee.SUBJECT_PREFIXES.TXN}.${e.stream_name}.${r}`]})}catch(s){if(s.code!=="400")throw s}try{await t.consumers.info(e.stream_name,e.durable_name)}catch(s){if(s.code.toString()==="404")await t.consumers.add(e.stream_name,{ack_policy:dA.Explicit,deliver_subject:`${e.deliver_subject}.${r}`,durable_name:e.durable_name,deliver_policy:Hl.All,max_ack_pending:1e4,deliver_group:e.deliver_group,filter_subject:`${ee.SUBJECT_PREFIXES.TXN}.>`});else throw s}}a(RF,"createWorkQueueStream");async function mA(e,t,r){let{jsm:s}=await Ut(),n=await s.streams.info(t),i=RA(s.prefix),o=r.start_time?r.start_time:new Date(Date.now()).toISOString(),{schema:c,table:_}=r,u=Wo.createNatsTableStreamName(c,_),l=i===e,E,d,h=!1;if(!Array.isArray(n.config.sources)||n.config.sources.length===0)n.config.sources=[];else for(let R=0,C=n.config.sources.length;R<C;R++)if(E=n.config.sources[R],d=R,l&&E.name===u||!l&&E.name===u&&E.external&&E.external.api===`$JS.${e}.API`){h=!0;break}if(h===!0){if(E.opt_start_time===o)return;await OA(c,_,E,t),n.config.sources.splice(d,1),await s.streams.update(t,n.config)}let m={name:u,opt_start_time:o,filter_subject:`${ee.SUBJECT_PREFIXES.TXN}.>`};l||(m.external={api:`$JS.${e}.API`,deliver:""}),n.config.sources.push(m),await s.streams.update(t,n.config)}a(mA,"addSourceToWorkStream");function RA(e){return e.split(".")[1]}a(RA,"extractServerName");async function AA(e,t,r){let{schema:s,table:n}=r,i=Wo.createNatsTableStreamName(s,n),{jsm:o}=await Ut(),c=await o.streams.info(t);if(!Array.isArray(c.config.sources)||c.config.sources.length===0)return;let _=c.config.sources.length,u;for(;_--;)if(u=c.config.sources[_],u.name===i&&u.external.api===`$JS.${e}.API`){c.config.sources.splice(_,1);break}await o.streams.update(t,c.config),await OA(s,n,u,t)}a(AA,"removeSourceFromWorkStream");async function OA(e,t,r,s){let n=await hn(),i;try{i=gA(e,t,r.external.api.split(".")[1]),await n.streams.purge(s,{filter:i})}catch{mr.error("Error purging source subject",i,"from work stream",s)}}a(OA,"purgeSourceFromWorkStream");async function AF(e,t,r=2e3,s=Fl()){if(!Gl.isObject(t))throw new Error("data param must be an object");let n=vl(t),{connection:i}=await Ut(),o={timeout:r};s&&(o.reply=s,o.noMux=!0);let c=await i.request(e,n,o);return _A(c.data)}a(AF,"request");function $l(e){return new Promise(async(t,r)=>{let s=eF(ql,["--signal",`reload=${e}`],{cwd:__dirname}),n,i;s.on("error",o=>{r(o)}),s.stdout.on("data",o=>{i+=o.toString()}),s.stderr.on("data",o=>{n+=o.toString()}),s.stderr.on("close",o=>{n&&r(n),t(i)})})}a($l,"reloadNATS");async function OF(){let{pid_file_path:e}=Ii(ie.PROCESS_DESCRIPTORS.CLUSTERING_HUB);await $l(e)}a(OF,"reloadNATSHub");async function pF(){let{pid_file_path:e}=Ii(ie.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);await $l(e)}a(pF,"reloadNATSLeaf");function NF(e,t,r){let s;switch(e.code){case aA.NoResponders:s=`Unable to ${t}, node '${r}' is not listening.`;break;case aA.Timeout:s=`Unable to ${t}, node '${r}' is listening but did not respond.`;break;default:s=e.message;break}return s}a(NF,"requestErrorHandler");async function gF(e,t){let r=t+ee.SERVER_SUFFIX.LEAF;await tF.writeTransaction(ie.SYSTEM_SCHEMA_NAME,ie.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,async()=>{e.subscribe===!0?await mA(r,ee.WORK_QUEUE_CONSUMER_NAMES.stream_name,e):await AA(r,ee.WORK_QUEUE_CONSUMER_NAMES.stream_name,e)})}a(gF,"updateWorkStream");async function pA(e,t){let r=Wo.createNatsTableStreamName(e,t),s=await Jo(),n=gA(e,t,s);await kl(r,[n])}a(pA,"createLocalTableStream");async function IF(e){for(let t=0,r=e.length;t<r;t++){let s=e[t].schema,n=e[t].table;await pA(s,n)}}a(IF,"createTableStreams");async function NA(e,t){if(Tr.get(ie.CONFIG_PARAMS.CLUSTERING_ENABLED))try{let r=Wo.createNatsTableStreamName(e,t),{jsm:s}=await Ut();await s.streams.purge(r)}catch(r){if(r.message==="stream not found")mr.warn(r);else throw r}}a(NA,"purgeTableStream");async function bF(e,t){if(Tr.get(ie.CONFIG_PARAMS.CLUSTERING_ENABLED))for(let r=0,s=t.length;r<s;r++)await NA(e,t[r])}a(bF,"purgeSchemaTableStreams");async function wF(e){return(await hn()).streams.info(e)}a(wF,"getStreamInfo");function gA(e,t,r){return`${ee.SUBJECT_PREFIXES.TXN}.${e}.${t}.${r}`}a(gA,"createSubjectName");async function Jo(){if(Oi)return Oi;if(Oi=(await hn())?.nc?.info?.server_name,Oi===void 0)throw new Error("Unable to get jetstream manager server name");return Oi}a(Jo,"getJsmServerName");async function CF(){let e=await hn(),t=await Jo(),r=await TA();for(let s of r){let n=s.config,i=n.subjects[0];if(!i)continue;let o=i.split(".");if(o[o.length-1]!==t){if(n.name===ee.SCHEMA_QUEUE_CONSUMER_NAMES.stream_name){let _=`${ee.SCHEMA_QUEUE_CONSUMER_NAMES.deliver_subject}.${t}`;mr.trace(`Updating stream subject name from: ${i} to: ${_}`),n.subjects[0]=_}else if(n.name===ee.WORK_QUEUE_CONSUMER_NAMES.stream_name){let _=`${ee.WORK_QUEUE_CONSUMER_NAMES.stream_name}.${t}`;mr.trace(`Updating stream subject name from: ${i} to: ${_}`),n.subjects[0]=_,await e.consumers.update(ee.WORK_QUEUE_CONSUMER_NAMES.stream_name,ee.WORK_QUEUE_CONSUMER_NAMES.durable_name,{deliver_subject:`${ee.WORK_QUEUE_CONSUMER_NAMES.deliver_subject}.${t}`})}else{let _=i.split(".");_[_.length-1]=t;let u=_.join(".");mr.trace(`Updating stream subject name from: ${i} to: ${u}`),n.subjects[0]=u}await e.streams.update(n.name,n)}}}a(CF,"updateNodeNameLocalStreams")});var xl=S((oZ,bA)=>{"use strict";var Xo=class{constructor(t,r,s){this.timestamp=t,this.user=r,this.node_name=s}};a(Xo,"ClusteringOriginObject");bA.exports=Xo});var As=S((cZ,LA)=>{"use strict";var wA=b(),wi=Y(),ue=T(),Yl=_e(),Sn=at(),Se=I(),CA=xl(),LF=Hr();wi.initSync();var fn=Yl.SCHEMA_QUEUE_CONSUMER_NAMES.stream_name,bi=Yl.SCHEMA_QUEUE_CONSUMER_NAMES.deliver_subject;LA.exports={sendAttributeTransaction:zo,postOperationHandler:yF};async function zo(e,t,r=[]){if(!!wi.get(ue.CONFIG_PARAMS.CLUSTERING_ENABLED)&&!wA.isEmptyOrZeroLength(e.new_attributes)&&t.schema!==ue.SYSTEM_SCHEMA_NAME){let s=t.hdb_user?.username,n=wi.get(ue.CONFIG_PARAMS.CLUSTERING_NODENAME);for(let i of e.new_attributes){let o={operation:ue.OPERATIONS_ENUM.CREATE_ATTRIBUTE,schema:t.schema,table:t.table,attribute:i,__origin:new CA(e.txn_time,s,n)};Se.trace(`sendAttributeTransaction publishing ${fn}`,o),await Sn.publishToStream(bi,fn,[o],r)}}}a(zo,"sendAttributeTransaction");async function Zo(e,t,r,s=[]){if(e.schema===ue.SYSTEM_SCHEMA_NAME)return;let n=UF(e,t,r);n&&(Se.trace(`sendOperationTransaction publishing to schema ${e.schema} table ${e.table} following transaction:`,n),await Sn.publishToStream(`${Yl.SUBJECT_PREFIXES.TXN}.${e.schema}.${e.table}`,LF.createNatsTableStreamName(e.schema,e.table),[n],s))}a(Zo,"sendOperationTransaction");function UF(e,t,r){if(wA.isEmptyOrZeroLength(t))return null;let s={operation:e.operation,schema:e.schema,table:e.table,__origin:r};return e.operation===ue.OPERATIONS_ENUM.DELETE?s.hash_values=t:s.records=e.records,s}a(UF,"convertCRUDOperationToTransaction");async function yF(e,t,r=[]){if(!wi.get(ue.CONFIG_PARAMS.CLUSTERING_ENABLED))return;Se.trace(`postOperationHandler called for operation ${e.operation} on schema.table: ${e.schema}.${e.table}`);let s=e.hdb_user?.username,n=wi.get(ue.CONFIG_PARAMS.CLUSTERING_NODENAME),i=new CA(t.txn_time,s,n);switch(e.operation){case ue.OPERATIONS_ENUM.INSERT:try{await Zo(e,t.inserted_hashes,i,r),await zo(t,e,r)}catch(o){Se.error("There was an error calling clustering postOperationHandler for insert."),Se.error(o)}break;case ue.OPERATIONS_ENUM.DELETE:try{await Zo(e,t.deleted_hashes,i,r)}catch(o){Se.error("There was an error calling clustering postOperationHandler for delete."),Se.error(o)}break;case ue.OPERATIONS_ENUM.UPDATE:try{await Zo(e,t.update_hashes,i,r),await zo(t,e,r)}catch(o){Se.error("There was an error calling clustering postOperationHandler for update."),Se.error(o)}break;case ue.OPERATIONS_ENUM.UPSERT:try{await Zo(e,t.upserted_hashes,i,r),await zo(t,e,r)}catch(o){Se.error("There was an error calling clustering postOperationHandler for upsert."),Se.error(o)}break;case ue.OPERATIONS_ENUM.CREATE_SCHEMA:try{let o={operation:ue.OPERATIONS_ENUM.CREATE_SCHEMA,schema:e.schema,__origin:i};await Sn.publishToStream(bi,fn,[o],r)}catch(o){Se.error("There was an error calling clustering postOperationHandler for create_schema."),Se.error(o)}break;case ue.OPERATIONS_ENUM.CREATE_TABLE:try{let o={operation:ue.OPERATIONS_ENUM.CREATE_TABLE,schema:e.schema,table:e.table,hash_attribute:e.hash_attribute,__origin:i};await Sn.publishToStream(bi,fn,[o],r)}catch(o){Se.error("There was an error calling clustering postOperationHandler for create_table."),Se.error(o)}break;case ue.OPERATIONS_ENUM.CREATE_ATTRIBUTE:try{let o={operation:ue.OPERATIONS_ENUM.CREATE_ATTRIBUTE,schema:e.schema,table:e.table,attribute:e.attribute,__origin:i};await Sn.publishToStream(bi,fn,[o],r)}catch(o){Se.error("There was an error calling clustering postOperationHandler for create_attribute."),Se.error(o)}break;case ue.OPERATIONS_ENUM.CSV_DATA_LOAD:try{let o={operation:ue.OPERATIONS_ENUM.CSV_DATA_LOAD,schema:e.schema,table:e.table,attribute:e.attribute};await Sn.publishToStream(bi,fn,[o],r)}catch(o){Se.error("There was an error calling clustering postOperationHandler for csv_data_load."),Se.error(o)}break;default:break}return t}a(yF,"postOperationHandler")});var PA=S((_Z,MA)=>{"use strict";var DF=Tt(),MF=Gr(),UA=I(),yA=Lt(),PF=Ko(),BF=require("clone"),Wl=require("alasql"),vF=wo(),DA=require("util"),HF=DA.promisify(MF.getTableSchema),qF=DA.promisify(DF.search),GF=T(),Kl=b(),FF=As();vF(Wl);MA.exports={update:kF};var VF="There was a problem performing this update. Please check the logs and try again.";async function kF({statement:e,hdb_user:t}){let r=await HF(e.table.databaseid,e.table.tableid),s=$F(e.columns);Kl.backtickASTSchemaItems(e);let{table:n,where:i}=e,o=BF(n),c=Kl.isEmpty(i)?"":` WHERE ${i.toString()}`,_=`SELECT ${r.hash_attribute} FROM ${n.toString()} ${c}`,u=Wl.parse(_).statements[0],l=await PF.writeTransaction(r.schema,r.name,async()=>{let E=await qF(u),d=xF(s,E);return YF(o,d,t)});return await yA.flush({schema:r.schema,table:r.name}),l}a(kF,"update");function $F(e){try{let t={};return e.forEach(r=>{"value"in r.expression?t[r.column.columnid]=r.expression.value:t[r.column.columnid]=Wl.compile(`SELECT ${r.expression.toString()} AS [${GF.FUNC_VAL}] FROM ?`)}),t}catch(t){throw UA.error(t),new Error(VF)}}a($F,"createUpdateRecord");function xF(e,t){return Kl.isEmptyOrZeroLength(t)?[]:t.map(r=>Object.assign(r,e))}a(xF,"buildUpdateRecords");async function YF(e,t,r){let s={operation:"update",schema:e.databaseid_orig,table:e.tableid_orig,records:t,hdb_user:r};try{let n=await yA.update(s);await FF.postOperationHandler(s,n);try{delete n.new_attributes,delete n.txn_time}catch(i){UA.error(`Error delete new_attributes from update response: ${i}`)}return n}catch(n){throw n}}a(YF,"updateRecords")});var vA=S((uZ,BA)=>{var KF=require("alasql"),WF=Tt(),QF=I(),JF=fr(),Jl=require("util"),Ql=b(),XF=T(),ZF=Gr(),zF=Ko(),jF=As(),e0=Lt(),t0="record",r0="successfully deleted",s0=Jl.callbackify(o0),n0=Jl.promisify(WF.search),i0=Jl.promisify(ZF.getTableSchema);BA.exports={convertDelete:s0};function a0(e){return`${e.deleted_hashes.length} ${t0}${e.deleted_hashes.length===1?"":"s"} ${r0}`}a(a0,"generateReturnMessage");async function o0({statement:e,hdb_user:t}){let r=await i0(e.table.databaseid,e.table.tableid);Ql.backtickASTSchemaItems(e);let{table:s,where:n}=e,i=Ql.isEmpty(n)?"":` WHERE ${n.toString()}`,o=`SELECT ${r.hash_attribute} FROM ${s.toString()} ${i}`,c=KF.parse(o).statements[0],_={operation:XF.OPERATIONS_ENUM.DELETE,schema:s.databaseid_orig,table:s.tableid_orig,hdb_user:t};try{let u=await zF.writeTransaction(r.schema,r.name,async()=>(_.records=await n0(c),JF.deleteRecords(_)));return await e0.flush({schema:r.schema,table:r.name}),u.deleted_hashes.length>0&&await jF.postOperationHandler(_,u),Ql.isEmptyOrZeroLength(u.message)&&(u.message=a0(u)),delete u.txn_time,u}catch(u){throw QF.error(u),u.hdb_code?u.message:u}}a(o0,"convertDelete")});var GA=S((lZ,qA)=>{"use strict";var Zl=ds(),{hdb_errors:Xl}=D();qA.exports={checkSchemaExists:HA,checkSchemaTableExists:c0,schema_describe:Zl};async function HA(e){if(!global.hdb_schema[e])try{let t=await Zl.describeSchema({schema:e});global.hdb_schema[e]=t}catch{return Xl.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}}a(HA,"checkSchemaExists");async function c0(e,t){let r=await HA(e);if(r)return r;if(!global.hdb_schema[e][t])try{let s=await Zl.describeTable({schema:e,table:t});if(!s||Object.keys(s).length===0)return Xl.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t);global.hdb_schema[e][t]=s}catch{return Xl.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}}a(c0,"checkSchemaTableExists")});var jo=S((dZ,xA)=>{"use strict";var Tn=xa(),Os=GA(),FA=I(),_0=require("uuid").v4,EZ=require("clone"),Rn=Xs(),ps=T(),u0=require("util"),Ns=fr(),{handleHDBError:Pe,hdb_errors:l0}=D(),{HDB_ERROR_MSGS:mn,HTTP_STATUS_CODES:Be}=l0,{SchemaEventMsg:An}=Pr(),VA=at();xA.exports={createSchema:E0,createSchemaStructure:kA,createTable:d0,createTableStructure:$A,createAttribute:m0,dropSchema:h0,dropTable:S0,dropAttribute:f0};async function E0(e){try{let t=await kA(e);return Rn.signalSchemaChange(new An(process.pid,e.operation,e.schema)),t}catch(t){throw t}}a(E0,"createSchema");async function kA(e){let t=Tn.schema_object(e);if(t)throw Pe(t,t.message,Be.BAD_REQUEST,void 0,void 0,!0);if(!await Os.checkSchemaExists(e.schema))throw Pe(new Error,mn.SCHEMA_EXISTS_ERR(e.schema),Be.BAD_REQUEST,ps.LOG_LEVELS.ERROR,mn.SCHEMA_EXISTS_ERR(e.schema),!0);try{return await Ns.createSchema(e),`schema '${e.schema}' successfully created`}catch(r){throw r}}a(kA,"createSchemaStructure");async function d0(e){try{let t=await $A(e);return Rn.signalSchemaChange(new An(process.pid,e.operation,e.schema,e.table)),t}catch(t){throw t}}a(d0,"createTable");async function $A(e){let t=Tn.create_table_object(e);if(t)throw Pe(t,t.message,Be.BAD_REQUEST,void 0,void 0,!0);Tn.validateTableResidence(e.residence);let r=await Os.checkSchemaExists(e.schema);if(r)throw Pe(new Error,r,Be.NOT_FOUND,ps.LOG_LEVELS.ERROR,r,!0);if(!await Os.checkSchemaTableExists(e.schema,e.table))throw Pe(new Error,mn.TABLE_EXISTS_ERR(e.schema,e.table),Be.BAD_REQUEST,ps.LOG_LEVELS.ERROR,mn.TABLE_EXISTS_ERR(e.schema,e.table),!0);let n={name:e.table,schema:e.schema,id:_0(),hash_attribute:e.hash_attribute};try{if(e.residence)if(global.clustering_on)n.residence=e.residence,await Ns.createTable(n,e);else throw Pe(new Error,"Clustering does not appear to be enabled. Cannot insert table with property 'residence'.",Be.BAD_REQUEST);else await Ns.createTable(n,e);return`table '${e.schema}.${e.table}' successfully created.`}catch(i){throw i}}a($A,"createTableStructure");async function h0(e){let t=Tn.schema_object(e);if(t)throw Pe(t,t.message,Be.BAD_REQUEST,void 0,void 0,!0);let r=await Os.checkSchemaExists(e.schema);if(r)throw Pe(new Error,r,Be.NOT_FOUND,ps.LOG_LEVELS.ERROR,r,!0);let s=await Os.schema_describe.describeSchema({schema:e.schema});global.hdb_schema[e.schema]=s;let n=Object.keys(global.hdb_schema[e.schema]);return await Ns.dropSchema(e),Rn.signalSchemaChange(new An(process.pid,e.operation,e.schema)),delete global.hdb_schema[e.schema],await VA.purgeSchemaTableStreams(e.schema,n),`successfully deleted schema '${e.schema}'`}a(h0,"dropSchema");async function S0(e){let t=Tn.table_object(e);if(t)throw Pe(t,t.message,Be.BAD_REQUEST,void 0,void 0,!0);let r=await Os.checkSchemaTableExists(e.schema,e.table);if(r)throw Pe(new Error,r,Be.NOT_FOUND,ps.LOG_LEVELS.ERROR,r,!0);return await Ns.dropTable(e),Rn.signalSchemaChange(new An(process.pid,e.operation,e.schema,e.table)),await VA.purgeTableStream(e.schema,e.table),`successfully deleted table '${e.schema}.${e.table}'`}a(S0,"dropTable");async function f0(e){let t=Tn.attribute_object(e);if(t)throw Pe(t,t.message,Be.BAD_REQUEST,void 0,void 0,!0);let r=await Os.checkSchemaTableExists(e.schema,e.table);if(r)throw Pe(new Error,r,Be.NOT_FOUND,ps.LOG_LEVELS.ERROR,r,!0);if(e.attribute===global.hdb_schema[e.schema][e.table].hash_attribute)throw Pe(new Error,"You cannot drop a hash attribute",Be.BAD_REQUEST,void 0,void 0,!0);if(ps.TIME_STAMP_NAMES.indexOf(e.attribute)>=0)throw Pe(new Error,`cannot drop internal timestamp attribute: ${e.attribute}`,Be.BAD_REQUEST,void 0,void 0,!0);try{return await Ns.dropAttribute(e),T0(e),Rn.signalSchemaChange(new An(process.pid,e.operation,e.schema,e.table,e.attribute)),`successfully deleted attribute '${e.attribute}'`}catch(s){throw FA.error(`Got an error deleting attribute ${u0.inspect(e)}.`),s}}a(f0,"dropAttribute");function T0(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(T0,"dropAttributeFromGlobal");async function m0(e){if(!global.hdb_schema[e.schema])throw Pe(new Error,mn.SCHEMA_NOT_FOUND(e.schema),Be.NOT_FOUND,void 0,void 0,!0);if(!global.hdb_schema[e.schema][e.table])throw Pe(new Error,mn.TABLE_NOT_FOUND(e.schema,e.table),Be.NOT_FOUND,void 0,void 0,!0);try{return await Ns.createAttribute(e),Rn.signalSchemaChange(new An(process.pid,e.operation,e.schema,e.table,e.attribute)),`attribute '${e.schema}.${e.table}.${e.attribute}' successfully created.`}catch(t){throw FA.error(t),t}}a(m0,"createAttribute")});var KA=S((hZ,YA)=>{"use strict";var{OPERATIONS_ENUM:R0}=T(),ec=class{constructor(t,r,s=void 0,n=void 0){this.operation=R0.READ_AUDIT_LOG,this.schema=t,this.table=r,this.search_type=s,this.search_values=n}};a(ec,"ReadAuditLogObject");YA.exports=ec});var zl=S((fZ,ZA)=>{"use strict";var A0=fr(),SZ=KA(),tc=b(),rc=T(),O0=Y(),{handleHDBError:WA,hdb_errors:p0}=D(),{HDB_ERROR_MSGS:QA,HTTP_STATUS_CODES:JA}=p0,N0=Object.values(rc.READ_AUDIT_LOG_SEARCH_TYPES_ENUM),XA="To use this operation audit log must be enabled in harperdb-config.yaml";ZA.exports=g0;async function g0(e){if(tc.isEmpty(e.schema))throw new Error(QA.SCHEMA_REQUIRED_ERR);if(tc.isEmpty(e.table))throw new Error(QA.TABLE_REQUIRED_ERR);if(!O0.get(rc.CONFIG_PARAMS.LOGGING_AUDITLOG))throw WA(new Error,XA,JA.BAD_REQUEST,rc.LOG_LEVELS.ERROR,XA,!0);let t=tc.checkSchemaTableExist(e.schema,e.table);if(t)throw WA(new Error,t,JA.NOT_FOUND,rc.LOG_LEVELS.ERROR,t,!0);if(!tc.isEmpty(e.search_type)&&N0.indexOf(e.search_type)<0)throw new Error(`Invalid search_type '${e.search_type}'`);return await A0.readAuditLog(e)}a(g0,"readAuditLog")});var sO=S((TZ,rO)=>{var Yr=require("validate.js"),jA=de(),On=T(),{handleHDBError:I0,hdb_errors:b0}=D(),{HDB_ERROR_MSGS:le,HTTP_STATUS_CODES:w0}=b0,jl=a(()=>({role:{presence:!0,format:"[\\w\\-\\_]+"},id:{presence:!0,format:"[\\w\\-\\_]+"},permission:{presence:!0}}),"constraintsTemplate"),C0={STRUCTURE_USER:"structure_user"},zA=Object.values(On.ROLE_TYPES_ENUM),L0="attribute_permissions",U0="attribute_name",{PERMS_CRUD_ENUM:pn}=On,y0=[L0,...Object.values(pn)],eO=[pn.READ,pn.INSERT,pn.UPDATE],D0=[U0,...eO];function M0(e){let t=jl();return t.role.presence=!0,t.id.presence=!1,t.permission.presence=!0,tO(e,t)}a(M0,"addRoleValidation");function P0(e){let t=jl();return t.role.presence=!1,t.id.presence=!0,t.permission.presence=!0,tO(e,t)}a(P0,"alterRoleValidation");function B0(e){let t=jl();return t.role.presence=!1,t.id.presence=!0,t.permission.presence=!1,jA.validateObject(e,t)}a(B0,"dropRoleValidation");var v0=["operation","role","id","permission","hdb_user","hdb_auth_header"];function tO(e,t){let r={main_permissions:[],schema_permissions:{}},s=Object.keys(e),n=[];for(let o=0,c=s.length;o<c;o++)v0.includes(s[o])||n.push(s[o]);n.length>0&&fe(le.INVALID_ROLE_JSON_KEYS(n),r);let i=jA.validateObject(e,t);if(i&&i.message.split(",").forEach(o=>{fe(o,r)}),e.permission){let o=H0(e);o&&fe(o,r),zA.forEach(c=>{e.permission[c]&&!Yr.isBoolean(e.permission[c])&&fe(le.SU_CU_ROLE_BOOLEAN_ERROR(c),r)})}for(let o in e.permission)if(zA.indexOf(o)<0){if(o===C0.STRUCTURE_USER){let _=e.permission[o];if(typeof _=="boolean")continue;if(Array.isArray(_)){for(let u=0,l=_.length;u<l;u++){let E=_[u];global.hdb_schema[E]||fe(le.SCHEMA_NOT_FOUND(E),r)}continue}fe(le.STRUCTURE_USER_ROLE_TYPE_ERROR(o),r);continue}let c=e.permission[o];if(!o||!global.hdb_schema[o]){fe(le.SCHEMA_NOT_FOUND(o),r);continue}if(c.tables)for(let _ in c.tables){let u=c.tables[_];if(!_||!global.hdb_schema[o][_]){fe(le.TABLE_NOT_FOUND(o,_),r);continue}if(Object.keys(u).forEach(l=>{y0.includes(l)||fe(le.INVALID_PERM_KEY(l),r,o,_)}),Object.values(pn).forEach(l=>{Yr.isDefined(u[l])?Yr.isBoolean(u[l])||fe(le.TABLE_PERM_NOT_BOOLEAN(l),r,o,_):fe(le.TABLE_PERM_MISSING(l),r,o,_)}),Yr.isDefined(u.attribute_permissions)){if(!Yr.isArray(u.attribute_permissions)){fe(le.ATTR_PERMS_NOT_ARRAY,r,o,_);continue}}else{fe(le.ATTR_PERMS_ARRAY_MISSING,r,o,_);continue}if(u.attribute_permissions){let l=global.hdb_schema[o][_].attributes.map(({attribute:d})=>d),E={read:!1,insert:!1,update:!1};for(let d in u.attribute_permissions){let h=u.attribute_permissions[d];if(Object.keys(h).forEach(R=>{!D0.includes(R)&&R!==pn.DELETE&&fe(le.INVALID_ATTR_PERM_KEY(R),r,o,_)}),!Yr.isDefined(h.attribute_name)){fe(le.ATTR_PERM_MISSING_NAME,r,o,_);continue}let m=h.attribute_name;if(!l.includes(m)){fe(le.INVALID_ATTRIBUTE_IN_PERMS(m),r,o,_);continue}eO.forEach(R=>{Yr.isDefined(h[R])?Yr.isBoolean(h[R])||fe(le.ATTR_PERM_NOT_BOOLEAN(R,m),r,o,_):fe(le.ATTR_PERM_MISSING(R,m),r,o,_)}),!E.read&&h.read===!0&&(E.read=!0),!E.insert&&h.insert===!0&&(E.insert=!0),!E.update&&h.update===!0&&(E.update=!0)}if(u.read===!1&&E.read===!0||u.insert===!1&&E.insert===!0||u.update===!1&&E.update===!0){let d=`${o}.${_}`;fe(le.MISMATCHED_TABLE_ATTR_PERMS(d),r,o,_)}}}}return q0(r)}a(tO,"customValidate");rO.exports={addRoleValidation:M0,alterRoleValidation:P0,dropRoleValidation:B0};function H0(e){let{operation:t,permission:r}=e;if(t===On.OPERATIONS_ENUM.ADD_ROLE||t===On.OPERATIONS_ENUM.ALTER_ROLE){let s=r.super_user===!0,n=r.cluster_user===!0;if(Object.keys(r).length>1&&(s||n)){if(n&&s)return le.SU_CU_ROLE_COMBINED_ERROR;{let o=r.super_user?On.ROLE_TYPES_ENUM.SUPER_USER:On.ROLE_TYPES_ENUM.CLUSTER_USER;return le.SU_CU_ROLE_NO_PERMS_ALLOWED(o)}}}return null}a(H0,"validateNoSUPerms");function q0(e){let{main_permissions:t,schema_permissions:r}=e;if(t.length>0||Object.keys(r).length>0){let s={error:le.ROLE_PERMS_ERROR,...e};return I0(new Error,s,w0.BAD_REQUEST)}else return null}a(q0,"generateRolePermResponse");function fe(e,t,r,s){if(!r)t.main_permissions.push(e);else{let n=s?r+"_"+s:r;t.schema_permissions[n]?t.schema_permissions[n].push(e):t.schema_permissions[n]=[e]}}a(fe,"addPermError")});var oE=S((mZ,_O)=>{"use strict";var nO=Lt(),iO=Tt(),G0=fs(),rE=sO(),sE=Xs(),F0=require("uuid").v4,nE=require("util"),V0=mi(),Rr=T(),aO=b(),iE=nE.promisify(iO.searchByValue),k0=nE.promisify(iO.searchByHash),$0=nE.promisify(G0.delete),x0=xt(),Y0=us(),{hdb_errors:K0,handleHDBError:Ci}=D(),{HDB_ERROR_MSGS:oO,HTTP_STATUS_CODES:eE}=K0,{UserEventMsg:aE}=Pr();_O.exports={addRole:W0,alterRole:J0,dropRole:X0,listRoles:cO};function tE(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(tE,"scrubRoleDetails");async function W0(e){let t=rE.addRoleValidation(e);if(t)throw t;if(!(await V0.getLicense()).enterprise){let o=await cO();if(Q0(e,o))throw new Error(`Your current license only supports ${Rr.BASIC_LICENSE_MAX_CLUSTER_USER_ROLES} cluster_user role. ${Rr.SUPPORT_HELP_MSG}`);if(o.length>=2)throw new Error(`Your current license only supports ${Rr.BASIC_LICENSE_MAX_NON_CU_ROLES+Rr.BASIC_LICENSE_MAX_CLUSTER_USER_ROLES} roles. ${Rr.SUPPORT_HELP_MSG}`)}e=tE(e);let s={schema:"system",table:"hdb_role",search_attribute:"role",search_value:e.role,hash_attribute:"id",get_attributes:["*"]},n;try{n=await iE(s)}catch(o){throw Ci(o)}if(n&&n.length>0)throw Ci(new Error,oO.ROLE_ALREADY_EXISTS(e.role),eE.CONFLICT,void 0,void 0,!0);e.id||(e.id=F0());let i={operation:"insert",schema:"system",table:"hdb_role",hash_attribute:"id",records:[e]};return await nO.insert(i),sE.signalUserChange(new aE(process.pid)),e=tE(e),e}a(W0,"addRole");function Q0(e,t){let r=!1;if(e.permission.cluster_user===!0)for(let s=0;s<t.length;s++){let i=t[s].permission;if(!aO.isEmpty(i)&&i.cluster_user===!0)return!0}return r}a(Q0,"checkClusterUserRole");async function J0(e){let t=rE.alterRoleValidation(e);if(t)throw t;e=tE(e);let r={operation:"update",schema:"system",table:"hdb_role",hash_attribute:"rolename",records:[e]};try{await nO.update(r)}catch(s){throw Ci(s)}return sE.signalUserChange(new aE(process.pid)),e}a(J0,"alterRole");async function X0(e){let t=rE.dropRoleValidation(e);if(t)throw Ci(new Error,t,eE.BAD_REQUEST,void 0,void 0,!0);let r=new Y0(Rr.SYSTEM_SCHEMA_NAME,Rr.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME,[e.id],["role"]),s=await k0(r);if(s.length===0)throw Ci(new Error,oO.ROLE_NOT_FOUND,eE.NOT_FOUND,void 0,void 0,!0);let n=new x0(Rr.SYSTEM_SCHEMA_NAME,Rr.SYSTEM_TABLE_NAMES.USER_TABLE_NAME,"role",e.id,void 0,["username","active"]),i=await iE(n),o=!1;if(aO.isEmptyOrZeroLength(i)===!1){for(let _=0;_<i.length;_++)if(i[_].active===!0){o=!0;break}}if(o===!0)throw new Error(`Cannot drop role ${s[0].role} as it has active user(s) tied to this role`);let c={table:"hdb_role",schema:"system",hash_values:[e.id]};return await $0(c),sE.signalUserChange(new aE(process.pid)),`${s[0].role} successfully deleted`}a(X0,"dropRole");async function cO(){return iE({table:"hdb_role",schema:"system",hash_attribute:"id",search_attribute:"id",search_value:"*",get_attributes:["*"]})}a(cO,"listRoles")});var dO=S((RZ,EO)=>{"use strict";var Z0=Y(),Kr=require("joi"),z0=de(),uO=require("moment"),j0=require("fs-extra"),cE=require("path"),eV=require("lodash"),Li=T(),{LOG_LEVELS:gs}=T(),tV="YYYY-MM-DD hh:mm:ss",rV=cE.resolve(__dirname,"../logs");EO.exports=function(e){return z0.validateBySchema(e,sV)};var sV=Kr.object({from:Kr.custom(lO),until:Kr.custom(lO),level:Kr.valid(gs.NOTIFY,gs.FATAL,gs.ERROR,gs.WARN,gs.INFO,gs.DEBUG,gs.TRACE),order:Kr.valid("asc","desc"),limit:Kr.number().min(1),start:Kr.number().min(0),log_name:Kr.custom(nV)});function lO(e,t){if(uO(e,uO.ISO_8601).format(tV)==="Invalid date")return t.message(`'${t.state.path[0]}' date '${e}' is invalid.`)}a(lO,"validateDatetime");function nV(e,t){if(eV.invert(Li.PROCESS_LOG_NAMES)[e]===void 0)return t.message(`'log_name' '${e}' is invalid.`);let s=Z0.get(Li.HDB_SETTINGS_NAMES.LOG_PATH_KEY),n=e===void 0?Li.PROCESS_LOG_NAMES.HDB:e,i=n===Li.PROCESS_LOG_NAMES.INSTALL?cE.join(rV,Li.PROCESS_LOG_NAMES.INSTALL):cE.join(s,n);return j0.existsSync(i)?null:t.message(`'log_name' '${e}' does not exist.`)}a(nV,"validateReadLogPath")});var uE=S((AZ,SO)=>{"use strict";var sc=T(),hO=I(),iV=Y(),aV=dO(),_E=require("path"),oV=require("fs-extra"),cV=require("readline"),{once:_V}=require("events"),{handleHDBError:uV,hdb_errors:lV}=D(),{PACKAGE_ROOT:EV}=T(),dV=_E.join(EV,"logs"),hV=1e3;SO.exports=SV;async function SV(e){let t=aV(e);if(t)throw uV(t,t.message,lV.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0);let r=iV.get(sc.HDB_SETTINGS_NAMES.LOG_PATH_KEY),s=e.log_name===void 0?sc.PROCESS_LOG_NAMES.HDB:e.log_name,n=s===sc.PROCESS_LOG_NAMES.INSTALL?_E.join(dV,sc.PROCESS_LOG_NAMES.INSTALL):_E.join(r,s),i=oV.createReadStream(n);i.on("error",z=>{hO.error(z)});let o=cV.createInterface({input:i,crlfDelay:1/0}),c=e.level!==void 0,_=c?e.level:void 0,u=e.from!==void 0,l=u?new Date(e.from):void 0,E=e.until!==void 0,d=E?new Date(e.until):void 0,h=e.limit===void 0?hV:e.limit,m=e.order===void 0?void 0:e.order,R=e.start===void 0?0:e.start,C=R+h,L=0,B=[];return o.on("line",z=>{let V,Q,ke,$e;try{V=JSON.parse(z)}catch(ca){hO.warn(ca.message);return}switch(!0){case(c&&u&&E):Q=new Date(V.timestamp),ke=new Date(l),$e=new Date(d),V.level===_&&Q>=ke&&Q<=$e&&L<R?L++:V.level===_&&Q>=ke&&Q<=$e&&(Qr(V,m,B),L++,L===C&&Wr(o));break;case(c&&u):Q=new Date(V.timestamp),ke=new Date(l),V.level===_&&Q>=ke&&L<R?L++:V.level===_&&Q>=ke&&(Qr(V,m,B),L++,L===C&&Wr(o));break;case(c&&E):Q=new Date(V.timestamp),$e=new Date(d),V.level===_&&Q<=$e&&L<R?L++:V.level===_&&Q<=$e&&(Qr(V,m,B),L++,L===C&&Wr(o));break;case(u&&E):Q=new Date(V.timestamp),ke=new Date(l),$e=new Date(d),Q>=ke&&Q<=$e&&L<R?L++:Q>=ke&&Q<=$e&&(Qr(V,m,B),L++,L===C&&Wr(o));break;case c:V.level===_&&L<R?L++:V.level===_&&(Qr(V,m,B),L++,L===C&&Wr(o));break;case u:Q=new Date(V.timestamp),ke=new Date(l),Q>=ke&&L<R?L++:Q>=ke&&L>=R&&(Qr(V,m,B),L++,L===C&&Wr(o));break;case E:Q=new Date(V.timestamp),$e=new Date(d),Q<=$e&&L<R?L++:Q<=$e&&L>=R&&(Qr(V,m,B),L++,L===C&&Wr(o));break;default:L<R?L++:(Qr(V,m,B),L++,L===C&&Wr(o))}}),await _V(o,"close"),B}a(SV,"readLog");function Wr(e){e.close(),e.removeAllListeners()}a(Wr,"endReadLine");function Qr(e,t,r){t==="desc"?fV(e,r):t==="asc"?TV(e,r):r.push(e)}a(Qr,"pushLineToResult");function fV(e,t){let r=new Date(e.timestamp),s=0,n=t.length;for(;s<n;){let i=s+n>>>1;new Date(t[i].timestamp)>r?s=i+1:n=i}t.splice(s,0,e)}a(fV,"insertDescending");function TV(e,t){let r=new Date(e.timestamp),s=0,n=t.length;for(;s<n;){let i=s+n>>>1;new Date(t[i].timestamp)<r?s=i+1:n=i}t.splice(s,0,e)}a(TV,"insertAscending")});var ic=S((NZ,mO)=>{"use strict";var lE=require("joi"),{string:nc,boolean:fO,date:mV}=lE.types(),RV=de(),{validateSchemaExists:OZ,validateTableExists:pZ,validateSchemaName:AV}=Er(),OV=T(),pV=_e(),NV=Y(),gV=nc.invalid(NV.get(OV.CONFIG_PARAMS.CLUSTERING_NODENAME)).pattern(pV.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(),TO={operation:nc.valid("add_node","update_node"),node_name:gV,subscriptions:lE.array().items({table:nc.required(),schema:nc.custom(AV).required(),subscribe:fO.required(),publish:fO.required().custom(bV),start_time:mV.iso()}).min(1).required()};function IV(e){return RV.validateBySchema(e,lE.object(TO))}a(IV,"addUpdateNodeValidator");function bV(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(bV,"checkForFalsy");mO.exports={addUpdateNodeValidator:IV,validation_schema:TO}});var AO=S((gZ,RO)=>{var wV=de(),CV={user:{presence:!0},schema:{presence:!0},table:{presence:!0},operation:{presence:!0}};RO.exports=function(e){return wV.validateObject(e,CV)}});var EE=S((IZ,OO)=>{"use strict";var LV=T().OPERATIONS_ENUM,ac=class{constructor(t,r,s,n=void 0){this.operation=LV.UPDATE,this.schema=t,this.table=r,this.records=s,this.__origin=n}};a(ac,"UpdateObject");OO.exports=ac});var NO=S((bZ,pO)=>{"use strict";var UV={OPERATION:"operation",REFRESH:"refresh"},oc=class{constructor(t,r){this.operation_token=t,this.refresh_token=r}};a(oc,"JWTTokens");var cc=class{constructor(t,r,s){this.public_key=t,this.private_key=r,this.passphrase=s}};a(cc,"JWTRSAKeys");pO.exports={JWTTokens:oc,TOKEN_TYPE_ENUM:UV,JWTRSAKeys:cc}});var Ec=S((wZ,wO)=>{"use strict";var yi=require("jsonwebtoken"),dE=require("fs-extra"),hE=b(),yt=T(),{handleHDBError:ot,hdb_errors:yV}=D(),{HTTP_STATUS_CODES:ct,AUTHENTICATION_ERROR_MSGS:_t}=yV,Ui=I(),gO=Vo(),TE=xr(),DV=Lt().update,MV=EE(),PV=Xs(),{UserEventMsg:BV}=Pr(),Jr=Y();Jr.initSync();var SE=require("path"),{JWTTokens:vV,JWTRSAKeys:HV,TOKEN_TYPE_ENUM:_c}=NO(),qV=Jr.get(yt.HDB_SETTINGS_NAMES.OPERATION_TOKEN_TIMEOUT_KEY)?Jr.get(yt.HDB_SETTINGS_NAMES.OPERATION_TOKEN_TIMEOUT_KEY):"1d",GV=Jr.get(yt.HDB_SETTINGS_NAMES.REFRESH_TOKEN_TIMEOUT_KEY)?Jr.get(yt.HDB_SETTINGS_NAMES.REFRESH_TOKEN_TIMEOUT_KEY):"30d",uc="RS256",fE;wO.exports={createTokens:FV,validateOperationToken:kV,refreshOperationToken:VV,validateRefreshToken:bO};async function FV(e){if(hE.isEmpty(e)||typeof e!="object")throw ot(new Error,_t.INVALID_AUTH_OBJECT,ct.BAD_REQUEST,void 0,void 0,!0);if(hE.isEmpty(e.username))throw ot(new Error,_t.USERNAME_REQUIRED,ct.BAD_REQUEST,void 0,void 0,!0);if(hE.isEmpty(e.password))throw ot(new Error,_t.PASSWORD_REQUIRED,ct.BAD_REQUEST,void 0,void 0,!0);let t;try{if(t=await TE.findAndValidateUser(e.username,e.password),!t)throw ot(new Error,_t.INVALID_CREDENTIALS,ct.UNAUTHORIZED,void 0,void 0,!0)}catch(d){throw Ui.error(d),ot(new Error,_t.INVALID_CREDENTIALS,ct.UNAUTHORIZED,void 0,void 0,!0)}let r=await lc(),s=!1,n=!1;t.role&&t.role.permission&&(s=t.role.permission.super_user===!0,n=t.role.permission.cluster_user===!0);let i={username:e.username,super_user:s,cluster_user:n},o=await IO(i,r.private_key,r.passphrase),c=await yi.sign(i,{key:r.private_key,passphrase:r.passphrase},{expiresIn:GV,algorithm:uc,subject:_c.REFRESH}),_=gO.hash(c),u=new MV(yt.SYSTEM_SCHEMA_NAME,yt.SYSTEM_TABLE_NAMES.USER_TABLE_NAME,[{username:e.username,refresh_token:_}]),l,E;try{l=await DV(u)}catch(d){Ui.error(d),E=d}if(E!==void 0||l.skipped_hashes.length>0)throw ot(new Error,_t.REFRESH_TOKEN_SAVE_FAILED,ct.INTERNAL_SERVER_ERROR);return PV.signalUserChange(new BV(process.pid)),new vV(o,c)}a(FV,"createTokens");async function IO(e,t,r){return await yi.sign(e,{key:t,passphrase:r},{expiresIn:qV,algorithm:uc,subject:_c.OPERATION})}a(IO,"signOperationToken");async function lc(){if(fE===void 0)try{let e=SE.join(Jr.getHdbBasePath(),yt.LICENSE_KEY_DIR_NAME,yt.JWT_ENUM.JWT_PASSPHRASE_NAME),t=SE.join(Jr.getHdbBasePath(),yt.LICENSE_KEY_DIR_NAME,yt.JWT_ENUM.JWT_PRIVATE_KEY_NAME),r=SE.join(Jr.getHdbBasePath(),yt.LICENSE_KEY_DIR_NAME,yt.JWT_ENUM.JWT_PUBLIC_KEY_NAME),s=(await dE.readFile(e)).toString(),n=(await dE.readFile(t)).toString(),i=(await dE.readFile(r)).toString();fE=new HV(i,n,s)}catch(e){throw Ui.error(e),ot(new Error,_t.NO_ENCRYPTION_KEYS,ct.INTERNAL_SERVER_ERROR)}return fE}a(lc,"getJWTRSAKeys");async function VV(e){if(!e)throw ot(new Error,_t.INVALID_BODY,ct.BAD_REQUEST,void 0,void 0,!0);if(!e.refresh_token)throw ot(new Error,_t.REFRESH_TOKEN_REQUIRED,ct.BAD_REQUEST,void 0,void 0,!0);await bO(e.refresh_token);let t=await lc(),r=await yi.decode(e.refresh_token);return{operation_token:await IO({username:r.username,super_user:r.super_user,cluster_user:r.cluster_user},t.private_key,t.passphrase)}}a(VV,"refreshOperationToken");async function kV(e){try{let t=await lc(),r=await yi.verify(e,t.public_key,{algorithms:uc,subject:_c.OPERATION});return await TE.findAndValidateUser(r.username,void 0,!1)}catch(t){throw Ui.warn(t),t.name&&t.name==="TokenExpiredError"?ot(new Error,_t.TOKEN_EXPIRED,ct.FORBIDDEN):ot(new Error,_t.INVALID_TOKEN,ct.UNAUTHORIZED)}}a(kV,"validateOperationToken");async function bO(e){let t;try{let r=await lc(),s=await yi.verify(e,r.public_key,{algorithms:uc,subject:_c.REFRESH});t=await TE.findAndValidateUser(s.username,void 0,!1)}catch(r){throw Ui.warn(r),r.name&&r.name==="TokenExpiredError"?ot(new Error,_t.TOKEN_EXPIRED,ct.FORBIDDEN):ot(new Error,_t.INVALID_TOKEN,ct.UNAUTHORIZED)}if(!gO.validate(t.refresh_token,e))throw ot(new Error,_t.INVALID_TOKEN,ct.UNAUTHORIZED);return t}a(bO,"validateRefreshToken")});var yO=S((LZ,UO)=>{"use strict";var $V=AO(),Nn=require("passport"),xV=require("passport-local").Strategy,YV=require("passport-http").BasicStrategy,KV=require("util"),WV=xr(),LO=KV.callbackify(WV.findAndValidateUser),CZ=Ke(),QV=T(),CO=Ec();Nn.use(new xV(function(e,t,r){LO(e,t,r)}));Nn.use(new YV(function(e,t,r){LO(e,t,r)}));Nn.serializeUser(function(e,t){t(null,e)});Nn.deserializeUser(function(e,t){t(null,e)});function JV(e,t,r){let s,n;if(e.headers&&e.headers.authorization){let o=e.headers.authorization.split(" ");s=o[0],n=o[1]}function i(o,c){return o?r(o):c?r(null,c):r("User not found")}switch(a(i,"handleResponse"),s){case"Basic":Nn.authenticate("basic",{session:!1},(o,c)=>{i(o,c)})(e,t,r);break;case"Bearer":e.body&&e.body.operation&&e.body.operation===QV.OPERATIONS_ENUM.REFRESH_OPERATION_TOKEN?CO.validateRefreshToken(n).then(o=>{e.body.refresh_token=n,r(null,o)}).catch(o=>{r(o)}):CO.validateOperationToken(n).then(o=>{r(null,o)}).catch(o=>{r(o)});break;default:Nn.authenticate("local",{session:!1},function(o,c){i(o,c)})(e,t,r);break}}a(JV,"authorize");function XV(e,t){let r=$V(e);if(r){t(r);return}let s={authorized:!0,messages:[]},n=e.user.role;if(!n||!n.permission)return t("Invalid role");let i=JSON.parse(n.permission);if(i.super_user)return t(null,s);if(!i[e.schema])return s.authorized=!1,s.messages.push(`Not authorized to access ${e.schema} schema`),t(null,s);if(!i[e.schema].tables[e.table])return s.authorized=!1,s.messages.push(`Not authorized to access ${e.table} table`),t(null,s);if(!i[e.schema].tables[e.table][e.operation])return s.authorized=!1,s.messages.push(`Not authorized to access ${e.operation} on ${e.table} table`),t(null,s);if(i[e.schema].tables[e.table].attribute_permissions&&!e.attributes)return s.authorized=!1,s.messages.push(`${e.schema}.${e.table} has attribute permissions. Missing attributes to validate`),t(null,s);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]&&(s.authorized=!1,s.messages.push(`Not authorized to ${e.operation} ${o[c].attribute_name} `))}return t(null,s)}a(XV,"checkPermissions");UO.exports={authorize:JV,checkPermissions:XV}});var gn=S((UZ,DO)=>{"use strict";var dc=class{constructor(t,r,s){this.name=t,this.subscriptions=r,this.system_info=s}};a(dc,"Node");var hc=class{constructor(t,r,s,n){this.schema=t,this.table=r,this.publish=s,this.subscribe=n}};a(hc,"NodeSubscription");DO.exports={Node:dc,NodeSubscription:hc}});var PO=S((yZ,MO)=>{"use strict";var ZV=T().OPERATIONS_ENUM,Sc=class{constructor(t,r,s,n=void 0){this.operation=ZV.UPSERT,this.schema=t,this.table=r,this.records=s,this.__origin=n}};a(Sc,"UpsertObject");MO.exports=Sc});var Di=S((DZ,BO)=>{"use strict";var fc=class{constructor(t,r,s,n){this.operation=t,this.node_name=r,this.subscriptions=s,this.system_info=n}};a(fc,"RemotePayloadObject");var Tc=class{constructor(t,r,s,n,i,o){this.schema=t,this.table=r,this.hash_attribute=s,this.publish=n,this.subscribe=i,this.start_time=o}};a(Tc,"RemotePayloadSubscription");BO.exports={RemotePayloadObject:fc,RemotePayloadSubscription:Tc}});var HO=S((MZ,vO)=>{"use strict";var mc=class{constructor(t,r,s=0,n=0,i=0,o=0){this.schema=t,this.table=r,this.table_size=s,this.record_count=n,this.transaction_log_size=i,this.transaction_log_record_count=o}};a(mc,"TableSizeObject");vO.exports=mc});var VO=S((PZ,FO)=>{"use strict";var zV=HO(),qO=require("path"),GO=te(),jV=Ye(),In=X(),ek=I();FO.exports=tk;async function tk(e){let t=new zV;try{let r=qO.join(GO.getBaseSchemaPath(),e.schema.toString()),s=await In.openEnvironment(r,e.name),n=In.statDBI(s,e.hash_attribute),i=qO.join(GO.getTransactionAuditStorePath(),e.schema.toString()),o=await In.openEnvironment(i,e.name,!0),c=In.statDBI(o,jV.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP),_=await In.environmentDataSize(r,e.name),u=await In.environmentDataSize(i,e.name);t.schema=e.schema,t.table=e.name,t.table_size=_,t.record_count=n.entryCount,t.transaction_log_size=u,t.transaction_log_record_count=c.entryCount}catch(r){ek.warn(`unable to stat table dbi due to ${r}`)}return t}a(tk,"lmdbGetTableSize")});var $O=S((BZ,kO)=>{"use strict";var rk=T(),Rc=class{constructor(t){this.operator=rk.OPERATIONS_ENUM.SYSTEM_INFORMATION,this.attributes=t}};a(Rc,"SystemInformationOperation");kO.exports=Rc});var YO=S((vZ,xO)=>{"use strict";var Ac=class{constructor(t,r,s,n,i,o,c){this.system=t,this.time=r,this.cpu=s,this.memory=n,this.disk=i,this.network=o,this.harperdb_processes=c}};a(Ac,"SystemInformationObject");xO.exports=Ac});var pc=S((qZ,KO)=>{"use strict";var ve=require("systeminformation"),bn=I(),sk=T(),nk=VO(),ik=ds(),ak=Y();ak.initSync();var HZ=$O(),ok=YO(),Oc;KO.exports={getHDBProcessInfo:OE,getNetworkInfo:NE,getDiskInfo:pE,getMemoryInfo:AE,getCPUInfo:RE,getTimeInfo:mE,getSystemInformation:gE,systemInformation:ck,getTableSize:IE};function mE(){return ve.time()}a(mE,"getTimeInfo");async function RE(){try{let{family:e,model:t,stepping:r,revision:s,voltage:n,speedmin:i,speedmax:o,governor:c,socket:_,cache:u,...l}=await ve.cpu();l.cpu_speed=await ve.cpuCurrentSpeed();let{raw_currentload:E,raw_currentload_idle:d,raw_currentload_irq:h,raw_currentload_nice:m,raw_currentload_system:R,raw_currentload_user:C,cpus:L,...B}=await ve.currentLoad();return B.cpus=[],L.forEach(z=>{let{raw_load:V,raw_load_idle:Q,raw_load_irq:ke,raw_load_nice:$e,raw_load_system:ca,raw_load_user:_a,...wr}=z;B.cpus.push(wr)}),l.current_load=B,l}catch(e){return bn.error(`error in getCPUInfo: ${e}`),{}}}a(RE,"getCPUInfo");async function AE(){try{let{buffers:e,cached:t,slab:r,buffcache:s,...n}=await ve.mem();return n}catch(e){return bn.error(`error in getMemoryInfo: ${e}`),{}}}a(AE,"getMemoryInfo");async function OE(){let e={core:[],clustering:[]};try{return(await ve.processes()).list.forEach(r=>{r.params.includes(sk.HDB_PROC_NAME)?e.core.push(r):r.params.includes("socketcluster")&&e.clustering.push(r)}),e}catch(t){return bn.error(`error in getHDBProcessInfo: ${t}`),e}}a(OE,"getHDBProcessInfo");async function pE(){let e={};try{let{rIO_sec:t,wIO_sec:r,tIO_sec:s,ms:n,...i}=await ve.disksIO();e.io=i;let{rx_sec:o,tx_sec:c,wx_sec:_,...u}=await ve.fsStats();return e.read_write=u,e.size=await ve.fsSize(),e}catch(t){return bn.error(`error in getDiskInfo: ${t}`),e}}a(pE,"getDiskInfo");async function NE(){let e={default_interface:null,latency:{},interfaces:[],stats:[],connections:[]};try{return e.default_interface=await ve.networkInterfaceDefault(),e.latency=await ve.inetChecksite("google.com"),(await ve.networkInterfaces()).forEach(s=>{let{internal:n,virtual:i,mtu:o,dhcp:c,dnsSuffix:_,ieee8021xAuth:u,ieee8021xState:l,carrier_changes:E,...d}=s;e.interfaces.push(d)}),(await ve.networkStats()).forEach(s=>{let{rx_sec:n,tx_sec:i,ms:o,...c}=s;e.stats.push(c)}),e.connections=await ve.networkConnections(),e}catch(t){return bn.error(`error in getNetworkInfo: ${t}`),e}}a(NE,"getNetworkInfo");async function gE(){if(Oc!==void 0)return Oc;let e={};try{let{codepage:t,logofile:r,serial:s,build:n,servicepack:i,uefi:o,...c}=await ve.osInfo();e=c;let _=await ve.versions("node, npm");return e.node_version=_.node,e.npm_version=_.npm,Oc=e,Oc}catch(t){return bn.error(`error in getSystemInformation: ${t}`),e}}a(gE,"getSystemInformation");async function IE(){let e=[],t=await ik.describeAll();for(let r of Object.values(t))for(let s of Object.values(r))e.push(await nk(s));return e}a(IE,"getTableSize");async function ck(e){let t=new ok;if(!Array.isArray(e.attributes)||e.attributes.length===0)return t.system=await gE(),t.time=mE(),t.cpu=await RE(),t.memory=await AE(),t.disk=await pE(),t.network=await NE(),t.harperdb_processes=await OE(),t.table_size=await IE(),t;for(let r=0;r<e.attributes.length;r++)switch(e.attributes[r]){case"system":t.system=await gE();break;case"time":t.time=mE();break;case"cpu":t.cpu=await RE();break;case"memory":t.memory=await AE();break;case"disk":t.disk=await pE();break;case"network":t.network=await NE();break;case"harperdb_processes":t.harperdb_processes=await OE();break;case"table_size":t.table_size=await IE();break;default:break}return t}a(ck,"systemInformation")});var bE=S((VZ,WO)=>{"use strict";var GZ=require("fs-extra"),FZ=I();WO.exports={version:_k,printVersion:lk,nodeVersion:uk};var Xr=Ml();function _k(){if(Xr)return Xr.version}a(_k,"version");function uk(){if(Xr&&Xr.engines&&Xr.engines["preferred-node"])return Xr.engines["preferred-node"]}a(uk,"nodeVersion");function lk(){Xr&&console.log(`HarperDB Version ${Xr.version}`)}a(lk,"printVersion")});var bs=S((xZ,ZO)=>{"use strict";var Ek=Lt(),wE=b(),CE=require("util"),Is=T(),QO=Y();QO.initSync();var dk=yO(),JO=Tt(),{Node:kZ,NodeSubscription:$Z}=gn(),hk=us(),Sk=PO(),{RemotePayloadObject:fk,RemotePayloadSubscription:Tk}=Di(),{handleHDBError:mk,hdb_errors:Rk}=D(),{HTTP_STATUS_CODES:Ak,HDB_ERROR_MSGS:Ok}=Rk,pk=xt(),Nk=pc(),gk=bE(),Ik=CE.promisify(dk.authorize),bk=CE.promisify(JO.searchByHash),wk=CE.promisify(JO.searchByValue);ZO.exports={authHeaderToUser:Ck,isEmpty:Lk,getNodeRecord:Uk,upsertNodeRecord:yk,buildNodePayloads:Dk,checkClusteringEnabled:Mk,getAllNodeRecords:Pk,getSystemInfo:Bk,reverseSubscription:XO};async function Ck(e){let t={headers:{authorization:e.hdb_auth_header}};return e.hdb_user=await Ik(t,null),e}a(Ck,"authHeaderToUser");function Lk(e){return e==null}a(Lk,"isEmpty");async function Uk(e){let t=new hk(Is.SYSTEM_SCHEMA_NAME,Is.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[e],["*"]);return bk(t)}a(Uk,"getNodeRecord");async function yk(e){let t=new Sk(Is.SYSTEM_SCHEMA_NAME,Is.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[e]);return Ek.upsert(t)}a(yk,"upsertNodeRecord");function XO(e){if(wE.isEmpty(e.subscribe)||wE.isEmpty(e.publish))throw new Error("Received invalid subscription object");let{schema:t,table:r,hash_attribute:s}=e,n={schema:t,table:r,hash_attribute:s};return e.subscribe===!0&&e.publish===!1?(n.subscribe=!1,n.publish=!0):e.subscribe===!1&&e.publish===!0?(n.subscribe=!0,n.publish=!1):(n.subscribe=e.subscribe,n.publish=e.publish),n}a(XO,"reverseSubscription");function Dk(e,t,r,s){let n=[];for(let i=0,o=e.length;i<o;i++){let c=e[i],{schema:_,table:u}=c,l=wE.getTableHashAttribute(_,u),{subscribe:E,publish:d}=XO(c),h=new Tk(_,u,l,d,E,c.start_time);n.push(h)}return new fk(r,t,n,s)}a(Dk,"buildNodePayloads");function Mk(){if(!QO.get(Is.CONFIG_PARAMS.CLUSTERING_ENABLED))throw mk(new Error,Ok.CLUSTERING_NOT_ENABLED,Ak.BAD_REQUEST,void 0,void 0,!0)}a(Mk,"checkClusteringEnabled");async function Pk(){let e=new pk(Is.SYSTEM_SCHEMA_NAME,Is.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,"name","*",void 0,["*"]);return wk(e)}a(Pk,"getAllNodeRecords");async function Bk(){let e=await Nk.getSystemInformation();return{hdb_version:gk.version(),node_version:e.node_version,platform:e.platform}}a(Bk,"getSystemInfo")});var UE=S((YZ,sp)=>{"use strict";var LE=at(),zO=b(),jO=_e(),vk=T(),Nc=I(),ep=jo(),Hk=Zu(),{RemotePayloadObject:qk}=Di(),{handleHDBError:tp,hdb_errors:Gk}=D(),{HTTP_STATUS_CODES:rp}=Gk,{NodeSubscription:Fk}=gn();sp.exports=Vk;async function Vk(e,t){let r;try{r=await LE.request(`${t}.${jO.REQUEST_SUFFIX}`,new qk(vk.OPERATIONS_ENUM.DESCRIBE_ALL,t,void 0,void 0)),Nc.trace("Response from remote describe all request:",r)}catch(o){Nc.error(`addNode received error from describe all request to remote node: ${o}`);let c=LE.requestErrorHandler(o,"add_node",t);throw tp(new Error,c,rp.INTERNAL_SERVER_ERROR,"error",c)}if(r.status===jO.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let o=`Error returned from remote node ${t}: ${r.message}`;throw tp(new Error,o,rp.INTERNAL_SERVER_ERROR,"error",o)}let s=r.message,n=[],i=[];for(let o of e){let{schema:c,table:_}=o,u=zO.doesSchemaExist(c),l=s[c]!==void 0,E=zO.doesTableExist(c,_),d=s?.[c]?.[_]!==void 0;if(!u&&!l||!E&&!d){n.push(o);continue}if(!u&&l&&(Nc.trace(`addNode creating schema: ${c}`),await ep.createSchema({operation:"create_schema",schema:c})),!E&&d){Nc.trace(`addNode creating table: ${_} in schema: ${c}`);let m=new Hk(c,_,s[c][_].hash_attribute);await ep.createTable(m)}await LE.createLocalTableStream(c,_);let h=new Fk(c,_,o.publish,o.subscribe);h.start_time=o.start_time,i.push(h)}return{added:i,skipped:n}}a(Vk,"reviewSubscriptions")});var bc=S((KZ,ap)=>{"use strict";var{handleHDBError:gc,hdb_errors:kk}=D(),{HTTP_STATUS_CODES:Ic}=kk,{addUpdateNodeValidator:$k}=ic(),Mi=I(),ip=T(),np=_e(),xk=b(),yE=at(),Pi=bs(),Yk=Y(),Kk=UE(),{Node:Wk,NodeSubscription:Qk}=gn(),Jk="Unable to create subscriptions due to schema and/or tables not existing on the local or remote node",Xk="Some subscriptions were unsuccessful due to schema and/or tables not existing on the local or remote node",Zk=Yk.get(ip.CONFIG_PARAMS.CLUSTERING_NODENAME);ap.exports=zk;async function zk(e,t=!1){Mi.trace("addNode called with:",e),Pi.checkClusteringEnabled();let r=$k(e);if(r)throw gc(r,r.message,Ic.BAD_REQUEST,void 0,void 0,!0);let s=e.node_name;if(!t){let E=await Pi.getNodeRecord(s);if(!xk.isEmptyOrZeroLength(E))throw gc(new Error,`Node '${s}' has already been added, perform update_node to proceed.`,Ic.BAD_REQUEST,void 0,void 0,!0)}let{added:n,skipped:i}=await Kk(e.subscriptions,s),o={message:void 0,added:n,skipped:i};if(n.length===0)return o.message=Jk,o;let c=Pi.buildNodePayloads(n,Zk,ip.OPERATIONS_ENUM.ADD_NODE,await Pi.getSystemInfo());Mi.trace("addNode sending remote payload:",c);let _;try{_=await yE.request(`${s}.${np.REQUEST_SUFFIX}`,c)}catch(E){Mi.error(`addNode received error from request: ${E}`);let d=yE.requestErrorHandler(E,"add_node",s);throw gc(new Error,d,Ic.INTERNAL_SERVER_ERROR,"error",d)}if(_.status===np.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let E=`Error returned from remote node ${s}: ${_.message}`;throw gc(new Error,E,Ic.INTERNAL_SERVER_ERROR,"error",E)}Mi.trace(_);let u=[];for(let E=0,d=n.length;E<d;E++){let h=n[E];Mi.trace("Add node updating work stream for node:",s,"subscriptions:",h),await yE.updateWorkStream(h,s),n[E].start_time===void 0&&delete n[E].start_time,u.push(new Qk(h.schema,h.table,h.publish,h.subscribe))}let l=new Wk(s,u,_.system_info);return await Pi.upsertNodeRecord(l),i.length>0?o.message=Xk:o.message=`Successfully added '${s}' to manifest`,o}a(zk,"addNode")});var ME=S((WZ,_p)=>{"use strict";var{handleHDBError:wc,hdb_errors:jk}=D(),{HTTP_STATUS_CODES:Cc}=jk,{addUpdateNodeValidator:e$}=ic(),Bi=I(),cp=T(),op=_e(),t$=b(),DE=at(),vi=bs(),r$=Y(),{cloneDeep:s$}=require("lodash"),n$=UE(),{NodeSubscription:i$}=gn(),a$="Unable to update subscriptions due to schema and/or tables not existing on the local or remote node",o$="Some subscriptions were unsuccessful due to schema and/or tables not existing on the local or remote node",c$=r$.get(cp.CONFIG_PARAMS.CLUSTERING_NODENAME);_p.exports=_$;async function _$(e){Bi.trace("updateNode called with:",e),vi.checkClusteringEnabled();let t=e$(e);if(t)throw wc(t,t.message,Cc.BAD_REQUEST,void 0,void 0,!0);let r=e.node_name,s=s$(await vi.getNodeRecord(r));if(t$.isEmptyOrZeroLength(s))throw wc(new Error,`Node '${r}' has not been added, perform add_node to proceed.`,Cc.BAD_REQUEST,void 0,void 0,!0);let{added:n,skipped:i}=await n$(e.subscriptions,r),o={message:void 0,updated:n,skipped:i};if(n.length===0)return o.message=a$,o;let c=vi.buildNodePayloads(n,c$,cp.OPERATIONS_ENUM.UPDATE_NODE,await vi.getSystemInfo());Bi.trace("updateNode sending remote payload:",c);let _;try{_=await DE.request(`${r}.${op.REQUEST_SUFFIX}`,c)}catch(u){Bi.error(`updateNode received error from request: ${u}`);let l=DE.requestErrorHandler(u,"update_node",r);throw wc(new Error,l,Cc.INTERNAL_SERVER_ERROR,"error",l)}if(_.status===op.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let u=`Error returned from remote node ${r}: ${_.message}`;throw wc(new Error,u,Cc.INTERNAL_SERVER_ERROR,"error",u)}Bi.trace(_);for(let u=0,l=n.length;u<l;u++){let E=n[u];Bi.trace(`updateNode updating work stream for node: ${r} subscription:`,E),await DE.updateWorkStream(E,r),n[u].start_time===void 0&&delete n[u].start_time}return await u$(s[0],n,_.system_info),i.length>0?o.message=o$:o.message=`Successfully updated '${r}'`,o}a(_$,"updateNode");async function u$(e,t,r){let s=e;for(let n=0,i=t.length;n<i;n++){let o=t[n],c=!1;for(let _=0,u=e.subscriptions.length;_<u;_++){let l=s.subscriptions[_];if(l.schema===o.schema&&l.table===o.table){l.publish=o.publish,l.subscribe=o.subscribe,c=!0;break}}c||s.subscriptions.push(new i$(o.schema,o.table,o.publish,o.subscribe))}s.system_info=r,await vi.upsertNodeRecord(s)}a(u$,"updateNodeTable")});var hp=S((QZ,dp)=>{"use strict";var Ep=require("joi"),{string:up}=Ep.types(),l$=de(),lp=T(),E$=Y(),d$=_e();dp.exports=h$;function h$(e){let t=up.invalid(E$.get(lp.CONFIG_PARAMS.CLUSTERING_NODENAME)).pattern(d$.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=Ep.object({operation:up.valid(lp.OPERATIONS_ENUM.REMOVE_NODE).required(),node_name:t});return l$.validateBySchema(e,r)}a(h$,"removeNodeValidator")});var Uc=S((JZ,Ap)=>{"use strict";var{handleHDBError:Sp,hdb_errors:S$}=D(),{HTTP_STATUS_CODES:fp}=S$,f$=hp(),Hi=I(),Tp=bs(),T$=b(),Lc=T(),mp=_e(),Rp=at(),m$=Y(),{RemotePayloadObject:R$}=Di(),{NodeSubscription:A$}=gn(),O$=_i(),p$=fs(),N$=m$.get(Lc.CONFIG_PARAMS.CLUSTERING_NODENAME);Ap.exports=g$;async function g$(e){Hi.trace("removeNode called with:",e),Tp.checkClusteringEnabled();let t=f$(e);if(t)throw Sp(t,t.message,fp.BAD_REQUEST,void 0,void 0,!0);let r=e.node_name,s=await Tp.getNodeRecord(r);if(T$.isEmptyOrZeroLength(s))throw Sp(new Error,`Node '${r}' was not found.`,fp.BAD_REQUEST,void 0,void 0,!0);s=s[0];let n=new R$(Lc.OPERATIONS_ENUM.REMOVE_NODE,N$,[]),i,o=!1;try{i=await Rp.request(`${r}.${mp.REQUEST_SUFFIX}`,n),Hi.trace("Remove node reply from remote node:",r,i)}catch(_){Hi.error("removeNode received error from request:",_),o=!0}for(let _=0,u=s.subscriptions.length;_<u;_++){let l=s.subscriptions[_];Hi.trace(`Remove node removing subscription: ${l.schema}.${l.table} for node: ${r}`);let E=new A$(l.schema,l.table,!1,!1);await Rp.updateWorkStream(E,r)}let c=new O$(Lc.SYSTEM_SCHEMA_NAME,Lc.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[r]);return await p$.deleteRecord(c),i?.status===mp.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR||o?(Hi.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(g$,"removeNode")});var Np=S((XZ,pp)=>{"use strict";var Op=require("joi"),{string:I$,array:b$}=Op.types(),w$=de(),C$=ic();pp.exports=L$;function L$(e){let t=Op.object({operation:I$.valid("configure_cluster").required(),connections:b$.items(C$.validation_schema).required()});return w$.validateBySchema(e,t)}a(L$,"configureClusterValidator")});var PE=S((ZZ,Cp)=>{"use strict";var U$=T(),yc=I(),y$=b(),D$=Uc(),M$=bc(),gp=bs(),P$=Np(),{handleHDBError:Ip,hdb_errors:B$}=D(),{HTTP_STATUS_CODES:bp}=B$,v$="Configure cluster complete.",H$="Failed to configure the cluster. Check the logs for more details.",q$="Configure cluster was partially successful. Errors occurred when attempting to configure the following nodes. Check the logs for more details.";Cp.exports=G$;async function G$(e){yc.trace("configure cluster called with:",e),gp.checkClusteringEnabled();let t=P$(e);if(t)throw Ip(t,t.message,bp.BAD_REQUEST,void 0,void 0,!0);let r=await gp.getAllNodeRecords(),s=[];for(let d=0,h=r.length;d<h;d++)s.push(wp(D$,{operation:U$.OPERATIONS_ENUM.REMOVE_NODE,node_name:r[d].name},r[d].name));let n=await Promise.allSettled(s);yc.trace("All results from configure_cluster remove node:",n);let i=[],o=e.connections.length;for(let d=0;d<o;d++){let h=e.connections[d];i.push(wp(M$,h,h.node_name))}let c=await Promise.allSettled(i);yc.trace("All results from configure_cluster add node:",c);let _=[],u=[],l=!1,E=n.concat(c);for(let d=0,h=E.length;d<h;d++){let m=E[d];m.status==="rejected"&&(yc.error(m.reason),_.includes(m.reason.node_name)||_.push(m.reason.node_name)),m.status==="fulfilled"&&(l=!0);let R=m?.value?.result;typeof R=="string"&&R.includes("Successfully removed")||m.status==="rejected"||u.push({node_name:m?.value?.node_name,subscriptions:m?.value?.result})}if(y$.isEmptyOrZeroLength(_))return{message:v$,connections:u};if(l)return{message:q$,failed_nodes:_,connections:u};throw Ip(new Error,H$,bp.INTERNAL_SERVER_ERROR,void 0,void 0,!0)}a(G$,"configureCluster");async function wp(e,t,r){try{return{node_name:r,result:await e(t)}}catch(s){throw{node_name:r,error:s}}}a(wp,"functionWrapper")});var HE=S((zZ,Pp)=>{"use strict";var vE=bs(),F$=at(),yp=Y(),Dc=T(),ws=_e(),V$=b(),BE=I(),{RemotePayloadObject:k$}=Di(),{ErrorCode:Lp}=require("nats"),Up=yp.get(Dc.CONFIG_PARAMS.CLUSTERING_ENABLED),Dp=yp.get(Dc.CONFIG_PARAMS.CLUSTERING_NODENAME);Pp.exports={clusterStatus:$$,buildNodeStatus:Mp};async function $$(){let e={node_name:Dp,is_enabled:Up,connections:[]};if(!Up)return e;let t=await vE.getAllNodeRecords();if(V$.isEmptyOrZeroLength(t))return e;let r=[];for(let s=0,n=t.length;s<n;s++)r.push(Mp(t[s],e.connections));return await Promise.allSettled(r),e}a($$,"clusterStatus");async function Mp(e,t){let r=e.name,s=new k$(Dc.OPERATIONS_ENUM.CLUSTER_STATUS,Dp,void 0,await vE.getSystemInfo()),n,i,o=ws.CLUSTER_STATUS_STATUSES.OPEN;try{let _=Date.now();n=await F$.request(ws.REQUEST_SUBJECT(r),s),i=Date.now()-_,n.status===ws.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR&&(o=ws.CLUSTER_STATUS_STATUSES.CLOSED,BE.error(`Error getting node status from ${r} `,n))}catch(_){BE.warn(`Error getting node status from ${r}`,_),_.code===Lp.NoResponders?o=ws.CLUSTER_STATUS_STATUSES.NO_RESPONDERS:_.code===Lp.Timeout?o=ws.CLUSTER_STATUS_STATUSES.TIMEOUT:o=ws.CLUSTER_STATUS_STATUSES.CLOSED}let c=new x$(r,o,n?.message?.ports?.clustering,n?.message?.ports?.operations_api,i,n?.message?.uptime,e.subscriptions,n?.message?.system_info);try{let _={name:r,system_info:n?.message?.system_info};e.system_info?.hdb_version!==Dc.PRE_4_0_0_VERSION&&await vE.upsertNodeRecord(_)}catch(_){BE.error("Cluster status encountered an error updating system info for node:",r,_)}t.push(c)}a(Mp,"buildNodeStatus");function x$(e,t,r,s,n,i,o,c){this.node_name=e,this.status=t,this.ports={clustering:r,operations_api:s},this.latency_ms=n,this.uptime=i,this.subscriptions=o,this.system_info=c}a(x$,"NodeStatusObject")});var qp=S((jZ,Hp)=>{"use strict";var qE=require("joi"),Bp=de(),{route_constraints:vp}=lu();Hp.exports={setRoutesValidator:Y$,deleteRoutesValidator:K$};function Y$(e){let t=qE.object({server:qE.valid("hub","leaf").required(),routes:vp.required()});return Bp.validateBySchema(e,t)}a(Y$,"setRoutesValidator");function K$(e){let t=qE.object({routes:vp.required()});return Bp.validateBySchema(e,t)}a(K$,"deleteRoutesValidator")});var FE=S((e3,kp)=>{"use strict";var Cs=ur(),GE=b(),Mc=T(),Gp=qp(),{handleHDBError:Fp,hdb_errors:W$}=D(),{HTTP_STATUS_CODES:Vp}=W$,Q$="cluster routes successfully set",J$="cluster routes successfully deleted";kp.exports={setRoutes:X$,getRoutes:Z$,deleteRoutes:z$};function X$(e){let t=Gp.setRoutesValidator(e);if(t)throw Fp(t,t.message,Vp.BAD_REQUEST,void 0,void 0,!0);let r=Cs.getClusteringRoutes(),s=e.server==="hub"?r.hub_routes:r.leaf_routes,n=e.server==="hub"?r.leaf_routes:r.hub_routes,i=[],o=[];for(let c=0,_=e.routes.length;c<_;c++){let u=e.routes[c];u.port=GE.autoCast(u.port);let l=s.some(d=>d.host===u.host&&d.port===u.port),E=n.some(d=>d.host===u.host&&d.port===u.port);l||E?i.push(u):(s.push(u),o.push(u))}return e.server==="hub"?Cs.updateConfigValue(Mc.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,s):Cs.updateConfigValue(Mc.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,s),{message:Q$,set:o,skipped:i}}a(X$,"setRoutes");function Z$(){let e=Cs.getClusteringRoutes();return{hub:e.hub_routes,leaf:e.leaf_routes}}a(Z$,"getRoutes");function z$(e){let t=Gp.deleteRoutesValidator(e);if(t)throw Fp(t,t.message,Vp.BAD_REQUEST,void 0,void 0,!0);let r=Cs.getClusteringRoutes(),s=r.hub_routes,n=r.leaf_routes,i=[],o=[],c=!1,_=!1;for(let u=0,l=e.routes.length;u<l;u++){let E=e.routes[u],d=!1;for(let h=0,m=s.length;h<m;h++){let R=s[h];if(E.host===R.host&&E.port===R.port){s.splice(h,1),d=!0,c=!0,i.push(E);break}}if(!d){let h=!0;for(let m=0,R=n.length;m<R;m++){let C=n[m];if(E.host===C.host&&E.port===C.port){n.splice(m,1),_=!0,h=!1,i.push(E);break}}h&&o.push(E)}}return c&&(s=GE.isEmptyOrZeroLength(s)?null:s,Cs.updateConfigValue(Mc.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,s)),_&&(n=GE.isEmptyOrZeroLength(n)?null:n,Cs.updateConfigValue(Mc.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,n)),{message:J$,deleted:i,skipped:o}}a(z$,"deleteRoutes")});var xp=S((t3,$p)=>{"use strict";var qi=require("alasql"),Ls=require("recursive-iterator"),Kt=I(),j$=b(),Gi=T(),Pc=class{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,tx(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(n=>Gi.SEARCH_WILDCARDS.includes(n.columnid));if(r.length===0)return this.ast;let s=this.ast.from[0].databaseid;return this.ast.columns=this.ast.columns.filter(n=>!Gi.SEARCH_WILDCARDS.includes(n.columnid)),r.forEach(n=>{let i=this.table_to_schema_lookup.has(n.tableid)?this.table_to_schema_lookup.get(n.tableid):s,o=this.table_lookup.has(n.tableid)?this.table_lookup.get(n.tableid):this.ast.from[0].tableid;if(t[i]&&t[i].tables[o]&&t[i].tables[o][Gi.PERMS_CRUD_ENUM.READ]){let c;t[i].tables[o].attribute_permissions.length>0?c=ex(t[i].tables[o].attribute_permissions):c=global.hdb_schema[i][o].attributes.map(u=>({attribute_name:u.attribute}));let _=this.affected_attributes.get(i).get(o).filter(u=>!Gi.SEARCH_WILDCARDS.includes(u));c.forEach(({attribute_name:u})=>{let l=new qi.yy.Column({columnid:u});n.tableid&&(l.tableid=n.tableid),this.ast.columns.push(l),_.includes(u)||_.push(u)}),this.affected_attributes.get(i).set(o,_)}}),this.ast}};a(Pc,"sql_statement_bucket");function ex(e){return e.filter(t=>t[Gi.PERMS_CRUD_ENUM.READ])}a(ex,"filterReadRestrictedAttrs");function tx(e,t,r,s,n){rx(e,t,r,s,n)}a(tx,"interpretAST");function Fi(e,t,r,s,n){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),s&&!s.has(e.as)&&s.set(e.as,e.databaseid)),n)){let i=e.databaseid,o=e.tableid;e.as&&(o=e.as),n.set(o,i)}}a(Fi,"addSchemaTableToMap");function rx(e,t,r,s,n){if(!e){Kt.info("getRecordAttributesAST: invalid SQL syntax tree");return}e instanceof qi.yy.Insert?ax(e,t,r):e instanceof qi.yy.Select?sx(e,t,r,s,n):e instanceof qi.yy.Update?nx(e,t,r):e instanceof qi.yy.Delete?ix(e,t,r):Kt.error("AST in getRecordAttributesAST() is not a valid SQL type.")}a(rx,"getRecordAttributesAST");function sx(e,t,r,s,n){if(!e){Kt.info("getSelectAttributes: invalid SQL syntax tree");return}if(!e.from||e.from[0]===void 0)return;let i=e.from[0].databaseid;if(j$.isEmptyOrZeroLength(i)){Kt.error("No schema specified");return}e.from.forEach(c=>{Fi(c,t,r,s,n)}),e.joins&&e.joins.forEach(c=>{c.as&&(c.table.as=c.as),Fi(c.table,t,r,s,n)});let o=new Ls(e.columns);for(let{node:c}of o)if(c&&c.columnid){let _=c.tableid,u=s.has(_)?s.get(_):i;if(_||(_=e.from[0].tableid),!t.get(u).has(_))if(r.has(_))_=r.get(_);else{Kt.info(`table specified as ${_} not found.`);return}t.get(u).get(_).indexOf(c.columnid)<0&&t.get(u).get(_).push(c.columnid)}if(e.where){let c=new Ls(e.where),_=e.from[0].tableid;for(let{node:u}of c)if(u&&u.columnid){let l=u.tableid?u.tableid:_;if(!t.get(i).has(l))if(r.has(l))l=r.get(l);else{Kt.info(`table specified as ${l} not found.`);continue}t.get(i).get(l).indexOf(u.columnid)<0&&t.get(i).get(l).push(u.columnid)}}if(e.joins&&e.joins.forEach(c=>{let _=new Ls(c.on);for(let{node:u}of _)if(u&&u.columnid){let l=u.tableid,E=n.get(l);if(!t.get(E).has(l))if(r.has(l))l=r.get(l);else{Kt.info(`table specified as ${l} not found.`);continue}t.get(E).get(l).indexOf(u.columnid)<0&&t.get(E).get(l).push(u.columnid)}}),e.order){let c=new Ls(e.order);for(let{node:_}of c)if(_&&_.columnid){let u=_.tableid,l=s.has(u)?s.get(u):i;if(u||(u=e.from[0].tableid),!t.get(l).has(u))if(r.has(u))u=r.get(u);else{Kt.info(`table specified as ${u} not found.`);return}t.get(l).get(u).indexOf(_.columnid)<0&&t.get(l).get(u).push(_.columnid)}}}a(sx,"getSelectAttributes");function nx(e,t,r){if(!e){Kt.info("getUpdateAttributes: invalid SQL syntax tree");return}let s=new Ls(e.columns),n=e.table.databaseid;Fi(e.table,t,r);for(let{node:i}of s)i&&i.columnid&&VE(e.table.tableid,n,i.columnid,t,r)}a(nx,"getUpdateAttributes");function ix(e,t,r){if(!e){Kt.info("getDeleteAttributes: invalid SQL syntax tree");return}let s=new Ls(e.where),n=e.table.databaseid;Fi(e.table,t,r);for(let{node:i}of s)i&&i.columnid&&VE(e.table.tableid,n,i.columnid,t,r)}a(ix,"getDeleteAttributes");function ax(e,t,r){if(!e){Kt.info("getInsertAttributes: invalid SQL syntax tree");return}let s=new Ls(e.columns),n=e.into.databaseid;Fi(e.into,t,r);for(let{node:i}of s)i&&i.columnid&&VE(e.into.tableid,n,i.columnid,t,r)}a(ax,"getInsertAttributes");function VE(e,t,r,s,n){if(!s.get(t))return;let i=e;s.get(t).has(i)||(i=n.get(i)),s.get(t).get(i).push(r)}a(VE,"pushAttribute");$p.exports=Pc});var Wp=S((r3,Kp)=>{var ox=require("os"),Yp=Y();Kp.exports={checkPermission:cx};function cx(){if(ox.userInfo().username!==Yp.get("install_user"))throw new Error(`Error: Must execute as ${Yp.get("install_user")}`)}a(cx,"checkPermission")});var $E=S((s3,zp)=>{var vc=mi(),Qp=require("chalk"),rr=I(),Jp=Wp(),Xp=require("prompt"),{promisify:_x}=require("util"),Bc=T(),ux=require("fs-extra"),lx=require("path"),Ex=b(),dx=bE(),Zp=Y();Zp.initSync();var hx=require("moment"),Sx=_x(Xp.get),fx=lx.join(Zp.getHdbBasePath(),Bc.LICENSE_KEY_DIR_NAME,Bc.LICENSE_FILE_NAME,Bc.LICENSE_FILE_NAME);zp.exports={getFingerprint:mx,setLicense:Tx,parseLicense:kE,register:Rx,getRegistrationInfo:Ox};async function Tx(e){if(e&&e.key&&e.company){try{rr.info(`parsing license key: ${e.key} and `);let t=e.company.toString();await kE(e.key.trim(),t.trim())}catch(t){let r="There was an error parsing the license key.";throw rr.error(r),rr.error(t),new Error(r)}return"Wrote license key file. Registration successful."}throw new Error("Invalid key or company specified for license file.")}a(Tx,"setLicense");async function mx(){try{Jp.checkPermission()}catch(t){throw rr.error(t),new Error("You do not have permission to generate a fingerprint.")}let e={};try{e=await vc.generateFingerPrint()}catch(t){let r="Error generating fingerprint.";throw rr.error(r),rr.error(t),new Error(r)}return e}a(mx,"getFingerprint");async function kE(e,t){if(!e||!t)throw new Error("Invalid entries for License Key and Customer Company");console.log("Validating license input...");let r=vc.validateLicense(e,t);if(console.log("checking for valid license..."),!r.valid_license)throw new Error("Invalid license found.");if(console.log("checking valid license date..."),!r.valid_date)throw new Error("This License has expired.");if(console.log(`checking for valid machine license ${r.valid_machine}`),!r.valid_machine)throw new Error("This license is in use on another machine.");try{rr.info("writing license to disk"),await ux.writeFile(fx,JSON.stringify({license_key:e,company:t}))}catch(s){throw rr.error("Failed to write License"),s}return"Registration successful."}a(kE,"parseLicense");async function Rx(){let e=await Ax();return kE(e.HDB_LICENSE,e.CUSTOMER_COMPANY)}a(Rx,"register");async function Ax(){try{Jp.checkPermission()}catch(s){return console.error(s.message)}let e=await vc.generateFingerPrint(),t={properties:{CUSTOMER_COMPANY:{description:Qp.magenta("[COMPANY] Please enter your company name"),required:!0},HDB_LICENSE:{description:Qp.magenta(`[HDB_LICENSE] Your fingerprint is ${e} Please enter your license key`),required:!0}}};try{Xp.start()}catch(s){rr.error(s)}let r;try{r=await Sx(t)}catch(s){throw console.error("There was a problem prompting for registration input. Exiting."),s}return r}a(Ax,"promptForRegistration");async function Ox(){let e={registered:!1,version:null,storage_type:null,ram_allocation:null,license_expiration_date:null},t;try{t=await vc.getLicense()}catch(r){throw rr.error(`There was an error when searching licenses due to: ${r.message}`),r}if(Ex.isEmptyOrZeroLength(t))throw new Error("There were no licenses found.");if(e.registered=t.enterprise,e.version=dx.version(),e.storage_type=Bc.STORAGE_TYPES_ENUM.LMDB,e.ram_allocation=t.ram_allocation,isNaN(t.exp_date))e.license_expiration_date=t.enterprise?t.exp_date:null;else{let r=hx.utc(t.exp_date).format("YYYY-MM-DD");e.license_expiration_date=t.enterprise?r:null}return e}a(Ox,"getRegistrationInfo")});var eN=S((n3,jp)=>{"use strict";var px=_e(),Hc=class{constructor(t,r,s,n,i,o,c,_,u,l,E,d,h){this.port=t,o===null&&(o=void 0),this.server_name=r+px.SERVER_SUFFIX.HUB,this.pid_file=s,this.max_payload=1e7,this.jetstream={enabled:!1},this.tls={cert_file:n,key_file:i,ca_file:o,insecure:c},this.leafnodes={port:_,tls:{cert_file:n,key_file:i,ca_file:o,insecure:c}},this.cluster={name:u,port:l,routes:E,tls:{cert_file:n,key_file:i,ca_file:o,insecure:c}},this.accounts={SYS:{users:d},HDB:{users:h}},this.system_account="SYS"}};a(Hc,"HubConfigObject");jp.exports=Hc});var sN=S((i3,rN)=>{"use strict";var tN=_e(),qc=class{constructor(t,r,s,n,i,o,c,_,u,l,E){this.port=t,E===null&&(E=void 0),this.server_name=r+tN.SERVER_SUFFIX.LEAF,this.pid_file=s,this.max_payload=1e7,this.jetstream={enabled:!0,store_dir:n,domain:r+tN.SERVER_SUFFIX.LEAF},this.tls={cert_file:u,key_file:l,ca_file:E,insecure:!0},this.leafnodes={remotes:[{tls:{ca_file:E,insecure:!0},urls:i,account:"SYS"},{tls:{ca_file:E,insecure:!0},urls:o,account:"HDB"}]},this.accounts={SYS:{users:c},HDB:{users:_,jetstream:"enabled"}},this.system_account="SYS"}};a(qc,"LeafConfigObject");rN.exports=qc});var iN=S((a3,nN)=>{"use strict";var Gc=class{constructor(t,r){this.user=t,this.password=r}};a(Gc,"HdbUserObject");nN.exports=Gc});var oN=S((o3,aN)=>{"use strict";var Nx=_e(),Fc=class{constructor(t,r){this.user=t+Nx.SERVER_SUFFIX.ADMIN,this.password=r}};a(Fc,"SysUserObject");aN.exports=Fc});var KE=S((c3,uN)=>{"use strict";var wn=require("path"),xc=require("fs-extra"),gx=eN(),Ix=sN(),bx=iN(),wx=oN(),xE=xr(),Ln=b(),Dt=ur(),$c=T(),Vc=_e(),{CONFIG_PARAMS:we}=$c,Yc=I(),Kc=Y(),cN=Hr(),YE=at(),Cn="clustering",Cx=1e4,_N=5;uN.exports={generateNatsConfig:Lx,removeNatsConfig:Ux};async function Lx(e=!1,t=void 0){Kc.initSync();let r=Kc.get(we.ROOTPATH),s=wn.join(r,Cn,Vc.PID_FILES.HUB),n=wn.join(r,Cn,Vc.PID_FILES.LEAF),i=wn.join(r,Cn,"leaf"),o=wn.join(r,Cn,Vc.NATS_CONFIG_FILES.HUB_SERVER),c=wn.join(r,Cn,Vc.NATS_CONFIG_FILES.LEAF_SERVER),_=Dt.getConfigFromFile(we.CLUSTERING_TLS_CERTIFICATE),u=Dt.getConfigFromFile(we.CLUSTERING_TLS_PRIVATEKEY),l=Dt.getConfigFromFile(we.CLUSTERING_TLS_CERT_AUTH),E=Dt.getConfigFromFile(we.CLUSTERING_TLS_INSECURE),d=Dt.getConfigFromFile(we.CLUSTERING_NODENAME),h=Dt.getConfigFromFile(we.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT);await YE.checkNATSServerInstalled()||Wc("nats-server dependency is either missing or the wrong version. Run 'npm install' to fix");let m=await xE.listUsers(),R=Dt.getConfigFromFile(we.CLUSTERING_USER),C=await xE.getClusterUser();(Ln.isEmpty(C)||C.active!==!0)&&Wc(`invalid cluster user '${R}'`),e||(await kc(we.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),await kc(we.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT),await kc(we.CLUSTERING_HUBSERVER_NETWORK_PORT),await kc(we.CLUSTERING_LEAFSERVER_NETWORK_PORT));let L=[],B=[];for(let[_a,wr]of m.entries())wr.role.role===$c.ROLE_TYPES_ENUM.CLUSTER_USER&&wr.active&&(L.push(new wx(wr.username,cN.decrypt(wr.hash))),B.push(new bx(wr.username,cN.decrypt(wr.hash))));let z=[],{hub_routes:V}=Dt.getClusteringRoutes();if(!Ln.isEmptyOrZeroLength(V))for(let _a of V)z.push(`tls://${C.sys_name_encoded}:${C.uri_encoded_d_hash}@${_a.host}:${_a.port}`);let Q=new gx(Dt.getConfigFromFile(we.CLUSTERING_HUBSERVER_NETWORK_PORT),d,s,_,u,l,E,h,Dt.getConfigFromFile(we.CLUSTERING_HUBSERVER_CLUSTER_NAME),Dt.getConfigFromFile(we.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),z,L,B);t=Ln.isEmpty(t)?void 0:t.toLowerCase(),(t===void 0||t===$c.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase())&&(await xc.writeJson(o,Q),Yc.trace(`Hub server config written to ${o}`));let ke=`tls://${C.sys_name_encoded}:${C.uri_encoded_d_hash}@0.0.0.0:${h}`,$e=`tls://${C.uri_encoded_name}:${C.uri_encoded_d_hash}@0.0.0.0:${h}`,ca=new Ix(Dt.getConfigFromFile(we.CLUSTERING_LEAFSERVER_NETWORK_PORT),d,n,i,[ke],[$e],L,B,_,u,l,E);(t===void 0||t===$c.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())&&(await xc.writeJson(c,ca),Yc.trace(`Leaf server config written to ${c}`))}a(Lx,"generateNatsConfig");async function kc(e){let t=Kc.get(e);Ln.isEmpty(t)&&Wc(`port undefined for '${e}'`),await Ln.isPortTaken(t)&&Wc(`'${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.`)}a(kc,"isPortAvailable");function Wc(e){let t=`Error generating clustering config: ${e}`;Yc.error(t),console.error(t),process.exit(1)}a(Wc,"generateNatsConfigError");async function Ux(e){let{port:t,config_file:r}=YE.getServerConfig(e),{username:s,decrypt_hash:n}=await xE.getClusterUser(),i=0,o=500;for(;i<_N;){try{let u=await YE.createConnection(t,s,n,!1);if(u.protocol.connected===!0){u.close();break}}catch(u){Yc.trace(`removeNatsConfig waiting for ${e}. Caught and swallowed error ${u}`)}if(i++,i>=_N)throw new Error(`Operations API timed out attempting to connect to ${e}. This is commonly caused by incorrect clustering config. Check the ${e} log for further details.`);await Ln.async_set_timeout(o*i)}let c="0".repeat(Cx),_=wn.join(Kc.get(we.ROOTPATH),Cn,r);await xc.writeFile(_,c),await xc.remove(_)}a(Ux,"removeNatsConfig")});var Jc=S((_3,TN)=>{"use strict";var se=Y(),lN=mi(),w=T(),WE=_e(),Ae=require("path"),{PACKAGE_ROOT:Qc}=T(),Ee="/dev/null",Un=Ae.join(Qc,"launchServiceScripts"),EN=Ae.join(Qc,"utility/scripts"),yx=Ae.join(EN,w.HDB_RESTART_SCRIPT),dN=Ae.resolve(Qc,"dependencies",`${process.platform}-${process.arch}`,WE.NATS_BINARY_NAME),He,qe;function sr(){(He===void 0||qe===void 0)&&(se.initSync(),He=se.get(w.HDB_SETTINGS_NAMES.LOG_TO_FILE),qe=se.get(w.HDB_SETTINGS_NAMES.LOG_PATH_KEY))}a(sr,"initLogConfig");function hN(){sr();let e=Ae.join(qe,w.PROCESS_LOG_NAMES.IPC),t={name:w.PROCESS_DESCRIPTORS.IPC,exec_mode:"fork",env:{[w.PROCESS_NAME_ENV_PROP]:w.PROCESS_DESCRIPTORS.IPC},merge_logs:!0,out_file:e,error_file:e,instances:1,cwd:w.SERVICE_SERVERS_CWD.IPC};return He||(t.out_file=Ee,t.error_file=Ee),{...t,script:w.SERVICE_SERVERS.IPC}}a(hN,"generateIPCServerConfig");function SN(){sr(),se.initSync(),He=se.get(w.HDB_SETTINGS_NAMES.LOG_TO_FILE),qe=se.get(w.HDB_SETTINGS_NAMES.LOG_PATH_KEY);let e=Ae.join(qe,w.PROCESS_LOG_NAMES.HDB),t=lN.licenseSearch(),r=t.ram_allocation?w.MEM_SETTING_KEY+t.ram_allocation:w.MEM_SETTING_KEY+w.RAM_ALLOCATION_ENUM.DEFAULT,s={name:w.PROCESS_DESCRIPTORS.HDB,script:w.LAUNCH_SERVICE_SCRIPTS.HDB,exec_mode:"cluster",env:{[w.PROCESS_NAME_ENV_PROP]:w.PROCESS_DESCRIPTORS.HDB},merge_logs:!0,out_file:e,error_file:e,instances:se.get(w.CONFIG_PARAMS.HTTP_THREADS),node_args:r,cwd:Un};return He||(s.out_file=Ee,s.error_file=Ee),s}a(SN,"generateHDBServerConfig");function fN(){sr(),se.initSync(),He=se.get(w.HDB_SETTINGS_NAMES.LOG_TO_FILE),qe=se.get(w.HDB_SETTINGS_NAMES.LOG_PATH_KEY);let e=Ae.join(qe,w.PROCESS_LOG_NAMES.CUSTOM_FUNCTIONS),t=lN.licenseSearch(),r=t.ram_allocation?w.MEM_SETTING_KEY+t.ram_allocation:w.MEM_SETTING_KEY+w.RAM_ALLOCATION_ENUM.DEFAULT,s={name:w.PROCESS_DESCRIPTORS.CUSTOM_FUNCTIONS,script:w.LAUNCH_SERVICE_SCRIPTS.CUSTOM_FUNCTIONS,exec_mode:"cluster",env:{[w.PROCESS_NAME_ENV_PROP]:w.PROCESS_DESCRIPTORS.CUSTOM_FUNCTIONS},merge_logs:!0,out_file:e,error_file:e,instances:se.get(w.CONFIG_PARAMS.HTTP_THREADS),node_args:r,cwd:Un};return He||(s.out_file=Ee,s.error_file=Ee),s}a(fN,"generateCFServerConfig");function Dx(){sr(),se.initSync(),He=se.get(w.HDB_SETTINGS_NAMES.LOG_TO_FILE),qe=se.get(w.HDB_SETTINGS_NAMES.LOG_PATH_KEY);let e=se.get(w.CONFIG_PARAMS.ROOTPATH),t=Ae.join(e,"clustering",WE.NATS_CONFIG_FILES.HUB_SERVER),r=Ae.join(qe,w.PROCESS_LOG_NAMES.CLUSTERING_HUB),s={name:w.PROCESS_DESCRIPTORS.CLUSTERING_HUB,script:dN,args:`-c ${t}`,exec_mode:"fork",env:{[w.PROCESS_NAME_ENV_PROP]:w.PROCESS_DESCRIPTORS.CLUSTERING_HUB},merge_logs:!0,out_file:r,error_file:r,instances:1};return He||(s.out_file=Ee,s.error_file=Ee),s}a(Dx,"generateNatsHubServerConfig");function Mx(){sr(),se.initSync(),He=se.get(w.HDB_SETTINGS_NAMES.LOG_TO_FILE),qe=se.get(w.HDB_SETTINGS_NAMES.LOG_PATH_KEY);let e=se.get(w.CONFIG_PARAMS.ROOTPATH),t=Ae.join(e,"clustering",WE.NATS_CONFIG_FILES.LEAF_SERVER),r=Ae.join(qe,w.PROCESS_LOG_NAMES.CLUSTERING_LEAF),s={name:w.PROCESS_DESCRIPTORS.CLUSTERING_LEAF,script:dN,args:`-c ${t}`,exec_mode:"fork",env:{[w.PROCESS_NAME_ENV_PROP]:w.PROCESS_DESCRIPTORS.CLUSTERING_LEAF},merge_logs:!0,out_file:r,error_file:r,instances:1};return He||(s.out_file=Ee,s.error_file=Ee),s}a(Mx,"generateNatsLeafServerConfig");function Px(){sr(),se.initSync();let e=Ae.join(qe,w.PROCESS_LOG_NAMES.CLUSTERING_INGEST_SERVICE),t={name:w.PROCESS_DESCRIPTORS.CLUSTERING_INGEST_SERVICE,script:w.LAUNCH_SERVICE_SCRIPTS.NATS_INGEST_SERVICE,exec_mode:"cluster",env:{[w.PROCESS_NAME_ENV_PROP]:w.PROCESS_DESCRIPTORS.CLUSTERING_INGEST_SERVICE},merge_logs:!0,out_file:e,error_file:e,instances:1,cwd:Un};return He||(t.out_file=Ee,t.error_file=Ee),t}a(Px,"generateNatsIngestServiceConfig");function Bx(){sr(),se.initSync();let e=Ae.join(qe,w.PROCESS_LOG_NAMES.CLUSTERING_REPLY_SERVICE),t={name:w.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE,script:w.LAUNCH_SERVICE_SCRIPTS.NATS_REPLY_SERVICE,exec_mode:"cluster",env:{[w.PROCESS_NAME_ENV_PROP]:w.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE},merge_logs:!0,out_file:e,error_file:e,instances:1,cwd:Un};return He||(t.out_file=Ee,t.error_file=Ee),t}a(Bx,"generateNatsReplyServiceConfig");function vx(){sr(),se.initSync();let e=Ae.join(qe,w.PROCESS_LOG_NAMES.CLUSTERING_UPGRADE),t={name:w.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0,script:w.LAUNCH_SERVICE_SCRIPTS.NODES_UPGRADE_4_0_0,exec_mode:"fork",env:{[w.PROCESS_NAME_ENV_PROP]:w.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0},merge_logs:!0,out_file:e,error_file:e,instances:1,cwd:Un,autorestart:!1};return He||(t.out_file=Ee,t.error_file=Ee),t}a(vx,"generateClusteringUpgradeV4ServiceConfig");function Hx(){sr();let e=Ae.join(qe,w.PROCESS_LOG_NAMES.PM2),t={name:w.PROCESS_DESCRIPTORS.RESTART_HDB,exec_mode:"fork",env:{[w.PROCESS_NAME_ENV_PROP]:w.PROCESS_DESCRIPTORS.RESTART_HDB},merge_logs:!0,out_file:e,error_file:e,instances:1,autorestart:!1,cwd:EN};return He||(t.out_file=Ee,t.error_file=Ee),{...t,script:yx}}a(Hx,"generateRestart");function qx(e){sr();let t=Ae.join(qe,w.PROCESS_LOG_NAMES.JOBS),r=Ae.join(Qc,"server/jobs"),s={name:`JOB-${e}`,exec_mode:"fork",env:{[w.PROCESS_NAME_ENV_PROP]:`JOB-${e}`},merge_logs:!0,out_file:t,error_file:t,instances:1,cwd:Un,autorestart:!1};return He||(s.out_file=Ee,s.error_file=Ee),{...s,script:Ae.join(r,"jobProcess.js")}}a(qx,"generateJobConfig");function Gx(){return{apps:[hN(),SN(),fN()]}}a(Gx,"generateAllServiceConfigs");TN.exports={generateAllServiceConfigs:Gx,generateIPCServerConfig:hN,generateHDBServerConfig:SN,generateCFServerConfig:fN,generateRestart:Hx,generateNatsHubServerConfig:Dx,generateNatsLeafServerConfig:Mx,generateNatsIngestServiceConfig:Px,generateNatsReplyServiceConfig:Bx,generateClusteringUpgradeV4ServiceConfig:vx,generateJobConfig:qx}});var ki=S((u3,CN)=>{"use strict";var P=T(),Xc=b(),Vi=KE(),Zc=at(),Fx=_e(),$=require("pm2"),Vx=require("fs-extra"),Ar=Jc(),ut=Y(),Or=I(),kx=Jc(),$x=bs(),xx=require("util"),RN=xx.promisify(require("child_process").exec),AN=require("path");CN.exports={start:Us,stop:jc,reload:pN,restart:NN,list:JE,describe:e_,connect:nr,kill:IN,startAllServices:eY,startService:zc,getUniqueServicesList:XE,restartAllServices:tY,stopAllServices:rY,isServiceRegistered:bN,reloadStopStart:QE,restartHdb:gN,deleteProcess:zx,configureLogRotate:iY,startClustering:wN,isHdbRestartRunning:jx,isClusteringRunning:oY,stopClustering:aY,reloadClustering:cY};var{PACKAGE_ROOT:Yx}=T(),Kx="2.7.0",ON=AN.join(Yx,"node_modules/pm2/bin/pm2"),Wx="Log rotate installed.",Qx="Error installing log rotate.",Jx="Log rotate updated.",Xx="Error updating log rotate.",Zx="The number of HarperDB processes running is different from the settings value. To restart and update the number HarperDB processes running you must stop and then start HarperDB";function nr(){return new Promise((e,t)=>{$.connect((r,s)=>{r&&t(r),e(s)})})}a(nr,"connect");function Us(e){return new Promise(async(t,r)=>{try{await nr()}catch(s){r(s)}$.start(e,(s,n)=>{s&&($.disconnect(),r(s)),$.disconnect(),t(n)})})}a(Us,"start");function jc(e){return new Promise(async(t,r)=>{try{await nr()}catch(s){r(s)}$.stop(e,(s,n)=>{s&&($.disconnect(),r(s)),$.delete(e,(i,o)=>{i&&($.disconnect(),r(s)),$.disconnect(),t(o)})})})}a(jc,"stop");function pN(e){return new Promise(async(t,r)=>{try{await nr()}catch(s){r(s)}$.reload(e,(s,n)=>{s&&($.disconnect(),r(s)),$.disconnect(),t(n)})})}a(pN,"reload");function NN(e){return new Promise(async(t,r)=>{try{await nr()}catch(s){r(s)}$.restart(e,(s,n)=>{s&&($.disconnect(),r(s)),$.disconnect(),t(n)})})}a(NN,"restart");function zx(e){return new Promise(async(t,r)=>{try{await nr()}catch(s){r(s)}$.delete(e,(s,n)=>{s&&($.disconnect(),r(s)),$.disconnect(),t(n)})})}a(zx,"deleteProcess");async function gN(){await Us(kx.generateRestart())}a(gN,"restartHdb");async function jx(){let e=await JE();for(let t in e)if(e[t].name===P.PROCESS_DESCRIPTORS.RESTART_HDB)return!0;return!1}a(jx,"isHdbRestartRunning");function JE(){return new Promise(async(e,t)=>{try{await nr()}catch(r){t(r)}$.list((r,s)=>{r&&($.disconnect(),t(r)),$.disconnect(),e(s)})})}a(JE,"list");function e_(e){return new Promise(async(t,r)=>{try{await nr()}catch(s){r(s)}$.describe(e,(s,n)=>{s&&($.disconnect(),r(s)),$.disconnect(),t(n)})})}a(e_,"describe");function IN(){return new Promise(async(e,t)=>{try{await nr()}catch(r){t(r)}$.killDaemon((r,s)=>{r&&($.disconnect(),t(r)),$.disconnect(),e(s)})})}a(IN,"kill");async function eY(){try{await wN(),await Us(Ar.generateAllServiceConfigs())}catch(e){throw $.disconnect(),e}}a(eY,"startAllServices");async function zc(e){try{let t;switch(e=e.toLowerCase(),e){case P.PROCESS_DESCRIPTORS.IPC.toLowerCase():t=Ar.generateIPCServerConfig();break;case P.PROCESS_DESCRIPTORS.HDB.toLowerCase():t=Ar.generateHDBServerConfig();break;case P.PROCESS_DESCRIPTORS.CUSTOM_FUNCTIONS.toLowerCase():t=Ar.generateCFServerConfig();break;case P.PROCESS_DESCRIPTORS.CLUSTERING_INGEST_SERVICE.toLowerCase():t=Ar.generateNatsIngestServiceConfig();break;case P.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE.toLowerCase():t=Ar.generateNatsReplyServiceConfig();break;case P.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase():t=Ar.generateNatsHubServerConfig(),await Us(t),await Vi.removeNatsConfig(e);return;case P.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase():t=Ar.generateNatsLeafServerConfig(),await Us(t),await Vi.removeNatsConfig(e);return;case P.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0.toLowerCase():t=Ar.generateClusteringUpgradeV4ServiceConfig();break;default:throw new Error(`Start service called with unknown service config: ${e}`)}await Us(t)}catch(t){throw $.disconnect(),t}}a(zc,"startService");async function XE(){try{let e=await JE(),t={};for(let r=0,s=e.length;r<s;r++){let n=e[r];t[n.name]===void 0&&(t[n.name]={name:n.name,exec_mode:n.pm2_env.exec_mode})}return t}catch(e){throw $.disconnect(),e}}a(XE,"getUniqueServicesList");async function tY(e=[]){try{let t=!1,r=await XE();for(let s=0,n=Object.values(r).length;s<n;s++){let i=Object.values(r)[s],o=i.name;e.includes(o)||(i.exec_mode==="cluster_mode"?o===P.PROCESS_DESCRIPTORS.HDB?t=!0:await QE(o):await NN(o))}t&&await QE(P.PROCESS_DESCRIPTORS.HDB)}catch(t){throw $.disconnect(),t}}a(tY,"restartAllServices");async function rY(){try{let e=await XE();for(let t=0,r=Object.values(e).length;t<r;t++){let s=Object.values(e)[t];await jc(s.name)}if(await IN(),ut.get(P.CONFIG_PARAMS.OPERATIONSAPI_FOREGROUND)===!0){let t=(await Vx.readFile(AN.join(ut.get(P.HDB_SETTINGS_NAMES.HDB_ROOT_KEY),P.FOREGROUND_PID_FILE))).toString();try{process.kill(t,"SIGTERM")}catch(r){Or.warn(`Error terminating foreground process: ${r}`)}}}catch(e){throw $.disconnect(),e}}a(rY,"stopAllServices");async function bN(e){return!Xc.isEmptyOrZeroLength(await e_(e))}a(bN,"isServiceRegistered");async function QE(e){let t=e===P.PROCESS_DESCRIPTORS.HDB?ut.get(P.HDB_SETTINGS_NAMES.MAX_HDB_PROCESSES):ut.get(P.HDB_SETTINGS_NAMES.MAX_CUSTOM_FUNCTION_PROCESSES),r=await e_(e),s=Xc.isEmptyOrZeroLength(r)?0:r.length;t!==s?e===P.PROCESS_DESCRIPTORS.HDB?Or.error(Zx):(await jc(e),await zc(e)):e===P.PROCESS_DESCRIPTORS.HDB?await gN():await pN(e)}a(QE,"reloadStopStart");function sY(){return new Promise(async(e,t)=>{try{await nr()}catch(r){t(r)}$.stop(P.PROCESS_DESCRIPTORS.PM2_LOGROTATE,(r,s)=>{r&&($.disconnect(),t(r)),$.disconnect(),e(s)})})}a(sY,"stopLogrotate");async function nY(){let{stdout:e,stderr:t}=await RN(`${process.platform==="win32"?"node":""} ${ON} install pm2-logrotate@${Kx}`);if(Or.debug(`loadLogRotate stdout: ${e}`),t)throw Or.error(Qx),t;Or.info(Wx)}a(nY,"installLogRotate");async function mN(){let e={max_size:ut.get(P.HDB_SETTINGS_NAMES.LOG_ROTATE_MAX_SIZE),retain:ut.get(P.HDB_SETTINGS_NAMES.LOG_ROTATE_RETAIN),compress:ut.get(P.HDB_SETTINGS_NAMES.LOG_ROTATE_COMPRESS),dateFormat:ut.get(P.HDB_SETTINGS_NAMES.LOG_ROTATE_DATE_FORMAT),rotateModule:ut.get(P.HDB_SETTINGS_NAMES.LOG_ROTATE_ROTATE_MODULE),workerInterval:ut.get(P.HDB_SETTINGS_NAMES.LOG_ROTATE_WORKER_INTERVAL),rotateInterval:ut.get(P.HDB_SETTINGS_NAMES.LOG_ROTATE_ROTATE_INTERVAL),TZ:ut.get(P.HDB_SETTINGS_NAMES.LOG_ROTATE_TIMEZONE)},t="";for(let n in e)t+=`${process.platform==="win32"?"node":""} ${ON} set pm2-logrotate:${n} ${e[n]}`,n!=="TZ"&&(t+=" && ");let{stdout:r,stderr:s}=await RN(t);if(Or.debug(`updateLogRotateConfig stdout: ${r}`),s)throw Or.error(Xx),s;Or.info(Jx)}a(mN,"updateLogRotateConfig");async function iY(){ut.initSync();let e=Xc.autoCastBoolean(ut.get(P.HDB_SETTINGS_NAMES.LOG_ROTATE)),t=await e_(P.PROCESS_DESCRIPTORS.PM2_LOGROTATE),r,s=!1;if(Xc.isEmptyOrZeroLength(t)||(s=!0,r=t[0].pm2_env.status),e&&!s){await nY(),await mN();return}if(e&&s){await Us(P.PROCESS_DESCRIPTORS.PM2_LOGROTATE),await mN();return}!e&&r===P.PM2_PROCESS_STATUSES.ONLINE&&await sY()}a(iY,"configureLogRotate");async function wN(){for(let t in P.CLUSTERING_PROCESSES){let r=P.CLUSTERING_PROCESSES[t];await zc(r)}await Zc.createWorkQueueStream(Fx.WORK_QUEUE_CONSUMER_NAMES),await Zc.updateNodeNameLocalStreams();let e=await $x.getAllNodeRecords();for(let t=0,r=e.length;t<r;t++)if(e[t].system_info?.hdb_version===P.PRE_4_0_0_VERSION){Or.info("Starting clustering upgrade 4.0.0 process"),await zc(P.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0);break}}a(wN,"startClustering");async function aY(){for(let e in P.CLUSTERING_PROCESSES){let t=P.CLUSTERING_PROCESSES[e];await jc(t)}}a(aY,"stopClustering");async function oY(){for(let e in P.CLUSTERING_PROCESSES){let t=P.CLUSTERING_PROCESSES[e];if(await bN(t)===!1)return!1}return!0}a(oY,"isClusteringRunning");async function cY(){await Vi.generateNatsConfig(!0),await Zc.reloadNATSHub(),await Zc.reloadNATSLeaf(),await Vi.removeNatsConfig(P.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase()),await Vi.removeNatsConfig(P.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())}a(cY,"reloadClustering")});var td=S((l3,MN)=>{"use strict";var y=T(),K=I(),t_=b(),_Y=z_(),ZE=KE(),ed=at(),uY=_e(),UN=require("minimist"),{handleHDBError:zE,hdb_errors:lY}=D(),$i=ur(),{HTTP_STATUS_CODES:jE}=lY,G,LN=`Restarting HarperDB. This may take up to ${y.RESTART_TIMEOUT_MS/1e3} seconds.`,ys="HarperDB is currently restarting and must complete before another HarperDB restart can be initialized.",EY="Invalid service",dY="'service' is required",hY="Restarting all services",SY="Clustering is not enabled so cannot be restarted";MN.exports={stop:TY,restartProcesses:fY,restartService:yN};async function fY(){K.createLogFile(y.PROCESS_LOG_NAMES.CLI,y.PROCESS_DESCRIPTORS.STOP);try{G===void 0&&(G=ki());let e=_Y(Object.keys(y.CONFIG_PARAM_MAP),!0);t_.isEmptyOrZeroLength(Object.keys(e))||$i.updateConfigValue(void 0,void 0,e,!0,!0);let t=$i.getConfigFromFile(y.CONFIG_PARAMS.CLUSTERING_ENABLED),r=$i.getConfigFromFile(y.CONFIG_PARAMS.CUSTOMFUNCTIONS_ENABLED),s=UN(process.argv);if(!t_.isEmpty(s.service)){if(typeof s.service!="string"){let c=`Restart service argument expected a string but received: ${s.service}`;return K.error(c),c}let o=s.service.split(",");for(let c of o){let _=c.toLowerCase();if(_===y.HDB_PROC_DESCRIPTOR.toLowerCase()&&await G.isHdbRestartRunning()===!0){K.notify(ys),console.error(ys);continue}if(y.PROCESS_DESCRIPTORS_VALIDATE[_]===void 0){console.error(`Restart received unrecognized service command argument: ${_}`),K.error(`Restart received unrecognized service command argument: ${_}`);continue}let u=y.PROCESS_DESCRIPTORS_VALIDATE[_];if(console.log(`Restarting ${u}`),K.trace(`Restarting ${u}`),u===y.PROCESS_DESCRIPTORS.PM2_LOGROTATE)await G.configureLogRotate();else if(_.toLowerCase().includes("clustering"))await yn(_);else if(await G.isServiceRegistered(u))u===y.PROCESS_DESCRIPTORS.CUSTOM_FUNCTIONS&&!r?(await G.stop(y.PROCESS_DESCRIPTORS.CUSTOM_FUNCTIONS),K.trace(`Stopping ${y.PROCESS_DESCRIPTORS.CUSTOM_FUNCTIONS}`)):await yN({service:u});else if(u===y.PROCESS_DESCRIPTORS.CUSTOM_FUNCTIONS)if(r)await G.startService(u),K.trace(`Starting ${u}`);else{let l=`${u} is not enabled in harperdb-config.yaml and cannot be restarted.`;K.error(l),console.log(l)}else await G.startService(u);K.notify(`${u} successfully restarted.`)}return}if(await G.isHdbRestartRunning()===!0)return K.notify(ys),console.error(ys),ys;console.log(LN),t&&await DN();let n=await G.isServiceRegistered(y.PROCESS_DESCRIPTORS.CUSTOM_FUNCTIONS);r&&!n&&(await G.startService(y.PROCESS_DESCRIPTORS.CUSTOM_FUNCTIONS),K.trace(`Starting ${y.PROCESS_DESCRIPTORS.CUSTOM_FUNCTIONS}`));let i=[y.PROCESS_DESCRIPTORS.CLUSTERING_HUB,y.PROCESS_DESCRIPTORS.CLUSTERING_LEAF,y.PROCESS_DESCRIPTORS.CLUSTERING_INGEST_SERVICE,y.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE];return!r&&n&&(i.push(y.PROCESS_DESCRIPTORS.CUSTOM_FUNCTIONS),await G.stop(y.PROCESS_DESCRIPTORS.CUSTOM_FUNCTIONS),K.trace(`Stopping ${y.PROCESS_DESCRIPTORS.CUSTOM_FUNCTIONS}`)),await G.configureLogRotate(),K.notify(hY),await G.restartAllServices(i),LN}catch(e){let t=`There was an error restarting HarperDB. ${e}`;return K.error(t),t}}a(fY,"restartProcesses");async function yN(e){if(K.createLogFile(y.PROCESS_LOG_NAMES.CLI,y.PROCESS_DESCRIPTORS.STOP),G===void 0&&(G=ki()),t_.isEmpty(e.service))throw zE(new Error,dY,jE.BAD_REQUEST,void 0,void 0,!0);let t=e.service.toLowerCase();if(y.PROCESS_DESCRIPTORS_VALIDATE[t]===void 0)throw zE(new Error,EY,jE.BAD_REQUEST,void 0,void 0,!0);let r=$i.getConfigFromFile(y.CONFIG_PARAMS.CUSTOMFUNCTIONS_ENABLED),s=y.PROCESS_DESCRIPTORS_VALIDATE[t];if(s===y.PROCESS_DESCRIPTORS.HDB){if(await G.isHdbRestartRunning()===!0)return K.notify(ys),ys;await G.reloadStopStart(s)}else if(s===y.PROCESS_DESCRIPTORS.PM2_LOGROTATE)await G.configureLogRotate();else if(s.toLowerCase().includes("clustering"))await yn(s);else if(s===y.PROCESS_DESCRIPTORS.CUSTOM_FUNCTIONS||s===y.SERVICES.CUSTOM_FUNCTIONS){let i=await G.isServiceRegistered(s);if(r)i?(await G.reloadStopStart(s),K.trace(`Reloading ${s}`)):(await G.startService(s),K.trace(`Starting ${s}`));else if(!r&&i)await G.stop(s),K.trace(`Stopping ${s}`);else{let o=`${s} is not enabled in harperdb-config.yaml and cannot be restarted.`;throw K.error(o),zE(new Error,o,jE.BAD_REQUEST,void 0,void 0,!0)}}else await G.restart(s);let n=`Restarting ${s}`;return K.notify(n),n}a(yN,"restartService");async function TY(){K.createLogFile(y.PROCESS_LOG_NAMES.CLI,y.PROCESS_DESCRIPTORS.STOP);try{G===void 0&&(G=ki());let e=UN(process.argv);if(t_.isEmpty(e.service))console.log("Stopping HarperDB."),await G.stopAllServices(),K.notify("HarperDB has stopped");else{if(typeof e.service!="string"){let r=`Stop service argument expected a string but received: ${e.service}`;K.error(r),console.log(r)}let t=e.service.split(",");for(let r of t){let s=r.toLowerCase();if(y.PROCESS_DESCRIPTORS_VALIDATE[s]===void 0){K.error(`Stop received unrecognized service command argument: ${s}`);continue}s==="clustering"?await G.stopClustering():await G.stop(y.PROCESS_DESCRIPTORS_VALIDATE[s]);let n=`${y.PROCESS_DESCRIPTORS_VALIDATE[s]} successfully stopped.`;K.notify(n),console.log(n)}}}catch(e){throw console.error(e),e}}a(TY,"stop");async function DN(){await yn(y.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await yn(y.PROCESS_DESCRIPTORS.CLUSTERING_LEAF),await yn(y.PROCESS_DESCRIPTORS.CLUSTERING_INGEST_SERVICE),await yn(y.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE),await ed.updateNodeNameLocalStreams(),await ed.closeConnection()}a(DN,"restartAllClusteringServices");async function yn(e){e=y.PROCESS_DESCRIPTORS_VALIDATE[e.toLowerCase()];let t=$i.getConfigFromFile(y.CONFIG_PARAMS.CLUSTERING_ENABLED),r=e==="clustering",s=e==="clustering config",n=r?void 0:await G.isServiceRegistered(e),i=r||s?await G.isClusteringRunning():void 0;switch(!0){case s:if(!i){K.error(SY);break}await G.reloadClustering();break;case(r&&i&&!t):await G.stopClustering();break;case(r&&!i&&t):await G.startClustering();break;case(r&&i&&t):await DN();break;case(r&&!i&&!t):K.error(`${e} is not enabled in harperdb-config.yaml and cannot be restarted.`);break;case(n&&!t):await G.stop(e),K.trace(`Stopping ${e}`);break;case(!n&&t):e!==y.PROCESS_DESCRIPTORS.CLUSTERING_INGEST_SERVICE&&e!==y.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE&&await ZE.generateNatsConfig(!0,e),await G.startService(e),K.trace(`Starting ${e}`),e===y.PROCESS_DESCRIPTORS.CLUSTERING_LEAF&&await ed.createWorkQueueStream(uY.WORK_QUEUE_CONSUMER_NAMES);break;case(!n&&!t):K.error(`${e} is not enabled in harperdb-config.yaml and cannot be restarted.`);break;case(n&&t):e===y.PROCESS_DESCRIPTORS.CLUSTERING_INGEST_SERVICE||e===y.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE?await G.reload(e):(await ZE.generateNatsConfig(!0,e),await G.restart(e),await ZE.removeNatsConfig(e));break;default:K.error(`Error restarting ${e}`)}}a(yn,"restartClustering")});var xN=S((d3,$N)=>{"use strict";var E3=require("lodash"),Ze=T(),{handleHDBError:PN,hdb_errors:mY}=D(),{HDB_ERROR_MSGS:RY,HTTP_STATUS_CODES:AY}=mY,rd=I();$N.exports={getRolePermissions:pY};var Ds=Object.create(null),OY=a(e=>({key:e,perms:{}}),"perms_template_obj"),qN=a((e=!1)=>({describe:e,tables:{}}),"schema_perms_template"),GN=a((e=!1,t=!1,r=!1,s=!1)=>({[Ze.PERMS_CRUD_ENUM.READ]:e,[Ze.PERMS_CRUD_ENUM.INSERT]:t,[Ze.PERMS_CRUD_ENUM.UPDATE]:r,[Ze.PERMS_CRUD_ENUM.DELETE]:s}),"permissions_template"),sd=a((e=!1,t=!1,r=!1,s=!1,n=!1)=>({attribute_permissions:[],describe:e,...GN(t,r,s,n)}),"table_perms_template"),BN=a((e,t=GN())=>({attribute_name:e,describe:kN(t),[xi]:t[xi],[nd]:t[nd],[id]:t[id]}),"attr_perms_template"),vN=a((e,t=!1)=>({attribute_name:e,describe:t,[xi]:t}),"timestamp_attr_perms_template"),{READ:xi,INSERT:nd,UPDATE:id}=Ze.PERMS_CRUD_ENUM,FN=Object.values(Ze.PERMS_CRUD_ENUM),VN=[xi,nd,id];function pY(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[Ze.SYSTEM_SCHEMA_NAME],t=e.role;let s=JSON.stringify([e.__updatedtime__,r]);if(Ds[t]&&Ds[t].key===s)return Ds[t].perms;let n=NY(e,r);return Ds[t]?Ds[t].key=s:Ds[t]=OY(s),Ds[t].perms=n,n}catch(r){if(!e[Ze.TIME_STAMP_NAMES_ENUM.UPDATED_TIME]||e[Ze.TIME_STAMP_NAMES_ENUM.UPDATED_TIME]<Ze.PERMS_UPDATE_RELEASE_TIMESTAMP){let s=`Role permissions for role '${t}' must be updated to align with new structure from the 2.2.0 release.`;throw rd.error(s),rd.debug(r),PN(new Error,RY.OUTDATED_PERMS_TRANSLATION_ERROR,AY.BAD_REQUEST)}else{let s=`There was an error while translating role permissions for role: ${t}.
|
|
8
|
+
${r.stack}`;throw rd.error(s),PN(new Error)}}}a(pY,"getRolePermissions");function NY(e,t){let r=Object.create(null);r.super_user=!1;let s=e.permission;r[Ze.SYSTEM_SCHEMA_NAME]=s[Ze.SYSTEM_SCHEMA_NAME],r.structure_user=s.structure_user;let n=Array.isArray(e.permission.structure_user)||e.permission.structure_user===!0?e.permission.structure_user:[];return Object.keys(t).forEach(i=>{if(n===!0||n.indexOf(i)>-1){r[i]=gY(t[i]);return}r[i]=qN(),s[i]?Object.keys(t[i]).forEach(o=>{if(s[i].tables[o]){let c=s[i].tables[o],_=t[i][o],u=IY(c,_);r[i].describe||FN.forEach(l=>{u[l]&&(r[i].describe=!0)}),r[i].tables[o]=u}else r[i].tables[o]=sd()}):Object.keys(t[i]).forEach(o=>{r[i].tables[o]=sd()})}),r}a(NY,"translateRolePermissions");function gY(e){let t=qN(!0);return Object.keys(e).forEach(r=>{t.tables[r]=sd(!0,!0,!0,!0,!0)}),t}a(gY,"createStructureUserPermissions");function IY(e,t){let{attribute_permissions:r}=e;if(r.length>0){let n=Object.assign({},e);n.attribute_permissions=[];let i=r.reduce((u,l)=>{let{attribute_name:E}=l,d=l;return Ze.TIME_STAMP_NAMES.includes(E)&&(d=vN(E,l[xi])),u[E]=d,u},{}),o=t[Ze.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_HASH_ATTRIBUTE_KEY],c=!!i[o],_=BN(o);return t.attributes.forEach(({attribute:u})=>{if(i[u]){let l=i[u];l.describe=kN(l),n.attribute_permissions.push(l),c||bY(l,_)}else if(u!==o){let l;Ze.TIME_STAMP_NAMES.includes(u)?l=vN(u):l=BN(u),n.attribute_permissions.push(l)}}),c||n.attribute_permissions.push(_),n.describe=HN(n),n}else return e.describe=HN(e),e}a(IY,"getTableAttrPerms");function HN(e){return FN.filter(t=>e[t]).length>0}a(HN,"getSchemaTableDescribePerm");function kN(e){return VN.filter(t=>e[t]).length>0}a(kN,"getAttributeDescribePerm");function bY(e,t){VN.forEach(r=>{e[r]&&!t[r]&&(t[r]=!0,t.describe=!0)})}a(bY,"checkForHashPerms")});var ZN=S((h3,XN)=>{"use strict";var Te=require("joi"),YN=require("fs-extra"),KN=require("path"),Dn=de(),WN=Y(),QN=T(),JN=I(),{hdb_errors:wY}=D(),{HDB_ERROR_MSGS:lt}=wY,Zr=/^[a-zA-Z0-9-_]+$/;XN.exports={getDropCustomFunctionValidator:LY,setCustomFunctionValidator:UY,addCustomFunctionProjectValidator:yY,dropCustomFunctionProjectValidator:DY,packageCustomFunctionProjectValidator:MY,deployCustomFunctionProjectValidator:PY};function Yi(e,t,r){try{let s=WN.get(QN.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY),n=KN.join(s,t);return YN.existsSync(n)?e?t:r.message(lt.PROJECT_EXISTS):e?r.message(lt.NO_PROJECT):t}catch(s){return JN.error(s),r.message(lt.VALIDATION_ERR)}}a(Yi,"checkProjectExists");function CY(e,t,r,s){try{let n=WN.get(QN.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY),i=KN.join(n,e,t,r+".js");return YN.existsSync(i)?r:s.message(lt.NO_FILE)}catch(n){return JN.error(n),s.message(lt.VALIDATION_ERR)}}a(CY,"checkFileExists");function LY(e){let t=Te.object({project:Te.string().pattern(Zr).custom(Yi.bind(null,!0)).required().messages({"string.pattern.base":lt.BAD_PROJECT_NAME}),type:Te.string().valid("helpers","routes").required(),file:Te.string().pattern(Zr).custom(CY.bind(null,e.project,e.type)).required().messages({"string.pattern.base":lt.BAD_FILE_NAME})});return Dn.validateBySchema(e,t)}a(LY,"getDropCustomFunctionValidator");function UY(e){let t=Te.object({project:Te.string().pattern(Zr).custom(Yi.bind(null,!0)).required().messages({"string.pattern.base":lt.BAD_PROJECT_NAME}),type:Te.string().valid("helpers","routes").required(),file:Te.string().pattern(Zr).required().messages({"string.pattern.base":lt.BAD_FILE_NAME}),function_content:Te.string().required()});return Dn.validateBySchema(e,t)}a(UY,"setCustomFunctionValidator");function yY(e){let t=Te.object({project:Te.string().pattern(Zr).custom(Yi.bind(null,!1)).required().messages({"string.pattern.base":lt.BAD_PROJECT_NAME})});return Dn.validateBySchema(e,t)}a(yY,"addCustomFunctionProjectValidator");function DY(e){let t=Te.object({project:Te.string().pattern(Zr).custom(Yi.bind(null,!0)).required().messages({"string.pattern.base":lt.BAD_PROJECT_NAME})});return Dn.validateBySchema(e,t)}a(DY,"dropCustomFunctionProjectValidator");function MY(e){let t=Te.object({project:Te.string().pattern(Zr).custom(Yi.bind(null,!0)).required().messages({"string.pattern.base":lt.BAD_PROJECT_NAME}),skip_node_modules:Te.boolean()});return Dn.validateBySchema(e,t)}a(MY,"packageCustomFunctionProjectValidator");function PY(e){let t=Te.object({project:Te.string().pattern(Zr).required().messages({"string.pattern.base":lt.BAD_PROJECT_NAME}),payload:Te.string().required().messages({"string.pattern.base":lt.BAD_PACKAGE})});return Dn.validateBySchema(e,t)}a(PY,"deployCustomFunctionProjectValidator")});var cd=S((S3,eg)=>{"use strict";var Ce=require("fs-extra"),r_=require("fast-glob"),ne=require("path"),zN=require("tar-fs"),jN=require("uuid").v4,Ki=require("normalize-path"),Ms=ZN(),Le=I(),Rt=T(),At=Y(),{PACKAGE_ROOT:BY}=T(),{handleHDBError:ze,hdb_errors:vY}=D(),{HDB_ERROR_MSGS:zr,HTTP_STATUS_CODES:je}=vY,HY=ne.join(BY,"custom_function_template"),ad=ne.join(At.get(Rt.HDB_SETTINGS_NAMES.HDB_ROOT_KEY),"tmp");function od(){let e=At.get(Rt.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_ENABLED_KEY);if(!(e==="true"||e===!0||e==="TRUE"))throw ze(new Error,zr.NOT_ENABLED,je.BAD_REQUEST,void 0,void 0,!0)}a(od,"isCFEnabled");function qY(){Le.trace("getting custom api status");let e={};try{e={is_enabled:At.get(Rt.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_ENABLED_KEY),port:At.get(Rt.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_PORT_KEY),directory:At.get(Rt.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY)}}catch(t){throw ze(new Error,zr.FUNCTION_STATUS,je.INTERNAL_SERVER_ERROR,Le.ERR,t)}return e}a(qY,"customFunctionsStatus");function GY(){Le.trace("getting custom api endpoints");let e={},t=At.get(Rt.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY);try{r_.sync(Ki(`${t}/*`),{onlyDirectories:!0}).forEach(s=>{let n=s.split("/").pop();e[n]={routes:r_.sync(Ki(`${s}/routes/*.js`)).map(i=>i.split("/").pop().split(".js")[0]),helpers:r_.sync(Ki(`${s}/helpers/*.js`)).map(i=>i.split("/").pop().split(".js")[0]),static:Ce.existsSync(Ki(`${s}/static`))&&r_.sync(Ki(`${s}/static/**/*`)).length}})}catch(r){throw ze(new Error,zr.GET_FUNCTIONS,je.INTERNAL_SERVER_ERROR,Le.ERR,r)}return e}a(GY,"getCustomFunctions");function FY(e){e.project&&(e.project=ne.parse(e.project).name),e.file&&(e.file=ne.parse(e.file).name);let t=Ms.getDropCustomFunctionValidator(e);if(t)throw ze(t,t.message,je.BAD_REQUEST);Le.trace("getting custom api endpoint file content");let r=At.get(Rt.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY),{project:s,type:n,file:i}=e,o=ne.join(r,s,n,i+".js");try{return Ce.readFileSync(o,{encoding:"utf8"})}catch(c){throw ze(new Error,zr.GET_FUNCTION,je.INTERNAL_SERVER_ERROR,Le.ERR,c)}}a(FY,"getCustomFunction");function VY(e){od(),e.project&&(e.project=ne.parse(e.project).name),e.file&&(e.file=ne.parse(e.file).name);let t=Ms.setCustomFunctionValidator(e);if(t)throw ze(t,t.message,je.BAD_REQUEST);Le.trace("setting custom function file content");let r=At.get(Rt.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY),{project:s,type:n,file:i,function_content:o}=e;try{return Ce.outputFileSync(ne.join(r,s,n,i+".js"),o),`Successfully updated custom function: ${i}.js`}catch(c){throw ze(new Error,zr.SET_FUNCTION,je.INTERNAL_SERVER_ERROR,Le.ERR,c)}}a(VY,"setCustomFunction");function kY(e){e.project&&(e.project=ne.parse(e.project).name),e.file&&(e.file=ne.parse(e.file).name);let t=Ms.getDropCustomFunctionValidator(e);if(t)throw ze(t,t.message,je.BAD_REQUEST);Le.trace("dropping custom function file");let r=At.get(Rt.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY),{project:s,type:n,file:i}=e;try{return Ce.unlinkSync(ne.join(r,s,n,i+".js")),`Successfully deleted custom function: ${i}.js`}catch(o){throw ze(new Error,zr.DROP_FUNCTION,je.INTERNAL_SERVER_ERROR,Le.ERR,o)}}a(kY,"dropCustomFunction");function $Y(e){od(),e.project&&(e.project=ne.parse(e.project).name);let t=Ms.addCustomFunctionProjectValidator(e);if(t)throw ze(t,t.message,je.BAD_REQUEST);Le.trace("adding custom function project");let r=At.get(Rt.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY),{project:s}=e;try{let n=ne.join(r,s);return Ce.mkdirSync(n,{recursive:!0}),Ce.copySync(HY,n),`Successfully created custom function project: ${s}`}catch(n){throw ze(new Error,zr.ADD_FUNCTION,je.INTERNAL_SERVER_ERROR,Le.ERR,n)}}a($Y,"addCustomFunctionProject");function xY(e){e.project&&(e.project=ne.parse(e.project).name);let t=Ms.dropCustomFunctionProjectValidator(e);if(t)throw ze(t,t.message,je.BAD_REQUEST);Le.trace("dropping custom function project");let r=At.get(Rt.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY),{project:s}=e;try{let n=ne.join(r,s);return Ce.rmSync(n,{recursive:!0}),`Successfully deleted project: ${s}`}catch(n){throw ze(new Error,zr.DROP_FUNCTION_PROJECT,je.INTERNAL_SERVER_ERROR,Le.ERR,n)}}a(xY,"dropCustomFunctionProject");async function YY(e){e.project&&(e.project=ne.parse(e.project).name);let t=Ms.packageCustomFunctionProjectValidator(e);if(t)throw ze(t,t.message,je.BAD_REQUEST);Le.trace("packaging custom function project");let r=At.get(Rt.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY),{project:s}=e,n=ne.join(r,s),i=jN();if(!Ce.existsSync(n)){let l=`Unable to locate custom function project: ${s}`;throw Le.error(l),l}Ce.ensureDirSync(ad);let c=ne.join(ad,`${i}.tar`),_={};(e.skip_node_modules===!0||e.skip_node_modules==="true")&&(_={ignore:l=>l.includes(ne.join(n,"node_modules"))}),zN.pack(n,_).pipe(Ce.createWriteStream(c)),await new Promise(l=>setTimeout(l,2e3));let u=Ce.readFileSync(c,{encoding:"base64"});return Ce.unlinkSync(c),{project:s,payload:u,file:c}}a(YY,"packageCustomFunctionProject");async function KY(e){od(),e.project&&(e.project=ne.parse(e.project).name);let t=Ms.deployCustomFunctionProjectValidator(e);if(t)throw ze(t,t.message,je.BAD_REQUEST);Le.trace("deploying custom function project");let r=At.get(Rt.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY),{project:s,payload:n,file:i}=e,o=ne.join(r,s);await Ce.ensureDir(o);let c,_;do c=ne.join(ad,jN()+".tar"),_=await Ce.pathExists(c);while(_);await Ce.outputFile(c,n,{encoding:"base64"});let u=Ce.createReadStream(c);return u.pipe(zN.extract(o)),await new Promise(l=>u.on("end",l)),await Ce.unlink(c),`Successfully deployed project: ${s}`}a(KY,"deployCustomFunctionProject");eg.exports={customFunctionsStatus:qY,getCustomFunctions:GY,getCustomFunction:FY,setCustomFunction:VY,dropCustomFunction:kY,addCustomFunctionProject:$Y,dropCustomFunctionProject:xY,packageCustomFunctionProject:YY,deployCustomFunctionProject:KY}});var _d=S((f3,rg)=>{"use strict";var ir=require("joi"),tg=de();rg.exports={readTransactionLogValidator:WY,deleteTransactionLogsBeforeValidator:QY};function WY(e){let t=ir.object({schema:ir.string().required(),table:ir.string().required(),from:ir.date().timestamp(),to:ir.date().timestamp(),limit:ir.number().min(1)});return tg.validateBySchema(e,t)}a(WY,"readTransactionLogValidator");function QY(e){let t=ir.object({schema:ir.string().required(),table:ir.string().required(),timestamp:ir.date().timestamp().required()});return tg.validateBySchema(e,t)}a(QY,"deleteTransactionLogsBeforeValidator")});var n_=S((T3,og)=>{"use strict";var ud=T(),s_=at(),sg=b(),ng=Y(),ig=Hr(),{handleHDBError:Mn,hdb_errors:JY}=D(),{HTTP_STATUS_CODES:Pn}=JY,{readTransactionLogValidator:XY,deleteTransactionLogsBeforeValidator:ZY}=_d(),ag="This operation relies on clustering and cannot run with it disable.",zY="Logs successfully deleted from transaction log.",jY="All logs successfully deleted from transaction log.";og.exports={readTransactionLog:eK,deleteTransactionLogsBefore:tK};async function eK(e){let t=XY(e);if(t)throw Mn(t,t.message,Pn.BAD_REQUEST,void 0,void 0,!0);if(!ng.get(ud.CONFIG_PARAMS.CLUSTERING_ENABLED))throw Mn(new Error,ag,Pn.NOT_FOUND,void 0,void 0,!0);let{schema:r,table:s}=e,n=sg.checkSchemaTableExist(r,s);if(n)throw Mn(new Error,n,Pn.NOT_FOUND,void 0,void 0,!0);let i=ig.createNatsTableStreamName(r,s),o=await s_.viewStream(i,parseInt(e.from),e.limit),c=[];for(let _=0,u=o.length;_<u;_++){let l=o[_],E=Math.floor(l?.nats_timestamp/1e6);if(e.to&&E>e.to)break;let d={operation:l?.entry?.operation,user:l?.entry?.__origin?.user,timestamp:E,records:l?.entry?.records};l?.entry?.operation===ud.OPERATIONS_ENUM.DELETE&&(d.hash_values=l?.entry?.hash_values),c.push(d)}return c}a(eK,"readTransactionLog");async function tK(e){let t=ZY(e);if(t)throw Mn(t,t.message,Pn.BAD_REQUEST,void 0,void 0,!0);if(!ng.get(ud.CONFIG_PARAMS.CLUSTERING_ENABLED))throw Mn(new Error,ag,Pn.NOT_FOUND,void 0,void 0,!0);let{schema:r,table:s,timestamp:n}=e,i=sg.checkSchemaTableExist(r,s);if(i)throw Mn(new Error,i,Pn.NOT_FOUND,void 0,void 0,!0);let o=ig.createNatsTableStreamName(r,s),{jsm:c}=await s_.getNATSReferences(),_=await s_.getStreamInfo(o),u=new Date(_.state.first_ts).getTime();if(n<=u)return`No transactions exist before: ${n}`;let l=zY,E,d=new Date(_.state.last_ts).getTime();return n>d?(E=_.state.last_seq+1,l=jY):E=(await s_.viewStream(o,parseInt(n),1))[0].nats_sequence,await c.streams.purge(o,{seq:E}),l}a(tK,"deleteTransactionLogsBefore")});var Ed=S((m3,Tg)=>{"use strict";var i_=require("joi"),a_=require("path"),cg=require("fs-extra"),{exec:rK}=require("child_process"),sK=require("util"),_g=sK.promisify(rK),nK=T(),{handleHDBError:Bn,hdb_errors:iK}=D(),{HTTP_STATUS_CODES:vn}=iK,ug=Y(),aK=de(),o_=I();ug.initSync();var ld=ug.get(nK.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY),lg="npm install --omit=dev --json",oK=`${lg} --dry-run`;Tg.exports={installModules:cK,auditModules:_K};async function Eg(e,t=void 0){let{stdout:r,stderr:s}=await _g(e,{cwd:t});if(s)throw new Error(s.replace(`
|
|
9
9
|
`,""));return r.replace(`
|
|
10
|
-
`,"")}a(
|
|
10
|
+
`,"")}a(Eg,"runCommand");async function cK(e){o_.info(`starting installModules for request: ${e}`);let t=fg(e);if(t)throw Bn(t,t.message,vn.BAD_REQUEST);let{projects:r,dry_run:s}=e,n=s===!0?oK:lg;await hg(),await Sg(r);let i={};for(let o=0,c=r.length;o<c;o++){let _=r[o];i[_]={npm_output:null,npm_error:null};let u=a_.join(ld,_),l,E=null;try{let{stdout:d,stderr:h}=await _g(n,{cwd:u});l=d?d.replace(`
|
|
11
11
|
`,""):null,E=h?h.replace(`
|
|
12
|
-
`,""):null}catch(d){d.stderr?i[_].npm_error=
|
|
13
|
-
`);return r>-1&&s>-1?JSON.parse(e.substring(r+t.length-1,s+1)):e}a(mg,"parseNPMStdErr");async function IK(e){__.info(`starting auditModules for request: ${e}`);let t=Og(e);if(t)throw Gn(t,t.message,qn.BAD_REQUEST);let{projects:r}=e;await Rg(),await Ag(r);let s={};for(let n=0,i=r.length;n<i;n++){let o=r[n],c=c_.join(hd,o);s[o]={npm_output:null,npm_error:null};try{let _=await Tg("npm audit --json",c);s[o].npm_output=JSON.parse(_)}catch(_){s[o].npm_error=mg(_.stderr)}}return __.info(`finished auditModules with response ${s}`),s}a(IK,"auditModules");async function Rg(){try{return await Tg("npm -v"),!0}catch{throw Gn(new Error,"Unable to install project dependencies: npm is not installed on this instance of HarperDB.",qn.BAD_REQUEST,void 0,void 0,!0)}}a(Rg,"checkNPMInstalled");async function Ag(e){if(!Array.isArray(e)||e.length===0)throw Gn(new Error,"projects argument must be an array with at least 1 element",qn.BAD_REQUEST,void 0,void 0,!0);let t=[],r=[];for(let s=0,n=e.length;s<n;s++){let i=e[s],o=c_.join(hd,i.toString());if(!await dg.pathExists(o)){t.push(i);continue}let _=c_.join(o,"package.json");await dg.pathExists(_)||r.push(i)}if(t.length>0)throw Gn(new Error,`Unable to install project dependencies: custom function projects '${t.join(",")}' does not exist.`,qn.BAD_REQUEST,void 0,void 0,!0);if(r.length>0)throw Gn(new Error,`Unable to install project dependencies: custom function projects '${r.join(",")}' do not have a package.json file.`,qn.BAD_REQUEST,void 0,void 0,!0)}a(Ag,"checkProjectPaths");function Og(e){let t=o_.object({projects:o_.array().min(1).items(o_.string()).required(),dry_run:o_.boolean().default(!1)});return pK.validateBySchema(e,t)}a(Og,"modulesValidator")});var gg=S((v3,Ng)=>{"use strict";var u_=class{constructor(t,r,s=[],n=[]){this.schema=t,this.table=r,this.required_table_permissions=s,this.required_attribute_permissions=n}};a(u_,"PermissionTableResponseObject");Ng.exports=u_});var bg=S((H3,Ig)=>{"use strict";var l_=class{constructor(t,r=[]){this.attribute_name=t,this.required_permissions=r}};a(l_,"PermissionAttributeResponseObject");Ig.exports=l_});var fd=S((G3,wg)=>{"use strict";var Cg=gg(),bK=bg(),{HDB_ERROR_MSGS:CK}=Ke(),E_=class{constructor(){this.error=CK.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,s){if(r&&s){let n=`${r}_${s}`;if(this.unauthorized_access[n])return}this.invalid_schema_items.push(t)}addUnauthorizedTable(t,r,s){let n=new Cg(t,r,s),i=`${t}_${r}`;this.unauthorized_access[i]=n}addUnauthorizedAttributes(t,r,s,n){let i=[];t.forEach(c=>{let _=new bK(c,n[c]);i.push(_)});let o=`${r}_${s}`;if(this.unauthorized_access[o])this.unauthorized_access[o].required_attribute_permissions=i;else{let c=new Cg(r,s,[],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}};a(E_,"PermissionResponseObject");wg.exports=E_});var f_=S((q3,xg)=>{"use strict";var Td=Ut(),d_=mt(),Bt=tc(),Xi=fs(),md=Rs(),wK=tE(),zi=Wr(),h_=uE(),Oe=I(),LK=dE(),UK=wc(),yK=vE(),DK=Dc(),MK=HE(),PK=FE(),Rd=xE(),br=b(),BK=Jp(),Ad=KE(),yg=nd(),Pt=T(),Dg=JN(),vK=gc(),Mg=hc(),Pg=Sr(),Cr=ld(),HK=require("alasql"),Bg=a_(),vg=Sd(),Hg=fd(),{handleHDBError:dt,hdb_errors:Gg}=D(),{HDB_ERROR_MSGS:qe,HTTP_STATUS_CODES:Ji}=Gg,O=new Map,qg="delete",ss="insert",_r="read",Hs="update",Zi="describe",Lg=Xi.describeSchema.name,Ug=Xi.describeTable.name,Fg={delete:!0,deleteRecord:!0,update:!0,updateData:!0,dropAttribute:!0,dropTable:!0,dropSchema:!0,upsert:!0,upsertData:!0},GK="catchup",qK="handleGetJob",FK="handleGetJobsByStartDate",S_={CSV_DATA_LOAD:"csvDataLoad",CSV_URL_LOAD:"csvURLLoad",CSV_FILE_LOAD:"csvFileLoad",IMPORT_FROM_S3:"importFromS3"},VK=[Bt.createTable.name,Bt.createAttribute.name,Bt.dropTable.name,Bt.dropAttribute.name],Vg={EXPORT_TO_S3:"export_to_s3",EXPORT_LOCAL:"export_local"},p=class{constructor(t,r){this.requires_su=t,this.perms=r}};a(p,"permission");O.set(Td.insert.name,new p(!1,[ss]));O.set(Td.update.name,new p(!1,[Hs]));O.set(Td.upsert.name,new p(!1,[ss,Hs]));O.set(d_.searchByConditions.name,new p(!1,[_r]));O.set(d_.searchByHash.name,new p(!1,[_r]));O.set(d_.searchByValue.name,new p(!1,[_r]));O.set(d_.search.name,new p(!1,[_r]));O.set(Bt.createSchema.name,new p(!0,[]));O.set(Bt.createTable.name,new p(!0,[]));O.set(Bt.createAttribute.name,new p(!1,[ss]));O.set(Bt.dropSchema.name,new p(!0,[]));O.set(Bt.dropTable.name,new p(!0,[]));O.set(Bt.dropAttribute.name,new p(!0,[]));O.set(Xi.describeSchema.name,new p(!1,[_r]));O.set(Xi.describeTable.name,new p(!1,[_r]));O.set(md.deleteRecord.name,new p(!1,[qg]));O.set(zi.addUser.name,new p(!0,[]));O.set(zi.alterUser.name,new p(!0,[]));O.set(zi.dropUser.name,new p(!0,[]));O.set(zi.listUsersExternal.name,new p(!0,[]));O.set(h_.listRoles.name,new p(!0,[]));O.set(h_.addRole.name,new p(!0,[]));O.set(h_.alterRole.name,new p(!0,[]));O.set(h_.dropRole.name,new p(!0,[]));O.set(LK.name,new p(!0,[]));O.set(UK.name,new p(!0,[]));O.set(yK.name,new p(!0,[]));O.set(DK.name,new p(!0,[]));O.set(MK.name,new p(!0,[]));O.set(Rd.setRoutes.name,new p(!0,[]));O.set(Rd.getRoutes.name,new p(!0,[]));O.set(Rd.deleteRoutes.name,new p(!0,[]));O.set(Pg.setConfiguration.name,new p(!0,[]));O.set(PK.clusterStatus.name,new p(!0,[]));O.set(Ad.getFingerprint.name,new p(!0,[]));O.set(Ad.setLicense.name,new p(!0,[]));O.set(md.deleteFilesBefore.name,new p(!0,[]));O.set(md.deleteAuditLogsBefore.name,new p(!0,[]));O.set(yg.restartProcesses.name,new p(!0,[]));O.set(yg.restartService.name,new p(!0,[]));O.set(wK.name,new p(!0,[]));O.set(vK.systemInformation.name,new p(!0,[]));O.set(Pg.getConfiguration.name,new p(!0,[]));O.set(Bg.readTransactionLog.name,new p(!0,[]));O.set(Bg.deleteTransactionLogsBefore.name,new p(!0,[]));O.set(vg.installModules.name,new p(!0,[]));O.set(vg.auditModules.name,new p(!0,[]));O.set(Mg.createTokens.name,new p(!1,[]));O.set(Mg.refreshOperationToken.name,new p(!1,[]));O.set(Cr.customFunctionsStatus.name,new p(!0,[]));O.set(Cr.getCustomFunctions.name,new p(!0,[]));O.set(Cr.getCustomFunction.name,new p(!0,[]));O.set(Cr.setCustomFunction.name,new p(!0,[]));O.set(Cr.dropCustomFunction.name,new p(!0,[]));O.set(Cr.addCustomFunctionProject.name,new p(!0,[]));O.set(Cr.dropCustomFunctionProject.name,new p(!0,[]));O.set(Cr.packageCustomFunctionProject.name,new p(!0,[]));O.set(Cr.deployCustomFunctionProject.name,new p(!0,[]));O.set(Ad.getRegistrationInfo.name,new p(!1,[]));O.set(zi.userInfo.name,new p(!1,[]));O.set(Xi.describeAll.name,new p(!1,[]));O.set(qK,new p(!1,[]));O.set(FK,new p(!0,[]));O.set(GK,new p(!0,[]));O.set(S_.CSV_DATA_LOAD,new p(!1,[ss,Hs]));O.set(S_.CSV_URL_LOAD,new p(!1,[ss,Hs]));O.set(S_.CSV_FILE_LOAD,new p(!1,[ss,Hs]));O.set(S_.IMPORT_FROM_S3,new p(!1,[ss,Hs]));O.set(Vg.EXPORT_TO_S3,new p(!1,[_r]));O.set(Vg.EXPORT_LOCAL,new p(!1,[_r]));O.set(Pt.VALID_SQL_OPS_ENUM.DELETE,new p(!1,[qg]));O.set(Pt.VALID_SQL_OPS_ENUM.SELECT,new p(!1,[_r]));O.set(Pt.VALID_SQL_OPS_ENUM.INSERT,new p(!1,[ss]));O.set(Pt.VALID_SQL_OPS_ENUM.UPDATE,new p(!1,[Hs]));xg.exports={verifyPerms:xK,verifyPermsAst:kK,verifyBulkLoadAttributePerms:YK};function kK(e,t,r){if(br.isEmptyOrZeroLength(e))throw Oe.info("verify_perms_ast has an empty user parameter"),dt(new Error);if(br.isEmptyOrZeroLength(t))throw Oe.info("verify_perms_ast has an empty user parameter"),dt(new Error);if(br.isEmptyOrZeroLength(r))throw Oe.info("verify_perms_ast has a null operation parameter"),dt(new Error);try{let s=new Hg,n=new BK(e),i=n.getSchemas(),o=new Map;if((!i||i.length===0)&&n.affected_attributes&&n.affected_attributes.size>0)throw Oe.info("No schemas defined in verifyPermsAst(), will not continue."),dt(new Error);let c=!!t.role.permission.super_user,_=i.includes("system");if(_&&Fg[r])throw dt(new Error,qe.DROP_SYSTEM,Ji.FORBIDDEN);if(c&&!_)return null;let u=Dg.getRolePermissions(t.role);t.role.permission=u,!c&&e instanceof HK.yy.Select&&(e=n.updateAttributeWildcardsForRolePerms(u));for(let E=0;E<i.length;E++){let d=n.getTablesBySchemaName(i[E]);d&&o.set(i[E],d)}let l=kg(t,r,o,s);return l||(o.forEach((E,d)=>{for(let h=0;h<E.length;h++){let m=n.getAttributesBySchemaTableName(d,E[h]),R=pd(t.role.permission,d,E[h]);Od(m,R,r,E[h],d,s)}}),s.getPermsResponse())}catch(s){throw dt(s)}}a(kK,"verifyPermsAst");function xK(e,t){if(e===null||t===null||e.hdb_user===void 0||e.hdb_user===null)throw Oe.info("null required parameter in verifyPerms"),dt(new Error,qe.DEFAULT_INVALID_REQUEST,Ji.BAD_REQUEST);let r;t instanceof Function?r=t.name:r=t;let s=e.action,n=e.schema,i=e.table,o=new Map;n&&i&&o.set(n,[i]);let c=new Hg;if(br.isEmptyOrZeroLength(e.hdb_user.role)||br.isEmptyOrZeroLength(e.hdb_user.role.permission))return Oe.info(`User ${e.hdb_user.username} has no role or permissions. Please assign the user a valid role.`),c.handleUnauthorizedItem(qe.USER_HAS_NO_PERMS(e.hdb_user.username));let _=!!e.hdb_user.role.permission.super_user,u=e.hdb_user.role.permission.structure_user,l=o.has(Pt.SYSTEM_SCHEMA_NAME)||n===Pt.SYSTEM_SCHEMA_NAME;if(l&&Fg[r])throw dt(new Error,qe.DROP_SYSTEM,Ji.FORBIDDEN);if(_&&!l||u===!0&&(r===Bt.createSchema.name||r===Bt.dropSchema.name))return null;if(VK.indexOf(r)>=0&&(u===!0||Array.isArray(u)))return u===!0||u.indexOf(n)>=0?null:c.handleUnauthorizedItem(`User does not have access to perform '${e.operation}' against schema '${n}'`);let E=Dg.getRolePermissions(e.hdb_user.role);if(e.hdb_user.role.permission=E,r===Lg||r===Ug){if(n===Pt.SYSTEM_SCHEMA_NAME)return c.handleUnauthorizedItem(qe.SCHEMA_PERM_ERROR(n));if(!E.super_user){if(r===Lg&&(!E[n]||!E[n][Zi]))return c.handleInvalidItem(qe.SCHEMA_NOT_FOUND(n));if(r===Ug&&(!E[n]||!E[n].tables[i]||!E[n].tables[i][Zi]))return c.handleInvalidItem(qe.TABLE_NOT_FOUND(n,i))}}let d=kg(e.hdb_user,r,o,c,s);if(d)return d;if(O.get(r)&&O.get(r).perms.length===0)return null;if(!_&&e.get_attributes&&Pt.SEARCH_WILDCARDS.includes(e.get_attributes[0])){let R=[],w=E[n].tables[i];w[Pt.PERMS_CRUD_ENUM.READ]&&(w.attribute_permissions.length>0?w.attribute_permissions.filter(B=>B[Pt.PERMS_CRUD_ENUM.READ]).forEach(B=>{R.push(B.attribute_name)}):R=global.hdb_schema[n][i].attributes.map(L=>L.attribute),e.get_attributes=R)}let h=$K(e),m=pd(e.hdb_user.role.permission,n,i);return Od(h,m,r,i,n,c,s),c.getPermsResponse()}a(xK,"verifyPerms");function kg(e,t,r,s,n){if(br.arrayHasEmptyValues([e,t,r]))throw Oe.info("hasPermissions has an invalid parameter"),dt(new Error);let i=r.has("system"),o=e.role.permission;if(o.super_user&&!i)return null;if(!O.get(t))throw Oe.info(`operation ${t} not found.`),dt(new Error,qe.OP_NOT_FOUND(t),Ji.BAD_REQUEST);if(O.get(t)&&O.get(t).requires_su)return Oe.info(`operation ${t} requires SU permissions.`),s.handleUnauthorizedItem(qe.OP_IS_SU_ONLY(t));let c=r.keys();for(let _ of c){try{if(_&&!o[_]||o[_][Zi]===!1){s.addInvalidItem(qe.SCHEMA_NOT_FOUND(_));continue}}catch{s.addInvalidItem(qe.SCHEMA_NOT_FOUND(_));continue}let u=r.get(_);for(let l of u){let E=o[_].tables[l];if(!E||E[Zi]===!1)s.addInvalidItem(qe.TABLE_NOT_FOUND(_,l));else try{let d=[],h=O.get(t).perms;!br.isEmpty(n)&&h.includes(n)&&(h=[n]);for(let m=0;m<h.length;m++){let R=h[m],w=E[R];(w==null||w===!1)&&(Oe.info(`Required ${R} permission not found for ${t} ${n?`${n} `:""}operation in role ${e.role.id}`),d.push(R))}d.length>0&&s.addUnauthorizedTable(_,l,d)}catch(d){let h=qe.UNKNOWN_OP_AUTH_ERROR(t,_,l);throw Oe.error(h),Oe.error(d),dt(Gg.CHECK_LOGS_WRAPPER(h))}}}return r.size<2?s.getPermsResponse():null}a(kg,"hasPermissions");function Od(e,t,r,s,n,i,o){if(!e||!t)throw Oe.info("no attributes specified in checkAttributePerms."),dt(new Error);let c=O.get(r).perms;if(!c||c==="")throw Oe.info(`no permissions found for ${r} in checkAttributePerms().`),dt(new Error);if(br.isEmptyOrZeroLength(t))return Oe.info("No role permissions set (this is OK)."),null;o&&c.includes(o)&&(c=[o]);let _={};for(let l of e){let E=t.get(l);if(E){if(E[Zi]===!1){i.addInvalidItem(qe.ATTR_NOT_FOUND(n,s,l),n,s);continue}if(c)for(let d of c){if(Pt.TIME_STAMP_NAMES.includes(E.attribute_name)&&d!==_r)throw dt(new Error,qe.SYSTEM_TIMESTAMP_PERMS_ERR,Ji.FORBIDDEN);E[d]===!1&&(_[E.attribute_name]?_[E.attribute_name].push(d):_[E.attribute_name]=[d])}}else i.addInvalidItem(qe.ATTR_NOT_FOUND(n,s,l),n,s)}let u=Object.keys(_);u.length>0&&i.addUnauthorizedAttributes(u,n,s,_)}a(Od,"checkAttributePerms");function $K(e){let t=new Set;try{if(e.action)return t;if(e.operation===Pt.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 s=Object.keys(e.records[r]);for(let n=0;n<s.length;n++)t.add(s[n])}}catch(r){Oe.info(r)}return t}a($K,"getRecordAttributes");function pd(e,t,r){let s=new Map;if(br.isEmpty(e))return Oe.info("no hdb_user specified in getAttributePermissions"),s;if(e.super_user||!t||!r)return s;try{e[t].tables[r].attribute_permissions.forEach(n=>{s.has(n.attribute_name)||s.set(n.attribute_name,n)})}catch{Oe.info(`No attribute permissions found for schema ${t} and table ${r}.`)}return s}a(pd,"getAttributePermissions");function YK(e,t,r,s,n,i,o){let c=new Set(i),_=pd(e,s,n);Od(c,_,t,n,s,o,r)}a(YK,"verifyBulkLoadAttributePerms")});var m_=S((F3,Wg)=>{"use strict";Wg.exports={evaluateSQL:aQ,processAST:Qg,convertSQLToAST:Kg,checkASTPermissions:Yg};var $g=Ut(),Id=require("util"),KK=Id.callbackify($g.insert),QK=mt().search,WK=qA().update,JK=Id.callbackify(WK),ZK=VA().convertDelete,ns=require("alasql"),XK=f_(),ea=I(),zK=Lo(),jK=b(),ji=T(),{hdb_errors:eQ,handleHDBError:Nd}=D(),{HTTP_STATUS_CODES:gd}=eQ,tQ=Ns();function rQ(e,t,r){return Promise.all([tQ.postOperationHandler(e,t,r),$g.flush(e)])}a(rQ,"postWrite");var sQ=Id.callbackify(rQ);zK(ns);var nQ=403,iQ="There was a problem performing this insert. Please check the logs and try again.",T_=class{constructor(){this.ast=void 0,this.variant=void 0,this.permissions_checked=!1}};a(T_,"ParsedSQLObject");function aQ(e,t){let r=e.parsed_sql_object;if(!r){r=Kg(e.sql);let s,n=r.ast.statements[0];if(n instanceof ns.yy.Insert?s=n.into.databaseid:n instanceof ns.yy.Select?s=n.from?n.from[0].databaseid:null:n instanceof ns.yy.Update||n instanceof ns.yy.Delete?s=n.table.databaseid:ea.error("AST in evaluateSQL is not a valid SQL type."),!(n instanceof ns.yy.Select)&&jK.isEmptyOrZeroLength(s))return t("No schema specified",null)}Qg(e,r,(s,n)=>{if(s)return t(s);t(null,n)})}a(aQ,"evaluateSQL");function Yg(e,t){let r;try{r=XK.verifyPermsAst(t.ast.statements[0],e.hdb_user,t.variant),t.permissions_checked=!0}catch(s){throw s}return r||null}a(Yg,"checkASTPermissions");function Kg(e){let t=new T_;if(!e)throw Nd(new Error,"The 'sql' parameter is missing from the request body",gd.BAD_REQUEST);try{let r=e.trim(),s=ns.parse(r),n=r.split(" ")[0].toLowerCase();t.ast=s,t.variant=n}catch(r){let s=r.message.split(`
|
|
14
|
-
`);throw s[1]?Nd(r,`Invalid SQL at: ${s[1]}. Please ensure your SQL is valid. Try adding backticks to reserved words and schema table references.`,gd.BAD_REQUEST):Nd(r,"We had trouble parsing your request. Please ensure your SQL is valid. Try adding backticks to reserved words and schema table references.",gd.BAD_REQUEST)}return t}a(Kg,"convertSQLToAST");function Qg(e,t,r){try{let s=oQ;if(!e.bypass_auth&&!t.permissions_checked){let i=Yg(e,t);if(i&&i.length>0)return r(nQ,i)}let n={statement:t.ast.statements[0],hdb_user:e.hdb_user};switch(t.variant){case ji.VALID_SQL_OPS_ENUM.SELECT:s=QK,n=t.ast.statements[0];break;case ji.VALID_SQL_OPS_ENUM.INSERT:s=cQ;break;case ji.VALID_SQL_OPS_ENUM.UPDATE:s=JK;break;case ji.VALID_SQL_OPS_ENUM.DELETE:s=ZK;break;default:throw new Error(`unsupported SQL type ${t.variant} in SQL: ${e}`)}s(n,(i,o)=>{if(i){r(i);return}r(null,o)})}catch(s){return r(s)}}a(Qg,"processAST");function oQ(e,t){ea.info(e),t("unknown sql statement")}a(oQ,"nullFunction");function cQ({statement:e,hdb_user:t},r){let s=e.into,n={schema:s.databaseid,table:s.tableid,operation:"insert",hdb_user:t},i=e.columns.map(o=>o.columnid);try{n.records=_Q(i,e.values)}catch(o){return r(o)}KK(n,(o,c)=>{if(o)return r(o);sQ(n,c,_=>{_&&ea.error(_)});try{delete c.new_attributes,delete c.txn_time}catch(_){ea.error(`Error delete new_attributes from insert response: ${_}`)}r(null,c)})}a(cQ,"convertInsert");function _Q(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 s={};return r.forEach((n,i)=>{if(n.columnid)throw"cannot use a column in insert value";"value"in n?s[e[i]]=n.value:s[e[i]]=ns.compile(`SELECT ${n.toString()} AS [${ji.FUNC_VAL}] FROM ?`)}),s})}catch(r){throw ea.error(r),new Error(iQ)}}a(_Q,"createDataObjects")});var Cd=S((V3,jg)=>{var N_=require("clone"),g_=de(),uQ=b(),p_=T(),lQ=I(),R_=require("fs"),{hdb_errors:EQ,handleHDBError:ta}=D(),{HDB_ERROR_MSGS:dQ,HTTP_STATUS_CODES:A_}=EQ,{common_validators:O_}=Tr(),Jg=1e9,bd=" is required",hQ=["insert","update","upsert"],I_={schema:{presence:!0,format:O_.schema_format,length:O_.schema_length},table:{presence:!0,format:O_.schema_format,length:O_.schema_length},action:{inclusion:{within:hQ,message:"is required and must be either insert, update, or upsert"}},file_path:{},csv_url:{url:{allowLocal:!0}},data:{}},{AWS_ACCESS_KEY:SQ,AWS_SECRET:fQ,AWS_BUCKET:TQ,AWS_FILE_KEY:mQ}=p_.S3_BUCKET_AUTH_KEYS,RQ={s3:{presence:!0},[`s3.${SQ}`]:{presence:!0,type:"String"},[`s3.${fQ}`]:{presence:!0,type:"String"},[`s3.${TQ}`]:{presence:!0,type:"String"},[`s3.${mQ}`]:{presence:!0,type:"String",hasValidFileExt:[".csv",".json"]}},Zg=N_(I_);Zg.data.presence={message:bd};var Xg=N_(I_);Xg.file_path.presence={message:bd};var AQ=Object.assign(N_(I_),RQ),zg=N_(I_);zg.csv_url.presence={message:bd};function OQ(e){let t=g_.validateObject(e,Zg);return b_(e,t)}a(OQ,"dataObject");function pQ(e){let t=g_.validateObject(e,zg);return b_(e,t)}a(pQ,"urlObject");function NQ(e){let t=g_.validateObject(e,Xg);return b_(e,t)}a(NQ,"fileObject");function gQ(e){let t=g_.validateObject(e,AQ);return b_(e,t)}a(gQ,"s3FileObject");function b_(e,t){if(!t){let r=uQ.checkGlobalSchemaTable(e.schema,e.table);if(r)return ta(new Error,r,A_.BAD_REQUEST);if(e.operation===p_.OPERATIONS_ENUM.CSV_FILE_LOAD){try{R_.accessSync(e.file_path,R_.constants.R_OK|R_.constants.F_OK)}catch(s){return s.code===p_.NODE_ERROR_CODES.ENOENT?ta(s,`No such file or directory ${s.path}`,A_.BAD_REQUEST):s.code===p_.NODE_ERROR_CODES.EACCES?ta(s,`Permission denied ${s.path}`,A_.BAD_REQUEST):ta(s)}try{let s=R_.statSync(e.file_path).size;if(s>Jg)return ta(new Error,dQ.MAX_FILE_SIZE_ERR(s,Jg),A_.BAD_REQUEST)}catch(s){lQ.error(s),console.error(s)}}}return t}a(b_,"postValidateChecks");jg.exports={dataObject:OQ,urlObject:pQ,fileObject:NQ,s3FileObject:gQ}});var w_=S((k3,eI)=>{"use strict";var ra=I(),C_=T();async function IQ(e,t,r,s=[]){if(!e||typeof e!="function")throw new Error("Invalid function parameter");let n;try{return n=await e(t),r&&await r(t,n,s),t.operation===C_.OPERATIONS_ENUM.INSERT||t.operation===C_.OPERATIONS_ENUM.UPDATE||t.operation===C_.OPERATIONS_ENUM.UPSERT?(delete n.new_attributes,delete n.txn_time):t.operation===C_.OPERATIONS_ENUM.DELETE&&delete n.txn_time,n}catch(i){throw i.message&&typeof i.message=="string"&&i.message.includes("already exists")?(ra.info(i.message),i):i.http_resp_msg?(ra.error(`Error calling operation: ${e.name}`),ra.error(i.http_resp_msg),i):(ra.error(`Error calling operation: ${e.name}`),ra.error(i),i)}}a(IQ,"callOperationFunctionAsAwait");eI.exports={callOperationFunctionAsAwait:IQ}});var wd=S((x3,rI)=>{"use strict";var bQ=require("aws-sdk/clients/s3");rI.exports={getFileStreamFromS3:CQ,getS3AuthObj:tI};function CQ(e){let{s3:t}=e,r={Bucket:t.bucket,Key:t.key};return tI(t.aws_access_key_id,t.aws_secret_access_key).getObject(r).createReadStream()}a(CQ,"getFileStreamFromS3");function tI(e,t){return new bQ({accessKeyId:e,secretAccessKey:t})}a(tI,"getS3AuthObj")});var nI=S(($3,sI)=>{"use strict";var L_=class{constructor(t,r,s,n,i,o,c=null){this.op=t,this.action=r,this.schema=s,this.table=n,this.file_path=i,this.file_type=o,this.role_perms=c}};a(L_,"BulkLoadFileObject");var U_=class{constructor(t,r,s,n){this.action=t,this.schema=r,this.table=s,this.data=n}};a(U_,"BulkLoadDataObject");sI.exports={BulkLoadFileObject:L_,BulkLoadDataObject:U_}});var Md=S((Y3,OI)=>{"use strict";var y_=Ut(),P_=Cd(),wQ=require("needle"),pt=T(),LQ=_e(),sa=b(),{handleHDBError:ae,hdb_errors:dI}=D(),{HTTP_STATUS_CODES:Fe,HDB_ERROR_MSGS:pe,CHECK_LOGS_WRAPPER:Fs}=dI,qs=I(),D_=require("papaparse");sa.promisifyPapaParse();var Jt=require("fs-extra"),UQ=require("path"),{chain:iI}=require("stream-chain"),aI=require("stream-json/streamers/StreamArray"),oI=require("stream-json/utils/Batch"),cI=require("stream-chain/utils/comp"),{finished:_I}=require("stream"),Ld=Y(),yQ=Ns(),hI=w_(),DQ=wd(),{BulkLoadFileObject:Ud,BulkLoadDataObject:MQ}=nI(),yd=fd(),{verifyBulkLoadAttributePerms:SI}=f_(),PQ=Ql(),BQ=ot(),vQ=Vr(),uI="No records parsed from csv file.",Gs=`${Ld.get("HDB_ROOT")}/tmp`,{schema_regex:HQ}=Tr(),lI=1024*1024*5,EI=5e3,GQ={"text/csv":!0,"application/octet-stream":!0,"text/plain":!0,"application/vnd.ms-excel":!0};OI.exports={csvDataLoad:qQ,csvURLLoad:FQ,csvFileLoad:VQ,importFromS3:kQ};async function qQ(e,t=[]){let r=P_.dataObject(e);if(r)throw ae(r,r.message,Fe.BAD_REQUEST,void 0,void 0,!0);let s={};try{let n=D_.parse(e.data,{header:!0,skipEmptyLines:!0,dynamicTyping:!0}),i=new yd;e.hdb_user&&e.hdb_user.role&&e.hdb_user.role.permission&&e.hdb_user.role.permission.super_user!==!0&&SI(e.hdb_user.role.permission,this.job_operation_function.name,e.action,e.schema,e.table,n.meta.fields,i);let o=i.getPermsResponse();if(o)throw ae(new Error,o,Fe.BAD_REQUEST,void 0,void 0,!0);let c=new MQ(e.action,e.schema,e.table,n.data);return s=await hI.callOperationFunctionAsAwait(mI,c,RI.bind(null,n.meta.fields),t),s.message===uI?uI:AI(s.records,s.number_written)}catch(n){throw Vs(n)}}a(qQ,"csvDataLoad");async function FQ(e){let t=P_.urlObject(e);if(t)throw ae(t,t.message,Fe.BAD_REQUEST,void 0,void 0,!0);let r=`${Date.now()}.csv`,s=`${Gs}/${r}`;try{await xQ(e.csv_url,r)}catch(n){throw qs.error(pe.DOWNLOAD_FILE_ERR(r)+" - "+n),ae(n,Fs(pe.DOWNLOAD_FILE_ERR(r)))}try{let n=new Ud(this.job_operation_function.name,e.action,e.schema,e.table,s,pt.VALID_S3_FILE_TYPES.CSV,e.hdb_user.role.permission),i=await Dd(n);return await M_(s),i}catch(n){throw await M_(s),Vs(n)}}a(FQ,"csvURLLoad");async function VQ(e){let t=P_.fileObject(e);if(t)throw ae(t,t.message,Fe.BAD_REQUEST,void 0,void 0,!0);let r=new Ud(this.job_operation_function.name,e.action,e.schema,e.table,e.file_path,pt.VALID_S3_FILE_TYPES.CSV,e.hdb_user.role.permission);try{return await Dd(r)}catch(s){throw Vs(s)}}a(VQ,"csvFileLoad");async function kQ(e){let t=P_.s3FileObject(e);if(t)throw ae(t,t.message,Fe.BAD_REQUEST,void 0,void 0,!0);let r;try{let s=UQ.extname(e.s3.key),n=`${Date.now()}${s}`;r=`${Gs}/${n}`;let i=new Ud(this.job_operation_function.name,e.action,e.schema,e.table,r,s,e.hdb_user.role.permission);await $Q(n,e);let o=await Dd(i);return await M_(r),o}catch(s){throw await M_(r),Vs(s)}}a(kQ,"importFromS3");async function xQ(e,t){let r;try{r=await wQ("get",e)}catch(s){let n=`Error downloading CSV file from ${e}, status code: ${s.statusCode}. Check the log for more information.`;throw ae(s,n,s.statusCode,pt.LOG_LEVELS.ERROR,"Error downloading CSV file - "+s)}KQ(r,e),await YQ(t,r.raw)}a(xQ,"downloadCSVFile");async function $Q(e,t){try{let r=`${Gs}/${e}`;await Jt.mkdirp(Gs),await Jt.writeFile(`${Gs}/${e}`,"",{flag:"a+"});let s=await Jt.createWriteStream(r),n=DQ.getFileStreamFromS3(t);await new Promise((i,o)=>{n.on("error",function(c){o(c)}),n.pipe(s).on("error",function(c){o(c)}).on("close",function(){qs.info(`${t.s3.key} successfully downloaded to ${r}`),i()})})}catch(r){throw qs.error(pe.S3_DOWNLOAD_ERR+" - "+r),ae(r,Fs(pe.S3_DOWNLOAD_ERR))}}a($Q,"downloadFileFromS3");async function YQ(e,t){try{await Jt.mkdirp(Gs),await Jt.writeFile(`${Gs}/${e}`,t)}catch(r){throw qs.error(pe.WRITE_TEMP_FILE_ERR),ae(r,Fs(pe.DEFAULT_BULK_LOAD_ERR))}}a(YQ,"writeFileToTempFolder");async function M_(e){if(e)try{await Jt.access(e),await Jt.unlink(e)}catch{qs.warn(`could not delete temp csv file at ${e}, file does not exist`)}}a(M_,"deleteTempFile");function KQ(e,t){if(e.statusCode!==dI.HTTP_STATUS_CODES.OK)throw ae(new Error,`CSV Load failed from URL: ${t}, status code: ${e.statusCode}, message: ${e.statusMessage}`,Fe.BAD_REQUEST);if(!GQ[e.headers["content-type"]])throw ae(new Error,`CSV Load failed from URL: ${t}, unsupported content type: ${e.headers["content-type"]}`,Fe.BAD_REQUEST);if(!e.raw)throw ae(new Error,`CSV Load failed from URL: ${t}, no csv found at url`,Fe.BAD_REQUEST)}a(KQ,"validateURLResponse");async function Dd(e){try{let t;switch(e.file_type){case pt.VALID_S3_FILE_TYPES.CSV:t=await QQ(e);break;case pt.VALID_S3_FILE_TYPES.JSON:t=await WQ(e);break;default:throw ae(new Error,pe.DEFAULT_BULK_LOAD_ERR,Fe.BAD_REQUEST,pt.LOG_LEVELS.ERROR,pe.INVALID_FILE_EXT_ERR(e))}return AI(t.records,t.number_written)}catch(t){throw Vs(t)}}a(Dd,"fileLoad");async function fI(e,t,r,s,n){let i=s.data?s.data:s;if(i.length===0)return;n&&n.pause();let o={operation:e.action,schema:e.schema,table:e.table,records:i};try{let{attributes:c}=await y_.validation(o);e.role_perms&&e.role_perms.super_user!==!0&&SI(e.role_perms,e.op,e.action,e.schema,e.table,c,t),n&&n.resume()}catch(c){let _=ae(c);r(_)}}a(fI,"validateChunk");async function TI(e,t,r,s,n){let i=s.data?s.data:s;if(i.length===0)return;sa.autoCastJSONDeep(i),n&&n.pause();let o=s.meta?s.meta.fields:null;if(o)i.forEach(c=>{!sa.isEmpty(c)&&!sa.isEmpty(c.__parsed_extra)&&delete c.__parsed_extra});else{let c=new Set;i.forEach(_=>{Object.keys(_).forEach(u=>c.add(u))}),o=[...c]}try{let c={schema:e.schema,table:e.table,action:e.action,data:i},_=await hI.callOperationFunctionAsAwait(mI,c,RI.bind(null,o));t.records+=_.records,t.number_written+=_.number_written,n&&n.resume()}catch(c){let _=ae(c,Fs(pe.INSERT_CSV_ERR),Fe.INTERNAL_SERVER_ERROR,pt.LOG_LEVELS.ERROR,pe.INSERT_CSV_ERR+" - "+c);r(_)}}a(TI,"insertChunk");async function QQ(e){let t={records:0,number_written:0};try{let r=new yd,s=Jt.createReadStream(e.file_path,{highWaterMark:lI});s.setEncoding("utf8"),await D_.parsePromise(s,fI.bind(null,e,r));let n=r.getPermsResponse();if(n)throw ae(new Error,n,Fe.BAD_REQUEST);return s=Jt.createReadStream(e.file_path,{highWaterMark:lI}),s.setEncoding("utf8"),await D_.parsePromise(s,TI.bind(null,e,t)),s.destroy(),t}catch(r){throw ae(r,Fs(pe.PAPA_PARSE_ERR),Fe.INTERNAL_SERVER_ERROR,pt.LOG_LEVELS.ERROR,pe.PAPA_PARSE_ERR+r)}}a(QQ,"callPapaParse");async function WQ(e){let t={records:0,number_written:0},r=a(s=>{throw s},"throwErr");try{let s=new yd,n=iI([Jt.createReadStream(e.file_path,{encoding:"utf-8"}),aI.withParser(),c=>c.value,new oI({batchSize:EI}),cI(async c=>{await fI(e,s,r,c)})]);await new Promise((c,_)=>{_I(n,u=>{u?_(u):c()}),n.resume()});let i=s.getPermsResponse();if(i)throw ae(new Error,i,Fe.BAD_REQUEST);let o=iI([Jt.createReadStream(e.file_path,{encoding:"utf-8"}),aI.withParser(),c=>c.value,new oI({batchSize:EI}),cI(async c=>{await TI(e,t,r,c)})]);return await new Promise((c,_)=>{_I(o,u=>{u?_(u):c()}),o.resume()}),t}catch(s){throw ae(s,Fs(pe.INSERT_JSON_ERR),Fe.INTERNAL_SERVER_ERROR,pt.LOG_LEVELS.ERROR,pe.INSERT_JSON_ERR+s)}}a(WQ,"insertJson");async function mI(e){let t={};try{e.data&&e.data.length>0&&JQ(e.data[0])?t=await ZQ(e.data,e.schema,e.table,e.action):(t.message="No records parsed from csv file.",qs.info(t.message))}catch(r){throw Vs(r)}return t}a(mI,"callBulkFileLoad");function JQ(e){let t=Object.keys(e);for(let r of t)if(!HQ.test(r))throw new Error(`Invalid column name '${r}', cancelling load operation`);return!0}a(JQ,"validateColumnNames");async function ZQ(e,t,r,s){s||(s="insert");let n={operation:s,schema:t,table:r,records:e},i;switch(s){case"insert":i=y_.insert;break;case"update":i=y_.update;break;case"upsert":i=y_.upsert;break;default:throw ae(new Error,pe.INVALID_ACTION_PARAM_ERR(s),Fe.BAD_REQUEST,pt.LOG_LEVELS.ERROR,pe.INVALID_ACTION_PARAM_ERR(s))}try{let o=await i(n),c;switch(s){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,E=e.length;for(;E--;)o.skipped_hashes.indexOf(e[E][l])>=0&&e.splice(E,1)}let _=sa.isEmptyOrZeroLength(c)?0:c.length;return{records:e.length,number_written:_,new_attributes:o.new_attributes}}catch(o){throw Vs(o)}}a(ZQ,"bulkFileLoad");async function RI(e,t,r,s=[]){try{if(t.data.length===0||!Ld.get(pt.CONFIG_PARAMS.CLUSTERING_ENABLED))return;let n=D_.unparse(t.data,{header:!0,skipEmptyLines:!0,columns:e}),i;t.hdb_user&&t.hdb_user.username&&(i=t.hdb_user.username);let o={operation:"csv_data_load",action:t.action?t.action:"insert",schema:t.schema,table:t.table,data:n,__origin:new PQ(r.txn_time,i,Ld.get(pt.HDB_SETTINGS_NAMES.CLUSTERING_NODE_NAME_KEY))};await BQ.publishToStream(`${LQ.SUBJECT_PREFIXES.TXN}.${t.schema}.${t.table}`,vQ.createNatsTableStreamName(t.schema,t.table),[o],s),await yQ.sendAttributeTransaction(r,t,s),delete r.new_attributes}catch(n){qs.error(n)}}a(RI,"postCSVLoadFunction");function AI(e,t){return`successfully loaded ${t} of ${e} records`}a(AI,"buildResponseMsg");function Vs(e){return ae(e,Fs(pe.DEFAULT_BULK_LOAD_ERR),Fe.INTERNAL_SERVER_ERROR,pt.LOG_LEVELS.ERROR,pe.DEFAULT_BULK_LOAD_ERR+" - "+e)}a(Vs,"buildTopLevelErrMsg")});var Bd=S((K3,LI)=>{"use strict";var gI=mt(),XQ=m_(),zQ=wd(),{AsyncParser:jQ,Transform:eW}=require("json2csv"),na=require("stream"),tW=require("events"),vt=b(),Pd=require("fs-extra"),rW=require("path"),et=I(),{promisify:B_}=require("util"),ia=b(),{handleHDBError:Ne,hdb_errors:sW}=D(),{HDB_ERROR_MSGS:Nt,HTTP_STATUS_CODES:ge}=sW,pI=["search_by_value","search_by_hash","sql"],NI=["json","csv"],II="json",bI="csv",nW="Successfully exported JSON locally.",iW="Successfully exported CSV locally.",aW=1e3,oW=1e3,cW=B_(gI.searchByHash),_W=B_(gI.searchByValue),uW=B_(XQ.evaluateSQL),lW=B_(na.finished);LI.exports={export_to_s3:SW,export_local:EW};async function EW(e){et.trace(`export_local request to path: ${e.path}, filename: ${e.filename}, format: ${e.format}`);let t=CI(e);if(!vt.isEmpty(t))throw et.error(t),Ne(new Error,t,ge.BAD_REQUEST,void 0,void 0,!0);if(vt.isEmpty(e.path))throw et.error(Nt.MISSING_VALUE("path")),Ne(new Error,Nt.MISSING_VALUE("path"),ge.BAD_REQUEST,void 0,void 0,!0);let r=(vt.isEmpty(e.filename)?new Date().getTime():e.filename)+"."+e.format;e.path.endsWith(rW.sep)&&(e.path=e.path.substring(0,e.path.length-1));let s=vt.buildFolderPath(e.path,r);try{await dW(e.path);let n=await wI(e);return await hW(s,e.format,n)}catch(n){throw et.error(n),new Error(n)}}a(EW,"export_local");async function dW(e){if(et.trace("in confirmPath"),vt.isEmptyOrZeroLength(e))throw Ne(new Error,`Invalid path: ${e}`,ge.BAD_REQUEST,void 0,void 0,!0);let t;try{t=await Pd.stat(e)}catch(r){let s;throw r.code==="ENOENT"?s=`path '${e}' does not exist`:r.code==="EACCES"?s=`access to path '${e}' is denied`:s=r.message,et.error(s),Ne(new Error,s,ge.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 et.error(r),Ne(new Error,r,ge.BAD_REQUEST,void 0,void 0,!0)}return!0}a(dW,"confirmPath");async function hW(e,t,r){if(et.trace("in saveToLocal"),ia.isEmptyOrZeroLength(e))throw Ne(new Error,Nt.INVALID_VALUE("file_path"),ge.BAD_REQUEST,void 0,void 0,!0);if(ia.isEmptyOrZeroLength(t))throw Ne(new Error,Nt.INVALID_VALUE("Source format"),ge.BAD_REQUEST,void 0,void 0,!0);if(ia.isEmpty(r))throw Ne(new Error,Nt.NOT_FOUND("Data"),ge.BAD_REQUEST,void 0,void 0,!0);if(t===II){let s=Pd.createWriteStream(e),n=r.length;s.write("[");let i="";for await(let[o,c]of r.entries())i+=o===n-1?JSON.stringify(c):JSON.stringify(c)+",",o!==0&&o%oW===0&&(s.write(i)||await tW.once(s,"drain"),i="");return i.length!==0&&s.write(i),s.write("]"),s.end(),await lW(s),nW}else if(t===bI){let s=Pd.createWriteStream(e),n=na.Readable.from(r),i={},o={objectMode:!0};return await new jQ(i,o).fromInput(n).toOutput(s).promise(!1),iW}throw Ne(new Error,Nt.INVALID_VALUE("format"),ge.BAD_REQUEST)}a(hW,"saveToLocal");async function SW(e){if(!e.s3||Object.keys(e.s3).length===0)throw Ne(new Error,Nt.MISSING_VALUE("S3 object"),ge.BAD_REQUEST);if(vt.isEmptyOrZeroLength(e.s3.aws_access_key_id))throw Ne(new Error,Nt.MISSING_VALUE("aws_access_key_id"),ge.BAD_REQUEST);if(vt.isEmptyOrZeroLength(e.s3.aws_secret_access_key))throw Ne(new Error,Nt.MISSING_VALUE("aws_secret_access_key"),ge.BAD_REQUEST);if(vt.isEmptyOrZeroLength(e.s3.bucket))throw Ne(new Error,Nt.MISSING_VALUE("bucket"),ge.BAD_REQUEST);if(vt.isEmptyOrZeroLength(e.s3.key))throw Ne(new Error,Nt.MISSING_VALUE("key"),ge.BAD_REQUEST);let t=CI(e);if(!vt.isEmpty(t))throw Ne(new Error,t,ge.BAD_REQUEST);et.trace(`called export_to_s3 to bucket: ${e.s3.bucket} and query ${e.search_operation.sql}`);let r;try{r=await wI(e)}catch(c){throw et.error(c),c}let s,n=zQ.getS3AuthObj(e.s3.aws_access_key_id,e.s3.aws_secret_access_key),i,o=new na.PassThrough;if(e.format===bI){i=e.s3.key+".csv";let c=na.Readable.from(r),_={},u={objectMode:!0},l=new eW(_,u);l.on("error",E=>{throw E}),c.pipe(l).pipe(o)}else if(e.format===II){i=e.s3.key+".json";let c=new na.Readable;c.pipe(o),c.on("error",l=>{throw l}),c.push("[");let _=r.length,u="";for(let[l,E]of r.entries())u+=l===_-1?JSON.stringify(E):JSON.stringify(E)+",",l!==0&&l%aW===0&&(c.push(u),u="");u.length!==0&&c.push(u),c.push("]"),c.push(null)}else throw Ne(new Error,Nt.INVALID_VALUE("format"),ge.BAD_REQUEST);try{s=await n.upload({Bucket:e.s3.bucket,Key:i,Body:o}).promise()}catch(c){throw et.error(c),c}return s}a(SW,"export_to_s3");function CI(e){if(et.trace("in exportCoreValidation"),vt.isEmpty(e.format))return"format missing";if(NI.indexOf(e.format)<0)return`format invalid. must be one of the following values: ${NI.join(", ")}`;let t=e.search_operation.operation;if(vt.isEmpty(t))return"search_operation.operation missing";if(pI.indexOf(t)<0)return`search_operation.operation must be one of the following values: ${pI.join(", ")}`}a(CI,"exportCoreValidation");async function wI(e){et.trace("in getRecords");let t,r;if(ia.isEmpty(e.search_operation)||ia.isEmptyOrZeroLength(e.search_operation.operation))throw Ne(new Error,Nt.INVALID_VALUE("Search operation"),ge.BAD_REQUEST);switch(e.search_operation.operation){case"search_by_value":t=_W;break;case"search_by_hash":t=cW;break;case"sql":t=uW;break;default:throw r=`Operation ${e.search_operation.operation} is not support by export.`,et.error(r),Ne(new Error,r,ge.BAD_REQUEST)}e.search_operation.hdb_user=e.hdb_user;try{return t(e.search_operation)}catch(s){throw et.error(s),s}}a(wI,"getRecords")});var yI=S((Q3,UI)=>{"use strict";var v_=class{constructor(t,r){this.operation="sql",this.sql=t,this.hdb_user=r}};a(v_,"SqlSearchObject");UI.exports=v_});var PI=S((W3,MI)=>{"use strict";var fW=T(),DI=require("moment"),TW=require("uuid").v4,H_=class{constructor(){this.id=TW(),this.type=void 0,this.start_datetime=DI().valueOf(),this.created_datetime=DI().valueOf(),this.end_datetime=void 0,this.status=fW.JOB_STATUS_ENUM.CREATED,this.message=void 0,this.user=void 0,this.request=void 0}};a(H_,"JobObject");MI.exports=H_});var Hd=S((J3,FI)=>{"use strict";var mW=require("uuid").v4,HI=Ut(),GI=mt(),RW=Kt(),AW=ds(),OW=yI(),oe=T(),pW=PI(),NW=SE(),Ht=I(),gW=ei(),Fn=b(),{promisify:vd}=require("util"),ks=require("moment"),IW=m_(),G_=Cd(),BI=Rl(),{deleteTransactionLogsBeforeValidator:bW}=Ed(),{handleHDBError:CW,hdb_errors:wW}=D(),{HTTP_STATUS_CODES:LW}=wW,vI=vd(GI.searchByValue),UW=vd(GI.searchByHash),yW=HI.insert,DW=vd(IW.evaluateSQL),MW=HI.update;FI.exports={addJob:vW,updateJob:GW,handleGetJob:PW,handleGetJobsByStartDate:BW,getJobById:qI};async function PW(e){try{let t=await qI(e.id);return Fn.isEmptyOrZeroLength(t)||(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 Ht.error(r),new Error(r)}}a(PW,"handleGetJob");async function BW(e){try{let t=await HW(e);if(Ht.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=ks(r.start_datetime)),r.end_datetime&&(r.end_datetime_converted=ks(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 Ht.error(r),new Error(r)}}a(BW,"handleGetJobsByStartDate");async function vW(e){let t={message:"",error:"",success:!1,createdJob:void 0};if(!e||Object.keys(e).length===0||Fn.isEmptyOrZeroLength(e.operation)){let l="job parameter is invalid";return Ht.info(l),t.error=l,t}if(!oe.JOB_TYPE_ENUM[e.operation])return Ht.info(`invalid job type specified: ${e.operation}.`),t;let r=e.operation,s;switch(r){case oe.OPERATIONS_ENUM.CSV_FILE_LOAD:s=G_.fileObject(e);break;case oe.OPERATIONS_ENUM.CSV_URL_LOAD:s=G_.urlObject(e);break;case oe.OPERATIONS_ENUM.CSV_DATA_LOAD:s=G_.dataObject(e);break;case oe.OPERATIONS_ENUM.IMPORT_FROM_S3:s=G_.s3FileObject(e);break;case oe.OPERATIONS_ENUM.DELETE_FILES_BEFORE:case oe.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE:s=BI(e,"date");break;case oe.OPERATIONS_ENUM.DELETE_AUDIT_LOGS_BEFORE:s=BI(e,"timestamp");break;case oe.OPERATIONS_ENUM.DELETE_TRANSACTION_LOGS_BEFORE:s=bW(e);break;default:break}if(s)throw CW(s,s.message,LW.BAD_REQUEST,void 0,void 0,!0);let n=new pW;n.type=e.operation===oe.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE?oe.OPERATIONS_ENUM.DELETE_FILES_BEFORE:e.operation,n.type=e.operation,n.user=e.hdb_user.username;let i=new RW(oe.SYSTEM_SCHEMA_NAME,oe.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,"id",n.id,"id",["id"]),o;try{o=await vI(i)}catch(l){let E=`There was an error inserting a new job: ${l}`;return Ht.error(E),t}let c=Array.isArray(o)?o:Object.keys(o);if(c&&c.length>0){n.id=mW();try{o=await vI(i)}catch(l){let E=`There was an error inserting a new job: ${l}`;return Ht.error(E),t}if(c=Array.isArray(o)?o:Object.keys(o),c&&c.length>0)return Ht.error("Error creating a job, could not find a unique job id."),t}n.request=e;let _=new gW(oe.SYSTEM_SCHEMA_NAME,oe.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,"id",[n]),u;try{u=await yW(_)}catch(l){return Ht.error(`There was an error inserting a job for job type: ${e.operation} -- ${l}`),t.success=!1,t}if(u.inserted_hashes.length===0)t.message=`Had a problem creating a job with type ${n.operation} and id ${n.id}`;else{let l=`Created a job with type ${n.type} and id ${n.id}`;t.message=l,t.createdJob=n,t.success=!0,Ht.trace(l)}return t}a(vW,"addJob");async function HW(e){let t=ks(e.from_date,ks.ISO_8601),r=ks(e.to_date,ks.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 s=`select * from system.hdb_job where start_datetime > '${t.valueOf()}' and start_datetime < '${r.valueOf()}'`,n=new OW(s,e.hdb_user);try{return await DW(n)}catch(i){throw Ht.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(HW,"getJobsInDateRange");async function qI(e){if(Fn.isEmptyOrZeroLength(e))return Fn.errorizeMessage("Invalid job ID specified.");let t=new AW(oe.SYSTEM_SCHEMA_NAME,oe.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,[e],["*"]);try{return await UW(t)}catch(r){let s=`There was an error searching for a job by id: ${e} ${r}`;return Ht.error(s),Fn.errorizeMessage("there was an error searching for jobs. Please check the log for details.")}}a(qI,"getJobById");async function GW(e){if(Object.keys(e).length===0)throw new Error("invalid job object passed to updateJob");if(Fn.isEmptyOrZeroLength(e.id))throw new Error("invalid ID passed to updateJob");(e.status===oe.JOB_STATUS_ENUM.COMPLETE||e.status===oe.JOB_STATUS_ENUM.ERROR)&&(e.end_datetime=ks().valueOf());let t=new NW(oe.SYSTEM_SCHEMA_NAME,oe.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,[e]),r;try{r=await MW(t)}catch(s){throw new Error(s)}return r}a(GW,"updateJob")});var KI=S((Z3,YI)=>{"use strict";var VI=b(),gt=T(),qW=require("moment"),q_=Md(),F_=I(),kI=Hd(),xI=Bd(),$I=Rs(),FW=Xc(),VW=$i(),kW=a_(),V_=class{constructor(t,r){this.job=t,this.json=r}};a(V_,"RunnerMessage");async function xW(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(VI.isEmptyOrZeroLength(e.json.operation))throw new Error("Invalid operation");if(VI.isEmptyOrZeroLength(e.job.id))throw new Error("Empty job id specified");switch(e.json.operation){case gt.JOB_TYPE_ENUM.csv_file_load:await wr(e,q_.csvFileLoad);break;case gt.JOB_TYPE_ENUM.csv_url_load:await wr(e,q_.csvURLLoad);break;case gt.JOB_TYPE_ENUM.csv_data_load:await wr(e,q_.csvDataLoad);break;case gt.JOB_TYPE_ENUM.import_from_s3:await wr(e,q_.importFromS3);break;case gt.JOB_TYPE_ENUM.empty_trash:break;case gt.JOB_TYPE_ENUM.export_local:await wr(e,xI.export_local);break;case gt.JOB_TYPE_ENUM.export_to_s3:await wr(e,xI.export_to_s3);break;case gt.JOB_TYPE_ENUM.delete_files_before:case gt.JOB_TYPE_ENUM.delete_records_before:await wr(e,$I.deleteFilesBefore);break;case gt.JOB_TYPE_ENUM.delete_audit_logs_before:await wr(e,$I.deleteAuditLogsBefore);break;case gt.JOB_TYPE_ENUM.delete_transaction_logs_before:await wr(e,kW.deleteTransactionLogsBefore);break;default:return`Invalid operation ${e.json.operation} specified`}}a(xW,"parseMessage");async function wr(e,t){try{e.job.status=gt.JOB_STATUS_ENUM.IN_PROGRESS,e.job.start_datetime=qW().valueOf(),await kI.updateJob(e.job),await $W(e.job.id)}catch(r){let s=r.message!==void 0?r.message:r;typeof s=="string"?(s=`There was an error running ${t.name} job with id ${e.job.id} - ${s}`,r.message=s):F_.error(`There was an error running ${t.name} job with id ${e.job.id}`),F_.error(s),e.job.message=s,e.job.status=gt.JOB_STATUS_ENUM.ERROR;try{await kI.updateJob(e.job)}catch(n){throw F_.error(`Unable to update job with id ${e.job.id}`),n}throw r}}a(wr,"runJob");async function $W(e){let t=FW.generateJobConfig(e);F_.trace("launching job process:",e),await VW.start(t)}a($W,"launchJobProcess");YI.exports={parseMessage:xW,RunnerMessage:V_}});var WI=S((X3,QI)=>{"use strict";var k_=class{constructor(t,r=void 0){this.operation_function=t,this.job_operation_function=r}};a(k_,"OperationFunctionObject");QI.exports=k_});var ob=S((z3,ab)=>{"use strict";var Y_=mt(),Vd=m_(),x_=Md(),Vn=tc(),Gd=fs(),oa=Rs(),YW=tE(),aa=Wr(),$_=uE(),Lr=ld(),Ve=I(),KW=dE(),QW=wc(),WW=vE(),JW=Dc(),ZW=HE(),XW=FE(),qd=xE(),JI=Bd(),zW=f_(),kd=Hd(),A=T(),{hdb_errors:_a,handleHDBError:ca}=D(),{HTTP_STATUS_CODES:ZI}=_a,Fd=KE(),XI=nd(),K_=require("util"),xs=Ut(),jW=xr(),e1=gc(),nb=Ns(),zI=KI(),jI=hc(),eb=Sr(),tb=a_(),rb=Sd(),t1=w_(),r1=K_.promisify(Y_.searchByHash),s1=K_.promisify(Y_.searchByValue),n1=K_.promisify(Y_.search),i1=K_.promisify(Vd.evaluateSQL),a1={[A.OPERATIONS_ENUM.CREATE_ATTRIBUTE]:!0,[A.OPERATIONS_ENUM.CREATE_TABLE]:!0,[A.OPERATIONS_ENUM.CREATE_SCHEMA]:!0,[A.OPERATIONS_ENUM.DROP_ATTRIBUTE]:!0,[A.OPERATIONS_ENUM.DROP_TABLE]:!0,[A.OPERATIONS_ENUM.DROP_SCHEMA]:!0},N=WI();function o1(e,t,r){return Promise.all([nb.postOperationHandler(e,t,r),e.table?xs.flush(e):null])}a(o1,"postWrite");async function c1(e,t){try{if(e.body.operation!=="read_log"&&(Ve.log_level===A.LOG_LEVELS.INFO||Ve.log_level===A.LOG_LEVELS.DEBUG||Ve.log_level===A.LOG_LEVELS.TRACE)){let{hdb_user:s,hdb_auth_header:n,password:i,...o}=e.body;Ve.info(o)}}catch(s){Ve.error(s)}let r=A.CLUSTER_OPERATIONS[e.body.operation]===void 0?null:o1;try{let s=await t1.callOperationFunctionAsAwait(t,e.body,r);if(typeof s!="object"&&(s={message:s}),s instanceof Error)throw s;return a1[e.body.operation]&&jW.setSchemaDataToGlobal(n=>{n&&Ve.error(n)}),s}catch(s){throw Ve.info(s),s}}a(c1,"processLocalTransaction");var sb=l1();ab.exports={chooseOperation:_1,getOperationFunction:ib,processLocalTransaction:c1};function _1(e){let t;try{t=ib(e)}catch(n){throw Ve.error(`Error when selecting operation function - ${n}`),n}let{operation_function:r,job_operation_function:s}=t;try{if(e.operation==="sql"||e.search_operation&&e.search_operation.operation==="sql"){let n=e.operation==="sql"?e.sql:e.search_operation.sql,i=Vd.convertSQLToAST(n);if(e.parsed_sql_object=i,!e.bypass_auth){let o=Vd.checkASTPermissions(e,i);if(o)throw Ve.error(`${ZI.FORBIDDEN} from operation ${e.search_operation}`),ca(new Error,o,_a.HTTP_STATUS_CODES.FORBIDDEN)}}else if(!e.bypass_auth&&e.operation!==A.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS){let n=s===void 0?r:s,i=e.search_operation?e.search_operation:e;i.hdb_user||(i.hdb_user=e.hdb_user);let o=zW.verifyPerms(i,n);if(o)throw Ve.error(`${ZI.FORBIDDEN} from operation ${e.operation}`),ca(new Error,o,_a.HTTP_STATUS_CODES.FORBIDDEN)}}catch(n){throw ca(n,"There was an error when trying to choose an operation path")}return r}a(_1,"chooseOperation");function ib(e){if(Ve.trace(`getOperationFunction with operation: ${e.operation}`),sb.has(e.operation))return sb.get(e.operation);throw ca(new Error,_a.HDB_ERROR_MSGS.OP_NOT_FOUND(e.operation),_a.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0)}a(ib,"getOperationFunction");async function u1(e){Ve.trace("In serverUtils.catchup");let t=e.transaction,r=t.channel.split(":"),s=r[0],n=r[1];for(let i of t.transactions)try{i.schema=s,i.table=n,i[A.CLUSTERING_FLAG]=!0;let o;switch(i.operation){case A.OPERATIONS_ENUM.INSERT:o=await xs.insert(i);break;case A.OPERATIONS_ENUM.UPDATE:o=await xs.update(i);break;case A.OPERATIONS_ENUM.UPSERT:o=await xs.upsert(i);break;case A.OPERATIONS_ENUM.DELETE:o=await oa.deleteRecord(i);break;default:Ve.warn("invalid operation in catchup");break}await nb.postOperationHandler(i,o,e)}catch(o){Ve.info("Invalid operation in transaction"),Ve.error(o)}}a(u1,"catchup");async function ur(e){let t,r;try{r=await kd.addJob(e),t=r.createdJob;let s=new zI.RunnerMessage(t,e);return await zI.parseMessage(s),`Starting job with id ${t.id}`}catch(s){let n=`There was an error executing job: ${s.http_resp_msg?s.http_resp_msg:s}`;throw Ve.error(n),ca(s,n)}}a(ur,"executeJob");function l1(){let e=new Map;return e.set(A.OPERATIONS_ENUM.INSERT,new N(xs.insert)),e.set(A.OPERATIONS_ENUM.UPDATE,new N(xs.update)),e.set(A.OPERATIONS_ENUM.UPSERT,new N(xs.upsert)),e.set(A.OPERATIONS_ENUM.SEARCH_BY_CONDITIONS,new N(Y_.searchByConditions)),e.set(A.OPERATIONS_ENUM.SEARCH_BY_HASH,new N(r1)),e.set(A.OPERATIONS_ENUM.SEARCH_BY_VALUE,new N(s1)),e.set(A.OPERATIONS_ENUM.SEARCH,new N(n1)),e.set(A.OPERATIONS_ENUM.SQL,new N(i1)),e.set(A.OPERATIONS_ENUM.CSV_DATA_LOAD,new N(ur,x_.csvDataLoad)),e.set(A.OPERATIONS_ENUM.CSV_FILE_LOAD,new N(ur,x_.csvFileLoad)),e.set(A.OPERATIONS_ENUM.CSV_URL_LOAD,new N(ur,x_.csvURLLoad)),e.set(A.OPERATIONS_ENUM.IMPORT_FROM_S3,new N(ur,x_.importFromS3)),e.set(A.OPERATIONS_ENUM.CREATE_SCHEMA,new N(Vn.createSchema)),e.set(A.OPERATIONS_ENUM.CREATE_TABLE,new N(Vn.createTable)),e.set(A.OPERATIONS_ENUM.CREATE_ATTRIBUTE,new N(Vn.createAttribute)),e.set(A.OPERATIONS_ENUM.DROP_SCHEMA,new N(Vn.dropSchema)),e.set(A.OPERATIONS_ENUM.DROP_TABLE,new N(Vn.dropTable)),e.set(A.OPERATIONS_ENUM.DROP_ATTRIBUTE,new N(Vn.dropAttribute)),e.set(A.OPERATIONS_ENUM.DESCRIBE_SCHEMA,new N(Gd.describeSchema)),e.set(A.OPERATIONS_ENUM.DESCRIBE_TABLE,new N(Gd.describeTable)),e.set(A.OPERATIONS_ENUM.DESCRIBE_ALL,new N(Gd.describeAll)),e.set(A.OPERATIONS_ENUM.DELETE,new N(oa.deleteRecord)),e.set(A.OPERATIONS_ENUM.ADD_USER,new N(aa.addUser)),e.set(A.OPERATIONS_ENUM.ALTER_USER,new N(aa.alterUser)),e.set(A.OPERATIONS_ENUM.DROP_USER,new N(aa.dropUser)),e.set(A.OPERATIONS_ENUM.LIST_USERS,new N(aa.listUsersExternal)),e.set(A.OPERATIONS_ENUM.LIST_ROLES,new N($_.listRoles)),e.set(A.OPERATIONS_ENUM.ADD_ROLE,new N($_.addRole)),e.set(A.OPERATIONS_ENUM.ALTER_ROLE,new N($_.alterRole)),e.set(A.OPERATIONS_ENUM.DROP_ROLE,new N($_.dropRole)),e.set(A.OPERATIONS_ENUM.USER_INFO,new N(aa.userInfo)),e.set(A.OPERATIONS_ENUM.READ_LOG,new N(KW)),e.set(A.OPERATIONS_ENUM.ADD_NODE,new N(QW)),e.set(A.OPERATIONS_ENUM.UPDATE_NODE,new N(WW)),e.set(A.OPERATIONS_ENUM.REMOVE_NODE,new N(JW)),e.set(A.OPERATIONS_ENUM.CONFIGURE_CLUSTER,new N(ZW)),e.set(A.OPERATIONS_ENUM.SET_CONFIGURATION,new N(eb.setConfiguration)),e.set(A.OPERATIONS_ENUM.CLUSTER_STATUS,new N(XW.clusterStatus)),e.set(A.OPERATIONS_ENUM.CLUSTER_SET_ROUTES,new N(qd.setRoutes)),e.set(A.OPERATIONS_ENUM.CLUSTER_GET_ROUTES,new N(qd.getRoutes)),e.set(A.OPERATIONS_ENUM.CLUSTER_DELETE_ROUTES,new N(qd.deleteRoutes)),e.set(A.OPERATIONS_ENUM.EXPORT_TO_S3,new N(ur,JI.export_to_s3)),e.set(A.OPERATIONS_ENUM.DELETE_FILES_BEFORE,new N(ur,oa.deleteFilesBefore)),e.set(A.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE,new N(ur,oa.deleteFilesBefore)),e.set(A.OPERATIONS_ENUM.EXPORT_LOCAL,new N(ur,JI.export_local)),e.set(A.OPERATIONS_ENUM.SEARCH_JOBS_BY_START_DATE,new N(kd.handleGetJobsByStartDate)),e.set(A.OPERATIONS_ENUM.GET_JOB,new N(kd.handleGetJob)),e.set(A.OPERATIONS_ENUM.GET_FINGERPRINT,new N(Fd.getFingerprint)),e.set(A.OPERATIONS_ENUM.SET_LICENSE,new N(Fd.setLicense)),e.set(A.OPERATIONS_ENUM.GET_REGISTRATION_INFO,new N(Fd.getRegistrationInfo)),e.set(A.OPERATIONS_ENUM.RESTART,new N(XI.restartProcesses)),e.set(A.OPERATIONS_ENUM.RESTART_SERVICE,new N(XI.restartService)),e.set(A.OPERATIONS_ENUM.CATCHUP,new N(u1)),e.set(A.OPERATIONS_ENUM.SYSTEM_INFORMATION,new N(e1.systemInformation)),e.set(A.OPERATIONS_ENUM.DELETE_AUDIT_LOGS_BEFORE,new N(ur,oa.deleteAuditLogsBefore)),e.set(A.OPERATIONS_ENUM.READ_AUDIT_LOG,new N(YW)),e.set(A.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS,new N(jI.createTokens)),e.set(A.OPERATIONS_ENUM.REFRESH_OPERATION_TOKEN,new N(jI.refreshOperationToken)),e.set(A.OPERATIONS_ENUM.GET_CONFIGURATION,new N(eb.getConfiguration)),e.set(A.OPERATIONS_ENUM.CUSTOM_FUNCTIONS_STATUS,new N(Lr.customFunctionsStatus)),e.set(A.OPERATIONS_ENUM.GET_CUSTOM_FUNCTIONS,new N(Lr.getCustomFunctions)),e.set(A.OPERATIONS_ENUM.GET_CUSTOM_FUNCTION,new N(Lr.getCustomFunction)),e.set(A.OPERATIONS_ENUM.SET_CUSTOM_FUNCTION,new N(Lr.setCustomFunction)),e.set(A.OPERATIONS_ENUM.DROP_CUSTOM_FUNCTION,new N(Lr.dropCustomFunction)),e.set(A.OPERATIONS_ENUM.ADD_CUSTOM_FUNCTION_PROJECT,new N(Lr.addCustomFunctionProject)),e.set(A.OPERATIONS_ENUM.DROP_CUSTOM_FUNCTION_PROJECT,new N(Lr.dropCustomFunctionProject)),e.set(A.OPERATIONS_ENUM.PACKAGE_CUSTOM_FUNCTION_PROJECT,new N(Lr.packageCustomFunctionProject)),e.set(A.OPERATIONS_ENUM.DEPLOY_CUSTOM_FUNCTION_PROJECT,new N(Lr.deployCustomFunctionProject)),e.set(A.OPERATIONS_ENUM.READ_TRANSACTION_LOG,new N(tb.readTransactionLog)),e.set(A.OPERATIONS_ENUM.DELETE_TRANSACTION_LOGS_BEFORE,new N(ur,tb.deleteTransactionLogsBefore)),e.set(A.OPERATIONS_ENUM.INSTALL_NODE_MODULES,new N(rb.installModules)),e.set(A.OPERATIONS_ENUM.AUDIT_NODE_MODULES,new N(rb.auditModules)),e}a(l1,"initializeOperationFunctionMap")});var lb=S((j3,ub)=>{"use strict";var E1=require("node-ipc").IPC,cb=b(),_b=T(),Ur=I(),{IPC_ERRORS:kn}=Ke(),d1=require("os"),Q_=class{constructor(t,r){this.ipc=new E1,this.server_name=_b.HDB_IPC_SERVER,this.ipc.config.retry=d1.platform()=="win32"?6e5:100,this.ipc.config.id=_b.HDB_IPC_CLIENT_PREFIX+t,this.ipc.config.silent=!0,this.event_handlers=r,this.connect()}connect(){this.ipc.connectTo(this.server_name,()=>{this.generateEventHandlers(this.event_handlers)})}addEventHandler(t,r){this.ipc.of[this.server_name].on(t,r)}generateEventHandlers(t){this.ipc.of[this.server_name].on("connect",()=>{Ur.info(`IPC client ${this.ipc.config.id} connected to ${this.server_name}`)}),this.ipc.of[this.server_name].on("disconnect",()=>{Ur.info(`IPC client ${this.ipc.config.id} disconnected from ${this.server_name}`)}),this.ipc.of[this.server_name].on("error",r=>{r.code==="ECONNREFUSED"&&Ur.warn("Error connecting to HDB IPC server. Confirm that the server is running."),Ur.warn(`Error with IPC client ${this.ipc.config.id}`),Ur.warn(r)});for(let[r,s]of Object.entries(t))this.addEventHandler(r,s)}emitToServer(t){if(typeof t!="object")throw Ur.warn(kn.INVALID_IPC_DATA_TYPE),new Error(kn.INVALID_IPC_DATA_TYPE);if(cb.isEmpty(t.type))throw Ur.warn(kn.MISSING_TYPE),new Error(kn.MISSING_TYPE);if(cb.isEmpty(t.message))throw Ur.warn(kn.MISSING_MSG),new Error(kn.MISSING_MSG);Ur.trace(`IPC client ${this.ipc.config.id} emitting`,t),this.ipc.of[this.server_name].emit("message",t)}};a(Q_,"IPCClient");ub.exports=Q_});var Sb=S((e2,hb)=>{"use strict";var h1=require("util"),{toJsMsg:S1}=require("nats"),{decode:f1}=require("msgpackr"),T1=xr(),m1=_A(),R1=ot(),J_=_e(),A1=T(),$s=I(),O1=ob(),p1=lb(),N1=w_(),g1=Ns(),I1=h1.promisify(T1.setSchemaDataToGlobal),b1={durable:J_.WORK_QUEUE_CONSUMER_NAMES.durable_name,queue:J_.WORK_QUEUE_CONSUMER_NAMES.deliver_group,filterSubject:`${J_.SUBJECT_PREFIXES.TXN}.>`},xd,$d,C1,w1;hb.exports={initialize:L1,workQueueListener:U1};async function L1(){$s.notify("Starting clustering ingest service."),await I1();try{global.hdb_ipc=new p1(process.pid,m1)}catch(s){throw $s.error("Error instantiating new instance of IPC client in natsIngestService"),s}let{connection:e,jsm:t,js:r}=await R1.getNATSReferences();xd=e,$d=e.info.server_name,C1=t,w1=r}a(L1,"initialize");var db=100,Eb=new Array(db),W_=0;async function U1(){let e=xd.subscribe(`${J_.WORK_QUEUE_CONSUMER_NAMES.deliver_subject}.${xd.info.server_name}`,b1);for await(let t of e)await Eb[W_],Eb[W_]=y1(t).catch(r=>{$s.error(r)}),++W_>=db&&(W_=0)}a(U1,"workQueueListener");async function y1(e){let t=S1(e);t.working();let r=f1(t.data);$s.trace("processing message:",r);let s=[],n=[];if(t.headers){let o=t.headers.get("originators");o&&(n=o.split(","),s=n)}let i;if($s.trace(`messageProcessor originators: ${s} on server: ${$d}`),s.indexOf($d)<0){let o,c=O1.getOperationFunction(r);o=c.job_operation_function?c.job_operation_function:c.operation_function;try{c.job_operation_function?i=await o(r,s):(r[A1.CLUSTERING_FLAG]=!0,i=await N1.callOperationFunctionAsAwait(o,r,g1.postOperationHandler,s)),$s.debug(i)}catch(_){$s.error(_)}}return t.ack(),i}a(y1,"messageProcessor")});var fb=Sb();(async()=>{try{await fb.initialize(),await fb.workQueueListener()}catch(e){console.error("Error launching Nats ingest service."),console.error(e)}})();
|
|
12
|
+
`,""):null}catch(d){d.stderr?i[_].npm_error=dg(d.stderr):i[_].npm_error=d.message;continue}try{i[_].npm_output=JSON.parse(l)}catch{i[_].npm_output=l}try{i[_].npm_error=JSON.parse(E)}catch{i[_].npm_error=E}}return o_.info(`finished installModules with response ${i}`),i}a(cK,"installModules");function dg(e){let t='"error": {',r=e.indexOf('"error": {'),s=e.indexOf(`}
|
|
13
|
+
`);return r>-1&&s>-1?JSON.parse(e.substring(r+t.length-1,s+1)):e}a(dg,"parseNPMStdErr");async function _K(e){o_.info(`starting auditModules for request: ${e}`);let t=fg(e);if(t)throw Bn(t,t.message,vn.BAD_REQUEST);let{projects:r}=e;await hg(),await Sg(r);let s={};for(let n=0,i=r.length;n<i;n++){let o=r[n],c=a_.join(ld,o);s[o]={npm_output:null,npm_error:null};try{let _=await Eg("npm audit --json",c);s[o].npm_output=JSON.parse(_)}catch(_){s[o].npm_error=dg(_.stderr)}}return o_.info(`finished auditModules with response ${s}`),s}a(_K,"auditModules");async function hg(){try{return await Eg("npm -v"),!0}catch{throw Bn(new Error,"Unable to install project dependencies: npm is not installed on this instance of HarperDB.",vn.BAD_REQUEST,void 0,void 0,!0)}}a(hg,"checkNPMInstalled");async function Sg(e){if(!Array.isArray(e)||e.length===0)throw Bn(new Error,"projects argument must be an array with at least 1 element",vn.BAD_REQUEST,void 0,void 0,!0);let t=[],r=[];for(let s=0,n=e.length;s<n;s++){let i=e[s],o=a_.join(ld,i.toString());if(!await cg.pathExists(o)){t.push(i);continue}let _=a_.join(o,"package.json");await cg.pathExists(_)||r.push(i)}if(t.length>0)throw Bn(new Error,`Unable to install project dependencies: custom function projects '${t.join(",")}' does not exist.`,vn.BAD_REQUEST,void 0,void 0,!0);if(r.length>0)throw Bn(new Error,`Unable to install project dependencies: custom function projects '${r.join(",")}' do not have a package.json file.`,vn.BAD_REQUEST,void 0,void 0,!0)}a(Sg,"checkProjectPaths");function fg(e){let t=i_.object({projects:i_.array().min(1).items(i_.string()).required(),dry_run:i_.boolean().default(!1)});return aK.validateBySchema(e,t)}a(fg,"modulesValidator")});var Rg=S((R3,mg)=>{"use strict";var c_=class{constructor(t,r,s=[],n=[]){this.schema=t,this.table=r,this.required_table_permissions=s,this.required_attribute_permissions=n}};a(c_,"PermissionTableResponseObject");mg.exports=c_});var Og=S((A3,Ag)=>{"use strict";var __=class{constructor(t,r=[]){this.attribute_name=t,this.required_permissions=r}};a(__,"PermissionAttributeResponseObject");Ag.exports=__});var dd=S((O3,Ng)=>{"use strict";var pg=Rg(),uK=Og(),{HDB_ERROR_MSGS:lK}=Ke(),u_=class{constructor(){this.error=lK.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,s){if(r&&s){let n=`${r}_${s}`;if(this.unauthorized_access[n])return}this.invalid_schema_items.push(t)}addUnauthorizedTable(t,r,s){let n=new pg(t,r,s),i=`${t}_${r}`;this.unauthorized_access[i]=n}addUnauthorizedAttributes(t,r,s,n){let i=[];t.forEach(c=>{let _=new uK(c,n[c]);i.push(_)});let o=`${r}_${s}`;if(this.unauthorized_access[o])this.unauthorized_access[o].required_attribute_permissions=i;else{let c=new pg(r,s,[],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}};a(u_,"PermissionResponseObject");Ng.exports=u_});var h_=S((p3,qg)=>{"use strict";var hd=Lt(),l_=Tt(),Pt=jo(),Ji=ds(),Sd=fs(),EK=zl(),Xi=xr(),E_=oE(),Oe=I(),dK=uE(),hK=bc(),SK=ME(),fK=Uc(),TK=PE(),mK=HE(),fd=FE(),pr=b(),RK=xp(),Td=$E(),bg=td(),Mt=T(),wg=xN(),AK=pc(),Cg=Ec(),Lg=ur(),Nr=cd(),OK=require("alasql"),Ug=n_(),yg=Ed(),Dg=dd(),{handleHDBError:Et,hdb_errors:Mg}=D(),{HDB_ERROR_MSGS:Ge,HTTP_STATUS_CODES:Wi}=Mg,O=new Map,Pg="delete",jr="insert",ar="read",Ps="update",Qi="describe",gg=Ji.describeSchema.name,Ig=Ji.describeTable.name,Bg={delete:!0,deleteRecord:!0,update:!0,updateData:!0,dropAttribute:!0,dropTable:!0,dropSchema:!0,upsert:!0,upsertData:!0},pK="catchup",NK="handleGetJob",gK="handleGetJobsByStartDate",d_={CSV_DATA_LOAD:"csvDataLoad",CSV_URL_LOAD:"csvURLLoad",CSV_FILE_LOAD:"csvFileLoad",IMPORT_FROM_S3:"importFromS3"},IK=[Pt.createTable.name,Pt.createAttribute.name,Pt.dropTable.name,Pt.dropAttribute.name],vg={EXPORT_TO_S3:"export_to_s3",EXPORT_LOCAL:"export_local"},p=class{constructor(t,r){this.requires_su=t,this.perms=r}};a(p,"permission");O.set(hd.insert.name,new p(!1,[jr]));O.set(hd.update.name,new p(!1,[Ps]));O.set(hd.upsert.name,new p(!1,[jr,Ps]));O.set(l_.searchByConditions.name,new p(!1,[ar]));O.set(l_.searchByHash.name,new p(!1,[ar]));O.set(l_.searchByValue.name,new p(!1,[ar]));O.set(l_.search.name,new p(!1,[ar]));O.set(Pt.createSchema.name,new p(!0,[]));O.set(Pt.createTable.name,new p(!0,[]));O.set(Pt.createAttribute.name,new p(!1,[jr]));O.set(Pt.dropSchema.name,new p(!0,[]));O.set(Pt.dropTable.name,new p(!0,[]));O.set(Pt.dropAttribute.name,new p(!0,[]));O.set(Ji.describeSchema.name,new p(!1,[ar]));O.set(Ji.describeTable.name,new p(!1,[ar]));O.set(Sd.deleteRecord.name,new p(!1,[Pg]));O.set(Xi.addUser.name,new p(!0,[]));O.set(Xi.alterUser.name,new p(!0,[]));O.set(Xi.dropUser.name,new p(!0,[]));O.set(Xi.listUsersExternal.name,new p(!0,[]));O.set(E_.listRoles.name,new p(!0,[]));O.set(E_.addRole.name,new p(!0,[]));O.set(E_.alterRole.name,new p(!0,[]));O.set(E_.dropRole.name,new p(!0,[]));O.set(dK.name,new p(!0,[]));O.set(hK.name,new p(!0,[]));O.set(SK.name,new p(!0,[]));O.set(fK.name,new p(!0,[]));O.set(TK.name,new p(!0,[]));O.set(fd.setRoutes.name,new p(!0,[]));O.set(fd.getRoutes.name,new p(!0,[]));O.set(fd.deleteRoutes.name,new p(!0,[]));O.set(Lg.setConfiguration.name,new p(!0,[]));O.set(mK.clusterStatus.name,new p(!0,[]));O.set(Td.getFingerprint.name,new p(!0,[]));O.set(Td.setLicense.name,new p(!0,[]));O.set(Sd.deleteFilesBefore.name,new p(!0,[]));O.set(Sd.deleteAuditLogsBefore.name,new p(!0,[]));O.set(bg.restartProcesses.name,new p(!0,[]));O.set(bg.restartService.name,new p(!0,[]));O.set(EK.name,new p(!0,[]));O.set(AK.systemInformation.name,new p(!0,[]));O.set(Lg.getConfiguration.name,new p(!0,[]));O.set(Ug.readTransactionLog.name,new p(!0,[]));O.set(Ug.deleteTransactionLogsBefore.name,new p(!0,[]));O.set(yg.installModules.name,new p(!0,[]));O.set(yg.auditModules.name,new p(!0,[]));O.set(Cg.createTokens.name,new p(!1,[]));O.set(Cg.refreshOperationToken.name,new p(!1,[]));O.set(Nr.customFunctionsStatus.name,new p(!0,[]));O.set(Nr.getCustomFunctions.name,new p(!0,[]));O.set(Nr.getCustomFunction.name,new p(!0,[]));O.set(Nr.setCustomFunction.name,new p(!0,[]));O.set(Nr.dropCustomFunction.name,new p(!0,[]));O.set(Nr.addCustomFunctionProject.name,new p(!0,[]));O.set(Nr.dropCustomFunctionProject.name,new p(!0,[]));O.set(Nr.packageCustomFunctionProject.name,new p(!0,[]));O.set(Nr.deployCustomFunctionProject.name,new p(!0,[]));O.set(Td.getRegistrationInfo.name,new p(!1,[]));O.set(Xi.userInfo.name,new p(!1,[]));O.set(Ji.describeAll.name,new p(!1,[]));O.set(NK,new p(!1,[]));O.set(gK,new p(!0,[]));O.set(pK,new p(!0,[]));O.set(d_.CSV_DATA_LOAD,new p(!1,[jr,Ps]));O.set(d_.CSV_URL_LOAD,new p(!1,[jr,Ps]));O.set(d_.CSV_FILE_LOAD,new p(!1,[jr,Ps]));O.set(d_.IMPORT_FROM_S3,new p(!1,[jr,Ps]));O.set(vg.EXPORT_TO_S3,new p(!1,[ar]));O.set(vg.EXPORT_LOCAL,new p(!1,[ar]));O.set(Mt.VALID_SQL_OPS_ENUM.DELETE,new p(!1,[Pg]));O.set(Mt.VALID_SQL_OPS_ENUM.SELECT,new p(!1,[ar]));O.set(Mt.VALID_SQL_OPS_ENUM.INSERT,new p(!1,[jr]));O.set(Mt.VALID_SQL_OPS_ENUM.UPDATE,new p(!1,[Ps]));qg.exports={verifyPerms:wK,verifyPermsAst:bK,verifyBulkLoadAttributePerms:LK};function bK(e,t,r){if(pr.isEmptyOrZeroLength(e))throw Oe.info("verify_perms_ast has an empty user parameter"),Et(new Error);if(pr.isEmptyOrZeroLength(t))throw Oe.info("verify_perms_ast has an empty user parameter"),Et(new Error);if(pr.isEmptyOrZeroLength(r))throw Oe.info("verify_perms_ast has a null operation parameter"),Et(new Error);try{let s=new Dg,n=new RK(e),i=n.getSchemas(),o=new Map;if((!i||i.length===0)&&n.affected_attributes&&n.affected_attributes.size>0)throw Oe.info("No schemas defined in verifyPermsAst(), will not continue."),Et(new Error);let c=!!t.role.permission.super_user,_=i.includes("system");if(_&&Bg[r])throw Et(new Error,Ge.DROP_SYSTEM,Wi.FORBIDDEN);if(c&&!_)return null;let u=wg.getRolePermissions(t.role);t.role.permission=u,!c&&e instanceof OK.yy.Select&&(e=n.updateAttributeWildcardsForRolePerms(u));for(let E=0;E<i.length;E++){let d=n.getTablesBySchemaName(i[E]);d&&o.set(i[E],d)}let l=Hg(t,r,o,s);return l||(o.forEach((E,d)=>{for(let h=0;h<E.length;h++){let m=n.getAttributesBySchemaTableName(d,E[h]),R=Rd(t.role.permission,d,E[h]);md(m,R,r,E[h],d,s)}}),s.getPermsResponse())}catch(s){throw Et(s)}}a(bK,"verifyPermsAst");function wK(e,t){if(e===null||t===null||e.hdb_user===void 0||e.hdb_user===null)throw Oe.info("null required parameter in verifyPerms"),Et(new Error,Ge.DEFAULT_INVALID_REQUEST,Wi.BAD_REQUEST);let r;t instanceof Function?r=t.name:r=t;let s=e.action,n=e.schema,i=e.table,o=new Map;n&&i&&o.set(n,[i]);let c=new Dg;if(pr.isEmptyOrZeroLength(e.hdb_user.role)||pr.isEmptyOrZeroLength(e.hdb_user.role.permission))return Oe.info(`User ${e.hdb_user.username} has no role or permissions. Please assign the user a valid role.`),c.handleUnauthorizedItem(Ge.USER_HAS_NO_PERMS(e.hdb_user.username));let _=!!e.hdb_user.role.permission.super_user,u=e.hdb_user.role.permission.structure_user,l=o.has(Mt.SYSTEM_SCHEMA_NAME)||n===Mt.SYSTEM_SCHEMA_NAME;if(l&&Bg[r])throw Et(new Error,Ge.DROP_SYSTEM,Wi.FORBIDDEN);if(_&&!l||u===!0&&(r===Pt.createSchema.name||r===Pt.dropSchema.name))return null;if(IK.indexOf(r)>=0&&(u===!0||Array.isArray(u)))return u===!0||u.indexOf(n)>=0?null:c.handleUnauthorizedItem(`User does not have access to perform '${e.operation}' against schema '${n}'`);let E=wg.getRolePermissions(e.hdb_user.role);if(e.hdb_user.role.permission=E,r===gg||r===Ig){if(n===Mt.SYSTEM_SCHEMA_NAME)return c.handleUnauthorizedItem(Ge.SCHEMA_PERM_ERROR(n));if(!E.super_user){if(r===gg&&(!E[n]||!E[n][Qi]))return c.handleInvalidItem(Ge.SCHEMA_NOT_FOUND(n));if(r===Ig&&(!E[n]||!E[n].tables[i]||!E[n].tables[i][Qi]))return c.handleInvalidItem(Ge.TABLE_NOT_FOUND(n,i))}}let d=Hg(e.hdb_user,r,o,c,s);if(d)return d;if(O.get(r)&&O.get(r).perms.length===0)return null;if(!_&&e.get_attributes&&Mt.SEARCH_WILDCARDS.includes(e.get_attributes[0])){let R=[],C=E[n].tables[i];C[Mt.PERMS_CRUD_ENUM.READ]&&(C.attribute_permissions.length>0?C.attribute_permissions.filter(B=>B[Mt.PERMS_CRUD_ENUM.READ]).forEach(B=>{R.push(B.attribute_name)}):R=global.hdb_schema[n][i].attributes.map(L=>L.attribute),e.get_attributes=R)}let h=CK(e),m=Rd(e.hdb_user.role.permission,n,i);return md(h,m,r,i,n,c,s),c.getPermsResponse()}a(wK,"verifyPerms");function Hg(e,t,r,s,n){if(pr.arrayHasEmptyValues([e,t,r]))throw Oe.info("hasPermissions has an invalid parameter"),Et(new Error);let i=r.has("system"),o=e.role.permission;if(o.super_user&&!i)return null;if(!O.get(t))throw Oe.info(`operation ${t} not found.`),Et(new Error,Ge.OP_NOT_FOUND(t),Wi.BAD_REQUEST);if(O.get(t)&&O.get(t).requires_su)return Oe.info(`operation ${t} requires SU permissions.`),s.handleUnauthorizedItem(Ge.OP_IS_SU_ONLY(t));let c=r.keys();for(let _ of c){try{if(_&&!o[_]||o[_][Qi]===!1){s.addInvalidItem(Ge.SCHEMA_NOT_FOUND(_));continue}}catch{s.addInvalidItem(Ge.SCHEMA_NOT_FOUND(_));continue}let u=r.get(_);for(let l of u){let E=o[_].tables[l];if(!E||E[Qi]===!1)s.addInvalidItem(Ge.TABLE_NOT_FOUND(_,l));else try{let d=[],h=O.get(t).perms;!pr.isEmpty(n)&&h.includes(n)&&(h=[n]);for(let m=0;m<h.length;m++){let R=h[m],C=E[R];(C==null||C===!1)&&(Oe.info(`Required ${R} permission not found for ${t} ${n?`${n} `:""}operation in role ${e.role.id}`),d.push(R))}d.length>0&&s.addUnauthorizedTable(_,l,d)}catch(d){let h=Ge.UNKNOWN_OP_AUTH_ERROR(t,_,l);throw Oe.error(h),Oe.error(d),Et(Mg.CHECK_LOGS_WRAPPER(h))}}}return r.size<2?s.getPermsResponse():null}a(Hg,"hasPermissions");function md(e,t,r,s,n,i,o){if(!e||!t)throw Oe.info("no attributes specified in checkAttributePerms."),Et(new Error);let c=O.get(r).perms;if(!c||c==="")throw Oe.info(`no permissions found for ${r} in checkAttributePerms().`),Et(new Error);if(pr.isEmptyOrZeroLength(t))return Oe.info("No role permissions set (this is OK)."),null;o&&c.includes(o)&&(c=[o]);let _={};for(let l of e){let E=t.get(l);if(E){if(E[Qi]===!1){i.addInvalidItem(Ge.ATTR_NOT_FOUND(n,s,l),n,s);continue}if(c)for(let d of c){if(Mt.TIME_STAMP_NAMES.includes(E.attribute_name)&&d!==ar)throw Et(new Error,Ge.SYSTEM_TIMESTAMP_PERMS_ERR,Wi.FORBIDDEN);E[d]===!1&&(_[E.attribute_name]?_[E.attribute_name].push(d):_[E.attribute_name]=[d])}}else i.addInvalidItem(Ge.ATTR_NOT_FOUND(n,s,l),n,s)}let u=Object.keys(_);u.length>0&&i.addUnauthorizedAttributes(u,n,s,_)}a(md,"checkAttributePerms");function CK(e){let t=new Set;try{if(e.action)return t;if(e.operation===Mt.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 s=Object.keys(e.records[r]);for(let n=0;n<s.length;n++)t.add(s[n])}}catch(r){Oe.info(r)}return t}a(CK,"getRecordAttributes");function Rd(e,t,r){let s=new Map;if(pr.isEmpty(e))return Oe.info("no hdb_user specified in getAttributePermissions"),s;if(e.super_user||!t||!r)return s;try{e[t].tables[r].attribute_permissions.forEach(n=>{s.has(n.attribute_name)||s.set(n.attribute_name,n)})}catch{Oe.info(`No attribute permissions found for schema ${t} and table ${r}.`)}return s}a(Rd,"getAttributePermissions");function LK(e,t,r,s,n,i,o){let c=new Set(i),_=Rd(e,s,n);md(c,_,t,n,s,o,r)}a(LK,"verifyBulkLoadAttributePerms")});var f_=S((N3,$g)=>{"use strict";$g.exports={evaluateSQL:xK,processAST:kg,convertSQLToAST:Vg,checkASTPermissions:Fg};var Gg=Lt(),pd=require("util"),UK=pd.callbackify(Gg.insert),yK=Tt().search,DK=PA().update,MK=pd.callbackify(DK),PK=vA().convertDelete,es=require("alasql"),BK=h_(),zi=I(),vK=wo(),HK=b(),Zi=T(),{hdb_errors:qK,handleHDBError:Ad}=D(),{HTTP_STATUS_CODES:Od}=qK,GK=As();function FK(e,t,r){return Promise.all([GK.postOperationHandler(e,t,r),Gg.flush(e)])}a(FK,"postWrite");var VK=pd.callbackify(FK);vK(es);var kK=403,$K="There was a problem performing this insert. Please check the logs and try again.",S_=class{constructor(){this.ast=void 0,this.variant=void 0,this.permissions_checked=!1}};a(S_,"ParsedSQLObject");function xK(e,t){let r=e.parsed_sql_object;if(!r){r=Vg(e.sql);let s,n=r.ast.statements[0];if(n instanceof es.yy.Insert?s=n.into.databaseid:n instanceof es.yy.Select?s=n.from?n.from[0].databaseid:null:n instanceof es.yy.Update||n instanceof es.yy.Delete?s=n.table.databaseid:zi.error("AST in evaluateSQL is not a valid SQL type."),!(n instanceof es.yy.Select)&&HK.isEmptyOrZeroLength(s))return t("No schema specified",null)}kg(e,r,(s,n)=>{if(s)return t(s);t(null,n)})}a(xK,"evaluateSQL");function Fg(e,t){let r;try{r=BK.verifyPermsAst(t.ast.statements[0],e.hdb_user,t.variant),t.permissions_checked=!0}catch(s){throw s}return r||null}a(Fg,"checkASTPermissions");function Vg(e){let t=new S_;if(!e)throw Ad(new Error,"The 'sql' parameter is missing from the request body",Od.BAD_REQUEST);try{let r=e.trim(),s=es.parse(r),n=r.split(" ")[0].toLowerCase();t.ast=s,t.variant=n}catch(r){let s=r.message.split(`
|
|
14
|
+
`);throw s[1]?Ad(r,`Invalid SQL at: ${s[1]}. Please ensure your SQL is valid. Try adding backticks to reserved words and schema table references.`,Od.BAD_REQUEST):Ad(r,"We had trouble parsing your request. Please ensure your SQL is valid. Try adding backticks to reserved words and schema table references.",Od.BAD_REQUEST)}return t}a(Vg,"convertSQLToAST");function kg(e,t,r){try{let s=YK;if(!e.bypass_auth&&!t.permissions_checked){let i=Fg(e,t);if(i&&i.length>0)return r(kK,i)}let n={statement:t.ast.statements[0],hdb_user:e.hdb_user};switch(t.variant){case Zi.VALID_SQL_OPS_ENUM.SELECT:s=yK,n=t.ast.statements[0];break;case Zi.VALID_SQL_OPS_ENUM.INSERT:s=KK;break;case Zi.VALID_SQL_OPS_ENUM.UPDATE:s=MK;break;case Zi.VALID_SQL_OPS_ENUM.DELETE:s=PK;break;default:throw new Error(`unsupported SQL type ${t.variant} in SQL: ${e}`)}s(n,(i,o)=>{if(i){r(i);return}r(null,o)})}catch(s){return r(s)}}a(kg,"processAST");function YK(e,t){zi.info(e),t("unknown sql statement")}a(YK,"nullFunction");function KK({statement:e,hdb_user:t},r){let s=e.into,n={schema:s.databaseid,table:s.tableid,operation:"insert",hdb_user:t},i=e.columns.map(o=>o.columnid);try{n.records=WK(i,e.values)}catch(o){return r(o)}UK(n,(o,c)=>{if(o)return r(o);VK(n,c,_=>{_&&zi.error(_)});try{delete c.new_attributes,delete c.txn_time}catch(_){zi.error(`Error delete new_attributes from insert response: ${_}`)}r(null,c)})}a(KK,"convertInsert");function WK(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 s={};return r.forEach((n,i)=>{if(n.columnid)throw"cannot use a column in insert value";"value"in n?s[e[i]]=n.value:s[e[i]]=es.compile(`SELECT ${n.toString()} AS [${Zi.FUNC_VAL}] FROM ?`)}),s})}catch(r){throw zi.error(r),new Error($K)}}a(WK,"createDataObjects")});var gd=S((g3,Qg)=>{var O_=require("clone"),p_=de(),QK=b(),A_=T(),JK=I(),T_=require("fs"),{hdb_errors:XK,handleHDBError:ji}=D(),{HDB_ERROR_MSGS:ZK,HTTP_STATUS_CODES:m_}=XK,{common_validators:R_}=Er(),xg=1e9,Nd=" is required",zK=["insert","update","upsert"],N_={schema:{presence:!0,format:R_.schema_format,length:R_.schema_length},table:{presence:!0,format:R_.schema_format,length:R_.schema_length},action:{inclusion:{within:zK,message:"is required and must be either insert, update, or upsert"}},file_path:{},csv_url:{url:{allowLocal:!0}},data:{}},{AWS_ACCESS_KEY:jK,AWS_SECRET:eW,AWS_BUCKET:tW,AWS_FILE_KEY:rW}=A_.S3_BUCKET_AUTH_KEYS,sW={s3:{presence:!0},[`s3.${jK}`]:{presence:!0,type:"String"},[`s3.${eW}`]:{presence:!0,type:"String"},[`s3.${tW}`]:{presence:!0,type:"String"},[`s3.${rW}`]:{presence:!0,type:"String",hasValidFileExt:[".csv",".json"]}},Yg=O_(N_);Yg.data.presence={message:Nd};var Kg=O_(N_);Kg.file_path.presence={message:Nd};var nW=Object.assign(O_(N_),sW),Wg=O_(N_);Wg.csv_url.presence={message:Nd};function iW(e){let t=p_.validateObject(e,Yg);return g_(e,t)}a(iW,"dataObject");function aW(e){let t=p_.validateObject(e,Wg);return g_(e,t)}a(aW,"urlObject");function oW(e){let t=p_.validateObject(e,Kg);return g_(e,t)}a(oW,"fileObject");function cW(e){let t=p_.validateObject(e,nW);return g_(e,t)}a(cW,"s3FileObject");function g_(e,t){if(!t){let r=QK.checkGlobalSchemaTable(e.schema,e.table);if(r)return ji(new Error,r,m_.BAD_REQUEST);if(e.operation===A_.OPERATIONS_ENUM.CSV_FILE_LOAD){try{T_.accessSync(e.file_path,T_.constants.R_OK|T_.constants.F_OK)}catch(s){return s.code===A_.NODE_ERROR_CODES.ENOENT?ji(s,`No such file or directory ${s.path}`,m_.BAD_REQUEST):s.code===A_.NODE_ERROR_CODES.EACCES?ji(s,`Permission denied ${s.path}`,m_.BAD_REQUEST):ji(s)}try{let s=T_.statSync(e.file_path).size;if(s>xg)return ji(new Error,ZK.MAX_FILE_SIZE_ERR(s,xg),m_.BAD_REQUEST)}catch(s){JK.error(s),console.error(s)}}}return t}a(g_,"postValidateChecks");Qg.exports={dataObject:iW,urlObject:aW,fileObject:oW,s3FileObject:cW}});var b_=S((I3,Jg)=>{"use strict";var ea=I(),I_=T();async function _W(e,t,r,s=[]){if(!e||typeof e!="function")throw new Error("Invalid function parameter");let n;try{return n=await e(t),r&&await r(t,n,s),t.operation===I_.OPERATIONS_ENUM.INSERT||t.operation===I_.OPERATIONS_ENUM.UPDATE||t.operation===I_.OPERATIONS_ENUM.UPSERT?(delete n.new_attributes,delete n.txn_time):t.operation===I_.OPERATIONS_ENUM.DELETE&&delete n.txn_time,n}catch(i){throw i.message&&typeof i.message=="string"&&i.message.includes("already exists")?(ea.info(i.message),i):i.http_resp_msg?(ea.error(`Error calling operation: ${e.name}`),ea.error(i.http_resp_msg),i):(ea.error(`Error calling operation: ${e.name}`),ea.error(i),i)}}a(_W,"callOperationFunctionAsAwait");Jg.exports={callOperationFunctionAsAwait:_W}});var Id=S((b3,Zg)=>{"use strict";var uW=require("aws-sdk/clients/s3");Zg.exports={getFileStreamFromS3:lW,getS3AuthObj:Xg};function lW(e){let{s3:t}=e,r={Bucket:t.bucket,Key:t.key};return Xg(t.aws_access_key_id,t.aws_secret_access_key).getObject(r).createReadStream()}a(lW,"getFileStreamFromS3");function Xg(e,t){return new uW({accessKeyId:e,secretAccessKey:t})}a(Xg,"getS3AuthObj")});var jg=S((w3,zg)=>{"use strict";var w_=class{constructor(t,r,s,n,i,o,c=null){this.op=t,this.action=r,this.schema=s,this.table=n,this.file_path=i,this.file_type=o,this.role_perms=c}};a(w_,"BulkLoadFileObject");var C_=class{constructor(t,r,s,n){this.action=t,this.schema=r,this.table=s,this.data=n}};a(C_,"BulkLoadDataObject");zg.exports={BulkLoadFileObject:w_,BulkLoadDataObject:C_}});var Ud=S((C3,fI)=>{"use strict";var L_=Lt(),D_=gd(),EW=require("needle"),Ot=T(),dW=_e(),ta=b(),{handleHDBError:ae,hdb_errors:cI}=D(),{HTTP_STATUS_CODES:Fe,HDB_ERROR_MSGS:pe,CHECK_LOGS_WRAPPER:Hs}=cI,vs=I(),U_=require("papaparse");ta.promisifyPapaParse();var Wt=require("fs-extra"),hW=require("path"),{chain:eI}=require("stream-chain"),tI=require("stream-json/streamers/StreamArray"),rI=require("stream-json/utils/Batch"),sI=require("stream-chain/utils/comp"),{finished:nI}=require("stream"),bd=Y(),SW=As(),_I=b_(),fW=Id(),{BulkLoadFileObject:wd,BulkLoadDataObject:TW}=jg(),Cd=dd(),{verifyBulkLoadAttributePerms:uI}=h_(),mW=xl(),RW=at(),AW=Hr(),iI="No records parsed from csv file.",Bs=`${bd.get("HDB_ROOT")}/tmp`,{schema_regex:OW}=Er(),aI=1024*1024*5,oI=5e3,pW={"text/csv":!0,"application/octet-stream":!0,"text/plain":!0,"application/vnd.ms-excel":!0};fI.exports={csvDataLoad:NW,csvURLLoad:gW,csvFileLoad:IW,importFromS3:bW};async function NW(e,t=[]){let r=D_.dataObject(e);if(r)throw ae(r,r.message,Fe.BAD_REQUEST,void 0,void 0,!0);let s={};try{let n=U_.parse(e.data,{header:!0,skipEmptyLines:!0,dynamicTyping:!0}),i=new Cd;e.hdb_user&&e.hdb_user.role&&e.hdb_user.role.permission&&e.hdb_user.role.permission.super_user!==!0&&uI(e.hdb_user.role.permission,this.job_operation_function.name,e.action,e.schema,e.table,n.meta.fields,i);let o=i.getPermsResponse();if(o)throw ae(new Error,o,Fe.BAD_REQUEST,void 0,void 0,!0);let c=new TW(e.action,e.schema,e.table,n.data);return s=await _I.callOperationFunctionAsAwait(dI,c,hI.bind(null,n.meta.fields),t),s.message===iI?iI:SI(s.records,s.number_written)}catch(n){throw qs(n)}}a(NW,"csvDataLoad");async function gW(e){let t=D_.urlObject(e);if(t)throw ae(t,t.message,Fe.BAD_REQUEST,void 0,void 0,!0);let r=`${Date.now()}.csv`,s=`${Bs}/${r}`;try{await wW(e.csv_url,r)}catch(n){throw vs.error(pe.DOWNLOAD_FILE_ERR(r)+" - "+n),ae(n,Hs(pe.DOWNLOAD_FILE_ERR(r)))}try{let n=new wd(this.job_operation_function.name,e.action,e.schema,e.table,s,Ot.VALID_S3_FILE_TYPES.CSV,e.hdb_user.role.permission),i=await Ld(n);return await y_(s),i}catch(n){throw await y_(s),qs(n)}}a(gW,"csvURLLoad");async function IW(e){let t=D_.fileObject(e);if(t)throw ae(t,t.message,Fe.BAD_REQUEST,void 0,void 0,!0);let r=new wd(this.job_operation_function.name,e.action,e.schema,e.table,e.file_path,Ot.VALID_S3_FILE_TYPES.CSV,e.hdb_user.role.permission);try{return await Ld(r)}catch(s){throw qs(s)}}a(IW,"csvFileLoad");async function bW(e){let t=D_.s3FileObject(e);if(t)throw ae(t,t.message,Fe.BAD_REQUEST,void 0,void 0,!0);let r;try{let s=hW.extname(e.s3.key),n=`${Date.now()}${s}`;r=`${Bs}/${n}`;let i=new wd(this.job_operation_function.name,e.action,e.schema,e.table,r,s,e.hdb_user.role.permission);await CW(n,e);let o=await Ld(i);return await y_(r),o}catch(s){throw await y_(r),qs(s)}}a(bW,"importFromS3");async function wW(e,t){let r;try{r=await EW("get",e)}catch(s){let n=`Error downloading CSV file from ${e}, status code: ${s.statusCode}. Check the log for more information.`;throw ae(s,n,s.statusCode,Ot.LOG_LEVELS.ERROR,"Error downloading CSV file - "+s)}UW(r,e),await LW(t,r.raw)}a(wW,"downloadCSVFile");async function CW(e,t){try{let r=`${Bs}/${e}`;await Wt.mkdirp(Bs),await Wt.writeFile(`${Bs}/${e}`,"",{flag:"a+"});let s=await Wt.createWriteStream(r),n=fW.getFileStreamFromS3(t);await new Promise((i,o)=>{n.on("error",function(c){o(c)}),n.pipe(s).on("error",function(c){o(c)}).on("close",function(){vs.info(`${t.s3.key} successfully downloaded to ${r}`),i()})})}catch(r){throw vs.error(pe.S3_DOWNLOAD_ERR+" - "+r),ae(r,Hs(pe.S3_DOWNLOAD_ERR))}}a(CW,"downloadFileFromS3");async function LW(e,t){try{await Wt.mkdirp(Bs),await Wt.writeFile(`${Bs}/${e}`,t)}catch(r){throw vs.error(pe.WRITE_TEMP_FILE_ERR),ae(r,Hs(pe.DEFAULT_BULK_LOAD_ERR))}}a(LW,"writeFileToTempFolder");async function y_(e){if(e)try{await Wt.access(e),await Wt.unlink(e)}catch{vs.warn(`could not delete temp csv file at ${e}, file does not exist`)}}a(y_,"deleteTempFile");function UW(e,t){if(e.statusCode!==cI.HTTP_STATUS_CODES.OK)throw ae(new Error,`CSV Load failed from URL: ${t}, status code: ${e.statusCode}, message: ${e.statusMessage}`,Fe.BAD_REQUEST);if(!pW[e.headers["content-type"]])throw ae(new Error,`CSV Load failed from URL: ${t}, unsupported content type: ${e.headers["content-type"]}`,Fe.BAD_REQUEST);if(!e.raw)throw ae(new Error,`CSV Load failed from URL: ${t}, no csv found at url`,Fe.BAD_REQUEST)}a(UW,"validateURLResponse");async function Ld(e){try{let t;switch(e.file_type){case Ot.VALID_S3_FILE_TYPES.CSV:t=await yW(e);break;case Ot.VALID_S3_FILE_TYPES.JSON:t=await DW(e);break;default:throw ae(new Error,pe.DEFAULT_BULK_LOAD_ERR,Fe.BAD_REQUEST,Ot.LOG_LEVELS.ERROR,pe.INVALID_FILE_EXT_ERR(e))}return SI(t.records,t.number_written)}catch(t){throw qs(t)}}a(Ld,"fileLoad");async function lI(e,t,r,s,n){let i=s.data?s.data:s;if(i.length===0)return;n&&n.pause();let o={operation:e.action,schema:e.schema,table:e.table,records:i};try{let{attributes:c}=await L_.validation(o);e.role_perms&&e.role_perms.super_user!==!0&&uI(e.role_perms,e.op,e.action,e.schema,e.table,c,t),n&&n.resume()}catch(c){let _=ae(c);r(_)}}a(lI,"validateChunk");async function EI(e,t,r,s,n){let i=s.data?s.data:s;if(i.length===0)return;ta.autoCastJSONDeep(i),n&&n.pause();let o=s.meta?s.meta.fields:null;if(o)i.forEach(c=>{!ta.isEmpty(c)&&!ta.isEmpty(c.__parsed_extra)&&delete c.__parsed_extra});else{let c=new Set;i.forEach(_=>{Object.keys(_).forEach(u=>c.add(u))}),o=[...c]}try{let c={schema:e.schema,table:e.table,action:e.action,data:i},_=await _I.callOperationFunctionAsAwait(dI,c,hI.bind(null,o));t.records+=_.records,t.number_written+=_.number_written,n&&n.resume()}catch(c){let _=ae(c,Hs(pe.INSERT_CSV_ERR),Fe.INTERNAL_SERVER_ERROR,Ot.LOG_LEVELS.ERROR,pe.INSERT_CSV_ERR+" - "+c);r(_)}}a(EI,"insertChunk");async function yW(e){let t={records:0,number_written:0};try{let r=new Cd,s=Wt.createReadStream(e.file_path,{highWaterMark:aI});s.setEncoding("utf8"),await U_.parsePromise(s,lI.bind(null,e,r));let n=r.getPermsResponse();if(n)throw ae(new Error,n,Fe.BAD_REQUEST);return s=Wt.createReadStream(e.file_path,{highWaterMark:aI}),s.setEncoding("utf8"),await U_.parsePromise(s,EI.bind(null,e,t)),s.destroy(),t}catch(r){throw ae(r,Hs(pe.PAPA_PARSE_ERR),Fe.INTERNAL_SERVER_ERROR,Ot.LOG_LEVELS.ERROR,pe.PAPA_PARSE_ERR+r)}}a(yW,"callPapaParse");async function DW(e){let t={records:0,number_written:0},r=a(s=>{throw s},"throwErr");try{let s=new Cd,n=eI([Wt.createReadStream(e.file_path,{encoding:"utf-8"}),tI.withParser(),c=>c.value,new rI({batchSize:oI}),sI(async c=>{await lI(e,s,r,c)})]);await new Promise((c,_)=>{nI(n,u=>{u?_(u):c()}),n.resume()});let i=s.getPermsResponse();if(i)throw ae(new Error,i,Fe.BAD_REQUEST);let o=eI([Wt.createReadStream(e.file_path,{encoding:"utf-8"}),tI.withParser(),c=>c.value,new rI({batchSize:oI}),sI(async c=>{await EI(e,t,r,c)})]);return await new Promise((c,_)=>{nI(o,u=>{u?_(u):c()}),o.resume()}),t}catch(s){throw ae(s,Hs(pe.INSERT_JSON_ERR),Fe.INTERNAL_SERVER_ERROR,Ot.LOG_LEVELS.ERROR,pe.INSERT_JSON_ERR+s)}}a(DW,"insertJson");async function dI(e){let t={};try{e.data&&e.data.length>0&&MW(e.data[0])?t=await PW(e.data,e.schema,e.table,e.action):(t.message="No records parsed from csv file.",vs.info(t.message))}catch(r){throw qs(r)}return t}a(dI,"callBulkFileLoad");function MW(e){let t=Object.keys(e);for(let r of t)if(!OW.test(r))throw new Error(`Invalid column name '${r}', cancelling load operation`);return!0}a(MW,"validateColumnNames");async function PW(e,t,r,s){s||(s="insert");let n={operation:s,schema:t,table:r,records:e},i;switch(s){case"insert":i=L_.insert;break;case"update":i=L_.update;break;case"upsert":i=L_.upsert;break;default:throw ae(new Error,pe.INVALID_ACTION_PARAM_ERR(s),Fe.BAD_REQUEST,Ot.LOG_LEVELS.ERROR,pe.INVALID_ACTION_PARAM_ERR(s))}try{let o=await i(n),c;switch(s){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,E=e.length;for(;E--;)o.skipped_hashes.indexOf(e[E][l])>=0&&e.splice(E,1)}let _=ta.isEmptyOrZeroLength(c)?0:c.length;return{records:e.length,number_written:_,new_attributes:o.new_attributes}}catch(o){throw qs(o)}}a(PW,"bulkFileLoad");async function hI(e,t,r,s=[]){try{if(t.data.length===0||!bd.get(Ot.CONFIG_PARAMS.CLUSTERING_ENABLED))return;let n=U_.unparse(t.data,{header:!0,skipEmptyLines:!0,columns:e}),i;t.hdb_user&&t.hdb_user.username&&(i=t.hdb_user.username);let o={operation:"csv_data_load",action:t.action?t.action:"insert",schema:t.schema,table:t.table,data:n,__origin:new mW(r.txn_time,i,bd.get(Ot.HDB_SETTINGS_NAMES.CLUSTERING_NODE_NAME_KEY))};await RW.publishToStream(`${dW.SUBJECT_PREFIXES.TXN}.${t.schema}.${t.table}`,AW.createNatsTableStreamName(t.schema,t.table),[o],s),await SW.sendAttributeTransaction(r,t,s),delete r.new_attributes}catch(n){vs.error(n)}}a(hI,"postCSVLoadFunction");function SI(e,t){return`successfully loaded ${t} of ${e} records`}a(SI,"buildResponseMsg");function qs(e){return ae(e,Hs(pe.DEFAULT_BULK_LOAD_ERR),Fe.INTERNAL_SERVER_ERROR,Ot.LOG_LEVELS.ERROR,pe.DEFAULT_BULK_LOAD_ERR+" - "+e)}a(qs,"buildTopLevelErrMsg")});var Dd=S((L3,gI)=>{"use strict";var RI=Tt(),BW=f_(),vW=Id(),{AsyncParser:HW,Transform:qW}=require("json2csv"),ra=require("stream"),GW=require("events"),Bt=b(),yd=require("fs-extra"),FW=require("path"),et=I(),{promisify:M_}=require("util"),sa=b(),{handleHDBError:Ne,hdb_errors:VW}=D(),{HDB_ERROR_MSGS:pt,HTTP_STATUS_CODES:ge}=VW,TI=["search_by_value","search_by_hash","sql"],mI=["json","csv"],AI="json",OI="csv",kW="Successfully exported JSON locally.",$W="Successfully exported CSV locally.",xW=1e3,YW=1e3,KW=M_(RI.searchByHash),WW=M_(RI.searchByValue),QW=M_(BW.evaluateSQL),JW=M_(ra.finished);gI.exports={export_to_s3:jW,export_local:XW};async function XW(e){et.trace(`export_local request to path: ${e.path}, filename: ${e.filename}, format: ${e.format}`);let t=pI(e);if(!Bt.isEmpty(t))throw et.error(t),Ne(new Error,t,ge.BAD_REQUEST,void 0,void 0,!0);if(Bt.isEmpty(e.path))throw et.error(pt.MISSING_VALUE("path")),Ne(new Error,pt.MISSING_VALUE("path"),ge.BAD_REQUEST,void 0,void 0,!0);let r=(Bt.isEmpty(e.filename)?new Date().getTime():e.filename)+"."+e.format;e.path.endsWith(FW.sep)&&(e.path=e.path.substring(0,e.path.length-1));let s=Bt.buildFolderPath(e.path,r);try{await ZW(e.path);let n=await NI(e);return await zW(s,e.format,n)}catch(n){throw et.error(n),new Error(n)}}a(XW,"export_local");async function ZW(e){if(et.trace("in confirmPath"),Bt.isEmptyOrZeroLength(e))throw Ne(new Error,`Invalid path: ${e}`,ge.BAD_REQUEST,void 0,void 0,!0);let t;try{t=await yd.stat(e)}catch(r){let s;throw r.code==="ENOENT"?s=`path '${e}' does not exist`:r.code==="EACCES"?s=`access to path '${e}' is denied`:s=r.message,et.error(s),Ne(new Error,s,ge.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 et.error(r),Ne(new Error,r,ge.BAD_REQUEST,void 0,void 0,!0)}return!0}a(ZW,"confirmPath");async function zW(e,t,r){if(et.trace("in saveToLocal"),sa.isEmptyOrZeroLength(e))throw Ne(new Error,pt.INVALID_VALUE("file_path"),ge.BAD_REQUEST,void 0,void 0,!0);if(sa.isEmptyOrZeroLength(t))throw Ne(new Error,pt.INVALID_VALUE("Source format"),ge.BAD_REQUEST,void 0,void 0,!0);if(sa.isEmpty(r))throw Ne(new Error,pt.NOT_FOUND("Data"),ge.BAD_REQUEST,void 0,void 0,!0);if(t===AI){let s=yd.createWriteStream(e),n=r.length;s.write("[");let i="";for await(let[o,c]of r.entries())i+=o===n-1?JSON.stringify(c):JSON.stringify(c)+",",o!==0&&o%YW===0&&(s.write(i)||await GW.once(s,"drain"),i="");return i.length!==0&&s.write(i),s.write("]"),s.end(),await JW(s),kW}else if(t===OI){let s=yd.createWriteStream(e),n=ra.Readable.from(r),i={},o={objectMode:!0};return await new HW(i,o).fromInput(n).toOutput(s).promise(!1),$W}throw Ne(new Error,pt.INVALID_VALUE("format"),ge.BAD_REQUEST)}a(zW,"saveToLocal");async function jW(e){if(!e.s3||Object.keys(e.s3).length===0)throw Ne(new Error,pt.MISSING_VALUE("S3 object"),ge.BAD_REQUEST);if(Bt.isEmptyOrZeroLength(e.s3.aws_access_key_id))throw Ne(new Error,pt.MISSING_VALUE("aws_access_key_id"),ge.BAD_REQUEST);if(Bt.isEmptyOrZeroLength(e.s3.aws_secret_access_key))throw Ne(new Error,pt.MISSING_VALUE("aws_secret_access_key"),ge.BAD_REQUEST);if(Bt.isEmptyOrZeroLength(e.s3.bucket))throw Ne(new Error,pt.MISSING_VALUE("bucket"),ge.BAD_REQUEST);if(Bt.isEmptyOrZeroLength(e.s3.key))throw Ne(new Error,pt.MISSING_VALUE("key"),ge.BAD_REQUEST);let t=pI(e);if(!Bt.isEmpty(t))throw Ne(new Error,t,ge.BAD_REQUEST);et.trace(`called export_to_s3 to bucket: ${e.s3.bucket} and query ${e.search_operation.sql}`);let r;try{r=await NI(e)}catch(c){throw et.error(c),c}let s,n=vW.getS3AuthObj(e.s3.aws_access_key_id,e.s3.aws_secret_access_key),i,o=new ra.PassThrough;if(e.format===OI){i=e.s3.key+".csv";let c=ra.Readable.from(r),_={},u={objectMode:!0},l=new qW(_,u);l.on("error",E=>{throw E}),c.pipe(l).pipe(o)}else if(e.format===AI){i=e.s3.key+".json";let c=new ra.Readable;c.pipe(o),c.on("error",l=>{throw l}),c.push("[");let _=r.length,u="";for(let[l,E]of r.entries())u+=l===_-1?JSON.stringify(E):JSON.stringify(E)+",",l!==0&&l%xW===0&&(c.push(u),u="");u.length!==0&&c.push(u),c.push("]"),c.push(null)}else throw Ne(new Error,pt.INVALID_VALUE("format"),ge.BAD_REQUEST);try{s=await n.upload({Bucket:e.s3.bucket,Key:i,Body:o}).promise()}catch(c){throw et.error(c),c}return s}a(jW,"export_to_s3");function pI(e){if(et.trace("in exportCoreValidation"),Bt.isEmpty(e.format))return"format missing";if(mI.indexOf(e.format)<0)return`format invalid. must be one of the following values: ${mI.join(", ")}`;let t=e.search_operation.operation;if(Bt.isEmpty(t))return"search_operation.operation missing";if(TI.indexOf(t)<0)return`search_operation.operation must be one of the following values: ${TI.join(", ")}`}a(pI,"exportCoreValidation");async function NI(e){et.trace("in getRecords");let t,r;if(sa.isEmpty(e.search_operation)||sa.isEmptyOrZeroLength(e.search_operation.operation))throw Ne(new Error,pt.INVALID_VALUE("Search operation"),ge.BAD_REQUEST);switch(e.search_operation.operation){case"search_by_value":t=WW;break;case"search_by_hash":t=KW;break;case"sql":t=QW;break;default:throw r=`Operation ${e.search_operation.operation} is not support by export.`,et.error(r),Ne(new Error,r,ge.BAD_REQUEST)}e.search_operation.hdb_user=e.hdb_user;try{return t(e.search_operation)}catch(s){throw et.error(s),s}}a(NI,"getRecords")});var bI=S((U3,II)=>{"use strict";var P_=class{constructor(t,r){this.operation="sql",this.sql=t,this.hdb_user=r}};a(P_,"SqlSearchObject");II.exports=P_});var LI=S((y3,CI)=>{"use strict";var eQ=T(),wI=require("moment"),tQ=require("uuid").v4,B_=class{constructor(){this.id=tQ(),this.type=void 0,this.start_datetime=wI().valueOf(),this.created_datetime=wI().valueOf(),this.end_datetime=void 0,this.status=eQ.JOB_STATUS_ENUM.CREATED,this.message=void 0,this.user=void 0,this.request=void 0}};a(B_,"JobObject");CI.exports=B_});var Pd=S((D3,BI)=>{"use strict";var rQ=require("uuid").v4,DI=Lt(),MI=Tt(),sQ=xt(),nQ=us(),iQ=bI(),oe=T(),aQ=LI(),oQ=EE(),vt=I(),cQ=zn(),Hn=b(),{promisify:Md}=require("util"),Gs=require("moment"),_Q=f_(),v_=gd(),UI=fl(),{deleteTransactionLogsBeforeValidator:uQ}=_d(),{handleHDBError:lQ,hdb_errors:EQ}=D(),{HTTP_STATUS_CODES:dQ}=EQ,yI=Md(MI.searchByValue),hQ=Md(MI.searchByHash),SQ=DI.insert,fQ=Md(_Q.evaluateSQL),TQ=DI.update;BI.exports={addJob:AQ,updateJob:pQ,handleGetJob:mQ,handleGetJobsByStartDate:RQ,getJobById:PI};async function mQ(e){try{let t=await PI(e.id);return Hn.isEmptyOrZeroLength(t)||(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 vt.error(r),new Error(r)}}a(mQ,"handleGetJob");async function RQ(e){try{let t=await OQ(e);if(vt.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=Gs(r.start_datetime)),r.end_datetime&&(r.end_datetime_converted=Gs(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 vt.error(r),new Error(r)}}a(RQ,"handleGetJobsByStartDate");async function AQ(e){let t={message:"",error:"",success:!1,createdJob:void 0};if(!e||Object.keys(e).length===0||Hn.isEmptyOrZeroLength(e.operation)){let l="job parameter is invalid";return vt.info(l),t.error=l,t}if(!oe.JOB_TYPE_ENUM[e.operation])return vt.info(`invalid job type specified: ${e.operation}.`),t;let r=e.operation,s;switch(r){case oe.OPERATIONS_ENUM.CSV_FILE_LOAD:s=v_.fileObject(e);break;case oe.OPERATIONS_ENUM.CSV_URL_LOAD:s=v_.urlObject(e);break;case oe.OPERATIONS_ENUM.CSV_DATA_LOAD:s=v_.dataObject(e);break;case oe.OPERATIONS_ENUM.IMPORT_FROM_S3:s=v_.s3FileObject(e);break;case oe.OPERATIONS_ENUM.DELETE_FILES_BEFORE:case oe.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE:s=UI(e,"date");break;case oe.OPERATIONS_ENUM.DELETE_AUDIT_LOGS_BEFORE:s=UI(e,"timestamp");break;case oe.OPERATIONS_ENUM.DELETE_TRANSACTION_LOGS_BEFORE:s=uQ(e);break;default:break}if(s)throw lQ(s,s.message,dQ.BAD_REQUEST,void 0,void 0,!0);let n=new aQ;n.type=e.operation===oe.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE?oe.OPERATIONS_ENUM.DELETE_FILES_BEFORE:e.operation,n.type=e.operation,n.user=e.hdb_user.username;let i=new sQ(oe.SYSTEM_SCHEMA_NAME,oe.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,"id",n.id,"id",["id"]),o;try{o=await yI(i)}catch(l){let E=`There was an error inserting a new job: ${l}`;return vt.error(E),t}let c=Array.isArray(o)?o:Object.keys(o);if(c&&c.length>0){n.id=rQ();try{o=await yI(i)}catch(l){let E=`There was an error inserting a new job: ${l}`;return vt.error(E),t}if(c=Array.isArray(o)?o:Object.keys(o),c&&c.length>0)return vt.error("Error creating a job, could not find a unique job id."),t}n.request=e;let _=new cQ(oe.SYSTEM_SCHEMA_NAME,oe.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,"id",[n]),u;try{u=await SQ(_)}catch(l){return vt.error(`There was an error inserting a job for job type: ${e.operation} -- ${l}`),t.success=!1,t}if(u.inserted_hashes.length===0)t.message=`Had a problem creating a job with type ${n.operation} and id ${n.id}`;else{let l=`Created a job with type ${n.type} and id ${n.id}`;t.message=l,t.createdJob=n,t.success=!0,vt.trace(l)}return t}a(AQ,"addJob");async function OQ(e){let t=Gs(e.from_date,Gs.ISO_8601),r=Gs(e.to_date,Gs.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 s=`select * from system.hdb_job where start_datetime > '${t.valueOf()}' and start_datetime < '${r.valueOf()}'`,n=new iQ(s,e.hdb_user);try{return await fQ(n)}catch(i){throw vt.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(OQ,"getJobsInDateRange");async function PI(e){if(Hn.isEmptyOrZeroLength(e))return Hn.errorizeMessage("Invalid job ID specified.");let t=new nQ(oe.SYSTEM_SCHEMA_NAME,oe.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,[e],["*"]);try{return await hQ(t)}catch(r){let s=`There was an error searching for a job by id: ${e} ${r}`;return vt.error(s),Hn.errorizeMessage("there was an error searching for jobs. Please check the log for details.")}}a(PI,"getJobById");async function pQ(e){if(Object.keys(e).length===0)throw new Error("invalid job object passed to updateJob");if(Hn.isEmptyOrZeroLength(e.id))throw new Error("invalid ID passed to updateJob");(e.status===oe.JOB_STATUS_ENUM.COMPLETE||e.status===oe.JOB_STATUS_ENUM.ERROR)&&(e.end_datetime=Gs().valueOf());let t=new oQ(oe.SYSTEM_SCHEMA_NAME,oe.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,[e]),r;try{r=await TQ(t)}catch(s){throw new Error(s)}return r}a(pQ,"updateJob")});var VI=S((M3,FI)=>{"use strict";var vI=b(),Nt=T(),NQ=require("moment"),H_=Ud(),q_=I(),HI=Pd(),qI=Dd(),GI=fs(),gQ=Jc(),IQ=ki(),bQ=n_(),G_=class{constructor(t,r){this.job=t,this.json=r}};a(G_,"RunnerMessage");async function wQ(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(vI.isEmptyOrZeroLength(e.json.operation))throw new Error("Invalid operation");if(vI.isEmptyOrZeroLength(e.job.id))throw new Error("Empty job id specified");switch(e.json.operation){case Nt.JOB_TYPE_ENUM.csv_file_load:await gr(e,H_.csvFileLoad);break;case Nt.JOB_TYPE_ENUM.csv_url_load:await gr(e,H_.csvURLLoad);break;case Nt.JOB_TYPE_ENUM.csv_data_load:await gr(e,H_.csvDataLoad);break;case Nt.JOB_TYPE_ENUM.import_from_s3:await gr(e,H_.importFromS3);break;case Nt.JOB_TYPE_ENUM.empty_trash:break;case Nt.JOB_TYPE_ENUM.export_local:await gr(e,qI.export_local);break;case Nt.JOB_TYPE_ENUM.export_to_s3:await gr(e,qI.export_to_s3);break;case Nt.JOB_TYPE_ENUM.delete_files_before:case Nt.JOB_TYPE_ENUM.delete_records_before:await gr(e,GI.deleteFilesBefore);break;case Nt.JOB_TYPE_ENUM.delete_audit_logs_before:await gr(e,GI.deleteAuditLogsBefore);break;case Nt.JOB_TYPE_ENUM.delete_transaction_logs_before:await gr(e,bQ.deleteTransactionLogsBefore);break;default:return`Invalid operation ${e.json.operation} specified`}}a(wQ,"parseMessage");async function gr(e,t){try{e.job.status=Nt.JOB_STATUS_ENUM.IN_PROGRESS,e.job.start_datetime=NQ().valueOf(),await HI.updateJob(e.job),await CQ(e.job.id)}catch(r){let s=r.message!==void 0?r.message:r;typeof s=="string"?(s=`There was an error running ${t.name} job with id ${e.job.id} - ${s}`,r.message=s):q_.error(`There was an error running ${t.name} job with id ${e.job.id}`),q_.error(s),e.job.message=s,e.job.status=Nt.JOB_STATUS_ENUM.ERROR;try{await HI.updateJob(e.job)}catch(n){throw q_.error(`Unable to update job with id ${e.job.id}`),n}throw r}}a(gr,"runJob");async function CQ(e){let t=gQ.generateJobConfig(e);q_.trace("launching job process:",e),await IQ.start(t)}a(CQ,"launchJobProcess");FI.exports={parseMessage:wQ,RunnerMessage:G_}});var $I=S((P3,kI)=>{"use strict";var F_=class{constructor(t,r=void 0){this.operation_function=t,this.job_operation_function=r}};a(F_,"OperationFunctionObject");kI.exports=F_});var rb=S((B3,tb)=>{"use strict";var $_=Tt(),qd=f_(),V_=Ud(),qn=jo(),Bd=ds(),ia=fs(),LQ=zl(),na=xr(),k_=oE(),Ir=cd(),Ve=I(),UQ=uE(),yQ=bc(),DQ=ME(),MQ=Uc(),PQ=PE(),BQ=HE(),vd=FE(),xI=Dd(),vQ=h_(),Gd=Pd(),A=T(),{hdb_errors:oa,handleHDBError:aa}=D(),{HTTP_STATUS_CODES:YI}=oa,Hd=$E(),KI=td(),x_=require("util"),Fs=Lt(),HQ=Gr(),qQ=pc(),jI=As(),WI=VI(),QI=Ec(),JI=ur(),XI=n_(),ZI=Ed(),GQ=b_(),FQ=x_.promisify($_.searchByHash),VQ=x_.promisify($_.searchByValue),kQ=x_.promisify($_.search),$Q=x_.promisify(qd.evaluateSQL),xQ={[A.OPERATIONS_ENUM.CREATE_ATTRIBUTE]:!0,[A.OPERATIONS_ENUM.CREATE_TABLE]:!0,[A.OPERATIONS_ENUM.CREATE_SCHEMA]:!0,[A.OPERATIONS_ENUM.DROP_ATTRIBUTE]:!0,[A.OPERATIONS_ENUM.DROP_TABLE]:!0,[A.OPERATIONS_ENUM.DROP_SCHEMA]:!0},N=$I();function YQ(e,t,r){return Promise.all([jI.postOperationHandler(e,t,r),e.table?Fs.flush(e):null])}a(YQ,"postWrite");async function KQ(e,t){try{if(e.body.operation!=="read_log"&&(Ve.log_level===A.LOG_LEVELS.INFO||Ve.log_level===A.LOG_LEVELS.DEBUG||Ve.log_level===A.LOG_LEVELS.TRACE)){let{hdb_user:s,hdb_auth_header:n,password:i,...o}=e.body;Ve.info(o)}}catch(s){Ve.error(s)}let r=A.CLUSTER_OPERATIONS[e.body.operation]===void 0?null:YQ;try{let s=await GQ.callOperationFunctionAsAwait(t,e.body,r);if(typeof s!="object"&&(s={message:s}),s instanceof Error)throw s;return xQ[e.body.operation]&&HQ.setSchemaDataToGlobal(n=>{n&&Ve.error(n)}),s}catch(s){throw Ve.info(s),s}}a(KQ,"processLocalTransaction");var zI=JQ();tb.exports={chooseOperation:WQ,getOperationFunction:eb,processLocalTransaction:KQ};function WQ(e){let t;try{t=eb(e)}catch(n){throw Ve.error(`Error when selecting operation function - ${n}`),n}let{operation_function:r,job_operation_function:s}=t;try{if(e.operation==="sql"||e.search_operation&&e.search_operation.operation==="sql"){let n=e.operation==="sql"?e.sql:e.search_operation.sql,i=qd.convertSQLToAST(n);if(e.parsed_sql_object=i,!e.bypass_auth){let o=qd.checkASTPermissions(e,i);if(o)throw Ve.error(`${YI.FORBIDDEN} from operation ${e.search_operation}`),aa(new Error,o,oa.HTTP_STATUS_CODES.FORBIDDEN)}}else if(!e.bypass_auth&&e.operation!==A.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS){let n=s===void 0?r:s,i=e.search_operation?e.search_operation:e;i.hdb_user||(i.hdb_user=e.hdb_user);let o=vQ.verifyPerms(i,n);if(o)throw Ve.error(`${YI.FORBIDDEN} from operation ${e.operation}`),aa(new Error,o,oa.HTTP_STATUS_CODES.FORBIDDEN)}}catch(n){throw aa(n,"There was an error when trying to choose an operation path")}return r}a(WQ,"chooseOperation");function eb(e){if(Ve.trace(`getOperationFunction with operation: ${e.operation}`),zI.has(e.operation))return zI.get(e.operation);throw aa(new Error,oa.HDB_ERROR_MSGS.OP_NOT_FOUND(e.operation),oa.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0)}a(eb,"getOperationFunction");async function QQ(e){Ve.trace("In serverUtils.catchup");let t=e.transaction,r=t.channel.split(":"),s=r[0],n=r[1];for(let i of t.transactions)try{i.schema=s,i.table=n,i[A.CLUSTERING_FLAG]=!0;let o;switch(i.operation){case A.OPERATIONS_ENUM.INSERT:o=await Fs.insert(i);break;case A.OPERATIONS_ENUM.UPDATE:o=await Fs.update(i);break;case A.OPERATIONS_ENUM.UPSERT:o=await Fs.upsert(i);break;case A.OPERATIONS_ENUM.DELETE:o=await ia.deleteRecord(i);break;default:Ve.warn("invalid operation in catchup");break}await jI.postOperationHandler(i,o,e)}catch(o){Ve.info("Invalid operation in transaction"),Ve.error(o)}}a(QQ,"catchup");async function or(e){let t,r;try{r=await Gd.addJob(e),t=r.createdJob;let s=new WI.RunnerMessage(t,e);return await WI.parseMessage(s),`Starting job with id ${t.id}`}catch(s){let n=`There was an error executing job: ${s.http_resp_msg?s.http_resp_msg:s}`;throw Ve.error(n),aa(s,n)}}a(or,"executeJob");function JQ(){let e=new Map;return e.set(A.OPERATIONS_ENUM.INSERT,new N(Fs.insert)),e.set(A.OPERATIONS_ENUM.UPDATE,new N(Fs.update)),e.set(A.OPERATIONS_ENUM.UPSERT,new N(Fs.upsert)),e.set(A.OPERATIONS_ENUM.SEARCH_BY_CONDITIONS,new N($_.searchByConditions)),e.set(A.OPERATIONS_ENUM.SEARCH_BY_HASH,new N(FQ)),e.set(A.OPERATIONS_ENUM.SEARCH_BY_VALUE,new N(VQ)),e.set(A.OPERATIONS_ENUM.SEARCH,new N(kQ)),e.set(A.OPERATIONS_ENUM.SQL,new N($Q)),e.set(A.OPERATIONS_ENUM.CSV_DATA_LOAD,new N(or,V_.csvDataLoad)),e.set(A.OPERATIONS_ENUM.CSV_FILE_LOAD,new N(or,V_.csvFileLoad)),e.set(A.OPERATIONS_ENUM.CSV_URL_LOAD,new N(or,V_.csvURLLoad)),e.set(A.OPERATIONS_ENUM.IMPORT_FROM_S3,new N(or,V_.importFromS3)),e.set(A.OPERATIONS_ENUM.CREATE_SCHEMA,new N(qn.createSchema)),e.set(A.OPERATIONS_ENUM.CREATE_TABLE,new N(qn.createTable)),e.set(A.OPERATIONS_ENUM.CREATE_ATTRIBUTE,new N(qn.createAttribute)),e.set(A.OPERATIONS_ENUM.DROP_SCHEMA,new N(qn.dropSchema)),e.set(A.OPERATIONS_ENUM.DROP_TABLE,new N(qn.dropTable)),e.set(A.OPERATIONS_ENUM.DROP_ATTRIBUTE,new N(qn.dropAttribute)),e.set(A.OPERATIONS_ENUM.DESCRIBE_SCHEMA,new N(Bd.describeSchema)),e.set(A.OPERATIONS_ENUM.DESCRIBE_TABLE,new N(Bd.describeTable)),e.set(A.OPERATIONS_ENUM.DESCRIBE_ALL,new N(Bd.describeAll)),e.set(A.OPERATIONS_ENUM.DELETE,new N(ia.deleteRecord)),e.set(A.OPERATIONS_ENUM.ADD_USER,new N(na.addUser)),e.set(A.OPERATIONS_ENUM.ALTER_USER,new N(na.alterUser)),e.set(A.OPERATIONS_ENUM.DROP_USER,new N(na.dropUser)),e.set(A.OPERATIONS_ENUM.LIST_USERS,new N(na.listUsersExternal)),e.set(A.OPERATIONS_ENUM.LIST_ROLES,new N(k_.listRoles)),e.set(A.OPERATIONS_ENUM.ADD_ROLE,new N(k_.addRole)),e.set(A.OPERATIONS_ENUM.ALTER_ROLE,new N(k_.alterRole)),e.set(A.OPERATIONS_ENUM.DROP_ROLE,new N(k_.dropRole)),e.set(A.OPERATIONS_ENUM.USER_INFO,new N(na.userInfo)),e.set(A.OPERATIONS_ENUM.READ_LOG,new N(UQ)),e.set(A.OPERATIONS_ENUM.ADD_NODE,new N(yQ)),e.set(A.OPERATIONS_ENUM.UPDATE_NODE,new N(DQ)),e.set(A.OPERATIONS_ENUM.REMOVE_NODE,new N(MQ)),e.set(A.OPERATIONS_ENUM.CONFIGURE_CLUSTER,new N(PQ)),e.set(A.OPERATIONS_ENUM.SET_CONFIGURATION,new N(JI.setConfiguration)),e.set(A.OPERATIONS_ENUM.CLUSTER_STATUS,new N(BQ.clusterStatus)),e.set(A.OPERATIONS_ENUM.CLUSTER_SET_ROUTES,new N(vd.setRoutes)),e.set(A.OPERATIONS_ENUM.CLUSTER_GET_ROUTES,new N(vd.getRoutes)),e.set(A.OPERATIONS_ENUM.CLUSTER_DELETE_ROUTES,new N(vd.deleteRoutes)),e.set(A.OPERATIONS_ENUM.EXPORT_TO_S3,new N(or,xI.export_to_s3)),e.set(A.OPERATIONS_ENUM.DELETE_FILES_BEFORE,new N(or,ia.deleteFilesBefore)),e.set(A.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE,new N(or,ia.deleteFilesBefore)),e.set(A.OPERATIONS_ENUM.EXPORT_LOCAL,new N(or,xI.export_local)),e.set(A.OPERATIONS_ENUM.SEARCH_JOBS_BY_START_DATE,new N(Gd.handleGetJobsByStartDate)),e.set(A.OPERATIONS_ENUM.GET_JOB,new N(Gd.handleGetJob)),e.set(A.OPERATIONS_ENUM.GET_FINGERPRINT,new N(Hd.getFingerprint)),e.set(A.OPERATIONS_ENUM.SET_LICENSE,new N(Hd.setLicense)),e.set(A.OPERATIONS_ENUM.GET_REGISTRATION_INFO,new N(Hd.getRegistrationInfo)),e.set(A.OPERATIONS_ENUM.RESTART,new N(KI.restartProcesses)),e.set(A.OPERATIONS_ENUM.RESTART_SERVICE,new N(KI.restartService)),e.set(A.OPERATIONS_ENUM.CATCHUP,new N(QQ)),e.set(A.OPERATIONS_ENUM.SYSTEM_INFORMATION,new N(qQ.systemInformation)),e.set(A.OPERATIONS_ENUM.DELETE_AUDIT_LOGS_BEFORE,new N(or,ia.deleteAuditLogsBefore)),e.set(A.OPERATIONS_ENUM.READ_AUDIT_LOG,new N(LQ)),e.set(A.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS,new N(QI.createTokens)),e.set(A.OPERATIONS_ENUM.REFRESH_OPERATION_TOKEN,new N(QI.refreshOperationToken)),e.set(A.OPERATIONS_ENUM.GET_CONFIGURATION,new N(JI.getConfiguration)),e.set(A.OPERATIONS_ENUM.CUSTOM_FUNCTIONS_STATUS,new N(Ir.customFunctionsStatus)),e.set(A.OPERATIONS_ENUM.GET_CUSTOM_FUNCTIONS,new N(Ir.getCustomFunctions)),e.set(A.OPERATIONS_ENUM.GET_CUSTOM_FUNCTION,new N(Ir.getCustomFunction)),e.set(A.OPERATIONS_ENUM.SET_CUSTOM_FUNCTION,new N(Ir.setCustomFunction)),e.set(A.OPERATIONS_ENUM.DROP_CUSTOM_FUNCTION,new N(Ir.dropCustomFunction)),e.set(A.OPERATIONS_ENUM.ADD_CUSTOM_FUNCTION_PROJECT,new N(Ir.addCustomFunctionProject)),e.set(A.OPERATIONS_ENUM.DROP_CUSTOM_FUNCTION_PROJECT,new N(Ir.dropCustomFunctionProject)),e.set(A.OPERATIONS_ENUM.PACKAGE_CUSTOM_FUNCTION_PROJECT,new N(Ir.packageCustomFunctionProject)),e.set(A.OPERATIONS_ENUM.DEPLOY_CUSTOM_FUNCTION_PROJECT,new N(Ir.deployCustomFunctionProject)),e.set(A.OPERATIONS_ENUM.READ_TRANSACTION_LOG,new N(XI.readTransactionLog)),e.set(A.OPERATIONS_ENUM.DELETE_TRANSACTION_LOGS_BEFORE,new N(or,XI.deleteTransactionLogsBefore)),e.set(A.OPERATIONS_ENUM.INSTALL_NODE_MODULES,new N(ZI.installModules)),e.set(A.OPERATIONS_ENUM.AUDIT_NODE_MODULES,new N(ZI.auditModules)),e}a(JQ,"initializeOperationFunctionMap")});var ab=S((v3,ib)=>{"use strict";var XQ=require("node-ipc").IPC,sb=b(),nb=T(),br=I(),{IPC_ERRORS:Gn}=Ke(),ZQ=require("os"),Y_=class{constructor(t,r){this.ipc=new XQ,this.server_name=nb.HDB_IPC_SERVER,this.ipc.config.retry=ZQ.platform()=="win32"?6e5:100,this.ipc.config.id=nb.HDB_IPC_CLIENT_PREFIX+t,this.ipc.config.silent=!0,this.event_handlers=r,this.connect()}connect(){this.ipc.connectTo(this.server_name,()=>{this.generateEventHandlers(this.event_handlers)})}addEventHandler(t,r){this.ipc.of[this.server_name].on(t,r)}generateEventHandlers(t){this.ipc.of[this.server_name].on("connect",()=>{br.info(`IPC client ${this.ipc.config.id} connected to ${this.server_name}`)}),this.ipc.of[this.server_name].on("disconnect",()=>{br.info(`IPC client ${this.ipc.config.id} disconnected from ${this.server_name}`)}),this.ipc.of[this.server_name].on("error",r=>{r.code==="ECONNREFUSED"&&br.warn("Error connecting to HDB IPC server. Confirm that the server is running."),br.warn(`Error with IPC client ${this.ipc.config.id}`),br.warn(r)});for(let[r,s]of Object.entries(t))this.addEventHandler(r,s)}emitToServer(t){if(typeof t!="object")throw br.warn(Gn.INVALID_IPC_DATA_TYPE),new Error(Gn.INVALID_IPC_DATA_TYPE);if(sb.isEmpty(t.type))throw br.warn(Gn.MISSING_TYPE),new Error(Gn.MISSING_TYPE);if(sb.isEmpty(t.message))throw br.warn(Gn.MISSING_MSG),new Error(Gn.MISSING_MSG);br.trace(`IPC client ${this.ipc.config.id} emitting`,t),this.ipc.of[this.server_name].emit("message",t)}};a(Y_,"IPCClient");ib.exports=Y_});var ub=S((H3,_b)=>{"use strict";var zQ=require("util"),{toJsMsg:jQ}=require("nats"),{decode:e1}=require("msgpackr"),t1=Gr(),r1=nA(),s1=at(),W_=_e(),n1=T(),Vs=I(),i1=rb(),a1=ab(),o1=b_(),c1=As(),_1=zQ.promisify(t1.setSchemaDataToGlobal),u1={durable:W_.WORK_QUEUE_CONSUMER_NAMES.durable_name,queue:W_.WORK_QUEUE_CONSUMER_NAMES.deliver_group,filterSubject:`${W_.SUBJECT_PREFIXES.TXN}.>`},Fd,Vd,l1,E1;_b.exports={initialize:d1,workQueueListener:h1};async function d1(){Vs.notify("Starting clustering ingest service."),await _1();try{global.hdb_ipc=new a1(process.pid,r1)}catch(s){throw Vs.error("Error instantiating new instance of IPC client in natsIngestService"),s}let{connection:e,jsm:t,js:r}=await s1.getNATSReferences();Fd=e,Vd=e.info.server_name,l1=t,E1=r}a(d1,"initialize");var cb=100,ob=new Array(cb),K_=0;async function h1(){let e=Fd.subscribe(`${W_.WORK_QUEUE_CONSUMER_NAMES.deliver_subject}.${Fd.info.server_name}`,u1);for await(let t of e)await ob[K_],ob[K_]=S1(t).catch(r=>{Vs.error(r)}),++K_>=cb&&(K_=0)}a(h1,"workQueueListener");async function S1(e){let t=jQ(e);t.working();let r=e1(t.data);Vs.trace("processing message:",r);let s=[],n=[];if(t.headers){let o=t.headers.get("originators");o&&(n=o.split(","),s=n)}let i;if(Vs.trace(`messageProcessor originators: ${s} on server: ${Vd}`),s.indexOf(Vd)<0){let o,c=i1.getOperationFunction(r);o=c.job_operation_function?c.job_operation_function:c.operation_function;try{c.job_operation_function?i=await o(r,s):(r[n1.CLUSTERING_FLAG]=!0,i=await o1.callOperationFunctionAsAwait(o,r,c1.postOperationHandler,s)),Vs.debug(i)}catch(_){Vs.error(_)}}return t.ack(),i}a(S1,"messageProcessor")});var lb=ub();(async()=>{try{await lb.initialize(),await lb.workQueueListener()}catch(e){console.error("Error launching Nats ingest service."),console.error(e)}})();
|