harperdb 4.0.0 → 4.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/bin/harperdb.js +2 -2
- package/launchServiceScripts/launchCustomFunctions.js +11 -11
- package/launchServiceScripts/launchHarperDB.js +11 -11
- package/launchServiceScripts/launchInstallNATSServer.js +1 -1
- package/launchServiceScripts/launchNatsIngestService.js +11 -11
- package/launchServiceScripts/launchNatsReplyService.js +2 -2
- package/package.json +3 -3
- package/server/ipc/hdbIpcServer.js +1 -1
- package/server/jobs/jobProcess.js +11 -11
- package/utility/scripts/restartHdb.js +2 -2
|
@@ -1,14 +1,14 @@
|
|
|
1
|
-
"use strict";var Hb=Object.defineProperty;var a=(e,t)=>Hb(e,"name",{value:t,configurable:!0});var h=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var eh=h((PJ,jd)=>{var qb=require("fastify-plugin");jd.exports=qb(function(e,t,r){e.addHook("onResponse",async(s,n)=>{n.getResponseTime()}),e.addHook("onSend",async(s,n)=>{let i=n.getResponseTime().toFixed(3);n.header("HDB-Response-Time",i),n.header("Server-Timing",`db;dur=${i}`)}),r()},{name:"hdb-request-time"})});var T=h((BJ,dh)=>{"use strict";var Ye=require("path"),Gb=require("fs");function Fb(){let e=__dirname;for(;!Gb.existsSync(Ye.join(e,"package.json"));){let t=Ye.dirname(e);if(t===e)throw new Error("Could not find package root");e=t}return e}a(Fb,"getHDBPackageRoot");var Gt=Fb(),th="js",$n=th,Vb="harperdb-config.yaml",kb="defaultConfig.yaml",xb="hdb",rh=`hdbServer.${$n}`,sh=`customFunctionsServer.${$n}`,nh=`hdbIpcServer.${$n}`,$b=`restartHdb.${$n}`,tu="HarperDB",Sa="Custom Functions",fa="Clustering Hub",Ta="Clustering Leaf",ru="Clustering Ingest Service",su="Clustering Reply Service",Yb="foreground.pid",eu={HDB:tu,IPC:"IPC",CLUSTERING_HUB:fa,CLUSTERING_LEAF:Ta,CLUSTERING_INGEST_SERVICE:ru,CLUSTERING_REPLY_SERVICE:su,CUSTOM_FUNCTIONS:Sa,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"},Kb={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"},Qb={NOTIFY:"notify",FATAL:"fatal",ERROR:"error",WARN:"warn",INFO:"info",DEBUG:"debug",TRACE:"trace"},Wb={harperdb:tu,ipc:"IPC","clustering hub":fa,"clustering leaf":Ta,"clustering ingest service":ru,"clustering reply service":su,"custom functions":Sa,custom_functions:Sa,"pm2-logrotate":eu.PM2_LOGROTATE,logrotate:eu.PM2_LOGROTATE,clustering:"clustering","clustering config":"clustering config"},Jb={CLUSTERING_HUB_PROC_DESCRIPTOR:fa,CLUSTERING_LEAF_PROC_DESCRIPTOR:Ta,CLUSTERING_INGEST_PROC_DESCRIPTOR:ru,CLUSTERING_REPLY_SERVICE_DESCRIPTOR:su},ha={HDB:Ye.join(Gt,"server/harperdb"),IPC:Ye.join(Gt,"server/ipc"),CUSTOM_FUNCTIONS:Ye.join(Gt,"server/customFunctions"),CLUSTERING_HUB:Ye.join(Gt,"server/nats"),CLUSTERING_LEAF:Ye.join(Gt,"server/nats")},Zb={HDB:Ye.join(ha.HDB,rh),IPC:Ye.join(ha.IPC,nh),CUSTOM_FUNCTIONS:Ye.join(ha.CUSTOM_FUNCTIONS,sh)},Xb={HDB:Ye.join(Gt,"launchServiceScripts/launchHarperDB.js"),CUSTOM_FUNCTIONS:Ye.join(Gt,"launchServiceScripts/launchCustomFunctions.js"),NATS_INGEST_SERVICE:Ye.join(Gt,"launchServiceScripts/launchNatsIngestService.js"),NATS_REPLY_SERVICE:Ye.join(Gt,"launchServiceScripts/launchNatsReplyService.js"),NODES_UPGRADE_4_0_0:Ye.resolve(Gt,"launchServiceScripts/launchUpdateNodes4-0-0.js")},zb={SUPER_USER:"super_user",CLUSTER_USER:"cluster_user"},ih="support@harperdb.io",jb="customer-success@harperdb.io",ah=1,eC=4141,oh="https://harperdbhelp.zendesk.com/hc/en-us/requests/new",tC="https://www.harperdb.io/product",rC=`For support, please submit a request at ${oh} or contact ${ih}`,ch=`For license support, please contact ${jb}`,sC="None of the specified records were found.",nC="hash attribute not found",iC=`Your current license only supports ${ah} role. ${ch}`,aC="Your current license only supports 3 connections to a node.",oC="127.0.0.1",cC=1,_C=/^\.$/,uC=/^\.\.$/,lC="U+002E",EC=/\//g,dC="U+002F",hC=/U\+002F/g,SC=/^U\+002E$/,fC=/^U\+002EU\+002E$/,TC="d",mC=999999,RC="*",AC="--max-old-space-size=",pC="system",OC="__hdb_hash",NC=".harperdb",gC=".hdb",IC="keys",bC="hdb_boot_properties.file",CC=".updateConfig.json",wC="SIGTSTP",UC=24,LC=6e4,yC=448,DC="blob",MC="trash",PC="schema",BC="transactions",vC=".count",HC="id",qC="install_log.log",GC="run_log.log",FC="PROCESS_NAME",VC={SETTINGS_PATH_KEY:"settings_path"},_h=require("lodash"),kC={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"},xC={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},$C={DATA_VERSION:"data_version",UPGRADE_VERSION:"upgrade_version"},YC={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"},KC={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:",QC={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"},JC="060493.ks",ZC=".license",XC={CREATED:"CREATED",IN_PROGRESS:"IN_PROGRESS",COMPLETE:"COMPLETE",ERROR:"ERROR"},I={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"},zC={CSV:".csv",JSON:".json"},jC={AWS_ACCESS_KEY:"aws_access_key_id",AWS_SECRET:"aws_secret_access_key",AWS_BUCKET:"bucket",AWS_FILE_KEY:"key"},ew={SELECT:"select",INSERT:"insert",UPDATE:"update",DELETE:"delete"},Br={};Br[I.CREATE_SCHEMA]=I.CREATE_SCHEMA;Br[I.CREATE_TABLE]=I.CREATE_TABLE;Br[I.CREATE_ATTRIBUTE]=I.CREATE_ATTRIBUTE;Br[I.INSERT]=I.INSERT;Br[I.UPDATE]=I.UPDATE;Br[I.UPSERT]=I.UPSERT;Br[I.DELETE]=I.DELETE;var Z=Object.create(null);Z[I.DESCRIBE_ALL]=I.DESCRIBE_ALL;Z[I.DESCRIBE_TABLE]=I.DESCRIBE_TABLE;Z[I.DESCRIBE_SCHEMA]=I.DESCRIBE_SCHEMA;Z[I.READ_LOG]=I.READ_LOG;Z[I.ADD_NODE]=I.ADD_NODE;Z[I.LIST_USERS]=I.LIST_USERS;Z[I.LIST_ROLES]=I.LIST_ROLES;Z[I.USER_INFO]=I.USER_INFO;Z[I.SQL]=I.SQL;Z[I.GET_JOB]=I.GET_JOB;Z[I.SEARCH_JOBS_BY_START_DATE]=I.SEARCH_JOBS_BY_START_DATE;Z[I.DELETE_FILES_BEFORE]=I.DELETE_FILES_BEFORE;Z[I.EXPORT_LOCAL]=I.EXPORT_LOCAL;Z[I.EXPORT_TO_S3]=I.EXPORT_TO_S3;Z[I.CLUSTER_STATUS]=I.CLUSTER_STATUS;Z[I.REMOVE_NODE]=I.REMOVE_NODE;Z[I.RESTART]=I.RESTART;Z[I.CUSTOM_FUNCTIONS_STATUS]=I.CUSTOM_FUNCTIONS_STATUS;Z[I.GET_CUSTOM_FUNCTIONS]=I.GET_CUSTOM_FUNCTIONS;Z[I.GET_CUSTOM_FUNCTION]=I.GET_CUSTOM_FUNCTION;Z[I.SET_CUSTOM_FUNCTION]=I.SET_CUSTOM_FUNCTION;Z[I.DROP_CUSTOM_FUNCTION]=I.DROP_CUSTOM_FUNCTION;Z[I.ADD_CUSTOM_FUNCTION_PROJECT]=I.ADD_CUSTOM_FUNCTION_PROJECT;Z[I.DROP_CUSTOM_FUNCTION_PROJECT]=I.DROP_CUSTOM_FUNCTION_PROJECT;Z[I.PACKAGE_CUSTOM_FUNCTION_PROJECT]=I.PACKAGE_CUSTOM_FUNCTION_PROJECT;Z[I.DEPLOY_CUSTOM_FUNCTION_PROJECT]=I.DEPLOY_CUSTOM_FUNCTION_PROJECT;var tw={RUN:"run",INSTALL:"install",REGISTER:"register",STOP:"stop",RESTART:"restart",VERSION:"version",UPGRADE:"upgrade"},rw={point:"point",lineString:"lineString",multiLineString:"multiLineString",multiPoint:"multiPoint",multiPolygon:"multiPolygon",polygon:"polygon"},uh={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"},sw=_h.invert(uh),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"},nw={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},iw={csv_file_load:"csv_file_load",csv_data_load:I.CSV_DATA_LOAD,csv_url_load:I.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"},aw={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"},ow={BIDIRECTIONAL:"BIDIRECTIONAL",OUTBOUND:"OUTBOUND",INBOUND:"INBOUND"},cw={FILE_SYSTEM:"fs",LMDB:"lmdb"},_w={API_CALL_DEFAULT:1e4,VERSION_DEFAULT:"2.2.0"},uw={DEVELOPMENT:8192,DEFAULT:512},lw={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"},Ew={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"},dw={ENOENT:"ENOENT",EACCES:"EACCES"},lh={CREATED_TIME:"__createdtime__",UPDATED_TIME:"__updatedtime__"},hw="__clustering__",Sw=Object.values(lh),fw=15984864e5,Eh={LESS:"<",LESS_OR_EQ:"<=",GREATER:">",GREATER_OR_EQ:">=",BETWEEN:"..."},Tw=_h.invert(Eh),mw={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"},Rw=111,Aw=`\r
|
|
2
|
-
`,
|
|
3
|
-
`}a(_s,"createLogRecord");function ph(e){Ys===void 0&&(
|
|
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(zw,"findPs")});var Ke=h((GJ,Ch)=>{"use strict";var jw="__dbis__",eU="__environment_name__",tU="__dbi_defintion__",rU={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"},sU=["__createdtime__","__updatedtime__"],nU="\uFFFF",bh={TIMESTAMP:"timestamp",HASH_VALUE:"hash_value",USER_NAME:"user_name"},iU=Object.values(bh);Ch.exports={INTERNAL_DBIS_NAME:jw,DBI_DEFINITION_NAME:tU,SEARCH_TYPES:rU,TIMESTAMP_NAMES:sU,MAX_SEARCH_KEY_LENGTH:256,ENVIRONMENT_NAME_KEY:eU,TRANSACTIONS_DBI_NAMES_ENUM:bh,TRANSACTIONS_DBIS:iU,OVERFLOW_MARKER:nU}});var Qe=h((FJ,vh)=>{"use strict";var wh=T(),Uh=Ke(),Lh={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},yh=a(e=>`${e} Check logs and try again.`,"CHECK_LOGS_WRAPPER"),Dh={500:yh("There was an error processing your request."),400:"Invalid request"},aU=Dh[Lh.INTERNAL_SERVER_ERROR],oU={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.`},cU={CONFIG_VALIDATION:e=>`HarperDB config file validation error: ${e}`},_U={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"},uU={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 ${Uh.INTERNAL_DBIS_NAME}`,CANNOT_DROP_INTERNAL_DBIS_NAME:`cannot drop a dbi named ${Uh.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"},lU={ATTR_NAME_LENGTH_ERR:e=>`transaction aborted due to attribute name ${e} being too long. Attribute names cannot be longer than ${wh.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 ${wh.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"},Mh={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"},EU={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."},dU={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`},hU={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"},SU={OUTER_JOIN_TRANSLATION_ERROR:"There was an error translating the final SQL outer join data."},fU={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`},Ph={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.`},Bh={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}`},TU={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."},mU={CLUSTERING_NOT_ENABLED:"Clustering must be enabled to perform this operation."},RU={...Mh,..._U,...oU,...EU,...dU,...hU,...SU,...fU,...lU,...Ph,...Bh,...TU,...mU,...cU};vh.exports={CHECK_LOGS_WRAPPER:yh,HDB_ERROR_MSGS:RU,DEFAULT_ERROR_MSGS:Dh,DEFAULT_ERROR_RESP:aU,HTTP_STATUS_CODES:Lh,LMDB_ERRORS_ENUM:uU,AUTHENTICATION_ERROR_MSGS:Mh,VALIDATION_ERROR_MSGS:Ph,IPC_ERRORS:Bh}});var D=h((VJ,Gh)=>{"use strict";var Qs=Qe(),AU=g(),pU=T(),Yn=class extends Error{constructor(t,r,s,n,i){super(),Error.captureStackTrace(this,Hh),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&&AU[n](i)}};a(Yn,"HdbError");function Hh(e,t,r,s=pU.LOG_LEVELS.ERROR,n=null,i=!1){if(qh(e))return e;let o=new Yn(e,t,r,s,n);return i&&delete o.stack,o}a(Hh,"handleHDBError");function qh(e){return e.__proto__.constructor.name===Yn.name}a(qh,"isHDBError");Gh.exports={isHDBError:qh,handleHDBError:Hh,hdb_errors:Qs}});var b=h((xJ,eS)=>{"use strict";var uu=require("path"),OU=require("fs-extra"),Ce=g(),Fh=require("fs-extra"),NU=require("truncate-utf8-bytes"),Kn=require("os"),gU=require("net"),IU=require("recursive-iterator"),ye=T(),Yh=Ih(),Vh=require("papaparse"),Aa=require("moment"),{inspect:bU}=require("util"),kh=require("is-number"),kJ=require("lodash"),{hdb_errors:pa}=D(),Kh=require("util").promisify(setTimeout),CU=100,wU=5,UU="",LU=4,xh=255,$h={true:!0,false:!1,undefined:null,null:null,NaN:NaN};eS.exports={isEmpty:St,isEmptyOrZeroLength:zt,arrayHasEmptyValues:MU,arrayHasEmptyOrZeroLengthValues:PU,buildFolderPath:BU,isBoolean:Qh,errorizeMessage:yU,stripFileExtension:HU,autoCast:qU,autoCastJSONDeep:lu,removeDir:FU,compareVersions:VU,isCompatibleDataVersion:kU,escapeRawValue:Jh,unescapeValue:xU,stringifyProps:$U,valueConverter:YU,timeoutPromise:QU,isClusterOperation:JU,getClusterUser:zU,sendTransactionToSocketCluster:ZU,checkGlobalSchemaTable:XU,getHomeDir:Zh,getPropsFilePath:KU,promisifyPapaParse:jU,removeBOM:Xh,createEventPromise:eL,checkProcessRunning:tL,checkSchemaTableExist:rL,checkSchemaExists:zh,checkTableExists:jh,getStartOfTomorrowInSeconds:sL,getLimitKey:nL,isObject:vU,isNotEmptyAndHasValue:DU,autoCasterIsNumberCheck:Wh,backtickASTSchemaItems:iL,isPortTaken:WU,stopProcess:aL,createForkArgs:oL,autoCastBoolean:cL,async_set_timeout:Kh,getTableHashAttribute:_L,doesSchemaExist:uL,doesTableExist:lL,stringifyObj:EL,ms_to_time:dL,PACKAGE_ROOT:ye.PACKAGE_ROOT};function yU(e){return e instanceof Error?e:new Error(e)}a(yU,"errorizeMessage");function St(e){return e==null}a(St,"isEmpty");function DU(e){return!St(e)&&(e||e===0||e===""||Qh(e))}a(DU,"isNotEmptyAndHasValue");function zt(e){return St(e)||e.length===0||e.size===0}a(zt,"isEmptyOrZeroLength");function MU(e){if(St(e))return!0;for(let t=0;t<e.length;t++)if(St(e[t]))return!0;return!1}a(MU,"arrayHasEmptyValues");function PU(e){if(zt(e))return!0;for(let t=0;t<e.length;t++)if(zt(e[t]))return!0;return!1}a(PU,"arrayHasEmptyOrZeroLengthValues");function BU(...e){try{return e.join(uu.sep)}catch{console.error(e)}}a(BU,"buildFolderPath");function Qh(e){return St(e)?!1:e===!0||e===!1}a(Qh,"isBoolean");function vU(e){return St(e)?!1:typeof e=="object"}a(vU,"isObject");function HU(e){return zt(e)?UU:e.slice(0,-LU)}a(HU,"stripFileExtension");function qU(e){return St(e)||e===""||typeof e!="string"?e:$h[e]!==void 0?$h[e]:Wh(e)===!0?Number(e):e}a(qU,"autoCast");function GU(e){if(typeof e=="string"&&(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")))try{return JSON.parse(e)}catch{}return e}a(GU,"autoCastJSON");function lu(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=lu(s);n!==s&&(e[t]=n)}else for(let t in e){let r=e[t],s=lu(r);s!==r&&(e[t]=s)}return e}else return GU(e)}a(lu,"autoCastJSONDeep");function Wh(e){if(e.startsWith("0.")&&kh(e))return!0;let t=e.toUpperCase().includes("E");return!!((e!=="0"&&e.startsWith("0"))===!1&&t===!1&&kh(e))}a(Wh,"autoCasterIsNumberCheck");async function FU(e){if(zt(e))throw new Error(`Directory path: ${e} does not exist`);try{await Fh.emptyDir(e),await Fh.remove(e)}catch(t){throw Ce.error(`Error removing files in ${e} -- ${t}`),t}}a(FU,"removeDir");function VU(e,t){if(zt(e)){Ce.info("Invalid current version sent as parameter.");return}if(zt(t)){Ce.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(VU,"compareVersions");function kU(e,t,r=!1){let s=e.toString().split("."),n=t.toString().split(".");return s[0]===n[0]&&(!r||s[1]===n[1])}a(kU,"isCompatibleDataVersion");function Jh(e){if(St(e))return e;let t=String(e);return t==="."?ye.UNICODE_PERIOD:t===".."?ye.UNICODE_PERIOD+ye.UNICODE_PERIOD:t.replace(ye.FORWARD_SLASH_REGEX,ye.UNICODE_FORWARD_SLASH)}a(Jh,"escapeRawValue");function xU(e){if(St(e))return e;let t=String(e);return t===ye.UNICODE_PERIOD?".":t===ye.UNICODE_PERIOD+ye.UNICODE_PERIOD?"..":String(e).replace(ye.ESCAPED_FORWARD_SLASH_REGEX,"/")}a(xU,"unescapeValue");function $U(e,t){if(St(e))return Ce.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}!zt(s)&&s[0]===";"?r+=" "+s+n+Kn.EOL:zt(s)||(r+=s+"="+n+Kn.EOL)}catch{Ce.error(`Found bad property during upgrade with key ${s} and value: ${n}`)}}),r}a($U,"stringifyProps");function YU(e){let t;try{t=typeof e=="object"?JSON.stringify(e):e}catch(n){Ce.error(n),t=e}let r=String(Jh(t)),s=Buffer.byteLength(r)>xh?NU(r,xh)+"/blob":r;return{value:t,value_stripped:r,value_path:s}}a(YU,"valueConverter");function Zh(){let e;try{e=Kn.homedir()}catch{e=process.env.HOME}return e||(e="~/"),e}a(Zh,"getHomeDir");function KU(){let e=uu.join(Zh(),ye.HDB_HOME_DIR_NAME,ye.BOOT_PROPS_FILE_NAME);return OU.existsSync(e)||(e=uu.join(__dirname,"../","hdb_boot_properties.file")),e}a(KU,"getPropsFilePath");function QU(e,t){let r,s;return s=new Promise(function(n){r=setTimeout(function(){n(t)},e)}),{promise:s,cancel:function(){clearTimeout(r)}}}a(QU,"timeoutPromise");async function WU(e){if(!e)throw new Error("Invalid port passed as parameter");return new Promise((t,r)=>{let s=gU.createServer().once("error",n=>{n.code==="EADDRINUSE"?t(!0):r(n)}).once("listening",()=>s.once("close",()=>t(!1)).close()).listen(e)})}a(WU,"isPortTaken");function JU(e){try{return ye.CLUSTER_OPERATIONS[e.toLowerCase()]!==void 0}catch(t){Ce.error(`Error checking operation against cluster ops ${t}`)}return!1}a(JU,"isClusterOperation");function ZU(e,t,r){if(global.hdb_socket_client!==void 0){Ce.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]=ye.ORIGINATOR_SET_VALUE),global.hdb_socket_client.publish(e,i)}}a(ZU,"sendTransactionToSocketCluster");function XU(e,t){if(!global.hdb_schema[e])return pa.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e);if(!global.hdb_schema[e]||!global.hdb_schema[e][t])return pa.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(XU,"checkGlobalSchemaTable");function zU(e,t){if(St(t)){Ce.warn("No CLUSTERING_USER defined, clustering disabled");return}if(St(e)||zt(e)){Ce.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){Ce.error(`unable to find cluster_user due to: ${s.message}`);return}if(r===void 0){Ce.warn(`CLUSTERING_USER: ${t} not found or is not active.`);return}return r}a(zU,"getClusterUser");function jU(){Vh.parsePromise=function(e,t){return new Promise(function(r,s){Vh.parse(e,{header:!0,transformHeader:Xh,chunk:t.bind(null,s),skipEmptyLines:!0,dynamicTyping:!0,error:s,complete:r})})}}a(jU,"promisifyPapaParse");function Xh(e){if(typeof e!="string")throw new TypeError(`Expected a string, got ${typeof e}`);return e.charCodeAt(0)===65279?e.slice(1):e}a(Xh,"removeBOM");function eL(e,t,r){return new Promise(s=>{t.once(e,n=>{let i=r;Ce.info(`Got cluster status event response: ${bU(n)}`);try{i.cancel()}catch{Ce.error("Error trying to cancel timeout.")}s(n)})})}a(eL,"createEventPromise");async function tL(e){let t=!0,r=0;do await Kh(CU*r++),(await Yh.findPs(e)).length>0&&(t=!1);while(t&&r<wU);if(t)throw new Error(`process ${e} was not started`)}a(tL,"checkProcessRunning");function rL(e,t){let r=zh(e);if(r)return r;let s=jh(e,t);if(s)return s}a(rL,"checkSchemaTableExist");function zh(e){if(!global.hdb_schema[e])return pa.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}a(zh,"checkSchemaExists");function jh(e,t){if(!global.hdb_schema[e][t])return pa.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(jh,"checkTableExists");function sL(){let e=Aa().utc().add(1,ye.MOMENT_DAYS_TAG).startOf(ye.MOMENT_DAYS_TAG).unix(),t=Aa().utc().unix();return e-t}a(sL,"getStartOfTomorrowInSeconds");function nL(){return Aa().utc().format("DD-MM-YYYY")}a(nL,"getLimitKey");function iL(e){try{let t=new IU(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){Ce.error("Got an error back ticking items."),Ce.error(t)}}a(iL,"backtickASTSchemaItems");async function aL(e){let t=Kn.userInfo();(await Yh.findPs(e)).forEach(s=>{(t.uid==0||s.uid==t.uid)&&(process.kill(s.pid),Ce.trace(`Following process was killed by stopProcess: ${s.cmd}`))})}a(aL,"stopProcess");function oL(e){return[e]}a(oL,"createForkArgs");function cL(e){return e===!0||typeof e=="string"&&e.toLowerCase()==="true"}a(cL,"autoCastBoolean");function _L(e,t){return global.hdb_schema?.[e]?.[t]?.hash_attribute}a(_L,"getTableHashAttribute");function uL(e){return global?.hdb_schema?.[e]!==void 0}a(uL,"doesSchemaExist");function lL(e,t){return global?.hdb_schema?.[e]?.[t]!==void 0}a(lL,"doesTableExist");function EL(e){try{return JSON.stringify(e)}catch{return e}}a(EL,"stringifyObj");function dL(e){let t=Aa.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(dL,"ms_to_time")});var rS=h(($J,tS)=>{"use strict";var hL={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))},SL="certificate.pem",fL="privateKey.pem",TL="ca.pem";tS.exports={CERTIFICATE_VALUES:hL,CERTIFICATE_PEM_NAME:SL,PRIVATEKEY_PEM_NAME:fL,CA_PEM_NAME:TL}});var he=h((YJ,sS)=>{"use strict";var it=require("validate.js");it.validators.type=function(e,t,r,s){return e===null||typeof e>"u"||it.validators.type.checks[t](e)?null:` must be a '${t}' value`};it.validators.type.checks={Object:function(e){return it.isObject(e)&&!it.isArray(e)},Array:it.isArray,Integer:it.isInteger,Number:it.isNumber,String:it.isString,Date:it.isDate,Boolean:function(e){return typeof e=="boolean"}};it.validators.hasValidFileExt=function(e,t){return!it.isString(e)||e===""||t.filter(r=>e.endsWith(r)).length>0?null:`must include one of the following valid file extensions - '${t.join("', '")}'`};sS.exports={validateObject:mL,validateObjectAsync:RL,validateBySchema:AL};function mL(e,t){if(!e||!t)return new Error("validateObject parameters were null");let r=it(e,t,{format:"flat"});return r?new Error(r):null}a(mL,"validateObject");async function RL(e,t){if(!e||!t)return new Error("validateObject parameters were null");try{await it.async(e,t,{format:"flat"})}catch(r){let s=r.join(",");return new Error(s)}return null}a(RL,"validateObjectAsync");function AL(e,t){let r=t.validate(e,{allowUnknown:!0,abortEarly:!1,errors:{wrap:{label:"'"}}});if(r.error)return new Error(r.error.message)}a(AL,"validateBySchema")});var du=h((KJ,iS)=>{"use strict";var pL=require("fs-extra"),F=require("joi"),OL=require("os"),{boolean:De,string:Sr,number:jt,array:Eu}=F.types(),Ft=require("path"),NL=g(),Oa=b(),fr=rS(),gL=he(),hr="keys",IL=fr.CERTIFICATE_PEM_NAME,bL=fr.PRIVATEKEY_PEM_NAME,CL=fr.CA_PEM_NAME,wL=fr.CERTIFICATE_PEM_NAME,UL=fr.PRIVATEKEY_PEM_NAME,LL=fr.CA_PEM_NAME,yL=fr.CERTIFICATE_PEM_NAME,DL=fr.PRIVATEKEY_PEM_NAME,ML=fr.CA_PEM_NAME,PL="log",BL="custom_functions",vL="Invalid logging.rotation.maxSize unit. Available units are G, M or K",HL="Invalid logging.rotation.maxSize value. Value should be a number followed by unit e.g. '10M'",qL="rootPath config parameter is undefined",GL="clustering.enabled config parameter is undefined",Hr=jt.min(0).required(),Na=Eu.items({host:Sr.required(),port:Hr}).empty(null),at;iS.exports={configValidator:FL,routesValidator:YL,route_constraints:Na};function FL(e){if(at=e.rootPath,Oa.isEmpty(at))throw qL;let t=De.required(),r=F.valid("production","development").required(),s=jt.min(1).max(1e3).empty(null).default($L),n=Sr.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path").empty(null).default(nS),i=F.custom(kL).messages({"any.custom":"{:#label} {:#error}"}).empty(null).default(nS),o=Sr.pattern(/^[^\s.,*>]+$/).messages({"string.pattern.base":"{:#label} invalid, must not contain ., * or >"}).empty(null),c=e.clustering?.enabled;if(Oa.isEmpty(c))throw GL;let _;return c===!0?_=F.object({enabled:t,hubServer:F.object({cluster:F.object({name:F.required().empty(null),network:F.object({port:Hr,routes:Na}).required()}).required(),leafNodes:F.object({network:F.object({port:Hr}).required()}).required(),network:F.object({port:Hr}).required()}).required(),leafServer:F.object({network:F.object({port:Hr,routes:Na}).required()}).required(),nodeName:o,tls:F.object({certificate:i,certificateAuthority:i,privateKey:i,insecure:De.required()}),user:F.string().required()}).required():_=F.object({enabled:t,tls:F.object({certificate:i,certificateAuthority:i,privateKey:i,insecure:De.required()})}).required(),F.object({clustering:_,customFunctions:F.object({enabled:t,network:F.object({cors:De.required(),corsAccessList:Eu.required(),headersTimeout:jt.min(1).required(),https:De.required(),keepAliveTimeout:jt.min(1).required(),port:Hr,timeout:jt.min(1).required()}),nodeEnv:r,root:n,tls:F.object({certificate:i,certificateAuthority:i,privateKey:i})}).required(),ipc:F.object({network:F.object({port:Hr})}).required(),localStudio:F.object({enabled:t}).required(),logging:F.object({file:De.required(),level:F.valid("notify","fatal","error","warn","info","debug","trace"),rotation:F.object({compress:De.required(),dateFormat:Sr.required(),maxSize:Sr.custom(xL).required(),retain:jt.min(0).required(),rotate:De.required(),rotateInterval:Sr.required(),rotateModule:De.required(),timezone:Sr.required(),workerInterval:jt.min(1).required()}).required(),root:n,stdStreams:De.required(),auditLog:De.required()}).required(),operationsApi:F.object({authentication:F.object({operationTokenTimeout:F.required(),refreshTokenTimeout:F.required()}).required(),foreground:De.required(),network:F.object({cors:De.required(),corsAccessList:Eu.required(),headersTimeout:jt.min(1).required(),https:De.required(),keepAliveTimeout:jt.min(1).required(),port:Hr,timeout:jt.min(1).required()}).required(),nodeEnv:r,tls:F.object({certificate:i,certificateAuthority:i,privateKey:i})}).required(),rootPath:Sr.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path").required(),http:F.object({threads:s}).required(),storage:F.object({writeAsync:De.required(),overlappingSync:De.optional()}).required()}).validate(e,{allowUnknown:!0,abortEarly:!1,errors:{wrap:{label:"'"}}})}a(FL,"configValidator");function VL(e){return pL.existsSync(e)?null:`Specified path ${e} does not exist.`}a(VL,"doesPathExist");function kL(e,t){F.assert(e,Sr.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+\.pem+$/).messages({"string.pattern.base":"must be a valid directory path and specify a .pem file"}));let r=VL(e);if(r)return t.message(r)}a(kL,"validatePemFile");function xL(e,t){let r=e.slice(-1);if(r!=="G"&&r!=="M"&&r!=="K")return t.message(vL);let s=e.slice(0,-1);if(isNaN(parseInt(s)))return t.message(HL)}a(xL,"validateRotationMaxSize");function $L(e,t){let r=t.state.path.join("."),s=OL.cpus().length,n=s-1;return n===1&&s===2&&(n=s),NL.info(`Detected ${s} cores on this machine, defaulting ${r} to ${n}`),n}a($L,"setDefaultThreads");function nS(e,t){if(!Oa.isEmpty(t.original))return t.original;let r=t.state.path.join(".");if(Oa.isEmpty(at))throw new Error(`Error setting default root for: ${r}. HDB root is not defined`);switch(r){case"customFunctions.root":return Ft.join(at,BL);case"logging.root":return Ft.join(at,PL);case"operationsApi.tls.certificate":return Ft.join(at,hr,IL);case"operationsApi.tls.privateKey":return Ft.join(at,hr,bL);case"operationsApi.tls.certificateAuthority":return Ft.join(at,hr,CL);case"customFunctions.tls.certificate":return Ft.join(at,hr,wL);case"customFunctions.tls.privateKey":return Ft.join(at,hr,UL);case"customFunctions.tls.certificateAuthority":return Ft.join(at,hr,LL);case"clustering.tls.certificate":return Ft.join(at,hr,yL);case"clustering.tls.privateKey":return Ft.join(at,hr,DL);case"clustering.tls.certificateAuthority":return Ft.join(at,hr,ML);default:throw new Error(`Error setting default root for config parameter: ${r}. Unrecognized config parameter`)}}a(nS,"setDefaultRoot");function YL(e){let t=F.object({routes:Na});return gL.validateBySchema({routes:e},t)}a(YL,"routesValidator")});var Tr=h((QJ,ES)=>{"use strict";var se=T(),bt=b(),We=g(),{configValidator:KL,routesValidator:aS}=du(),Vt=require("fs-extra"),QL=require("yaml"),Ws=require("path"),WL=require("is-number"),ba=require("properties-reader"),JL=require("lodash"),{handleHDBError:ZL}=D(),{HTTP_STATUS_CODES:XL,HDB_ERROR_MSGS:ga}=Qe(),{PACKAGE_ROOT:zL}=T(),jL="Unable to get config value because config is uninitialized",ey="Config successfully initialized",ty="Error backing up config file",ry="Empty parameter sent to getConfigValue",oS=Ws.join(zL,"config","yaml",se.HDB_DEFAULT_CONFIG_FILE),sy="Configuration successfully set. You must restart HarperDB for new config settings to take effect.",Ia,ot;ES.exports={createConfigFile:ny,getDefaultConfig:iy,getConfigValue:cS,initConfig:_S,flattenConfig:us,updateConfigValue:uS,updateConfigObject:ay,getConfiguration:oy,setConfiguration:cy,readConfigFile:fu,getClusteringRoutes:_y,initOldConfig:lS,getConfigFromFile:uy};function ny(e){let t=Js(oS);Ia=us(t.toJSON());for(let i in e){let o=se.CONFIG_PARAM_MAP[i.toLowerCase()];if(o!==void 0){let c=o.split("_"),_=hu(o,e[i]);try{t.setIn([...c],_)}catch(u){We.error(u)}}}Su(t);let r=t.toJSON();ot=us(r);let s=t.getIn(["rootPath"]),n=Ws.join(s,se.HDB_CONFIG_FILE);Vt.createFileSync(n),Vt.writeFileSync(n,String(t)),We.trace(`Config file written to ${n}`)}a(ny,"createConfigFile");function iy(e){if(Ia===void 0){let r=Js(oS);Ia=us(r.toJSON())}let t=se.CONFIG_PARAM_MAP[e.toLowerCase()];if(t!==void 0)return Ia[t.toLowerCase()]}a(iy,"getDefaultConfig");function cS(e){if(bt.isEmpty(e)){We.error(ry);return}if(ot===void 0){We.trace(jL);return}let t=se.CONFIG_PARAM_MAP[e.toLowerCase()];if(t!==void 0)return ot[t.toLowerCase()]}a(cS,"getConfigValue");function _S(e=!1){if(ot===void 0||e){let t=bt.getPropsFilePath();try{Vt.accessSync(t,Vt.constants.F_OK|Vt.constants.R_OK)}catch(o){throw We.error(o),new Error(`HarperDB properties file at path ${t} does not exist`)}let s=ba(t).get(se.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY),n;if(s.includes("config/settings.js"))try{lS(s);return}catch(o){if(o.code!==se.NODE_ERROR_CODES.ENOENT)throw o}try{n=Js(s)}catch(o){if(o.code===se.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}`)}Su(n);let i=n.toJSON();ot=us(i),We.trace(ey)}}a(_S,"initConfig");function Su(e){let t=e.toJSON(),r=KL(t);if(r.error)throw ga.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(Su,"validateConfig");function ay(e,t){ot===void 0&&(ot={});let r=se.CONFIG_PARAM_MAP[e.toLowerCase()];if(r===void 0){We.trace(`Unable to update config object because config param '${e}' does not exist`);return}ot[r.toLowerCase()]=t}a(ay,"updateConfigObject");function uS(e,t,r=void 0,s=!1,n=!1){ot===void 0&&_S();let i=cS(se.CONFIG_PARAM_MAP.hdb_root),o=Ws.join(i,se.HDB_CONFIG_FILE),c=Js(o);if(r===void 0){let l=se.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=hu(l,t);c.setIn([...E],d)}else for(let l in r){let E=se.CONFIG_PARAM_MAP[l.toLowerCase()];if(E!==void 0){let d=E.split("_"),S=hu(E,r[l]);try{c.setIn([...d],S)}catch(m){We.error(m)}}}Su(c);let _=c.getIn(["rootPath"]),u=Ws.join(_,se.HDB_CONFIG_FILE);if(s===!0)try{let l=Ws.join(_,"backup",`${se.HDB_CONFIG_FILE}.bak`);Vt.copySync(o,l),We.trace(`Config file: ${o} backed up to: ${l}`)}catch(l){We.error(ty),We.error(l)}Vt.writeFileSync(u,String(c)),n&&(ot=us(c.toJSON())),We.trace(`Config parameter: ${e} updated with value: ${t}`)}a(uS,"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 hu(e,t){if(e===se.CONFIG_PARAMS.CLUSTERING_NODENAME||e===se.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(WL(t))return parseFloat(t);if(t===!0||t===!1||Array.isArray(t)||bt.isObject(t)||t===null)return t;if(typeof t=="string"&&t.toLowerCase()==="true")return!0;if(typeof t=="string"&&t.toLowerCase()==="false")return!1}if(t===void 0||t.toLowerCase()==="undefined")return null;if(typeof t=="string"&&(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]")))try{return JSON.parse(t)}catch{}return bt.autoCast(t)}a(hu,"castConfigValue");function oy(){let e=bt.getPropsFilePath(),r=ba(e).get(se.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY);return Js(r).toJSON()}a(oy,"getConfiguration");async function cy(e){let{operation:t,hdb_user:r,hdb_auth_header:s,...n}=e;try{return uS(void 0,void 0,n,!0),sy}catch(i){throw typeof i=="string"||i instanceof String?ZL(i,i,XL.BAD_REQUEST,void 0,void 0,!0):i}}a(cy,"setConfiguration");function fu(){let e=bt.getPropsFilePath();try{Vt.accessSync(e,Vt.constants.F_OK|Vt.constants.R_OK)}catch(n){throw We.error(n),new Error(`HarperDB properties file at path ${e} does not exist`)}let r=ba(e).get(se.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY);return Js(r).toJSON()}a(fu,"readConfigFile");function Js(e){return QL.parseDocument(Vt.readFileSync(e,"utf8"),{simpleKeys:!0})}a(Js,"parseYamlDoc");function _y(){let e=fu(),t=e?.clustering?.hubServer?.cluster?.network?.routes;t=bt.isEmptyOrZeroLength(t)?[]:t;let r=aS(t);if(r)throw ga.CONFIG_VALIDATION(r.message);let s=e?.clustering?.leafServer?.network?.routes;s=bt.isEmptyOrZeroLength(s)?[]:s;let n=aS(s);if(n)throw ga.CONFIG_VALIDATION(n.message);if(!bt.isEmptyOrZeroLength(s)&&!bt.isEmptyOrZeroLength(t)){let i=t.filter(o=>s.some(c=>c.host===o.host&&c.port===o.port));if(!bt.isEmptyOrZeroLength(i)){let o=`Duplicate hub and leaf routes found ${JSON.stringify(i)}`;throw ga.CONFIG_VALIDATION(o)}}return{hub_routes:t,leaf_routes:s}}a(_y,"getClusteringRoutes");function lS(e){let t=ba(e);ot={};for(let r in se.CONFIG_PARAM_MAP){let s=t.get(r.toUpperCase());if(bt.isEmpty(s)||typeof s=="string"&&s.trim().length===0)continue;let n=se.CONFIG_PARAM_MAP[r].toLowerCase();n===se.CONFIG_PARAMS.LOGGING_ROOT?ot[n]=Ws.dirname(s):ot[n]=s}return ot}a(lS,"initOldConfig");function uy(e){let t=fu();return JL.get(t,e.replaceAll("_","."))}a(uy,"getConfigFromFile")});var V=h((WJ,hS)=>{"use strict";var Tu=require("fs-extra"),er=require("path"),ly=require("os"),Ey=require("properties-reader"),Qn=g(),Zs=b(),M=T(),Ca=Tr(),dy="Error initializing environment manager",wa="BOOT_PROPS_FILE_PATH",dS=!1,hy={[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},mr={};hS.exports={BOOT_PROPS_FILE_PATH:wa,getHdbBasePath:Sy,setHdbBasePath:fy,get:Ty,initSync:Ry,setProperty:Y,initTestEnvironment:Ay};function Sy(){return mr[M.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]}a(Sy,"getHdbBasePath");function fy(e){mr[M.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=e}a(fy,"setHdbBasePath");function Ty(e){let t=Ca.getConfigValue(e);return t===void 0?mr[e]:t}a(Ty,"get");function Y(e,t){hy[e]&&(mr[e]=t),Ca.updateConfigObject(e,t)}a(Y,"setProperty");function my(){let e;try{e=Zs.getPropsFilePath(),Tu.accessSync(e,Tu.constants.F_OK|Tu.constants.R_OK),dS=!0;let t=Ey(e);return mr[M.HDB_SETTINGS_NAMES.INSTALL_USER]=t.get(M.HDB_SETTINGS_NAMES.INSTALL_USER),mr[M.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY]=t.get(M.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY),mr[wa]=e,!0}catch{return Qn.trace(`Environment manager found no properties file at ${e}`),!1}}a(my,"doesPropFileExist");function Ry(e=!1){try{(dS||my())&&(Ca.initConfig(e),mr[M.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=Ca.getConfigValue(M.HDB_SETTINGS_NAMES.HDB_ROOT_KEY))}catch(t){Qn.error(dy),Qn.error(t),console.error(t),process.exit(1)}}a(Ry,"initSync");function Ay(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,_=er.join(__dirname,"../../","unitTests");mr[wa]=er.join(_,"hdb_boot_properties.file"),Y(M.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY,er.join(_,"settings.test")),Y(M.HDB_SETTINGS_NAMES.INSTALL_USER,ly.userInfo().username),Y(M.HDB_SETTINGS_NAMES.PRIVATE_KEY_KEY,er.join(_,"envDir","utility","keys","privateKey.pem")),Y(M.HDB_SETTINGS_NAMES.CERT_KEY,er.join(_,"envDir","utility","keys","certificate.pem")),Y(M.CONFIG_PARAMS.CUSTOMFUNCTIONS_TLS_PRIVATEKEY,er.join(_,"envDir","utility","keys","privateKey.pem")),Y(M.CONFIG_PARAMS.CUSTOMFUNCTIONS_TLS_CERTIFICATE,er.join(_,"envDir","utility","keys","certificate.pem")),Y(M.HDB_SETTINGS_NAMES.LOG_LEVEL_KEY,"debug"),Y(M.HDB_SETTINGS_NAMES.LOG_PATH_KEY,er.join(_,"envDir","log")),Y(M.HDB_SETTINGS_NAMES.LOG_DAILY_ROTATE_KEY,!1),Y(M.HDB_SETTINGS_NAMES.CLUSTERING_ENABLED_KEY,!0),Y(M.HDB_SETTINGS_NAMES.CLUSTERING_NODE_NAME_KEY,"1231412de213"),Y(M.HDB_SETTINGS_NAMES.HDB_ROOT_KEY,er.join(_,"envDir")),Y(M.HDB_SETTINGS_NAMES.HTTP_SECURE_ENABLED_KEY,Zs.isEmpty(n)?!0:n),Y(M.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HTTPS,Zs.isEmpty(n)?!0:n),Y(M.HDB_SETTINGS_NAMES.SERVER_PORT_KEY,9925),Y(M.HDB_SETTINGS_NAMES.CORS_ENABLED_KEY,Zs.isEmpty(i)?!1:i),Y(M.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_CORS,Zs.isEmpty(i)?!1:i),Y(M.HDB_SETTINGS_NAMES.IPC_SERVER_PORT,9383),Y(M.HDB_SETTINGS_NAMES.MAX_CUSTOM_FUNCTION_PROCESSES,2),Y(M.HDB_SETTINGS_NAMES.MAX_HDB_PROCESSES,4),Y(M.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_PORT_KEY,9926),Y(M.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_ENABLED_KEY,!0),Y(M.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY,er.resolve(__dirname,"../../unitTests/server/customFunctions/custom_functions")),Y(M.HDB_SETTINGS_NAMES.LOCAL_STUDIO_ON,Zs.isEmpty(c)?!1:c),o&&(Y("CORS_ACCESSLIST",o),Y(M.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_CORSACCESSLIST,o)),s&&(Y(M.HDB_SETTINGS_NAMES.SERVER_TIMEOUT_KEY,s),Y(M.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_TIMEOUT,s)),t&&(Y(M.HDB_SETTINGS_NAMES.SERVER_KEEP_ALIVE_TIMEOUT_KEY,t),Y(M.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_KEEPALIVETIMEOUT,t)),r&&(Y(M.HDB_SETTINGS_NAMES.SERVER_HEADERS_TIMEOUT_KEY,r),Y(M.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HEADERSTIMEOUT,r))}catch(t){let r=`Error reading in HDB environment variables from path ${wa}. Please check your boot props and settings files`;Qn.fatal(r),Qn.error(t)}}a(Ay,"initTestEnvironment")});var ls=h((JJ,py)=>{py.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 CS=h((XJ,bS)=>{"use strict";var mu=require("recursive-iterator"),Oy=require("alasql"),Ru=require("clone"),SS=b(),{handleHDBError:fS,hdb_errors:Ny}=D(),{HDB_ERROR_MSGS:TS,HTTP_STATUS_CODES:mS}=Ny,gy=["DISTINCT_ARRAY"],RS=Symbol("validateTables"),Au=Symbol("validateTable"),ZJ=Symbol("getAllColumns"),AS=Symbol("validateAllColumns"),Ua=Symbol("findColumn"),pS=Symbol("validateOrderBy"),Wn=Symbol("validateSegment"),pu=Symbol("validateColumn"),OS=Symbol("setColumnsForTable"),NS=Symbol("checkColumnsForAsterisk"),gS=Symbol("validateGroupBy"),IS=Symbol("hasColumns"),La=class{constructor(t){this.statement=t,this.attributes=[]}validate(){if(!this.statement)throw new Error("invalid sql statement");this[RS](),this[NS](),this[AS]()}[RS](){if(this[IS]()){if(!this.statement.from||this.statement.from.length===0)throw"no from clause";this.statement.from.forEach(t=>{this[Au](t)}),this.statement.joins&&this.statement.joins.forEach(t=>{t.table.as=t.as,this[Au](t.table)})}}[IS](){let t=!1,r=new mu(this.statement);for(let{node:s,path:n}of r)if(s&&s.columnid){t=!0;break}return t}[Au](t){if(!t.databaseid)throw`schema not defined for table ${t.tableid}`;if(!global.hdb_schema[t.databaseid])throw fS(new Error,TS.SCHEMA_NOT_FOUND(t.databaseid),mS.NOT_FOUND);if(!global.hdb_schema[t.databaseid][t.tableid])throw fS(new Error,TS.TABLE_NOT_FOUND(t.databaseid,t.tableid),mS.NOT_FOUND);global.hdb_schema[t.databaseid][t.tableid].attributes.forEach(s=>{let n=Ru(s);n.table=Ru(t),this.attributes.push(n)})}[Ua](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)}[NS](){let t=new mu(this.statement.columns);for(let{node:r,path:s}of t)r&&r.columnid==="*"&&s.indexOf("expression")<0&&this[OS](r.tableid)}[OS](t){this.attributes.forEach(r=>{(!t||t&&(r.table.tableid===t||r.table.as===t))&&this.statement.columns.push(new Oy.yy.Column({columnid:r.attribute,tableid:r.table.as?r.table.as:r.table.tableid}))})}[AS](){this[Wn](this.statement.columns,!1),this[Wn](this.statement.joins,!1),this[Wn](this.statement.where,!1),this[gS](this.statement.group,!1),this[Wn](this.statement.order,!0)}[Wn](t,r){if(!t)return;let s=new mu(t),n=[];for(let{node:i,path:o}of s)!SS.isEmpty(i)&&!SS.isEmpty(i.columnid)&&i.columnid!=="*"&&(r?this[pS](i):n.push(this[pu](i)));return n}[gS](t){if(!t)return;let r=[];if(this.statement.columns.forEach(s=>{if(!(s.funcid&&gy.indexOf(s.funcid.toUpperCase())>=0)){if(!s.aggregatorid&&!s.columnid){let n=Ru(s);delete n.as,r.push(n)}else if(s.columnid){let n=this[Ua](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[Ua](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`}[pS](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[pu](t)}[pu](t){let r=this[Ua](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(La,"SelectValidator");bS.exports=La});var Ou=h((zJ,wS)=>{"use strict";var ya=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(ya,"BridgeMethods");wS.exports=ya});var Es=h((tZ,DS)=>{"use strict";var US=Qe().LMDB_ERRORS_ENUM,jJ=require("lmdb"),Iy=Ke(),eZ=require("buffer").Buffer,by=require("microtime"),{OVERFLOW_MARKER:LS,MAX_SEARCH_KEY_LENGTH:Da}=Iy,yS=["number","string","symbol","boolean","bigint"];function Cy(e){if(!e)throw new Error(US.ENV_REQUIRED);if(e.constructor.name!=="LMDBStore")throw new Error(US.INVALID_ENVIRONMENT)}a(Cy,"validateEnv");function wy(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(wy,"stringifyData");function Uy(e){return e instanceof Date?e.valueOf():e}a(Uy,"convertKeyValueToWrite");function Ly(e){if(e==null)return;if(yS.includes(typeof e))return e.length>Da?[e.slice(0,Da)+LS]:[e];let t;if(Array.isArray(e)){t=[];for(let r=0,s=e.length;r<s;r++){let n=e[r];yS.includes(typeof n)&&(n.length>Da?t.push(n.slice(0,Da)+LS):t.push(n))}}return t}a(Ly,"getIndexedValues");function yy(){let e=by.now().toString(),t=e.length-3;return Number(e.slice(0,t)+"."+e.slice(t))}a(yy,"getMicroTime");DS.exports={validateEnv:Cy,stringifyData:wy,convertKeyValueToWrite:Uy,getMicroTime:yy,getIndexedValues:Ly}});var PS=h((rZ,MS)=>{"use strict";var Ma=class{constructor(t=!1,r=!1){this.dup_sort=t,this.is_hash_attribute=r,this.useVersions=r}};a(Ma,"DBIDefinition");MS.exports=Ma});var vS=h((sZ,BS)=>{"use strict";var Pa=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(Pa,"OpenDBIObject");BS.exports=Pa});var qS=h((nZ,HS)=>{"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");HS.exports=Ba});var X=h((aZ,ZS)=>{"use strict";var Nu=require("lmdb"),Ct=require("fs-extra"),kt=require("path"),Ha=Es(),GS=g(),Me=Qe().LMDB_ERRORS_ENUM,qa=PS(),gu=vS(),FS=qS(),qr=Ke(),iZ=T(),Jn=V();Jn.initSync();var VS=Jn.get("STORAGE_WRITEASYNC")===!0||Jn.get("STORAGE_WRITEASYNC")==="true"||Jn.get("STORAGE_WRITEASYNC")==="TRUE",kS=Jn.get("STORAGE_OVERLAPPINGSYNC"),xS=1024*1024*1024,$S=1e4,YS=1e3,xt=qr.INTERNAL_DBIS_NAME,KS=qr.DBI_DEFINITION_NAME,Dy="data.mdb",My="lock.mdb",Zn=".mdb",Py="-lock",va=class{constructor(t,r,s=!1){this.dbi=wt(t,r),this.key_type=this.dbi[qr.DBI_DEFINITION_NAME].key_type,this.is_hash_attribute=this.dbi[qr.DBI_DEFINITION_NAME].is_hash_attribute,this.txn=t.beginTxn({readOnly:s===!1}),this.cursor=new Nu.Cursor(this.txn,this.dbi)}close(){this.cursor.close(),this.txn.abort()}commit(){this.cursor.close(),this.txn.commit()}};a(va,"TransactionCursor");function Iu(e,t){if(e===void 0)throw new Error(Me.BASE_PATH_REQUIRED);if(t===void 0)throw new Error(Me.ENV_NAME_REQUIRED)}a(Iu,"pathEnvNameValidation");async function bu(e,t,r=!0){try{await Ct.access(e)}catch(s){throw s.code==="ENOENT"?new Error(Me.INVALID_BASE_PATH):s}try{let s=kt.join(e,t+Zn);return await Ct.access(s,Ct.constants.R_OK|Ct.constants.F_OK),s}catch(s){if(s.code==="ENOENT")if(r)try{return await Ct.access(kt.join(e,t,Dy),Ct.constants.R_OK|Ct.constants.F_OK),kt.join(e,t)}catch(n){if(n.code==="ENOENT")throw new Error(Me.INVALID_ENVIRONMENT)}else throw new Error(Me.INVALID_ENVIRONMENT);throw s}}a(bu,"validateEnvironmentPath");function Ga(e,t){if(Ha.validateEnv(e),t===void 0)throw new Error(Me.DBI_NAME_REQUIRED)}a(Ga,"validateEnvDBIName");async function By(e,t,r=!1,s=!1){Iu(e,t),t=t.toString();try{return await bu(e,t,s),Cu(e,t,r)}catch(n){if(n.message===Me.INVALID_ENVIRONMENT){let i=kt.join(e,t);await Ct.mkdirp(s?i:e);let o=new FS(s?i:i+Zn,xS,$S,YS,!1,VS,kS),c=Nu.open(o);c.dbis=Object.create(null);let _=new gu(!1);c.openDB(xt,_),global.lmdb_map===void 0&&(global.lmdb_map=Object.create(null));let u=wu(e,t,r);return c[qr.ENVIRONMENT_NAME_KEY]=u,global.lmdb_map[u]=c,c}throw n}}a(By,"createEnvironment");async function vy(e,t,r,s=!0){let n=await Cu(e,t);if(r===void 0)throw new Error(Me.DESTINATION_PATH_REQUIRED);try{await Ct.access(kt.dirname(r))}catch(i){throw i.code==="ENOENT"?new Error(Me.INVALID_DESTINATION_PATH):i}await n.backup(r,s)}a(vy,"copyEnvironment");async function Cu(e,t,r=!1){Iu(e,t),t=t.toString();let s=wu(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 bu(e,t),i=kt.join(e,t+Zn),o=n!=i,c=new FS(n,xS,$S,YS,o,VS,kS),_=Nu.open(c);_.dbis=Object.create(null);let u=WS(_);for(let l=0;l<u.length;l++)wt(_,u[l]);return _[qr.ENVIRONMENT_NAME_KEY]=s,global.lmdb_map[s]=_,_}a(Cu,"openEnvironment");async function Hy(e,t,r=!1){Iu(e,t),t=t.toString();let s=kt.join(e,t+Zn),n=await bu(e,t);if(global.lmdb_map!==void 0){let i=wu(e,t,r);if(global.lmdb_map[i]){let o=global.lmdb_map[i];await QS(o),delete global.lmdb_map[i]}}await Ct.remove(n),await Ct.remove(n===s?n+Py:kt.join(kt.dirname(n),My))}a(Hy,"deleteEnvironment");async function QS(e){Ha.validateEnv(e);let t=e[qr.ENVIRONMENT_NAME_KEY];await e.close(),t!==void 0&&global.lmdb_map!==void 0&&delete global.lmdb_map[t]}a(QS,"closeEnvironment");function wu(e,t,r=!1){let n=`${kt.basename(e)}.${t}`;return r===!0&&(n=`txn.${n}`),n}a(wu,"getCachedEnvironmentName");function qy(e){Ha.validateEnv(e);let t=Object.create(null),r=wt(e,xt);for(let{key:s,value:n}of r.getRange({start:!1}))if(s!==xt)try{t[s]=Object.assign(new qa,n)}catch{GS.warn(`an internal error occurred: unable to parse DBI Definition for ${s}`)}return t}a(qy,"listDBIDefinitions");function WS(e){Ha.validateEnv(e);let t=[],r=wt(e,xt);for(let{key:s}of r.getRange({start:!1}))s!==xt&&t.push(s);return t}a(WS,"listDBIs");function Gy(e,t){let s=wt(e,xt).getEntry(t),n=new qa;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(Gy,"getDBIDefinition");function JS(e,t,r,s=!1){if(Ga(e,t),t=t.toString(),t===xt)throw new Error(Me.CANNOT_CREATE_INTERNAL_DBIS_NAME);try{return wt(e,t)}catch(n){if(n.message===Me.DBI_DOES_NOT_EXIST){let i=new gu(r,s===!0),o=e.openDB(t,i),c=new qa(r===!0,s);return o[KS]=c,wt(e,xt).putSync(t,c),e.dbis[t]=o,o}throw n}}a(JS,"createDBI");function wt(e,t){if(Ga(e,t),t=t.toString(),e.dbis[t]!==void 0)return e.dbis[t];let r;if(t!==xt?r=Gy(e,t):r=new qa,r===void 0)throw new Error(Me.DBI_DOES_NOT_EXIST);let s;try{let n=new gu(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(Me.DBI_DOES_NOT_EXIST):n}return s[KS]=r,e.dbis[t]=s,s}a(wt,"openDBI");function Fy(e,t){Ga(e,t),t=t.toString();let r=wt(e,t),s=r.getStats();return r[qr.DBI_DEFINITION_NAME].is_hash_attribute&&s.entryCount>0&&s.entryCount--,s}a(Fy,"statDBI");async function Vy(e,t){try{let r=kt.join(e,t+Zn);return(await Ct.stat(r)).size}catch{throw new Error(Me.INVALID_ENVIRONMENT)}}a(Vy,"environmentDataSize");function ky(e,t){if(Ga(e,t),t=t.toString(),t===xt)throw new Error(Me.CANNOT_DROP_INTERNAL_DBIS_NAME);wt(e,t).dropSync(),e.dbis!==void 0&&delete e.dbis[t],wt(e,xt).removeSync(t)}a(ky,"dropDBI");function xy(e,t,r){for(let s=0;s<r.length;s++){let n=r[s];if(!e.dbis[n])try{wt(e,n)}catch(i){if(i.message===Me.DBI_DOES_NOT_EXIST)JS(e,n,n!==t,n===t);else throw i}}}a(xy,"initializeDBIs");ZS.exports={openDBI:wt,openEnvironment:Cu,createEnvironment:By,listDBIs:WS,listDBIDefinitions:qy,createDBI:JS,dropDBI:ky,statDBI:Fy,deleteEnvironment:Hy,initializeDBIs:xy,TransactionCursor:va,environmentDataSize:Vy,copyEnvironment:vy,closeEnvironment:QS}});var zS=h((oZ,XS)=>{"use strict";var Fa=class{constructor(t=[],r=[],s=void 0){this.written_hashes=t,this.skipped_hashes=r,this.txn_time=s}};a(Fa,"InsertRecordsResponseObject");XS.exports=Fa});var ef=h((cZ,jS)=>{"use strict";var Va=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(Va,"UpdateRecordsResponseObject");jS.exports=Va});var rf=h((_Z,tf)=>{"use strict";var ka=class{constructor(t=[],r=void 0,s=[]){this.written_hashes=t,this.txn_time=r,this.original_records=s}};a(ka,"UpsertRecordsResponseObject");tf.exports=ka});var Xs=h((dZ,nf)=>{"use strict";var $y=X(),Yy=zS(),Ky=ef(),Qy=rf(),zn=Es(),Xn=Qe().LMDB_ERRORS_ENUM,Wy=Ke(),Gr=T(),Jy=b(),Zy=require("uuid"),uZ=require("lmdb"),{handleHDBError:Xy,hdb_errors:zy}=D(),{OVERFLOW_MARKER:lZ,MAX_SEARCH_KEY_LENGTH:EZ}=Wy,Uu=Gr.TIME_STAMP_NAMES_ENUM.CREATED_TIME,ds=Gr.TIME_STAMP_NAMES_ENUM.UPDATED_TIME;async function jy(e,t,r,s,n=!0){Mu(e,t,r,s),Lu(e,t,r);let i=new Yy,o=[],c=[];for(let _=0;_<s.length;_++){let u=s[_];sf(u,!0,n);let l=eD(e,t,r,u),E=u[t];o.push(l),c.push(E)}return yu(o,c,s,i)}a(jy,"insertRecords");function eD(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][Gr.FUNC_VAL],s[o]=c)}let _=zn.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[ds])})}a(eD,"insertRecord");function tD(e,t=[]){let r=0;for(let s=0;s<t.length;s++){let n=t[s];e.splice(n-r,1),r++}}a(tD,"removeSkippedRecords");function sf(e,t,r=!0){let s=Date.now();(r===!0||!Number.isInteger(e[ds]))&&(e[ds]=s),t===!0?(r===!0||!Number.isInteger(e[Uu]))&&(e[Uu]=s):delete e[Uu]}a(sf,"setTimestamps");function Lu(e,t,r){r.indexOf(Gr.TIME_STAMP_NAMES_ENUM.CREATED_TIME)<0&&r.push(Gr.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.indexOf(Gr.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)<0&&r.push(Gr.TIME_STAMP_NAMES_ENUM.UPDATED_TIME),$y.initializeDBIs(e,t,r)}a(Lu,"initializeTransaction");async function rD(e,t,r,s,n=!0){Mu(e,t,r,s),Lu(e,t,r);let i=new Ky,o=[],c=[],_=[];for(let u=0;u<s.length;u++){let l=s[u],E=l[t],d;try{d=Du(e,t,l,E,i,!0,n)}catch{i.skipped_hashes.push(E),o.push(u);continue}c.push(d),_.push(E)}return yu(c,_,s,i,o)}a(rD,"updateRecords");async function sD(e,t,r,s,n=!0){try{Mu(e,t,r,s)}catch(_){throw Xy(_,_.message,zy.HTTP_STATUS_CODES.BAD_REQUEST)}Lu(e,t,r);let i=new Qy,o=[],c=[];for(let _=0;_<s.length;_++){let u=s[_],l;Jy.isEmpty(u[t])?(l=Zy.v4(),u[t]=l):l=u[t];let E=Du(e,t,u,l,i,!1,n);o.push(E),c.push(l)}return yu(o,c,s,i)}a(sD,"upsertRecords");async function yu(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=zn.getMicroTime(),tD(r,n),s}a(yu,"finalizeWrite");function Du(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(sf(r,!l,o),Number.isInteger(r[ds])&&u[ds]>r[ds])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 U=u[m];if(typeof R=="function"){let j=R([[u]]);Array.isArray(j)&&(R=j[0][Gr.FUNC_VAL],r[m]=R)}if(R===U)continue;let B=zn.getIndexedValues(U);if(B)for(let j=0,k=B.length;j<k;j++)w.remove(B[j],s);if(B=zn.getIndexedValues(R),B)for(let j=0,k=B.length;j<k;j++)w.put(B[j],s)}let S=Object.assign({},u,r);c.put(s,S,S[ds])},"do_put");return _?E=c.ifVersion(s,_.version,d):E=c.ifNoExists(s,d),E.then(S=>S?!0:Du(e,t,r,s,n,i,o))}a(Du,"updateUpsertRecord");function nD(e,t,r){if(zn.validateEnv(e),t===void 0)throw new Error(Xn.HASH_ATTRIBUTE_REQUIRED);if(!Array.isArray(r))throw r===void 0?new Error(Xn.WRITE_ATTRIBUTES_REQUIRED):new Error(Xn.WRITE_ATTRIBUTES_MUST_BE_ARRAY)}a(nD,"validateBasic");function Mu(e,t,r,s){if(nD(e,t,r),!Array.isArray(s))throw s===void 0?new Error(Xn.RECORDS_REQUIRED):new Error(Xn.RECORDS_MUST_BE_ARRAY)}a(Mu,"validateWrite");nf.exports={insertRecords:jy,updateRecords:rD,upsertRecords:sD}});var re=h((hZ,of)=>{"use strict";var Pu=T(),zs=V(),Bu=require("path");zs.initSync();var xa,$a,Ya;function af(){if(xa!==void 0)return xa;if(zs.getHdbBasePath()!==void 0)return xa=Bu.join(zs.getHdbBasePath(),Pu.SCHEMA_DIR_NAME),xa}a(af,"getBaseSchemaPath");function iD(){if($a!==void 0)return $a;if(zs.getHdbBasePath()!==void 0)return $a=Bu.join(af(),Pu.SYSTEM_SCHEMA_NAME),$a}a(iD,"getSystemSchemaPath");function aD(){if(Ya!==void 0)return Ya;if(zs.getHdbBasePath()!==void 0)return Ya=Bu.join(zs.getHdbBasePath(),Pu.TRANSACTIONS_DIR_NAME),Ya}a(aD,"getTransactionAuditStorePath");of.exports={getBaseSchemaPath:af,getSystemSchemaPath:iD,getTransactionAuditStorePath:aD}});var Rr=h((SZ,uf)=>{"use strict";var _f=b(),cf=T(),Qa=/^[\x20-\x2E|\x30-\x5F|\x61-\x7E]*$/,vu=require("joi"),Ka={schema_format:{pattern:Qa,message:"names cannot include backticks or forward slashes"},schema_length:{maximum:250,tooLong:"cannot exceed 250 characters"}},oD=vu.alternatives(vu.string().min(1).max(Ka.schema_length.maximum).pattern(Qa).messages({"string.pattern.base":"{:#label} "+Ka.schema_format.message}),vu.number()).required();function cD(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`:Qa.test(t)?"":`'${e}' has illegal characters`:`'${e}' must be at least one character`:`'${e}' is required`}a(cD,"checkValidTable");function _D(e,t){return _f.doesSchemaExist(e)?e:t.message(`Schema '${e}' does not exist`)}a(_D,"validateSchemaExists");function uD(e,t){let r=t.state.ancestors[0].schema;return _f.doesTableExist(r,e)?e:t.message(`Table '${e}' does not exist`)}a(uD,"validateTableExists");function lD(e,t){return e.toLowerCase()===cf.SYSTEM_SCHEMA_NAME?t.message(`'subscriptions[${t.state.path[1]}]' invalid schema name, '${cf.SYSTEM_SCHEMA_NAME}' name is reserved`):e}a(lD,"validateSchemaName");uf.exports={common_validators:Ka,schema_regex:Qa,hdb_schema_table:oD,validateSchemaExists:_D,validateTableExists:uD,validateSchemaName:lD,checkValidTable:cD}});var Wa=h((fZ,lf)=>{var{common_validators:Fr}=Rr(),jn=he(),$t="is required",z={schema:{presence:!0,format:Fr.schema_format,length:Fr.schema_length},table:{presence:!0,format:Fr.schema_format,length:Fr.schema_length},attribute:{presence:!0,format:Fr.schema_format,length:Fr.schema_length},hash_attribute:{presence:!0,format:Fr.schema_format,length:Fr.schema_length}};function ei(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(ei,"makeAttributesStrings");function ED(e){return e=ei(e),z.schema.presence={message:$t},z.table.presence=!1,z.attribute.presence=!1,z.hash_attribute.presence=!1,jn.validateObject(e,z)}a(ED,"schema_object");function dD(e){return e=ei(e),z.schema.presence={message:$t},z.table.presence={message:$t},z.attribute.presence=!1,z.hash_attribute.presence=!1,jn.validateObject(e,z)}a(dD,"table_object");function hD(e){return e=ei(e),z.schema.presence={message:$t},z.table.presence={message:$t},z.attribute.presence=!1,z.hash_attribute.presence={message:$t},jn.validateObject(e,z)}a(hD,"create_table_object");function SD(e){return e=ei(e),z.schema.presence={message:$t},z.table.presence={message:$t},z.attribute.presence={message:$t},z.hash_attribute.presence=!1,jn.validateObject(e,z)}a(SD,"attribute_object");function fD(e){return e=ei(e),z.schema.presence={message:$t},z.table.presence={message:$t},z.attribute.presence=!1,z.hash_attribute.presence=!1,jn.validateObject(e,z)}a(fD,"describe_table");function TD(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(TD,"validateTableResidence");lf.exports={schema_object:ED,create_table_object:hD,table_object:dD,attribute_object:SD,describe_table:fD,validateTableResidence:TD}});var df=h((TZ,Ef)=>{"use strict";var mD=require("uuid"),Ja=class{constructor(t,r,s,n){this.schema=t,this.table=r,this.attribute=s,this.id=n||mD.v4(),this.schema_table=`${this.schema}.${this.table}`}};a(Ja,"CreateAttributeObject");Ef.exports=Ja});var Xa=h((mZ,hf)=>{"use strict";var RD=df(),Za=class extends RD{constructor(t,r,s,n,i=!0,o=!1){super(t,r,s,n),this.dup_sort=i,this.is_hash_attribute=o}};a(Za,"LMDBCreateAttributeObject");hf.exports=Za});var ff=h((RZ,Sf)=>{"use strict";Sf.exports=pD;var AD="inserted";function pD(e,t,r,s){let n={message:`${e} ${t.length} of ${r.records.length} records`,skipped_hashes:s};return e===AD?(n.inserted_hashes=t,n):(n.update_hashes=t,n)}a(pD,"returnObject")});var za=h((AZ,mf)=>{"use strict";var OD=T(),Hu=X(),ND=Xs(),{getSystemSchemaPath:gD,getBaseSchemaPath:ID}=re(),bD=require("path"),CD=ls(),wD=Wa(),UD=Xa(),LD=ff(),{handleHDBError:yD,hdb_errors:DD}=D(),MD=b(),qu=CD.hdb_attribute,Tf=[];for(let e=0;e<qu.attributes.length;e++)Tf.push(qu.attributes[e].attribute);var PD="inserted";mf.exports=BD;async function BD(e){let t=wD.attribute_object(e);if(t)throw yD(new Error,t.message,DD.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0);e.is_hash_attribute=e.is_hash_attribute=="true",e.dup_sort=MD.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 UD(e.schema,e.table,e.attribute,e.id);try{let n=await Hu.openEnvironment(bD.join(ID(),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}`);Hu.createDBI(n,e.attribute,e.dup_sort,e.is_hash_attribute);let i=await Hu.openEnvironment(gD(),OD.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME),{written_hashes:o,skipped_hashes:c}=await ND.insertRecords(i,qu.hash_attribute,Tf,[s]);return LD(PD,o,{records:[s]},c)}catch(n){throw n}}a(BD,"lmdbCreateAttribute")});var Fu=h((pZ,Af)=>{var{hdb_schema_table:Rf}=Rr(),vD=he(),Gu=require("joi"),HD={undefined:"undefined",null:"null"},qD=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||HD[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"),GD=Gu.object({schema:Rf,table:Rf,records:Gu.array().items(Gu.object().custom(qD)).required()});Af.exports=function(e){return vD.validateBySchema(e,GD)}});var ja=h((NZ,Of)=>{"use strict";var Ar=b(),pf=g(),OZ=Fu();Of.exports=FD;function FD(e){if(Ar.isEmpty(e))throw new Error("invalid update parameters defined.");if(Ar.isEmptyOrZeroLength(e.schema))throw new Error("invalid schema specified.");if(Ar.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(Ar.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&&Ar.isEmptyOrZeroLength(o[r]))throw pf.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(!Ar.isEmptyOrZeroLength(o[r])&&(o[r]==="null"||o[r]==="undefined"))throw pf.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`);!Ar.isEmpty(o[r])&&o[r]!==""&&s.has(Ar.autoCast(o[r]))&&(o.skip=!0),s.add(Ar.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(FD,"insertUpdateValidate")});var ti=h((gZ,Nf)=>{"use strict";var VD=T().OPERATIONS_ENUM,eo=class{constructor(t,r,s,n,i=void 0){this.operation=VD.INSERT,this.schema=t,this.table=r,this.hash_attribute=s,this.records=n,this.__origin=i}};a(eo,"InsertObject");Nf.exports=eo});var ro=h((bZ,gf)=>{"use strict";var IZ=ti(),to=T(),ku=b(),Vu=g(),kD=require("uuid"),{handleHDBError:ri,hdb_errors:xD}=D(),{HDB_ERROR_MSGS:si,HTTP_STATUS_CODES:ni}=xD;gf.exports=$D;function $D(e,t,r){for(let n=0;n<t.length;n++)YD(t[n]);let{records:s}=e;for(let n=0;n<s.length;n++){let i=s[n];KD(i,r,e.operation)}}a($D,"processRows");function YD(e){if(Buffer.byteLength(String(e))>to.INSERT_MODULE_ENUM.MAX_CHARACTER_SIZE)throw ri(new Error,si.ATTR_NAME_LENGTH_ERR(e),ni.BAD_REQUEST,void 0,void 0,!0);if(ku.isEmptyOrZeroLength(e)||ku.isEmpty(e.trim()))throw ri(new Error,si.ATTR_NAME_NULLISH_ERR,ni.BAD_REQUEST,void 0,void 0,!0)}a(YD,"validateAttribute");function KD(e,t,r){if(!e.hasOwnProperty(t)||ku.isEmptyOrZeroLength(e[t])){if(r===to.OPERATIONS_ENUM.INSERT||r===to.OPERATIONS_ENUM.UPSERT){e[t]=kD.v4();return}throw Vu.error("Update transaction aborted due to record with no hash value:",e),ri(new Error,si.RECORD_MISSING_HASH_ERR,ni.BAD_REQUEST,void 0,void 0,!0)}if(Buffer.byteLength(String(e[t]))>to.INSERT_MODULE_ENUM.MAX_CHARACTER_SIZE)throw Vu.error(e),ri(new Error,si.HASH_VAL_LENGTH_ERR,ni.BAD_REQUEST,void 0,void 0,!0);if(isNaN(e[t])&&e[t].includes("/"))throw Vu.error(e),ri(new Error,si.INVALID_FORWARD_SLASH_IN_HASH_ERR,ni.BAD_REQUEST,void 0,void 0,!0)}a(KD,"validateHash")});var bf=h((CZ,If)=>{"use strict";var so=class{constructor(t,r){this.type=t,this.message=r}};a(so,"IPCEventObject");If.exports=so});var Vr=h((wZ,Cf)=>{"use strict";var QD=g(),xu=b(),WD=T(),{IPC_ERRORS:ii}=Qe();Cf.exports={sendIpcEvent:JD,validateEvent:ZD,SchemaEventMsg:XD,UserEventMsg:zD};function JD(e){global.hdb_ipc?global.hdb_ipc.emitToServer(e):QD.warn("Tried to send event:",e,"to HDB IPC client but it does not exist")}a(JD,"sendIpcEvent");function ZD(e){if(typeof e!="object")return ii.INVALID_IPC_DATA_TYPE;if(!e.hasOwnProperty("type")||xu.isEmpty(e.type))return ii.MISSING_TYPE;if(!e.hasOwnProperty("message")||xu.isEmpty(e.message))return ii.MISSING_MSG;if(!e.message.hasOwnProperty("originator")||xu.isEmpty(e.message.originator))return ii.MISSING_ORIGIN;if(WD.IPC_EVENT_TYPES[e.type.toUpperCase()]===void 0)return ii.INVALID_EVENT(e.type)}a(ZD,"validateEvent");function XD(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(XD,"SchemaEventMsg");function zD(e){this.originator=e}a(zD,"UserEventMsg")});var js=h((LZ,yf)=>{"use strict";var wf=T(),UZ=b(),no=g(),Uf=bf(),{sendIpcEvent:Lf}=Vr();function jD(e){try{no.trace("signalSchemaChange called with message:",e);let t=new Uf(wf.IPC_EVENT_TYPES.SCHEMA,e);Lf(t)}catch(t){no.error(t)}}a(jD,"signalSchemaChange");function eM(e){try{no.trace("signalUserChange called with message:",e);let t=new Uf(wf.IPC_EVENT_TYPES.USER,e);Lf(t)}catch(t){no.error(t)}}a(eM,"signalUserChange");yf.exports={signalSchemaChange:jD,signalUserChange:eM}});var io=h((yZ,Mf)=>{"use strict";var Df=b(),tM=T(),rM=g(),sM=za(),nM=Xa(),iM=js(),{SchemaEventMsg:aM}=Vr(),oM="already exists in";Mf.exports=cM;async function cM(e,t,r){try{if(Df.isEmptyOrZeroLength(r))return r;let s=[];Df.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 _M(e,t.schema,t.name,i)})),n}catch(s){throw s}}a(cM,"lmdbCheckForNewAttributes");async function _M(e,t,r,s){let n=new nM(t,r,s,void 0,!0);e&&(n.hdb_auth_header=e);try{await uM(n)}catch(i){if(typeof i=="object"&&i.message!==void 0&&i.message.includes(oM))rM.warn(`attribute ${t}.${r}.${s} already exists`);else throw i}}a(_M,"createNewAttribute");async function uM(e){let t;try{return t=await sM(e),iM.signalSchemaChange(new aM(process.pid,tM.OPERATIONS_ENUM.CREATE_ATTRIBUTE,e.schema,e.table,e.attribute)),t}catch(r){throw r}}a(uM,"createAttribute")});var en=h((DZ,Pf)=>{"use strict";var ao=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(ao,"LMDBTransactionObject");Pf.exports=ao});var vf=h((MZ,Bf)=>{"use strict";var lM=en(),EM=T().OPERATIONS_ENUM,oo=class extends lM{constructor(t,r,s,n,i=void 0){super(EM.INSERT,r,s,n,i),this.records=t}};a(oo,"LMDBInsertTransactionObject");Bf.exports=oo});var qf=h((PZ,Hf)=>{"use strict";var dM=en(),hM=T().OPERATIONS_ENUM,co=class extends dM{constructor(t,r,s,n,i,o=void 0){super(hM.UPDATE,s,n,i,o),this.records=t,this.original_records=r}};a(co,"LMDBUpdateTransactionObject");Hf.exports=co});var Ff=h((BZ,Gf)=>{"use strict";var SM=en(),fM=T().OPERATIONS_ENUM,_o=class extends SM{constructor(t,r,s,n,i,o=void 0){super(fM.UPSERT,s,n,i,o),this.records=t,this.original_records=r}};a(_o,"LMDBUpsertTransactionObject");Gf.exports=_o});var kf=h((vZ,Vf)=>{"use strict";var TM=en(),mM=T().OPERATIONS_ENUM,uo=class extends TM{constructor(t,r,s,n,i=void 0){super(mM.DELETE,s,n,t,i),this.original_records=r}};a(uo,"LMDBDeleteTransactionObject");Vf.exports=uo});var ai=h((HZ,Kf)=>{"use strict";var RM=require("path"),xf=X(),AM=vf(),pM=qf(),OM=Ff(),NM=kf(),tn=Ke(),$f=b(),{CONFIG_PARAMS:gM}=T(),Yf=V();Yf.initSync();var lo=T().OPERATIONS_ENUM,{getTransactionAuditStorePath:IM}=re();Kf.exports=bM;async function bM(e,t){if(Yf.get(gM.LOGGING_AUDITLOG)===!1)return;let r=RM.join(IM(),e.schema.toString()),s=await xf.openEnvironment(r,e.table,!0),n=CM(e,t);if(!(n===void 0||n.hash_values.length===0)&&s!==void 0){xf.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),$f.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(bM,"writeTransaction");function CM(e,t){let r=$f.isEmpty(e.hdb_user)?void 0:e.hdb_user.username;if(e.operation===lo.INSERT)return new AM(e.records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===lo.UPDATE)return new pM(e.records,t.original_records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===lo.UPSERT)return new OM(e.records,t.original_records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===lo.DELETE)return new NM(t.deleted,t.original_records,r,t.txn_time,e.__origin)}a(CM,"createTransactionObject")});var $u=h((GZ,Qf)=>{"use strict";var wM=ja(),qZ=ti(),rn=T(),UM=ro(),LM=Xs().insertRecords,yM=X(),DM=require("path"),MM=g(),PM=io(),{getBaseSchemaPath:BM}=re(),vM=ai();Qf.exports=HM;async function HM(e){try{let{schema_table:t,attributes:r}=wM(e);UM(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 PM(e.hdb_auth_header,t,r),n=DM.join(BM(),e.schema.toString()),i=await yM.openEnvironment(n,e.table),o=await LM(i,t.hash_attribute,r,e.records,e[rn.CLUSTERING_FLAG]!==!0);try{await vM(e,o)}catch(c){MM.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(HM,"lmdbCreateRecords")});var Zf=h((FZ,Jf)=>{"use strict";var Wf=T(),qM=$u(),GM=ti(),FM=require("fs-extra"),VM=require("path"),{getBaseSchemaPath:kM}=re();Jf.exports=xM;async function xM(e){let t=[{name:e.schema,createddate:Date.now()}],r=new GM(Wf.SYSTEM_SCHEMA_NAME,Wf.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,void 0,t);await qM(r),await FM.mkdirp(VM.join(kM(),e.schema.toString()))}a(xM,"lmdbCreateSchema")});var zf=h((VZ,Xf)=>{"use strict";var Eo=class{constructor(t=[],r=[],s=void 0,n=[]){this.deleted=t,this.skipped=r,this.txn_time=s,this.original_records=n}};a(Eo,"DeleteRecordsResponseObject");Xf.exports=Eo});var Qu=h((YZ,tT)=>{"use strict";var jf=X(),Yu=Es(),Ku=Qe().LMDB_ERRORS_ENUM,$M=Ke(),eT=g(),kZ=b(),YM=require("lmdb"),KM=zf(),{OVERFLOW_MARKER:xZ,MAX_SEARCH_KEY_LENGTH:$Z}=$M;async function QM(e,t,r){if(Yu.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=jf.listDBIs(e);jf.initializeDBIs(e,t,s);let n=new KM,i,o=[],c=[];for(let E=0,d=r.length;E<d;E++)try{i=r[E];let S=e.dbis[t].get(i);if(!S){n.skipped.push(i);continue}let m=e.dbis[t].ifVersion(i,YM.IF_EXISTS,()=>{e.dbis[t].remove(i);for(let R=0;R<s.length;R++){let w=s[R];if(!S.hasOwnProperty(w)||w===t)continue;let U=e.dbis[w],B=S[w];if(B!=null)try{let j=Yu.getIndexedValues(B);if(j)for(let k=0,J=j.length;k<J;k++)U.remove(j[k],i)}catch{eT.warn(`cannot delete from attribute: ${w}, ${B}:${i}`)}}});o.push(m),c.push(i),n.original_records.push(S)}catch(S){eT.warn(S),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=Yu.getMicroTime(),n}catch(s){throw s}}a(QM,"deleteRecords");tT.exports={deleteRecords:QM}});var oi=h((KZ,sT)=>{"use strict";var sn=b(),WM=Qu(),JM=X(),ZM=require("path"),{getBaseSchemaPath:XM}=re(),zM=ai(),jM=g();sT.exports=eP;async function eP(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 rT([],[]);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=ZM.join(XM(),e.schema.toString()),i=await JM.openEnvironment(n,e.table),o=await WM.deleteRecords(i,s,e.hash_values);try{t===!0&&await zM(e,o)}catch(c){jM.error(`unable to write transaction due to ${c.message}`)}return rT(o.deleted,o.skipped,o.txn_time)}catch(n){throw n}}a(eP,"lmdbDeleteRecords");function rT(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(rT,"createDeleteResponse")});var Ju=h((WZ,nT)=>{"use strict";var tP=T(),QZ=Es();function Wu(e,t){let r=Object.create(null);if(t.length===1&&tP.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(Wu,"parseRow");function rP(e,t,r,s){let n=Wu(r,e);s.push(n)}a(rP,"searchAll");function sP(e,t,r,s){let n=Wu(r,e);s[t]=n}a(sP,"searchAllToMap");function nP(e,t,r){r[e]===void 0&&(r[e]=[]),r[e].push(t)}a(nP,"iterateDBI");function hs(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(hs,"pushResults");function iP(e,t,r,s,n,i){t.toString().endsWith(e)&&hs(t,r,s,n,i)}a(iP,"endsWith");function aP(e,t,r,s,n,i){t.toString().includes(e)&&hs(t,r,s,n,i)}a(aP,"contains");function oP(e,t,r,s,n,i){t>e&&hs(t,r,s,n,i)}a(oP,"greaterThanCompare");function cP(e,t,r,s,n,i){t>=e&&hs(t,r,s,n,i)}a(cP,"greaterThanEqualCompare");function _P(e,t,r,s,n,i){t<e&&hs(t,r,s,n,i)}a(_P,"lessThanCompare");function uP(e,t,r,s,n,i){t<=e&&hs(t,r,s,n,i)}a(uP,"lessThanEqualCompare");nT.exports={parseRow:Wu,searchAll:rP,searchAllToMap:sP,iterateDBI:nP,endsWith:iP,contains:aP,greaterThanCompare:oP,greaterThanEqualCompare:cP,lessThanCompare:_P,lessThanEqualCompare:uP,pushResults:hs}});var nn=h((XZ,uT)=>{"use strict";var Ut=X(),lP=g(),ft=Es(),kr=Ke(),_e=Qe().LMDB_ERRORS_ENUM,JZ=b(),EP=T(),Yt=Ju(),ZZ=require("lmdb"),{OVERFLOW_MARKER:iT,MAX_SEARCH_KEY_LENGTH:dP}=kr,ci={lazy:!0};function aT(e,t,r,s,n=!1,i=void 0,o=void 0){let c=Object.create(null),_=Ut.openDBI(e,r);_[kr.DBI_DEFINITION_NAME].is_hash_attribute&&(t=r);let u=Zu(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(aT,"iterateFullIndex");function _i(e,t,r,s,n,i=!1,o=void 0,c=void 0,_=!1,u=!1){let l=[[],[]],E=Ut.openDBI(e,r),d=Zu(e,t,r);E[kr.DBI_DEFINITION_NAME].is_hash_attribute&&(t=r);let S=i===!0?s:n,m=i===!0?n:s,R=i===!0?!_:!u,w=i===!0?u:_;for(let{key:U,value:B}of E.getRange({start:m,end:S,reverse:i,limit:o,offset:c,inclusiveEnd:R,exclusiveStart:w}))Yt.pushResults(d(U,B),B,l,t,r);return l}a(_i,"iterateRangeBetween");function Zu(e,t,r){let s;return function(n,i){if(typeof n=="string"&&n.endsWith(iT)){if(!s)if(t)s=Ut.openDBI(e,t);else{let c=Ut.listDBIs(e);for(let _=0,u=c.length;_<u&&(s=Ut.openDBI(e,c[_]),!s[kr.DBI_DEFINITION_NAME].is_hash_attribute);_++);}n=s.get(i,ci)[r]}return n}}a(Zu,"getOverflowCheck");function hP(e,t,r,s=!1,n=void 0,i=void 0){if(ft.validateEnv(e),t===void 0)throw new Error(_e.HASH_ATTRIBUTE_REQUIRED);ho(r),r=ui(e,r);let o=[],c=Ut.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}))Yt.searchAll(r,_,u,o);return o}a(hP,"searchAll");function SP(e,t,r,s=!1,n=void 0,i=void 0){if(ft.validateEnv(e),t===void 0)throw new Error(_e.HASH_ATTRIBUTE_REQUIRED);return ho(r),r=ui(e,r),aT(e,t,t,Yt.searchAllToMap.bind(null,r),s,n,i)}a(SP,"searchAllToMap");function fP(e,t,r=!1,s=void 0,n=void 0){if(ft.validateEnv(e),t===void 0)throw new Error(_e.ATTRIBUTE_REQUIRED);return aT(e,void 0,t,Yt.iterateDBI,r,s,n)}a(fP,"iterateDBI");function TP(e,t){if(ft.validateEnv(e),t===void 0)throw new Error(_e.HASH_ATTRIBUTE_REQUIRED);return Ut.statDBI(e,t).entryCount}a(TP,"countAll");function mP(e,t,r,s,n=!1,i=void 0,o=void 0){xr(e,r,s);let c=Ut.openDBI(e,r);s=ft.convertKeyValueToWrite(s);let _=[[],[]];if(c[kr.DBI_DEFINITION_NAME].is_hash_attribute){t=r;let u=c.get(s,ci);u!==void 0&&Yt.pushResults(s,u,_,t,r)}else for(let u of c.getValues(s,{reverse:n,limit:i,offset:o}))Yt.pushResults(s,u,_,t,r);return _}a(mP,"equals");function RP(e,t,r){return xr(e,t,r),Ut.openDBI(e,t).getValuesCount(r)}a(RP,"count");function AP(e,t,r,s,n=!1,i=void 0,o=void 0){xr(e,r,s);let c=[[],[]],_=Ut.openDBI(e,r);_[kr.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))Yt.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))Yt.pushResults(l,E,c,t,r);else if(u===!0)break;return c}a(AP,"startsWith");function pP(e,t,r,s,n=!1,i=void 0,o=void 0){return oT(e,t,r,s,n,i,o,!0)}a(pP,"endsWith");function oT(e,t,r,s,n=!1,i=void 0,o=void 0,c=!1){xr(e,r,s);let _=[[],[]],u=Ut.openDBI(e,r);u[kr.DBI_DEFINITION_NAME].is_hash_attribute&&(t=r);let l=Zu(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 S=d.toString();if(S.endsWith(iT))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?S.endsWith(s):S.includes(s))if(u[kr.DBI_DEFINITION_NAME].is_hash_attribute)E(d,d);else for(let m of u.getValues(d))E(d,m)}function E(d,S){if(o>0){o--;return}i!==0&&(Yt.pushResults(d,S,_,t,r),i--)}return a(E,"found_match"),_}a(oT,"contains");function OP(e,t,r,s,n=!1,i=void 0,o=void 0){xr(e,r,s);let c=typeof s,_;return c==="string"?_="\uFFFF":c==="number"?_=1/0:c==="boolean"&&(_=!0),_i(e,t,r,s,_,n,i,o,!0,!1)}a(OP,"greaterThan");function NP(e,t,r,s,n=!1,i=void 0,o=void 0){xr(e,r,s);let c=typeof s,_;return c==="string"?_="\uFFFF":c==="number"?_=1/0:c==="boolean"&&(_=!0),_i(e,t,r,s,_,n,i,o,!1,!1)}a(NP,"greaterThanEqual");function gP(e,t,r,s,n=!1,i=void 0,o=void 0){xr(e,r,s);let c=typeof s,_;return c==="string"?_="\0":c==="number"?_=-1/0:c==="boolean"&&(_=!1),_i(e,t,r,_,s,n,i,o,!1,!0)}a(gP,"lessThan");function IP(e,t,r,s,n=!1,i=void 0,o=void 0){xr(e,r,s);let c=typeof s,_;return c==="string"?_="\0":c==="number"?_=-1/0:c==="boolean"&&(_=!1),_i(e,t,r,_,s,n,i,o,!1,!1)}a(IP,"lessThanEqual");function bP(e,t,r,s,n,i=!1,o=void 0,c=void 0){if(ft.validateEnv(e),r===void 0)throw new Error(_e.ATTRIBUTE_REQUIRED);if(s===void 0)throw new Error(_e.START_VALUE_REQUIRED);if(n===void 0)throw new Error(_e.END_VALUE_REQUIRED);if(s=ft.convertKeyValueToWrite(s),n=ft.convertKeyValueToWrite(n),s>n)throw new Error(_e.END_VALUE_MUST_BE_GREATER_THAN_START_VALUE);return _i(e,t,r,s,n,i,o,c)}a(bP,"between");function CP(e,t,r,s){if(ft.validateEnv(e),t===void 0)throw new Error(_e.HASH_ATTRIBUTE_REQUIRED);if(ho(r),r=ui(e,r),s===void 0)throw new Error(_e.ID_REQUIRED);let n=null,i=e.dbis[t].get(s,r.length<3?ci:void 0);return i&&(n=Yt.parseRow(i,r)),n}a(CP,"searchByHash");function wP(e,t,r){if(ft.validateEnv(e),t===void 0)throw new Error(_e.HASH_ATTRIBUTE_REQUIRED);if(r===void 0)throw new Error(_e.ID_REQUIRED);let s=!0;return e.dbis[t].get(r,ci)===void 0&&(s=!1),s}a(wP,"checkHashExists");function UP(e,t,r,s,n=[]){_T(e,t,r,s,n);let i=cT(e,t,r,s,n);return Object.values(i)}a(UP,"batchSearchByHash");function LP(e,t,r,s,n=[]){return _T(e,t,r,s,n),cT(e,t,r,s,n)}a(LP,"batchSearchByHashToMap");function cT(e,t,r,s,n=[]){r=ui(e,r);let i=Object.create(null),o=r.length<3?ci: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=Yt.parseRow(u,r);i[_]=l}else n.push(_)}catch(u){throw lP.warn(u),u}}return i}a(cT,"batchHashSearch");function _T(e,t,r,s,n){if(ft.validateEnv(e),t===void 0)throw new Error(_e.HASH_ATTRIBUTE_REQUIRED);if(ho(r),!Array.isArray(s))throw s===void 0?new Error(_e.IDS_REQUIRED):new Error(_e.IDS_MUST_BE_ARRAY);Array.isArray(n)||(n=[])}a(_T,"initializeBatchSearchByHash");function ho(e){if(!Array.isArray(e))throw e===void 0?new Error(_e.FETCH_ATTRIBUTES_REQUIRED):new Error(_e.FETCH_ATTRIBUTES_MUST_BE_ARRAY)}a(ho,"validateFetchAttributes");function xr(e,t,r){if(ft.validateEnv(e),t===void 0)throw new Error(_e.ATTRIBUTE_REQUIRED);if(r===void 0)throw new Error(_e.SEARCH_VALUE_REQUIRED);if(r?.length>dP)throw new Error(_e.SEARCH_VALUE_TOO_LARGE)}a(xr,"validateComparisonFunctions");function ui(e,t){return t.length===1&&EP.SEARCH_WILDCARDS.indexOf(t[0])>=0&&(t=Ut.listDBIs(e)),t}a(ui,"setGetWholeRowAttributes");uT.exports={searchAll:hP,searchAllToMap:SP,count:RP,countAll:TP,equals:mP,startsWith:AP,endsWith:pP,contains:oT,searchByHash:CP,setGetWholeRowAttributes:ui,batchSearchByHash:UP,batchSearchByHashToMap:LP,checkHashExists:wP,iterateDBI:fP,greaterThan:OP,greaterThanEqual:NP,lessThan:gP,lessThanEqual:IP,between:bP}});var li=h((jZ,hT)=>{var lT=require("lodash"),ET=he(),Q=require("joi"),yP=b(),{hdb_schema_table:Kt,checkValidTable:dT}=Rr(),{handleHDBError:DP,hdb_errors:MP}=D(),{HTTP_STATUS_CODES:PP}=MP,zZ=Q.object({schema:Kt,table:Kt,hash_values:Q.array().min(1).items(Q.alternatives(Q.string(),Q.number())).required(),get_attributes:Q.array().min(1).items(Kt).required()}),BP=Q.object({schema:Kt,table:Kt,search_attribute:Kt,search_value:Q.any().required(),get_attributes:Q.array().min(1).items(Kt).required(),desc:Q.bool(),limit:Q.number().integer().min(1),offset:Q.number().integer().min(0)}),vP=Q.object({schema:Kt,table:Kt,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(Kt).required(),conditions:Q.array().min(1).items(Q.object({search_attribute:Kt,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()});hT.exports=function(e,t){let r=null;switch(t){case"value":r=ET.validateBySchema(e,BP);break;case"hashes":let i=function(o){n?n+=". "+o:n=o};var s=i;a(i,"addError");let n;i(dT("schema",e.schema)),i(dT("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=ET.validateBySchema(e,vP);break;default:throw new Error(`Error validating search, unknown type: ${t}`)}if(!r&&e.schema!=="system"){let n=yP.checkGlobalSchemaTable(e.schema,e.table);if(n)return DP(new Error,n,PP.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 _=lT.filter(c,u=>u!=="*"&&u.attribute!=="*"&&!lT.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=h((eX,ST)=>{"use strict";var HP=X(),qP=li(),GP=require("path"),{getBaseSchemaPath:FP}=re();ST.exports=VP;function VP(e){let t=qP(e,"hashes");if(t)throw t;let r=GP.join(FP(),e.schema.toString());return HP.openEnvironment(r,e.table)}a(VP,"initialize")});var zu=h((tX,fT)=>{"use strict";var kP=nn(),xP=Xu();fT.exports=$P;async function $P(e){try{let t=await xP(e),r=global.hdb_schema[e.schema][e.table];return kP.batchSearchByHashToMap(t,r.hash_attribute,e.get_attributes,e.hash_values)}catch(t){throw t}}a($P,"lmdbGetDataByHash")});var Ss=h((rX,TT)=>{"use strict";var So=class{constructor(t,r,s,n){this.schema=t,this.table=r,this.hash_values=s,this.get_attributes=n}};a(So,"SearchByHashObject");TT.exports=So});var RT=h((nX,mT)=>{"use strict";var sX=Ss(),YP=nn(),KP=Xu();mT.exports=QP;async function QP(e){try{let t=await KP(e),r=global.hdb_schema[e.schema][e.table];return YP.batchSearchByHash(t,r.hash_attribute,e.get_attributes,e.hash_values)}catch(t){throw t}}a(QP,"lmdbSearchByHash")});var Qt=h((iX,AT)=>{"use strict";var fo=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(fo,"SearchObject");AT.exports=fo});var To=h((aX,IT)=>{"use strict";var Je=nn(),WP=X(),JP=require("path"),ZP=b(),L=Ke(),fs=T(),{getBaseSchemaPath:XP}=re(),zP=ls(),pT=Qe().LMDB_ERRORS_ENUM,{compareKeys:an}=require("ordered-binary"),pr=fs.SEARCH_WILDCARDS;async function jP(e,t,r){let s;e.schema===fs.SYSTEM_SCHEMA_NAME?s=zP[e.table]:s=global.hdb_schema[e.schema][e.table];let n=gT(e,s.hash_attribute,r,t);return OT(e,n,s.hash_attribute,r)}a(jP,"prepSearch");async function OT(e,t,r,s){let n=JP.join(XP(),e.schema.toString()),i=await WP.openEnvironment(n,e.table),o=NT(i,e,t,r);if([L.SEARCH_TYPES.BATCH_SEARCH_BY_HASH,L.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP,L.SEARCH_TYPES.SEARCH_ALL,L.SEARCH_TYPES.SEARCH_ALL_TO_MAP].indexOf(t)>=0)return o;if(rB(e,r)===!1)return s===!0?tB(o):o[1];let _=o[0];return s===!0?Je.batchSearchByHashToMap(i,r,e.get_attributes,_):Je.batchSearchByHash(i,r,e.get_attributes,_)}a(OT,"executeSearch");function NT(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 L.SEARCH_TYPES.EQUALS:n=Je.equals(e,i,t.search_attribute,t.search_value,o,c,_);break;case L.SEARCH_TYPES.CONTAINS:n=Je.contains(e,i,t.search_attribute,t.search_value,o,c,_);break;case L.SEARCH_TYPES.ENDS_WITH:case L.SEARCH_TYPES._ENDS_WITH:n=Je.endsWith(e,i,t.search_attribute,t.search_value,o,c,_);break;case L.SEARCH_TYPES.STARTS_WITH:case L.SEARCH_TYPES._STARTS_WITH:n=Je.startsWith(e,i,t.search_attribute,t.search_value,o,c,_);break;case L.SEARCH_TYPES.BATCH_SEARCH_BY_HASH:return Je.batchSearchByHash(e,t.search_attribute,t.get_attributes,[t.search_value]);case L.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP:return Je.batchSearchByHashToMap(e,t.search_attribute,t.get_attributes,[t.search_value]);case L.SEARCH_TYPES.SEARCH_ALL:return Je.searchAll(e,s,t.get_attributes,o,c,_);case L.SEARCH_TYPES.SEARCH_ALL_TO_MAP:return Je.searchAllToMap(e,s,t.get_attributes,o,c,_);case L.SEARCH_TYPES.BETWEEN:n=Je.between(e,i,t.search_attribute,t.search_value,t.end_value,o,c,_);break;case L.SEARCH_TYPES.GREATER_THAN:case L.SEARCH_TYPES._GREATER_THAN:n=Je.greaterThan(e,i,t.search_attribute,t.search_value,o,c,_);break;case L.SEARCH_TYPES.GREATER_THAN_EQUAL:case L.SEARCH_TYPES._GREATER_THAN_EQUAL:n=Je.greaterThanEqual(e,i,t.search_attribute,t.search_value,o,c,_);break;case L.SEARCH_TYPES.LESS_THAN:case L.SEARCH_TYPES._LESS_THAN:n=Je.lessThan(e,i,t.search_attribute,t.search_value,o,c,_);break;case L.SEARCH_TYPES.LESS_THAN_EQUAL:case L.SEARCH_TYPES._LESS_THAN_EQUAL:n=Je.lessThanEqual(e,i,t.search_attribute,t.search_value,o,c,_);break;default:return Object.create(null)}return n}a(NT,"searchByType");function eB(e){let t=e.search_type,r=e.search_attribute,s=e.search_value;switch(t){case L.SEARCH_TYPES.EQUALS:return n=>n[r]===s;case L.SEARCH_TYPES.CONTAINS:return n=>typeof n[r]=="string"&&n[r].includes(s);case L.SEARCH_TYPES.ENDS_WITH:case L.SEARCH_TYPES._ENDS_WITH:return n=>typeof n[r]=="string"&&n[r].endsWith(s);case L.SEARCH_TYPES.STARTS_WITH:case L.SEARCH_TYPES._STARTS_WITH:return n=>typeof n[r]=="string"&&n[r].startsWith(s);case L.SEARCH_TYPES.BETWEEN:return n=>{let i=n[r];return an(i,s[0])>=0&&an(i,s[1])<=0};case L.SEARCH_TYPES.GREATER_THAN:case L.SEARCH_TYPES._GREATER_THAN:return n=>an(n[r],s)>0;case L.SEARCH_TYPES.GREATER_THAN_EQUAL:case L.SEARCH_TYPES._GREATER_THAN_EQUAL:return n=>an(n[r],s)>=0;case L.SEARCH_TYPES.LESS_THAN:case L.SEARCH_TYPES._LESS_THAN:return n=>an(n[r],s)<0;case L.SEARCH_TYPES.LESS_THAN_EQUAL:case L.SEARCH_TYPES._LESS_THAN_EQUAL:return n=>an(n[r],s)<=0;default:return Object.create(null)}}a(eB,"filterByType");function tB(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(tB,"createMapFromArrays");function rB(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(rB,"checkToFetchMore");function gT(e,t,r,s){if(ZP.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),pr.indexOf(n)>-1)return r===!0?L.SEARCH_TYPES.SEARCH_ALL_TO_MAP:L.SEARCH_TYPES.SEARCH_ALL;if(n.indexOf(pr[0])<0&&n.indexOf(pr[1])<0)return c===!0?r===!0?L.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP:L.SEARCH_TYPES.BATCH_SEARCH_BY_HASH:L.SEARCH_TYPES.EQUALS;if(pr.indexOf(i)>=0&&pr.indexOf(o)>=0)return e.search_value=e.search_value.slice(1,-1),L.SEARCH_TYPES.CONTAINS;if(pr.indexOf(i)>=0)return e.search_value=e.search_value.substr(1),L.SEARCH_TYPES.ENDS_WITH;if(pr.indexOf(o)>=0)return e.search_value=e.search_value.slice(0,-1),L.SEARCH_TYPES.STARTS_WITH;if(n.includes(pr[0])||n.includes(pr[1]))return L.SEARCH_TYPES.EQUALS;throw new Error(pT.UNKNOWN_SEARCH_TYPE)}else switch(s){case fs.VALUE_SEARCH_COMPARATORS.BETWEEN:return L.SEARCH_TYPES.BETWEEN;case fs.VALUE_SEARCH_COMPARATORS.GREATER:return L.SEARCH_TYPES.GREATER_THAN;case fs.VALUE_SEARCH_COMPARATORS.GREATER_OR_EQ:return L.SEARCH_TYPES.GREATER_THAN_EQUAL;case fs.VALUE_SEARCH_COMPARATORS.LESS:return L.SEARCH_TYPES.LESS_THAN;case fs.VALUE_SEARCH_COMPARATORS.LESS_OR_EQ:return L.SEARCH_TYPES.LESS_THAN_EQUAL;default:throw new Error(pT.UNKNOWN_SEARCH_TYPE)}}a(gT,"createSearchTypeFromSearchObject");IT.exports={executeSearch:OT,createSearchTypeFromSearchObject:gT,prepSearch:jP,searchByType:NT,filterByType:eB}});var CT=h((cX,bT)=>{"use strict";var oX=Qt(),sB=li(),nB=b(),iB=T(),aB=To();bT.exports=oB;async function oB(e,t){if(!nB.isEmpty(t)&&iB.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[t]===void 0)throw new Error(`Value search comparator - ${t} - is not valid`);let s=sB(e,"value");if(s)throw s;let n=!0;try{return await aB.prepSearch(e,t,n)}catch(i){throw i}}a(oB,"lmdbGetDataByValue")});var on=h((uX,wT)=>{"use strict";var _X=Qt(),cB=li(),_B=b(),uB=T(),lB=To();wT.exports=EB;async function EB(e,t){if(!_B.isEmpty(t)&&uB.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[t]===void 0)throw new Error(`Value search comparator - ${t} - is not valid`);let s=cB(e,"value");if(s)throw s;let n=!1;try{return await lB.prepSearch(e,t,n)}catch(i){throw i}}a(EB,"lmdbSearchByValue")});var LT=h((EX,UT)=>{"use strict";var lX=Ke(),mo=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(mo,"SearchByConditionsObject");var Ro=class{constructor(t,r,s){this.search_attribute=t,this.search_type=r,this.search_value=s}};a(Ro,"SearchCondition");var Ao=class{constructor(t,r){this.attribute=t,this.desc=r}};a(Ao,"SortAttribute");UT.exports={SearchByConditionsObject:mo,SearchCondition:Ro,SortAttribute:Ao}});var vT=h((hX,BT)=>{"use strict";var dX=LT().SearchByConditionsObject,dB=Qt(),hB=li(),ju=nn(),po=Ke(),PT=To(),SB=Ju(),yT=require("lodash"),{getBaseSchemaPath:fB}=re(),TB=require("path"),mB=X(),{handleHDBError:DT,hdb_errors:RB}=D(),{HTTP_STATUS_CODES:AB}=RB,pB=1e8,OB={lazy:!0};BT.exports=NB;async function NB(e){try{let t=hB(e,"conditions");if(t)throw DT(t,t.message,AB.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=TB.join(fB(),e.schema.toString()),s=await mB.openEnvironment(r,e.table),n=global.hdb_schema[e.schema][e.table],i=yT.sortBy(e.conditions,o=>{if(o.estimated_count===void 0){let c=o.search_type;c===po.SEARCH_TYPES.EQUALS?o.estimated_count=ju.count(s,o.search_attribute,o.search_value):c===po.SEARCH_TYPES.CONTAINS||c===po.SEARCH_TYPES.ENDS_WITH?o.estimated_count=1/0:o.estimated_count=pB}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(PT.filterByType),u=_.length,l=[],E=ju.setGetWholeRowAttributes(s,e.get_attributes),d=e.offset>-1?e.offset:0,S=e.limit>-1?e.limit:1/0;e:for(let m of o){let R=c.get(m,OB);for(let w=0;w<u;w++)if(!_[w](R))continue e;if(d>0){d--;continue}if(S<=0)break;S--,l.push(SB.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=yT.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 DT(t)}}a(NB,"lmdbSearchByConditions");async function MT(e,t,r,s){let n=new dB(t.schema,t.table,void 0,void 0,s,t.get_attributes),i=r.search_type;return n.search_attribute=r.search_attribute,i===po.SEARCH_TYPES.BETWEEN?(n.search_value=r.search_value[0],n.end_value=r.search_value[1]):n.search_value=r.search_value,PT.searchByType(e,n,i,s)}a(MT,"executeConditionSearch")});var Ei=h((SX,HT)=>{"use strict";var gB=T().OPERATIONS_ENUM,Oo=class{constructor(t,r,s,n=void 0){this.operation=gB.DELETE,this.schema=t,this.table=r,this.hash_values=s,this.__origin=n}};a(Oo,"DeleteObject");HT.exports=Oo});var el=h((fX,qT)=>{"use strict";var No=class{constructor(t,r,s){this.schema=t,this.table=r,this.attribute=s}};a(No,"DropAttributeObject");qT.exports=No});var rl=h((mX,GT)=>{"use strict";var IB=Qt(),bB=Ei(),TX=el(),tr=T(),CB=b(),tl=X(),wB=ls(),UB=on(),LB=oi(),{getBaseSchemaPath:yB}=re(),DB=require("path");GT.exports=MB;async function MB(e,t=!0){let r;e.schema===tr.SYSTEM_SCHEMA_NAME?r=wB[e.table]:r=global.hdb_schema[e.schema][e.table];let s=await BB(e),n=DB.join(yB(),e.schema.toString()),i=await tl.openEnvironment(n,e.table);return t===!0&&await PB(e,i,r.hash_attribute),tl.dropDBI(i,e.attribute),s}a(MB,"lmdbDropAttribute");async function PB(e,t,r){let s=tl.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(PB,"removeAttributeFromAllObjects");async function BB(e){let t=new IB(tr.SYSTEM_SCHEMA_NAME,tr.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,tr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_TABLE_KEY,`${e.schema}.${e.table}`,void 0,[tr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY,tr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ATTRIBUTE_KEY]),s=(await UB(t)).filter(o=>o[tr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ATTRIBUTE_KEY]===e.attribute);if(CB.isEmptyOrZeroLength(s))throw new Error(`Attribute '${e.attribute}' was not found in '${e.schema}.${e.table}'`);let n=s.map(o=>o[tr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),i=new bB(tr.SYSTEM_SCHEMA_NAME,tr.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,n);return LB(i)}a(BB,"dropAttributeFromSystem")});var xT=h((RX,kT)=>{"use strict";var vB=rl(),HB=el(),FT=b(),VT=g(),qB=Qe().LMDB_ERRORS_ENUM;kT.exports=GB;async function GB(e){if(FT.isEmpty(global.hdb_schema[e.schema])||FT.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 HB(e.schema,e.table,r);try{await vB(n,!1)}catch(i){i.message!==qB.DBI_DOES_NOT_EXIST&&VT.error(`unable to drop attribute ${e.schema}.${e.table}.${r}:`+i)}}}catch(s){throw VT.error(`Error dropping attribute ${r}`),s}}a(GB,"lmdbDropAllAttributes")});var sl=h((pX,zT)=>{"use strict";var WT=Qt(),JT=Ei(),ZT=on(),XT=oi(),AX=xT(),ct=T(),$T=b(),YT=X(),{getBaseSchemaPath:FB,getTransactionAuditStorePath:VB}=re(),KT=require("path"),QT=g();zT.exports=kB;async function kB(e){try{if($T.isEmpty(global.hdb_schema[e.schema])||$T.isEmpty(global.hdb_schema[e.schema][e.table]))throw new Error(`unknown schema:${e.schema} and table ${e.table}`);await xB(e),await $B(e);let t=KT.join(FB(),e.schema.toString());try{await YT.deleteEnvironment(t,e.table)}catch(r){if(r.message==="invalid environment")QT.warn(`cannot delete environment for ${e.schema}.${e.table}, environment not found`);else throw r}try{let r=KT.join(VB(),e.schema.toString());await YT.deleteEnvironment(r,e.table,!0)}catch(r){if(r.message==="invalid environment")QT.warn(`cannot delete environment for ${e.schema}.${e.table}, environment not found`);else throw r}}catch(t){throw t}}a(kB,"lmdbDropTable");async function xB(e){let t=new WT(ct.SYSTEM_SCHEMA_NAME,ct.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,ct.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_TABLE_KEY,`${e.schema}.${e.table}`,void 0,[ct.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),r=await ZT(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 JT(ct.SYSTEM_SCHEMA_NAME,ct.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,s);await XT(n)}a(xB,"deleteAttributesFromSystem");async function $B(e){let t=new WT(ct.SYSTEM_SCHEMA_NAME,ct.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,ct.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY,e.table,void 0,[ct.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY,ct.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_KEY,ct.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),r,s;try{r=await ZT(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 JT(ct.SYSTEM_SCHEMA_NAME,ct.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,[s.id]);try{await XT(n)}catch(i){throw i}}a($B,"dropTableFromSystem")});var em=h((NX,jT)=>{"use strict";var YB=require("fs-extra"),KB=Qt(),QB=Ss(),WB=Ei(),JB=sl(),ZB=oi(),XB=zu(),zB=on(),Or=T(),OX=b(),jB=require("path"),{getBaseSchemaPath:ev}=re(),{handleHDBError:tv,hdb_errors:rv}=D(),{HDB_ERROR_MSGS:sv,HTTP_STATUS_CODES:nv}=rv;jT.exports=iv;async function iv(e){let t;try{t=await av(e.schema);let r=new KB(Or.SYSTEM_SCHEMA_NAME,Or.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,Or.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_KEY,t,void 0,[Or.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY]),s=await zB(r);for(let o=0;o<s.length;o++){let c={schema:t,table:s[o].name};try{await JB(c)}catch(_){if(_.message!=="invalid environment")throw _}}let n=new WB(Or.SYSTEM_SCHEMA_NAME,Or.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,[t]);await ZB(n);let i=jB.join(ev(),t.toString());await YB.remove(i)}catch(r){throw r}}a(iv,"lmdbDropSchema");async function av(e){let t=new QB(Or.SYSTEM_SCHEMA_NAME,Or.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,[e],[Or.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY]),r,s;try{r=await XB(t)}catch(n){throw n}for(let n in r)r[n].name===e&&(s=e);if(!s)throw tv(new Error,sv.SCHEMA_NOT_FOUND(e),nv.NOT_FOUND,void 0,void 0,!0);return s}a(av,"validateDropSchema")});var nl=h((gX,tm)=>{"use strict";var go=class{constructor(t,r,s){this.schema=t,this.table=r,this.hash_attribute=s}};a(go,"CreateTableObject");tm.exports=go});var sm=h((bX,rm)=>{"use strict";var ov=require("path"),cv=require("fs-extra"),Io=X(),{getTransactionAuditStorePath:_v}=re(),il=Ke(),IX=nl();rm.exports=uv;async function uv(e){let t;try{let r=ov.join(_v(),e.schema.toString());await cv.mkdirp(r),t=await Io.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{Io.createDBI(t,il.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,!1,!0),Io.createDBI(t,il.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE,!0,!1),Io.createDBI(t,il.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(uv,"createTransactionsAuditEnvironment")});var om=h((CX,am)=>{"use strict";var al=T(),nm=X(),lv=Xs(),Ev=require("path"),{getSystemSchemaPath:dv,getBaseSchemaPath:hv}=re(),Sv=ls(),fv=za(),ol=Xa(),Tv=g(),mv=sm(),_l=Sv.hdb_table,im=[];for(let e=0;e<_l.attributes.length;e++)im.push(_l.attributes[e].attribute);am.exports=Rv;async function Rv(e,t){let r=Ev.join(hv(),t.schema.toString()),s=new ol(t.schema,t.table,al.TIME_STAMP_NAMES_ENUM.CREATED_TIME,void 0,!0),n=new ol(t.schema,t.table,al.TIME_STAMP_NAMES_ENUM.UPDATED_TIME,void 0,!0),i=new ol(t.schema,t.table,t.hash_attribute,void 0,!1,!0);try{if(await nm.createEnvironment(r,t.table),e!==void 0){let o=await nm.openEnvironment(dv(),al.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME);await lv.insertRecords(o,_l.hash_attribute,im,[e]),await cl(s),await cl(n),await cl(i)}await mv(t)}catch(o){throw o}}a(Rv,"lmdbCreateTable");async function cl(e){try{await fv(e)}catch(t){Tv.warn(`failed to create attribute ${e.attribute} due to ${t.message}`)}}a(cl,"createAttribute")});var _m=h((wX,cm)=>{"use strict";var Av=ja(),pv=ro(),Ov=io(),cn=T(),Nv=Xs().updateRecords,gv=X(),Iv=require("path"),{getBaseSchemaPath:bv}=re(),Cv=ai(),wv=g();cm.exports=Uv;async function Uv(e){try{let{schema_table:t,attributes:r}=Av(e);pv(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 Ov(e.hdb_auth_header,t,r),n=Iv.join(bv(),e.schema.toString()),i=await gv.openEnvironment(n,e.table),o=await Nv(i,t.hash_attribute,r,e.records,e[cn.CLUSTERING_FLAG]!==!0);try{await Cv(e,o)}catch(c){wv.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(Uv,"lmdbUpdateRecords")});var lm=h((UX,um)=>{"use strict";var Lv=T().OPERATIONS_ENUM,bo=class{constructor(t,r,s,n=void 0){this.operation=Lv.UPSERT,this.schema=t,this.table=r,this.records=s,this.__origin=n}};a(bo,"UpsertObject");um.exports=bo});var dm=h((yX,Em)=>{"use strict";var LX=lm(),yv=ja(),Dv=ro(),Mv=io(),_n=T(),Pv=Xs().upsertRecords,Bv=X(),vv=require("path"),{getBaseSchemaPath:Hv}=re(),qv=ai(),Gv=g(),{handleHDBError:Fv,hdb_errors:Vv}=D();Em.exports=kv;async function kv(e){let t;try{t=yv(e)}catch(_){throw Fv(_,_.message,Vv.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0)}let{schema_table:r,attributes:s}=t;Dv(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 Mv(e.hdb_auth_header,r,s),i=vv.join(Hv(),e.schema.toString()),o=await Bv.openEnvironment(i,e.table),c=await Pv(o,r.hash_attribute,s,e.records,e[_n.CLUSTERING_FLAG]!==!0);try{await qv(e,c)}catch(_){Gv.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(kv,"lmdbUpsertRecords")});var Rm=h((DX,mm)=>{"use strict";var xv=Qt(),hm=b(),Sm=g(),$v=on(),fm=T(),Yv=Qu().deleteRecords,Kv=X(),Qv=require("path"),{getBaseSchemaPath:Wv}=re(),{promisify:Jv}=require("util"),Zv=Jv(setTimeout),Tm=1e4,Xv=10;mm.exports=zv;async function zv(e){let t=global.hdb_schema[e.schema][e.table].hash_attribute;if(hm.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 xv(e.schema,e.table,fm.TIME_STAMP_NAMES_ENUM.CREATED_TIME,r,void 0,[t]);s=await $v(n,fm.VALUE_SEARCH_COMPARATORS.LESS)}catch(n){throw Sm.error(`Error searching for date: ${e.date} in schema: ${e.schema} table: ${e.table}`),n}return hm.isEmptyOrZeroLength(s)?(Sm.trace("No records found to delete"),{message:"No records found to delete"}):await jv(e,s,t)}a(zv,"lmdbDeleteRecordsBefore");async function jv(e,t,r){let s=Qv.join(Wv(),e.schema.toString()),n=await Kv.openEnvironment(s,e.table),i={message:"",deleted_hashes:[],skipped_hashes:[]};for(let o=0,c=t.length;o<c;o+=Tm){let _=t.slice(o,o+Tm),u=[];for(let l=0,E=_.length;l<E;l++)u.push(_[l][r]);try{let l=await Yv(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 Zv(Xv)}return i.message=`${i.deleted_hashes.length} of ${i.deleted_hashes.length+i.skipped_hashes.length} records successfully deleted`,i}a(jv,"chunkDeletes")});var pm=h((MX,Am)=>{"use strict";var Co=class{constructor(t,r,s){this.schema=t,this.table=r,this.timestamp=s}};a(Co,"DeleteBeforeObject");Am.exports=Co});var Nm=h((PX,Om)=>{"use strict";var wo=class{constructor(t=void 0,r=void 0,s=0){this.start_timestamp=t,this.end_timestamp=r,this.transactions_deleted=s}};a(wo,"DeleteAuditLogsBeforeResults");Om.exports=wo});var bm=h((vX,Im)=>{"use strict";var ul=X(),{getTransactionAuditStorePath:eH}=re(),BX=pm(),tH=require("path"),di=Ke(),rH=b(),gm=Nm(),sH=require("util").promisify,nH=sH(setTimeout),iH=1e4,aH=100;Im.exports=oH;async function oH(e){let t=tH.join(eH(),e.schema),r=await ul.openEnvironment(t,e.table,!0),s=ul.listDBIs(r);ul.initializeDBIs(r,di.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,s);let n,i=new gm;do n=await cH(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 nH(aH);while(n.transactions_deleted>0);return i}a(oH,"deleteAuditLogsBefore");async function cH(e,t){let r=new gm;try{let s=e.dbis[di.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[di.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME];rH.isEmpty(c)||(n=e.dbis[di.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].remove(c,i));for(let _=0;_<o.hash_values.length;_++)n=e.dbis[di.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE].remove(o.hash_values[_],i);if(r.transactions_deleted++,r.end_timestamp=i,r.transactions_deleted>iH)break}return await n,r}catch(s){throw s}}a(cH,"deleteTransactions")});var Mm=h((HX,Dm)=>{"use strict";var ll=X(),un=Ke(),Cm=Es(),El=T(),wm=b(),{getTransactionAuditStorePath:_H}=re(),uH=require("path"),lH=nn(),Uo=en(),EH=g();Dm.exports=dH;async function dH(e){let t=uH.join(_H(),e.schema),r=await ll.openEnvironment(t,e.table,!0),s=ll.listDBIs(r);ll.initializeDBIs(r,un.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,s);let n;switch(e.search_type){case El.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.TIMESTAMP:return Um(r,e.search_values);case El.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.HASH_VALUE:return n=global.hdb_schema[e.schema][e.table].hash_attribute,SH(r,e.search_values,n);case El.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.USERNAME:return hH(r,e.search_values);default:return Um(r)}}a(dH,"readAuditLog");function Um(e,t=[0,Cm.getMicroTime()]){wm.isEmpty(t[0])&&(t[0]=0),wm.isEmpty(t[1])&&(t[1]=Cm.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 Uo,i);r.push(o)}return r}catch(s){throw s}}a(Um,"searchTransactionsByTimestamp");function hH(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,ym(e,i))}return Object.fromEntries(r)}a(hH,"searchTransactionsByUsername");function SH(e,t,r){let s=new Map;for(let c=0,_=t.length;c<_;c++){let u=t[c],l=lH.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 S=l[0][E],m=Number(S);s.has(m)?s.get(m).push(u.toString()):s.set(m,[u.toString()])}}let n=Array.from(s.keys()),i=ym(e,n),o=new Map;for(let c=0;c<i.length;c++){let _=i[c],u=_.timestamp,l=s.get(u);Lm(_,"records",r,l,o),Lm(_,"original_records",r,l,o)}return Object.fromEntries(o)}a(SH,"searchTransactionsByHashValues");function Lm(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 Uo(e.operation,e.user_name,i,void 0);E[t]=[c],u.push(E)}}else{let u=new Uo(e.operation,e.user_name,i,void 0);u[t]=[c],n.set(_,[u])}}}a(Lm,"loopRecords");function ym(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 Uo,i);r.push(o)}}catch(i){EH.warn(i)}return r}catch(s){throw s}}a(ym,"batchSearchTransactions")});var Bm=h((qX,Pm)=>{"use strict";var fH=require("path"),{getBaseSchemaPath:TH}=re(),mH=X();Pm.exports={writeTransaction:RH};async function RH(e,t,r){let s=fH.join(TH(),e);return(await mH.openEnvironment(s,t)).transaction(r)}a(RH,"writeTransaction")});var Hm=h((GX,vm)=>{"use strict";var AH=require("path"),{getBaseSchemaPath:pH}=re(),OH=X();vm.exports={flush:NH};async function NH(e,t){let r=AH.join(pH(),e.toString());return(await OH.openEnvironment(r,t.toString())).flushed}a(NH,"flush")});var Gm=h((FX,qm)=>{"use strict";var pe=g(),{handleHDBError:gH}=D(),IH=Ou(),bH=za(),CH=$u(),wH=Zf(),UH=oi(),LH=zu(),yH=RT(),DH=CT(),MH=on(),PH=vT(),BH=em(),vH=om(),HH=_m(),qH=dm(),GH=Rm(),FH=bm(),VH=sl(),kH=rl(),xH=Mm(),$H=Bm(),YH=Hm(),Lo=class extends IH{async searchByConditions(t){try{return PH(t)}catch(r){throw pe.error(r),r}}async getDataByHash(t){try{return await LH(t)}catch(r){throw pe.error(r),r}}async searchByHash(t){try{return await yH(t)}catch(r){throw pe.error(r),r}}async getDataByValue(t,r){try{return await DH(t,r)}catch(s){throw pe.error(s),s}}async searchByValue(t){try{return await MH(t)}catch(r){throw pe.error(r),r}}async createSchema(t){try{return await wH(t)}catch(r){throw pe.error(r),r}}async dropSchema(t){try{return await BH(t)}catch(r){throw pe.error(r),r}}async createTable(t,r){try{return await vH(t,r)}catch(s){throw pe.error(s),s}}async dropTable(t){try{return await VH(t)}catch(r){throw pe.error(r),r}}async createAttribute(t){try{return await bH(t)}catch(r){throw pe.error(r),r}}async createRecords(t){try{return await CH(t)}catch(r){throw pe.error(r),r}}async updateRecords(t){try{return await HH(t)}catch(r){throw pe.error(r),r}}async upsertRecords(t){try{return await qH(t)}catch(r){throw gH(r,null,null,pe.ERR,r)}}async deleteRecords(t){try{return await UH(t)}catch(r){throw pe.error(r),r}}async deleteRecordsBefore(t){try{return await GH(t)}catch(r){throw pe.error(r),r}}async dropAttribute(t){try{return await kH(t)}catch(r){throw pe.error(r),r}}async deleteAuditLogsBefore(t){try{return await FH(t)}catch(r){throw pe.error(r),r}}async readAuditLog(t){try{return await xH(t)}catch(r){throw pe.error(r),r}}writeTransaction(t,r,s){return $H.writeTransaction(t,r,s)}flush(t,r){return YH.flush(t,r)}};a(Lo,"LMDBBridge");qm.exports=Lo});var Nr=h((VX,Vm)=>{"use strict";var KH=Gm(),QH=Ou(),WH=V();WH.initSync();var Fm;function JH(){return Fm instanceof QH?Fm:new KH}a(JH,"getBridge");Vm.exports=JH()});var Ym=h((kX,$m)=>{"use strict";var km=require("lodash"),hi=require("mathjs"),ZH=require("jsonata"),xm=b();$m.exports={distinct_array:e=>Array.isArray(e)&&e.length>1?km.uniqWith(e,km.isEqual):e,searchJSON:XH,mad:Si.bind(null,hi.mad),mean:Si.bind(null,hi.mean),mode:Si.bind(null,hi.mode),prod:Si.bind(null,hi.prod),median:Si.bind(null,hi.median)};function Si(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(Si,"aggregateFunction");function XH(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(xm.isEmpty(this.__ala__.res)&&(this.__ala__.res={}),xm.isEmpty(this.__ala__.res[r])){let s=ZH(e);this.__ala__.res[r]=s}return this.__ala__.res[r].evaluate(t)}a(XH,"searchJSON")});var Qm=h((xX,Km)=>{"use strict";var Se=require("moment"),dl="YYYY-MM-DDTHH:mm:ss.SSSZZ";Se.suppressDeprecationWarnings=!0;Km.exports={current_date:()=>Se().utc().format("YYYY-MM-DD"),current_time:()=>Se().utc().format("HH:mm:ss.SSS"),extract:(e,t)=>{switch(t.toLowerCase()){case"year":return Se(e).utc().format("YYYY");case"month":return Se(e).utc().format("MM");case"day":return Se(e).utc().format("DD");case"hour":return Se(e).utc().format("HH");case"minute":return Se(e).utc().format("mm");case"second":return Se(e).utc().format("ss");case"millisecond":return Se(e).utc().format("SSS");default:break}},date:e=>Se(e).utc().format(dl),date_format:(e,t)=>Se(e).utc().format(t),date_add:(e,t,r)=>Se(e).utc().add(t,r).valueOf(),date_sub:(e,t,r)=>Se(e).utc().subtract(t,r).valueOf(),date_diff:(e,t,r)=>{let s=Se(e).utc(),n=Se(t).utc();return r?s.diff(n,r,!0):s.diff(n)},now:()=>Se().utc().valueOf(),get_server_time:()=>Se().format(dl),offset_utc:(e,t)=>Se(e).utc().utcOffset(t).format(dl)}});var Xm=h(($X,Zm)=>{"use strict";var zH=require("@turf/area"),jH=require("@turf/length"),eq=require("@turf/circle"),tq=require("@turf/difference"),rq=require("@turf/distance"),sq=require("@turf/boolean-contains"),nq=require("@turf/boolean-equal"),iq=require("@turf/boolean-disjoint"),aq=require("@turf/helpers"),Wm=T(),x=b();Zm.exports={geoArea:oq,geoLength:cq,geoCircle:_q,geoDifference:uq,geoDistance:Jm,geoNear:lq,geoContains:Eq,geoEqual:dq,geoCrosses:hq,geoConvert:Sq};var hl="geo1 is required",Sl="geo2 is required";function oq(e){if(x.isEmpty(e))throw new Error("geoJSON is required");return typeof e=="string"&&(e=x.autoCast(e)),zH.default(e)}a(oq,"geoArea");function cq(e,t){if(x.isEmpty(e))throw new Error("geoJSON is required");return typeof e=="string"&&(e=x.autoCast(e)),jH.default(e,{units:t||"kilometers"})}a(cq,"geoLength");function _q(e,t,r){if(x.isEmpty(e))throw new Error("point is required");if(x.isEmpty(t))throw new Error("radius is required");return typeof e=="string"&&(e=x.autoCast(e)),eq.default(e,t,{units:r||"kilometers"})}a(_q,"geoCircle");function uq(e,t){if(x.isEmpty(e))throw new Error("poly1 is required");if(x.isEmpty(t))throw new Error("poly2 is required");return typeof e=="string"&&(e=x.autoCast(e)),typeof t=="string"&&(t=x.autoCast(t)),tq(e,t)}a(uq,"geoDifference");function Jm(e,t,r){if(x.isEmpty(e))throw new Error("point1 is required");if(x.isEmpty(t))throw new Error("point2 is required");return typeof e=="string"&&(e=x.autoCast(e)),typeof t=="string"&&(t=x.autoCast(t)),rq.default(e,t,{units:r||"kilometers"})}a(Jm,"geoDistance");function lq(e,t,r,s){if(x.isEmpty(e))throw new Error("point1 is required");if(x.isEmpty(t))throw new Error("point2 is required");if(x.isEmpty(r))throw new Error("distance is required");if(typeof e=="string"&&(e=x.autoCast(e)),typeof t=="string"&&(t=x.autoCast(t)),isNaN(r))throw new Error("distance must be a number");return Jm(e,t,s)<=r}a(lq,"geoNear");function Eq(e,t){if(x.isEmpty(e))throw new Error(hl);if(x.isEmpty(e))throw new Error(Sl);return typeof e=="string"&&(e=x.autoCast(e)),typeof t=="string"&&(t=x.autoCast(t)),sq.default(e,t)}a(Eq,"geoContains");function dq(e,t){if(x.isEmpty(e))throw new Error(hl);if(x.isEmpty(e))throw new Error(Sl);return typeof e=="string"&&(e=x.autoCast(e)),typeof t=="string"&&(t=x.autoCast(t)),nq.default(e,t)}a(dq,"geoEqual");function hq(e,t){if(x.isEmpty(e))throw new Error(hl);if(x.isEmpty(e))throw new Error(Sl);return typeof e=="string"&&(e=x.autoCast(e)),typeof t=="string"&&(t=x.autoCast(t)),!iq.default(e,t)}a(hq,"geoCrosses");function Sq(e,t,r){if(x.isEmptyOrZeroLength(e))throw new Error("coordinates is required");if(x.isEmpty(t))throw new Error("geo_type is required");if(x.isEmpty(Wm.GEO_CONVERSION_ENUM[t]))throw new Error(`geo_type of ${t} is invalid please use one of the following types: ${Object.keys(Wm.GEO_CONVERSION_ENUM).join(",")}`);return aq[t](e,r)}a(Sq,"geoConvert")});var yo=h((YX,zm)=>{var Ts=Ym(),Tt=Qm(),rr=Xm();zm.exports=e=>{e.aggr.mad=e.aggr.MAD=Ts.mad,e.aggr.mean=e.aggr.MEAN=Ts.mean,e.aggr.mode=e.aggr.MODE=Ts.mode,e.aggr.prod=e.aggr.PROD=Ts.prod,e.aggr.median=e.aggr.MEDIAN=Ts.median,e.fn.distinct_array=e.fn.DISTINCT_ARRAY=Ts.distinct_array,e.fn.search_json=e.fn.SEARCH_JSON=Ts.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=rr.geoArea,e.fn.geocircle=e.fn.GEOCIRCLE=e.fn.geoCircle=rr.geoCircle,e.fn.geocontains=e.fn.GEOCONTAINS=e.fn.geoContains=rr.geoContains,e.fn.geoconvert=e.fn.GEOCONVERT=e.fn.geoConvert=rr.geoConvert,e.fn.geocrosses=e.fn.GEOCROSSES=e.fn.geoCrosses=rr.geoCrosses,e.fn.geodifference=e.fn.GEODIFFERENCE=e.fn.geoDifference=rr.geoDifference,e.fn.geodistance=e.fn.GEODISTANCE=e.fn.geoDistance=rr.geoDistance,e.fn.geoequal=e.fn.GEOEQUAL=e.fn.geoEqual=rr.geoEqual,e.fn.geolength=e.fn.GEOLENGTH=e.fn.geoLength=rr.geoLength,e.fn.geonear=e.fn.GEONEAR=e.fn.geoNear=rr.geoNear}});var tR=h((KX,eR)=>{"use strict";var fi=require("lodash"),Pe=require("alasql");Pe.options.cache=!1;var fq=yo(),jm=require("clone"),Do=require("recursive-iterator"),v=g(),q=b(),ln=Nr(),Tq=T(),{hdb_errors:mq}=D(),Rq="IS NULL",Ti="There was a problem performing this search. Please check the logs and try again.";fq(Pe);var Mo=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(Ti)}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(Ti)}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(Ti)}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(Ti)}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(Ti)}}_getColumns(){let t=new Do(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(jm(r)))}_getTables(){let t=[];this.all_table_attributes.forEach(r=>{t.push(r.table)}),this.tables=fi.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 Do(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 Pe.yy.LogicValue({value:s}):r.right instanceof Pe.yy.StringValue&&!q.isEmpty(s)&&q.autoCasterIsNumberCheck(s.toString())&&(r.right=new Pe.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 Pe.yy.LogicValue({value:i}):s instanceof Pe.yy.StringValue&&q.autoCasterIsNumberCheck(i.toString())&&(r.right[n]=new Pe.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 Do(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(Tq.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&&fi.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 Pe.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(jm(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(Rq)>-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=fi.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 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 S in d)this.data[i].__merged_data[S]?this._updateMergedAttribute(i,S,n.attribute,d[S][n.attribute]):(this.data[i].__merged_data[S]=[...s[i]],this._updateMergedAttribute(i,S,n.attribute,d[S][n.attribute]),this._setMergedHashAttribute(i,q.autoCast(S)))}))}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 S=l[E];c.search_attribute=S.attribute,c.search_value=S.search_value;let m=await ln.getDataByValue(c,S.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 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,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 Pe.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 Pe.yy.Column;n.columnid=s.as,n.columnid_orig=s.as_orig,t.expression=n}else{t.initial_select_column=Object.assign(new Pe.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 Pe.yy.FuncValue:new Pe.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(S=>{S.joinmode&&S.joinmode!=="INNER"&&(this.has_outer_join=!0),n.push(S.table);let m=S.joinmode+" JOIN ? AS "+(S.as?S.as:S.table.tableid);S.on&&(m+=" ON "+S.on.toString()),i.push(m),t.push(Object.values(this.data[`${S.table.databaseid_orig}_${S.table.as?S.table.as_orig:S.table.tableid_orig}`].__merged_data))});let o=[],c={};n.forEach(S=>{let m=this.data[`${S.databaseid_orig}_${S.as?S.as_orig:S.tableid_orig}`].__hash_name,R=S.as?S.as_orig:S.tableid_orig;o.push({key:`'${R}.${m}'`,schema:S.databaseid_orig,table:S.as?S.as_orig:S.tableid_orig,keys:new Set}),r.push(`${S.as?S.as:S.tableid}.\`${m}\` AS "${R}.${m}"`),c[S.as?S.as_orig:S.tableid_orig]=this.data[`${S.databaseid_orig}_${S.as?S.as_orig:S.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(S=>{S.is_func?r.push(S.initial_select_column.toString()):S.initial_select_column.tableid?r.push(`${S.initial_select_column.tableid}.${S.initial_select_column.columnid} AS ${S.expression.columnid}`):r.push(`${S.initial_select_column.columnid} AS ${S.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 S=`SELECT ${r.join(", ")} FROM ${i.join(" ")} ${_} ${u} ${l} ${E}`,m=this._convertColumnsToIndexes(S,n);d=await Pe.promise(m,t),t=null}catch(S){throw v.error("Error thrown from AlaSQL in SQLSearch class method processJoins."),v.error(S),new Error("There was a problem processing the data.")}if(d&&d.length>0){for(let S=0,m=d.length;S<m;S++){let R=d[S];o.forEach(w=>{R[w.key]!==null&&R[w.key]!==void 0&&w.keys.add(R[w.key])})}o.forEach(S=>{let m=Object.keys(this.data[`${S.schema}_${S.table}`].__merged_data),R=fi.difference(m,[...S.keys].map(w=>w.toString()));for(let w=0,U=R.length;w<U;w++){let B=R[w];delete this.data[`${S.schema}_${S.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 Do(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=fi.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],S=_[d];for(let m=0;m<u;m++){let R=n.columns[m],w=S[R]===void 0?null:S[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 Pe.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(mq.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(Mo,"SQLSearch");eR.exports=Mo});var mt=h((QX,sR)=>{"use strict";var Aq=CS();sR.exports={searchByConditions:gq,searchByHash:Iq,searchByValue:bq,search:Cq};var fl=Nr(),rR=require("util"),pq=rR.callbackify(fl.searchByHash),Oq=rR.callbackify(fl.searchByValue),Nq=tR();async function gq(e){return fl.searchByConditions(e)}a(gq,"searchByConditions");function Iq(e,t){try{pq(e,(r,s)=>{if(r){t(r);return}t(null,s)})}catch(r){return t(r)}}a(Iq,"searchByHash");function bq(e,t){try{e.hasOwnProperty("desc")===!0&&(e.reverse=e.desc),Oq(e,(r,s)=>{if(r){t(r);return}t(null,s)})}catch(r){return t(r)}}a(bq,"searchByValue");function Cq(e,t){try{let r=new Aq(e);r.validate(),new Nq(r.statement,r.attributes).search().then(n=>{t(null,n)}).catch(n=>{t(n,null)})}catch(r){return t(r)}}a(Cq,"search")});var $r=h((WX,oR)=>{"use strict";var mi=require("crypto"),iR="aes-256-cbc",wq=32,Uq=16,Tl=64,aR=32,Lq=Tl+aR,nR=new Map;oR.exports={encrypt:yq,decrypt:Dq,createNatsTableStreamName:Mq};function yq(e){let t=mi.randomBytes(wq),r=mi.randomBytes(Uq),s=mi.createCipheriv(iR,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(yq,"encrypt");function Dq(e){let t=e.substr(0,Tl),r=e.substr(Tl,aR),s=e.substr(Lq,e.length),n=Buffer.from(r,"hex"),i=Buffer.from(s,"hex"),o=mi.createDecipheriv(iR,Buffer.from(t,"hex"),n),c=o.update(i);return c=Buffer.concat([c,o.final()]),c.toString()}a(Dq,"decrypt");function Mq(e,t){let r=`${e}.${t}`,s=nR.get(r);return s||(s=mi.createHash("md5").update(`${e}.${t}`).digest("hex"),nR.set(r,s)),s}a(Mq,"createNatsTableStreamName")});var ms=h((JX,hR)=>{"use strict";var _R=mt(),Yr=g(),uR=Wa(),Pq=require("lodash"),Bq=require("path"),vq=$r(),ml=b(),{promisify:lR}=require("util"),ee=T(),{handleHDBError:Po,hdb_errors:Hq}=D(),{HDB_ERROR_MSGS:Bo,HTTP_STATUS_CODES:ER}=Hq,qq=V();qq.initSync();var cR=X(),Gq=re(),Ri=lR(_R.searchByValue),Fq=lR(_R.searchByHash),En="name",dR="hash_attribute",Rl="schema",Vq="schema_table",kq="attribute";hR.exports={describeAll:xq,describeTable:vo,describeSchema:Yq};async function xq(e){try{let t=ml.isEmptyOrZeroLength(e),r,s;t||(r=e.hdb_user.role.permission,s=r.super_user||r.cluster_user);let n={schema:ee.SYSTEM_SCHEMA_NAME,table:ee.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,search_attribute:En,search_value:ee.WILDCARD_SEARCH_VALUE,get_attributes:[En]},i=await Ri(n);if(ml.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:ee.SYSTEM_SCHEMA_NAME,table:ee.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,search_attribute:ee.ID_ATTRIBUTE_STRING,search_value:ee.WILDCARD_SEARCH_VALUE,get_attributes:[dR,ee.ID_ATTRIBUTE_STRING,En,Rl]},u=await Ri(_),l=[];for(let d of u)try{let S;if(t||s)S=await vo({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;S=await vo({schema:d.schema,table:d.name},m)}S&&l.push(S)}catch(S){Yr.error(S)}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 Yr.error("Got an error in describeAll"),Yr.error(t),Po(new Error,Bo.DESCRIBE_ALL_ERR)}}a(xq,"describeAll");async function vo(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=uR.describe_table(e);if(o)throw o;if(r===ee.SYSTEM_SCHEMA_NAME)return global.hdb_schema[ee.SYSTEM_SCHEMA_NAME][s];let c={schema:ee.SYSTEM_SCHEMA_NAME,table:ee.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,hash_attribute:ee.SYSTEM_TABLE_HASH_ATTRIBUTES.TABLE_TABLE_HASH_ATTRIBUTE,search_attribute:En,search_value:s,hash_values:[],get_attributes:[ee.WILDCARD_SEARCH_VALUE]},_=await Ri(c);if(!_||_.length===0)throw Po(new Error,Bo.TABLE_NOT_FOUND(e.schema,e.table),ER.NOT_FOUND);for await(let u of _)try{if(u.schema!==r)continue;if(i=u,!i.hash_attribute)throw Po(new Error,Bo.INVALID_TABLE_ERR(i));let l={schema:ee.SYSTEM_SCHEMA_NAME,table:ee.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,hash_attribute:ee.SYSTEM_TABLE_HASH_ATTRIBUTES.ATTRIBUTE_TABLE_HASH_ATTRIBUTE,search_attribute:Vq,search_value:r+"."+s,get_attributes:[kq]},E=await Ri(l);E=Pq.uniqBy(E,d=>d.attribute),n&&n.length>0&&(E=$q(n)),i.attributes=E,i.clustering_stream_name=vq.createNatsTableStreamName(u.schema,u.name);try{let d=Bq.join(Gq.getBaseSchemaPath(),i.schema.toString()),S=await cR.openEnvironment(d,i.name),m=cR.statDBI(S,i.hash_attribute);i.record_count=m.entryCount}catch(d){Yr.warn(`unable to stat table dbi due to ${d}`)}}catch(l){Yr.error(`There was an error getting attributes for table '${u.name}'`),Yr.error(l)}return i}a(vo,"descTable");function $q(e){return e.reduce((t,r)=>(r.describe&&t.push({attribute:r.attribute_name}),t),[])}a($q,"getAttrsByPerms");async function Yq(e){let t=uR.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:ee.SYSTEM_SCHEMA_NAME,table:ee.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,hash_attribute:ee.SYSTEM_TABLE_HASH_ATTRIBUTES.TABLE_TABLE_HASH_ATTRIBUTE,search_attribute:Rl,search_value:s,hash_values:[],get_attributes:[dR,ee.ID_ATTRIBUTE_STRING,En,Rl]},i=await Ri(n);if(i&&i.length<1){let o={schema:ee.SYSTEM_SCHEMA_NAME,table:ee.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,hash_attribute:ee.SYSTEM_TABLE_HASH_ATTRIBUTES.SCHEMA_TABLE_HASH_ATTRIBUTE,hash_values:[s],get_attributes:[En]},c=await Fq(o);if(c&&c.length<1)throw Po(new Error,Bo.SCHEMA_NOT_FOUND(e.schema),ER.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]),ml.isEmpty(_)||_.describe){let u=await vo({schema:e.schema,table:c.name},_?_.attribute_permissions:null);u&&(o[u.name]=u)}}catch(_){Yr.error(`Error describing schema table '${e.schema}.${c}'`),Yr.error(_)}})),o}}a(Yq,"describeSchema")});var Kr=h((zX,RR)=>{var ZX=require("async"),dn=ls(),XX=g(),{callbackify:TR,promisify:Kq}=require("util");RR.exports={setSchemaDataToGlobal:SR,getTableSchema:Jq,getSystemSchema:Xq,setSchemaDataToGlobalAsync:Kq(SR)};var mR=ms(),Qq=TR(mR.describeAll),Wq=TR(mR.describeTable);function SR(e){Qq(null,(t,r)=>{if(t){e(t);return}r.system||(r.system=dn),global.hdb_schema=r,e(null,null)})}a(SR,"setSchemaDataToGlobal");function fR(e,t){return e==="system"?dn[t]:global.hdb_schema[e][t]}a(fR,"returnSchema");function Jq(e,t,r){!global.hdb_schema||!global.hdb_schema[e]||!global.hdb_schema[e][t]?Zq(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,fR(e,t))}):r(null,fR(e,t))}a(Jq,"getTableSchema");function Zq(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}Wq(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(Zq,"setTableDataToGlobal");function Xq(){return dn}a(Xq,"getSystemSchema")});var yt=h((jX,OR)=>{"use strict";var qo=Fu(),Lt=b(),zq=require("util"),Go=Nr(),jq=Kr(),Al=g(),{handleHDBError:Qr,hdb_errors:eG}=D(),{HTTP_STATUS_CODES:Rs}=eG,tG=zq.promisify(jq.getTableSchema),rG="updated",AR="inserted",pR="upserted";OR.exports={insert:nG,update:iG,upsert:aG,validation:sG,flush:oG};async function sG(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 tG(e.schema,e.table),r=qo(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 Al.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 Al.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(sG,"validation");async function nG(e){if(e.operation!=="insert")throw new Error("invalid operation, must be insert");let t=qo(e);if(t)throw Qr(new Error,t.message,Rs.BAD_REQUEST);let r=Lt.checkSchemaTableExist(e.schema,e.table);if(r)throw Qr(new Error,r,Rs.BAD_REQUEST);try{let s=await Go.createRecords(e);return Ho(AR,s.written_hashes,e,s.skipped_hashes,s.new_attributes,s.txn_time)}catch(s){throw s}}a(nG,"insertData");async function iG(e){if(e.operation!=="update")throw new Error("invalid operation, must be update");let t=qo(e);if(t)throw Qr(new Error,t.message,Rs.BAD_REQUEST);let r=Lt.checkSchemaTableExist(e.schema,e.table);if(r)throw Qr(new Error,r,Rs.BAD_REQUEST);try{let s=await Go.updateRecords(e);return Lt.isEmpty(s.existing_rows)?Ho(rG,s.written_hashes,e,s.skipped_hashes,s.new_attributes,s.txn_time):Ho(s.update_action,[],e,s.hashes,void 0,s.txn_time)}catch(s){throw s}}a(iG,"updateData");async function aG(e){if(e.operation!=="upsert")throw Qr(new Error,"invalid operation, must be upsert",Rs.INTERNAL_SERVER_ERROR);let t=qo(e);if(t)throw Qr(new Error,t.message,Rs.BAD_REQUEST);let r=Lt.checkSchemaTableExist(e.schema,e.table);if(r)throw Qr(new Error,r,Rs.BAD_REQUEST);try{let s=await Go.upsertRecords(e);return Ho(pR,s.written_hashes,e,[],s.new_attributes,s.txn_time)}catch(s){let n=`There was an error during an upsert op: ${s}`;throw Qr(s,null,null,Al.ERR,n)}}a(aG,"upsertData");function Ho(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===AR?(o.inserted_hashes=t,o.skipped_hashes=s,o):e===pR?(o.upserted_hashes=t,o):(o.update_hashes=t,o.skipped_hashes=s,o)}a(Ho,"returnObject");function oG(e){return Go.flush(e.schema,e.table)}a(oG,"flush")});var Ol=h((e3,IR)=>{var cG=he(),pl=require("joi"),{hdb_schema_table:NR}=Rr(),gR={schema:NR,table:NR},_G={date:pl.date().iso().required()},uG={timestamp:pl.date().timestamp().required().messages({"date.format":"'timestamp' is invalid"})};IR.exports=function(e,t){let r=t==="timestamp"?{...gR,...uG}:{...gR,..._G},s=pl.object(r);return cG.validateBySchema(e,s)}});var UR=h((t3,wR)=>{var lG=he(),bR=require("joi"),{hdb_schema_table:CR}=Rr(),EG=bR.object({schema:CR,table:CR,hash_values:bR.array().required()});wR.exports=function(e){return lG.validateBySchema(e,EG)}});var yR=h((r3,LR)=>{"use strict";var Fo=class{constructor(t,r,s,n,i){this.operation=t,this.schema=r,this.table=s,this.hash_attribute=n,this.records=i}};a(Fo,"InsertObject");var Vo=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(Vo,"NoSQLSeachObject");var ko=class{constructor(){this.message=void 0,this.deleted_hashes=[],this.skipped_hashes=[]}};a(ko,"DeleteResponseObject");LR.exports={InsertObject:Fo,NoSQLSeachObject:Vo,DeleteResponseObject:ko}});var ps=h((s3,vR)=>{"use strict";var MR=Ol(),dG=UR(),xo=b(),DR=require("moment"),PR=g(),{promisify:hG,callbackify:SG}=require("util"),As=T(),fG=Kr(),Nl=hG(fG.getTableSchema),gl=Nr(),{DeleteResponseObject:TG}=yR(),{handleHDBError:Wr,hdb_errors:mG}=D(),{HDB_ERROR_MSGS:$o,HTTP_STATUS_CODES:Jr}=mG,RG="records successfully deleted",AG=SG(BR);vR.exports={delete:AG,deleteRecord:BR,deleteFilesBefore:pG,deleteAuditLogsBefore:OG};async function pG(e){let t=MR(e,"date");if(t)throw Wr(t,t.message,Jr.BAD_REQUEST,void 0,void 0,!0);if(!DR(e.date,DR.ISO_8601).isValid())throw Wr(new Error,$o.INVALID_DATE,Jr.BAD_REQUEST,As.LOG_LEVELS.ERROR,$o.INVALID_DATE,!0);let s=xo.checkSchemaTableExist(e.schema,e.table);if(s)throw Wr(new Error,s,Jr.NOT_FOUND,As.LOG_LEVELS.ERROR,s,!0);try{let n=await gl.deleteRecordsBefore(e);if(await Nl(e.schema,e.table),PR.info(`Finished deleting files before ${e.date}`),n&&n.message)return n.message}catch(n){throw n}}a(pG,"deleteFilesBefore");async function OG(e){let t=MR(e,"timestamp");if(t)throw Wr(t,t.message,Jr.BAD_REQUEST,void 0,void 0,!0);if(isNaN(e.timestamp))throw Wr(new Error,$o.INVALID_VALUE("Timestamp"),Jr.BAD_REQUEST,As.LOG_LEVELS.ERROR,$o.INVALID_VALUE("Timestamp"),!0);let r=xo.checkSchemaTableExist(e.schema,e.table);if(r)throw Wr(new Error,r,Jr.NOT_FOUND,As.LOG_LEVELS.ERROR,r,!0);try{let s=await gl.deleteAuditLogsBefore(e);return await Nl(e.schema,e.table),PR.info(`Finished deleting audit logs before ${e.timestamp}`),s}catch(s){throw s}}a(OG,"deleteAuditLogsBefore");async function BR(e){let t=dG(e);if(t)throw Wr(t,t.message,Jr.BAD_REQUEST,void 0,void 0,!0);let r=xo.checkSchemaTableExist(e.schema,e.table);if(r)throw Wr(new Error,r,Jr.NOT_FOUND,As.LOG_LEVELS.ERROR,r,!0);try{await Nl(e.schema,e.table);let s=await gl.deleteRecords(e);return xo.isEmptyOrZeroLength(s.message)&&(s.message=`${s.deleted_hashes.length} of ${e.hash_values.length} ${RG}`),s}catch(s){if(s.message===As.SEARCH_NOT_FOUND_MESSAGE){let n=new TG;return n.message=As.SEARCH_NOT_FOUND_MESSAGE,n.skipped_hashes=e.hash_values.length,n.deleted_hashes=0,n}throw s}}a(BR,"deleteRecord")});var Yo=h((n3,GR)=>{var NG=require("crypto"),HR=9;function gG(e){let t=bG(HR),r=qR(e+t);return t+r}a(gG,"createHash");function IG(e,t){let r=e.substr(0,HR),s=r+qR(t+r);return e===s}a(IG,"validateHash");function bG(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(bG,"generateSalt");function qR(e){return NG.createHash("md5").update(e).digest("hex")}a(qR,"md5");GR.exports={hash:gG,validate:IG}});var VR=h((i3,FR)=>{var Il=he(),Ze={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 CG(e){return Ze.password.presence=!0,Ze.username.presence=!0,Ze.role.presence=!0,Ze.active.presence=!0,Il.validateObject(e,Ze)}a(CG,"addUserValidation");function wG(e){return Ze.password.presence=!1,Ze.username.presence=!0,Ze.role.presence=!1,Ze.active.presence=!1,Il.validateObject(e,Ze)}a(wG,"alterUserValidation");function UG(e){return Ze.password.presence=!1,Ze.username.presence=!0,Ze.role.presence=!1,Ze.active.presence=!1,Il.validateObject(e,Ze)}a(UG,"dropUserValidation");FR.exports={addUserValidation:CG,alterUserValidation:wG,dropUserValidation:UG}});var fe=h((o3,xR)=>{"use strict";var{platform:a3}=require("os"),LG="nats-server.zip",bl="nats-server",yG=process.platform==="win32"?`${bl}.exe`:bl,Cl="HDB",DG=/^[^\s.,*>]+$/,kR="__request__",MG=a(e=>`${e}.${kR}`,"REQUEST_SUBJECT"),PG={HUB_SERVER:"hub.json",LEAF_SERVER:"leaf.json"},BG={HUB:"hub.pid",LEAF:"leaf.pid"},vG={HUB:"-hub",LEAF:"-leaf",ADMIN:"-admin"},HG={stream_name:"__HARPERDB_WORK_QUEUE__",durable_name:"HDB_WORK_QUEUE",deliver_group:Cl,deliver_subject:"__HDB__.WORKQUEUE"},qG={stream_name:"__HARPERDB_SCHEMA_QUEUE__",durable_name:"HDB_SCHEMA_QUEUE",deliver_group:Cl,deliver_subject:"HDB.SCHEMAQUEUE"},GG={stream_name:"__HARPERDB_USER_QUEUE__",durable_name:"HDB_USER_QUEUE",deliver_group:Cl,deliver_subject:"HDB.USERQUEUE"},FG={SUCCESS:"success",ERROR:"error"},VG={OPEN:"open",CLOSED:"closed",NO_RESPONDERS:"NoResponders",TIMEOUT:"Timeout"},kG={TXN:"txn",MSGID:"msgid"};xR.exports={NATS_SERVER_ZIP:LG,NATS_SERVER_NAME:bl,NATS_BINARY_NAME:yG,PID_FILES:BG,NATS_CONFIG_FILES:PG,SERVER_SUFFIX:vG,WORK_QUEUE_CONSUMER_NAMES:HG,SCHEMA_QUEUE_CONSUMER_NAMES:qG,USER_QUEUE_CONSUMER_NAMES:GG,NATS_TERM_CONSTRAINTS_RX:DG,REQUEST_SUFFIX:kR,UPDATE_REMOTE_RESPONSE_STATUSES:FG,CLUSTER_STATUS_STATUSES:VG,REQUEST_SUBJECT:MG,SUBJECT_PREFIXES:kG}});var YR=h((c3,$R)=>{"use strict";var Zr=T(),Ai=class{constructor(t=0,r=Zr.STORAGE_TYPES_ENUM.LMDB,s=Zr.LICENSE_VALUES.API_CALL_DEFAULT,n=Zr.RAM_ALLOCATION_ENUM.DEFAULT,i=Zr.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(Ai,"BaseLicense");var Ko=class extends Ai{constructor(t=0,r=Zr.STORAGE_TYPES_ENUM.LMDB,s=Zr.LICENSE_VALUES.API_CALL_DEFAULT,n=Zr.RAM_ALLOCATION_ENUM.DEFAULT,i=Zr.LICENSE_VALUES.VERSION_DEFAULT,o,c=!1){super(t,r,s,n,i,o),this.enterprise=c}};a(Ko,"ExtendedLicense");$R.exports={BaseLicense:Ai,ExtendedLicense:Ko}});var pi=h((_3,XR)=>{"use strict";var Sn=require("fs-extra"),KR=Yo(),QR=require("crypto"),xG=require("moment"),$G=require("uuid").v4,Xe=g(),Ul=require("path"),YG=b(),Rt=T(),KG=YR().ExtendedLicense,hn="invalid license key format",QG="061183",WG="mofi25",JG="aes-256-cbc",ZG=16,XG=32,WR=V();WR.initSync();var wl;XR.exports={validateLicense:JR,generateFingerPrint:jG,licenseSearch:ZR,getLicense:rF};function Ll(){return Ul.join(WR.getHdbBasePath(),Rt.LICENSE_KEY_DIR_NAME,Rt.LICENSE_FILE_NAME)}a(Ll,"getLicenseDirPath");function zG(){let e=Ll();return Ul.join(e,Rt.LICENSE_FILE_NAME)}a(zG,"getLicenseFilePath");function yl(){let e=Ll();return Ul.join(e,Rt.REG_KEY_FILE_NAME)}a(yl,"getFingerPrintFilePath");async function jG(){let e=yl();try{return await Sn.readFile(e,"utf8")}catch(t){if(t.code==="ENOENT")return await eF();throw Xe.error(`Error writing fingerprint file to ${e}`),Xe.error(t),new Error("There was an error generating the fingerprint")}}a(jG,"generateFingerPrint");async function eF(){let e=$G(),t=KR.hash(e),r=yl();try{await Sn.mkdirp(Ll()),await Sn.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(eF,"writeFingerprint");function JR(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 Xe.error("empty license key passed to validate."),r;let s=yl(),n=!1;try{n=Sn.statSync(s)}catch(i){Xe.error(i)}if(n){let i;try{i=Sn.readFileSync(s,"utf8")}catch{Xe.error("error validating this machine in the license"),r.valid_machine=!1;return}let o=e.split(WG),c=o[1];c=Buffer.concat([Buffer.from(c)],ZG);let _=Buffer.concat([Buffer.from(i)],XG),u=QR.createDecipheriv(JG,_,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 S=tF(o[0],i);if(S)l=S;else throw r.valid_license=!1,r.valid_machine=!1,console.error(hn),Xe.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),Xe.error(hn),new Error(hn)}else r.exp_date=l;r.exp_date<xG().valueOf()&&(r.valid_date=!1),KR.validate(o[1],`${QG}${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(JR,"validateLicense");function tF(e,t){try{let r=QR.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(tF,"checkOldLicense");function ZR(){let e=new KG;e.api_call=0;let t=[];try{t=Sn.readFileSync(zG(),"utf-8").split(Rt.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(YG.isEmptyOrZeroLength(s))continue;let n=JSON.parse(s),i=JR(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=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),wl=e,e}a(ZR,"licenseSearch");async function rF(){return wl||await ZR(),wl}a(rF,"getLicense")});var gr=h((u3,lA)=>{"use strict";var tA="username is required",rA="nothing to update, must supply active, role or password to update",sA="password cannot be an empty string",nA="If role is specified, it cannot be empty.",iA="active must be true or false";lA.exports={addUser:uF,alterUser:lF,dropUser:dF,userInfo:hF,listUsers:Wo,listUsersExternal:SF,setUsersToGlobal:Oi,findAndValidateUser:mF,getClusterUser:RF,USERNAME_REQUIRED:tA,ALTERUSER_NOTHING_TO_UPDATE:rA,EMPTY_PASSWORD:sA,EMPTY_ROLE:nA,ACTIVE_BOOLEAN:iA};var aA=yt(),sF=ps(),Ml=Yo(),oA=VR(),cA=mt(),Pl=js(),we=b(),_A=require("validate.js"),H=g(),{promisify:Bl}=require("util"),vl=$r(),Os=T(),zR=fe(),nF=Tr(),Hl=V(),iF=pi(),aF=ls(),{handleHDBError:sr,hdb_errors:oF}=D(),{HTTP_STATUS_CODES:nr,AUTHENTICATION_ERROR_MSGS:Dl,HDB_ERROR_MSGS:fn}=oF,{UserEventMsg:ql}=Vr(),jR=require("lodash"),uA={username:!0,active:!0,role:!0,password:!0},eA=new Map,Qo=Bl(cA.searchByValue),cF=Bl(cA.searchByHash),_F=Bl(sF.delete);async function uF(e){let t=_A.cleanAttributes(e,uA),r=oA.addUserValidation(t);if(r)throw sr(new Error,r.message,nr.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 Qo(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 sr(new Error,fn.ROLE_NAME_NOT_FOUND(t.role),nr.NOT_FOUND,void 0,void 0,!0);if(n.length>1)throw sr(new Error,fn.DUP_ROLES_FOUND(t.role),nr.CONFLICT,void 0,void 0,!0);n[0].permission.cluster_user===!0&&(t.hash=vl.encrypt(t.password)),t.password=Ml.hash(t.password),t.role=n[0].id;let i={operation:"insert",schema:"system",table:"hdb_user",records:[t]},o;try{o=await aA.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 sr(new Error,fn.USER_ALREADY_EXISTS(t.username),nr.CONFLICT,void 0,void 0,!0);let c=Object.assign({},t);c.role=n[0];let _={user:null};return _.user=c,we.sendTransactionToSocketCluster(Os.INTERNAL_SC_CHANNELS.ADD_USER,_,Hl.get(Os.HDB_SETTINGS_NAMES.CLUSTERING_NODE_NAME_KEY)),Pl.signalUserChange(new ql(process.pid)),`${c.username} successfully added`}a(uF,"addUser");async function lF(e){let t=_A.cleanAttributes(e,uA);if(we.isEmptyOrZeroLength(t.username))throw new Error(tA);if(we.isEmptyOrZeroLength(t.password)&&we.isEmptyOrZeroLength(t.role)&&we.isEmptyOrZeroLength(t.active))throw new Error(rA);if(!we.isEmpty(t.password)&&we.isEmptyOrZeroLength(t.password.trim()))throw new Error(sA);if(!we.isEmpty(t.active)&&!we.isBoolean(t.active))throw new Error(iA);let r=EF(t.username);if(!we.isEmpty(t.password)&&!we.isEmptyOrZeroLength(t.password.trim())&&(r&&(t.hash=vl.encrypt(t.password)),t.password=Ml.hash(t.password)),t.role==="")throw new Error(nA);if(t.role){let o={schema:"system",table:"hdb_role",search_attribute:"role",search_value:t.role,get_attributes:["*"]},c;try{c=await Qo(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(_),sr(new Error,_,nr.NOT_FOUND,void 0,void 0,!0)}if(c.length>1){let _=fn.ALTER_USER_DUP_ROLES(t.role);throw H.error(_),sr(new Error,_,nr.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 aA.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,we.sendTransactionToSocketCluster(Os.INTERNAL_SC_CHANNELS.ALTER_USER,i,Hl.get(Os.HDB_SETTINGS_NAMES.CLUSTERING_NODE_NAME_KEY)),Pl.signalUserChange(new ql(process.pid)),n}a(lF,"alterUser");function EF(e){let t=!1,r=global.hdb_users.get(e);return r&&r.role.permission.cluster_user===!0&&(t=!0),t}a(EF,"isClusterUser");async function dF(e){try{let t=oA.dropUserValidation(e);if(t)throw new Error(t);let r={table:"hdb_user",schema:"system",hash_values:[e.username]};if(we.isEmpty(global.hdb_users.get(e.username)))throw sr(new Error,fn.USER_NOT_EXIST(e.username),nr.NOT_FOUND,void 0,void 0,!0);let s;try{s=await _F(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,we.sendTransactionToSocketCluster(Os.INTERNAL_SC_CHANNELS.DROP_USER,n,Hl.get(Os.HDB_SETTINGS_NAMES.CLUSTERING_NODE_NAME_KEY)),Pl.signalUserChange(new ql(process.pid)),`${e.username} successfully deleted`}catch(t){throw t}}a(dF,"dropUser");async function hF(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 cF(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(hF,"userInfo");async function SF(){let e;try{e=await Wo()}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(SF,"listUsersExternal");async function Wo(){try{let e={schema:"system",table:"hdb_role",search_value:"*",search_attribute:"role",get_attributes:["*"]},t;try{t=jR.cloneDeep(await Qo(e))}catch(r){throw H.error("Got an error searching for roles."),H.error(r),r}if(!we.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=jR.cloneDeep(await Qo(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],fF(c.role),i.set(c.username,c)}return(await iF.getLicense()).enterprise?i:TF(i)}}catch(e){throw H.error("got an error listing users"),H.error(e),we.errorizeMessage(e)}return null}a(Wo,"listUsers");function fF(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(aF)){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(fF,"appendSystemTablesToRole");function TF(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(TF,"nonEnterpriseFilter");async function Oi(){try{let e=await Wo();global.hdb_users=e}catch(e){throw H.error(e),e}}a(Oi,"setUsersToGlobal");async function mF(e,t,r=!0){global.hdb_users||await Oi();let s=global.hdb_users.get(e);if(!s)throw sr(new Error,Dl.GENERIC_AUTH_FAIL,nr.UNAUTHORIZED,void 0,void 0,!0);if(s&&!s.active)throw sr(new Error,Dl.USER_INACTIVE,nr.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(eA.get(t)===s.password)return n;if(Ml.validate(s.password,t))eA.set(t,s.password);else throw sr(new Error,Dl.GENERIC_AUTH_FAIL,nr.UNAUTHORIZED,void 0,void 0,!0)}return n}a(mF,"findAndValidateUser");async function RF(){let e=await Wo(),t=nF.getConfigFromFile(Os.CONFIG_PARAMS.CLUSTERING_USER),r=e.get(t);if(!we.isEmpty(r))return r.decrypt_hash=vl.decrypt(r.hash),r.uri_encoded_d_hash=encodeURIComponent(r.decrypt_hash),r.uri_encoded_name=encodeURIComponent(r.username),r.sys_name=r.username+zR.SERVER_SUFFIX.ADMIN,r.sys_name_encoded=r.uri_encoded_name+zR.SERVER_SUFFIX.ADMIN,r}a(RF,"getClusterUser")});var SA=h((l3,hA)=>{"use strict";var AF=require("node-ipc").IPC,EA=b(),dA=T(),Ir=g(),{IPC_ERRORS:Tn}=Qe(),pF=require("os"),Jo=class{constructor(t,r){this.ipc=new AF,this.server_name=dA.HDB_IPC_SERVER,this.ipc.config.retry=pF.platform()=="win32"?6e5:100,this.ipc.config.id=dA.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",()=>{Ir.info(`IPC client ${this.ipc.config.id} connected to ${this.server_name}`)}),this.ipc.of[this.server_name].on("disconnect",()=>{Ir.info(`IPC client ${this.ipc.config.id} disconnected from ${this.server_name}`)}),this.ipc.of[this.server_name].on("error",r=>{r.code==="ECONNREFUSED"&&Ir.warn("Error connecting to HDB IPC server. Confirm that the server is running."),Ir.warn(`Error with IPC client ${this.ipc.config.id}`),Ir.warn(r)});for(let[r,s]of Object.entries(t))this.addEventHandler(r,s)}emitToServer(t){if(typeof t!="object")throw Ir.warn(Tn.INVALID_IPC_DATA_TYPE),new Error(Tn.INVALID_IPC_DATA_TYPE);if(EA.isEmpty(t.type))throw Ir.warn(Tn.MISSING_TYPE),new Error(Tn.MISSING_TYPE);if(EA.isEmpty(t.message))throw Ir.warn(Tn.MISSING_MSG),new Error(Tn.MISSING_MSG);Ir.trace(`IPC client ${this.ipc.config.id} emitting`,t),this.ipc.of[this.server_name].emit("message",t)}};a(Jo,"IPCClient");hA.exports=Jo});var mA=h((E3,TA)=>{"use strict";var Gl=X(),OF=g(),fA=Qe().LMDB_ERRORS_ENUM;TA.exports=NF;async function NF(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 Gl.closeEnvironment(global.lmdb_map[o])}catch(c){if(c.message!==fA.ENV_REQUIRED)throw c}}break;case"drop_table":let s=`${e.schema}.${e.table}`,n=`txn.${s}`;try{await Gl.closeEnvironment(global.lmdb_map[s]),await Gl.closeEnvironment(global.lmdb_map[n])}catch(i){if(i.message!==fA.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){OF.error(t)}}a(NF,"cleanLMDBMap")});var NA=h((d3,OA)=>{"use strict";var Ns=g(),Zo=T(),gF=mA(),RA=Kr(),IF=ms(),bF=gr(),{validateEvent:pA}=Vr(),CF={[Zo.IPC_EVENT_TYPES.SCHEMA]:wF,[Zo.IPC_EVENT_TYPES.USER]:LF};async function wF(e){let t=pA(e);if(t){Ns.error(t);return}Ns.trace(`IPC schemaHandler ${Zo.HDB_IPC_CLIENT_PREFIX}${process.pid} received schema event:`,e),await gF(e.message),await UF(e.message)}a(wF,"schemaHandler");async function UF(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 IF.describeTable({schema:e.schema,table:e.table});break;default:RA.setSchemaDataToGlobal(AA);break}else RA.setSchemaDataToGlobal(AA)}catch(t){Ns.error(t)}}a(UF,"syncSchemaMetadata");function AA(e){e&&Ns.error(e)}a(AA,"handleErrorCallback");async function LF(e){try{let t=pA(e);if(t){Ns.error(t);return}Ns.trace(`IPC userHandler ${Zo.HDB_IPC_CLIENT_PREFIX}${process.pid} received user event:`,e),await bF.setUsersToGlobal()}catch(t){Ns.error(t)}}a(LF,"userHandler");OA.exports=CF});var bA=h((h3,IA)=>{"use strict";var gA=require("fs"),Ni=V();Ni.initSync();var{CONFIG_PARAMS:Xo}=T(),yF=1024*1024*1024;function DF(e){let t=Ni.get(Xo.CUSTOMFUNCTIONS_NETWORK_TIMEOUT),r=Ni.get(Xo.CUSTOMFUNCTIONS_NETWORK_KEEPALIVETIMEOUT),s={bodyLimit:yF,connectionTimeout:t,keepAliveTimeout:r,ignoreTrailingSlash:!0};if(e){let n=Ni.get(Xo.CUSTOMFUNCTIONS_TLS_PRIVATEKEY),i=Ni.get(Xo.CUSTOMFUNCTIONS_TLS_CERTIFICATE);s.https={key:gA.readFileSync(`${n}`),cert:gA.readFileSync(`${i}`)}}return s}a(DF,"getServerOptions");IA.exports=DF});var UA=h((S3,wA)=>{"use strict";var Fl=V();Fl.initSync();var{CONFIG_PARAMS:CA}=T();function MF(){let e=Fl.get(CA.CUSTOMFUNCTIONS_NETWORK_CORSACCESSLIST),t=Fl.get(CA.CUSTOMFUNCTIONS_NETWORK_CORS),r;if(t&&(r={origin:!0,allowedHeaders:["Content-Type","Authorization"],credentials:!1},e&&e.length>0&&e[0]!==null)){let s=e.split(",");r.origin=(n,i)=>s.indexOf(n)!==-1?i(null,!0):i(new Error(`domain ${n} is not on access list`))}return r}a(MF,"getCORSOptions");wA.exports=MF});var DA=h((f3,yA)=>{"use strict";var LA=V();LA.initSync();var PF=T();function BF(){return LA.get(PF.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HEADERSTIMEOUT)}a(BF,"getHeaderTimeoutConfig");yA.exports=BF});var PA=h((T3,MA)=>{var vF=he(),HF={user:{presence:!0},schema:{presence:!0},table:{presence:!0},operation:{presence:!0}};MA.exports=function(e){return vF.validateObject(e,HF)}});var Vl=h((m3,BA)=>{"use strict";var qF=T().OPERATIONS_ENUM,zo=class{constructor(t,r,s,n=void 0){this.operation=qF.UPDATE,this.schema=t,this.table=r,this.records=s,this.__origin=n}};a(zo,"UpdateObject");BA.exports=zo});var HA=h((R3,vA)=>{"use strict";var GF={OPERATION:"operation",REFRESH:"refresh"},jo=class{constructor(t,r){this.operation_token=t,this.refresh_token=r}};a(jo,"JWTTokens");var ec=class{constructor(t,r,s){this.public_key=t,this.private_key=r,this.passphrase=s}};a(ec,"JWTRSAKeys");vA.exports={JWTTokens:jo,TOKEN_TYPE_ENUM:GF,JWTRSAKeys:ec}});var nc=h((A3,VA)=>{"use strict";var Ii=require("jsonwebtoken"),kl=require("fs-extra"),xl=b(),Dt=T(),{handleHDBError:_t,hdb_errors:FF}=D(),{HTTP_STATUS_CODES:ut,AUTHENTICATION_ERROR_MSGS:lt}=FF,gi=g(),qA=Yo(),Kl=gr(),VF=yt().update,kF=Vl(),xF=js(),{UserEventMsg:$F}=Vr(),Xr=V();Xr.initSync();var $l=require("path"),{JWTTokens:YF,JWTRSAKeys:KF,TOKEN_TYPE_ENUM:tc}=HA(),QF=Xr.get(Dt.HDB_SETTINGS_NAMES.OPERATION_TOKEN_TIMEOUT_KEY)?Xr.get(Dt.HDB_SETTINGS_NAMES.OPERATION_TOKEN_TIMEOUT_KEY):"1d",WF=Xr.get(Dt.HDB_SETTINGS_NAMES.REFRESH_TOKEN_TIMEOUT_KEY)?Xr.get(Dt.HDB_SETTINGS_NAMES.REFRESH_TOKEN_TIMEOUT_KEY):"30d",rc="RS256",Yl;VA.exports={createTokens:JF,validateOperationToken:XF,refreshOperationToken:ZF,validateRefreshToken:FA};async function JF(e){if(xl.isEmpty(e)||typeof e!="object")throw _t(new Error,lt.INVALID_AUTH_OBJECT,ut.BAD_REQUEST,void 0,void 0,!0);if(xl.isEmpty(e.username))throw _t(new Error,lt.USERNAME_REQUIRED,ut.BAD_REQUEST,void 0,void 0,!0);if(xl.isEmpty(e.password))throw _t(new Error,lt.PASSWORD_REQUIRED,ut.BAD_REQUEST,void 0,void 0,!0);let t;try{if(t=await Kl.findAndValidateUser(e.username,e.password),!t)throw _t(new Error,lt.INVALID_CREDENTIALS,ut.UNAUTHORIZED,void 0,void 0,!0)}catch(d){throw gi.error(d),_t(new Error,lt.INVALID_CREDENTIALS,ut.UNAUTHORIZED,void 0,void 0,!0)}let r=await sc(),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 GA(i,r.private_key,r.passphrase),c=await Ii.sign(i,{key:r.private_key,passphrase:r.passphrase},{expiresIn:WF,algorithm:rc,subject:tc.REFRESH}),_=qA.hash(c),u=new kF(Dt.SYSTEM_SCHEMA_NAME,Dt.SYSTEM_TABLE_NAMES.USER_TABLE_NAME,[{username:e.username,refresh_token:_}]),l,E;try{l=await VF(u)}catch(d){gi.error(d),E=d}if(E!==void 0||l.skipped_hashes.length>0)throw _t(new Error,lt.REFRESH_TOKEN_SAVE_FAILED,ut.INTERNAL_SERVER_ERROR);return xF.signalUserChange(new $F(process.pid)),new YF(o,c)}a(JF,"createTokens");async function GA(e,t,r){return await Ii.sign(e,{key:t,passphrase:r},{expiresIn:QF,algorithm:rc,subject:tc.OPERATION})}a(GA,"signOperationToken");async function sc(){if(Yl===void 0)try{let e=$l.join(Xr.getHdbBasePath(),Dt.LICENSE_KEY_DIR_NAME,Dt.JWT_ENUM.JWT_PASSPHRASE_NAME),t=$l.join(Xr.getHdbBasePath(),Dt.LICENSE_KEY_DIR_NAME,Dt.JWT_ENUM.JWT_PRIVATE_KEY_NAME),r=$l.join(Xr.getHdbBasePath(),Dt.LICENSE_KEY_DIR_NAME,Dt.JWT_ENUM.JWT_PUBLIC_KEY_NAME),s=(await kl.readFile(e)).toString(),n=(await kl.readFile(t)).toString(),i=(await kl.readFile(r)).toString();Yl=new KF(i,n,s)}catch(e){throw gi.error(e),_t(new Error,lt.NO_ENCRYPTION_KEYS,ut.INTERNAL_SERVER_ERROR)}return Yl}a(sc,"getJWTRSAKeys");async function ZF(e){if(!e)throw _t(new Error,lt.INVALID_BODY,ut.BAD_REQUEST,void 0,void 0,!0);if(!e.refresh_token)throw _t(new Error,lt.REFRESH_TOKEN_REQUIRED,ut.BAD_REQUEST,void 0,void 0,!0);await FA(e.refresh_token);let t=await sc(),r=await Ii.decode(e.refresh_token);return{operation_token:await GA({username:r.username,super_user:r.super_user,cluster_user:r.cluster_user},t.private_key,t.passphrase)}}a(ZF,"refreshOperationToken");async function XF(e){try{let t=await sc(),r=await Ii.verify(e,t.public_key,{algorithms:rc,subject:tc.OPERATION});return await Kl.findAndValidateUser(r.username,void 0,!1)}catch(t){throw gi.warn(t),t.name&&t.name==="TokenExpiredError"?_t(new Error,lt.TOKEN_EXPIRED,ut.FORBIDDEN):_t(new Error,lt.INVALID_TOKEN,ut.UNAUTHORIZED)}}a(XF,"validateOperationToken");async function FA(e){let t;try{let r=await sc(),s=await Ii.verify(e,r.public_key,{algorithms:rc,subject:tc.REFRESH});t=await Kl.findAndValidateUser(s.username,void 0,!1)}catch(r){throw gi.warn(r),r.name&&r.name==="TokenExpiredError"?_t(new Error,lt.TOKEN_EXPIRED,ut.FORBIDDEN):_t(new Error,lt.INVALID_TOKEN,ut.UNAUTHORIZED)}if(!qA.validate(t.refresh_token,e))throw _t(new Error,lt.INVALID_TOKEN,ut.UNAUTHORIZED);return t}a(FA,"validateRefreshToken")});var Ql=h((O3,$A)=>{"use strict";var zF=PA(),mn=require("passport"),jF=require("passport-local").Strategy,e0=require("passport-http").BasicStrategy,t0=require("util"),r0=gr(),xA=t0.callbackify(r0.findAndValidateUser),p3=Qe(),s0=T(),kA=nc();mn.use(new jF(function(e,t,r){xA(e,t,r)}));mn.use(new e0(function(e,t,r){xA(e,t,r)}));mn.serializeUser(function(e,t){t(null,e)});mn.deserializeUser(function(e,t){t(null,e)});function n0(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":mn.authenticate("basic",{session:!1},(o,c)=>{i(o,c)})(e,t,r);break;case"Bearer":e.body&&e.body.operation&&e.body.operation===s0.OPERATIONS_ENUM.REFRESH_OPERATION_TOKEN?kA.validateRefreshToken(n).then(o=>{e.body.refresh_token=n,r(null,o)}).catch(o=>{r(o)}):kA.validateOperationToken(n).then(o=>{r(null,o)}).catch(o=>{r(o)});break;default:mn.authenticate("local",{session:!1},function(o,c){i(o,c)})(e,t,r);break}}a(n0,"authorize");function i0(e,t){let r=zF(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(i0,"checkPermissions");$A.exports={authorize:n0,checkPermissions:i0}});var ic=h((N3,YA)=>{"use strict";var a0=Nr();YA.exports={writeTransaction:o0};function o0(e,t,r){return a0.writeTransaction(e,t,r)}a(o0,"writeTransaction")});var Wl=h((g3,c0)=>{c0.exports={name:"harperdb",version:"4.0.0",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.3",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.7.0",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=h((B3,lp)=>{"use strict";var ir=V();ir.initSync();var _0=require("fs-extra"),u0=require("semver"),Li=require("path"),{monotonicFactory:l0}=require("ulidx"),E0=l0(),QA=require("util"),WA=require("child_process"),d0=QA.promisify(WA.exec),h0=WA.spawn,te=fe(),ne=T(),eE=b(),br=g(),ac=$r(),S0=ic(),bi=Tr(),{encode:Xl,decode:JA}=require("msgpackr"),{isEmpty:gs}=eE,ZA=gr(),I3=Ss(),f0=mt(),b3=QA.promisify(f0.searchByHash),{connect:T0,StorageType:XA,RetentionPolicy:zA,AckPolicy:jA,DeliverPolicy:zl,NatsConnection:C3,JetStreamManager:w3,JetStreamClient:U3,StringCodec:L3,JSONCodec:m0,createInbox:tE,StreamSource:y3,headers:R0,toJsMsg:A0,nuid:D3,JetStreamOptions:M3,ErrorCode:KA,nanos:P3}=require("nats"),{PACKAGE_ROOT:p0}=T(),O0=Wl(),ep=m0(),N0="clustering",g0=O0.engines[te.NATS_SERVER_NAME],I0=Li.join(p0,"dependencies"),jl=Li.join(I0,`${process.platform}-${process.arch}`,te.NATS_BINARY_NAME),Jl,Zl,Ci,wi,Ui,Wt;lp.exports={runCommand:tp,checkNATSServerInstalled:b0,createConnection:rE,getConnection:oc,getJetStreamManager:Rn,getJetStream:rp,getNATSReferences:Mt,getServerList:w0,createLocalStream:sE,listStreams:sp,deleteLocalStream:U0,getServerConfig:yi,listRemoteStreams:L0,viewStream:y0,publishToStream:D0,createWorkQueueStream:M0,addSourceToWorkStream:np,request:P0,removeSourceFromWorkStream:ap,reloadNATS:nE,reloadNATSHub:B0,reloadNATSLeaf:v0,extractServerName:ip,requestErrorHandler:H0,updateWorkStream:q0,createLocalTableStream:cp,createTableStreams:G0,purgeTableStream:_p,purgeSchemaTableStreams:F0,getStreamInfo:V0,updateNodeNameLocalStreams:k0,closeConnection:C0};async function tp(e,t=void 0){let{stdout:r,stderr:s}=await d0(e,{cwd:t});if(s)throw new Error(s.replace(`
|
|
1
|
+
"use strict";var qb=Object.defineProperty;var a=(e,t)=>qb(e,"name",{value:t,configurable:!0});var h=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var eh=h((PJ,jd)=>{var Gb=require("fastify-plugin");jd.exports=Gb(function(e,t,r){e.addHook("onResponse",async(s,n)=>{n.getResponseTime()}),e.addHook("onSend",async(s,n)=>{let i=n.getResponseTime().toFixed(3);n.header("HDB-Response-Time",i),n.header("Server-Timing",`db;dur=${i}`)}),r()},{name:"hdb-request-time"})});var T=h((BJ,dh)=>{"use strict";var Ye=require("path"),Fb=require("fs");function Vb(){let e=__dirname;for(;!Fb.existsSync(Ye.join(e,"package.json"));){let t=Ye.dirname(e);if(t===e)throw new Error("Could not find package root");e=t}return e}a(Vb,"getHDBPackageRoot");var Gt=Vb(),th="js",$n=th,kb="harperdb-config.yaml",xb="defaultConfig.yaml",$b="hdb",rh=`hdbServer.${$n}`,sh=`customFunctionsServer.${$n}`,nh=`hdbIpcServer.${$n}`,Yb=`restartHdb.${$n}`,eu="HarperDB",Sa="Custom Functions",fa="Clustering Hub",Ta="Clustering Leaf",tu="Clustering Ingest Service",ru="Clustering Reply Service",Kb="foreground.pid",j_={HDB:eu,IPC:"IPC",CLUSTERING_HUB:fa,CLUSTERING_LEAF:Ta,CLUSTERING_INGEST_SERVICE:tu,CLUSTERING_REPLY_SERVICE:ru,CUSTOM_FUNCTIONS:Sa,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"},Qb={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"},Wb={NOTIFY:"notify",FATAL:"fatal",ERROR:"error",WARN:"warn",INFO:"info",DEBUG:"debug",TRACE:"trace"},Jb={harperdb:eu,ipc:"IPC","clustering hub":fa,"clustering leaf":Ta,"clustering ingest service":tu,"clustering reply service":ru,"custom functions":Sa,custom_functions:Sa,"pm2-logrotate":j_.PM2_LOGROTATE,logrotate:j_.PM2_LOGROTATE,clustering:"clustering","clustering config":"clustering config"},Zb={CLUSTERING_HUB_PROC_DESCRIPTOR:fa,CLUSTERING_LEAF_PROC_DESCRIPTOR:Ta,CLUSTERING_INGEST_PROC_DESCRIPTOR:tu,CLUSTERING_REPLY_SERVICE_DESCRIPTOR:ru},ha={HDB:Ye.join(Gt,"server/harperdb"),IPC:Ye.join(Gt,"server/ipc"),CUSTOM_FUNCTIONS:Ye.join(Gt,"server/customFunctions"),CLUSTERING_HUB:Ye.join(Gt,"server/nats"),CLUSTERING_LEAF:Ye.join(Gt,"server/nats")},Xb={HDB:Ye.join(ha.HDB,rh),IPC:Ye.join(ha.IPC,nh),CUSTOM_FUNCTIONS:Ye.join(ha.CUSTOM_FUNCTIONS,sh)},zb={HDB:Ye.join(Gt,"launchServiceScripts/launchHarperDB.js"),CUSTOM_FUNCTIONS:Ye.join(Gt,"launchServiceScripts/launchCustomFunctions.js"),NATS_INGEST_SERVICE:Ye.join(Gt,"launchServiceScripts/launchNatsIngestService.js"),NATS_REPLY_SERVICE:Ye.join(Gt,"launchServiceScripts/launchNatsReplyService.js"),NODES_UPGRADE_4_0_0:Ye.resolve(Gt,"launchServiceScripts/launchUpdateNodes4-0-0.js")},jb={SUPER_USER:"super_user",CLUSTER_USER:"cluster_user"},ih="support@harperdb.io",eC="customer-success@harperdb.io",ah=1,tC=4141,oh="https://harperdbhelp.zendesk.com/hc/en-us/requests/new",rC="https://www.harperdb.io/product",sC=`For support, please submit a request at ${oh} or contact ${ih}`,ch=`For license support, please contact ${eC}`,nC="None of the specified records were found.",iC="hash attribute not found",aC=`Your current license only supports ${ah} role. ${ch}`,oC="Your current license only supports 3 connections to a node.",cC="127.0.0.1",_C=1,uC=/^\.$/,lC=/^\.\.$/,EC="U+002E",dC=/\//g,hC="U+002F",SC=/U\+002F/g,fC=/^U\+002E$/,TC=/^U\+002EU\+002E$/,mC="d",RC=999999,AC="*",pC="--max-old-space-size=",OC="system",NC="__hdb_hash",gC=".harperdb",IC=".hdb",bC="keys",CC="hdb_boot_properties.file",wC=".updateConfig.json",UC="SIGTSTP",LC=24,yC=6e4,DC=448,MC="blob",PC="trash",BC="schema",vC="transactions",HC=".count",qC="id",GC="install_log.log",FC="run_log.log",VC="PROCESS_NAME",kC={SETTINGS_PATH_KEY:"settings_path"},_h=require("lodash"),xC={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"},$C={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},YC={DATA_VERSION:"data_version",UPGRADE_VERSION:"upgrade_version"},KC={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"},QC={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:",WC={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"},JC={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"},ZC="060493.ks",XC=".license",zC={CREATED:"CREATED",IN_PROGRESS:"IN_PROGRESS",COMPLETE:"COMPLETE",ERROR:"ERROR"},I={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"},jC={CSV:".csv",JSON:".json"},ew={AWS_ACCESS_KEY:"aws_access_key_id",AWS_SECRET:"aws_secret_access_key",AWS_BUCKET:"bucket",AWS_FILE_KEY:"key"},tw={SELECT:"select",INSERT:"insert",UPDATE:"update",DELETE:"delete"},Br={};Br[I.CREATE_SCHEMA]=I.CREATE_SCHEMA;Br[I.CREATE_TABLE]=I.CREATE_TABLE;Br[I.CREATE_ATTRIBUTE]=I.CREATE_ATTRIBUTE;Br[I.INSERT]=I.INSERT;Br[I.UPDATE]=I.UPDATE;Br[I.UPSERT]=I.UPSERT;Br[I.DELETE]=I.DELETE;var Z=Object.create(null);Z[I.DESCRIBE_ALL]=I.DESCRIBE_ALL;Z[I.DESCRIBE_TABLE]=I.DESCRIBE_TABLE;Z[I.DESCRIBE_SCHEMA]=I.DESCRIBE_SCHEMA;Z[I.READ_LOG]=I.READ_LOG;Z[I.ADD_NODE]=I.ADD_NODE;Z[I.LIST_USERS]=I.LIST_USERS;Z[I.LIST_ROLES]=I.LIST_ROLES;Z[I.USER_INFO]=I.USER_INFO;Z[I.SQL]=I.SQL;Z[I.GET_JOB]=I.GET_JOB;Z[I.SEARCH_JOBS_BY_START_DATE]=I.SEARCH_JOBS_BY_START_DATE;Z[I.DELETE_FILES_BEFORE]=I.DELETE_FILES_BEFORE;Z[I.EXPORT_LOCAL]=I.EXPORT_LOCAL;Z[I.EXPORT_TO_S3]=I.EXPORT_TO_S3;Z[I.CLUSTER_STATUS]=I.CLUSTER_STATUS;Z[I.REMOVE_NODE]=I.REMOVE_NODE;Z[I.RESTART]=I.RESTART;Z[I.CUSTOM_FUNCTIONS_STATUS]=I.CUSTOM_FUNCTIONS_STATUS;Z[I.GET_CUSTOM_FUNCTIONS]=I.GET_CUSTOM_FUNCTIONS;Z[I.GET_CUSTOM_FUNCTION]=I.GET_CUSTOM_FUNCTION;Z[I.SET_CUSTOM_FUNCTION]=I.SET_CUSTOM_FUNCTION;Z[I.DROP_CUSTOM_FUNCTION]=I.DROP_CUSTOM_FUNCTION;Z[I.ADD_CUSTOM_FUNCTION_PROJECT]=I.ADD_CUSTOM_FUNCTION_PROJECT;Z[I.DROP_CUSTOM_FUNCTION_PROJECT]=I.DROP_CUSTOM_FUNCTION_PROJECT;Z[I.PACKAGE_CUSTOM_FUNCTION_PROJECT]=I.PACKAGE_CUSTOM_FUNCTION_PROJECT;Z[I.DEPLOY_CUSTOM_FUNCTION_PROJECT]=I.DEPLOY_CUSTOM_FUNCTION_PROJECT;var rw={RUN:"run",INSTALL:"install",REGISTER:"register",STOP:"stop",RESTART:"restart",VERSION:"version",UPGRADE:"upgrade"},sw={point:"point",lineString:"lineString",multiLineString:"multiLineString",multiPoint:"multiPoint",multiPolygon:"multiPolygon",polygon:"polygon"},uh={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"},nw=_h.invert(uh),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"},iw={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},aw={csv_file_load:"csv_file_load",csv_data_load:I.CSV_DATA_LOAD,csv_url_load:I.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"},ow={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"},cw={BIDIRECTIONAL:"BIDIRECTIONAL",OUTBOUND:"OUTBOUND",INBOUND:"INBOUND"},_w={FILE_SYSTEM:"fs",LMDB:"lmdb"},uw={API_CALL_DEFAULT:1e4,VERSION_DEFAULT:"2.2.0"},lw={DEVELOPMENT:8192,DEFAULT:512},Ew={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"},dw={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"},hw={ENOENT:"ENOENT",EACCES:"EACCES"},lh={CREATED_TIME:"__createdtime__",UPDATED_TIME:"__updatedtime__"},Sw="__clustering__",fw=Object.values(lh),Tw=15984864e5,Eh={LESS:"<",LESS_OR_EQ:"<=",GREATER:">",GREATER_OR_EQ:">=",BETWEEN:"..."},mw=_h.invert(Eh),Rw={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"},Aw=111,pw=`\r
|
|
2
|
+
`,Ow={READ:"read",INSERT:"insert",UPDATE:"update",DELETE:"delete"},Nw=["*","%"],gw="unauthorized_access",Iw="func_val",bw={HASH_VALUE:"hash_value",TIMESTAMP:"timestamp",USERNAME:"username"},Cw={JWT_PRIVATE_KEY_NAME:".jwtPrivate.key",JWT_PUBLIC_KEY_NAME:".jwtPublic.key",JWT_PASSPHRASE_NAME:".jwtPass"},ww="hdb_ipc_server",Uw="hdb_ipc_client_",Lw={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"},yw={HDB_CORE:"hdb_core",CUSTOM_FUNCTIONS:"custom_functions"},Dw={STOPPED:"stopped",ONLINE:"online"},Mw="3.x.x";dh.exports={LOCAL_HARPERDB_OPERATIONS:Z,HDB_SUPPORT_ADDRESS:ih,HDB_SUPPORT_URL:oh,HDB_PRICING_URL:rC,SUPPORT_HELP_MSG:sC,LICENSE_HELP_MSG:ch,HDB_PROC_NAME:rh,HDB_PROC_DESCRIPTOR:eu,CLUSTERING_LEAF_PROC_DESCRIPTOR:Ta,CLUSTERING_HUB_PROC_DESCRIPTOR:fa,SYSTEM_SCHEMA_NAME:OC,HASH_FOLDER_NAME:NC,HDB_HOME_DIR_NAME:gC,UPDATE_FILE_NAME:wC,LICENSE_KEY_DIR_NAME:bC,BOOT_PROPS_FILE_NAME:CC,JOB_TYPE_ENUM:aw,JOB_STATUS_ENUM:zC,SYSTEM_TABLE_NAMES:KC,SYSTEM_TABLE_HASH_ATTRIBUTES:QC,OPERATIONS_ENUM:I,VALID_S3_FILE_TYPES:jC,S3_BUCKET_AUTH_KEYS:ew,VALID_SQL_OPS_ENUM:tw,GEO_CONVERSION_ENUM:sw,HDB_SETTINGS_NAMES:uh,HDB_SETTINGS_NAMES_REVERSE_LOOKUP:nw,SERVICE_ACTIONS_ENUM:rw,CLUSTER_MESSAGE_TYPE_ENUM:ow,CLUSTER_CONNECTION_DIRECTION_ENUM:cw,CLUSTER_EVENTS_DEFS_ENUM:Ew,PERIOD_REGEX:uC,DOUBLE_PERIOD_REGEX:lC,UNICODE_PERIOD:EC,FORWARD_SLASH_REGEX:dC,UNICODE_FORWARD_SLASH:hC,ESCAPED_FORWARD_SLASH_REGEX:SC,ESCAPED_PERIOD_REGEX:fC,ESCAPED_DOUBLE_PERIOD_REGEX:TC,REG_KEY_FILE_NAME:ZC,RESTART_TIMEOUT_MS:yC,HDB_FILE_PERMISSIONS:DC,SCHEMA_DIR_NAME:BC,TRANSACTIONS_DIR_NAME:vC,LIMIT_COUNT_NAME:HC,ID_ATTRIBUTE_STRING:qC,INSERT_MODULE_ENUM:$C,UPGRADE_JSON_FIELD_NAMES_ENUM:YC,RESTART_CODE:UC,RESTART_CODE_NUM:LC,CLUSTER_OPERATIONS:Br,SYSTEM_DEFAULT_ATTRIBUTE_NAMES:JC,HDB_INTERNAL_SC_CHANNEL_PREFIX:ht,INTERNAL_SC_CHANNELS:WC,CLUSTERING_MESSAGE_TYPES:Rw,HDB_FILE_SUFFIX:IC,BLOB_FOLDER_NAME:MC,HDB_TRASH_DIR:PC,ORIGINATOR_SET_VALUE:Aw,LICENSE_VALUES:uw,RAM_ALLOCATION_ENUM:lw,STORAGE_TYPES_ENUM:_w,TIME_STAMP_NAMES_ENUM:lh,TIME_STAMP_NAMES:fw,PERMS_UPDATE_RELEASE_TIMESTAMP:Tw,SEARCH_NOT_FOUND_MESSAGE:nC,SEARCH_ATTRIBUTE_NOT_FOUND:iC,LICENSE_ROLE_DENIED_RESPONSE:aC,LICENSE_MAX_CONNS_REACHED:oC,BASIC_LICENSE_MAX_NON_CU_ROLES:ah,BASIC_LICENSE_CLUSTER_CONNECTION_LIMIT_WS_ERROR_CODE:tC,VALUE_SEARCH_COMPARATORS:Eh,VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP:mw,LICENSE_FILE_NAME:XC,WEBSOCKET_CLOSE_CODE_DESCRIPTION_LOOKUP:dw,NEW_LINE:pw,BASIC_LICENSE_MAX_CLUSTER_USER_ROLES:_C,MOMENT_DAYS_TAG:mC,API_TURNOVER_SEC:RC,LOOPBACK:cC,CODE_EXTENSION:$n,WILDCARD_SEARCH_VALUE:AC,NODE_ERROR_CODES:hw,JAVASCRIPT_EXTENSION:th,PERMS_CRUD_ENUM:Ow,UNAUTHORIZED_PERMISSION_NAME:gw,SEARCH_WILDCARDS:Nw,FUNC_VAL:Iw,READ_AUDIT_LOG_SEARCH_TYPES_ENUM:bw,JWT_ENUM:Cw,CLUSTERING_FLAG:Sw,RUN_LOG:FC,INSTALL_LOG:GC,IPC_SERVER_MODULE:nh,HDB_IPC_SERVER:ww,IPC_EVENT_TYPES:Lw,HDB_IPC_CLIENT_PREFIX:Uw,CUSTOM_FUNCTION_PROC_NAME:sh,CUSTOM_FUNCTION_PROC_DESCRIPTOR:Sa,SERVICES:yw,MEM_SETTING_KEY:pC,HDB_RESTART_SCRIPT:Yb,PROCESS_DESCRIPTORS:j_,SERVICE_SERVERS:Xb,SERVICE_SERVERS_CWD:ha,PROCESS_DESCRIPTORS_VALIDATE:Jb,LAUNCH_SERVICE_SCRIPTS:zb,LOG_LEVELS:Wb,PROCESS_NAME_ENV_PROP:VC,PROCESS_LOG_NAMES:Qb,PM2_PROCESS_STATUSES:Dw,CONFIG_PARAM_MAP:iw,CONFIG_PARAMS:f,HDB_CONFIG_FILE:kb,HDB_DEFAULT_CONFIG_FILE:xb,ROLE_TYPES_ENUM:jb,BOOT_PROP_PARAMS:kC,INSTALL_PROMPTS:xC,HDB_ROOT_DIR_NAME:$b,CLUSTERING_PROCESSES:Zb,FOREGROUND_PID_FILE:Kb,PACKAGE_ROOT:Gt,PRE_4_0_0_VERSION:Mw}});var su=h((vJ,fh)=>{"use strict";var hh=require("minimist");fh.exports=Pw;function Pw(e=[],t=!1){if(!Array.isArray(e))return{};let r,s;t?(r=Sh(process.env),s=Sh(hh(process.argv))):(r=process.env,s=hh(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(Pw,"assignCMDENVVariables");function Sh(e){let t,r=Object.keys(e),s=r.length,n={};for(;s--;)t=r[s],n[t.toLowerCase()]=e[t];return n}a(Sh,"objKeysToLowerCase")});var g=h((HJ,Nh)=>{"use strict";var os=require("fs-extra"),cs=require("path"),mh=require("yaml"),Rh=require("properties-reader"),Re=T(),Bw=su(),vw=require("os"),{PACKAGE_ROOT:au}=T(),st={notify:7,fatal:6,error:5,warn:4,info:3,debug:2,trace:1},ma=cs.join(au,"logs"),vr=process.env.pm_id===void 0,Hw=cs.join(au,"config/yaml/",Re.HDB_DEFAULT_CONFIG_FILE),ou=process.env.PROCESS_NAME===void 0?Re.PROCESS_DESCRIPTORS.INSTALL:process.env.PROCESS_NAME,Ys,Xt,dr,rt,nu,Ks;Ks===void 0&&Ah();Nh.exports={createLogFile:qw,notify:Vw,fatal:kw,error:iu,warn:xw,info:Gw,debug:Fw,trace:Oh,setLogLevel:Yw,log_level:rt};function Ah(){try{if(Ks===void 0){let e=$w();Ks=Rh(e),{level:rt,config_log_path:nu,to_file:Xt,to_stream:dr}=Kw(Ks.get("settings_path"))}}catch(e){if(Ks=void 0,e.code===Re.NODE_ERROR_CODES.ENOENT){let t=Bw(Object.keys(Re.CONFIG_PARAM_MAP),!0);for(let i in t){let o=Re.CONFIG_PARAM_MAP[i];o&&o.toLowerCase();let c=t[i];if(o===Re.CONFIG_PARAMS.LOGGING_LEVEL){rt=c;continue}if(o===Re.CONFIG_PARAMS.LOGGING_STDSTREAMS){dr=c;continue}o===Re.CONFIG_PARAMS.LOGGING_FILE&&(Xt=o)}let{default_level:r,default_to_file:s,default_to_stream:n}=Qw();Xt=Xt===void 0?s:Xt,Xt=Th(Xt),dr=dr===void 0?n:dr,dr=Th(dr),rt=rt===void 0?r:rt,nu=ma;return}throw iu("Error initializing log settings"),iu(e),e}}a(Ah,"initLogSettings");function qw(e,t){if(!vr){Oh("createLogFile should only be used if the process is not being managed by pm2");return}Ks===void 0&&Ah(),ou=t;let r;e===Re.PROCESS_LOG_NAMES.INSTALL?r=ma:r=nu,Xt&&(Ys=cs.join(r,e),os.ensureFileSync(Ys))}a(qw,"createLogFile");function _s(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": "${ou}", "level": "${e}", "timestamp": "${r}", "message": "${s}"}
|
|
3
|
+
`}a(_s,"createLogRecord");function ph(e){Ys===void 0&&(ou=Re.PROCESS_DESCRIPTORS.INSTALL,os.ensureDirSync(ma),Ys=cs.join(ma,Re.PROCESS_LOG_NAMES.INSTALL),os.ensureFileSync(Ys)),os.appendFileSync(Ys,e)}a(ph,"writeToLogFile");function Ra(e){Xt&&ph(e),dr&&process.stdout.write(e)}a(Ra,"nonPm2LogStdOut");function cu(e){Xt&&ph(e),dr&&process.stderr.write(e)}a(cu,"nonPm2LogStdErr");function Gw(...e){if(st[rt]<=st.info){let t=_s("info",e);if(vr){Ra(t);return}process.stdout.write(t)}}a(Gw,"info");function Oh(...e){if(st[rt]<=st.trace){let t=_s("trace",e);if(vr){Ra(t);return}process.stdout.write(t)}}a(Oh,"trace");function iu(...e){if(st[rt]<=st.error){let t=_s("error",e);if(vr){cu(t);return}process.stderr.write(t)}}a(iu,"error");function Fw(...e){if(st[rt]<=st.debug){let t=_s("debug",e);if(vr){Ra(t);return}process.stdout.write(t)}}a(Fw,"debug");function Vw(...e){if(st[rt]<=st.notify){let t=_s("notify",e);if(vr){Ra(t);return}process.stdout.write(t)}}a(Vw,"notify");function kw(...e){if(st[rt]<=st.fatal){let t=_s("fatal",e);if(vr){cu(t);return}process.stderr.write(t)}}a(kw,"fatal");function xw(...e){if(st[rt]<=st.warn){let t=_s("warn",e);if(vr){cu(t);return}process.stderr.write(t)}}a(xw,"warn");function $w(){let e;try{e=vw.homedir()}catch{e=process.env.HOME}e||(e="~/");let t=cs.join(e,Re.HDB_HOME_DIR_NAME,Re.BOOT_PROPS_FILE_NAME);return os.existsSync(t)||(t=cs.join(au,"utility/hdb_boot_properties.file")),t}a($w,"getPropsFilePath");function Yw(e){rt=e}a(Yw,"setLogLevel");function Th(e){return e===!0||typeof e=="string"&&e.toLowerCase()==="true"}a(Th,"autoCastBoolean");function Kw(e){try{if(e.includes("config/settings.js")){let o=Rh(e);return{level:o.get(Re.HDB_SETTINGS_NAMES.LOG_LEVEL_KEY),config_log_path:cs.dirname(o.get(Re.HDB_SETTINGS_NAMES.LOG_PATH_KEY)),to_file:o.get(Re.HDB_SETTINGS_NAMES.LOG_TO_FILE),to_stream:o.get(Re.HDB_SETTINGS_NAMES.LOG_TO_STDSTREAMS)}}let t=mh.parseDocument(os.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===Re.NODE_ERROR_CODES.ENOENT)throw t;console.error("Error accessing config file for logging"),console.error(t)}}a(Kw,"getLogConfig");function Qw(){try{let e=mh.parseDocument(os.readFileSync(Hw,"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(Qw,"getDefaultConfig")});var Ih=h((qJ,gh)=>{"use strict";var Ww=require("util"),Jw=require("path"),Zw=require("child_process"),Xw=Ww.promisify(Zw.execFile),zw=1e3*1e3*10;gh.exports={findPs:jw};async function jw(e){let t={};try{await Promise.all(["comm","args","ppid","uid","%cpu","%mem"].map(async r=>{let{stdout:s}=await Xw("ps",["wwxo",`pid,${r}`],{maxBuffer:zw});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:Jw.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(jw,"findPs")});var Ke=h((GJ,Ch)=>{"use strict";var eU="__dbis__",tU="__environment_name__",rU="__dbi_defintion__",sU={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"},nU=["__createdtime__","__updatedtime__"],iU="\uFFFF",bh={TIMESTAMP:"timestamp",HASH_VALUE:"hash_value",USER_NAME:"user_name"},aU=Object.values(bh);Ch.exports={INTERNAL_DBIS_NAME:eU,DBI_DEFINITION_NAME:rU,SEARCH_TYPES:sU,TIMESTAMP_NAMES:nU,MAX_SEARCH_KEY_LENGTH:256,ENVIRONMENT_NAME_KEY:tU,TRANSACTIONS_DBI_NAMES_ENUM:bh,TRANSACTIONS_DBIS:aU,OVERFLOW_MARKER:iU}});var Qe=h((FJ,vh)=>{"use strict";var wh=T(),Uh=Ke(),Lh={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},yh=a(e=>`${e} Check logs and try again.`,"CHECK_LOGS_WRAPPER"),Dh={500:yh("There was an error processing your request."),400:"Invalid request"},oU=Dh[Lh.INTERNAL_SERVER_ERROR],cU={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.`},_U={CONFIG_VALIDATION:e=>`HarperDB config file validation error: ${e}`},uU={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"},lU={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 ${Uh.INTERNAL_DBIS_NAME}`,CANNOT_DROP_INTERNAL_DBIS_NAME:`cannot drop a dbi named ${Uh.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"},EU={ATTR_NAME_LENGTH_ERR:e=>`transaction aborted due to attribute name ${e} being too long. Attribute names cannot be longer than ${wh.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 ${wh.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"},Mh={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"},dU={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."},hU={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`},SU={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"},fU={OUTER_JOIN_TRANSLATION_ERROR:"There was an error translating the final SQL outer join data."},TU={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`},Ph={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.`},Bh={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}`},mU={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."},RU={CLUSTERING_NOT_ENABLED:"Clustering must be enabled to perform this operation."},AU={...Mh,...uU,...cU,...dU,...hU,...SU,...fU,...TU,...EU,...Ph,...Bh,...mU,...RU,..._U};vh.exports={CHECK_LOGS_WRAPPER:yh,HDB_ERROR_MSGS:AU,DEFAULT_ERROR_MSGS:Dh,DEFAULT_ERROR_RESP:oU,HTTP_STATUS_CODES:Lh,LMDB_ERRORS_ENUM:lU,AUTHENTICATION_ERROR_MSGS:Mh,VALIDATION_ERROR_MSGS:Ph,IPC_ERRORS:Bh}});var D=h((VJ,Gh)=>{"use strict";var Qs=Qe(),pU=g(),OU=T(),Yn=class extends Error{constructor(t,r,s,n,i){super(),Error.captureStackTrace(this,Hh),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&&pU[n](i)}};a(Yn,"HdbError");function Hh(e,t,r,s=OU.LOG_LEVELS.ERROR,n=null,i=!1){if(qh(e))return e;let o=new Yn(e,t,r,s,n);return i&&delete o.stack,o}a(Hh,"handleHDBError");function qh(e){return e.__proto__.constructor.name===Yn.name}a(qh,"isHDBError");Gh.exports={isHDBError:qh,handleHDBError:Hh,hdb_errors:Qs}});var b=h((xJ,eS)=>{"use strict";var _u=require("path"),NU=require("fs-extra"),be=g(),Fh=require("fs-extra"),gU=require("truncate-utf8-bytes"),Kn=require("os"),IU=require("net"),bU=require("recursive-iterator"),ye=T(),Yh=Ih(),Vh=require("papaparse"),Aa=require("moment"),{inspect:CU}=require("util"),kh=require("is-number"),kJ=require("lodash"),{hdb_errors:pa}=D(),Kh=require("util").promisify(setTimeout),wU=100,UU=5,LU="",yU=4,xh=255,$h={true:!0,false:!1,undefined:null,null:null,NaN:NaN};eS.exports={isEmpty:St,isEmptyOrZeroLength:zt,arrayHasEmptyValues:PU,arrayHasEmptyOrZeroLengthValues:BU,buildFolderPath:vU,isBoolean:Qh,errorizeMessage:DU,stripFileExtension:qU,autoCast:GU,autoCastJSONDeep:uu,removeDir:VU,compareVersions:kU,isCompatibleDataVersion:xU,escapeRawValue:Jh,unescapeValue:$U,stringifyProps:YU,valueConverter:KU,timeoutPromise:WU,isClusterOperation:ZU,getClusterUser:jU,sendTransactionToSocketCluster:XU,checkGlobalSchemaTable:zU,getHomeDir:Zh,getPropsFilePath:QU,promisifyPapaParse:eL,removeBOM:Xh,createEventPromise:tL,checkProcessRunning:rL,checkSchemaTableExist:sL,checkSchemaExists:zh,checkTableExists:jh,getStartOfTomorrowInSeconds:nL,getLimitKey:iL,isObject:HU,isNotEmptyAndHasValue:MU,autoCasterIsNumberCheck:Wh,backtickASTSchemaItems:aL,isPortTaken:JU,stopProcess:oL,createForkArgs:cL,autoCastBoolean:_L,async_set_timeout:Kh,getTableHashAttribute:uL,doesSchemaExist:lL,doesTableExist:EL,stringifyObj:dL,ms_to_time:hL,PACKAGE_ROOT:ye.PACKAGE_ROOT};function DU(e){return e instanceof Error?e:new Error(e)}a(DU,"errorizeMessage");function St(e){return e==null}a(St,"isEmpty");function MU(e){return!St(e)&&(e||e===0||e===""||Qh(e))}a(MU,"isNotEmptyAndHasValue");function zt(e){return St(e)||e.length===0||e.size===0}a(zt,"isEmptyOrZeroLength");function PU(e){if(St(e))return!0;for(let t=0;t<e.length;t++)if(St(e[t]))return!0;return!1}a(PU,"arrayHasEmptyValues");function BU(e){if(zt(e))return!0;for(let t=0;t<e.length;t++)if(zt(e[t]))return!0;return!1}a(BU,"arrayHasEmptyOrZeroLengthValues");function vU(...e){try{return e.join(_u.sep)}catch{console.error(e)}}a(vU,"buildFolderPath");function Qh(e){return St(e)?!1:e===!0||e===!1}a(Qh,"isBoolean");function HU(e){return St(e)?!1:typeof e=="object"}a(HU,"isObject");function qU(e){return zt(e)?LU:e.slice(0,-yU)}a(qU,"stripFileExtension");function GU(e){return St(e)||e===""||typeof e!="string"?e:$h[e]!==void 0?$h[e]:Wh(e)===!0?Number(e):e}a(GU,"autoCast");function FU(e){if(typeof e=="string"&&(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")))try{return JSON.parse(e)}catch{}return e}a(FU,"autoCastJSON");function uu(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=uu(s);n!==s&&(e[t]=n)}else for(let t in e){let r=e[t],s=uu(r);s!==r&&(e[t]=s)}return e}else return FU(e)}a(uu,"autoCastJSONDeep");function Wh(e){if(e.startsWith("0.")&&kh(e))return!0;let t=e.toUpperCase().includes("E");return!!((e!=="0"&&e.startsWith("0"))===!1&&t===!1&&kh(e))}a(Wh,"autoCasterIsNumberCheck");async function VU(e){if(zt(e))throw new Error(`Directory path: ${e} does not exist`);try{await Fh.emptyDir(e),await Fh.remove(e)}catch(t){throw be.error(`Error removing files in ${e} -- ${t}`),t}}a(VU,"removeDir");function kU(e,t){if(zt(e)){be.info("Invalid current version sent as parameter.");return}if(zt(t)){be.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(kU,"compareVersions");function xU(e,t,r=!1){let s=e.toString().split("."),n=t.toString().split(".");return s[0]===n[0]&&(!r||s[1]===n[1])}a(xU,"isCompatibleDataVersion");function Jh(e){if(St(e))return e;let t=String(e);return t==="."?ye.UNICODE_PERIOD:t===".."?ye.UNICODE_PERIOD+ye.UNICODE_PERIOD:t.replace(ye.FORWARD_SLASH_REGEX,ye.UNICODE_FORWARD_SLASH)}a(Jh,"escapeRawValue");function $U(e){if(St(e))return e;let t=String(e);return t===ye.UNICODE_PERIOD?".":t===ye.UNICODE_PERIOD+ye.UNICODE_PERIOD?"..":String(e).replace(ye.ESCAPED_FORWARD_SLASH_REGEX,"/")}a($U,"unescapeValue");function YU(e,t){if(St(e))return be.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}!zt(s)&&s[0]===";"?r+=" "+s+n+Kn.EOL:zt(s)||(r+=s+"="+n+Kn.EOL)}catch{be.error(`Found bad property during upgrade with key ${s} and value: ${n}`)}}),r}a(YU,"stringifyProps");function KU(e){let t;try{t=typeof e=="object"?JSON.stringify(e):e}catch(n){be.error(n),t=e}let r=String(Jh(t)),s=Buffer.byteLength(r)>xh?gU(r,xh)+"/blob":r;return{value:t,value_stripped:r,value_path:s}}a(KU,"valueConverter");function Zh(){let e;try{e=Kn.homedir()}catch{e=process.env.HOME}return e||(e="~/"),e}a(Zh,"getHomeDir");function QU(){let e=_u.join(Zh(),ye.HDB_HOME_DIR_NAME,ye.BOOT_PROPS_FILE_NAME);return NU.existsSync(e)||(e=_u.join(__dirname,"../","hdb_boot_properties.file")),e}a(QU,"getPropsFilePath");function WU(e,t){let r,s;return s=new Promise(function(n){r=setTimeout(function(){n(t)},e)}),{promise:s,cancel:function(){clearTimeout(r)}}}a(WU,"timeoutPromise");async function JU(e){if(!e)throw new Error("Invalid port passed as parameter");return new Promise((t,r)=>{let s=IU.createServer().once("error",n=>{n.code==="EADDRINUSE"?t(!0):r(n)}).once("listening",()=>s.once("close",()=>t(!1)).close()).listen(e)})}a(JU,"isPortTaken");function ZU(e){try{return ye.CLUSTER_OPERATIONS[e.toLowerCase()]!==void 0}catch(t){be.error(`Error checking operation against cluster ops ${t}`)}return!1}a(ZU,"isClusterOperation");function XU(e,t,r){if(global.hdb_socket_client!==void 0){be.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]=ye.ORIGINATOR_SET_VALUE),global.hdb_socket_client.publish(e,i)}}a(XU,"sendTransactionToSocketCluster");function zU(e,t){if(!global.hdb_schema[e])return pa.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e);if(!global.hdb_schema[e]||!global.hdb_schema[e][t])return pa.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(zU,"checkGlobalSchemaTable");function jU(e,t){if(St(t)){be.warn("No CLUSTERING_USER defined, clustering disabled");return}if(St(e)||zt(e)){be.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){be.error(`unable to find cluster_user due to: ${s.message}`);return}if(r===void 0){be.warn(`CLUSTERING_USER: ${t} not found or is not active.`);return}return r}a(jU,"getClusterUser");function eL(){Vh.parsePromise=function(e,t){return new Promise(function(r,s){Vh.parse(e,{header:!0,transformHeader:Xh,chunk:t.bind(null,s),skipEmptyLines:!0,dynamicTyping:!0,error:s,complete:r})})}}a(eL,"promisifyPapaParse");function Xh(e){if(typeof e!="string")throw new TypeError(`Expected a string, got ${typeof e}`);return e.charCodeAt(0)===65279?e.slice(1):e}a(Xh,"removeBOM");function tL(e,t,r){return new Promise(s=>{t.once(e,n=>{let i=r;be.info(`Got cluster status event response: ${CU(n)}`);try{i.cancel()}catch{be.error("Error trying to cancel timeout.")}s(n)})})}a(tL,"createEventPromise");async function rL(e){let t=!0,r=0;do await Kh(wU*r++),(await Yh.findPs(e)).length>0&&(t=!1);while(t&&r<UU);if(t)throw new Error(`process ${e} was not started`)}a(rL,"checkProcessRunning");function sL(e,t){let r=zh(e);if(r)return r;let s=jh(e,t);if(s)return s}a(sL,"checkSchemaTableExist");function zh(e){if(!global.hdb_schema[e])return pa.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}a(zh,"checkSchemaExists");function jh(e,t){if(!global.hdb_schema[e][t])return pa.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(jh,"checkTableExists");function nL(){let e=Aa().utc().add(1,ye.MOMENT_DAYS_TAG).startOf(ye.MOMENT_DAYS_TAG).unix(),t=Aa().utc().unix();return e-t}a(nL,"getStartOfTomorrowInSeconds");function iL(){return Aa().utc().format("DD-MM-YYYY")}a(iL,"getLimitKey");function aL(e){try{let t=new bU(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){be.error("Got an error back ticking items."),be.error(t)}}a(aL,"backtickASTSchemaItems");async function oL(e){let t=Kn.userInfo();(await Yh.findPs(e)).forEach(s=>{(t.uid==0||s.uid==t.uid)&&(process.kill(s.pid),be.trace(`Following process was killed by stopProcess: ${s.cmd}`))})}a(oL,"stopProcess");function cL(e){return[e]}a(cL,"createForkArgs");function _L(e){return e===!0||typeof e=="string"&&e.toLowerCase()==="true"}a(_L,"autoCastBoolean");function uL(e,t){return global.hdb_schema?.[e]?.[t]?.hash_attribute}a(uL,"getTableHashAttribute");function lL(e){return global?.hdb_schema?.[e]!==void 0}a(lL,"doesSchemaExist");function EL(e,t){return global?.hdb_schema?.[e]?.[t]!==void 0}a(EL,"doesTableExist");function dL(e){try{return JSON.stringify(e)}catch{return e}}a(dL,"stringifyObj");function hL(e){let t=Aa.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(hL,"ms_to_time")});var rS=h(($J,tS)=>{"use strict";var SL={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))},fL="certificate.pem",TL="privateKey.pem",mL="ca.pem";tS.exports={CERTIFICATE_VALUES:SL,CERTIFICATE_PEM_NAME:fL,PRIVATEKEY_PEM_NAME:TL,CA_PEM_NAME:mL}});var de=h((YJ,sS)=>{"use strict";var nt=require("validate.js");nt.validators.type=function(e,t,r,s){return e===null||typeof e>"u"||nt.validators.type.checks[t](e)?null:` must be a '${t}' value`};nt.validators.type.checks={Object:function(e){return nt.isObject(e)&&!nt.isArray(e)},Array:nt.isArray,Integer:nt.isInteger,Number:nt.isNumber,String:nt.isString,Date:nt.isDate,Boolean:function(e){return typeof e=="boolean"}};nt.validators.hasValidFileExt=function(e,t){return!nt.isString(e)||e===""||t.filter(r=>e.endsWith(r)).length>0?null:`must include one of the following valid file extensions - '${t.join("', '")}'`};sS.exports={validateObject:RL,validateObjectAsync:AL,validateBySchema:pL};function RL(e,t){if(!e||!t)return new Error("validateObject parameters were null");let r=nt(e,t,{format:"flat"});return r?new Error(r):null}a(RL,"validateObject");async function AL(e,t){if(!e||!t)return new Error("validateObject parameters were null");try{await nt.async(e,t,{format:"flat"})}catch(r){let s=r.join(",");return new Error(s)}return null}a(AL,"validateObjectAsync");function pL(e,t){let r=t.validate(e,{allowUnknown:!0,abortEarly:!1,errors:{wrap:{label:"'"}}});if(r.error)return new Error(r.error.message)}a(pL,"validateBySchema")});var Eu=h((KJ,iS)=>{"use strict";var OL=require("fs-extra"),F=require("joi"),NL=require("os"),{boolean:De,string:Sr,number:jt,array:lu}=F.types(),Ft=require("path"),gL=g(),Oa=b(),fr=rS(),IL=de(),hr="keys",bL=fr.CERTIFICATE_PEM_NAME,CL=fr.PRIVATEKEY_PEM_NAME,wL=fr.CA_PEM_NAME,UL=fr.CERTIFICATE_PEM_NAME,LL=fr.PRIVATEKEY_PEM_NAME,yL=fr.CA_PEM_NAME,DL=fr.CERTIFICATE_PEM_NAME,ML=fr.PRIVATEKEY_PEM_NAME,PL=fr.CA_PEM_NAME,BL="log",vL="custom_functions",HL="Invalid logging.rotation.maxSize unit. Available units are G, M or K",qL="Invalid logging.rotation.maxSize value. Value should be a number followed by unit e.g. '10M'",GL="rootPath config parameter is undefined",FL="clustering.enabled config parameter is undefined",Hr=jt.min(0).required(),Na=lu.items({host:Sr.required(),port:Hr}).empty(null),it;iS.exports={configValidator:VL,routesValidator:KL,route_constraints:Na};function VL(e){if(it=e.rootPath,Oa.isEmpty(it))throw GL;let t=De.required(),r=F.valid("production","development").required(),s=jt.min(1).max(1e3).empty(null).default(YL),n=Sr.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path").empty(null).default(nS),i=F.custom(xL).messages({"any.custom":"{:#label} {:#error}"}).empty(null).default(nS),o=Sr.pattern(/^[^\s.,*>]+$/).messages({"string.pattern.base":"{:#label} invalid, must not contain ., * or >"}).empty(null),c=e.clustering?.enabled;if(Oa.isEmpty(c))throw FL;let _;return c===!0?_=F.object({enabled:t,hubServer:F.object({cluster:F.object({name:F.required().empty(null),network:F.object({port:Hr,routes:Na}).required()}).required(),leafNodes:F.object({network:F.object({port:Hr}).required()}).required(),network:F.object({port:Hr}).required()}).required(),leafServer:F.object({network:F.object({port:Hr,routes:Na}).required()}).required(),nodeName:o,tls:F.object({certificate:i,certificateAuthority:i,privateKey:i,insecure:De.required()}),user:F.string().required()}).required():_=F.object({enabled:t,tls:F.object({certificate:i,certificateAuthority:i,privateKey:i,insecure:De.required()})}).required(),F.object({clustering:_,customFunctions:F.object({enabled:t,network:F.object({cors:De.required(),corsAccessList:lu.required(),headersTimeout:jt.min(1).required(),https:De.required(),keepAliveTimeout:jt.min(1).required(),port:Hr,timeout:jt.min(1).required()}),nodeEnv:r,root:n,tls:F.object({certificate:i,certificateAuthority:i,privateKey:i})}).required(),ipc:F.object({network:F.object({port:Hr})}).required(),localStudio:F.object({enabled:t}).required(),logging:F.object({file:De.required(),level:F.valid("notify","fatal","error","warn","info","debug","trace"),rotation:F.object({compress:De.required(),dateFormat:Sr.required(),maxSize:Sr.custom($L).required(),retain:jt.min(0).required(),rotate:De.required(),rotateInterval:Sr.required(),rotateModule:De.required(),timezone:Sr.required(),workerInterval:jt.min(1).required()}).required(),root:n,stdStreams:De.required(),auditLog:De.required()}).required(),operationsApi:F.object({authentication:F.object({operationTokenTimeout:F.required(),refreshTokenTimeout:F.required()}).required(),foreground:De.required(),network:F.object({cors:De.required(),corsAccessList:lu.required(),headersTimeout:jt.min(1).required(),https:De.required(),keepAliveTimeout:jt.min(1).required(),port:Hr,timeout:jt.min(1).required()}).required(),nodeEnv:r,tls:F.object({certificate:i,certificateAuthority:i,privateKey:i})}).required(),rootPath:Sr.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path").required(),http:F.object({threads:s}).required(),storage:F.object({writeAsync:De.required(),overlappingSync:De.optional()}).required()}).validate(e,{allowUnknown:!0,abortEarly:!1,errors:{wrap:{label:"'"}}})}a(VL,"configValidator");function kL(e){return OL.existsSync(e)?null:`Specified path ${e} does not exist.`}a(kL,"doesPathExist");function xL(e,t){F.assert(e,Sr.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+\.pem+$/).messages({"string.pattern.base":"must be a valid directory path and specify a .pem file"}));let r=kL(e);if(r)return t.message(r)}a(xL,"validatePemFile");function $L(e,t){let r=e.slice(-1);if(r!=="G"&&r!=="M"&&r!=="K")return t.message(HL);let s=e.slice(0,-1);if(isNaN(parseInt(s)))return t.message(qL)}a($L,"validateRotationMaxSize");function YL(e,t){let r=t.state.path.join("."),s=NL.cpus().length,n=s-1;return n<=2&&(n=2),gL.info(`Detected ${s} cores on this machine, defaulting ${r} to ${n}`),n}a(YL,"setDefaultThreads");function nS(e,t){if(!Oa.isEmpty(t.original))return t.original;let r=t.state.path.join(".");if(Oa.isEmpty(it))throw new Error(`Error setting default root for: ${r}. HDB root is not defined`);switch(r){case"customFunctions.root":return Ft.join(it,vL);case"logging.root":return Ft.join(it,BL);case"operationsApi.tls.certificate":return Ft.join(it,hr,bL);case"operationsApi.tls.privateKey":return Ft.join(it,hr,CL);case"operationsApi.tls.certificateAuthority":return Ft.join(it,hr,wL);case"customFunctions.tls.certificate":return Ft.join(it,hr,UL);case"customFunctions.tls.privateKey":return Ft.join(it,hr,LL);case"customFunctions.tls.certificateAuthority":return Ft.join(it,hr,yL);case"clustering.tls.certificate":return Ft.join(it,hr,DL);case"clustering.tls.privateKey":return Ft.join(it,hr,ML);case"clustering.tls.certificateAuthority":return Ft.join(it,hr,PL);default:throw new Error(`Error setting default root for config parameter: ${r}. Unrecognized config parameter`)}}a(nS,"setDefaultRoot");function KL(e){let t=F.object({routes:Na});return IL.validateBySchema({routes:e},t)}a(KL,"routesValidator")});var Tr=h((QJ,ES)=>{"use strict";var se=T(),bt=b(),We=g(),{configValidator:QL,routesValidator:aS}=Eu(),Vt=require("fs-extra"),WL=require("yaml"),Ws=require("path"),JL=require("is-number"),ba=require("properties-reader"),ZL=require("lodash"),{handleHDBError:XL}=D(),{HTTP_STATUS_CODES:zL,HDB_ERROR_MSGS:ga}=Qe(),{PACKAGE_ROOT:jL}=T(),ey="Unable to get config value because config is uninitialized",ty="Config successfully initialized",ry="Error backing up config file",sy="Empty parameter sent to getConfigValue",oS=Ws.join(jL,"config","yaml",se.HDB_DEFAULT_CONFIG_FILE),ny="Configuration successfully set. You must restart HarperDB for new config settings to take effect.",Ia,at;ES.exports={createConfigFile:iy,getDefaultConfig:ay,getConfigValue:cS,initConfig:_S,flattenConfig:us,updateConfigValue:uS,updateConfigObject:oy,getConfiguration:cy,setConfiguration:_y,readConfigFile:Su,getClusteringRoutes:uy,initOldConfig:lS,getConfigFromFile:ly};function iy(e){let t=Js(oS);Ia=us(t.toJSON());for(let i in e){let o=se.CONFIG_PARAM_MAP[i.toLowerCase()];if(o!==void 0){let c=o.split("_"),_=du(o,e[i]);try{t.setIn([...c],_)}catch(u){We.error(u)}}}hu(t);let r=t.toJSON();at=us(r);let s=t.getIn(["rootPath"]),n=Ws.join(s,se.HDB_CONFIG_FILE);Vt.createFileSync(n),Vt.writeFileSync(n,String(t)),We.trace(`Config file written to ${n}`)}a(iy,"createConfigFile");function ay(e){if(Ia===void 0){let r=Js(oS);Ia=us(r.toJSON())}let t=se.CONFIG_PARAM_MAP[e.toLowerCase()];if(t!==void 0)return Ia[t.toLowerCase()]}a(ay,"getDefaultConfig");function cS(e){if(bt.isEmpty(e)){We.error(sy);return}if(at===void 0){We.trace(ey);return}let t=se.CONFIG_PARAM_MAP[e.toLowerCase()];if(t!==void 0)return at[t.toLowerCase()]}a(cS,"getConfigValue");function _S(e=!1){if(at===void 0||e){let t=bt.getPropsFilePath();try{Vt.accessSync(t,Vt.constants.F_OK|Vt.constants.R_OK)}catch(o){throw We.error(o),new Error(`HarperDB properties file at path ${t} does not exist`)}let s=ba(t).get(se.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY),n;if(s.includes("config/settings.js"))try{lS(s);return}catch(o){if(o.code!==se.NODE_ERROR_CODES.ENOENT)throw o}try{n=Js(s)}catch(o){if(o.code===se.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}`)}hu(n);let i=n.toJSON();at=us(i),We.trace(ty)}}a(_S,"initConfig");function hu(e){let t=e.toJSON(),r=QL(t);if(r.error)throw ga.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(hu,"validateConfig");function oy(e,t){at===void 0&&(at={});let r=se.CONFIG_PARAM_MAP[e.toLowerCase()];if(r===void 0){We.trace(`Unable to update config object because config param '${e}' does not exist`);return}at[r.toLowerCase()]=t}a(oy,"updateConfigObject");function uS(e,t,r=void 0,s=!1,n=!1){at===void 0&&_S();let i=cS(se.CONFIG_PARAM_MAP.hdb_root),o=Ws.join(i,se.HDB_CONFIG_FILE),c=Js(o);if(r===void 0){let l=se.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=du(l,t);c.setIn([...E],d)}else for(let l in r){let E=se.CONFIG_PARAM_MAP[l.toLowerCase()];if(E!==void 0){let d=E.split("_"),S=du(E,r[l]);try{c.setIn([...d],S)}catch(m){We.error(m)}}}hu(c);let _=c.getIn(["rootPath"]),u=Ws.join(_,se.HDB_CONFIG_FILE);if(s===!0)try{let l=Ws.join(_,"backup",`${se.HDB_CONFIG_FILE}.bak`);Vt.copySync(o,l),We.trace(`Config file: ${o} backed up to: ${l}`)}catch(l){We.error(ry),We.error(l)}Vt.writeFileSync(u,String(c)),n&&(at=us(c.toJSON())),We.trace(`Config parameter: ${e} updated with value: ${t}`)}a(uS,"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 du(e,t){if(e===se.CONFIG_PARAMS.CLUSTERING_NODENAME||e===se.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(JL(t))return parseFloat(t);if(t===!0||t===!1||Array.isArray(t)||bt.isObject(t)||t===null)return t;if(typeof t=="string"&&t.toLowerCase()==="true")return!0;if(typeof t=="string"&&t.toLowerCase()==="false")return!1}if(t===void 0||t.toLowerCase()==="undefined")return null;if(typeof t=="string"&&(t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]")))try{return JSON.parse(t)}catch{}return bt.autoCast(t)}a(du,"castConfigValue");function cy(){let e=bt.getPropsFilePath(),r=ba(e).get(se.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY);return Js(r).toJSON()}a(cy,"getConfiguration");async function _y(e){let{operation:t,hdb_user:r,hdb_auth_header:s,...n}=e;try{return uS(void 0,void 0,n,!0),ny}catch(i){throw typeof i=="string"||i instanceof String?XL(i,i,zL.BAD_REQUEST,void 0,void 0,!0):i}}a(_y,"setConfiguration");function Su(){let e=bt.getPropsFilePath();try{Vt.accessSync(e,Vt.constants.F_OK|Vt.constants.R_OK)}catch(n){throw We.error(n),new Error(`HarperDB properties file at path ${e} does not exist`)}let r=ba(e).get(se.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY);return Js(r).toJSON()}a(Su,"readConfigFile");function Js(e){return WL.parseDocument(Vt.readFileSync(e,"utf8"),{simpleKeys:!0})}a(Js,"parseYamlDoc");function uy(){let e=Su(),t=e?.clustering?.hubServer?.cluster?.network?.routes;t=bt.isEmptyOrZeroLength(t)?[]:t;let r=aS(t);if(r)throw ga.CONFIG_VALIDATION(r.message);let s=e?.clustering?.leafServer?.network?.routes;s=bt.isEmptyOrZeroLength(s)?[]:s;let n=aS(s);if(n)throw ga.CONFIG_VALIDATION(n.message);if(!bt.isEmptyOrZeroLength(s)&&!bt.isEmptyOrZeroLength(t)){let i=t.filter(o=>s.some(c=>c.host===o.host&&c.port===o.port));if(!bt.isEmptyOrZeroLength(i)){let o=`Duplicate hub and leaf routes found ${JSON.stringify(i)}`;throw ga.CONFIG_VALIDATION(o)}}return{hub_routes:t,leaf_routes:s}}a(uy,"getClusteringRoutes");function lS(e){let t=ba(e);at={};for(let r in se.CONFIG_PARAM_MAP){let s=t.get(r.toUpperCase());if(bt.isEmpty(s)||typeof s=="string"&&s.trim().length===0)continue;let n=se.CONFIG_PARAM_MAP[r].toLowerCase();n===se.CONFIG_PARAMS.LOGGING_ROOT?at[n]=Ws.dirname(s):at[n]=s}return at}a(lS,"initOldConfig");function ly(e){let t=Su();return ZL.get(t,e.replaceAll("_","."))}a(ly,"getConfigFromFile")});var V=h((WJ,hS)=>{"use strict";var fu=require("fs-extra"),er=require("path"),Ey=require("os"),dy=require("properties-reader"),Qn=g(),Zs=b(),M=T(),Ca=Tr(),hy="Error initializing environment manager",wa="BOOT_PROPS_FILE_PATH",dS=!1,Sy={[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},mr={};hS.exports={BOOT_PROPS_FILE_PATH:wa,getHdbBasePath:fy,setHdbBasePath:Ty,get:my,initSync:Ay,setProperty:Y,initTestEnvironment:py};function fy(){return mr[M.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]}a(fy,"getHdbBasePath");function Ty(e){mr[M.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=e}a(Ty,"setHdbBasePath");function my(e){let t=Ca.getConfigValue(e);return t===void 0?mr[e]:t}a(my,"get");function Y(e,t){Sy[e]&&(mr[e]=t),Ca.updateConfigObject(e,t)}a(Y,"setProperty");function Ry(){let e;try{e=Zs.getPropsFilePath(),fu.accessSync(e,fu.constants.F_OK|fu.constants.R_OK),dS=!0;let t=dy(e);return mr[M.HDB_SETTINGS_NAMES.INSTALL_USER]=t.get(M.HDB_SETTINGS_NAMES.INSTALL_USER),mr[M.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY]=t.get(M.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY),mr[wa]=e,!0}catch{return Qn.trace(`Environment manager found no properties file at ${e}`),!1}}a(Ry,"doesPropFileExist");function Ay(e=!1){try{(dS||Ry())&&(Ca.initConfig(e),mr[M.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=Ca.getConfigValue(M.HDB_SETTINGS_NAMES.HDB_ROOT_KEY))}catch(t){Qn.error(hy),Qn.error(t),console.error(t),process.exit(1)}}a(Ay,"initSync");function py(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,_=er.join(__dirname,"../../","unitTests");mr[wa]=er.join(_,"hdb_boot_properties.file"),Y(M.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY,er.join(_,"settings.test")),Y(M.HDB_SETTINGS_NAMES.INSTALL_USER,Ey.userInfo().username),Y(M.HDB_SETTINGS_NAMES.PRIVATE_KEY_KEY,er.join(_,"envDir","utility","keys","privateKey.pem")),Y(M.HDB_SETTINGS_NAMES.CERT_KEY,er.join(_,"envDir","utility","keys","certificate.pem")),Y(M.CONFIG_PARAMS.CUSTOMFUNCTIONS_TLS_PRIVATEKEY,er.join(_,"envDir","utility","keys","privateKey.pem")),Y(M.CONFIG_PARAMS.CUSTOMFUNCTIONS_TLS_CERTIFICATE,er.join(_,"envDir","utility","keys","certificate.pem")),Y(M.HDB_SETTINGS_NAMES.LOG_LEVEL_KEY,"debug"),Y(M.HDB_SETTINGS_NAMES.LOG_PATH_KEY,er.join(_,"envDir","log")),Y(M.HDB_SETTINGS_NAMES.LOG_DAILY_ROTATE_KEY,!1),Y(M.HDB_SETTINGS_NAMES.CLUSTERING_ENABLED_KEY,!0),Y(M.HDB_SETTINGS_NAMES.CLUSTERING_NODE_NAME_KEY,"1231412de213"),Y(M.HDB_SETTINGS_NAMES.HDB_ROOT_KEY,er.join(_,"envDir")),Y(M.HDB_SETTINGS_NAMES.HTTP_SECURE_ENABLED_KEY,Zs.isEmpty(n)?!0:n),Y(M.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HTTPS,Zs.isEmpty(n)?!0:n),Y(M.HDB_SETTINGS_NAMES.SERVER_PORT_KEY,9925),Y(M.HDB_SETTINGS_NAMES.CORS_ENABLED_KEY,Zs.isEmpty(i)?!1:i),Y(M.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_CORS,Zs.isEmpty(i)?!1:i),Y(M.HDB_SETTINGS_NAMES.IPC_SERVER_PORT,9383),Y(M.HDB_SETTINGS_NAMES.MAX_CUSTOM_FUNCTION_PROCESSES,2),Y(M.HDB_SETTINGS_NAMES.MAX_HDB_PROCESSES,4),Y(M.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_PORT_KEY,9926),Y(M.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_ENABLED_KEY,!0),Y(M.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY,er.resolve(__dirname,"../../unitTests/server/customFunctions/custom_functions")),Y(M.HDB_SETTINGS_NAMES.LOCAL_STUDIO_ON,Zs.isEmpty(c)?!1:c),o&&(Y("CORS_ACCESSLIST",o),Y(M.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_CORSACCESSLIST,o)),s&&(Y(M.HDB_SETTINGS_NAMES.SERVER_TIMEOUT_KEY,s),Y(M.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_TIMEOUT,s)),t&&(Y(M.HDB_SETTINGS_NAMES.SERVER_KEEP_ALIVE_TIMEOUT_KEY,t),Y(M.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_KEEPALIVETIMEOUT,t)),r&&(Y(M.HDB_SETTINGS_NAMES.SERVER_HEADERS_TIMEOUT_KEY,r),Y(M.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HEADERSTIMEOUT,r))}catch(t){let r=`Error reading in HDB environment variables from path ${wa}. Please check your boot props and settings files`;Qn.fatal(r),Qn.error(t)}}a(py,"initTestEnvironment")});var ls=h((JJ,Oy)=>{Oy.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 CS=h((XJ,bS)=>{"use strict";var Tu=require("recursive-iterator"),Ny=require("alasql"),mu=require("clone"),SS=b(),{handleHDBError:fS,hdb_errors:gy}=D(),{HDB_ERROR_MSGS:TS,HTTP_STATUS_CODES:mS}=gy,Iy=["DISTINCT_ARRAY"],RS=Symbol("validateTables"),Ru=Symbol("validateTable"),ZJ=Symbol("getAllColumns"),AS=Symbol("validateAllColumns"),Ua=Symbol("findColumn"),pS=Symbol("validateOrderBy"),Wn=Symbol("validateSegment"),Au=Symbol("validateColumn"),OS=Symbol("setColumnsForTable"),NS=Symbol("checkColumnsForAsterisk"),gS=Symbol("validateGroupBy"),IS=Symbol("hasColumns"),La=class{constructor(t){this.statement=t,this.attributes=[]}validate(){if(!this.statement)throw new Error("invalid sql statement");this[RS](),this[NS](),this[AS]()}[RS](){if(this[IS]()){if(!this.statement.from||this.statement.from.length===0)throw"no from clause";this.statement.from.forEach(t=>{this[Ru](t)}),this.statement.joins&&this.statement.joins.forEach(t=>{t.table.as=t.as,this[Ru](t.table)})}}[IS](){let t=!1,r=new Tu(this.statement);for(let{node:s,path:n}of r)if(s&&s.columnid){t=!0;break}return t}[Ru](t){if(!t.databaseid)throw`schema not defined for table ${t.tableid}`;if(!global.hdb_schema[t.databaseid])throw fS(new Error,TS.SCHEMA_NOT_FOUND(t.databaseid),mS.NOT_FOUND);if(!global.hdb_schema[t.databaseid][t.tableid])throw fS(new Error,TS.TABLE_NOT_FOUND(t.databaseid,t.tableid),mS.NOT_FOUND);global.hdb_schema[t.databaseid][t.tableid].attributes.forEach(s=>{let n=mu(s);n.table=mu(t),this.attributes.push(n)})}[Ua](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)}[NS](){let t=new Tu(this.statement.columns);for(let{node:r,path:s}of t)r&&r.columnid==="*"&&s.indexOf("expression")<0&&this[OS](r.tableid)}[OS](t){this.attributes.forEach(r=>{(!t||t&&(r.table.tableid===t||r.table.as===t))&&this.statement.columns.push(new Ny.yy.Column({columnid:r.attribute,tableid:r.table.as?r.table.as:r.table.tableid}))})}[AS](){this[Wn](this.statement.columns,!1),this[Wn](this.statement.joins,!1),this[Wn](this.statement.where,!1),this[gS](this.statement.group,!1),this[Wn](this.statement.order,!0)}[Wn](t,r){if(!t)return;let s=new Tu(t),n=[];for(let{node:i,path:o}of s)!SS.isEmpty(i)&&!SS.isEmpty(i.columnid)&&i.columnid!=="*"&&(r?this[pS](i):n.push(this[Au](i)));return n}[gS](t){if(!t)return;let r=[];if(this.statement.columns.forEach(s=>{if(!(s.funcid&&Iy.indexOf(s.funcid.toUpperCase())>=0)){if(!s.aggregatorid&&!s.columnid){let n=mu(s);delete n.as,r.push(n)}else if(s.columnid){let n=this[Ua](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[Ua](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`}[pS](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[Au](t)}[Au](t){let r=this[Ua](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(La,"SelectValidator");bS.exports=La});var pu=h((zJ,wS)=>{"use strict";var ya=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(ya,"BridgeMethods");wS.exports=ya});var Es=h((tZ,DS)=>{"use strict";var US=Qe().LMDB_ERRORS_ENUM,jJ=require("lmdb"),by=Ke(),eZ=require("buffer").Buffer,Cy=require("microtime"),{OVERFLOW_MARKER:LS,MAX_SEARCH_KEY_LENGTH:Da}=by,yS=["number","string","symbol","boolean","bigint"];function wy(e){if(!e)throw new Error(US.ENV_REQUIRED);if(e.constructor.name!=="LMDBStore")throw new Error(US.INVALID_ENVIRONMENT)}a(wy,"validateEnv");function Uy(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(Uy,"stringifyData");function Ly(e){return e instanceof Date?e.valueOf():e}a(Ly,"convertKeyValueToWrite");function yy(e){if(e==null)return;if(yS.includes(typeof e))return e.length>Da?[e.slice(0,Da)+LS]:[e];let t;if(Array.isArray(e)){t=[];for(let r=0,s=e.length;r<s;r++){let n=e[r];yS.includes(typeof n)&&(n.length>Da?t.push(n.slice(0,Da)+LS):t.push(n))}}return t}a(yy,"getIndexedValues");function Dy(){let e=Cy.now().toString(),t=e.length-3;return Number(e.slice(0,t)+"."+e.slice(t))}a(Dy,"getMicroTime");DS.exports={validateEnv:wy,stringifyData:Uy,convertKeyValueToWrite:Ly,getMicroTime:Dy,getIndexedValues:yy}});var PS=h((rZ,MS)=>{"use strict";var Ma=class{constructor(t=!1,r=!1){this.dup_sort=t,this.is_hash_attribute=r,this.useVersions=r}};a(Ma,"DBIDefinition");MS.exports=Ma});var vS=h((sZ,BS)=>{"use strict";var Pa=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(Pa,"OpenDBIObject");BS.exports=Pa});var qS=h((nZ,HS)=>{"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");HS.exports=Ba});var X=h((aZ,ZS)=>{"use strict";var Ou=require("lmdb"),Ct=require("fs-extra"),kt=require("path"),Ha=Es(),GS=g(),Me=Qe().LMDB_ERRORS_ENUM,qa=PS(),Nu=vS(),FS=qS(),qr=Ke(),iZ=T(),Jn=V();Jn.initSync();var VS=Jn.get("STORAGE_WRITEASYNC")===!0||Jn.get("STORAGE_WRITEASYNC")==="true"||Jn.get("STORAGE_WRITEASYNC")==="TRUE",kS=Jn.get("STORAGE_OVERLAPPINGSYNC"),xS=1024*1024*1024,$S=1e4,YS=1e3,xt=qr.INTERNAL_DBIS_NAME,KS=qr.DBI_DEFINITION_NAME,My="data.mdb",Py="lock.mdb",Zn=".mdb",By="-lock",va=class{constructor(t,r,s=!1){this.dbi=wt(t,r),this.key_type=this.dbi[qr.DBI_DEFINITION_NAME].key_type,this.is_hash_attribute=this.dbi[qr.DBI_DEFINITION_NAME].is_hash_attribute,this.txn=t.beginTxn({readOnly:s===!1}),this.cursor=new Ou.Cursor(this.txn,this.dbi)}close(){this.cursor.close(),this.txn.abort()}commit(){this.cursor.close(),this.txn.commit()}};a(va,"TransactionCursor");function gu(e,t){if(e===void 0)throw new Error(Me.BASE_PATH_REQUIRED);if(t===void 0)throw new Error(Me.ENV_NAME_REQUIRED)}a(gu,"pathEnvNameValidation");async function Iu(e,t,r=!0){try{await Ct.access(e)}catch(s){throw s.code==="ENOENT"?new Error(Me.INVALID_BASE_PATH):s}try{let s=kt.join(e,t+Zn);return await Ct.access(s,Ct.constants.R_OK|Ct.constants.F_OK),s}catch(s){if(s.code==="ENOENT")if(r)try{return await Ct.access(kt.join(e,t,My),Ct.constants.R_OK|Ct.constants.F_OK),kt.join(e,t)}catch(n){if(n.code==="ENOENT")throw new Error(Me.INVALID_ENVIRONMENT)}else throw new Error(Me.INVALID_ENVIRONMENT);throw s}}a(Iu,"validateEnvironmentPath");function Ga(e,t){if(Ha.validateEnv(e),t===void 0)throw new Error(Me.DBI_NAME_REQUIRED)}a(Ga,"validateEnvDBIName");async function vy(e,t,r=!1,s=!1){gu(e,t),t=t.toString();try{return await Iu(e,t,s),bu(e,t,r)}catch(n){if(n.message===Me.INVALID_ENVIRONMENT){let i=kt.join(e,t);await Ct.mkdirp(s?i:e);let o=new FS(s?i:i+Zn,xS,$S,YS,!1,VS,kS),c=Ou.open(o);c.dbis=Object.create(null);let _=new Nu(!1);c.openDB(xt,_),global.lmdb_map===void 0&&(global.lmdb_map=Object.create(null));let u=Cu(e,t,r);return c[qr.ENVIRONMENT_NAME_KEY]=u,global.lmdb_map[u]=c,c}throw n}}a(vy,"createEnvironment");async function Hy(e,t,r,s=!0){let n=await bu(e,t);if(r===void 0)throw new Error(Me.DESTINATION_PATH_REQUIRED);try{await Ct.access(kt.dirname(r))}catch(i){throw i.code==="ENOENT"?new Error(Me.INVALID_DESTINATION_PATH):i}await n.backup(r,s)}a(Hy,"copyEnvironment");async function bu(e,t,r=!1){gu(e,t),t=t.toString();let s=Cu(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 Iu(e,t),i=kt.join(e,t+Zn),o=n!=i,c=new FS(n,xS,$S,YS,o,VS,kS),_=Ou.open(c);_.dbis=Object.create(null);let u=WS(_);for(let l=0;l<u.length;l++)wt(_,u[l]);return _[qr.ENVIRONMENT_NAME_KEY]=s,global.lmdb_map[s]=_,_}a(bu,"openEnvironment");async function qy(e,t,r=!1){gu(e,t),t=t.toString();let s=kt.join(e,t+Zn),n=await Iu(e,t);if(global.lmdb_map!==void 0){let i=Cu(e,t,r);if(global.lmdb_map[i]){let o=global.lmdb_map[i];await QS(o),delete global.lmdb_map[i]}}await Ct.remove(n),await Ct.remove(n===s?n+By:kt.join(kt.dirname(n),Py))}a(qy,"deleteEnvironment");async function QS(e){Ha.validateEnv(e);let t=e[qr.ENVIRONMENT_NAME_KEY];await e.close(),t!==void 0&&global.lmdb_map!==void 0&&delete global.lmdb_map[t]}a(QS,"closeEnvironment");function Cu(e,t,r=!1){let n=`${kt.basename(e)}.${t}`;return r===!0&&(n=`txn.${n}`),n}a(Cu,"getCachedEnvironmentName");function Gy(e){Ha.validateEnv(e);let t=Object.create(null),r=wt(e,xt);for(let{key:s,value:n}of r.getRange({start:!1}))if(s!==xt)try{t[s]=Object.assign(new qa,n)}catch{GS.warn(`an internal error occurred: unable to parse DBI Definition for ${s}`)}return t}a(Gy,"listDBIDefinitions");function WS(e){Ha.validateEnv(e);let t=[],r=wt(e,xt);for(let{key:s}of r.getRange({start:!1}))s!==xt&&t.push(s);return t}a(WS,"listDBIs");function Fy(e,t){let s=wt(e,xt).getEntry(t),n=new qa;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(Fy,"getDBIDefinition");function JS(e,t,r,s=!1){if(Ga(e,t),t=t.toString(),t===xt)throw new Error(Me.CANNOT_CREATE_INTERNAL_DBIS_NAME);try{return wt(e,t)}catch(n){if(n.message===Me.DBI_DOES_NOT_EXIST){let i=new Nu(r,s===!0),o=e.openDB(t,i),c=new qa(r===!0,s);return o[KS]=c,wt(e,xt).putSync(t,c),e.dbis[t]=o,o}throw n}}a(JS,"createDBI");function wt(e,t){if(Ga(e,t),t=t.toString(),e.dbis[t]!==void 0)return e.dbis[t];let r;if(t!==xt?r=Fy(e,t):r=new qa,r===void 0)throw new Error(Me.DBI_DOES_NOT_EXIST);let s;try{let n=new Nu(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(Me.DBI_DOES_NOT_EXIST):n}return s[KS]=r,e.dbis[t]=s,s}a(wt,"openDBI");function Vy(e,t){Ga(e,t),t=t.toString();let r=wt(e,t),s=r.getStats();return r[qr.DBI_DEFINITION_NAME].is_hash_attribute&&s.entryCount>0&&s.entryCount--,s}a(Vy,"statDBI");async function ky(e,t){try{let r=kt.join(e,t+Zn);return(await Ct.stat(r)).size}catch{throw new Error(Me.INVALID_ENVIRONMENT)}}a(ky,"environmentDataSize");function xy(e,t){if(Ga(e,t),t=t.toString(),t===xt)throw new Error(Me.CANNOT_DROP_INTERNAL_DBIS_NAME);wt(e,t).dropSync(),e.dbis!==void 0&&delete e.dbis[t],wt(e,xt).removeSync(t)}a(xy,"dropDBI");function $y(e,t,r){for(let s=0;s<r.length;s++){let n=r[s];if(!e.dbis[n])try{wt(e,n)}catch(i){if(i.message===Me.DBI_DOES_NOT_EXIST)JS(e,n,n!==t,n===t);else throw i}}}a($y,"initializeDBIs");ZS.exports={openDBI:wt,openEnvironment:bu,createEnvironment:vy,listDBIs:WS,listDBIDefinitions:Gy,createDBI:JS,dropDBI:xy,statDBI:Vy,deleteEnvironment:qy,initializeDBIs:$y,TransactionCursor:va,environmentDataSize:ky,copyEnvironment:Hy,closeEnvironment:QS}});var zS=h((oZ,XS)=>{"use strict";var Fa=class{constructor(t=[],r=[],s=void 0){this.written_hashes=t,this.skipped_hashes=r,this.txn_time=s}};a(Fa,"InsertRecordsResponseObject");XS.exports=Fa});var ef=h((cZ,jS)=>{"use strict";var Va=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(Va,"UpdateRecordsResponseObject");jS.exports=Va});var rf=h((_Z,tf)=>{"use strict";var ka=class{constructor(t=[],r=void 0,s=[]){this.written_hashes=t,this.txn_time=r,this.original_records=s}};a(ka,"UpsertRecordsResponseObject");tf.exports=ka});var Xs=h((dZ,nf)=>{"use strict";var Yy=X(),Ky=zS(),Qy=ef(),Wy=rf(),zn=Es(),Xn=Qe().LMDB_ERRORS_ENUM,Jy=Ke(),Gr=T(),Zy=b(),Xy=require("uuid"),uZ=require("lmdb"),{handleHDBError:zy,hdb_errors:jy}=D(),{OVERFLOW_MARKER:lZ,MAX_SEARCH_KEY_LENGTH:EZ}=Jy,wu=Gr.TIME_STAMP_NAMES_ENUM.CREATED_TIME,ds=Gr.TIME_STAMP_NAMES_ENUM.UPDATED_TIME;async function eD(e,t,r,s,n=!0){Du(e,t,r,s),Uu(e,t,r);let i=new Ky,o=[],c=[];for(let _=0;_<s.length;_++){let u=s[_];sf(u,!0,n);let l=tD(e,t,r,u),E=u[t];o.push(l),c.push(E)}return Lu(o,c,s,i)}a(eD,"insertRecords");function tD(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][Gr.FUNC_VAL],s[o]=c)}let _=zn.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[ds])})}a(tD,"insertRecord");function rD(e,t=[]){let r=0;for(let s=0;s<t.length;s++){let n=t[s];e.splice(n-r,1),r++}}a(rD,"removeSkippedRecords");function sf(e,t,r=!0){let s=Date.now();(r===!0||!Number.isInteger(e[ds]))&&(e[ds]=s),t===!0?(r===!0||!Number.isInteger(e[wu]))&&(e[wu]=s):delete e[wu]}a(sf,"setTimestamps");function Uu(e,t,r){r.indexOf(Gr.TIME_STAMP_NAMES_ENUM.CREATED_TIME)<0&&r.push(Gr.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.indexOf(Gr.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)<0&&r.push(Gr.TIME_STAMP_NAMES_ENUM.UPDATED_TIME),Yy.initializeDBIs(e,t,r)}a(Uu,"initializeTransaction");async function sD(e,t,r,s,n=!0){Du(e,t,r,s),Uu(e,t,r);let i=new Qy,o=[],c=[],_=[];for(let u=0;u<s.length;u++){let l=s[u],E=l[t],d;try{d=yu(e,t,l,E,i,!0,n)}catch{i.skipped_hashes.push(E),o.push(u);continue}c.push(d),_.push(E)}return Lu(c,_,s,i,o)}a(sD,"updateRecords");async function nD(e,t,r,s,n=!0){try{Du(e,t,r,s)}catch(_){throw zy(_,_.message,jy.HTTP_STATUS_CODES.BAD_REQUEST)}Uu(e,t,r);let i=new Wy,o=[],c=[];for(let _=0;_<s.length;_++){let u=s[_],l;Zy.isEmpty(u[t])?(l=Xy.v4(),u[t]=l):l=u[t];let E=yu(e,t,u,l,i,!1,n);o.push(E),c.push(l)}return Lu(o,c,s,i)}a(nD,"upsertRecords");async function Lu(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=zn.getMicroTime(),rD(r,n),s}a(Lu,"finalizeWrite");function yu(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(sf(r,!l,o),Number.isInteger(r[ds])&&u[ds]>r[ds])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 U=u[m];if(typeof R=="function"){let j=R([[u]]);Array.isArray(j)&&(R=j[0][Gr.FUNC_VAL],r[m]=R)}if(R===U)continue;let B=zn.getIndexedValues(U);if(B)for(let j=0,k=B.length;j<k;j++)w.remove(B[j],s);if(B=zn.getIndexedValues(R),B)for(let j=0,k=B.length;j<k;j++)w.put(B[j],s)}let S=Object.assign({},u,r);c.put(s,S,S[ds])},"do_put");return _?E=c.ifVersion(s,_.version,d):E=c.ifNoExists(s,d),E.then(S=>S?!0:yu(e,t,r,s,n,i,o))}a(yu,"updateUpsertRecord");function iD(e,t,r){if(zn.validateEnv(e),t===void 0)throw new Error(Xn.HASH_ATTRIBUTE_REQUIRED);if(!Array.isArray(r))throw r===void 0?new Error(Xn.WRITE_ATTRIBUTES_REQUIRED):new Error(Xn.WRITE_ATTRIBUTES_MUST_BE_ARRAY)}a(iD,"validateBasic");function Du(e,t,r,s){if(iD(e,t,r),!Array.isArray(s))throw s===void 0?new Error(Xn.RECORDS_REQUIRED):new Error(Xn.RECORDS_MUST_BE_ARRAY)}a(Du,"validateWrite");nf.exports={insertRecords:eD,updateRecords:sD,upsertRecords:nD}});var re=h((hZ,of)=>{"use strict";var Mu=T(),zs=V(),Pu=require("path");zs.initSync();var xa,$a,Ya;function af(){if(xa!==void 0)return xa;if(zs.getHdbBasePath()!==void 0)return xa=Pu.join(zs.getHdbBasePath(),Mu.SCHEMA_DIR_NAME),xa}a(af,"getBaseSchemaPath");function aD(){if($a!==void 0)return $a;if(zs.getHdbBasePath()!==void 0)return $a=Pu.join(af(),Mu.SYSTEM_SCHEMA_NAME),$a}a(aD,"getSystemSchemaPath");function oD(){if(Ya!==void 0)return Ya;if(zs.getHdbBasePath()!==void 0)return Ya=Pu.join(zs.getHdbBasePath(),Mu.TRANSACTIONS_DIR_NAME),Ya}a(oD,"getTransactionAuditStorePath");of.exports={getBaseSchemaPath:af,getSystemSchemaPath:aD,getTransactionAuditStorePath:oD}});var Rr=h((SZ,uf)=>{"use strict";var _f=b(),cf=T(),Qa=/^[\x20-\x2E|\x30-\x5F|\x61-\x7E]*$/,Bu=require("joi"),Ka={schema_format:{pattern:Qa,message:"names cannot include backticks or forward slashes"},schema_length:{maximum:250,tooLong:"cannot exceed 250 characters"}},cD=Bu.alternatives(Bu.string().min(1).max(Ka.schema_length.maximum).pattern(Qa).messages({"string.pattern.base":"{:#label} "+Ka.schema_format.message}),Bu.number()).required();function _D(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`:Qa.test(t)?"":`'${e}' has illegal characters`:`'${e}' must be at least one character`:`'${e}' is required`}a(_D,"checkValidTable");function uD(e,t){return _f.doesSchemaExist(e)?e:t.message(`Schema '${e}' does not exist`)}a(uD,"validateSchemaExists");function lD(e,t){let r=t.state.ancestors[0].schema;return _f.doesTableExist(r,e)?e:t.message(`Table '${e}' does not exist`)}a(lD,"validateTableExists");function ED(e,t){return e.toLowerCase()===cf.SYSTEM_SCHEMA_NAME?t.message(`'subscriptions[${t.state.path[1]}]' invalid schema name, '${cf.SYSTEM_SCHEMA_NAME}' name is reserved`):e}a(ED,"validateSchemaName");uf.exports={common_validators:Ka,schema_regex:Qa,hdb_schema_table:cD,validateSchemaExists:uD,validateTableExists:lD,validateSchemaName:ED,checkValidTable:_D}});var Wa=h((fZ,lf)=>{var{common_validators:Fr}=Rr(),jn=de(),$t="is required",z={schema:{presence:!0,format:Fr.schema_format,length:Fr.schema_length},table:{presence:!0,format:Fr.schema_format,length:Fr.schema_length},attribute:{presence:!0,format:Fr.schema_format,length:Fr.schema_length},hash_attribute:{presence:!0,format:Fr.schema_format,length:Fr.schema_length}};function ei(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(ei,"makeAttributesStrings");function dD(e){return e=ei(e),z.schema.presence={message:$t},z.table.presence=!1,z.attribute.presence=!1,z.hash_attribute.presence=!1,jn.validateObject(e,z)}a(dD,"schema_object");function hD(e){return e=ei(e),z.schema.presence={message:$t},z.table.presence={message:$t},z.attribute.presence=!1,z.hash_attribute.presence=!1,jn.validateObject(e,z)}a(hD,"table_object");function SD(e){return e=ei(e),z.schema.presence={message:$t},z.table.presence={message:$t},z.attribute.presence=!1,z.hash_attribute.presence={message:$t},jn.validateObject(e,z)}a(SD,"create_table_object");function fD(e){return e=ei(e),z.schema.presence={message:$t},z.table.presence={message:$t},z.attribute.presence={message:$t},z.hash_attribute.presence=!1,jn.validateObject(e,z)}a(fD,"attribute_object");function TD(e){return e=ei(e),z.schema.presence={message:$t},z.table.presence={message:$t},z.attribute.presence=!1,z.hash_attribute.presence=!1,jn.validateObject(e,z)}a(TD,"describe_table");function mD(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(mD,"validateTableResidence");lf.exports={schema_object:dD,create_table_object:SD,table_object:hD,attribute_object:fD,describe_table:TD,validateTableResidence:mD}});var df=h((TZ,Ef)=>{"use strict";var RD=require("uuid"),Ja=class{constructor(t,r,s,n){this.schema=t,this.table=r,this.attribute=s,this.id=n||RD.v4(),this.schema_table=`${this.schema}.${this.table}`}};a(Ja,"CreateAttributeObject");Ef.exports=Ja});var Xa=h((mZ,hf)=>{"use strict";var AD=df(),Za=class extends AD{constructor(t,r,s,n,i=!0,o=!1){super(t,r,s,n),this.dup_sort=i,this.is_hash_attribute=o}};a(Za,"LMDBCreateAttributeObject");hf.exports=Za});var ff=h((RZ,Sf)=>{"use strict";Sf.exports=OD;var pD="inserted";function OD(e,t,r,s){let n={message:`${e} ${t.length} of ${r.records.length} records`,skipped_hashes:s};return e===pD?(n.inserted_hashes=t,n):(n.update_hashes=t,n)}a(OD,"returnObject")});var za=h((AZ,mf)=>{"use strict";var ND=T(),vu=X(),gD=Xs(),{getSystemSchemaPath:ID,getBaseSchemaPath:bD}=re(),CD=require("path"),wD=ls(),UD=Wa(),LD=Xa(),yD=ff(),{handleHDBError:DD,hdb_errors:MD}=D(),PD=b(),Hu=wD.hdb_attribute,Tf=[];for(let e=0;e<Hu.attributes.length;e++)Tf.push(Hu.attributes[e].attribute);var BD="inserted";mf.exports=vD;async function vD(e){let t=UD.attribute_object(e);if(t)throw DD(new Error,t.message,MD.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0);e.is_hash_attribute=e.is_hash_attribute=="true",e.dup_sort=PD.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 LD(e.schema,e.table,e.attribute,e.id);try{let n=await vu.openEnvironment(CD.join(bD(),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}`);vu.createDBI(n,e.attribute,e.dup_sort,e.is_hash_attribute);let i=await vu.openEnvironment(ID(),ND.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME),{written_hashes:o,skipped_hashes:c}=await gD.insertRecords(i,Hu.hash_attribute,Tf,[s]);return yD(BD,o,{records:[s]},c)}catch(n){throw n}}a(vD,"lmdbCreateAttribute")});var Gu=h((pZ,Af)=>{var{hdb_schema_table:Rf}=Rr(),HD=de(),qu=require("joi"),qD={undefined:"undefined",null:"null"},GD=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||qD[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"),FD=qu.object({schema:Rf,table:Rf,records:qu.array().items(qu.object().custom(GD)).required()});Af.exports=function(e){return HD.validateBySchema(e,FD)}});var ja=h((NZ,Of)=>{"use strict";var Ar=b(),pf=g(),OZ=Gu();Of.exports=VD;function VD(e){if(Ar.isEmpty(e))throw new Error("invalid update parameters defined.");if(Ar.isEmptyOrZeroLength(e.schema))throw new Error("invalid schema specified.");if(Ar.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(Ar.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&&Ar.isEmptyOrZeroLength(o[r]))throw pf.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(!Ar.isEmptyOrZeroLength(o[r])&&(o[r]==="null"||o[r]==="undefined"))throw pf.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`);!Ar.isEmpty(o[r])&&o[r]!==""&&s.has(Ar.autoCast(o[r]))&&(o.skip=!0),s.add(Ar.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(VD,"insertUpdateValidate")});var ti=h((gZ,Nf)=>{"use strict";var kD=T().OPERATIONS_ENUM,eo=class{constructor(t,r,s,n,i=void 0){this.operation=kD.INSERT,this.schema=t,this.table=r,this.hash_attribute=s,this.records=n,this.__origin=i}};a(eo,"InsertObject");Nf.exports=eo});var ro=h((bZ,gf)=>{"use strict";var IZ=ti(),to=T(),Vu=b(),Fu=g(),xD=require("uuid"),{handleHDBError:ri,hdb_errors:$D}=D(),{HDB_ERROR_MSGS:si,HTTP_STATUS_CODES:ni}=$D;gf.exports=YD;function YD(e,t,r){for(let n=0;n<t.length;n++)KD(t[n]);let{records:s}=e;for(let n=0;n<s.length;n++){let i=s[n];QD(i,r,e.operation)}}a(YD,"processRows");function KD(e){if(Buffer.byteLength(String(e))>to.INSERT_MODULE_ENUM.MAX_CHARACTER_SIZE)throw ri(new Error,si.ATTR_NAME_LENGTH_ERR(e),ni.BAD_REQUEST,void 0,void 0,!0);if(Vu.isEmptyOrZeroLength(e)||Vu.isEmpty(e.trim()))throw ri(new Error,si.ATTR_NAME_NULLISH_ERR,ni.BAD_REQUEST,void 0,void 0,!0)}a(KD,"validateAttribute");function QD(e,t,r){if(!e.hasOwnProperty(t)||Vu.isEmptyOrZeroLength(e[t])){if(r===to.OPERATIONS_ENUM.INSERT||r===to.OPERATIONS_ENUM.UPSERT){e[t]=xD.v4();return}throw Fu.error("Update transaction aborted due to record with no hash value:",e),ri(new Error,si.RECORD_MISSING_HASH_ERR,ni.BAD_REQUEST,void 0,void 0,!0)}if(Buffer.byteLength(String(e[t]))>to.INSERT_MODULE_ENUM.MAX_CHARACTER_SIZE)throw Fu.error(e),ri(new Error,si.HASH_VAL_LENGTH_ERR,ni.BAD_REQUEST,void 0,void 0,!0);if(isNaN(e[t])&&e[t].includes("/"))throw Fu.error(e),ri(new Error,si.INVALID_FORWARD_SLASH_IN_HASH_ERR,ni.BAD_REQUEST,void 0,void 0,!0)}a(QD,"validateHash")});var bf=h((CZ,If)=>{"use strict";var so=class{constructor(t,r){this.type=t,this.message=r}};a(so,"IPCEventObject");If.exports=so});var Vr=h((wZ,Cf)=>{"use strict";var WD=g(),ku=b(),JD=T(),{IPC_ERRORS:ii}=Qe();Cf.exports={sendIpcEvent:ZD,validateEvent:XD,SchemaEventMsg:zD,UserEventMsg:jD};function ZD(e){global.hdb_ipc?global.hdb_ipc.emitToServer(e):WD.warn("Tried to send event:",e,"to HDB IPC client but it does not exist")}a(ZD,"sendIpcEvent");function XD(e){if(typeof e!="object")return ii.INVALID_IPC_DATA_TYPE;if(!e.hasOwnProperty("type")||ku.isEmpty(e.type))return ii.MISSING_TYPE;if(!e.hasOwnProperty("message")||ku.isEmpty(e.message))return ii.MISSING_MSG;if(!e.message.hasOwnProperty("originator")||ku.isEmpty(e.message.originator))return ii.MISSING_ORIGIN;if(JD.IPC_EVENT_TYPES[e.type.toUpperCase()]===void 0)return ii.INVALID_EVENT(e.type)}a(XD,"validateEvent");function zD(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(zD,"SchemaEventMsg");function jD(e){this.originator=e}a(jD,"UserEventMsg")});var js=h((LZ,yf)=>{"use strict";var wf=T(),UZ=b(),no=g(),Uf=bf(),{sendIpcEvent:Lf}=Vr();function eM(e){try{no.trace("signalSchemaChange called with message:",e);let t=new Uf(wf.IPC_EVENT_TYPES.SCHEMA,e);Lf(t)}catch(t){no.error(t)}}a(eM,"signalSchemaChange");function tM(e){try{no.trace("signalUserChange called with message:",e);let t=new Uf(wf.IPC_EVENT_TYPES.USER,e);Lf(t)}catch(t){no.error(t)}}a(tM,"signalUserChange");yf.exports={signalSchemaChange:eM,signalUserChange:tM}});var io=h((yZ,Mf)=>{"use strict";var Df=b(),rM=T(),sM=g(),nM=za(),iM=Xa(),aM=js(),{SchemaEventMsg:oM}=Vr(),cM="already exists in";Mf.exports=_M;async function _M(e,t,r){try{if(Df.isEmptyOrZeroLength(r))return r;let s=[];Df.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 uM(e,t.schema,t.name,i)})),n}catch(s){throw s}}a(_M,"lmdbCheckForNewAttributes");async function uM(e,t,r,s){let n=new iM(t,r,s,void 0,!0);e&&(n.hdb_auth_header=e);try{await lM(n)}catch(i){if(typeof i=="object"&&i.message!==void 0&&i.message.includes(cM))sM.warn(`attribute ${t}.${r}.${s} already exists`);else throw i}}a(uM,"createNewAttribute");async function lM(e){let t;try{return t=await nM(e),aM.signalSchemaChange(new oM(process.pid,rM.OPERATIONS_ENUM.CREATE_ATTRIBUTE,e.schema,e.table,e.attribute)),t}catch(r){throw r}}a(lM,"createAttribute")});var en=h((DZ,Pf)=>{"use strict";var ao=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(ao,"LMDBTransactionObject");Pf.exports=ao});var vf=h((MZ,Bf)=>{"use strict";var EM=en(),dM=T().OPERATIONS_ENUM,oo=class extends EM{constructor(t,r,s,n,i=void 0){super(dM.INSERT,r,s,n,i),this.records=t}};a(oo,"LMDBInsertTransactionObject");Bf.exports=oo});var qf=h((PZ,Hf)=>{"use strict";var hM=en(),SM=T().OPERATIONS_ENUM,co=class extends hM{constructor(t,r,s,n,i,o=void 0){super(SM.UPDATE,s,n,i,o),this.records=t,this.original_records=r}};a(co,"LMDBUpdateTransactionObject");Hf.exports=co});var Ff=h((BZ,Gf)=>{"use strict";var fM=en(),TM=T().OPERATIONS_ENUM,_o=class extends fM{constructor(t,r,s,n,i,o=void 0){super(TM.UPSERT,s,n,i,o),this.records=t,this.original_records=r}};a(_o,"LMDBUpsertTransactionObject");Gf.exports=_o});var kf=h((vZ,Vf)=>{"use strict";var mM=en(),RM=T().OPERATIONS_ENUM,uo=class extends mM{constructor(t,r,s,n,i=void 0){super(RM.DELETE,s,n,t,i),this.original_records=r}};a(uo,"LMDBDeleteTransactionObject");Vf.exports=uo});var ai=h((HZ,Kf)=>{"use strict";var AM=require("path"),xf=X(),pM=vf(),OM=qf(),NM=Ff(),gM=kf(),tn=Ke(),$f=b(),{CONFIG_PARAMS:IM}=T(),Yf=V();Yf.initSync();var lo=T().OPERATIONS_ENUM,{getTransactionAuditStorePath:bM}=re();Kf.exports=CM;async function CM(e,t){if(Yf.get(IM.LOGGING_AUDITLOG)===!1)return;let r=AM.join(bM(),e.schema.toString()),s=await xf.openEnvironment(r,e.table,!0),n=wM(e,t);if(!(n===void 0||n.hash_values.length===0)&&s!==void 0){xf.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),$f.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(CM,"writeTransaction");function wM(e,t){let r=$f.isEmpty(e.hdb_user)?void 0:e.hdb_user.username;if(e.operation===lo.INSERT)return new pM(e.records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===lo.UPDATE)return new OM(e.records,t.original_records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===lo.UPSERT)return new NM(e.records,t.original_records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===lo.DELETE)return new gM(t.deleted,t.original_records,r,t.txn_time,e.__origin)}a(wM,"createTransactionObject")});var xu=h((GZ,Qf)=>{"use strict";var UM=ja(),qZ=ti(),rn=T(),LM=ro(),yM=Xs().insertRecords,DM=X(),MM=require("path"),PM=g(),BM=io(),{getBaseSchemaPath:vM}=re(),HM=ai();Qf.exports=qM;async function qM(e){try{let{schema_table:t,attributes:r}=UM(e);LM(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 BM(e.hdb_auth_header,t,r),n=MM.join(vM(),e.schema.toString()),i=await DM.openEnvironment(n,e.table),o=await yM(i,t.hash_attribute,r,e.records,e[rn.CLUSTERING_FLAG]!==!0);try{await HM(e,o)}catch(c){PM.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(qM,"lmdbCreateRecords")});var Zf=h((FZ,Jf)=>{"use strict";var Wf=T(),GM=xu(),FM=ti(),VM=require("fs-extra"),kM=require("path"),{getBaseSchemaPath:xM}=re();Jf.exports=$M;async function $M(e){let t=[{name:e.schema,createddate:Date.now()}],r=new FM(Wf.SYSTEM_SCHEMA_NAME,Wf.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,void 0,t);await GM(r),await VM.mkdirp(kM.join(xM(),e.schema.toString()))}a($M,"lmdbCreateSchema")});var zf=h((VZ,Xf)=>{"use strict";var Eo=class{constructor(t=[],r=[],s=void 0,n=[]){this.deleted=t,this.skipped=r,this.txn_time=s,this.original_records=n}};a(Eo,"DeleteRecordsResponseObject");Xf.exports=Eo});var Ku=h((YZ,tT)=>{"use strict";var jf=X(),$u=Es(),Yu=Qe().LMDB_ERRORS_ENUM,YM=Ke(),eT=g(),kZ=b(),KM=require("lmdb"),QM=zf(),{OVERFLOW_MARKER:xZ,MAX_SEARCH_KEY_LENGTH:$Z}=YM;async function WM(e,t,r){if($u.validateEnv(e),t===void 0)throw new Error(Yu.HASH_ATTRIBUTE_REQUIRED);if(!Array.isArray(r))throw r===void 0?new Error(Yu.IDS_REQUIRED):new Error(Yu.IDS_MUST_BE_ARRAY);try{let s=jf.listDBIs(e);jf.initializeDBIs(e,t,s);let n=new QM,i,o=[],c=[];for(let E=0,d=r.length;E<d;E++)try{i=r[E];let S=e.dbis[t].get(i);if(!S){n.skipped.push(i);continue}let m=e.dbis[t].ifVersion(i,KM.IF_EXISTS,()=>{e.dbis[t].remove(i);for(let R=0;R<s.length;R++){let w=s[R];if(!S.hasOwnProperty(w)||w===t)continue;let U=e.dbis[w],B=S[w];if(B!=null)try{let j=$u.getIndexedValues(B);if(j)for(let k=0,J=j.length;k<J;k++)U.remove(j[k],i)}catch{eT.warn(`cannot delete from attribute: ${w}, ${B}:${i}`)}}});o.push(m),c.push(i),n.original_records.push(S)}catch(S){eT.warn(S),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=$u.getMicroTime(),n}catch(s){throw s}}a(WM,"deleteRecords");tT.exports={deleteRecords:WM}});var oi=h((KZ,sT)=>{"use strict";var sn=b(),JM=Ku(),ZM=X(),XM=require("path"),{getBaseSchemaPath:zM}=re(),jM=ai(),eP=g();sT.exports=tP;async function tP(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 rT([],[]);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=XM.join(zM(),e.schema.toString()),i=await ZM.openEnvironment(n,e.table),o=await JM.deleteRecords(i,s,e.hash_values);try{t===!0&&await jM(e,o)}catch(c){eP.error(`unable to write transaction due to ${c.message}`)}return rT(o.deleted,o.skipped,o.txn_time)}catch(n){throw n}}a(tP,"lmdbDeleteRecords");function rT(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(rT,"createDeleteResponse")});var Wu=h((WZ,nT)=>{"use strict";var rP=T(),QZ=Es();function Qu(e,t){let r=Object.create(null);if(t.length===1&&rP.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(Qu,"parseRow");function sP(e,t,r,s){let n=Qu(r,e);s.push(n)}a(sP,"searchAll");function nP(e,t,r,s){let n=Qu(r,e);s[t]=n}a(nP,"searchAllToMap");function iP(e,t,r){r[e]===void 0&&(r[e]=[]),r[e].push(t)}a(iP,"iterateDBI");function hs(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(hs,"pushResults");function aP(e,t,r,s,n,i){t.toString().endsWith(e)&&hs(t,r,s,n,i)}a(aP,"endsWith");function oP(e,t,r,s,n,i){t.toString().includes(e)&&hs(t,r,s,n,i)}a(oP,"contains");function cP(e,t,r,s,n,i){t>e&&hs(t,r,s,n,i)}a(cP,"greaterThanCompare");function _P(e,t,r,s,n,i){t>=e&&hs(t,r,s,n,i)}a(_P,"greaterThanEqualCompare");function uP(e,t,r,s,n,i){t<e&&hs(t,r,s,n,i)}a(uP,"lessThanCompare");function lP(e,t,r,s,n,i){t<=e&&hs(t,r,s,n,i)}a(lP,"lessThanEqualCompare");nT.exports={parseRow:Qu,searchAll:sP,searchAllToMap:nP,iterateDBI:iP,endsWith:aP,contains:oP,greaterThanCompare:cP,greaterThanEqualCompare:_P,lessThanCompare:uP,lessThanEqualCompare:lP,pushResults:hs}});var nn=h((XZ,uT)=>{"use strict";var Ut=X(),EP=g(),ft=Es(),kr=Ke(),_e=Qe().LMDB_ERRORS_ENUM,JZ=b(),dP=T(),Yt=Wu(),ZZ=require("lmdb"),{OVERFLOW_MARKER:iT,MAX_SEARCH_KEY_LENGTH:hP}=kr,ci={lazy:!0};function aT(e,t,r,s,n=!1,i=void 0,o=void 0){let c=Object.create(null),_=Ut.openDBI(e,r);_[kr.DBI_DEFINITION_NAME].is_hash_attribute&&(t=r);let u=Ju(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(aT,"iterateFullIndex");function _i(e,t,r,s,n,i=!1,o=void 0,c=void 0,_=!1,u=!1){let l=[[],[]],E=Ut.openDBI(e,r),d=Ju(e,t,r);E[kr.DBI_DEFINITION_NAME].is_hash_attribute&&(t=r);let S=i===!0?s:n,m=i===!0?n:s,R=i===!0?!_:!u,w=i===!0?u:_;for(let{key:U,value:B}of E.getRange({start:m,end:S,reverse:i,limit:o,offset:c,inclusiveEnd:R,exclusiveStart:w}))Yt.pushResults(d(U,B),B,l,t,r);return l}a(_i,"iterateRangeBetween");function Ju(e,t,r){let s;return function(n,i){if(typeof n=="string"&&n.endsWith(iT)){if(!s)if(t)s=Ut.openDBI(e,t);else{let c=Ut.listDBIs(e);for(let _=0,u=c.length;_<u&&(s=Ut.openDBI(e,c[_]),!s[kr.DBI_DEFINITION_NAME].is_hash_attribute);_++);}n=s.get(i,ci)[r]}return n}}a(Ju,"getOverflowCheck");function SP(e,t,r,s=!1,n=void 0,i=void 0){if(ft.validateEnv(e),t===void 0)throw new Error(_e.HASH_ATTRIBUTE_REQUIRED);ho(r),r=ui(e,r);let o=[],c=Ut.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}))Yt.searchAll(r,_,u,o);return o}a(SP,"searchAll");function fP(e,t,r,s=!1,n=void 0,i=void 0){if(ft.validateEnv(e),t===void 0)throw new Error(_e.HASH_ATTRIBUTE_REQUIRED);return ho(r),r=ui(e,r),aT(e,t,t,Yt.searchAllToMap.bind(null,r),s,n,i)}a(fP,"searchAllToMap");function TP(e,t,r=!1,s=void 0,n=void 0){if(ft.validateEnv(e),t===void 0)throw new Error(_e.ATTRIBUTE_REQUIRED);return aT(e,void 0,t,Yt.iterateDBI,r,s,n)}a(TP,"iterateDBI");function mP(e,t){if(ft.validateEnv(e),t===void 0)throw new Error(_e.HASH_ATTRIBUTE_REQUIRED);return Ut.statDBI(e,t).entryCount}a(mP,"countAll");function RP(e,t,r,s,n=!1,i=void 0,o=void 0){xr(e,r,s);let c=Ut.openDBI(e,r);s=ft.convertKeyValueToWrite(s);let _=[[],[]];if(c[kr.DBI_DEFINITION_NAME].is_hash_attribute){t=r;let u=c.get(s,ci);u!==void 0&&Yt.pushResults(s,u,_,t,r)}else for(let u of c.getValues(s,{reverse:n,limit:i,offset:o}))Yt.pushResults(s,u,_,t,r);return _}a(RP,"equals");function AP(e,t,r){return xr(e,t,r),Ut.openDBI(e,t).getValuesCount(r)}a(AP,"count");function pP(e,t,r,s,n=!1,i=void 0,o=void 0){xr(e,r,s);let c=[[],[]],_=Ut.openDBI(e,r);_[kr.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))Yt.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))Yt.pushResults(l,E,c,t,r);else if(u===!0)break;return c}a(pP,"startsWith");function OP(e,t,r,s,n=!1,i=void 0,o=void 0){return oT(e,t,r,s,n,i,o,!0)}a(OP,"endsWith");function oT(e,t,r,s,n=!1,i=void 0,o=void 0,c=!1){xr(e,r,s);let _=[[],[]],u=Ut.openDBI(e,r);u[kr.DBI_DEFINITION_NAME].is_hash_attribute&&(t=r);let l=Ju(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 S=d.toString();if(S.endsWith(iT))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?S.endsWith(s):S.includes(s))if(u[kr.DBI_DEFINITION_NAME].is_hash_attribute)E(d,d);else for(let m of u.getValues(d))E(d,m)}function E(d,S){if(o>0){o--;return}i!==0&&(Yt.pushResults(d,S,_,t,r),i--)}return a(E,"found_match"),_}a(oT,"contains");function NP(e,t,r,s,n=!1,i=void 0,o=void 0){xr(e,r,s);let c=typeof s,_;return c==="string"?_="\uFFFF":c==="number"?_=1/0:c==="boolean"&&(_=!0),_i(e,t,r,s,_,n,i,o,!0,!1)}a(NP,"greaterThan");function gP(e,t,r,s,n=!1,i=void 0,o=void 0){xr(e,r,s);let c=typeof s,_;return c==="string"?_="\uFFFF":c==="number"?_=1/0:c==="boolean"&&(_=!0),_i(e,t,r,s,_,n,i,o,!1,!1)}a(gP,"greaterThanEqual");function IP(e,t,r,s,n=!1,i=void 0,o=void 0){xr(e,r,s);let c=typeof s,_;return c==="string"?_="\0":c==="number"?_=-1/0:c==="boolean"&&(_=!1),_i(e,t,r,_,s,n,i,o,!1,!0)}a(IP,"lessThan");function bP(e,t,r,s,n=!1,i=void 0,o=void 0){xr(e,r,s);let c=typeof s,_;return c==="string"?_="\0":c==="number"?_=-1/0:c==="boolean"&&(_=!1),_i(e,t,r,_,s,n,i,o,!1,!1)}a(bP,"lessThanEqual");function CP(e,t,r,s,n,i=!1,o=void 0,c=void 0){if(ft.validateEnv(e),r===void 0)throw new Error(_e.ATTRIBUTE_REQUIRED);if(s===void 0)throw new Error(_e.START_VALUE_REQUIRED);if(n===void 0)throw new Error(_e.END_VALUE_REQUIRED);if(s=ft.convertKeyValueToWrite(s),n=ft.convertKeyValueToWrite(n),s>n)throw new Error(_e.END_VALUE_MUST_BE_GREATER_THAN_START_VALUE);return _i(e,t,r,s,n,i,o,c)}a(CP,"between");function wP(e,t,r,s){if(ft.validateEnv(e),t===void 0)throw new Error(_e.HASH_ATTRIBUTE_REQUIRED);if(ho(r),r=ui(e,r),s===void 0)throw new Error(_e.ID_REQUIRED);let n=null,i=e.dbis[t].get(s,r.length<3?ci:void 0);return i&&(n=Yt.parseRow(i,r)),n}a(wP,"searchByHash");function UP(e,t,r){if(ft.validateEnv(e),t===void 0)throw new Error(_e.HASH_ATTRIBUTE_REQUIRED);if(r===void 0)throw new Error(_e.ID_REQUIRED);let s=!0;return e.dbis[t].get(r,ci)===void 0&&(s=!1),s}a(UP,"checkHashExists");function LP(e,t,r,s,n=[]){_T(e,t,r,s,n);let i=cT(e,t,r,s,n);return Object.values(i)}a(LP,"batchSearchByHash");function yP(e,t,r,s,n=[]){return _T(e,t,r,s,n),cT(e,t,r,s,n)}a(yP,"batchSearchByHashToMap");function cT(e,t,r,s,n=[]){r=ui(e,r);let i=Object.create(null),o=r.length<3?ci: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=Yt.parseRow(u,r);i[_]=l}else n.push(_)}catch(u){throw EP.warn(u),u}}return i}a(cT,"batchHashSearch");function _T(e,t,r,s,n){if(ft.validateEnv(e),t===void 0)throw new Error(_e.HASH_ATTRIBUTE_REQUIRED);if(ho(r),!Array.isArray(s))throw s===void 0?new Error(_e.IDS_REQUIRED):new Error(_e.IDS_MUST_BE_ARRAY);Array.isArray(n)||(n=[])}a(_T,"initializeBatchSearchByHash");function ho(e){if(!Array.isArray(e))throw e===void 0?new Error(_e.FETCH_ATTRIBUTES_REQUIRED):new Error(_e.FETCH_ATTRIBUTES_MUST_BE_ARRAY)}a(ho,"validateFetchAttributes");function xr(e,t,r){if(ft.validateEnv(e),t===void 0)throw new Error(_e.ATTRIBUTE_REQUIRED);if(r===void 0)throw new Error(_e.SEARCH_VALUE_REQUIRED);if(r?.length>hP)throw new Error(_e.SEARCH_VALUE_TOO_LARGE)}a(xr,"validateComparisonFunctions");function ui(e,t){return t.length===1&&dP.SEARCH_WILDCARDS.indexOf(t[0])>=0&&(t=Ut.listDBIs(e)),t}a(ui,"setGetWholeRowAttributes");uT.exports={searchAll:SP,searchAllToMap:fP,count:AP,countAll:mP,equals:RP,startsWith:pP,endsWith:OP,contains:oT,searchByHash:wP,setGetWholeRowAttributes:ui,batchSearchByHash:LP,batchSearchByHashToMap:yP,checkHashExists:UP,iterateDBI:TP,greaterThan:NP,greaterThanEqual:gP,lessThan:IP,lessThanEqual:bP,between:CP}});var li=h((jZ,hT)=>{var lT=require("lodash"),ET=de(),Q=require("joi"),DP=b(),{hdb_schema_table:Kt,checkValidTable:dT}=Rr(),{handleHDBError:MP,hdb_errors:PP}=D(),{HTTP_STATUS_CODES:BP}=PP,zZ=Q.object({schema:Kt,table:Kt,hash_values:Q.array().min(1).items(Q.alternatives(Q.string(),Q.number())).required(),get_attributes:Q.array().min(1).items(Kt).required()}),vP=Q.object({schema:Kt,table:Kt,search_attribute:Kt,search_value:Q.any().required(),get_attributes:Q.array().min(1).items(Kt).required(),desc:Q.bool(),limit:Q.number().integer().min(1),offset:Q.number().integer().min(0)}),HP=Q.object({schema:Kt,table:Kt,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(Kt).required(),conditions:Q.array().min(1).items(Q.object({search_attribute:Kt,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()});hT.exports=function(e,t){let r=null;switch(t){case"value":r=ET.validateBySchema(e,vP);break;case"hashes":let i=function(o){n?n+=". "+o:n=o};var s=i;a(i,"addError");let n;i(dT("schema",e.schema)),i(dT("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=ET.validateBySchema(e,HP);break;default:throw new Error(`Error validating search, unknown type: ${t}`)}if(!r&&e.schema!=="system"){let n=DP.checkGlobalSchemaTable(e.schema,e.table);if(n)return MP(new Error,n,BP.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 _=lT.filter(c,u=>u!=="*"&&u.attribute!=="*"&&!lT.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 Zu=h((eX,ST)=>{"use strict";var qP=X(),GP=li(),FP=require("path"),{getBaseSchemaPath:VP}=re();ST.exports=kP;function kP(e){let t=GP(e,"hashes");if(t)throw t;let r=FP.join(VP(),e.schema.toString());return qP.openEnvironment(r,e.table)}a(kP,"initialize")});var Xu=h((tX,fT)=>{"use strict";var xP=nn(),$P=Zu();fT.exports=YP;async function YP(e){try{let t=await $P(e),r=global.hdb_schema[e.schema][e.table];return xP.batchSearchByHashToMap(t,r.hash_attribute,e.get_attributes,e.hash_values)}catch(t){throw t}}a(YP,"lmdbGetDataByHash")});var Ss=h((rX,TT)=>{"use strict";var So=class{constructor(t,r,s,n){this.schema=t,this.table=r,this.hash_values=s,this.get_attributes=n}};a(So,"SearchByHashObject");TT.exports=So});var RT=h((nX,mT)=>{"use strict";var sX=Ss(),KP=nn(),QP=Zu();mT.exports=WP;async function WP(e){try{let t=await QP(e),r=global.hdb_schema[e.schema][e.table];return KP.batchSearchByHash(t,r.hash_attribute,e.get_attributes,e.hash_values)}catch(t){throw t}}a(WP,"lmdbSearchByHash")});var Qt=h((iX,AT)=>{"use strict";var fo=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(fo,"SearchObject");AT.exports=fo});var To=h((aX,IT)=>{"use strict";var Je=nn(),JP=X(),ZP=require("path"),XP=b(),L=Ke(),fs=T(),{getBaseSchemaPath:zP}=re(),jP=ls(),pT=Qe().LMDB_ERRORS_ENUM,{compareKeys:an}=require("ordered-binary"),pr=fs.SEARCH_WILDCARDS;async function eB(e,t,r){let s;e.schema===fs.SYSTEM_SCHEMA_NAME?s=jP[e.table]:s=global.hdb_schema[e.schema][e.table];let n=gT(e,s.hash_attribute,r,t);return OT(e,n,s.hash_attribute,r)}a(eB,"prepSearch");async function OT(e,t,r,s){let n=ZP.join(zP(),e.schema.toString()),i=await JP.openEnvironment(n,e.table),o=NT(i,e,t,r);if([L.SEARCH_TYPES.BATCH_SEARCH_BY_HASH,L.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP,L.SEARCH_TYPES.SEARCH_ALL,L.SEARCH_TYPES.SEARCH_ALL_TO_MAP].indexOf(t)>=0)return o;if(sB(e,r)===!1)return s===!0?rB(o):o[1];let _=o[0];return s===!0?Je.batchSearchByHashToMap(i,r,e.get_attributes,_):Je.batchSearchByHash(i,r,e.get_attributes,_)}a(OT,"executeSearch");function NT(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 L.SEARCH_TYPES.EQUALS:n=Je.equals(e,i,t.search_attribute,t.search_value,o,c,_);break;case L.SEARCH_TYPES.CONTAINS:n=Je.contains(e,i,t.search_attribute,t.search_value,o,c,_);break;case L.SEARCH_TYPES.ENDS_WITH:case L.SEARCH_TYPES._ENDS_WITH:n=Je.endsWith(e,i,t.search_attribute,t.search_value,o,c,_);break;case L.SEARCH_TYPES.STARTS_WITH:case L.SEARCH_TYPES._STARTS_WITH:n=Je.startsWith(e,i,t.search_attribute,t.search_value,o,c,_);break;case L.SEARCH_TYPES.BATCH_SEARCH_BY_HASH:return Je.batchSearchByHash(e,t.search_attribute,t.get_attributes,[t.search_value]);case L.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP:return Je.batchSearchByHashToMap(e,t.search_attribute,t.get_attributes,[t.search_value]);case L.SEARCH_TYPES.SEARCH_ALL:return Je.searchAll(e,s,t.get_attributes,o,c,_);case L.SEARCH_TYPES.SEARCH_ALL_TO_MAP:return Je.searchAllToMap(e,s,t.get_attributes,o,c,_);case L.SEARCH_TYPES.BETWEEN:n=Je.between(e,i,t.search_attribute,t.search_value,t.end_value,o,c,_);break;case L.SEARCH_TYPES.GREATER_THAN:case L.SEARCH_TYPES._GREATER_THAN:n=Je.greaterThan(e,i,t.search_attribute,t.search_value,o,c,_);break;case L.SEARCH_TYPES.GREATER_THAN_EQUAL:case L.SEARCH_TYPES._GREATER_THAN_EQUAL:n=Je.greaterThanEqual(e,i,t.search_attribute,t.search_value,o,c,_);break;case L.SEARCH_TYPES.LESS_THAN:case L.SEARCH_TYPES._LESS_THAN:n=Je.lessThan(e,i,t.search_attribute,t.search_value,o,c,_);break;case L.SEARCH_TYPES.LESS_THAN_EQUAL:case L.SEARCH_TYPES._LESS_THAN_EQUAL:n=Je.lessThanEqual(e,i,t.search_attribute,t.search_value,o,c,_);break;default:return Object.create(null)}return n}a(NT,"searchByType");function tB(e){let t=e.search_type,r=e.search_attribute,s=e.search_value;switch(t){case L.SEARCH_TYPES.EQUALS:return n=>n[r]===s;case L.SEARCH_TYPES.CONTAINS:return n=>typeof n[r]=="string"&&n[r].includes(s);case L.SEARCH_TYPES.ENDS_WITH:case L.SEARCH_TYPES._ENDS_WITH:return n=>typeof n[r]=="string"&&n[r].endsWith(s);case L.SEARCH_TYPES.STARTS_WITH:case L.SEARCH_TYPES._STARTS_WITH:return n=>typeof n[r]=="string"&&n[r].startsWith(s);case L.SEARCH_TYPES.BETWEEN:return n=>{let i=n[r];return an(i,s[0])>=0&&an(i,s[1])<=0};case L.SEARCH_TYPES.GREATER_THAN:case L.SEARCH_TYPES._GREATER_THAN:return n=>an(n[r],s)>0;case L.SEARCH_TYPES.GREATER_THAN_EQUAL:case L.SEARCH_TYPES._GREATER_THAN_EQUAL:return n=>an(n[r],s)>=0;case L.SEARCH_TYPES.LESS_THAN:case L.SEARCH_TYPES._LESS_THAN:return n=>an(n[r],s)<0;case L.SEARCH_TYPES.LESS_THAN_EQUAL:case L.SEARCH_TYPES._LESS_THAN_EQUAL:return n=>an(n[r],s)<=0;default:return Object.create(null)}}a(tB,"filterByType");function rB(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(rB,"createMapFromArrays");function sB(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(sB,"checkToFetchMore");function gT(e,t,r,s){if(XP.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),pr.indexOf(n)>-1)return r===!0?L.SEARCH_TYPES.SEARCH_ALL_TO_MAP:L.SEARCH_TYPES.SEARCH_ALL;if(n.indexOf(pr[0])<0&&n.indexOf(pr[1])<0)return c===!0?r===!0?L.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP:L.SEARCH_TYPES.BATCH_SEARCH_BY_HASH:L.SEARCH_TYPES.EQUALS;if(pr.indexOf(i)>=0&&pr.indexOf(o)>=0)return e.search_value=e.search_value.slice(1,-1),L.SEARCH_TYPES.CONTAINS;if(pr.indexOf(i)>=0)return e.search_value=e.search_value.substr(1),L.SEARCH_TYPES.ENDS_WITH;if(pr.indexOf(o)>=0)return e.search_value=e.search_value.slice(0,-1),L.SEARCH_TYPES.STARTS_WITH;if(n.includes(pr[0])||n.includes(pr[1]))return L.SEARCH_TYPES.EQUALS;throw new Error(pT.UNKNOWN_SEARCH_TYPE)}else switch(s){case fs.VALUE_SEARCH_COMPARATORS.BETWEEN:return L.SEARCH_TYPES.BETWEEN;case fs.VALUE_SEARCH_COMPARATORS.GREATER:return L.SEARCH_TYPES.GREATER_THAN;case fs.VALUE_SEARCH_COMPARATORS.GREATER_OR_EQ:return L.SEARCH_TYPES.GREATER_THAN_EQUAL;case fs.VALUE_SEARCH_COMPARATORS.LESS:return L.SEARCH_TYPES.LESS_THAN;case fs.VALUE_SEARCH_COMPARATORS.LESS_OR_EQ:return L.SEARCH_TYPES.LESS_THAN_EQUAL;default:throw new Error(pT.UNKNOWN_SEARCH_TYPE)}}a(gT,"createSearchTypeFromSearchObject");IT.exports={executeSearch:OT,createSearchTypeFromSearchObject:gT,prepSearch:eB,searchByType:NT,filterByType:tB}});var CT=h((cX,bT)=>{"use strict";var oX=Qt(),nB=li(),iB=b(),aB=T(),oB=To();bT.exports=cB;async function cB(e,t){if(!iB.isEmpty(t)&&aB.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[t]===void 0)throw new Error(`Value search comparator - ${t} - is not valid`);let s=nB(e,"value");if(s)throw s;let n=!0;try{return await oB.prepSearch(e,t,n)}catch(i){throw i}}a(cB,"lmdbGetDataByValue")});var on=h((uX,wT)=>{"use strict";var _X=Qt(),_B=li(),uB=b(),lB=T(),EB=To();wT.exports=dB;async function dB(e,t){if(!uB.isEmpty(t)&&lB.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[t]===void 0)throw new Error(`Value search comparator - ${t} - is not valid`);let s=_B(e,"value");if(s)throw s;let n=!1;try{return await EB.prepSearch(e,t,n)}catch(i){throw i}}a(dB,"lmdbSearchByValue")});var LT=h((EX,UT)=>{"use strict";var lX=Ke(),mo=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(mo,"SearchByConditionsObject");var Ro=class{constructor(t,r,s){this.search_attribute=t,this.search_type=r,this.search_value=s}};a(Ro,"SearchCondition");var Ao=class{constructor(t,r){this.attribute=t,this.desc=r}};a(Ao,"SortAttribute");UT.exports={SearchByConditionsObject:mo,SearchCondition:Ro,SortAttribute:Ao}});var vT=h((hX,BT)=>{"use strict";var dX=LT().SearchByConditionsObject,hB=Qt(),SB=li(),zu=nn(),po=Ke(),PT=To(),fB=Wu(),yT=require("lodash"),{getBaseSchemaPath:TB}=re(),mB=require("path"),RB=X(),{handleHDBError:DT,hdb_errors:AB}=D(),{HTTP_STATUS_CODES:pB}=AB,OB=1e8,NB={lazy:!0};BT.exports=gB;async function gB(e){try{let t=SB(e,"conditions");if(t)throw DT(t,t.message,pB.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=mB.join(TB(),e.schema.toString()),s=await RB.openEnvironment(r,e.table),n=global.hdb_schema[e.schema][e.table],i=yT.sortBy(e.conditions,o=>{if(o.estimated_count===void 0){let c=o.search_type;c===po.SEARCH_TYPES.EQUALS?o.estimated_count=zu.count(s,o.search_attribute,o.search_value):c===po.SEARCH_TYPES.CONTAINS||c===po.SEARCH_TYPES.ENDS_WITH?o.estimated_count=1/0:o.estimated_count=OB}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(PT.filterByType),u=_.length,l=[],E=zu.setGetWholeRowAttributes(s,e.get_attributes),d=e.offset>-1?e.offset:0,S=e.limit>-1?e.limit:1/0;e:for(let m of o){let R=c.get(m,NB);for(let w=0;w<u;w++)if(!_[w](R))continue e;if(d>0){d--;continue}if(S<=0)break;S--,l.push(fB.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=yT.union(...c),e.limit>0||e.offset>0){let _=Number.isInteger(e.limit)?e.limit:o.length;o=o.splice(e.offset,_)}return zu.batchSearchByHash(s,n.hash_attribute,e.get_attributes,o)}}catch(t){throw DT(t)}}a(gB,"lmdbSearchByConditions");async function MT(e,t,r,s){let n=new hB(t.schema,t.table,void 0,void 0,s,t.get_attributes),i=r.search_type;return n.search_attribute=r.search_attribute,i===po.SEARCH_TYPES.BETWEEN?(n.search_value=r.search_value[0],n.end_value=r.search_value[1]):n.search_value=r.search_value,PT.searchByType(e,n,i,s)}a(MT,"executeConditionSearch")});var Ei=h((SX,HT)=>{"use strict";var IB=T().OPERATIONS_ENUM,Oo=class{constructor(t,r,s,n=void 0){this.operation=IB.DELETE,this.schema=t,this.table=r,this.hash_values=s,this.__origin=n}};a(Oo,"DeleteObject");HT.exports=Oo});var ju=h((fX,qT)=>{"use strict";var No=class{constructor(t,r,s){this.schema=t,this.table=r,this.attribute=s}};a(No,"DropAttributeObject");qT.exports=No});var tl=h((mX,GT)=>{"use strict";var bB=Qt(),CB=Ei(),TX=ju(),tr=T(),wB=b(),el=X(),UB=ls(),LB=on(),yB=oi(),{getBaseSchemaPath:DB}=re(),MB=require("path");GT.exports=PB;async function PB(e,t=!0){let r;e.schema===tr.SYSTEM_SCHEMA_NAME?r=UB[e.table]:r=global.hdb_schema[e.schema][e.table];let s=await vB(e),n=MB.join(DB(),e.schema.toString()),i=await el.openEnvironment(n,e.table);return t===!0&&await BB(e,i,r.hash_attribute),el.dropDBI(i,e.attribute),s}a(PB,"lmdbDropAttribute");async function BB(e,t,r){let s=el.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(BB,"removeAttributeFromAllObjects");async function vB(e){let t=new bB(tr.SYSTEM_SCHEMA_NAME,tr.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,tr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_TABLE_KEY,`${e.schema}.${e.table}`,void 0,[tr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY,tr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ATTRIBUTE_KEY]),s=(await LB(t)).filter(o=>o[tr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ATTRIBUTE_KEY]===e.attribute);if(wB.isEmptyOrZeroLength(s))throw new Error(`Attribute '${e.attribute}' was not found in '${e.schema}.${e.table}'`);let n=s.map(o=>o[tr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),i=new CB(tr.SYSTEM_SCHEMA_NAME,tr.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,n);return yB(i)}a(vB,"dropAttributeFromSystem")});var xT=h((RX,kT)=>{"use strict";var HB=tl(),qB=ju(),FT=b(),VT=g(),GB=Qe().LMDB_ERRORS_ENUM;kT.exports=FB;async function FB(e){if(FT.isEmpty(global.hdb_schema[e.schema])||FT.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 qB(e.schema,e.table,r);try{await HB(n,!1)}catch(i){i.message!==GB.DBI_DOES_NOT_EXIST&&VT.error(`unable to drop attribute ${e.schema}.${e.table}.${r}:`+i)}}}catch(s){throw VT.error(`Error dropping attribute ${r}`),s}}a(FB,"lmdbDropAllAttributes")});var rl=h((pX,zT)=>{"use strict";var WT=Qt(),JT=Ei(),ZT=on(),XT=oi(),AX=xT(),ot=T(),$T=b(),YT=X(),{getBaseSchemaPath:VB,getTransactionAuditStorePath:kB}=re(),KT=require("path"),QT=g();zT.exports=xB;async function xB(e){try{if($T.isEmpty(global.hdb_schema[e.schema])||$T.isEmpty(global.hdb_schema[e.schema][e.table]))throw new Error(`unknown schema:${e.schema} and table ${e.table}`);await $B(e),await YB(e);let t=KT.join(VB(),e.schema.toString());try{await YT.deleteEnvironment(t,e.table)}catch(r){if(r.message==="invalid environment")QT.warn(`cannot delete environment for ${e.schema}.${e.table}, environment not found`);else throw r}try{let r=KT.join(kB(),e.schema.toString());await YT.deleteEnvironment(r,e.table,!0)}catch(r){if(r.message==="invalid environment")QT.warn(`cannot delete environment for ${e.schema}.${e.table}, environment not found`);else throw r}}catch(t){throw t}}a(xB,"lmdbDropTable");async function $B(e){let t=new WT(ot.SYSTEM_SCHEMA_NAME,ot.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,ot.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_TABLE_KEY,`${e.schema}.${e.table}`,void 0,[ot.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),r=await ZT(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 JT(ot.SYSTEM_SCHEMA_NAME,ot.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,s);await XT(n)}a($B,"deleteAttributesFromSystem");async function YB(e){let t=new WT(ot.SYSTEM_SCHEMA_NAME,ot.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,ot.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY,e.table,void 0,[ot.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY,ot.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_KEY,ot.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),r,s;try{r=await ZT(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 JT(ot.SYSTEM_SCHEMA_NAME,ot.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,[s.id]);try{await XT(n)}catch(i){throw i}}a(YB,"dropTableFromSystem")});var em=h((NX,jT)=>{"use strict";var KB=require("fs-extra"),QB=Qt(),WB=Ss(),JB=Ei(),ZB=rl(),XB=oi(),zB=Xu(),jB=on(),Or=T(),OX=b(),ev=require("path"),{getBaseSchemaPath:tv}=re(),{handleHDBError:rv,hdb_errors:sv}=D(),{HDB_ERROR_MSGS:nv,HTTP_STATUS_CODES:iv}=sv;jT.exports=av;async function av(e){let t;try{t=await ov(e.schema);let r=new QB(Or.SYSTEM_SCHEMA_NAME,Or.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,Or.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_KEY,t,void 0,[Or.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY]),s=await jB(r);for(let o=0;o<s.length;o++){let c={schema:t,table:s[o].name};try{await ZB(c)}catch(_){if(_.message!=="invalid environment")throw _}}let n=new JB(Or.SYSTEM_SCHEMA_NAME,Or.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,[t]);await XB(n);let i=ev.join(tv(),t.toString());await KB.remove(i)}catch(r){throw r}}a(av,"lmdbDropSchema");async function ov(e){let t=new WB(Or.SYSTEM_SCHEMA_NAME,Or.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,[e],[Or.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY]),r,s;try{r=await zB(t)}catch(n){throw n}for(let n in r)r[n].name===e&&(s=e);if(!s)throw rv(new Error,nv.SCHEMA_NOT_FOUND(e),iv.NOT_FOUND,void 0,void 0,!0);return s}a(ov,"validateDropSchema")});var sl=h((gX,tm)=>{"use strict";var go=class{constructor(t,r,s){this.schema=t,this.table=r,this.hash_attribute=s}};a(go,"CreateTableObject");tm.exports=go});var sm=h((bX,rm)=>{"use strict";var cv=require("path"),_v=require("fs-extra"),Io=X(),{getTransactionAuditStorePath:uv}=re(),nl=Ke(),IX=sl();rm.exports=lv;async function lv(e){let t;try{let r=cv.join(uv(),e.schema.toString());await _v.mkdirp(r),t=await Io.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{Io.createDBI(t,nl.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,!1,!0),Io.createDBI(t,nl.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE,!0,!1),Io.createDBI(t,nl.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(lv,"createTransactionsAuditEnvironment")});var om=h((CX,am)=>{"use strict";var il=T(),nm=X(),Ev=Xs(),dv=require("path"),{getSystemSchemaPath:hv,getBaseSchemaPath:Sv}=re(),fv=ls(),Tv=za(),al=Xa(),mv=g(),Rv=sm(),cl=fv.hdb_table,im=[];for(let e=0;e<cl.attributes.length;e++)im.push(cl.attributes[e].attribute);am.exports=Av;async function Av(e,t){let r=dv.join(Sv(),t.schema.toString()),s=new al(t.schema,t.table,il.TIME_STAMP_NAMES_ENUM.CREATED_TIME,void 0,!0),n=new al(t.schema,t.table,il.TIME_STAMP_NAMES_ENUM.UPDATED_TIME,void 0,!0),i=new al(t.schema,t.table,t.hash_attribute,void 0,!1,!0);try{if(await nm.createEnvironment(r,t.table),e!==void 0){let o=await nm.openEnvironment(hv(),il.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME);await Ev.insertRecords(o,cl.hash_attribute,im,[e]),await ol(s),await ol(n),await ol(i)}await Rv(t)}catch(o){throw o}}a(Av,"lmdbCreateTable");async function ol(e){try{await Tv(e)}catch(t){mv.warn(`failed to create attribute ${e.attribute} due to ${t.message}`)}}a(ol,"createAttribute")});var _m=h((wX,cm)=>{"use strict";var pv=ja(),Ov=ro(),Nv=io(),cn=T(),gv=Xs().updateRecords,Iv=X(),bv=require("path"),{getBaseSchemaPath:Cv}=re(),wv=ai(),Uv=g();cm.exports=Lv;async function Lv(e){try{let{schema_table:t,attributes:r}=pv(e);Ov(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 Nv(e.hdb_auth_header,t,r),n=bv.join(Cv(),e.schema.toString()),i=await Iv.openEnvironment(n,e.table),o=await gv(i,t.hash_attribute,r,e.records,e[cn.CLUSTERING_FLAG]!==!0);try{await wv(e,o)}catch(c){Uv.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(Lv,"lmdbUpdateRecords")});var lm=h((UX,um)=>{"use strict";var yv=T().OPERATIONS_ENUM,bo=class{constructor(t,r,s,n=void 0){this.operation=yv.UPSERT,this.schema=t,this.table=r,this.records=s,this.__origin=n}};a(bo,"UpsertObject");um.exports=bo});var dm=h((yX,Em)=>{"use strict";var LX=lm(),Dv=ja(),Mv=ro(),Pv=io(),_n=T(),Bv=Xs().upsertRecords,vv=X(),Hv=require("path"),{getBaseSchemaPath:qv}=re(),Gv=ai(),Fv=g(),{handleHDBError:Vv,hdb_errors:kv}=D();Em.exports=xv;async function xv(e){let t;try{t=Dv(e)}catch(_){throw Vv(_,_.message,kv.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0)}let{schema_table:r,attributes:s}=t;Mv(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 Pv(e.hdb_auth_header,r,s),i=Hv.join(qv(),e.schema.toString()),o=await vv.openEnvironment(i,e.table),c=await Bv(o,r.hash_attribute,s,e.records,e[_n.CLUSTERING_FLAG]!==!0);try{await Gv(e,c)}catch(_){Fv.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(xv,"lmdbUpsertRecords")});var Rm=h((DX,mm)=>{"use strict";var $v=Qt(),hm=b(),Sm=g(),Yv=on(),fm=T(),Kv=Ku().deleteRecords,Qv=X(),Wv=require("path"),{getBaseSchemaPath:Jv}=re(),{promisify:Zv}=require("util"),Xv=Zv(setTimeout),Tm=1e4,zv=10;mm.exports=jv;async function jv(e){let t=global.hdb_schema[e.schema][e.table].hash_attribute;if(hm.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 $v(e.schema,e.table,fm.TIME_STAMP_NAMES_ENUM.CREATED_TIME,r,void 0,[t]);s=await Yv(n,fm.VALUE_SEARCH_COMPARATORS.LESS)}catch(n){throw Sm.error(`Error searching for date: ${e.date} in schema: ${e.schema} table: ${e.table}`),n}return hm.isEmptyOrZeroLength(s)?(Sm.trace("No records found to delete"),{message:"No records found to delete"}):await eH(e,s,t)}a(jv,"lmdbDeleteRecordsBefore");async function eH(e,t,r){let s=Wv.join(Jv(),e.schema.toString()),n=await Qv.openEnvironment(s,e.table),i={message:"",deleted_hashes:[],skipped_hashes:[]};for(let o=0,c=t.length;o<c;o+=Tm){let _=t.slice(o,o+Tm),u=[];for(let l=0,E=_.length;l<E;l++)u.push(_[l][r]);try{let l=await Kv(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 Xv(zv)}return i.message=`${i.deleted_hashes.length} of ${i.deleted_hashes.length+i.skipped_hashes.length} records successfully deleted`,i}a(eH,"chunkDeletes")});var pm=h((MX,Am)=>{"use strict";var Co=class{constructor(t,r,s){this.schema=t,this.table=r,this.timestamp=s}};a(Co,"DeleteBeforeObject");Am.exports=Co});var Nm=h((PX,Om)=>{"use strict";var wo=class{constructor(t=void 0,r=void 0,s=0){this.start_timestamp=t,this.end_timestamp=r,this.transactions_deleted=s}};a(wo,"DeleteAuditLogsBeforeResults");Om.exports=wo});var bm=h((vX,Im)=>{"use strict";var _l=X(),{getTransactionAuditStorePath:tH}=re(),BX=pm(),rH=require("path"),di=Ke(),sH=b(),gm=Nm(),nH=require("util").promisify,iH=nH(setTimeout),aH=1e4,oH=100;Im.exports=cH;async function cH(e){let t=rH.join(tH(),e.schema),r=await _l.openEnvironment(t,e.table,!0),s=_l.listDBIs(r);_l.initializeDBIs(r,di.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,s);let n,i=new gm;do n=await _H(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 iH(oH);while(n.transactions_deleted>0);return i}a(cH,"deleteAuditLogsBefore");async function _H(e,t){let r=new gm;try{let s=e.dbis[di.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[di.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME];sH.isEmpty(c)||(n=e.dbis[di.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].remove(c,i));for(let _=0;_<o.hash_values.length;_++)n=e.dbis[di.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE].remove(o.hash_values[_],i);if(r.transactions_deleted++,r.end_timestamp=i,r.transactions_deleted>aH)break}return await n,r}catch(s){throw s}}a(_H,"deleteTransactions")});var Mm=h((HX,Dm)=>{"use strict";var ul=X(),un=Ke(),Cm=Es(),ll=T(),wm=b(),{getTransactionAuditStorePath:uH}=re(),lH=require("path"),EH=nn(),Uo=en(),dH=g();Dm.exports=hH;async function hH(e){let t=lH.join(uH(),e.schema),r=await ul.openEnvironment(t,e.table,!0),s=ul.listDBIs(r);ul.initializeDBIs(r,un.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,s);let n;switch(e.search_type){case ll.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.TIMESTAMP:return Um(r,e.search_values);case ll.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.HASH_VALUE:return n=global.hdb_schema[e.schema][e.table].hash_attribute,fH(r,e.search_values,n);case ll.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.USERNAME:return SH(r,e.search_values);default:return Um(r)}}a(hH,"readAuditLog");function Um(e,t=[0,Cm.getMicroTime()]){wm.isEmpty(t[0])&&(t[0]=0),wm.isEmpty(t[1])&&(t[1]=Cm.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 Uo,i);r.push(o)}return r}catch(s){throw s}}a(Um,"searchTransactionsByTimestamp");function SH(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,ym(e,i))}return Object.fromEntries(r)}a(SH,"searchTransactionsByUsername");function fH(e,t,r){let s=new Map;for(let c=0,_=t.length;c<_;c++){let u=t[c],l=EH.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 S=l[0][E],m=Number(S);s.has(m)?s.get(m).push(u.toString()):s.set(m,[u.toString()])}}let n=Array.from(s.keys()),i=ym(e,n),o=new Map;for(let c=0;c<i.length;c++){let _=i[c],u=_.timestamp,l=s.get(u);Lm(_,"records",r,l,o),Lm(_,"original_records",r,l,o)}return Object.fromEntries(o)}a(fH,"searchTransactionsByHashValues");function Lm(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 Uo(e.operation,e.user_name,i,void 0);E[t]=[c],u.push(E)}}else{let u=new Uo(e.operation,e.user_name,i,void 0);u[t]=[c],n.set(_,[u])}}}a(Lm,"loopRecords");function ym(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 Uo,i);r.push(o)}}catch(i){dH.warn(i)}return r}catch(s){throw s}}a(ym,"batchSearchTransactions")});var Bm=h((qX,Pm)=>{"use strict";var TH=require("path"),{getBaseSchemaPath:mH}=re(),RH=X();Pm.exports={writeTransaction:AH};async function AH(e,t,r){let s=TH.join(mH(),e);return(await RH.openEnvironment(s,t)).transaction(r)}a(AH,"writeTransaction")});var Hm=h((GX,vm)=>{"use strict";var pH=require("path"),{getBaseSchemaPath:OH}=re(),NH=X();vm.exports={flush:gH};async function gH(e,t){let r=pH.join(OH(),e.toString());return(await NH.openEnvironment(r,t.toString())).flushed}a(gH,"flush")});var Gm=h((FX,qm)=>{"use strict";var Ae=g(),{handleHDBError:IH}=D(),bH=pu(),CH=za(),wH=xu(),UH=Zf(),LH=oi(),yH=Xu(),DH=RT(),MH=CT(),PH=on(),BH=vT(),vH=em(),HH=om(),qH=_m(),GH=dm(),FH=Rm(),VH=bm(),kH=rl(),xH=tl(),$H=Mm(),YH=Bm(),KH=Hm(),Lo=class extends bH{async searchByConditions(t){try{return BH(t)}catch(r){throw Ae.error(r),r}}async getDataByHash(t){try{return await yH(t)}catch(r){throw Ae.error(r),r}}async searchByHash(t){try{return await DH(t)}catch(r){throw Ae.error(r),r}}async getDataByValue(t,r){try{return await MH(t,r)}catch(s){throw Ae.error(s),s}}async searchByValue(t){try{return await PH(t)}catch(r){throw Ae.error(r),r}}async createSchema(t){try{return await UH(t)}catch(r){throw Ae.error(r),r}}async dropSchema(t){try{return await vH(t)}catch(r){throw Ae.error(r),r}}async createTable(t,r){try{return await HH(t,r)}catch(s){throw Ae.error(s),s}}async dropTable(t){try{return await kH(t)}catch(r){throw Ae.error(r),r}}async createAttribute(t){try{return await CH(t)}catch(r){throw Ae.error(r),r}}async createRecords(t){try{return await wH(t)}catch(r){throw Ae.error(r),r}}async updateRecords(t){try{return await qH(t)}catch(r){throw Ae.error(r),r}}async upsertRecords(t){try{return await GH(t)}catch(r){throw IH(r,null,null,Ae.ERR,r)}}async deleteRecords(t){try{return await LH(t)}catch(r){throw Ae.error(r),r}}async deleteRecordsBefore(t){try{return await FH(t)}catch(r){throw Ae.error(r),r}}async dropAttribute(t){try{return await xH(t)}catch(r){throw Ae.error(r),r}}async deleteAuditLogsBefore(t){try{return await VH(t)}catch(r){throw Ae.error(r),r}}async readAuditLog(t){try{return await $H(t)}catch(r){throw Ae.error(r),r}}writeTransaction(t,r,s){return YH.writeTransaction(t,r,s)}flush(t,r){return KH.flush(t,r)}};a(Lo,"LMDBBridge");qm.exports=Lo});var Nr=h((VX,Vm)=>{"use strict";var QH=Gm(),WH=pu(),JH=V();JH.initSync();var Fm;function ZH(){return Fm instanceof WH?Fm:new QH}a(ZH,"getBridge");Vm.exports=ZH()});var Ym=h((kX,$m)=>{"use strict";var km=require("lodash"),hi=require("mathjs"),XH=require("jsonata"),xm=b();$m.exports={distinct_array:e=>Array.isArray(e)&&e.length>1?km.uniqWith(e,km.isEqual):e,searchJSON:zH,mad:Si.bind(null,hi.mad),mean:Si.bind(null,hi.mean),mode:Si.bind(null,hi.mode),prod:Si.bind(null,hi.prod),median:Si.bind(null,hi.median)};function Si(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(Si,"aggregateFunction");function zH(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(xm.isEmpty(this.__ala__.res)&&(this.__ala__.res={}),xm.isEmpty(this.__ala__.res[r])){let s=XH(e);this.__ala__.res[r]=s}return this.__ala__.res[r].evaluate(t)}a(zH,"searchJSON")});var Qm=h((xX,Km)=>{"use strict";var he=require("moment"),El="YYYY-MM-DDTHH:mm:ss.SSSZZ";he.suppressDeprecationWarnings=!0;Km.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(El),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(El),offset_utc:(e,t)=>he(e).utc().utcOffset(t).format(El)}});var Xm=h(($X,Zm)=>{"use strict";var jH=require("@turf/area"),eq=require("@turf/length"),tq=require("@turf/circle"),rq=require("@turf/difference"),sq=require("@turf/distance"),nq=require("@turf/boolean-contains"),iq=require("@turf/boolean-equal"),aq=require("@turf/boolean-disjoint"),oq=require("@turf/helpers"),Wm=T(),x=b();Zm.exports={geoArea:cq,geoLength:_q,geoCircle:uq,geoDifference:lq,geoDistance:Jm,geoNear:Eq,geoContains:dq,geoEqual:hq,geoCrosses:Sq,geoConvert:fq};var dl="geo1 is required",hl="geo2 is required";function cq(e){if(x.isEmpty(e))throw new Error("geoJSON is required");return typeof e=="string"&&(e=x.autoCast(e)),jH.default(e)}a(cq,"geoArea");function _q(e,t){if(x.isEmpty(e))throw new Error("geoJSON is required");return typeof e=="string"&&(e=x.autoCast(e)),eq.default(e,{units:t||"kilometers"})}a(_q,"geoLength");function uq(e,t,r){if(x.isEmpty(e))throw new Error("point is required");if(x.isEmpty(t))throw new Error("radius is required");return typeof e=="string"&&(e=x.autoCast(e)),tq.default(e,t,{units:r||"kilometers"})}a(uq,"geoCircle");function lq(e,t){if(x.isEmpty(e))throw new Error("poly1 is required");if(x.isEmpty(t))throw new Error("poly2 is required");return typeof e=="string"&&(e=x.autoCast(e)),typeof t=="string"&&(t=x.autoCast(t)),rq(e,t)}a(lq,"geoDifference");function Jm(e,t,r){if(x.isEmpty(e))throw new Error("point1 is required");if(x.isEmpty(t))throw new Error("point2 is required");return typeof e=="string"&&(e=x.autoCast(e)),typeof t=="string"&&(t=x.autoCast(t)),sq.default(e,t,{units:r||"kilometers"})}a(Jm,"geoDistance");function Eq(e,t,r,s){if(x.isEmpty(e))throw new Error("point1 is required");if(x.isEmpty(t))throw new Error("point2 is required");if(x.isEmpty(r))throw new Error("distance is required");if(typeof e=="string"&&(e=x.autoCast(e)),typeof t=="string"&&(t=x.autoCast(t)),isNaN(r))throw new Error("distance must be a number");return Jm(e,t,s)<=r}a(Eq,"geoNear");function dq(e,t){if(x.isEmpty(e))throw new Error(dl);if(x.isEmpty(e))throw new Error(hl);return typeof e=="string"&&(e=x.autoCast(e)),typeof t=="string"&&(t=x.autoCast(t)),nq.default(e,t)}a(dq,"geoContains");function hq(e,t){if(x.isEmpty(e))throw new Error(dl);if(x.isEmpty(e))throw new Error(hl);return typeof e=="string"&&(e=x.autoCast(e)),typeof t=="string"&&(t=x.autoCast(t)),iq.default(e,t)}a(hq,"geoEqual");function Sq(e,t){if(x.isEmpty(e))throw new Error(dl);if(x.isEmpty(e))throw new Error(hl);return typeof e=="string"&&(e=x.autoCast(e)),typeof t=="string"&&(t=x.autoCast(t)),!aq.default(e,t)}a(Sq,"geoCrosses");function fq(e,t,r){if(x.isEmptyOrZeroLength(e))throw new Error("coordinates is required");if(x.isEmpty(t))throw new Error("geo_type is required");if(x.isEmpty(Wm.GEO_CONVERSION_ENUM[t]))throw new Error(`geo_type of ${t} is invalid please use one of the following types: ${Object.keys(Wm.GEO_CONVERSION_ENUM).join(",")}`);return oq[t](e,r)}a(fq,"geoConvert")});var yo=h((YX,zm)=>{var Ts=Ym(),Tt=Qm(),rr=Xm();zm.exports=e=>{e.aggr.mad=e.aggr.MAD=Ts.mad,e.aggr.mean=e.aggr.MEAN=Ts.mean,e.aggr.mode=e.aggr.MODE=Ts.mode,e.aggr.prod=e.aggr.PROD=Ts.prod,e.aggr.median=e.aggr.MEDIAN=Ts.median,e.fn.distinct_array=e.fn.DISTINCT_ARRAY=Ts.distinct_array,e.fn.search_json=e.fn.SEARCH_JSON=Ts.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=rr.geoArea,e.fn.geocircle=e.fn.GEOCIRCLE=e.fn.geoCircle=rr.geoCircle,e.fn.geocontains=e.fn.GEOCONTAINS=e.fn.geoContains=rr.geoContains,e.fn.geoconvert=e.fn.GEOCONVERT=e.fn.geoConvert=rr.geoConvert,e.fn.geocrosses=e.fn.GEOCROSSES=e.fn.geoCrosses=rr.geoCrosses,e.fn.geodifference=e.fn.GEODIFFERENCE=e.fn.geoDifference=rr.geoDifference,e.fn.geodistance=e.fn.GEODISTANCE=e.fn.geoDistance=rr.geoDistance,e.fn.geoequal=e.fn.GEOEQUAL=e.fn.geoEqual=rr.geoEqual,e.fn.geolength=e.fn.GEOLENGTH=e.fn.geoLength=rr.geoLength,e.fn.geonear=e.fn.GEONEAR=e.fn.geoNear=rr.geoNear}});var tR=h((KX,eR)=>{"use strict";var fi=require("lodash"),Pe=require("alasql");Pe.options.cache=!1;var Tq=yo(),jm=require("clone"),Do=require("recursive-iterator"),v=g(),q=b(),ln=Nr(),mq=T(),{hdb_errors:Rq}=D(),Aq="IS NULL",Ti="There was a problem performing this search. Please check the logs and try again.";Tq(Pe);var Mo=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(Ti)}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(Ti)}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(Ti)}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(Ti)}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(Ti)}}_getColumns(){let t=new Do(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(jm(r)))}_getTables(){let t=[];this.all_table_attributes.forEach(r=>{t.push(r.table)}),this.tables=fi.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 Do(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 Pe.yy.LogicValue({value:s}):r.right instanceof Pe.yy.StringValue&&!q.isEmpty(s)&&q.autoCasterIsNumberCheck(s.toString())&&(r.right=new Pe.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 Pe.yy.LogicValue({value:i}):s instanceof Pe.yy.StringValue&&q.autoCasterIsNumberCheck(i.toString())&&(r.right[n]=new Pe.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 Do(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(mq.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&&fi.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 Pe.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(jm(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(Aq)>-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=fi.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 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 S in d)this.data[i].__merged_data[S]?this._updateMergedAttribute(i,S,n.attribute,d[S][n.attribute]):(this.data[i].__merged_data[S]=[...s[i]],this._updateMergedAttribute(i,S,n.attribute,d[S][n.attribute]),this._setMergedHashAttribute(i,q.autoCast(S)))}))}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 S=l[E];c.search_attribute=S.attribute,c.search_value=S.search_value;let m=await ln.getDataByValue(c,S.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 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,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 Pe.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 Pe.yy.Column;n.columnid=s.as,n.columnid_orig=s.as_orig,t.expression=n}else{t.initial_select_column=Object.assign(new Pe.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 Pe.yy.FuncValue:new Pe.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(S=>{S.joinmode&&S.joinmode!=="INNER"&&(this.has_outer_join=!0),n.push(S.table);let m=S.joinmode+" JOIN ? AS "+(S.as?S.as:S.table.tableid);S.on&&(m+=" ON "+S.on.toString()),i.push(m),t.push(Object.values(this.data[`${S.table.databaseid_orig}_${S.table.as?S.table.as_orig:S.table.tableid_orig}`].__merged_data))});let o=[],c={};n.forEach(S=>{let m=this.data[`${S.databaseid_orig}_${S.as?S.as_orig:S.tableid_orig}`].__hash_name,R=S.as?S.as_orig:S.tableid_orig;o.push({key:`'${R}.${m}'`,schema:S.databaseid_orig,table:S.as?S.as_orig:S.tableid_orig,keys:new Set}),r.push(`${S.as?S.as:S.tableid}.\`${m}\` AS "${R}.${m}"`),c[S.as?S.as_orig:S.tableid_orig]=this.data[`${S.databaseid_orig}_${S.as?S.as_orig:S.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(S=>{S.is_func?r.push(S.initial_select_column.toString()):S.initial_select_column.tableid?r.push(`${S.initial_select_column.tableid}.${S.initial_select_column.columnid} AS ${S.expression.columnid}`):r.push(`${S.initial_select_column.columnid} AS ${S.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 S=`SELECT ${r.join(", ")} FROM ${i.join(" ")} ${_} ${u} ${l} ${E}`,m=this._convertColumnsToIndexes(S,n);d=await Pe.promise(m,t),t=null}catch(S){throw v.error("Error thrown from AlaSQL in SQLSearch class method processJoins."),v.error(S),new Error("There was a problem processing the data.")}if(d&&d.length>0){for(let S=0,m=d.length;S<m;S++){let R=d[S];o.forEach(w=>{R[w.key]!==null&&R[w.key]!==void 0&&w.keys.add(R[w.key])})}o.forEach(S=>{let m=Object.keys(this.data[`${S.schema}_${S.table}`].__merged_data),R=fi.difference(m,[...S.keys].map(w=>w.toString()));for(let w=0,U=R.length;w<U;w++){let B=R[w];delete this.data[`${S.schema}_${S.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 Do(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=fi.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],S=_[d];for(let m=0;m<u;m++){let R=n.columns[m],w=S[R]===void 0?null:S[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 Pe.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(Rq.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(Mo,"SQLSearch");eR.exports=Mo});var mt=h((QX,sR)=>{"use strict";var pq=CS();sR.exports={searchByConditions:Iq,searchByHash:bq,searchByValue:Cq,search:wq};var Sl=Nr(),rR=require("util"),Oq=rR.callbackify(Sl.searchByHash),Nq=rR.callbackify(Sl.searchByValue),gq=tR();async function Iq(e){return Sl.searchByConditions(e)}a(Iq,"searchByConditions");function bq(e,t){try{Oq(e,(r,s)=>{if(r){t(r);return}t(null,s)})}catch(r){return t(r)}}a(bq,"searchByHash");function Cq(e,t){try{e.hasOwnProperty("desc")===!0&&(e.reverse=e.desc),Nq(e,(r,s)=>{if(r){t(r);return}t(null,s)})}catch(r){return t(r)}}a(Cq,"searchByValue");function wq(e,t){try{let r=new pq(e);r.validate(),new gq(r.statement,r.attributes).search().then(n=>{t(null,n)}).catch(n=>{t(n,null)})}catch(r){return t(r)}}a(wq,"search")});var $r=h((WX,oR)=>{"use strict";var mi=require("crypto"),iR="aes-256-cbc",Uq=32,Lq=16,fl=64,aR=32,yq=fl+aR,nR=new Map;oR.exports={encrypt:Dq,decrypt:Mq,createNatsTableStreamName:Pq};function Dq(e){let t=mi.randomBytes(Uq),r=mi.randomBytes(Lq),s=mi.createCipheriv(iR,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(Dq,"encrypt");function Mq(e){let t=e.substr(0,fl),r=e.substr(fl,aR),s=e.substr(yq,e.length),n=Buffer.from(r,"hex"),i=Buffer.from(s,"hex"),o=mi.createDecipheriv(iR,Buffer.from(t,"hex"),n),c=o.update(i);return c=Buffer.concat([c,o.final()]),c.toString()}a(Mq,"decrypt");function Pq(e,t){let r=`${e}.${t}`,s=nR.get(r);return s||(s=mi.createHash("md5").update(`${e}.${t}`).digest("hex"),nR.set(r,s)),s}a(Pq,"createNatsTableStreamName")});var ms=h((JX,hR)=>{"use strict";var _R=mt(),Yr=g(),uR=Wa(),Bq=require("lodash"),vq=require("path"),Hq=$r(),Tl=b(),{promisify:lR}=require("util"),ee=T(),{handleHDBError:Po,hdb_errors:qq}=D(),{HDB_ERROR_MSGS:Bo,HTTP_STATUS_CODES:ER}=qq,Gq=V();Gq.initSync();var cR=X(),Fq=re(),Ri=lR(_R.searchByValue),Vq=lR(_R.searchByHash),En="name",dR="hash_attribute",ml="schema",kq="schema_table",xq="attribute";hR.exports={describeAll:$q,describeTable:vo,describeSchema:Kq};async function $q(e){try{let t=Tl.isEmptyOrZeroLength(e),r,s;t||(r=e.hdb_user.role.permission,s=r.super_user||r.cluster_user);let n={schema:ee.SYSTEM_SCHEMA_NAME,table:ee.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,search_attribute:En,search_value:ee.WILDCARD_SEARCH_VALUE,get_attributes:[En]},i=await Ri(n);if(Tl.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:ee.SYSTEM_SCHEMA_NAME,table:ee.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,search_attribute:ee.ID_ATTRIBUTE_STRING,search_value:ee.WILDCARD_SEARCH_VALUE,get_attributes:[dR,ee.ID_ATTRIBUTE_STRING,En,ml]},u=await Ri(_),l=[];for(let d of u)try{let S;if(t||s)S=await vo({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;S=await vo({schema:d.schema,table:d.name},m)}S&&l.push(S)}catch(S){Yr.error(S)}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 Yr.error("Got an error in describeAll"),Yr.error(t),Po(new Error,Bo.DESCRIBE_ALL_ERR)}}a($q,"describeAll");async function vo(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=uR.describe_table(e);if(o)throw o;if(r===ee.SYSTEM_SCHEMA_NAME)return global.hdb_schema[ee.SYSTEM_SCHEMA_NAME][s];let c={schema:ee.SYSTEM_SCHEMA_NAME,table:ee.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,hash_attribute:ee.SYSTEM_TABLE_HASH_ATTRIBUTES.TABLE_TABLE_HASH_ATTRIBUTE,search_attribute:En,search_value:s,hash_values:[],get_attributes:[ee.WILDCARD_SEARCH_VALUE]},_=await Ri(c);if(!_||_.length===0)throw Po(new Error,Bo.TABLE_NOT_FOUND(e.schema,e.table),ER.NOT_FOUND);for await(let u of _)try{if(u.schema!==r)continue;if(i=u,!i.hash_attribute)throw Po(new Error,Bo.INVALID_TABLE_ERR(i));let l={schema:ee.SYSTEM_SCHEMA_NAME,table:ee.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,hash_attribute:ee.SYSTEM_TABLE_HASH_ATTRIBUTES.ATTRIBUTE_TABLE_HASH_ATTRIBUTE,search_attribute:kq,search_value:r+"."+s,get_attributes:[xq]},E=await Ri(l);E=Bq.uniqBy(E,d=>d.attribute),n&&n.length>0&&(E=Yq(n)),i.attributes=E,i.clustering_stream_name=Hq.createNatsTableStreamName(u.schema,u.name);try{let d=vq.join(Fq.getBaseSchemaPath(),i.schema.toString()),S=await cR.openEnvironment(d,i.name),m=cR.statDBI(S,i.hash_attribute);i.record_count=m.entryCount}catch(d){Yr.warn(`unable to stat table dbi due to ${d}`)}}catch(l){Yr.error(`There was an error getting attributes for table '${u.name}'`),Yr.error(l)}return i}a(vo,"descTable");function Yq(e){return e.reduce((t,r)=>(r.describe&&t.push({attribute:r.attribute_name}),t),[])}a(Yq,"getAttrsByPerms");async function Kq(e){let t=uR.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:ee.SYSTEM_SCHEMA_NAME,table:ee.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,hash_attribute:ee.SYSTEM_TABLE_HASH_ATTRIBUTES.TABLE_TABLE_HASH_ATTRIBUTE,search_attribute:ml,search_value:s,hash_values:[],get_attributes:[dR,ee.ID_ATTRIBUTE_STRING,En,ml]},i=await Ri(n);if(i&&i.length<1){let o={schema:ee.SYSTEM_SCHEMA_NAME,table:ee.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,hash_attribute:ee.SYSTEM_TABLE_HASH_ATTRIBUTES.SCHEMA_TABLE_HASH_ATTRIBUTE,hash_values:[s],get_attributes:[En]},c=await Vq(o);if(c&&c.length<1)throw Po(new Error,Bo.SCHEMA_NOT_FOUND(e.schema),ER.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]),Tl.isEmpty(_)||_.describe){let u=await vo({schema:e.schema,table:c.name},_?_.attribute_permissions:null);u&&(o[u.name]=u)}}catch(_){Yr.error(`Error describing schema table '${e.schema}.${c}'`),Yr.error(_)}})),o}}a(Kq,"describeSchema")});var Kr=h((zX,RR)=>{var ZX=require("async"),dn=ls(),XX=g(),{callbackify:TR,promisify:Qq}=require("util");RR.exports={setSchemaDataToGlobal:SR,getTableSchema:Zq,getSystemSchema:zq,setSchemaDataToGlobalAsync:Qq(SR)};var mR=ms(),Wq=TR(mR.describeAll),Jq=TR(mR.describeTable);function SR(e){Wq(null,(t,r)=>{if(t){e(t);return}r.system||(r.system=dn),global.hdb_schema=r,e(null,null)})}a(SR,"setSchemaDataToGlobal");function fR(e,t){return e==="system"?dn[t]:global.hdb_schema[e][t]}a(fR,"returnSchema");function Zq(e,t,r){!global.hdb_schema||!global.hdb_schema[e]||!global.hdb_schema[e][t]?Xq(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,fR(e,t))}):r(null,fR(e,t))}a(Zq,"getTableSchema");function Xq(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}Jq(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(Xq,"setTableDataToGlobal");function zq(){return dn}a(zq,"getSystemSchema")});var yt=h((jX,OR)=>{"use strict";var qo=Gu(),Lt=b(),jq=require("util"),Go=Nr(),eG=Kr(),Rl=g(),{handleHDBError:Qr,hdb_errors:tG}=D(),{HTTP_STATUS_CODES:Rs}=tG,rG=jq.promisify(eG.getTableSchema),sG="updated",AR="inserted",pR="upserted";OR.exports={insert:iG,update:aG,upsert:oG,validation:nG,flush:cG};async function nG(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 rG(e.schema,e.table),r=qo(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 Rl.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 Rl.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(nG,"validation");async function iG(e){if(e.operation!=="insert")throw new Error("invalid operation, must be insert");let t=qo(e);if(t)throw Qr(new Error,t.message,Rs.BAD_REQUEST);let r=Lt.checkSchemaTableExist(e.schema,e.table);if(r)throw Qr(new Error,r,Rs.BAD_REQUEST);try{let s=await Go.createRecords(e);return Ho(AR,s.written_hashes,e,s.skipped_hashes,s.new_attributes,s.txn_time)}catch(s){throw s}}a(iG,"insertData");async function aG(e){if(e.operation!=="update")throw new Error("invalid operation, must be update");let t=qo(e);if(t)throw Qr(new Error,t.message,Rs.BAD_REQUEST);let r=Lt.checkSchemaTableExist(e.schema,e.table);if(r)throw Qr(new Error,r,Rs.BAD_REQUEST);try{let s=await Go.updateRecords(e);return Lt.isEmpty(s.existing_rows)?Ho(sG,s.written_hashes,e,s.skipped_hashes,s.new_attributes,s.txn_time):Ho(s.update_action,[],e,s.hashes,void 0,s.txn_time)}catch(s){throw s}}a(aG,"updateData");async function oG(e){if(e.operation!=="upsert")throw Qr(new Error,"invalid operation, must be upsert",Rs.INTERNAL_SERVER_ERROR);let t=qo(e);if(t)throw Qr(new Error,t.message,Rs.BAD_REQUEST);let r=Lt.checkSchemaTableExist(e.schema,e.table);if(r)throw Qr(new Error,r,Rs.BAD_REQUEST);try{let s=await Go.upsertRecords(e);return Ho(pR,s.written_hashes,e,[],s.new_attributes,s.txn_time)}catch(s){let n=`There was an error during an upsert op: ${s}`;throw Qr(s,null,null,Rl.ERR,n)}}a(oG,"upsertData");function Ho(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===AR?(o.inserted_hashes=t,o.skipped_hashes=s,o):e===pR?(o.upserted_hashes=t,o):(o.update_hashes=t,o.skipped_hashes=s,o)}a(Ho,"returnObject");function cG(e){return Go.flush(e.schema,e.table)}a(cG,"flush")});var pl=h((e3,IR)=>{var _G=de(),Al=require("joi"),{hdb_schema_table:NR}=Rr(),gR={schema:NR,table:NR},uG={date:Al.date().iso().required()},lG={timestamp:Al.date().timestamp().required().messages({"date.format":"'timestamp' is invalid"})};IR.exports=function(e,t){let r=t==="timestamp"?{...gR,...lG}:{...gR,...uG},s=Al.object(r);return _G.validateBySchema(e,s)}});var UR=h((t3,wR)=>{var EG=de(),bR=require("joi"),{hdb_schema_table:CR}=Rr(),dG=bR.object({schema:CR,table:CR,hash_values:bR.array().required()});wR.exports=function(e){return EG.validateBySchema(e,dG)}});var yR=h((r3,LR)=>{"use strict";var Fo=class{constructor(t,r,s,n,i){this.operation=t,this.schema=r,this.table=s,this.hash_attribute=n,this.records=i}};a(Fo,"InsertObject");var Vo=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(Vo,"NoSQLSeachObject");var ko=class{constructor(){this.message=void 0,this.deleted_hashes=[],this.skipped_hashes=[]}};a(ko,"DeleteResponseObject");LR.exports={InsertObject:Fo,NoSQLSeachObject:Vo,DeleteResponseObject:ko}});var ps=h((s3,vR)=>{"use strict";var MR=pl(),hG=UR(),xo=b(),DR=require("moment"),PR=g(),{promisify:SG,callbackify:fG}=require("util"),As=T(),TG=Kr(),Ol=SG(TG.getTableSchema),Nl=Nr(),{DeleteResponseObject:mG}=yR(),{handleHDBError:Wr,hdb_errors:RG}=D(),{HDB_ERROR_MSGS:$o,HTTP_STATUS_CODES:Jr}=RG,AG="records successfully deleted",pG=fG(BR);vR.exports={delete:pG,deleteRecord:BR,deleteFilesBefore:OG,deleteAuditLogsBefore:NG};async function OG(e){let t=MR(e,"date");if(t)throw Wr(t,t.message,Jr.BAD_REQUEST,void 0,void 0,!0);if(!DR(e.date,DR.ISO_8601).isValid())throw Wr(new Error,$o.INVALID_DATE,Jr.BAD_REQUEST,As.LOG_LEVELS.ERROR,$o.INVALID_DATE,!0);let s=xo.checkSchemaTableExist(e.schema,e.table);if(s)throw Wr(new Error,s,Jr.NOT_FOUND,As.LOG_LEVELS.ERROR,s,!0);try{let n=await Nl.deleteRecordsBefore(e);if(await Ol(e.schema,e.table),PR.info(`Finished deleting files before ${e.date}`),n&&n.message)return n.message}catch(n){throw n}}a(OG,"deleteFilesBefore");async function NG(e){let t=MR(e,"timestamp");if(t)throw Wr(t,t.message,Jr.BAD_REQUEST,void 0,void 0,!0);if(isNaN(e.timestamp))throw Wr(new Error,$o.INVALID_VALUE("Timestamp"),Jr.BAD_REQUEST,As.LOG_LEVELS.ERROR,$o.INVALID_VALUE("Timestamp"),!0);let r=xo.checkSchemaTableExist(e.schema,e.table);if(r)throw Wr(new Error,r,Jr.NOT_FOUND,As.LOG_LEVELS.ERROR,r,!0);try{let s=await Nl.deleteAuditLogsBefore(e);return await Ol(e.schema,e.table),PR.info(`Finished deleting audit logs before ${e.timestamp}`),s}catch(s){throw s}}a(NG,"deleteAuditLogsBefore");async function BR(e){let t=hG(e);if(t)throw Wr(t,t.message,Jr.BAD_REQUEST,void 0,void 0,!0);let r=xo.checkSchemaTableExist(e.schema,e.table);if(r)throw Wr(new Error,r,Jr.NOT_FOUND,As.LOG_LEVELS.ERROR,r,!0);try{await Ol(e.schema,e.table);let s=await Nl.deleteRecords(e);return xo.isEmptyOrZeroLength(s.message)&&(s.message=`${s.deleted_hashes.length} of ${e.hash_values.length} ${AG}`),s}catch(s){if(s.message===As.SEARCH_NOT_FOUND_MESSAGE){let n=new mG;return n.message=As.SEARCH_NOT_FOUND_MESSAGE,n.skipped_hashes=e.hash_values.length,n.deleted_hashes=0,n}throw s}}a(BR,"deleteRecord")});var Yo=h((n3,GR)=>{var gG=require("crypto"),HR=9;function IG(e){let t=CG(HR),r=qR(e+t);return t+r}a(IG,"createHash");function bG(e,t){let r=e.substr(0,HR),s=r+qR(t+r);return e===s}a(bG,"validateHash");function CG(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(CG,"generateSalt");function qR(e){return gG.createHash("md5").update(e).digest("hex")}a(qR,"md5");GR.exports={hash:IG,validate:bG}});var VR=h((i3,FR)=>{var gl=de(),Ze={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 wG(e){return Ze.password.presence=!0,Ze.username.presence=!0,Ze.role.presence=!0,Ze.active.presence=!0,gl.validateObject(e,Ze)}a(wG,"addUserValidation");function UG(e){return Ze.password.presence=!1,Ze.username.presence=!0,Ze.role.presence=!1,Ze.active.presence=!1,gl.validateObject(e,Ze)}a(UG,"alterUserValidation");function LG(e){return Ze.password.presence=!1,Ze.username.presence=!0,Ze.role.presence=!1,Ze.active.presence=!1,gl.validateObject(e,Ze)}a(LG,"dropUserValidation");FR.exports={addUserValidation:wG,alterUserValidation:UG,dropUserValidation:LG}});var Se=h((o3,xR)=>{"use strict";var{platform:a3}=require("os"),yG="nats-server.zip",Il="nats-server",DG=process.platform==="win32"?`${Il}.exe`:Il,bl="HDB",MG=/^[^\s.,*>]+$/,kR="__request__",PG=a(e=>`${e}.${kR}`,"REQUEST_SUBJECT"),BG={HUB_SERVER:"hub.json",LEAF_SERVER:"leaf.json"},vG={HUB:"hub.pid",LEAF:"leaf.pid"},HG={HUB:"-hub",LEAF:"-leaf",ADMIN:"-admin"},qG={stream_name:"__HARPERDB_WORK_QUEUE__",durable_name:"HDB_WORK_QUEUE",deliver_group:bl,deliver_subject:"__HDB__.WORKQUEUE"},GG={stream_name:"__HARPERDB_SCHEMA_QUEUE__",durable_name:"HDB_SCHEMA_QUEUE",deliver_group:bl,deliver_subject:"HDB.SCHEMAQUEUE"},FG={stream_name:"__HARPERDB_USER_QUEUE__",durable_name:"HDB_USER_QUEUE",deliver_group:bl,deliver_subject:"HDB.USERQUEUE"},VG={SUCCESS:"success",ERROR:"error"},kG={OPEN:"open",CLOSED:"closed",NO_RESPONDERS:"NoResponders",TIMEOUT:"Timeout"},xG={TXN:"txn",MSGID:"msgid"};xR.exports={NATS_SERVER_ZIP:yG,NATS_SERVER_NAME:Il,NATS_BINARY_NAME:DG,PID_FILES:vG,NATS_CONFIG_FILES:BG,SERVER_SUFFIX:HG,WORK_QUEUE_CONSUMER_NAMES:qG,SCHEMA_QUEUE_CONSUMER_NAMES:GG,USER_QUEUE_CONSUMER_NAMES:FG,NATS_TERM_CONSTRAINTS_RX:MG,REQUEST_SUFFIX:kR,UPDATE_REMOTE_RESPONSE_STATUSES:VG,CLUSTER_STATUS_STATUSES:kG,REQUEST_SUBJECT:PG,SUBJECT_PREFIXES:xG}});var YR=h((c3,$R)=>{"use strict";var Zr=T(),Ai=class{constructor(t=0,r=Zr.STORAGE_TYPES_ENUM.LMDB,s=Zr.LICENSE_VALUES.API_CALL_DEFAULT,n=Zr.RAM_ALLOCATION_ENUM.DEFAULT,i=Zr.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(Ai,"BaseLicense");var Ko=class extends Ai{constructor(t=0,r=Zr.STORAGE_TYPES_ENUM.LMDB,s=Zr.LICENSE_VALUES.API_CALL_DEFAULT,n=Zr.RAM_ALLOCATION_ENUM.DEFAULT,i=Zr.LICENSE_VALUES.VERSION_DEFAULT,o,c=!1){super(t,r,s,n,i,o),this.enterprise=c}};a(Ko,"ExtendedLicense");$R.exports={BaseLicense:Ai,ExtendedLicense:Ko}});var pi=h((_3,XR)=>{"use strict";var Sn=require("fs-extra"),KR=Yo(),QR=require("crypto"),$G=require("moment"),YG=require("uuid").v4,Xe=g(),wl=require("path"),KG=b(),Rt=T(),QG=YR().ExtendedLicense,hn="invalid license key format",WG="061183",JG="mofi25",ZG="aes-256-cbc",XG=16,zG=32,WR=V();WR.initSync();var Cl;XR.exports={validateLicense:JR,generateFingerPrint:eF,licenseSearch:ZR,getLicense:sF};function Ul(){return wl.join(WR.getHdbBasePath(),Rt.LICENSE_KEY_DIR_NAME,Rt.LICENSE_FILE_NAME)}a(Ul,"getLicenseDirPath");function jG(){let e=Ul();return wl.join(e,Rt.LICENSE_FILE_NAME)}a(jG,"getLicenseFilePath");function Ll(){let e=Ul();return wl.join(e,Rt.REG_KEY_FILE_NAME)}a(Ll,"getFingerPrintFilePath");async function eF(){let e=Ll();try{return await Sn.readFile(e,"utf8")}catch(t){if(t.code==="ENOENT")return await tF();throw Xe.error(`Error writing fingerprint file to ${e}`),Xe.error(t),new Error("There was an error generating the fingerprint")}}a(eF,"generateFingerPrint");async function tF(){let e=YG(),t=KR.hash(e),r=Ll();try{await Sn.mkdirp(Ul()),await Sn.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(tF,"writeFingerprint");function JR(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 Xe.error("empty license key passed to validate."),r;let s=Ll(),n=!1;try{n=Sn.statSync(s)}catch(i){Xe.error(i)}if(n){let i;try{i=Sn.readFileSync(s,"utf8")}catch{Xe.error("error validating this machine in the license"),r.valid_machine=!1;return}let o=e.split(JG),c=o[1];c=Buffer.concat([Buffer.from(c)],XG);let _=Buffer.concat([Buffer.from(i)],zG),u=QR.createDecipheriv(ZG,_,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 S=rF(o[0],i);if(S)l=S;else throw r.valid_license=!1,r.valid_machine=!1,console.error(hn),Xe.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),Xe.error(hn),new Error(hn)}else r.exp_date=l;r.exp_date<$G().valueOf()&&(r.valid_date=!1),KR.validate(o[1],`${WG}${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(JR,"validateLicense");function rF(e,t){try{let r=QR.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(rF,"checkOldLicense");function ZR(){let e=new QG;e.api_call=0;let t=[];try{t=Sn.readFileSync(jG(),"utf-8").split(Rt.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(KG.isEmptyOrZeroLength(s))continue;let n=JSON.parse(s),i=JR(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=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),Cl=e,e}a(ZR,"licenseSearch");async function sF(){return Cl||await ZR(),Cl}a(sF,"getLicense")});var gr=h((u3,lA)=>{"use strict";var tA="username is required",rA="nothing to update, must supply active, role or password to update",sA="password cannot be an empty string",nA="If role is specified, it cannot be empty.",iA="active must be true or false";lA.exports={addUser:lF,alterUser:EF,dropUser:hF,userInfo:SF,listUsers:Wo,listUsersExternal:fF,setUsersToGlobal:Oi,findAndValidateUser:RF,getClusterUser:AF,USERNAME_REQUIRED:tA,ALTERUSER_NOTHING_TO_UPDATE:rA,EMPTY_PASSWORD:sA,EMPTY_ROLE:nA,ACTIVE_BOOLEAN:iA};var aA=yt(),nF=ps(),Dl=Yo(),oA=VR(),cA=mt(),Ml=js(),Ce=b(),_A=require("validate.js"),H=g(),{promisify:Pl}=require("util"),Bl=$r(),Os=T(),zR=Se(),iF=Tr(),vl=V(),aF=pi(),oF=ls(),{handleHDBError:sr,hdb_errors:cF}=D(),{HTTP_STATUS_CODES:nr,AUTHENTICATION_ERROR_MSGS:yl,HDB_ERROR_MSGS:fn}=cF,{UserEventMsg:Hl}=Vr(),jR=require("lodash"),uA={username:!0,active:!0,role:!0,password:!0},eA=new Map,Qo=Pl(cA.searchByValue),_F=Pl(cA.searchByHash),uF=Pl(nF.delete);async function lF(e){let t=_A.cleanAttributes(e,uA),r=oA.addUserValidation(t);if(r)throw sr(new Error,r.message,nr.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 Qo(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 sr(new Error,fn.ROLE_NAME_NOT_FOUND(t.role),nr.NOT_FOUND,void 0,void 0,!0);if(n.length>1)throw sr(new Error,fn.DUP_ROLES_FOUND(t.role),nr.CONFLICT,void 0,void 0,!0);n[0].permission.cluster_user===!0&&(t.hash=Bl.encrypt(t.password)),t.password=Dl.hash(t.password),t.role=n[0].id;let i={operation:"insert",schema:"system",table:"hdb_user",records:[t]},o;try{o=await aA.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 sr(new Error,fn.USER_ALREADY_EXISTS(t.username),nr.CONFLICT,void 0,void 0,!0);let c=Object.assign({},t);c.role=n[0];let _={user:null};return _.user=c,Ce.sendTransactionToSocketCluster(Os.INTERNAL_SC_CHANNELS.ADD_USER,_,vl.get(Os.HDB_SETTINGS_NAMES.CLUSTERING_NODE_NAME_KEY)),Ml.signalUserChange(new Hl(process.pid)),`${c.username} successfully added`}a(lF,"addUser");async function EF(e){let t=_A.cleanAttributes(e,uA);if(Ce.isEmptyOrZeroLength(t.username))throw new Error(tA);if(Ce.isEmptyOrZeroLength(t.password)&&Ce.isEmptyOrZeroLength(t.role)&&Ce.isEmptyOrZeroLength(t.active))throw new Error(rA);if(!Ce.isEmpty(t.password)&&Ce.isEmptyOrZeroLength(t.password.trim()))throw new Error(sA);if(!Ce.isEmpty(t.active)&&!Ce.isBoolean(t.active))throw new Error(iA);let r=dF(t.username);if(!Ce.isEmpty(t.password)&&!Ce.isEmptyOrZeroLength(t.password.trim())&&(r&&(t.hash=Bl.encrypt(t.password)),t.password=Dl.hash(t.password)),t.role==="")throw new Error(nA);if(t.role){let o={schema:"system",table:"hdb_role",search_attribute:"role",search_value:t.role,get_attributes:["*"]},c;try{c=await Qo(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(_),sr(new Error,_,nr.NOT_FOUND,void 0,void 0,!0)}if(c.length>1){let _=fn.ALTER_USER_DUP_ROLES(t.role);throw H.error(_),sr(new Error,_,nr.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 aA.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,Ce.sendTransactionToSocketCluster(Os.INTERNAL_SC_CHANNELS.ALTER_USER,i,vl.get(Os.HDB_SETTINGS_NAMES.CLUSTERING_NODE_NAME_KEY)),Ml.signalUserChange(new Hl(process.pid)),n}a(EF,"alterUser");function dF(e){let t=!1,r=global.hdb_users.get(e);return r&&r.role.permission.cluster_user===!0&&(t=!0),t}a(dF,"isClusterUser");async function hF(e){try{let t=oA.dropUserValidation(e);if(t)throw new Error(t);let r={table:"hdb_user",schema:"system",hash_values:[e.username]};if(Ce.isEmpty(global.hdb_users.get(e.username)))throw sr(new Error,fn.USER_NOT_EXIST(e.username),nr.NOT_FOUND,void 0,void 0,!0);let s;try{s=await uF(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,Ce.sendTransactionToSocketCluster(Os.INTERNAL_SC_CHANNELS.DROP_USER,n,vl.get(Os.HDB_SETTINGS_NAMES.CLUSTERING_NODE_NAME_KEY)),Ml.signalUserChange(new Hl(process.pid)),`${e.username} successfully deleted`}catch(t){throw t}}a(hF,"dropUser");async function SF(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 _F(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(SF,"userInfo");async function fF(){let e;try{e=await Wo()}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(fF,"listUsersExternal");async function Wo(){try{let e={schema:"system",table:"hdb_role",search_value:"*",search_attribute:"role",get_attributes:["*"]},t;try{t=jR.cloneDeep(await Qo(e))}catch(r){throw H.error("Got an error searching for roles."),H.error(r),r}if(!Ce.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=jR.cloneDeep(await Qo(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],TF(c.role),i.set(c.username,c)}return(await aF.getLicense()).enterprise?i:mF(i)}}catch(e){throw H.error("got an error listing users"),H.error(e),Ce.errorizeMessage(e)}return null}a(Wo,"listUsers");function TF(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(oF)){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(TF,"appendSystemTablesToRole");function mF(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(mF,"nonEnterpriseFilter");async function Oi(){try{let e=await Wo();global.hdb_users=e}catch(e){throw H.error(e),e}}a(Oi,"setUsersToGlobal");async function RF(e,t,r=!0){global.hdb_users||await Oi();let s=global.hdb_users.get(e);if(!s)throw sr(new Error,yl.GENERIC_AUTH_FAIL,nr.UNAUTHORIZED,void 0,void 0,!0);if(s&&!s.active)throw sr(new Error,yl.USER_INACTIVE,nr.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(eA.get(t)===s.password)return n;if(Dl.validate(s.password,t))eA.set(t,s.password);else throw sr(new Error,yl.GENERIC_AUTH_FAIL,nr.UNAUTHORIZED,void 0,void 0,!0)}return n}a(RF,"findAndValidateUser");async function AF(){let e=await Wo(),t=iF.getConfigFromFile(Os.CONFIG_PARAMS.CLUSTERING_USER),r=e.get(t);if(!Ce.isEmpty(r))return r.decrypt_hash=Bl.decrypt(r.hash),r.uri_encoded_d_hash=encodeURIComponent(r.decrypt_hash),r.uri_encoded_name=encodeURIComponent(r.username),r.sys_name=r.username+zR.SERVER_SUFFIX.ADMIN,r.sys_name_encoded=r.uri_encoded_name+zR.SERVER_SUFFIX.ADMIN,r}a(AF,"getClusterUser")});var SA=h((l3,hA)=>{"use strict";var pF=require("node-ipc").IPC,EA=b(),dA=T(),Ir=g(),{IPC_ERRORS:Tn}=Qe(),OF=require("os"),Jo=class{constructor(t,r){this.ipc=new pF,this.server_name=dA.HDB_IPC_SERVER,this.ipc.config.retry=OF.platform()=="win32"?6e5:100,this.ipc.config.id=dA.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",()=>{Ir.info(`IPC client ${this.ipc.config.id} connected to ${this.server_name}`)}),this.ipc.of[this.server_name].on("disconnect",()=>{Ir.info(`IPC client ${this.ipc.config.id} disconnected from ${this.server_name}`)}),this.ipc.of[this.server_name].on("error",r=>{r.code==="ECONNREFUSED"&&Ir.warn("Error connecting to HDB IPC server. Confirm that the server is running."),Ir.warn(`Error with IPC client ${this.ipc.config.id}`),Ir.warn(r)});for(let[r,s]of Object.entries(t))this.addEventHandler(r,s)}emitToServer(t){if(typeof t!="object")throw Ir.warn(Tn.INVALID_IPC_DATA_TYPE),new Error(Tn.INVALID_IPC_DATA_TYPE);if(EA.isEmpty(t.type))throw Ir.warn(Tn.MISSING_TYPE),new Error(Tn.MISSING_TYPE);if(EA.isEmpty(t.message))throw Ir.warn(Tn.MISSING_MSG),new Error(Tn.MISSING_MSG);Ir.trace(`IPC client ${this.ipc.config.id} emitting`,t),this.ipc.of[this.server_name].emit("message",t)}};a(Jo,"IPCClient");hA.exports=Jo});var mA=h((E3,TA)=>{"use strict";var ql=X(),NF=g(),fA=Qe().LMDB_ERRORS_ENUM;TA.exports=gF;async function gF(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 ql.closeEnvironment(global.lmdb_map[o])}catch(c){if(c.message!==fA.ENV_REQUIRED)throw c}}break;case"drop_table":let s=`${e.schema}.${e.table}`,n=`txn.${s}`;try{await ql.closeEnvironment(global.lmdb_map[s]),await ql.closeEnvironment(global.lmdb_map[n])}catch(i){if(i.message!==fA.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){NF.error(t)}}a(gF,"cleanLMDBMap")});var NA=h((d3,OA)=>{"use strict";var Ns=g(),Zo=T(),IF=mA(),RA=Kr(),bF=ms(),CF=gr(),{validateEvent:pA}=Vr(),wF={[Zo.IPC_EVENT_TYPES.SCHEMA]:UF,[Zo.IPC_EVENT_TYPES.USER]:yF};async function UF(e){let t=pA(e);if(t){Ns.error(t);return}Ns.trace(`IPC schemaHandler ${Zo.HDB_IPC_CLIENT_PREFIX}${process.pid} received schema event:`,e),await IF(e.message),await LF(e.message)}a(UF,"schemaHandler");async function LF(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 bF.describeTable({schema:e.schema,table:e.table});break;default:RA.setSchemaDataToGlobal(AA);break}else RA.setSchemaDataToGlobal(AA)}catch(t){Ns.error(t)}}a(LF,"syncSchemaMetadata");function AA(e){e&&Ns.error(e)}a(AA,"handleErrorCallback");async function yF(e){try{let t=pA(e);if(t){Ns.error(t);return}Ns.trace(`IPC userHandler ${Zo.HDB_IPC_CLIENT_PREFIX}${process.pid} received user event:`,e),await CF.setUsersToGlobal()}catch(t){Ns.error(t)}}a(yF,"userHandler");OA.exports=wF});var bA=h((h3,IA)=>{"use strict";var gA=require("fs"),Ni=V();Ni.initSync();var{CONFIG_PARAMS:Xo}=T(),DF=1024*1024*1024;function MF(e){let t=Ni.get(Xo.CUSTOMFUNCTIONS_NETWORK_TIMEOUT),r=Ni.get(Xo.CUSTOMFUNCTIONS_NETWORK_KEEPALIVETIMEOUT),s={bodyLimit:DF,connectionTimeout:t,keepAliveTimeout:r,ignoreTrailingSlash:!0};if(e){let n=Ni.get(Xo.CUSTOMFUNCTIONS_TLS_PRIVATEKEY),i=Ni.get(Xo.CUSTOMFUNCTIONS_TLS_CERTIFICATE);s.https={key:gA.readFileSync(`${n}`),cert:gA.readFileSync(`${i}`)}}return s}a(MF,"getServerOptions");IA.exports=MF});var UA=h((S3,wA)=>{"use strict";var Gl=V();Gl.initSync();var{CONFIG_PARAMS:CA}=T();function PF(){let e=Gl.get(CA.CUSTOMFUNCTIONS_NETWORK_CORSACCESSLIST),t=Gl.get(CA.CUSTOMFUNCTIONS_NETWORK_CORS),r;if(t&&(r={origin:!0,allowedHeaders:["Content-Type","Authorization"],credentials:!1},e&&e.length>0&&e[0]!==null)){let s=e.split(",");r.origin=(n,i)=>s.indexOf(n)!==-1?i(null,!0):i(new Error(`domain ${n} is not on access list`))}return r}a(PF,"getCORSOptions");wA.exports=PF});var DA=h((f3,yA)=>{"use strict";var LA=V();LA.initSync();var BF=T();function vF(){return LA.get(BF.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HEADERSTIMEOUT)}a(vF,"getHeaderTimeoutConfig");yA.exports=vF});var PA=h((T3,MA)=>{var HF=de(),qF={user:{presence:!0},schema:{presence:!0},table:{presence:!0},operation:{presence:!0}};MA.exports=function(e){return HF.validateObject(e,qF)}});var Fl=h((m3,BA)=>{"use strict";var GF=T().OPERATIONS_ENUM,zo=class{constructor(t,r,s,n=void 0){this.operation=GF.UPDATE,this.schema=t,this.table=r,this.records=s,this.__origin=n}};a(zo,"UpdateObject");BA.exports=zo});var HA=h((R3,vA)=>{"use strict";var FF={OPERATION:"operation",REFRESH:"refresh"},jo=class{constructor(t,r){this.operation_token=t,this.refresh_token=r}};a(jo,"JWTTokens");var ec=class{constructor(t,r,s){this.public_key=t,this.private_key=r,this.passphrase=s}};a(ec,"JWTRSAKeys");vA.exports={JWTTokens:jo,TOKEN_TYPE_ENUM:FF,JWTRSAKeys:ec}});var nc=h((A3,VA)=>{"use strict";var Ii=require("jsonwebtoken"),Vl=require("fs-extra"),kl=b(),Dt=T(),{handleHDBError:ct,hdb_errors:VF}=D(),{HTTP_STATUS_CODES:_t,AUTHENTICATION_ERROR_MSGS:ut}=VF,gi=g(),qA=Yo(),Yl=gr(),kF=yt().update,xF=Fl(),$F=js(),{UserEventMsg:YF}=Vr(),Xr=V();Xr.initSync();var xl=require("path"),{JWTTokens:KF,JWTRSAKeys:QF,TOKEN_TYPE_ENUM:tc}=HA(),WF=Xr.get(Dt.HDB_SETTINGS_NAMES.OPERATION_TOKEN_TIMEOUT_KEY)?Xr.get(Dt.HDB_SETTINGS_NAMES.OPERATION_TOKEN_TIMEOUT_KEY):"1d",JF=Xr.get(Dt.HDB_SETTINGS_NAMES.REFRESH_TOKEN_TIMEOUT_KEY)?Xr.get(Dt.HDB_SETTINGS_NAMES.REFRESH_TOKEN_TIMEOUT_KEY):"30d",rc="RS256",$l;VA.exports={createTokens:ZF,validateOperationToken:zF,refreshOperationToken:XF,validateRefreshToken:FA};async function ZF(e){if(kl.isEmpty(e)||typeof e!="object")throw ct(new Error,ut.INVALID_AUTH_OBJECT,_t.BAD_REQUEST,void 0,void 0,!0);if(kl.isEmpty(e.username))throw ct(new Error,ut.USERNAME_REQUIRED,_t.BAD_REQUEST,void 0,void 0,!0);if(kl.isEmpty(e.password))throw ct(new Error,ut.PASSWORD_REQUIRED,_t.BAD_REQUEST,void 0,void 0,!0);let t;try{if(t=await Yl.findAndValidateUser(e.username,e.password),!t)throw ct(new Error,ut.INVALID_CREDENTIALS,_t.UNAUTHORIZED,void 0,void 0,!0)}catch(d){throw gi.error(d),ct(new Error,ut.INVALID_CREDENTIALS,_t.UNAUTHORIZED,void 0,void 0,!0)}let r=await sc(),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 GA(i,r.private_key,r.passphrase),c=await Ii.sign(i,{key:r.private_key,passphrase:r.passphrase},{expiresIn:JF,algorithm:rc,subject:tc.REFRESH}),_=qA.hash(c),u=new xF(Dt.SYSTEM_SCHEMA_NAME,Dt.SYSTEM_TABLE_NAMES.USER_TABLE_NAME,[{username:e.username,refresh_token:_}]),l,E;try{l=await kF(u)}catch(d){gi.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 $F.signalUserChange(new YF(process.pid)),new KF(o,c)}a(ZF,"createTokens");async function GA(e,t,r){return await Ii.sign(e,{key:t,passphrase:r},{expiresIn:WF,algorithm:rc,subject:tc.OPERATION})}a(GA,"signOperationToken");async function sc(){if($l===void 0)try{let e=xl.join(Xr.getHdbBasePath(),Dt.LICENSE_KEY_DIR_NAME,Dt.JWT_ENUM.JWT_PASSPHRASE_NAME),t=xl.join(Xr.getHdbBasePath(),Dt.LICENSE_KEY_DIR_NAME,Dt.JWT_ENUM.JWT_PRIVATE_KEY_NAME),r=xl.join(Xr.getHdbBasePath(),Dt.LICENSE_KEY_DIR_NAME,Dt.JWT_ENUM.JWT_PUBLIC_KEY_NAME),s=(await Vl.readFile(e)).toString(),n=(await Vl.readFile(t)).toString(),i=(await Vl.readFile(r)).toString();$l=new QF(i,n,s)}catch(e){throw gi.error(e),ct(new Error,ut.NO_ENCRYPTION_KEYS,_t.INTERNAL_SERVER_ERROR)}return $l}a(sc,"getJWTRSAKeys");async function XF(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 FA(e.refresh_token);let t=await sc(),r=await Ii.decode(e.refresh_token);return{operation_token:await GA({username:r.username,super_user:r.super_user,cluster_user:r.cluster_user},t.private_key,t.passphrase)}}a(XF,"refreshOperationToken");async function zF(e){try{let t=await sc(),r=await Ii.verify(e,t.public_key,{algorithms:rc,subject:tc.OPERATION});return await Yl.findAndValidateUser(r.username,void 0,!1)}catch(t){throw gi.warn(t),t.name&&t.name==="TokenExpiredError"?ct(new Error,ut.TOKEN_EXPIRED,_t.FORBIDDEN):ct(new Error,ut.INVALID_TOKEN,_t.UNAUTHORIZED)}}a(zF,"validateOperationToken");async function FA(e){let t;try{let r=await sc(),s=await Ii.verify(e,r.public_key,{algorithms:rc,subject:tc.REFRESH});t=await Yl.findAndValidateUser(s.username,void 0,!1)}catch(r){throw gi.warn(r),r.name&&r.name==="TokenExpiredError"?ct(new Error,ut.TOKEN_EXPIRED,_t.FORBIDDEN):ct(new Error,ut.INVALID_TOKEN,_t.UNAUTHORIZED)}if(!qA.validate(t.refresh_token,e))throw ct(new Error,ut.INVALID_TOKEN,_t.UNAUTHORIZED);return t}a(FA,"validateRefreshToken")});var Kl=h((O3,$A)=>{"use strict";var jF=PA(),mn=require("passport"),e0=require("passport-local").Strategy,t0=require("passport-http").BasicStrategy,r0=require("util"),s0=gr(),xA=r0.callbackify(s0.findAndValidateUser),p3=Qe(),n0=T(),kA=nc();mn.use(new e0(function(e,t,r){xA(e,t,r)}));mn.use(new t0(function(e,t,r){xA(e,t,r)}));mn.serializeUser(function(e,t){t(null,e)});mn.deserializeUser(function(e,t){t(null,e)});function i0(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":mn.authenticate("basic",{session:!1},(o,c)=>{i(o,c)})(e,t,r);break;case"Bearer":e.body&&e.body.operation&&e.body.operation===n0.OPERATIONS_ENUM.REFRESH_OPERATION_TOKEN?kA.validateRefreshToken(n).then(o=>{e.body.refresh_token=n,r(null,o)}).catch(o=>{r(o)}):kA.validateOperationToken(n).then(o=>{r(null,o)}).catch(o=>{r(o)});break;default:mn.authenticate("local",{session:!1},function(o,c){i(o,c)})(e,t,r);break}}a(i0,"authorize");function a0(e,t){let r=jF(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(a0,"checkPermissions");$A.exports={authorize:i0,checkPermissions:a0}});var ic=h((N3,YA)=>{"use strict";var o0=Nr();YA.exports={writeTransaction:c0};function c0(e,t,r){return o0.writeTransaction(e,t,r)}a(c0,"writeTransaction")});var Ql=h((g3,_0)=>{_0.exports={name:"harperdb",version:"4.0.2",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=h((B3,lp)=>{"use strict";var ir=V();ir.initSync();var u0=require("fs-extra"),l0=require("semver"),Li=require("path"),{monotonicFactory:E0}=require("ulidx"),d0=E0(),QA=require("util"),WA=require("child_process"),h0=QA.promisify(WA.exec),S0=WA.spawn,te=Se(),ne=T(),jl=b(),br=g(),ac=$r(),f0=ic(),bi=Tr(),{encode:Zl,decode:JA}=require("msgpackr"),{isEmpty:gs}=jl,ZA=gr(),I3=Ss(),T0=mt(),b3=QA.promisify(T0.searchByHash),{connect:m0,StorageType:XA,RetentionPolicy:zA,AckPolicy:jA,DeliverPolicy:Xl,NatsConnection:C3,JetStreamManager:w3,JetStreamClient:U3,StringCodec:L3,JSONCodec:R0,createInbox:eE,StreamSource:y3,headers:A0,toJsMsg:p0,nuid:D3,JetStreamOptions:M3,ErrorCode:KA,nanos:P3}=require("nats"),{PACKAGE_ROOT:O0}=T(),N0=Ql(),ep=R0(),g0="clustering",I0=N0.engines[te.NATS_SERVER_NAME],b0=Li.join(O0,"dependencies"),zl=Li.join(b0,`${process.platform}-${process.arch}`,te.NATS_BINARY_NAME),Wl,Jl,Ci,wi,Ui,Wt;lp.exports={runCommand:tp,checkNATSServerInstalled:C0,createConnection:tE,getConnection:oc,getJetStreamManager:Rn,getJetStream:rp,getNATSReferences:Mt,getServerList:U0,createLocalStream:rE,listStreams:sp,deleteLocalStream:L0,getServerConfig:yi,listRemoteStreams:y0,viewStream:D0,publishToStream:M0,createWorkQueueStream:P0,addSourceToWorkStream:np,request:B0,removeSourceFromWorkStream:ap,reloadNATS:sE,reloadNATSHub:v0,reloadNATSLeaf:H0,extractServerName:ip,requestErrorHandler:q0,updateWorkStream:G0,createLocalTableStream:cp,createTableStreams:F0,purgeTableStream:_p,purgeSchemaTableStreams:V0,getStreamInfo:k0,updateNodeNameLocalStreams:x0,closeConnection:w0};async function tp(e,t=void 0){let{stdout:r,stderr:s}=await h0(e,{cwd:t});if(s)throw new Error(s.replace(`
|
|
6
6
|
`,""));return r.replace(`
|
|
7
|
-
`,"")}a(tp,"runCommand");async function b0(){try{await _0.access(jl)}catch{return!1}let e=await tp(`${jl} --version`,void 0),t=e.substring(e.lastIndexOf("v")+1,e.length);return u0.eq(t,g0)}a(b0,"checkNATSServerInstalled");async function rE(e,t,r,s=!0,n="127.0.0.1"){return T0({name:n,port:e,user:t,pass:r,maxReconnectAttempts:-1,waitOnFirstConnect:s,tls:{keyFile:ir.get(ne.CONFIG_PARAMS.CLUSTERING_TLS_PRIVATEKEY),certFile:ir.get(ne.CONFIG_PARAMS.CLUSTERING_TLS_CERTIFICATE),caFile:ir.get(ne.CONFIG_PARAMS.CLUSTERING_TLS_CERT_AUTH),insecure:ir.get(ne.CONFIG_PARAMS.CLUSTERING_TLS_INSECURE)}})}a(rE,"createConnection");async function C0(){Wt&&(await Wt.close(),Wt=void 0)}a(C0,"closeConnection");async function oc(){if(!Wt){let e=await ZA.getClusterUser();if(gs(e))throw new Error("Unable to get nats connection. Cluster user is undefined.");let t=ir.get(ne.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT);Wt=await rE(t,e.username,e.decrypt_hash)}return Wt}a(oc,"getConnection");async function Rn(){if(wi)return wi;gs(Wt)&&await oc();let{domain:e}=yi(ne.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);if(gs(e))throw new Error("Error getting JetStream domain. Unable to get JetStream manager.");return wi=await Wt.jetstreamManager({domain:e}),wi}a(Rn,"getJetStreamManager");async function rp(){if(Ui)return Ui;gs(Wt)&&await oc();let{domain:e}=yi(ne.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);if(gs(e))throw new Error("Error getting JetStream domain. Unable to get JetStream manager.");return Ui=Wt.jetstream({domain:e}),Ui}a(rp,"getJetStream");async function Mt(){let e=Wt||await oc(),t=wi||await Rn(),r=Ui||await rp();return{connection:e,jsm:t,js:r}}a(Mt,"getNATSReferences");async function w0(){let e=ir.get(ne.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),{sys_name:t,decrypt_hash:r}=await ZA.getClusterUser(),s=await rE(e,t,r),n=tE(),i=s.subscribe(n),o=[],c=(async()=>{for await(let _ of i)o.push(ep.decode(_.data))})();return await s.publish("$SYS.REQ.SERVER.PING.VARZ",void 0,{reply:n}),await s.flush(),await eE.async_set_timeout(50),await i.drain(),await s.close(),await c,o}a(w0,"getServerList");async function sE(e,t){let{jsm:r}=await Mt();await r.streams.add({name:e,storage:XA.File,retention:zA.Limits,subjects:t})}a(sE,"createLocalStream");async function sp(){let{jsm:e}=await Mt(),t=await e.streams.list().next(),r=[];return t.forEach(s=>{r.push(s)}),r}a(sp,"listStreams");async function U0(e){let{jsm:t}=await Mt();await t.streams.delete(e)}a(U0,"deleteLocalStream");async function L0(e){let{connection:t}=await Mt(),r=[],s=tE(),n=t.subscribe(s),i=(async()=>{for await(let o of n)r.push(ep.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(L0,"listRemoteStreams");async function y0(e,t=void 0,r=void 0){let{jsm:s,connection:n}=await Mt(),i=E0(),o=[],c={ack_policy:jA.None,durable_name:i,deliver_subject:i,deliver_policy:zl.All};t&&(c.deliver_policy=zl.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=A0(l),d=JA(E.data),S={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(","),S.originators=m)}o.push(S),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(y0,"viewStream");async function D0(e,t,r=[],s=[]){br.trace(`publishToStream called with subject: ${e}, stream: ${t}, entries:`,r,"originators:",s);let{connection:n,js:i}=await Mt(),o=await cc(),c=`${e}.${o}`,_=R0();s.push(o),_.append("originators",s.join());for(let u=0,l=r.length;u<l;u++)try{br.trace(`publishToStream publishing to subject: ${c}, data:`,r[u]),await i.publish(c,Xl(r[u]),{headers:_})}catch(E){if(E.code&&E.code.toString()==="503")br.trace(`publishToStream creating stream: ${t}`),await sE(t,[c]),await i.publish(c,Xl(r[u]),{headers:_});else throw E}}a(D0,"publishToStream");function yi(e){e=e.toLowerCase();let t=Li.join(ir.get(ne.CONFIG_PARAMS.ROOTPATH),N0);if(e===ne.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase())return gs(Zl)&&(Zl={port:bi.getConfigFromFile(ne.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),server_name:bi.getConfigFromFile(ne.CONFIG_PARAMS.CLUSTERING_NODENAME)+te.SERVER_SUFFIX.HUB,config_file:te.NATS_CONFIG_FILES.HUB_SERVER,pid_file_path:Li.join(t,te.PID_FILES.HUB),hdb_nats_path:t}),Zl;if(e===ne.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())return gs(Jl)&&(Jl={port:bi.getConfigFromFile(ne.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),server_name:bi.getConfigFromFile(ne.CONFIG_PARAMS.CLUSTERING_NODENAME)+te.SERVER_SUFFIX.LEAF,config_file:te.NATS_CONFIG_FILES.LEAF_SERVER,domain:bi.getConfigFromFile(ne.CONFIG_PARAMS.CLUSTERING_NODENAME)+te.SERVER_SUFFIX.LEAF,pid_file_path:Li.join(t,te.PID_FILES.LEAF),hdb_nats_path:t}),Jl;br.error(`Unable to get Nats server config. Unrecognized process: ${e}`)}a(yi,"getServerConfig");async function M0(e){let{jsm:t}=await Mt(),r=await cc();try{await t.streams.add({name:e.stream_name,storage:XA.File,retention:zA.Workqueue,subjects:[`${te.SUBJECT_PREFIXES.MSGID}.${r}`,`${te.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:jA.Explicit,deliver_subject:`${e.deliver_subject}.${r}`,durable_name:e.durable_name,deliver_policy:zl.All,max_ack_pending:1e4,deliver_group:e.deliver_group,filter_subject:`${te.SUBJECT_PREFIXES.TXN}.>`});else throw s}}a(M0,"createWorkQueueStream");async function np(e,t,r){let{jsm:s}=await Mt(),n=await s.streams.info(t),i=ip(s.prefix),o=r.start_time?r.start_time:new Date(Date.now()).toISOString(),{schema:c,table:_}=r,u=ac.createNatsTableStreamName(c,_),l=i===e,E,d,S=!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`){S=!0;break}if(S===!0){if(E.opt_start_time===o)return;await op(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:`${te.SUBJECT_PREFIXES.TXN}.>`};l||(m.external={api:`$JS.${e}.API`,deliver:""}),n.config.sources.push(m),await s.streams.update(t,n.config)}a(np,"addSourceToWorkStream");function ip(e){return e.split(".")[1]}a(ip,"extractServerName");async function ap(e,t,r){let{schema:s,table:n}=r,i=ac.createNatsTableStreamName(s,n),{jsm:o}=await Mt(),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 op(s,n,u,t)}a(ap,"removeSourceFromWorkStream");async function op(e,t,r,s){let n=await Rn(),i;try{i=up(e,t,r.external.api.split(".")[1]),await n.streams.purge(s,{filter:i})}catch{br.error("Error purging source subject",i,"from work stream",s)}}a(op,"purgeSourceFromWorkStream");async function P0(e,t,r=2e3,s=tE()){if(!eE.isObject(t))throw new Error("data param must be an object");let n=Xl(t),{connection:i}=await Mt(),o={timeout:r};s&&(o.reply=s,o.noMux=!0);let c=await i.request(e,n,o);return JA(c.data)}a(P0,"request");function nE(e){return new Promise(async(t,r)=>{let s=h0(jl,["--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(nE,"reloadNATS");async function B0(){let{pid_file_path:e}=yi(ne.PROCESS_DESCRIPTORS.CLUSTERING_HUB);await nE(e)}a(B0,"reloadNATSHub");async function v0(){let{pid_file_path:e}=yi(ne.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);await nE(e)}a(v0,"reloadNATSLeaf");function H0(e,t,r){let s;switch(e.code){case KA.NoResponders:s=`Unable to ${t}, node '${r}' is not listening.`;break;case KA.Timeout:s=`Unable to ${t}, node '${r}' is listening but did not respond.`;break;default:s=e.message;break}return s}a(H0,"requestErrorHandler");async function q0(e,t){let r=t+te.SERVER_SUFFIX.LEAF;await S0.writeTransaction(ne.SYSTEM_SCHEMA_NAME,ne.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,async()=>{e.subscribe===!0?await np(r,te.WORK_QUEUE_CONSUMER_NAMES.stream_name,e):await ap(r,te.WORK_QUEUE_CONSUMER_NAMES.stream_name,e)})}a(q0,"updateWorkStream");async function cp(e,t){let r=ac.createNatsTableStreamName(e,t),s=await cc(),n=up(e,t,s);await sE(r,[n])}a(cp,"createLocalTableStream");async function G0(e){for(let t=0,r=e.length;t<r;t++){let s=e[t].schema,n=e[t].table;await cp(s,n)}}a(G0,"createTableStreams");async function _p(e,t){if(ir.get(ne.CONFIG_PARAMS.CLUSTERING_ENABLED))try{let r=ac.createNatsTableStreamName(e,t),{jsm:s}=await Mt();await s.streams.purge(r)}catch(r){if(r.message==="stream not found")br.warn(r);else throw r}}a(_p,"purgeTableStream");async function F0(e,t){if(ir.get(ne.CONFIG_PARAMS.CLUSTERING_ENABLED))for(let r=0,s=t.length;r<s;r++)await _p(e,t[r])}a(F0,"purgeSchemaTableStreams");async function V0(e){return(await Rn()).streams.info(e)}a(V0,"getStreamInfo");function up(e,t,r){return`${te.SUBJECT_PREFIXES.TXN}.${e}.${t}.${r}`}a(up,"createSubjectName");async function cc(){if(Ci)return Ci;if(Ci=(await Rn())?.nc?.info?.server_name,Ci===void 0)throw new Error("Unable to get jetstream manager server name");return Ci}a(cc,"getJsmServerName");async function k0(){let e=await Rn(),t=await cc(),r=await sp();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===te.SCHEMA_QUEUE_CONSUMER_NAMES.stream_name){let _=`${te.SCHEMA_QUEUE_CONSUMER_NAMES.deliver_subject}.${t}`;br.trace(`Updating stream subject name from: ${i} to: ${_}`),n.subjects[0]=_}else if(n.name===te.WORK_QUEUE_CONSUMER_NAMES.stream_name){let _=`${te.WORK_QUEUE_CONSUMER_NAMES.stream_name}.${t}`;br.trace(`Updating stream subject name from: ${i} to: ${_}`),n.subjects[0]=_,await e.consumers.update(te.WORK_QUEUE_CONSUMER_NAMES.stream_name,te.WORK_QUEUE_CONSUMER_NAMES.durable_name,{deliver_subject:`${te.WORK_QUEUE_CONSUMER_NAMES.deliver_subject}.${t}`})}else{let _=i.split(".");_[_.length-1]=t;let u=_.join(".");br.trace(`Updating stream subject name from: ${i} to: ${u}`),n.subjects[0]=u}await e.streams.update(n.name,n)}}}a(k0,"updateNodeNameLocalStreams")});var iE=h((v3,Ep)=>{"use strict";var _c=class{constructor(t,r,s){this.timestamp=t,this.user=r,this.node_name=s}};a(_c,"ClusteringOriginObject");Ep.exports=_c});var On=h((H3,Sp)=>{"use strict";var dp=b(),Mi=V(),ue=T(),aE=fe(),An=At(),Te=g(),hp=iE(),x0=$r();Mi.initSync();var pn=aE.SCHEMA_QUEUE_CONSUMER_NAMES.stream_name,Di=aE.SCHEMA_QUEUE_CONSUMER_NAMES.deliver_subject;Sp.exports={sendAttributeTransaction:lc,postOperationHandler:Y0};async function lc(e,t,r=[]){if(!!Mi.get(ue.CONFIG_PARAMS.CLUSTERING_ENABLED)&&!dp.isEmptyOrZeroLength(e.new_attributes)&&t.schema!==ue.SYSTEM_SCHEMA_NAME){let s=t.hdb_user?.username,n=Mi.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 hp(e.txn_time,s,n)};Te.trace(`sendAttributeTransaction publishing ${pn}`,o),await An.publishToStream(Di,pn,[o],r)}}}a(lc,"sendAttributeTransaction");async function uc(e,t,r,s=[]){if(e.schema===ue.SYSTEM_SCHEMA_NAME)return;let n=$0(e,t,r);n&&(Te.trace(`sendOperationTransaction publishing to schema ${e.schema} table ${e.table} following transaction:`,n),await An.publishToStream(`${aE.SUBJECT_PREFIXES.TXN}.${e.schema}.${e.table}`,x0.createNatsTableStreamName(e.schema,e.table),[n],s))}a(uc,"sendOperationTransaction");function $0(e,t,r){if(dp.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($0,"convertCRUDOperationToTransaction");async function Y0(e,t,r=[]){if(!Mi.get(ue.CONFIG_PARAMS.CLUSTERING_ENABLED))return;Te.trace(`postOperationHandler called for operation ${e.operation} on schema.table: ${e.schema}.${e.table}`);let s=e.hdb_user?.username,n=Mi.get(ue.CONFIG_PARAMS.CLUSTERING_NODENAME),i=new hp(t.txn_time,s,n);switch(e.operation){case ue.OPERATIONS_ENUM.INSERT:try{await uc(e,t.inserted_hashes,i,r),await lc(t,e,r)}catch(o){Te.error("There was an error calling clustering postOperationHandler for insert."),Te.error(o)}break;case ue.OPERATIONS_ENUM.DELETE:try{await uc(e,t.deleted_hashes,i,r)}catch(o){Te.error("There was an error calling clustering postOperationHandler for delete."),Te.error(o)}break;case ue.OPERATIONS_ENUM.UPDATE:try{await uc(e,t.update_hashes,i,r),await lc(t,e,r)}catch(o){Te.error("There was an error calling clustering postOperationHandler for update."),Te.error(o)}break;case ue.OPERATIONS_ENUM.UPSERT:try{await uc(e,t.upserted_hashes,i,r),await lc(t,e,r)}catch(o){Te.error("There was an error calling clustering postOperationHandler for upsert."),Te.error(o)}break;case ue.OPERATIONS_ENUM.CREATE_SCHEMA:try{let o={operation:ue.OPERATIONS_ENUM.CREATE_SCHEMA,schema:e.schema,__origin:i};await An.publishToStream(Di,pn,[o],r)}catch(o){Te.error("There was an error calling clustering postOperationHandler for create_schema."),Te.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 An.publishToStream(Di,pn,[o],r)}catch(o){Te.error("There was an error calling clustering postOperationHandler for create_table."),Te.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 An.publishToStream(Di,pn,[o],r)}catch(o){Te.error("There was an error calling clustering postOperationHandler for create_attribute."),Te.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 An.publishToStream(Di,pn,[o],r)}catch(o){Te.error("There was an error calling clustering postOperationHandler for csv_data_load."),Te.error(o)}break;default:break}return t}a(Y0,"postOperationHandler")});var Ap=h((q3,Rp)=>{"use strict";var K0=mt(),Q0=Kr(),fp=g(),Tp=yt(),W0=ic(),J0=require("clone"),cE=require("alasql"),Z0=yo(),mp=require("util"),X0=mp.promisify(Q0.getTableSchema),z0=mp.promisify(K0.search),j0=T(),oE=b(),eV=On();Z0(cE);Rp.exports={update:rV};var tV="There was a problem performing this update. Please check the logs and try again.";async function rV({statement:e,hdb_user:t}){let r=await X0(e.table.databaseid,e.table.tableid),s=sV(e.columns);oE.backtickASTSchemaItems(e);let{table:n,where:i}=e,o=J0(n),c=oE.isEmpty(i)?"":` WHERE ${i.toString()}`,_=`SELECT ${r.hash_attribute} FROM ${n.toString()} ${c}`,u=cE.parse(_).statements[0],l=await W0.writeTransaction(r.schema,r.name,async()=>{let E=await z0(u),d=nV(s,E);return iV(o,d,t)});return await Tp.flush({schema:r.schema,table:r.name}),l}a(rV,"update");function sV(e){try{let t={};return e.forEach(r=>{"value"in r.expression?t[r.column.columnid]=r.expression.value:t[r.column.columnid]=cE.compile(`SELECT ${r.expression.toString()} AS [${j0.FUNC_VAL}] FROM ?`)}),t}catch(t){throw fp.error(t),new Error(tV)}}a(sV,"createUpdateRecord");function nV(e,t){return oE.isEmptyOrZeroLength(t)?[]:t.map(r=>Object.assign(r,e))}a(nV,"buildUpdateRecords");async function iV(e,t,r){let s={operation:"update",schema:e.databaseid_orig,table:e.tableid_orig,records:t,hdb_user:r};try{let n=await Tp.update(s);await eV.postOperationHandler(s,n);try{delete n.new_attributes,delete n.txn_time}catch(i){fp.error(`Error delete new_attributes from update response: ${i}`)}return n}catch(n){throw n}}a(iV,"updateRecords")});var Op=h((G3,pp)=>{var aV=require("alasql"),oV=mt(),cV=g(),_V=Nr(),uE=require("util"),_E=b(),uV=T(),lV=Kr(),EV=ic(),dV=On(),hV=yt(),SV="record",fV="successfully deleted",TV=uE.callbackify(pV),mV=uE.promisify(oV.search),RV=uE.promisify(lV.getTableSchema);pp.exports={convertDelete:TV};function AV(e){return`${e.deleted_hashes.length} ${SV}${e.deleted_hashes.length===1?"":"s"} ${fV}`}a(AV,"generateReturnMessage");async function pV({statement:e,hdb_user:t}){let r=await RV(e.table.databaseid,e.table.tableid);_E.backtickASTSchemaItems(e);let{table:s,where:n}=e,i=_E.isEmpty(n)?"":` WHERE ${n.toString()}`,o=`SELECT ${r.hash_attribute} FROM ${s.toString()} ${i}`,c=aV.parse(o).statements[0],_={operation:uV.OPERATIONS_ENUM.DELETE,schema:s.databaseid_orig,table:s.tableid_orig,hdb_user:t};try{let u=await EV.writeTransaction(r.schema,r.name,async()=>(_.records=await mV(c),_V.deleteRecords(_)));return await hV.flush({schema:r.schema,table:r.name}),u.deleted_hashes.length>0&&await dV.postOperationHandler(_,u),_E.isEmptyOrZeroLength(u.message)&&(u.message=AV(u)),delete u.txn_time,u}catch(u){throw cV.error(u),u.hdb_code?u.message:u}}a(pV,"convertDelete")});var Ip=h((F3,gp)=>{"use strict";var EE=ms(),{hdb_errors:lE}=D();gp.exports={checkSchemaExists:Np,checkSchemaTableExists:OV,schema_describe:EE};async function Np(e){if(!global.hdb_schema[e])try{let t=await EE.describeSchema({schema:e});global.hdb_schema[e]=t}catch{return lE.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}}a(Np,"checkSchemaExists");async function OV(e,t){let r=await Np(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 lE.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t);global.hdb_schema[e][t]=s}catch{return lE.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}}a(OV,"checkSchemaTableExists")});var Ec=h((k3,Lp)=>{"use strict";var Nn=Wa(),Is=Ip(),bp=g(),NV=require("uuid").v4,V3=require("clone"),In=js(),bs=T(),gV=require("util"),Cs=Nr(),{handleHDBError:Be,hdb_errors:IV}=D(),{HDB_ERROR_MSGS:gn,HTTP_STATUS_CODES:ve}=IV,{SchemaEventMsg:bn}=Vr(),Cp=At();Lp.exports={createSchema:bV,createSchemaStructure:wp,createTable:CV,createTableStructure:Up,createAttribute:DV,dropSchema:wV,dropTable:UV,dropAttribute:LV};async function bV(e){try{let t=await wp(e);return In.signalSchemaChange(new bn(process.pid,e.operation,e.schema)),t}catch(t){throw t}}a(bV,"createSchema");async function wp(e){let t=Nn.schema_object(e);if(t)throw Be(t,t.message,ve.BAD_REQUEST,void 0,void 0,!0);if(!await Is.checkSchemaExists(e.schema))throw Be(new Error,gn.SCHEMA_EXISTS_ERR(e.schema),ve.BAD_REQUEST,bs.LOG_LEVELS.ERROR,gn.SCHEMA_EXISTS_ERR(e.schema),!0);try{return await Cs.createSchema(e),`schema '${e.schema}' successfully created`}catch(r){throw r}}a(wp,"createSchemaStructure");async function CV(e){try{let t=await Up(e);return In.signalSchemaChange(new bn(process.pid,e.operation,e.schema,e.table)),t}catch(t){throw t}}a(CV,"createTable");async function Up(e){let t=Nn.create_table_object(e);if(t)throw Be(t,t.message,ve.BAD_REQUEST,void 0,void 0,!0);Nn.validateTableResidence(e.residence);let r=await Is.checkSchemaExists(e.schema);if(r)throw Be(new Error,r,ve.NOT_FOUND,bs.LOG_LEVELS.ERROR,r,!0);if(!await Is.checkSchemaTableExists(e.schema,e.table))throw Be(new Error,gn.TABLE_EXISTS_ERR(e.schema,e.table),ve.BAD_REQUEST,bs.LOG_LEVELS.ERROR,gn.TABLE_EXISTS_ERR(e.schema,e.table),!0);let n={name:e.table,schema:e.schema,id:NV(),hash_attribute:e.hash_attribute};try{if(e.residence)if(global.clustering_on)n.residence=e.residence,await Cs.createTable(n,e);else throw Be(new Error,"Clustering does not appear to be enabled. Cannot insert table with property 'residence'.",ve.BAD_REQUEST);else await Cs.createTable(n,e);return`table '${e.schema}.${e.table}' successfully created.`}catch(i){throw i}}a(Up,"createTableStructure");async function wV(e){let t=Nn.schema_object(e);if(t)throw Be(t,t.message,ve.BAD_REQUEST,void 0,void 0,!0);let r=await Is.checkSchemaExists(e.schema);if(r)throw Be(new Error,r,ve.NOT_FOUND,bs.LOG_LEVELS.ERROR,r,!0);let s=await Is.schema_describe.describeSchema({schema:e.schema});global.hdb_schema[e.schema]=s;let n=Object.keys(global.hdb_schema[e.schema]);return await Cs.dropSchema(e),In.signalSchemaChange(new bn(process.pid,e.operation,e.schema)),delete global.hdb_schema[e.schema],await Cp.purgeSchemaTableStreams(e.schema,n),`successfully deleted schema '${e.schema}'`}a(wV,"dropSchema");async function UV(e){let t=Nn.table_object(e);if(t)throw Be(t,t.message,ve.BAD_REQUEST,void 0,void 0,!0);let r=await Is.checkSchemaTableExists(e.schema,e.table);if(r)throw Be(new Error,r,ve.NOT_FOUND,bs.LOG_LEVELS.ERROR,r,!0);return await Cs.dropTable(e),In.signalSchemaChange(new bn(process.pid,e.operation,e.schema,e.table)),await Cp.purgeTableStream(e.schema,e.table),`successfully deleted table '${e.schema}.${e.table}'`}a(UV,"dropTable");async function LV(e){let t=Nn.attribute_object(e);if(t)throw Be(t,t.message,ve.BAD_REQUEST,void 0,void 0,!0);let r=await Is.checkSchemaTableExists(e.schema,e.table);if(r)throw Be(new Error,r,ve.NOT_FOUND,bs.LOG_LEVELS.ERROR,r,!0);if(e.attribute===global.hdb_schema[e.schema][e.table].hash_attribute)throw Be(new Error,"You cannot drop a hash attribute",ve.BAD_REQUEST,void 0,void 0,!0);if(bs.TIME_STAMP_NAMES.indexOf(e.attribute)>=0)throw Be(new Error,`cannot drop internal timestamp attribute: ${e.attribute}`,ve.BAD_REQUEST,void 0,void 0,!0);try{return await Cs.dropAttribute(e),yV(e),In.signalSchemaChange(new bn(process.pid,e.operation,e.schema,e.table,e.attribute)),`successfully deleted attribute '${e.attribute}'`}catch(s){throw bp.error(`Got an error deleting attribute ${gV.inspect(e)}.`),s}}a(LV,"dropAttribute");function yV(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(yV,"dropAttributeFromGlobal");async function DV(e){if(!global.hdb_schema[e.schema])throw Be(new Error,gn.SCHEMA_NOT_FOUND(e.schema),ve.NOT_FOUND,void 0,void 0,!0);if(!global.hdb_schema[e.schema][e.table])throw Be(new Error,gn.TABLE_NOT_FOUND(e.schema,e.table),ve.NOT_FOUND,void 0,void 0,!0);try{return await Cs.createAttribute(e),In.signalSchemaChange(new bn(process.pid,e.operation,e.schema,e.table,e.attribute)),`attribute '${e.schema}.${e.table}.${e.attribute}' successfully created.`}catch(t){throw bp.error(t),t}}a(DV,"createAttribute")});var Dp=h((x3,yp)=>{"use strict";var{OPERATIONS_ENUM:MV}=T(),dc=class{constructor(t,r,s=void 0,n=void 0){this.operation=MV.READ_AUDIT_LOG,this.schema=t,this.table=r,this.search_type=s,this.search_values=n}};a(dc,"ReadAuditLogObject");yp.exports=dc});var dE=h((Y3,Hp)=>{"use strict";var PV=Nr(),$3=Dp(),hc=b(),Sc=T(),BV=V(),{handleHDBError:Mp,hdb_errors:vV}=D(),{HDB_ERROR_MSGS:Pp,HTTP_STATUS_CODES:Bp}=vV,HV=Object.values(Sc.READ_AUDIT_LOG_SEARCH_TYPES_ENUM),vp="To use this operation audit log must be enabled in harperdb-config.yaml";Hp.exports=qV;async function qV(e){if(hc.isEmpty(e.schema))throw new Error(Pp.SCHEMA_REQUIRED_ERR);if(hc.isEmpty(e.table))throw new Error(Pp.TABLE_REQUIRED_ERR);if(!BV.get(Sc.CONFIG_PARAMS.LOGGING_AUDITLOG))throw Mp(new Error,vp,Bp.BAD_REQUEST,Sc.LOG_LEVELS.ERROR,vp,!0);let t=hc.checkSchemaTableExist(e.schema,e.table);if(t)throw Mp(new Error,t,Bp.NOT_FOUND,Sc.LOG_LEVELS.ERROR,t,!0);if(!hc.isEmpty(e.search_type)&&HV.indexOf(e.search_type)<0)throw new Error(`Invalid search_type '${e.search_type}'`);return await PV.readAuditLog(e)}a(qV,"readAuditLog")});var xp=h((K3,kp)=>{var zr=require("validate.js"),Gp=he(),Cn=T(),{handleHDBError:GV,hdb_errors:FV}=D(),{HDB_ERROR_MSGS:le,HTTP_STATUS_CODES:VV}=FV,hE=a(()=>({role:{presence:!0,format:"[\\w\\-\\_]+"},id:{presence:!0,format:"[\\w\\-\\_]+"},permission:{presence:!0}}),"constraintsTemplate"),kV={STRUCTURE_USER:"structure_user"},qp=Object.values(Cn.ROLE_TYPES_ENUM),xV="attribute_permissions",$V="attribute_name",{PERMS_CRUD_ENUM:wn}=Cn,YV=[xV,...Object.values(wn)],Fp=[wn.READ,wn.INSERT,wn.UPDATE],KV=[$V,...Fp];function QV(e){let t=hE();return t.role.presence=!0,t.id.presence=!1,t.permission.presence=!0,Vp(e,t)}a(QV,"addRoleValidation");function WV(e){let t=hE();return t.role.presence=!1,t.id.presence=!0,t.permission.presence=!0,Vp(e,t)}a(WV,"alterRoleValidation");function JV(e){let t=hE();return t.role.presence=!1,t.id.presence=!0,t.permission.presence=!1,Gp.validateObject(e,t)}a(JV,"dropRoleValidation");var ZV=["operation","role","id","permission","hdb_user","hdb_auth_header"];function Vp(e,t){let r={main_permissions:[],schema_permissions:{}},s=Object.keys(e),n=[];for(let o=0,c=s.length;o<c;o++)ZV.includes(s[o])||n.push(s[o]);n.length>0&&me(le.INVALID_ROLE_JSON_KEYS(n),r);let i=Gp.validateObject(e,t);if(i&&i.message.split(",").forEach(o=>{me(o,r)}),e.permission){let o=XV(e);o&&me(o,r),qp.forEach(c=>{e.permission[c]&&!zr.isBoolean(e.permission[c])&&me(le.SU_CU_ROLE_BOOLEAN_ERROR(c),r)})}for(let o in e.permission)if(qp.indexOf(o)<0){if(o===kV.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]||me(le.SCHEMA_NOT_FOUND(E),r)}continue}me(le.STRUCTURE_USER_ROLE_TYPE_ERROR(o),r);continue}let c=e.permission[o];if(!o||!global.hdb_schema[o]){me(le.SCHEMA_NOT_FOUND(o),r);continue}if(c.tables)for(let _ in c.tables){let u=c.tables[_];if(!_||!global.hdb_schema[o][_]){me(le.TABLE_NOT_FOUND(o,_),r);continue}if(Object.keys(u).forEach(l=>{YV.includes(l)||me(le.INVALID_PERM_KEY(l),r,o,_)}),Object.values(wn).forEach(l=>{zr.isDefined(u[l])?zr.isBoolean(u[l])||me(le.TABLE_PERM_NOT_BOOLEAN(l),r,o,_):me(le.TABLE_PERM_MISSING(l),r,o,_)}),zr.isDefined(u.attribute_permissions)){if(!zr.isArray(u.attribute_permissions)){me(le.ATTR_PERMS_NOT_ARRAY,r,o,_);continue}}else{me(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 S=u.attribute_permissions[d];if(Object.keys(S).forEach(R=>{!KV.includes(R)&&R!==wn.DELETE&&me(le.INVALID_ATTR_PERM_KEY(R),r,o,_)}),!zr.isDefined(S.attribute_name)){me(le.ATTR_PERM_MISSING_NAME,r,o,_);continue}let m=S.attribute_name;if(!l.includes(m)){me(le.INVALID_ATTRIBUTE_IN_PERMS(m),r,o,_);continue}Fp.forEach(R=>{zr.isDefined(S[R])?zr.isBoolean(S[R])||me(le.ATTR_PERM_NOT_BOOLEAN(R,m),r,o,_):me(le.ATTR_PERM_MISSING(R,m),r,o,_)}),!E.read&&S.read===!0&&(E.read=!0),!E.insert&&S.insert===!0&&(E.insert=!0),!E.update&&S.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}.${_}`;me(le.MISMATCHED_TABLE_ATTR_PERMS(d),r,o,_)}}}}return zV(r)}a(Vp,"customValidate");kp.exports={addRoleValidation:QV,alterRoleValidation:WV,dropRoleValidation:JV};function XV(e){let{operation:t,permission:r}=e;if(t===Cn.OPERATIONS_ENUM.ADD_ROLE||t===Cn.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?Cn.ROLE_TYPES_ENUM.SUPER_USER:Cn.ROLE_TYPES_ENUM.CLUSTER_USER;return le.SU_CU_ROLE_NO_PERMS_ALLOWED(o)}}}return null}a(XV,"validateNoSUPerms");function zV(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 GV(new Error,s,VV.BAD_REQUEST)}else return null}a(zV,"generateRolePermResponse");function me(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(me,"addPermError")});var OE=h((Q3,Jp)=>{"use strict";var $p=yt(),Yp=mt(),jV=ps(),TE=xp(),mE=js(),ek=require("uuid").v4,RE=require("util"),tk=pi(),Cr=T(),Kp=b(),AE=RE.promisify(Yp.searchByValue),rk=RE.promisify(Yp.searchByHash),sk=RE.promisify(jV.delete),nk=Qt(),ik=Ss(),{hdb_errors:ak,handleHDBError:Pi}=D(),{HDB_ERROR_MSGS:Qp,HTTP_STATUS_CODES:SE}=ak,{UserEventMsg:pE}=Vr();Jp.exports={addRole:ok,alterRole:_k,dropRole:uk,listRoles:Wp};function fE(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(fE,"scrubRoleDetails");async function ok(e){let t=TE.addRoleValidation(e);if(t)throw t;if(!(await tk.getLicense()).enterprise){let o=await Wp();if(ck(e,o))throw new Error(`Your current license only supports ${Cr.BASIC_LICENSE_MAX_CLUSTER_USER_ROLES} cluster_user role. ${Cr.SUPPORT_HELP_MSG}`);if(o.length>=2)throw new Error(`Your current license only supports ${Cr.BASIC_LICENSE_MAX_NON_CU_ROLES+Cr.BASIC_LICENSE_MAX_CLUSTER_USER_ROLES} roles. ${Cr.SUPPORT_HELP_MSG}`)}e=fE(e);let s={schema:"system",table:"hdb_role",search_attribute:"role",search_value:e.role,hash_attribute:"id",get_attributes:["*"]},n;try{n=await AE(s)}catch(o){throw Pi(o)}if(n&&n.length>0)throw Pi(new Error,Qp.ROLE_ALREADY_EXISTS(e.role),SE.CONFLICT,void 0,void 0,!0);e.id||(e.id=ek());let i={operation:"insert",schema:"system",table:"hdb_role",hash_attribute:"id",records:[e]};return await $p.insert(i),mE.signalUserChange(new pE(process.pid)),e=fE(e),e}a(ok,"addRole");function ck(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(!Kp.isEmpty(i)&&i.cluster_user===!0)return!0}return r}a(ck,"checkClusterUserRole");async function _k(e){let t=TE.alterRoleValidation(e);if(t)throw t;e=fE(e);let r={operation:"update",schema:"system",table:"hdb_role",hash_attribute:"rolename",records:[e]};try{await $p.update(r)}catch(s){throw Pi(s)}return mE.signalUserChange(new pE(process.pid)),e}a(_k,"alterRole");async function uk(e){let t=TE.dropRoleValidation(e);if(t)throw Pi(new Error,t,SE.BAD_REQUEST,void 0,void 0,!0);let r=new ik(Cr.SYSTEM_SCHEMA_NAME,Cr.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME,[e.id],["role"]),s=await rk(r);if(s.length===0)throw Pi(new Error,Qp.ROLE_NOT_FOUND,SE.NOT_FOUND,void 0,void 0,!0);let n=new nk(Cr.SYSTEM_SCHEMA_NAME,Cr.SYSTEM_TABLE_NAMES.USER_TABLE_NAME,"role",e.id,void 0,["username","active"]),i=await AE(n),o=!1;if(Kp.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 sk(c),mE.signalUserChange(new pE(process.pid)),`${s[0].role} successfully deleted`}a(uk,"dropRole");async function Wp(){return AE({table:"hdb_role",schema:"system",hash_attribute:"id",search_attribute:"id",search_value:"*",get_attributes:["*"]})}a(Wp,"listRoles")});var jp=h((W3,zp)=>{"use strict";var lk=V(),jr=require("joi"),Ek=he(),Zp=require("moment"),dk=require("fs-extra"),NE=require("path"),hk=require("lodash"),Bi=T(),{LOG_LEVELS:ws}=T(),Sk="YYYY-MM-DD hh:mm:ss",fk=NE.resolve(__dirname,"../logs");zp.exports=function(e){return Ek.validateBySchema(e,Tk)};var Tk=jr.object({from:jr.custom(Xp),until:jr.custom(Xp),level:jr.valid(ws.NOTIFY,ws.FATAL,ws.ERROR,ws.WARN,ws.INFO,ws.DEBUG,ws.TRACE),order:jr.valid("asc","desc"),limit:jr.number().min(1),start:jr.number().min(0),log_name:jr.custom(mk)});function Xp(e,t){if(Zp(e,Zp.ISO_8601).format(Sk)==="Invalid date")return t.message(`'${t.state.path[0]}' date '${e}' is invalid.`)}a(Xp,"validateDatetime");function mk(e,t){if(hk.invert(Bi.PROCESS_LOG_NAMES)[e]===void 0)return t.message(`'log_name' '${e}' is invalid.`);let s=lk.get(Bi.HDB_SETTINGS_NAMES.LOG_PATH_KEY),n=e===void 0?Bi.PROCESS_LOG_NAMES.HDB:e,i=n===Bi.PROCESS_LOG_NAMES.INSTALL?NE.join(fk,Bi.PROCESS_LOG_NAMES.INSTALL):NE.join(s,n);return dk.existsSync(i)?null:t.message(`'log_name' '${e}' does not exist.`)}a(mk,"validateReadLogPath")});var IE=h((J3,tO)=>{"use strict";var fc=T(),eO=g(),Rk=V(),Ak=jp(),gE=require("path"),pk=require("fs-extra"),Ok=require("readline"),{once:Nk}=require("events"),{handleHDBError:gk,hdb_errors:Ik}=D(),{PACKAGE_ROOT:bk}=T(),Ck=gE.join(bk,"logs"),wk=1e3;tO.exports=Uk;async function Uk(e){let t=Ak(e);if(t)throw gk(t,t.message,Ik.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0);let r=Rk.get(fc.HDB_SETTINGS_NAMES.LOG_PATH_KEY),s=e.log_name===void 0?fc.PROCESS_LOG_NAMES.HDB:e.log_name,n=s===fc.PROCESS_LOG_NAMES.INSTALL?gE.join(Ck,fc.PROCESS_LOG_NAMES.INSTALL):gE.join(r,s),i=pk.createReadStream(n);i.on("error",j=>{eO.error(j)});let o=Ok.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,S=e.limit===void 0?wk:e.limit,m=e.order===void 0?void 0:e.order,R=e.start===void 0?0:e.start,w=R+S,U=0,B=[];return o.on("line",j=>{let k,J,xe,$e;try{k=JSON.parse(j)}catch(Ea){eO.warn(Ea.message);return}switch(!0){case(c&&u&&E):J=new Date(k.timestamp),xe=new Date(l),$e=new Date(d),k.level===_&&J>=xe&&J<=$e&&U<R?U++:k.level===_&&J>=xe&&J<=$e&&(ts(k,m,B),U++,U===w&&es(o));break;case(c&&u):J=new Date(k.timestamp),xe=new Date(l),k.level===_&&J>=xe&&U<R?U++:k.level===_&&J>=xe&&(ts(k,m,B),U++,U===w&&es(o));break;case(c&&E):J=new Date(k.timestamp),$e=new Date(d),k.level===_&&J<=$e&&U<R?U++:k.level===_&&J<=$e&&(ts(k,m,B),U++,U===w&&es(o));break;case(u&&E):J=new Date(k.timestamp),xe=new Date(l),$e=new Date(d),J>=xe&&J<=$e&&U<R?U++:J>=xe&&J<=$e&&(ts(k,m,B),U++,U===w&&es(o));break;case c:k.level===_&&U<R?U++:k.level===_&&(ts(k,m,B),U++,U===w&&es(o));break;case u:J=new Date(k.timestamp),xe=new Date(l),J>=xe&&U<R?U++:J>=xe&&U>=R&&(ts(k,m,B),U++,U===w&&es(o));break;case E:J=new Date(k.timestamp),$e=new Date(d),J<=$e&&U<R?U++:J<=$e&&U>=R&&(ts(k,m,B),U++,U===w&&es(o));break;default:U<R?U++:(ts(k,m,B),U++,U===w&&es(o))}}),await Nk(o,"close"),B}a(Uk,"readLog");function es(e){e.close(),e.removeAllListeners()}a(es,"endReadLine");function ts(e,t,r){t==="desc"?Lk(e,r):t==="asc"?yk(e,r):r.push(e)}a(ts,"pushLineToResult");function Lk(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(Lk,"insertDescending");function yk(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(yk,"insertAscending")});var mc=h((z3,nO)=>{"use strict";var bE=require("joi"),{string:Tc,boolean:rO,date:Dk}=bE.types(),Mk=he(),{validateSchemaExists:Z3,validateTableExists:X3,validateSchemaName:Pk}=Rr(),Bk=T(),vk=fe(),Hk=V(),qk=Tc.invalid(Hk.get(Bk.CONFIG_PARAMS.CLUSTERING_NODENAME)).pattern(vk.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(),sO={operation:Tc.valid("add_node","update_node"),node_name:qk,subscriptions:bE.array().items({table:Tc.required(),schema:Tc.custom(Pk).required(),subscribe:rO.required(),publish:rO.required().custom(Fk),start_time:Dk.iso()}).min(1).required()};function Gk(e){return Mk.validateBySchema(e,bE.object(sO))}a(Gk,"addUpdateNodeValidator");function Fk(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(Fk,"checkForFalsy");nO.exports={addUpdateNodeValidator:Gk,validation_schema:sO}});var Un=h((j3,iO)=>{"use strict";var Rc=class{constructor(t,r,s){this.name=t,this.subscriptions=r,this.system_info=s}};a(Rc,"Node");var Ac=class{constructor(t,r,s,n){this.schema=t,this.table=r,this.publish=s,this.subscribe=n}};a(Ac,"NodeSubscription");iO.exports={Node:Rc,NodeSubscription:Ac}});var oO=h((e2,aO)=>{"use strict";var Vk=T().OPERATIONS_ENUM,pc=class{constructor(t,r,s,n=void 0){this.operation=Vk.UPSERT,this.schema=t,this.table=r,this.records=s,this.__origin=n}};a(pc,"UpsertObject");aO.exports=pc});var vi=h((t2,cO)=>{"use strict";var Oc=class{constructor(t,r,s,n){this.operation=t,this.node_name=r,this.subscriptions=s,this.system_info=n}};a(Oc,"RemotePayloadObject");var Nc=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(Nc,"RemotePayloadSubscription");cO.exports={RemotePayloadObject:Oc,RemotePayloadSubscription:Nc}});var uO=h((r2,_O)=>{"use strict";var gc=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(gc,"TableSizeObject");_O.exports=gc});var hO=h((s2,dO)=>{"use strict";var kk=uO(),lO=require("path"),EO=re(),xk=Ke(),Ln=X(),$k=g();dO.exports=Yk;async function Yk(e){let t=new kk;try{let r=lO.join(EO.getBaseSchemaPath(),e.schema.toString()),s=await Ln.openEnvironment(r,e.name),n=Ln.statDBI(s,e.hash_attribute),i=lO.join(EO.getTransactionAuditStorePath(),e.schema.toString()),o=await Ln.openEnvironment(i,e.name,!0),c=Ln.statDBI(o,xk.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP),_=await Ln.environmentDataSize(r,e.name),u=await Ln.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){$k.warn(`unable to stat table dbi due to ${r}`)}return t}a(Yk,"lmdbGetTableSize")});var fO=h((n2,SO)=>{"use strict";var Kk=T(),Ic=class{constructor(t){this.operator=Kk.OPERATIONS_ENUM.SYSTEM_INFORMATION,this.attributes=t}};a(Ic,"SystemInformationOperation");SO.exports=Ic});var mO=h((i2,TO)=>{"use strict";var bc=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(bc,"SystemInformationObject");TO.exports=bc});var wc=h((o2,RO)=>{"use strict";var He=require("systeminformation"),yn=g(),Qk=T(),Wk=hO(),Jk=ms(),Zk=V();Zk.initSync();var a2=fO(),Xk=mO(),Cc;RO.exports={getHDBProcessInfo:LE,getNetworkInfo:DE,getDiskInfo:yE,getMemoryInfo:UE,getCPUInfo:wE,getTimeInfo:CE,getSystemInformation:ME,systemInformation:zk,getTableSize:PE};function CE(){return He.time()}a(CE,"getTimeInfo");async function wE(){try{let{family:e,model:t,stepping:r,revision:s,voltage:n,speedmin:i,speedmax:o,governor:c,socket:_,cache:u,...l}=await He.cpu();l.cpu_speed=await He.cpuCurrentSpeed();let{raw_currentload:E,raw_currentload_idle:d,raw_currentload_irq:S,raw_currentload_nice:m,raw_currentload_system:R,raw_currentload_user:w,cpus:U,...B}=await He.currentLoad();return B.cpus=[],U.forEach(j=>{let{raw_load:k,raw_load_idle:J,raw_load_irq:xe,raw_load_nice:$e,raw_load_system:Ea,raw_load_user:da,...Pr}=j;B.cpus.push(Pr)}),l.current_load=B,l}catch(e){return yn.error(`error in getCPUInfo: ${e}`),{}}}a(wE,"getCPUInfo");async function UE(){try{let{buffers:e,cached:t,slab:r,buffcache:s,...n}=await He.mem();return n}catch(e){return yn.error(`error in getMemoryInfo: ${e}`),{}}}a(UE,"getMemoryInfo");async function LE(){let e={core:[],clustering:[]};try{return(await He.processes()).list.forEach(r=>{r.params.includes(Qk.HDB_PROC_NAME)?e.core.push(r):r.params.includes("socketcluster")&&e.clustering.push(r)}),e}catch(t){return yn.error(`error in getHDBProcessInfo: ${t}`),e}}a(LE,"getHDBProcessInfo");async function yE(){let e={};try{let{rIO_sec:t,wIO_sec:r,tIO_sec:s,ms:n,...i}=await He.disksIO();e.io=i;let{rx_sec:o,tx_sec:c,wx_sec:_,...u}=await He.fsStats();return e.read_write=u,e.size=await He.fsSize(),e}catch(t){return yn.error(`error in getDiskInfo: ${t}`),e}}a(yE,"getDiskInfo");async function DE(){let e={default_interface:null,latency:{},interfaces:[],stats:[],connections:[]};try{return e.default_interface=await He.networkInterfaceDefault(),e.latency=await He.inetChecksite("google.com"),(await He.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 He.networkStats()).forEach(s=>{let{rx_sec:n,tx_sec:i,ms:o,...c}=s;e.stats.push(c)}),e.connections=await He.networkConnections(),e}catch(t){return yn.error(`error in getNetworkInfo: ${t}`),e}}a(DE,"getNetworkInfo");async function ME(){if(Cc!==void 0)return Cc;let e={};try{let{codepage:t,logofile:r,serial:s,build:n,servicepack:i,uefi:o,...c}=await He.osInfo();e=c;let _=await He.versions("node, npm");return e.node_version=_.node,e.npm_version=_.npm,Cc=e,Cc}catch(t){return yn.error(`error in getSystemInformation: ${t}`),e}}a(ME,"getSystemInformation");async function PE(){let e=[],t=await Jk.describeAll();for(let r of Object.values(t))for(let s of Object.values(r))e.push(await Wk(s));return e}a(PE,"getTableSize");async function zk(e){let t=new Xk;if(!Array.isArray(e.attributes)||e.attributes.length===0)return t.system=await ME(),t.time=CE(),t.cpu=await wE(),t.memory=await UE(),t.disk=await yE(),t.network=await DE(),t.harperdb_processes=await LE(),t.table_size=await PE(),t;for(let r=0;r<e.attributes.length;r++)switch(e.attributes[r]){case"system":t.system=await ME();break;case"time":t.time=CE();break;case"cpu":t.cpu=await wE();break;case"memory":t.memory=await UE();break;case"disk":t.disk=await yE();break;case"network":t.network=await DE();break;case"harperdb_processes":t.harperdb_processes=await LE();break;case"table_size":t.table_size=await PE();break;default:break}return t}a(zk,"systemInformation")});var BE=h((u2,AO)=>{"use strict";var c2=require("fs-extra"),_2=g();AO.exports={version:jk,printVersion:tx,nodeVersion:ex};var rs=Wl();function jk(){if(rs)return rs.version}a(jk,"version");function ex(){if(rs&&rs.engines&&rs.engines["preferred-node"])return rs.engines["preferred-node"]}a(ex,"nodeVersion");function tx(){rs&&console.log(`HarperDB Version ${rs.version}`)}a(tx,"printVersion")});var Ls=h((d2,gO)=>{"use strict";var rx=yt(),vE=b(),HE=require("util"),Us=T(),pO=V();pO.initSync();var sx=Ql(),OO=mt(),{Node:l2,NodeSubscription:E2}=Un(),nx=Ss(),ix=oO(),{RemotePayloadObject:ax,RemotePayloadSubscription:ox}=vi(),{handleHDBError:cx,hdb_errors:_x}=D(),{HTTP_STATUS_CODES:ux,HDB_ERROR_MSGS:lx}=_x,Ex=Qt(),dx=wc(),hx=BE(),Sx=HE.promisify(sx.authorize),fx=HE.promisify(OO.searchByHash),Tx=HE.promisify(OO.searchByValue);gO.exports={authHeaderToUser:mx,isEmpty:Rx,getNodeRecord:Ax,upsertNodeRecord:px,buildNodePayloads:Ox,checkClusteringEnabled:Nx,getAllNodeRecords:gx,getSystemInfo:Ix,reverseSubscription:NO};async function mx(e){let t={headers:{authorization:e.hdb_auth_header}};return e.hdb_user=await Sx(t,null),e}a(mx,"authHeaderToUser");function Rx(e){return e==null}a(Rx,"isEmpty");async function Ax(e){let t=new nx(Us.SYSTEM_SCHEMA_NAME,Us.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[e],["*"]);return fx(t)}a(Ax,"getNodeRecord");async function px(e){let t=new ix(Us.SYSTEM_SCHEMA_NAME,Us.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[e]);return rx.upsert(t)}a(px,"upsertNodeRecord");function NO(e){if(vE.isEmpty(e.subscribe)||vE.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(NO,"reverseSubscription");function Ox(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=vE.getTableHashAttribute(_,u),{subscribe:E,publish:d}=NO(c),S=new ox(_,u,l,d,E,c.start_time);n.push(S)}return new ax(r,t,n,s)}a(Ox,"buildNodePayloads");function Nx(){if(!pO.get(Us.CONFIG_PARAMS.CLUSTERING_ENABLED))throw cx(new Error,lx.CLUSTERING_NOT_ENABLED,ux.BAD_REQUEST,void 0,void 0,!0)}a(Nx,"checkClusteringEnabled");async function gx(){let e=new Ex(Us.SYSTEM_SCHEMA_NAME,Us.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,"name","*",void 0,["*"]);return Tx(e)}a(gx,"getAllNodeRecords");async function Ix(){let e=await dx.getSystemInformation();return{hdb_version:hx.version(),node_version:e.node_version,platform:e.platform}}a(Ix,"getSystemInfo")});var GE=h((h2,LO)=>{"use strict";var qE=At(),IO=b(),bO=fe(),bx=T(),Uc=g(),CO=Ec(),Cx=nl(),{RemotePayloadObject:wx}=vi(),{handleHDBError:wO,hdb_errors:Ux}=D(),{HTTP_STATUS_CODES:UO}=Ux,{NodeSubscription:Lx}=Un();LO.exports=yx;async function yx(e,t){let r;try{r=await qE.request(`${t}.${bO.REQUEST_SUFFIX}`,new wx(bx.OPERATIONS_ENUM.DESCRIBE_ALL,t,void 0,void 0)),Uc.trace("Response from remote describe all request:",r)}catch(o){Uc.error(`addNode received error from describe all request to remote node: ${o}`);let c=qE.requestErrorHandler(o,"add_node",t);throw wO(new Error,c,UO.INTERNAL_SERVER_ERROR,"error",c)}if(r.status===bO.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let o=`Error returned from remote node ${t}: ${r.message}`;throw wO(new Error,o,UO.INTERNAL_SERVER_ERROR,"error",o)}let s=r.message,n=[],i=[];for(let o of e){let{schema:c,table:_}=o,u=IO.doesSchemaExist(c),l=s[c]!==void 0,E=IO.doesTableExist(c,_),d=s?.[c]?.[_]!==void 0;if(!u&&!l||!E&&!d){n.push(o);continue}if(!u&&l&&(Uc.trace(`addNode creating schema: ${c}`),await CO.createSchema({operation:"create_schema",schema:c})),!E&&d){Uc.trace(`addNode creating table: ${_} in schema: ${c}`);let m=new Cx(c,_,s[c][_].hash_attribute);await CO.createTable(m)}await qE.createLocalTableStream(c,_);let S=new Lx(c,_,o.publish,o.subscribe);S.start_time=o.start_time,i.push(S)}return{added:i,skipped:n}}a(yx,"reviewSubscriptions")});var Dc=h((S2,MO)=>{"use strict";var{handleHDBError:Lc,hdb_errors:Dx}=D(),{HTTP_STATUS_CODES:yc}=Dx,{addUpdateNodeValidator:Mx}=mc(),Hi=g(),DO=T(),yO=fe(),Px=b(),FE=At(),qi=Ls(),Bx=V(),vx=GE(),{Node:Hx,NodeSubscription:qx}=Un(),Gx="Unable to create subscriptions due to schema and/or tables not existing on the local or remote node",Fx="Some subscriptions were unsuccessful due to schema and/or tables not existing on the local or remote node",Vx=Bx.get(DO.CONFIG_PARAMS.CLUSTERING_NODENAME);MO.exports=kx;async function kx(e,t=!1){Hi.trace("addNode called with:",e),qi.checkClusteringEnabled();let r=Mx(e);if(r)throw Lc(r,r.message,yc.BAD_REQUEST,void 0,void 0,!0);let s=e.node_name;if(!t){let E=await qi.getNodeRecord(s);if(!Px.isEmptyOrZeroLength(E))throw Lc(new Error,`Node '${s}' has already been added, perform update_node to proceed.`,yc.BAD_REQUEST,void 0,void 0,!0)}let{added:n,skipped:i}=await vx(e.subscriptions,s),o={message:void 0,added:n,skipped:i};if(n.length===0)return o.message=Gx,o;let c=qi.buildNodePayloads(n,Vx,DO.OPERATIONS_ENUM.ADD_NODE,await qi.getSystemInfo());Hi.trace("addNode sending remote payload:",c);let _;try{_=await FE.request(`${s}.${yO.REQUEST_SUFFIX}`,c)}catch(E){Hi.error(`addNode received error from request: ${E}`);let d=FE.requestErrorHandler(E,"add_node",s);throw Lc(new Error,d,yc.INTERNAL_SERVER_ERROR,"error",d)}if(_.status===yO.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let E=`Error returned from remote node ${s}: ${_.message}`;throw Lc(new Error,E,yc.INTERNAL_SERVER_ERROR,"error",E)}Hi.trace(_);let u=[];for(let E=0,d=n.length;E<d;E++){let S=n[E];Hi.trace("Add node updating work stream for node:",s,"subscriptions:",S),await FE.updateWorkStream(S,s),n[E].start_time===void 0&&delete n[E].start_time,u.push(new qx(S.schema,S.table,S.publish,S.subscribe))}let l=new Hx(s,u,_.system_info);return await qi.upsertNodeRecord(l),i.length>0?o.message=Fx:o.message=`Successfully added '${s}' to manifest`,o}a(kx,"addNode")});var kE=h((f2,vO)=>{"use strict";var{handleHDBError:Mc,hdb_errors:xx}=D(),{HTTP_STATUS_CODES:Pc}=xx,{addUpdateNodeValidator:$x}=mc(),Gi=g(),BO=T(),PO=fe(),Yx=b(),VE=At(),Fi=Ls(),Kx=V(),{cloneDeep:Qx}=require("lodash"),Wx=GE(),{NodeSubscription:Jx}=Un(),Zx="Unable to update subscriptions due to schema and/or tables not existing on the local or remote node",Xx="Some subscriptions were unsuccessful due to schema and/or tables not existing on the local or remote node",zx=Kx.get(BO.CONFIG_PARAMS.CLUSTERING_NODENAME);vO.exports=jx;async function jx(e){Gi.trace("updateNode called with:",e),Fi.checkClusteringEnabled();let t=$x(e);if(t)throw Mc(t,t.message,Pc.BAD_REQUEST,void 0,void 0,!0);let r=e.node_name,s=Qx(await Fi.getNodeRecord(r));if(Yx.isEmptyOrZeroLength(s))throw Mc(new Error,`Node '${r}' has not been added, perform add_node to proceed.`,Pc.BAD_REQUEST,void 0,void 0,!0);let{added:n,skipped:i}=await Wx(e.subscriptions,r),o={message:void 0,updated:n,skipped:i};if(n.length===0)return o.message=Zx,o;let c=Fi.buildNodePayloads(n,zx,BO.OPERATIONS_ENUM.UPDATE_NODE,await Fi.getSystemInfo());Gi.trace("updateNode sending remote payload:",c);let _;try{_=await VE.request(`${r}.${PO.REQUEST_SUFFIX}`,c)}catch(u){Gi.error(`updateNode received error from request: ${u}`);let l=VE.requestErrorHandler(u,"update_node",r);throw Mc(new Error,l,Pc.INTERNAL_SERVER_ERROR,"error",l)}if(_.status===PO.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let u=`Error returned from remote node ${r}: ${_.message}`;throw Mc(new Error,u,Pc.INTERNAL_SERVER_ERROR,"error",u)}Gi.trace(_);for(let u=0,l=n.length;u<l;u++){let E=n[u];Gi.trace(`updateNode updating work stream for node: ${r} subscription:`,E),await VE.updateWorkStream(E,r),n[u].start_time===void 0&&delete n[u].start_time}return await e$(s[0],n,_.system_info),i.length>0?o.message=Xx:o.message=`Successfully updated '${r}'`,o}a(jx,"updateNode");async function e$(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 Jx(o.schema,o.table,o.publish,o.subscribe))}s.system_info=r,await Fi.upsertNodeRecord(s)}a(e$,"updateNodeTable")});var VO=h((T2,FO)=>{"use strict";var GO=require("joi"),{string:HO}=GO.types(),t$=he(),qO=T(),r$=V(),s$=fe();FO.exports=n$;function n$(e){let t=HO.invalid(r$.get(qO.CONFIG_PARAMS.CLUSTERING_NODENAME)).pattern(s$.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=GO.object({operation:HO.valid(qO.OPERATIONS_ENUM.REMOVE_NODE).required(),node_name:t});return t$.validateBySchema(e,r)}a(n$,"removeNodeValidator")});var vc=h((m2,QO)=>{"use strict";var{handleHDBError:kO,hdb_errors:i$}=D(),{HTTP_STATUS_CODES:xO}=i$,a$=VO(),Vi=g(),$O=Ls(),o$=b(),Bc=T(),YO=fe(),KO=At(),c$=V(),{RemotePayloadObject:_$}=vi(),{NodeSubscription:u$}=Un(),l$=Ei(),E$=ps(),d$=c$.get(Bc.CONFIG_PARAMS.CLUSTERING_NODENAME);QO.exports=h$;async function h$(e){Vi.trace("removeNode called with:",e),$O.checkClusteringEnabled();let t=a$(e);if(t)throw kO(t,t.message,xO.BAD_REQUEST,void 0,void 0,!0);let r=e.node_name,s=await $O.getNodeRecord(r);if(o$.isEmptyOrZeroLength(s))throw kO(new Error,`Node '${r}' was not found.`,xO.BAD_REQUEST,void 0,void 0,!0);s=s[0];let n=new _$(Bc.OPERATIONS_ENUM.REMOVE_NODE,d$,[]),i,o=!1;try{i=await KO.request(`${r}.${YO.REQUEST_SUFFIX}`,n),Vi.trace("Remove node reply from remote node:",r,i)}catch(_){Vi.error("removeNode received error from request:",_),o=!0}for(let _=0,u=s.subscriptions.length;_<u;_++){let l=s.subscriptions[_];Vi.trace(`Remove node removing subscription: ${l.schema}.${l.table} for node: ${r}`);let E=new u$(l.schema,l.table,!1,!1);await KO.updateWorkStream(E,r)}let c=new l$(Bc.SYSTEM_SCHEMA_NAME,Bc.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[r]);return await E$.deleteRecord(c),i?.status===YO.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR||o?(Vi.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(h$,"removeNode")});var ZO=h((R2,JO)=>{"use strict";var WO=require("joi"),{string:S$,array:f$}=WO.types(),T$=he(),m$=mc();JO.exports=R$;function R$(e){let t=WO.object({operation:S$.valid("configure_cluster").required(),connections:f$.items(m$.validation_schema).required()});return T$.validateBySchema(e,t)}a(R$,"configureClusterValidator")});var xE=h((A2,tN)=>{"use strict";var A$=T(),Hc=g(),p$=b(),O$=vc(),N$=Dc(),XO=Ls(),g$=ZO(),{handleHDBError:zO,hdb_errors:I$}=D(),{HTTP_STATUS_CODES:jO}=I$,b$="Configure cluster complete.",C$="Failed to configure the cluster. Check the logs for more details.",w$="Configure cluster was partially successful. Errors occurred when attempting to configure the following nodes. Check the logs for more details.";tN.exports=U$;async function U$(e){Hc.trace("configure cluster called with:",e),XO.checkClusteringEnabled();let t=g$(e);if(t)throw zO(t,t.message,jO.BAD_REQUEST,void 0,void 0,!0);let r=await XO.getAllNodeRecords(),s=[];for(let d=0,S=r.length;d<S;d++)s.push(eN(O$,{operation:A$.OPERATIONS_ENUM.REMOVE_NODE,node_name:r[d].name},r[d].name));let n=await Promise.allSettled(s);Hc.trace("All results from configure_cluster remove node:",n);let i=[],o=e.connections.length;for(let d=0;d<o;d++){let S=e.connections[d];i.push(eN(N$,S,S.node_name))}let c=await Promise.allSettled(i);Hc.trace("All results from configure_cluster add node:",c);let _=[],u=[],l=!1,E=n.concat(c);for(let d=0,S=E.length;d<S;d++){let m=E[d];m.status==="rejected"&&(Hc.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(p$.isEmptyOrZeroLength(_))return{message:b$,connections:u};if(l)return{message:w$,failed_nodes:_,connections:u};throw zO(new Error,C$,jO.INTERNAL_SERVER_ERROR,void 0,void 0,!0)}a(U$,"configureCluster");async function eN(e,t,r){try{return{node_name:r,result:await e(t)}}catch(s){throw{node_name:r,error:s}}}a(eN,"functionWrapper")});var KE=h((p2,oN)=>{"use strict";var YE=Ls(),L$=At(),nN=V(),qc=T(),ys=fe(),y$=b(),$E=g(),{RemotePayloadObject:D$}=vi(),{ErrorCode:rN}=require("nats"),sN=nN.get(qc.CONFIG_PARAMS.CLUSTERING_ENABLED),iN=nN.get(qc.CONFIG_PARAMS.CLUSTERING_NODENAME);oN.exports={clusterStatus:M$,buildNodeStatus:aN};async function M$(){let e={node_name:iN,is_enabled:sN,connections:[]};if(!sN)return e;let t=await YE.getAllNodeRecords();if(y$.isEmptyOrZeroLength(t))return e;let r=[];for(let s=0,n=t.length;s<n;s++)r.push(aN(t[s],e.connections));return await Promise.allSettled(r),e}a(M$,"clusterStatus");async function aN(e,t){let r=e.name,s=new D$(qc.OPERATIONS_ENUM.CLUSTER_STATUS,iN,void 0,await YE.getSystemInfo()),n,i,o=ys.CLUSTER_STATUS_STATUSES.OPEN;try{let _=Date.now();n=await L$.request(ys.REQUEST_SUBJECT(r),s),i=Date.now()-_,n.status===ys.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR&&(o=ys.CLUSTER_STATUS_STATUSES.CLOSED,$E.error(`Error getting node status from ${r} `,n))}catch(_){$E.warn(`Error getting node status from ${r}`,_),_.code===rN.NoResponders?o=ys.CLUSTER_STATUS_STATUSES.NO_RESPONDERS:_.code===rN.Timeout?o=ys.CLUSTER_STATUS_STATUSES.TIMEOUT:o=ys.CLUSTER_STATUS_STATUSES.CLOSED}let c=new P$(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!==qc.PRE_4_0_0_VERSION&&await YE.upsertNodeRecord(_)}catch(_){$E.error("Cluster status encountered an error updating system info for node:",r,_)}t.push(c)}a(aN,"buildNodeStatus");function P$(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(P$,"NodeStatusObject")});var lN=h((O2,uN)=>{"use strict";var QE=require("joi"),cN=he(),{route_constraints:_N}=du();uN.exports={setRoutesValidator:B$,deleteRoutesValidator:v$};function B$(e){let t=QE.object({server:QE.valid("hub","leaf").required(),routes:_N.required()});return cN.validateBySchema(e,t)}a(B$,"setRoutesValidator");function v$(e){let t=QE.object({routes:_N.required()});return cN.validateBySchema(e,t)}a(v$,"deleteRoutesValidator")});var JE=h((N2,SN)=>{"use strict";var Ds=Tr(),WE=b(),Gc=T(),EN=lN(),{handleHDBError:dN,hdb_errors:H$}=D(),{HTTP_STATUS_CODES:hN}=H$,q$="cluster routes successfully set",G$="cluster routes successfully deleted";SN.exports={setRoutes:F$,getRoutes:V$,deleteRoutes:k$};function F$(e){let t=EN.setRoutesValidator(e);if(t)throw dN(t,t.message,hN.BAD_REQUEST,void 0,void 0,!0);let r=Ds.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=WE.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"?Ds.updateConfigValue(Gc.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,s):Ds.updateConfigValue(Gc.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,s),{message:q$,set:o,skipped:i}}a(F$,"setRoutes");function V$(){let e=Ds.getClusteringRoutes();return{hub:e.hub_routes,leaf:e.leaf_routes}}a(V$,"getRoutes");function k$(e){let t=EN.deleteRoutesValidator(e);if(t)throw dN(t,t.message,hN.BAD_REQUEST,void 0,void 0,!0);let r=Ds.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 S=0,m=s.length;S<m;S++){let R=s[S];if(E.host===R.host&&E.port===R.port){s.splice(S,1),d=!0,c=!0,i.push(E);break}}if(!d){let S=!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,S=!1,i.push(E);break}}S&&o.push(E)}}return c&&(s=WE.isEmptyOrZeroLength(s)?null:s,Ds.updateConfigValue(Gc.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,s)),_&&(n=WE.isEmptyOrZeroLength(n)?null:n,Ds.updateConfigValue(Gc.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,n)),{message:G$,deleted:i,skipped:o}}a(k$,"deleteRoutes")});var TN=h((g2,fN)=>{"use strict";var ki=require("alasql"),Ms=require("recursive-iterator"),Jt=g(),x$=b(),xi=T(),Fc=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,Y$(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=>xi.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=>!xi.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][xi.PERMS_CRUD_ENUM.READ]){let c;t[i].tables[o].attribute_permissions.length>0?c=$$(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=>!xi.SEARCH_WILDCARDS.includes(u));c.forEach(({attribute_name:u})=>{let l=new ki.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(Fc,"sql_statement_bucket");function $$(e){return e.filter(t=>t[xi.PERMS_CRUD_ENUM.READ])}a($$,"filterReadRestrictedAttrs");function Y$(e,t,r,s,n){K$(e,t,r,s,n)}a(Y$,"interpretAST");function $i(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($i,"addSchemaTableToMap");function K$(e,t,r,s,n){if(!e){Jt.info("getRecordAttributesAST: invalid SQL syntax tree");return}e instanceof ki.yy.Insert?Z$(e,t,r):e instanceof ki.yy.Select?Q$(e,t,r,s,n):e instanceof ki.yy.Update?W$(e,t,r):e instanceof ki.yy.Delete?J$(e,t,r):Jt.error("AST in getRecordAttributesAST() is not a valid SQL type.")}a(K$,"getRecordAttributesAST");function Q$(e,t,r,s,n){if(!e){Jt.info("getSelectAttributes: invalid SQL syntax tree");return}if(!e.from||e.from[0]===void 0)return;let i=e.from[0].databaseid;if(x$.isEmptyOrZeroLength(i)){Jt.error("No schema specified");return}e.from.forEach(c=>{$i(c,t,r,s,n)}),e.joins&&e.joins.forEach(c=>{c.as&&(c.table.as=c.as),$i(c.table,t,r,s,n)});let o=new Ms(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{Jt.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 Ms(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{Jt.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 Ms(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{Jt.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 Ms(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{Jt.info(`table specified as ${u} not found.`);return}t.get(l).get(u).indexOf(_.columnid)<0&&t.get(l).get(u).push(_.columnid)}}}a(Q$,"getSelectAttributes");function W$(e,t,r){if(!e){Jt.info("getUpdateAttributes: invalid SQL syntax tree");return}let s=new Ms(e.columns),n=e.table.databaseid;$i(e.table,t,r);for(let{node:i}of s)i&&i.columnid&&ZE(e.table.tableid,n,i.columnid,t,r)}a(W$,"getUpdateAttributes");function J$(e,t,r){if(!e){Jt.info("getDeleteAttributes: invalid SQL syntax tree");return}let s=new Ms(e.where),n=e.table.databaseid;$i(e.table,t,r);for(let{node:i}of s)i&&i.columnid&&ZE(e.table.tableid,n,i.columnid,t,r)}a(J$,"getDeleteAttributes");function Z$(e,t,r){if(!e){Jt.info("getInsertAttributes: invalid SQL syntax tree");return}let s=new Ms(e.columns),n=e.into.databaseid;$i(e.into,t,r);for(let{node:i}of s)i&&i.columnid&&ZE(e.into.tableid,n,i.columnid,t,r)}a(Z$,"getInsertAttributes");function ZE(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(ZE,"pushAttribute");fN.exports=Fc});var AN=h((I2,RN)=>{var X$=require("os"),mN=V();RN.exports={checkPermission:z$};function z$(){if(X$.userInfo().username!==mN.get("install_user"))throw new Error(`Error: Must execute as ${mN.get("install_user")}`)}a(z$,"checkPermission")});var zE=h((b2,IN)=>{var kc=pi(),pN=require("chalk"),ar=g(),ON=AN(),NN=require("prompt"),{promisify:j$}=require("util"),Vc=T(),eY=require("fs-extra"),tY=require("path"),rY=b(),sY=BE(),gN=V();gN.initSync();var nY=require("moment"),iY=j$(NN.get),aY=tY.join(gN.getHdbBasePath(),Vc.LICENSE_KEY_DIR_NAME,Vc.LICENSE_FILE_NAME,Vc.LICENSE_FILE_NAME);IN.exports={getFingerprint:cY,setLicense:oY,parseLicense:XE,register:_Y,getRegistrationInfo:lY};async function oY(e){if(e&&e.key&&e.company){try{ar.info(`parsing license key: ${e.key} and `);let t=e.company.toString();await XE(e.key.trim(),t.trim())}catch(t){let r="There was an error parsing the license key.";throw ar.error(r),ar.error(t),new Error(r)}return"Wrote license key file. Registration successful."}throw new Error("Invalid key or company specified for license file.")}a(oY,"setLicense");async function cY(){try{ON.checkPermission()}catch(t){throw ar.error(t),new Error("You do not have permission to generate a fingerprint.")}let e={};try{e=await kc.generateFingerPrint()}catch(t){let r="Error generating fingerprint.";throw ar.error(r),ar.error(t),new Error(r)}return e}a(cY,"getFingerprint");async function XE(e,t){if(!e||!t)throw new Error("Invalid entries for License Key and Customer Company");console.log("Validating license input...");let r=kc.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{ar.info("writing license to disk"),await eY.writeFile(aY,JSON.stringify({license_key:e,company:t}))}catch(s){throw ar.error("Failed to write License"),s}return"Registration successful."}a(XE,"parseLicense");async function _Y(){let e=await uY();return XE(e.HDB_LICENSE,e.CUSTOMER_COMPANY)}a(_Y,"register");async function uY(){try{ON.checkPermission()}catch(s){return console.error(s.message)}let e=await kc.generateFingerPrint(),t={properties:{CUSTOMER_COMPANY:{description:pN.magenta("[COMPANY] Please enter your company name"),required:!0},HDB_LICENSE:{description:pN.magenta(`[HDB_LICENSE] Your fingerprint is ${e} Please enter your license key`),required:!0}}};try{NN.start()}catch(s){ar.error(s)}let r;try{r=await iY(t)}catch(s){throw console.error("There was a problem prompting for registration input. Exiting."),s}return r}a(uY,"promptForRegistration");async function lY(){let e={registered:!1,version:null,storage_type:null,ram_allocation:null,license_expiration_date:null},t;try{t=await kc.getLicense()}catch(r){throw ar.error(`There was an error when searching licenses due to: ${r.message}`),r}if(rY.isEmptyOrZeroLength(t))throw new Error("There were no licenses found.");if(e.registered=t.enterprise,e.version=sY.version(),e.storage_type=Vc.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=nY.utc(t.exp_date).format("YYYY-MM-DD");e.license_expiration_date=t.enterprise?r:null}return e}a(lY,"getRegistrationInfo")});var CN=h((C2,bN)=>{"use strict";var EY=fe(),xc=class{constructor(t,r,s,n,i,o,c,_,u,l,E,d,S){this.port=t,this.server_name=r+EY.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:S}},this.system_account="SYS"}};a(xc,"HubConfigObject");bN.exports=xc});var LN=h((w2,UN)=>{"use strict";var wN=fe(),$c=class{constructor(t,r,s,n,i,o,c,_,u,l,E,d){this.port=t,this.server_name=r+wN.SERVER_SUFFIX.LEAF,this.pid_file=s,this.max_payload=1e7,this.jetstream={enabled:!0,store_dir:n,domain:r+wN.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($c,"LeafConfigObject");UN.exports=$c});var DN=h((U2,yN)=>{"use strict";var Yc=class{constructor(t,r){this.user=t,this.password=r}};a(Yc,"HdbUserObject");yN.exports=Yc});var PN=h((L2,MN)=>{"use strict";var dY=fe(),Kc=class{constructor(t,r){this.user=t+dY.SERVER_SUFFIX.ADMIN,this.password=r}};a(Kc,"SysUserObject");MN.exports=Kc});var td=h((y2,HN)=>{"use strict";var Dn=require("path"),Zc=require("fs-extra"),hY=CN(),SY=LN(),fY=DN(),TY=PN(),jE=gr(),Pn=b(),Pt=Tr(),Jc=T(),Qc=fe(),{CONFIG_PARAMS:Ue}=Jc,Xc=g(),zc=V(),BN=$r(),ed=At(),Mn="clustering",mY=1e4,vN=5;HN.exports={generateNatsConfig:RY,removeNatsConfig:AY};async function RY(e=!1,t=void 0){zc.initSync();let r=zc.get(Ue.ROOTPATH),s=Dn.join(r,Mn,Qc.PID_FILES.HUB),n=Dn.join(r,Mn,Qc.PID_FILES.LEAF),i=Dn.join(r,Mn,"leaf"),o=Dn.join(r,Mn,Qc.NATS_CONFIG_FILES.HUB_SERVER),c=Dn.join(r,Mn,Qc.NATS_CONFIG_FILES.LEAF_SERVER),_=Pt.getConfigFromFile(Ue.CLUSTERING_TLS_CERTIFICATE),u=Pt.getConfigFromFile(Ue.CLUSTERING_TLS_PRIVATEKEY),l=Pt.getConfigFromFile(Ue.CLUSTERING_TLS_CERT_AUTH),E=Pt.getConfigFromFile(Ue.CLUSTERING_TLS_INSECURE),d=Pt.getConfigFromFile(Ue.CLUSTERING_NODENAME),S=Pt.getConfigFromFile(Ue.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT);await ed.checkNATSServerInstalled()||jc("nats-server dependency is either missing or the wrong version. Run 'npm install' to fix");let m=await jE.listUsers(),R=Pt.getConfigFromFile(Ue.CLUSTERING_USER),w=await jE.getClusterUser();(Pn.isEmpty(w)||w.active!==!0)&&jc(`invalid cluster user '${R}'`),e||(await Wc(Ue.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),await Wc(Ue.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT),await Wc(Ue.CLUSTERING_HUBSERVER_NETWORK_PORT),await Wc(Ue.CLUSTERING_LEAFSERVER_NETWORK_PORT));let U=[],B=[];for(let[da,Pr]of m.entries())Pr.role.role===Jc.ROLE_TYPES_ENUM.CLUSTER_USER&&Pr.active&&(U.push(new TY(Pr.username,BN.decrypt(Pr.hash))),B.push(new fY(Pr.username,BN.decrypt(Pr.hash))));let j=[],{hub_routes:k}=Pt.getClusteringRoutes();if(!Pn.isEmptyOrZeroLength(k))for(let da of k)j.push(`tls://${w.sys_name_encoded}:${w.uri_encoded_d_hash}@${da.host}:${da.port}`);let J=new hY(Pt.getConfigFromFile(Ue.CLUSTERING_HUBSERVER_NETWORK_PORT),d,s,_,u,l,E,S,Pt.getConfigFromFile(Ue.CLUSTERING_HUBSERVER_CLUSTER_NAME),Pt.getConfigFromFile(Ue.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),j,U,B);t=Pn.isEmpty(t)?void 0:t.toLowerCase(),(t===void 0||t===Jc.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase())&&(await Zc.writeJson(o,J),Xc.trace(`Hub server config written to ${o}`));let xe=`tls://${w.sys_name_encoded}:${w.uri_encoded_d_hash}@0.0.0.0:${S}`,$e=`tls://${w.uri_encoded_name}:${w.uri_encoded_d_hash}@0.0.0.0:${S}`,Ea=new SY(Pt.getConfigFromFile(Ue.CLUSTERING_LEAFSERVER_NETWORK_PORT),d,n,i,[xe],[$e],U,B,_,u,l,E);(t===void 0||t===Jc.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())&&(await Zc.writeJson(c,Ea),Xc.trace(`Leaf server config written to ${c}`))}a(RY,"generateNatsConfig");async function Wc(e){let t=zc.get(e);Pn.isEmpty(t)&&jc(`port undefined for '${e}'`),await Pn.isPortTaken(t)&&jc(`'${e}' port '${t}' is unavailable`)}a(Wc,"isPortAvailable");function jc(e){let t=`Error generating clustering config: ${e}`;Xc.error(t),console.error(t),process.exit(1)}a(jc,"generateNatsConfigError");async function AY(e){let{port:t,config_file:r}=ed.getServerConfig(e),{username:s,decrypt_hash:n}=await jE.getClusterUser(),i=0,o=500;for(;i<vN;){try{let u=await ed.createConnection(t,s,n,!1);if(u.protocol.connected===!0){u.close();break}}catch(u){Xc.trace(`removeNatsConfig waiting for ${e}. Caught and swallowed error ${u}`)}if(i++,i>=vN)throw new Error(`removeNatsConfig timed out waiting to connect to ${e}`);await Pn.async_set_timeout(o*i)}let c="0".repeat(mY),_=Dn.join(zc.get(Ue.ROOTPATH),Mn,r);await Zc.writeFile(_,c),await Zc.remove(_)}a(AY,"removeNatsConfig")});var t_=h((D2,$N)=>{"use strict";var ie=V(),qN=pi(),C=T(),rd=fe(),Oe=require("path"),{PACKAGE_ROOT:e_}=T(),Ee="/dev/null",Bn=Oe.join(e_,"launchServiceScripts"),GN=Oe.join(e_,"utility/scripts"),pY=Oe.join(GN,C.HDB_RESTART_SCRIPT),FN=Oe.resolve(e_,"dependencies",`${process.platform}-${process.arch}`,rd.NATS_BINARY_NAME),qe,Ge;function or(){(qe===void 0||Ge===void 0)&&(ie.initSync(),qe=ie.get(C.HDB_SETTINGS_NAMES.LOG_TO_FILE),Ge=ie.get(C.HDB_SETTINGS_NAMES.LOG_PATH_KEY))}a(or,"initLogConfig");function VN(){or();let e=Oe.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 qe||(t.out_file=Ee,t.error_file=Ee),{...t,script:C.SERVICE_SERVERS.IPC}}a(VN,"generateIPCServerConfig");function kN(){or(),ie.initSync(),qe=ie.get(C.HDB_SETTINGS_NAMES.LOG_TO_FILE),Ge=ie.get(C.HDB_SETTINGS_NAMES.LOG_PATH_KEY);let e=Oe.join(Ge,C.PROCESS_LOG_NAMES.HDB),t=qN.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:ie.get(C.CONFIG_PARAMS.HTTP_THREADS),node_args:r,cwd:Bn};return qe||(s.out_file=Ee,s.error_file=Ee),s}a(kN,"generateHDBServerConfig");function xN(){or(),ie.initSync(),qe=ie.get(C.HDB_SETTINGS_NAMES.LOG_TO_FILE),Ge=ie.get(C.HDB_SETTINGS_NAMES.LOG_PATH_KEY);let e=Oe.join(Ge,C.PROCESS_LOG_NAMES.CUSTOM_FUNCTIONS),t=qN.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:ie.get(C.CONFIG_PARAMS.HTTP_THREADS),node_args:r,cwd:Bn};return qe||(s.out_file=Ee,s.error_file=Ee),s}a(xN,"generateCFServerConfig");function OY(){or(),ie.initSync(),qe=ie.get(C.HDB_SETTINGS_NAMES.LOG_TO_FILE),Ge=ie.get(C.HDB_SETTINGS_NAMES.LOG_PATH_KEY);let e=ie.get(C.CONFIG_PARAMS.ROOTPATH),t=Oe.join(e,"clustering",rd.NATS_CONFIG_FILES.HUB_SERVER),r=Oe.join(Ge,C.PROCESS_LOG_NAMES.CLUSTERING_HUB),s={name:C.PROCESS_DESCRIPTORS.CLUSTERING_HUB,script:FN,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 qe||(s.out_file=Ee,s.error_file=Ee),s}a(OY,"generateNatsHubServerConfig");function NY(){or(),ie.initSync(),qe=ie.get(C.HDB_SETTINGS_NAMES.LOG_TO_FILE),Ge=ie.get(C.HDB_SETTINGS_NAMES.LOG_PATH_KEY);let e=ie.get(C.CONFIG_PARAMS.ROOTPATH),t=Oe.join(e,"clustering",rd.NATS_CONFIG_FILES.LEAF_SERVER),r=Oe.join(Ge,C.PROCESS_LOG_NAMES.CLUSTERING_LEAF),s={name:C.PROCESS_DESCRIPTORS.CLUSTERING_LEAF,script:FN,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 qe||(s.out_file=Ee,s.error_file=Ee),s}a(NY,"generateNatsLeafServerConfig");function gY(){or(),ie.initSync();let e=Oe.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:Bn};return qe||(t.out_file=Ee,t.error_file=Ee),t}a(gY,"generateNatsIngestServiceConfig");function IY(){or(),ie.initSync();let e=Oe.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:Bn};return qe||(t.out_file=Ee,t.error_file=Ee),t}a(IY,"generateNatsReplyServiceConfig");function bY(){or(),ie.initSync();let e=Oe.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:Bn,autorestart:!1};return qe||(t.out_file=Ee,t.error_file=Ee),t}a(bY,"generateClusteringUpgradeV4ServiceConfig");function CY(){or();let e=Oe.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:GN};return qe||(t.out_file=Ee,t.error_file=Ee),{...t,script:pY}}a(CY,"generateRestart");function wY(e){or();let t=Oe.join(Ge,C.PROCESS_LOG_NAMES.JOBS),r=Oe.join(e_,"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:Bn,autorestart:!1};return qe||(s.out_file=Ee,s.error_file=Ee),{...s,script:Oe.join(r,"jobProcess.js")}}a(wY,"generateJobConfig");function UY(){return{apps:[VN(),kN(),xN()]}}a(UY,"generateAllServiceConfigs");$N.exports={generateAllServiceConfigs:UY,generateIPCServerConfig:VN,generateHDBServerConfig:kN,generateCFServerConfig:xN,generateRestart:CY,generateNatsHubServerConfig:OY,generateNatsLeafServerConfig:NY,generateNatsIngestServiceConfig:gY,generateNatsReplyServiceConfig:IY,generateClusteringUpgradeV4ServiceConfig:bY,generateJobConfig:wY}});var Ki=h((M2,tg)=>{"use strict";var P=T(),r_=b(),Yi=td(),s_=At(),LY=fe(),$=require("pm2"),yY=require("fs-extra"),wr=t_(),Et=V(),Ur=g(),DY=t_(),MY=Ls(),PY=require("util"),KN=PY.promisify(require("child_process").exec),QN=require("path");tg.exports={start:Ps,stop:i_,reload:JN,restart:ZN,list:nd,describe:a_,connect:cr,kill:zN,startAllServices:$Y,startService:n_,getUniqueServicesList:id,restartAllServices:YY,stopAllServices:KY,isServiceRegistered:jN,reloadStopStart:sd,restartHdb:XN,deleteProcess:kY,configureLogRotate:JY,startClustering:eg,isHdbRestartRunning:xY,isClusteringRunning:XY,stopClustering:ZY,reloadClustering:zY};var{PACKAGE_ROOT:BY}=T(),vY="2.7.0",WN=QN.join(BY,"node_modules/pm2/bin/pm2"),HY="Log rotate installed.",qY="Error installing log rotate.",GY="Log rotate updated.",FY="Error updating log rotate.",VY="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 cr(){return new Promise((e,t)=>{$.connect((r,s)=>{r&&t(r),e(s)})})}a(cr,"connect");function Ps(e){return new Promise(async(t,r)=>{try{await cr()}catch(s){r(s)}$.start(e,(s,n)=>{s&&($.disconnect(),r(s)),$.disconnect(),t(n)})})}a(Ps,"start");function i_(e){return new Promise(async(t,r)=>{try{await cr()}catch(s){r(s)}$.stop(e,(s,n)=>{s&&($.disconnect(),r(s)),$.delete(e,(i,o)=>{i&&($.disconnect(),r(s)),$.disconnect(),t(o)})})})}a(i_,"stop");function JN(e){return new Promise(async(t,r)=>{try{await cr()}catch(s){r(s)}$.reload(e,(s,n)=>{s&&($.disconnect(),r(s)),$.disconnect(),t(n)})})}a(JN,"reload");function ZN(e){return new Promise(async(t,r)=>{try{await cr()}catch(s){r(s)}$.restart(e,(s,n)=>{s&&($.disconnect(),r(s)),$.disconnect(),t(n)})})}a(ZN,"restart");function kY(e){return new Promise(async(t,r)=>{try{await cr()}catch(s){r(s)}$.delete(e,(s,n)=>{s&&($.disconnect(),r(s)),$.disconnect(),t(n)})})}a(kY,"deleteProcess");async function XN(){await Ps(DY.generateRestart())}a(XN,"restartHdb");async function xY(){let e=await nd();for(let t in e)if(e[t].name===P.PROCESS_DESCRIPTORS.RESTART_HDB)return!0;return!1}a(xY,"isHdbRestartRunning");function nd(){return new Promise(async(e,t)=>{try{await cr()}catch(r){t(r)}$.list((r,s)=>{r&&($.disconnect(),t(r)),$.disconnect(),e(s)})})}a(nd,"list");function a_(e){return new Promise(async(t,r)=>{try{await cr()}catch(s){r(s)}$.describe(e,(s,n)=>{s&&($.disconnect(),r(s)),$.disconnect(),t(n)})})}a(a_,"describe");function zN(){return new Promise(async(e,t)=>{try{await cr()}catch(r){t(r)}$.killDaemon((r,s)=>{r&&($.disconnect(),t(r)),$.disconnect(),e(s)})})}a(zN,"kill");async function $Y(){try{await eg(),await Ps(wr.generateAllServiceConfigs())}catch(e){throw $.disconnect(),e}}a($Y,"startAllServices");async function n_(e){try{let t;switch(e=e.toLowerCase(),e){case P.PROCESS_DESCRIPTORS.IPC.toLowerCase():t=wr.generateIPCServerConfig();break;case P.PROCESS_DESCRIPTORS.HDB.toLowerCase():t=wr.generateHDBServerConfig();break;case P.PROCESS_DESCRIPTORS.CUSTOM_FUNCTIONS.toLowerCase():t=wr.generateCFServerConfig();break;case P.PROCESS_DESCRIPTORS.CLUSTERING_INGEST_SERVICE.toLowerCase():t=wr.generateNatsIngestServiceConfig();break;case P.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE.toLowerCase():t=wr.generateNatsReplyServiceConfig();break;case P.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase():t=wr.generateNatsHubServerConfig(),await Ps(t),await Yi.removeNatsConfig(e);return;case P.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase():t=wr.generateNatsLeafServerConfig(),await Ps(t),await Yi.removeNatsConfig(e);return;case P.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0.toLowerCase():t=wr.generateClusteringUpgradeV4ServiceConfig();break;default:throw new Error(`Start service called with unknown service config: ${e}`)}await Ps(t)}catch(t){throw $.disconnect(),t}}a(n_,"startService");async function id(){try{let e=await nd(),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(id,"getUniqueServicesList");async function YY(e=[]){try{let t=!1,r=await id();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 sd(o):await ZN(o))}t&&await sd(P.PROCESS_DESCRIPTORS.HDB)}catch(t){throw $.disconnect(),t}}a(YY,"restartAllServices");async function KY(){try{let e=await id();for(let t=0,r=Object.values(e).length;t<r;t++){let s=Object.values(e)[t];await i_(s.name)}if(await zN(),Et.get(P.CONFIG_PARAMS.OPERATIONSAPI_FOREGROUND)===!0){let t=(await yY.readFile(QN.join(Et.get(P.HDB_SETTINGS_NAMES.HDB_ROOT_KEY),P.FOREGROUND_PID_FILE))).toString();try{process.kill(t,"SIGTERM")}catch(r){Ur.warn(`Error terminating foreground process: ${r}`)}}}catch(e){throw $.disconnect(),e}}a(KY,"stopAllServices");async function jN(e){return!r_.isEmptyOrZeroLength(await a_(e))}a(jN,"isServiceRegistered");async function sd(e){let t=e===P.PROCESS_DESCRIPTORS.HDB?Et.get(P.HDB_SETTINGS_NAMES.MAX_HDB_PROCESSES):Et.get(P.HDB_SETTINGS_NAMES.MAX_CUSTOM_FUNCTION_PROCESSES),r=await a_(e),s=r_.isEmptyOrZeroLength(r)?0:r.length;t!==s?e===P.PROCESS_DESCRIPTORS.HDB?Ur.error(VY):(await i_(e),await n_(e)):e===P.PROCESS_DESCRIPTORS.HDB?await XN():await JN(e)}a(sd,"reloadStopStart");function QY(){return new Promise(async(e,t)=>{try{await cr()}catch(r){t(r)}$.stop(P.PROCESS_DESCRIPTORS.PM2_LOGROTATE,(r,s)=>{r&&($.disconnect(),t(r)),$.disconnect(),e(s)})})}a(QY,"stopLogrotate");async function WY(){let{stdout:e,stderr:t}=await KN(`${process.platform==="win32"?"node":""} ${WN} install pm2-logrotate@${vY}`);if(Ur.debug(`loadLogRotate stdout: ${e}`),t)throw Ur.error(qY),t;Ur.info(HY)}a(WY,"installLogRotate");async function YN(){let e={max_size:Et.get(P.HDB_SETTINGS_NAMES.LOG_ROTATE_MAX_SIZE),retain:Et.get(P.HDB_SETTINGS_NAMES.LOG_ROTATE_RETAIN),compress:Et.get(P.HDB_SETTINGS_NAMES.LOG_ROTATE_COMPRESS),dateFormat:Et.get(P.HDB_SETTINGS_NAMES.LOG_ROTATE_DATE_FORMAT),rotateModule:Et.get(P.HDB_SETTINGS_NAMES.LOG_ROTATE_ROTATE_MODULE),workerInterval:Et.get(P.HDB_SETTINGS_NAMES.LOG_ROTATE_WORKER_INTERVAL),rotateInterval:Et.get(P.HDB_SETTINGS_NAMES.LOG_ROTATE_ROTATE_INTERVAL),TZ:Et.get(P.HDB_SETTINGS_NAMES.LOG_ROTATE_TIMEZONE)},t="";for(let n in e)t+=`${process.platform==="win32"?"node":""} ${WN} set pm2-logrotate:${n} ${e[n]}`,n!=="TZ"&&(t+=" && ");let{stdout:r,stderr:s}=await KN(t);if(Ur.debug(`updateLogRotateConfig stdout: ${r}`),s)throw Ur.error(FY),s;Ur.info(GY)}a(YN,"updateLogRotateConfig");async function JY(){Et.initSync();let e=r_.autoCastBoolean(Et.get(P.HDB_SETTINGS_NAMES.LOG_ROTATE)),t=await a_(P.PROCESS_DESCRIPTORS.PM2_LOGROTATE),r,s=!1;if(r_.isEmptyOrZeroLength(t)||(s=!0,r=t[0].pm2_env.status),e&&!s){await WY(),await YN();return}if(e&&s){await Ps(P.PROCESS_DESCRIPTORS.PM2_LOGROTATE),await YN();return}!e&&r===P.PM2_PROCESS_STATUSES.ONLINE&&await QY()}a(JY,"configureLogRotate");async function eg(){for(let t in P.CLUSTERING_PROCESSES){let r=P.CLUSTERING_PROCESSES[t];await n_(r)}await s_.createWorkQueueStream(LY.WORK_QUEUE_CONSUMER_NAMES),await s_.updateNodeNameLocalStreams();let e=await MY.getAllNodeRecords();for(let t=0,r=e.length;t<r;t++)if(e[t].system_info?.hdb_version===P.PRE_4_0_0_VERSION){Ur.info("Starting clustering upgrade 4.0.0 process"),await n_(P.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0);break}}a(eg,"startClustering");async function ZY(){for(let e in P.CLUSTERING_PROCESSES){let t=P.CLUSTERING_PROCESSES[e];await i_(t)}}a(ZY,"stopClustering");async function XY(){for(let e in P.CLUSTERING_PROCESSES){let t=P.CLUSTERING_PROCESSES[e];if(await jN(t)===!1)return!1}return!0}a(XY,"isClusteringRunning");async function zY(){await Yi.generateNatsConfig(!0),await s_.reloadNATSHub(),await s_.reloadNATSLeaf(),await Yi.removeNatsConfig(P.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase()),await Yi.removeNatsConfig(P.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())}a(zY,"reloadClustering")});var ud=h((P2,ag)=>{"use strict";var y=T(),K=g(),o_=b(),jY=nu(),ad=td(),_d=At(),eK=fe(),sg=require("minimist"),{handleHDBError:od,hdb_errors:tK}=D(),Qi=Tr(),{HTTP_STATUS_CODES:cd}=tK,G,rg=`Restarting HarperDB. This may take up to ${y.RESTART_TIMEOUT_MS/1e3} seconds.`,Bs="HarperDB is currently restarting and must complete before another HarperDB restart can be initialized.",rK="Invalid service",sK="'service' is required",nK="Restarting all services",iK="Clustering is not enabled so cannot be restarted";ag.exports={stop:oK,restartProcesses:aK,restartService:ng};async function aK(){K.createLogFile(y.PROCESS_LOG_NAMES.CLI,y.PROCESS_DESCRIPTORS.STOP);try{G===void 0&&(G=Ki());let e=jY(Object.keys(y.CONFIG_PARAM_MAP),!0);o_.isEmptyOrZeroLength(Object.keys(e))||Qi.updateConfigValue(void 0,void 0,e,!0,!0);let t=Qi.getConfigFromFile(y.CONFIG_PARAMS.CLUSTERING_ENABLED),r=Qi.getConfigFromFile(y.CONFIG_PARAMS.CUSTOMFUNCTIONS_ENABLED),s=sg(process.argv);if(!o_.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(Bs),console.error(Bs);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 vn(_);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 ng({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(Bs),console.error(Bs),Bs;console.log(rg),t&&await ig();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(nK),await G.restartAllServices(i),rg}catch(e){let t=`There was an error restarting HarperDB. ${e}`;return K.error(t),t}}a(aK,"restartProcesses");async function ng(e){if(K.createLogFile(y.PROCESS_LOG_NAMES.CLI,y.PROCESS_DESCRIPTORS.STOP),G===void 0&&(G=Ki()),o_.isEmpty(e.service))throw od(new Error,sK,cd.BAD_REQUEST,void 0,void 0,!0);let t=e.service.toLowerCase();if(y.PROCESS_DESCRIPTORS_VALIDATE[t]===void 0)throw od(new Error,rK,cd.BAD_REQUEST,void 0,void 0,!0);let r=Qi.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(Bs),Bs;await G.reloadStopStart(s)}else if(s===y.PROCESS_DESCRIPTORS.PM2_LOGROTATE)await G.configureLogRotate();else if(s.toLowerCase().includes("clustering"))await vn(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),od(new Error,o,cd.BAD_REQUEST,void 0,void 0,!0)}}else await G.restart(s);let n=`Restarting ${s}`;return K.notify(n),n}a(ng,"restartService");async function oK(){K.createLogFile(y.PROCESS_LOG_NAMES.CLI,y.PROCESS_DESCRIPTORS.STOP);try{G===void 0&&(G=Ki());let e=sg(process.argv);if(o_.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(oK,"stop");async function ig(){await vn(y.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await vn(y.PROCESS_DESCRIPTORS.CLUSTERING_LEAF),await vn(y.PROCESS_DESCRIPTORS.CLUSTERING_INGEST_SERVICE),await vn(y.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE),await _d.updateNodeNameLocalStreams(),await _d.closeConnection()}a(ig,"restartAllClusteringServices");async function vn(e){e=y.PROCESS_DESCRIPTORS_VALIDATE[e.toLowerCase()];let t=Qi.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(iK);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 ig();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 ad.generateNatsConfig(!0,e),await G.startService(e),K.trace(`Starting ${e}`),e===y.PROCESS_DESCRIPTORS.CLUSTERING_LEAF&&await _d.createWorkQueueStream(eK.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 ad.generateNatsConfig(!0,e),await G.restart(e),await ad.removeNatsConfig(e));break;default:K.error(`Error restarting ${e}`)}}a(vn,"restartClustering")});var Tg=h((v2,fg)=>{"use strict";var B2=require("lodash"),ze=T(),{handleHDBError:og,hdb_errors:cK}=D(),{HDB_ERROR_MSGS:_K,HTTP_STATUS_CODES:uK}=cK,ld=g();fg.exports={getRolePermissions:EK};var vs=Object.create(null),lK=a(e=>({key:e,perms:{}}),"perms_template_obj"),lg=a((e=!1)=>({describe:e,tables:{}}),"schema_perms_template"),Eg=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"),Ed=a((e=!1,t=!1,r=!1,s=!1,n=!1)=>({attribute_permissions:[],describe:e,...Eg(t,r,s,n)}),"table_perms_template"),cg=a((e,t=Eg())=>({attribute_name:e,describe:Sg(t),[Wi]:t[Wi],[dd]:t[dd],[hd]:t[hd]}),"attr_perms_template"),_g=a((e,t=!1)=>({attribute_name:e,describe:t,[Wi]:t}),"timestamp_attr_perms_template"),{READ:Wi,INSERT:dd,UPDATE:hd}=ze.PERMS_CRUD_ENUM,dg=Object.values(ze.PERMS_CRUD_ENUM),hg=[Wi,dd,hd];function EK(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(vs[t]&&vs[t].key===s)return vs[t].perms;let n=dK(e,r);return vs[t]?vs[t].key=s:vs[t]=lK(s),vs[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 ld.error(s),ld.debug(r),og(new Error,_K.OUTDATED_PERMS_TRANSLATION_ERROR,uK.BAD_REQUEST)}else{let s=`There was an error while translating role permissions for role: ${t}.
|
|
8
|
-
${r.stack}`;throw ld.error(s),og(new Error)}}}a(EK,"getRolePermissions");function dK(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]=hK(t[i]);return}r[i]=lg(),s[i]?Object.keys(t[i]).forEach(o=>{if(s[i].tables[o]){let c=s[i].tables[o],_=t[i][o],u=SK(c,_);r[i].describe||dg.forEach(l=>{u[l]&&(r[i].describe=!0)}),r[i].tables[o]=u}else r[i].tables[o]=Ed()}):Object.keys(t[i]).forEach(o=>{r[i].tables[o]=Ed()})}),r}a(dK,"translateRolePermissions");function hK(e){let t=lg(!0);return Object.keys(e).forEach(r=>{t.tables[r]=Ed(!0,!0,!0,!0,!0)}),t}a(hK,"createStructureUserPermissions");function SK(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=_g(E,l[Wi])),u[E]=d,u},{}),o=t[ze.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_HASH_ATTRIBUTE_KEY],c=!!i[o],_=cg(o);return t.attributes.forEach(({attribute:u})=>{if(i[u]){let l=i[u];l.describe=Sg(l),n.attribute_permissions.push(l),c||fK(l,_)}else if(u!==o){let l;ze.TIME_STAMP_NAMES.includes(u)?l=_g(u):l=cg(u),n.attribute_permissions.push(l)}}),c||n.attribute_permissions.push(_),n.describe=ug(n),n}else return e.describe=ug(e),e}a(SK,"getTableAttrPerms");function ug(e){return dg.filter(t=>e[t]).length>0}a(ug,"getSchemaTableDescribePerm");function Sg(e){return hg.filter(t=>e[t]).length>0}a(Sg,"getAttributeDescribePerm");function fK(e,t){hg.forEach(r=>{e[r]&&!t[r]&&(t[r]=!0,t.describe=!0)})}a(fK,"checkForHashPerms")});var gg=h((H2,Ng)=>{"use strict";var de=require("joi"),mg=require("fs-extra"),Rg=require("path"),Hn=he(),Ag=V(),pg=T(),Og=g(),{hdb_errors:TK}=D(),{HDB_ERROR_MSGS:je}=TK,ss=/^[a-zA-Z0-9-_]+$/;Ng.exports={getDropCustomFunctionValidator:RK,setCustomFunctionValidator:AK,addCustomFunctionProjectValidator:pK,dropCustomFunctionProjectValidator:OK,packageCustomFunctionProjectValidator:NK,deployCustomFunctionProjectValidator:gK};function Ji(e,t,r){try{let s=Ag.get(pg.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY),n=Rg.join(s,t);return mg.existsSync(n)?e?t:r.message(je.PROJECT_EXISTS):e?r.message(je.NO_PROJECT):t}catch(s){return Og.error(s),r.message(je.VALIDATION_ERR)}}a(Ji,"checkProjectExists");function mK(e,t,r,s){try{let n=Ag.get(pg.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY),i=Rg.join(n,e,t,r+".js");return mg.existsSync(i)?r:s.message(je.NO_FILE)}catch(n){return Og.error(n),s.message(je.VALIDATION_ERR)}}a(mK,"checkFileExists");function RK(e){let t=de.object({project:de.string().pattern(ss).custom(Ji.bind(null,!0)).required().messages({"string.pattern.base":je.BAD_PROJECT_NAME}),type:de.string().valid("helpers","routes").required(),file:de.string().pattern(ss).custom(mK.bind(null,e.project,e.type)).required().messages({"string.pattern.base":je.BAD_FILE_NAME})});return Hn.validateBySchema(e,t)}a(RK,"getDropCustomFunctionValidator");function AK(e){let t=de.object({project:de.string().pattern(ss).custom(Ji.bind(null,!0)).required().messages({"string.pattern.base":je.BAD_PROJECT_NAME}),type:de.string().valid("helpers","routes").required(),file:de.string().pattern(ss).required().messages({"string.pattern.base":je.BAD_FILE_NAME}),function_content:de.string().required()});return Hn.validateBySchema(e,t)}a(AK,"setCustomFunctionValidator");function pK(e){let t=de.object({project:de.string().pattern(ss).custom(Ji.bind(null,!1)).required().messages({"string.pattern.base":je.BAD_PROJECT_NAME})});return Hn.validateBySchema(e,t)}a(pK,"addCustomFunctionProjectValidator");function OK(e){let t=de.object({project:de.string().pattern(ss).custom(Ji.bind(null,!0)).required().messages({"string.pattern.base":je.BAD_PROJECT_NAME})});return Hn.validateBySchema(e,t)}a(OK,"dropCustomFunctionProjectValidator");function NK(e){let t=de.object({project:de.string().pattern(ss).custom(Ji.bind(null,!0)).required().messages({"string.pattern.base":je.BAD_PROJECT_NAME}),skip_node_modules:de.boolean()});return Hn.validateBySchema(e,t)}a(NK,"packageCustomFunctionProjectValidator");function gK(e){let t=de.object({project:de.string().pattern(ss).required().messages({"string.pattern.base":je.BAD_PROJECT_NAME}),payload:de.string().required().messages({"string.pattern.base":je.BAD_PACKAGE}),file:de.string().required().messages({"string.pattern.base":je.BAD_FILE_PATH})});return Hn.validateBySchema(e,t)}a(gK,"deployCustomFunctionProjectValidator")});var fd=h((q2,bg)=>{"use strict";var Re=require("fs-extra"),c_=require("fast-glob"),ae=require("path"),Ig=require("tar-fs"),IK=require("uuid").v4,Zi=require("normalize-path"),Hs=gg(),Le=g(),pt=T(),Ot=V(),{PACKAGE_ROOT:bK}=T(),{handleHDBError:et,hdb_errors:CK}=D(),{HDB_ERROR_MSGS:ns,HTTP_STATUS_CODES:tt}=CK,wK=ae.join(bK,"custom_function_template"),__=ae.join(Ot.get(pt.HDB_SETTINGS_NAMES.HDB_ROOT_KEY),"tmp");function Sd(){let e=Ot.get(pt.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_ENABLED_KEY);if(!(e==="true"||e===!0||e==="TRUE"))throw et(new Error,ns.NOT_ENABLED,tt.BAD_REQUEST,void 0,void 0,!0)}a(Sd,"isCFEnabled");function UK(){Le.trace("getting custom api status");let e={};try{e={is_enabled:Ot.get(pt.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_ENABLED_KEY),port:Ot.get(pt.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_PORT_KEY),directory:Ot.get(pt.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY)}}catch(t){throw et(new Error,ns.FUNCTION_STATUS,tt.INTERNAL_SERVER_ERROR,Le.ERR,t)}return e}a(UK,"customFunctionsStatus");function LK(){Le.trace("getting custom api endpoints");let e={},t=Ot.get(pt.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY);try{c_.sync(Zi(`${t}/*`),{onlyDirectories:!0}).forEach(s=>{let n=s.split("/").pop();e[n]={routes:c_.sync(Zi(`${s}/routes/*.js`)).map(i=>i.split("/").pop().split(".js")[0]),helpers:c_.sync(Zi(`${s}/helpers/*.js`)).map(i=>i.split("/").pop().split(".js")[0]),static:Re.existsSync(Zi(`${s}/static`))&&c_.sync(Zi(`${s}/static/**/*`)).length}})}catch(r){throw et(new Error,ns.GET_FUNCTIONS,tt.INTERNAL_SERVER_ERROR,Le.ERR,r)}return e}a(LK,"getCustomFunctions");function yK(e){e.project&&(e.project=ae.parse(e.project).name),e.file&&(e.file=ae.parse(e.file).name);let t=Hs.getDropCustomFunctionValidator(e);if(t)throw et(t,t.message,tt.BAD_REQUEST);Le.trace("getting custom api endpoint file content");let r=Ot.get(pt.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY),{project:s,type:n,file:i}=e,o=ae.join(r,s,n,i+".js");try{return Re.readFileSync(o,{encoding:"utf8"})}catch(c){throw et(new Error,ns.GET_FUNCTION,tt.INTERNAL_SERVER_ERROR,Le.ERR,c)}}a(yK,"getCustomFunction");function DK(e){Sd(),e.project&&(e.project=ae.parse(e.project).name),e.file&&(e.file=ae.parse(e.file).name);let t=Hs.setCustomFunctionValidator(e);if(t)throw et(t,t.message,tt.BAD_REQUEST);Le.trace("setting custom function file content");let r=Ot.get(pt.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY),{project:s,type:n,file:i,function_content:o}=e;try{return Re.outputFileSync(ae.join(r,s,n,i+".js"),o),`Successfully updated custom function: ${i}.js`}catch(c){throw et(new Error,ns.SET_FUNCTION,tt.INTERNAL_SERVER_ERROR,Le.ERR,c)}}a(DK,"setCustomFunction");function MK(e){e.project&&(e.project=ae.parse(e.project).name),e.file&&(e.file=ae.parse(e.file).name);let t=Hs.getDropCustomFunctionValidator(e);if(t)throw et(t,t.message,tt.BAD_REQUEST);Le.trace("dropping custom function file");let r=Ot.get(pt.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY),{project:s,type:n,file:i}=e;try{return Re.unlinkSync(ae.join(r,s,n,i+".js")),`Successfully deleted custom function: ${i}.js`}catch(o){throw et(new Error,ns.DROP_FUNCTION,tt.INTERNAL_SERVER_ERROR,Le.ERR,o)}}a(MK,"dropCustomFunction");function PK(e){Sd(),e.project&&(e.project=ae.parse(e.project).name);let t=Hs.addCustomFunctionProjectValidator(e);if(t)throw et(t,t.message,tt.BAD_REQUEST);Le.trace("adding custom function project");let r=Ot.get(pt.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY),{project:s}=e;try{let n=ae.join(r,s);return Re.mkdirSync(n,{recursive:!0}),Re.copySync(wK,n),`Successfully created custom function project: ${s}`}catch(n){throw et(new Error,ns.ADD_FUNCTION,tt.INTERNAL_SERVER_ERROR,Le.ERR,n)}}a(PK,"addCustomFunctionProject");function BK(e){e.project&&(e.project=ae.parse(e.project).name);let t=Hs.dropCustomFunctionProjectValidator(e);if(t)throw et(t,t.message,tt.BAD_REQUEST);Le.trace("dropping custom function project");let r=Ot.get(pt.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY),{project:s}=e;try{let n=ae.join(r,s);return Re.rmSync(n,{recursive:!0}),`Successfully deleted project: ${s}`}catch(n){throw et(new Error,ns.DROP_FUNCTION_PROJECT,tt.INTERNAL_SERVER_ERROR,Le.ERR,n)}}a(BK,"dropCustomFunctionProject");async function vK(e){e.project&&(e.project=ae.parse(e.project).name);let t=Hs.packageCustomFunctionProjectValidator(e);if(t)throw et(t,t.message,tt.BAD_REQUEST);Le.trace("packaging custom function project");let r=Ot.get(pt.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY),{project:s}=e,n=ae.join(r,s),i=IK();if(!Re.existsSync(n)){let l=`Unable to locate custom function project: ${s}`;throw Le.error(l),l}Re.ensureDirSync(__);let c=ae.join(__,`${i}.tar`),_={};(e.skip_node_modules===!0||e.skip_node_modules==="true")&&(_={ignore:l=>l.includes(ae.join(n,"node_modules"))}),Ig.pack(n,_).pipe(Re.createWriteStream(c)),await new Promise(l=>setTimeout(l,2e3));let u=Re.readFileSync(c,{encoding:"base64"});return Re.unlinkSync(c),{project:s,payload:u,file:c}}a(vK,"packageCustomFunctionProject");async function HK(e){Sd(),e.project&&(e.project=ae.parse(e.project).name);let t=Hs.deployCustomFunctionProjectValidator(e);if(t)throw et(t,t.message,tt.BAD_REQUEST);Le.trace("deploying custom function project");let r=Ot.get(pt.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY),{project:s,payload:n,file:i}=e,o=ae.join(r,s);return Re.existsSync(o)||Re.mkdirSync(o,{recursive:!0}),Re.existsSync(__)||Re.mkdirSync(__),Re.writeFileSync(i,n,{encoding:"base64"}),await new Promise(_=>setTimeout(_,2e3)),Re.createReadStream(i).pipe(Ig.extract(o)),Re.unlinkSync(i),`Successfully deployed project: ${s}`}a(HK,"deployCustomFunctionProject");bg.exports={customFunctionsStatus:UK,getCustomFunctions:LK,getCustomFunction:yK,setCustomFunction:DK,dropCustomFunction:MK,addCustomFunctionProject:PK,dropCustomFunctionProject:BK,packageCustomFunctionProject:vK,deployCustomFunctionProject:HK}});var Td=h((G2,wg)=>{"use strict";var _r=require("joi"),Cg=he();wg.exports={readTransactionLogValidator:qK,deleteTransactionLogsBeforeValidator:GK};function qK(e){let t=_r.object({schema:_r.string().required(),table:_r.string().required(),from:_r.date().timestamp(),to:_r.date().timestamp(),limit:_r.number().min(1)});return Cg.validateBySchema(e,t)}a(qK,"readTransactionLogValidator");function GK(e){let t=_r.object({schema:_r.string().required(),table:_r.string().required(),timestamp:_r.date().timestamp().required()});return Cg.validateBySchema(e,t)}a(GK,"deleteTransactionLogsBeforeValidator")});var l_=h((F2,Mg)=>{"use strict";var md=T(),u_=At(),Ug=b(),Lg=V(),yg=$r(),{handleHDBError:qn,hdb_errors:FK}=D(),{HTTP_STATUS_CODES:Gn}=FK,{readTransactionLogValidator:VK,deleteTransactionLogsBeforeValidator:kK}=Td(),Dg="This operation relies on clustering and cannot run with it disable.",xK="Logs successfully deleted from transaction log.",$K="All logs successfully deleted from transaction log.";Mg.exports={readTransactionLog:YK,deleteTransactionLogsBefore:KK};async function YK(e){let t=VK(e);if(t)throw qn(t,t.message,Gn.BAD_REQUEST,void 0,void 0,!0);if(!Lg.get(md.CONFIG_PARAMS.CLUSTERING_ENABLED))throw qn(new Error,Dg,Gn.NOT_FOUND,void 0,void 0,!0);let{schema:r,table:s}=e,n=Ug.checkSchemaTableExist(r,s);if(n)throw qn(new Error,n,Gn.NOT_FOUND,void 0,void 0,!0);let i=yg.createNatsTableStreamName(r,s),o=await u_.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===md.OPERATIONS_ENUM.DELETE&&(d.hash_values=l?.entry?.hash_values),c.push(d)}return c}a(YK,"readTransactionLog");async function KK(e){let t=kK(e);if(t)throw qn(t,t.message,Gn.BAD_REQUEST,void 0,void 0,!0);if(!Lg.get(md.CONFIG_PARAMS.CLUSTERING_ENABLED))throw qn(new Error,Dg,Gn.NOT_FOUND,void 0,void 0,!0);let{schema:r,table:s,timestamp:n}=e,i=Ug.checkSchemaTableExist(r,s);if(i)throw qn(new Error,i,Gn.NOT_FOUND,void 0,void 0,!0);let o=yg.createNatsTableStreamName(r,s),{jsm:c}=await u_.getNATSReferences(),_=await u_.getStreamInfo(o),u=new Date(_.state.first_ts).getTime();if(n<=u)return`No transactions exist before: ${n}`;let l=xK,E,d=new Date(_.state.last_ts).getTime();return n>d?(E=_.state.last_seq+1,l=$K):E=(await u_.viewStream(o,parseInt(n),1))[0].nats_sequence,await c.streams.purge(o,{seq:E}),l}a(KK,"deleteTransactionLogsBefore")});var Ad=h((V2,xg)=>{"use strict";var E_=require("joi"),d_=require("path"),Pg=require("fs-extra"),{exec:QK}=require("child_process"),WK=require("util"),Bg=WK.promisify(QK),JK=T(),{handleHDBError:Fn,hdb_errors:ZK}=D(),{HTTP_STATUS_CODES:Vn}=ZK,vg=V(),XK=he(),h_=g();vg.initSync();var Rd=vg.get(JK.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY),Hg="npm install --omit=dev --json",zK=`${Hg} --dry-run`;xg.exports={installModules:jK,auditModules:eQ};async function qg(e,t=void 0){let{stdout:r,stderr:s}=await Bg(e,{cwd:t});if(s)throw new Error(s.replace(`
|
|
7
|
+
`,"")}a(tp,"runCommand");async function C0(){try{await u0.access(zl)}catch{return!1}let e=await tp(`${zl} --version`,void 0),t=e.substring(e.lastIndexOf("v")+1,e.length);return l0.eq(t,I0)}a(C0,"checkNATSServerInstalled");async function tE(e,t,r,s=!0,n="127.0.0.1"){return m0({name:n,port:e,user:t,pass:r,maxReconnectAttempts:-1,waitOnFirstConnect:s,tls:{keyFile:ir.get(ne.CONFIG_PARAMS.CLUSTERING_TLS_PRIVATEKEY),certFile:ir.get(ne.CONFIG_PARAMS.CLUSTERING_TLS_CERTIFICATE),caFile:ir.get(ne.CONFIG_PARAMS.CLUSTERING_TLS_CERT_AUTH),insecure:ir.get(ne.CONFIG_PARAMS.CLUSTERING_TLS_INSECURE)}})}a(tE,"createConnection");async function w0(){Wt&&(await Wt.close(),Wt=void 0)}a(w0,"closeConnection");async function oc(){if(!Wt){let e=await ZA.getClusterUser();if(gs(e))throw new Error("Unable to get nats connection. Cluster user is undefined.");let t=ir.get(ne.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT);Wt=await tE(t,e.username,e.decrypt_hash)}return Wt}a(oc,"getConnection");async function Rn(){if(wi)return wi;gs(Wt)&&await oc();let{domain:e}=yi(ne.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);if(gs(e))throw new Error("Error getting JetStream domain. Unable to get JetStream manager.");return wi=await Wt.jetstreamManager({domain:e}),wi}a(Rn,"getJetStreamManager");async function rp(){if(Ui)return Ui;gs(Wt)&&await oc();let{domain:e}=yi(ne.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);if(gs(e))throw new Error("Error getting JetStream domain. Unable to get JetStream manager.");return Ui=Wt.jetstream({domain:e}),Ui}a(rp,"getJetStream");async function Mt(){let e=Wt||await oc(),t=wi||await Rn(),r=Ui||await rp();return{connection:e,jsm:t,js:r}}a(Mt,"getNATSReferences");async function U0(){let e=ir.get(ne.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),{sys_name:t,decrypt_hash:r}=await ZA.getClusterUser(),s=await tE(e,t,r),n=eE(),i=s.subscribe(n),o=[],c=(async()=>{for await(let _ of i)o.push(ep.decode(_.data))})();return await s.publish("$SYS.REQ.SERVER.PING.VARZ",void 0,{reply:n}),await s.flush(),await jl.async_set_timeout(50),await i.drain(),await s.close(),await c,o}a(U0,"getServerList");async function rE(e,t){let{jsm:r}=await Mt();await r.streams.add({name:e,storage:XA.File,retention:zA.Limits,subjects:t})}a(rE,"createLocalStream");async function sp(){let{jsm:e}=await Mt(),t=await e.streams.list().next(),r=[];return t.forEach(s=>{r.push(s)}),r}a(sp,"listStreams");async function L0(e){let{jsm:t}=await Mt();await t.streams.delete(e)}a(L0,"deleteLocalStream");async function y0(e){let{connection:t}=await Mt(),r=[],s=eE(),n=t.subscribe(s),i=(async()=>{for await(let o of n)r.push(ep.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(y0,"listRemoteStreams");async function D0(e,t=void 0,r=void 0){let{jsm:s,connection:n}=await Mt(),i=d0(),o=[],c={ack_policy:jA.None,durable_name:i,deliver_subject:i,deliver_policy:Xl.All};t&&(c.deliver_policy=Xl.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=p0(l),d=JA(E.data),S={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(","),S.originators=m)}o.push(S),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(D0,"viewStream");async function M0(e,t,r=[],s=[]){br.trace(`publishToStream called with subject: ${e}, stream: ${t}, entries:`,r,"originators:",s);let{connection:n,js:i}=await Mt(),o=await cc(),c=`${e}.${o}`,_=A0();s.push(o),_.append("originators",s.join());for(let u=0,l=r.length;u<l;u++)try{br.trace(`publishToStream publishing to subject: ${c}, data:`,r[u]),await i.publish(c,Zl(r[u]),{headers:_})}catch(E){if(E.code&&E.code.toString()==="503")br.trace(`publishToStream creating stream: ${t}`),await rE(t,[c]),await i.publish(c,Zl(r[u]),{headers:_});else throw E}}a(M0,"publishToStream");function yi(e){e=e.toLowerCase();let t=Li.join(ir.get(ne.CONFIG_PARAMS.ROOTPATH),g0);if(e===ne.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase())return gs(Jl)&&(Jl={port:bi.getConfigFromFile(ne.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),server_name:bi.getConfigFromFile(ne.CONFIG_PARAMS.CLUSTERING_NODENAME)+te.SERVER_SUFFIX.HUB,config_file:te.NATS_CONFIG_FILES.HUB_SERVER,pid_file_path:Li.join(t,te.PID_FILES.HUB),hdb_nats_path:t}),Jl;if(e===ne.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())return gs(Wl)&&(Wl={port:bi.getConfigFromFile(ne.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),server_name:bi.getConfigFromFile(ne.CONFIG_PARAMS.CLUSTERING_NODENAME)+te.SERVER_SUFFIX.LEAF,config_file:te.NATS_CONFIG_FILES.LEAF_SERVER,domain:bi.getConfigFromFile(ne.CONFIG_PARAMS.CLUSTERING_NODENAME)+te.SERVER_SUFFIX.LEAF,pid_file_path:Li.join(t,te.PID_FILES.LEAF),hdb_nats_path:t}),Wl;br.error(`Unable to get Nats server config. Unrecognized process: ${e}`)}a(yi,"getServerConfig");async function P0(e){let{jsm:t}=await Mt(),r=await cc();try{await t.streams.add({name:e.stream_name,storage:XA.File,retention:zA.Workqueue,subjects:[`${te.SUBJECT_PREFIXES.MSGID}.${r}`,`${te.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:jA.Explicit,deliver_subject:`${e.deliver_subject}.${r}`,durable_name:e.durable_name,deliver_policy:Xl.All,max_ack_pending:1e4,deliver_group:e.deliver_group,filter_subject:`${te.SUBJECT_PREFIXES.TXN}.>`});else throw s}}a(P0,"createWorkQueueStream");async function np(e,t,r){let{jsm:s}=await Mt(),n=await s.streams.info(t),i=ip(s.prefix),o=r.start_time?r.start_time:new Date(Date.now()).toISOString(),{schema:c,table:_}=r,u=ac.createNatsTableStreamName(c,_),l=i===e,E,d,S=!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`){S=!0;break}if(S===!0){if(E.opt_start_time===o)return;await op(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:`${te.SUBJECT_PREFIXES.TXN}.>`};l||(m.external={api:`$JS.${e}.API`,deliver:""}),n.config.sources.push(m),await s.streams.update(t,n.config)}a(np,"addSourceToWorkStream");function ip(e){return e.split(".")[1]}a(ip,"extractServerName");async function ap(e,t,r){let{schema:s,table:n}=r,i=ac.createNatsTableStreamName(s,n),{jsm:o}=await Mt(),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 op(s,n,u,t)}a(ap,"removeSourceFromWorkStream");async function op(e,t,r,s){let n=await Rn(),i;try{i=up(e,t,r.external.api.split(".")[1]),await n.streams.purge(s,{filter:i})}catch{br.error("Error purging source subject",i,"from work stream",s)}}a(op,"purgeSourceFromWorkStream");async function B0(e,t,r=2e3,s=eE()){if(!jl.isObject(t))throw new Error("data param must be an object");let n=Zl(t),{connection:i}=await Mt(),o={timeout:r};s&&(o.reply=s,o.noMux=!0);let c=await i.request(e,n,o);return JA(c.data)}a(B0,"request");function sE(e){return new Promise(async(t,r)=>{let s=S0(zl,["--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(sE,"reloadNATS");async function v0(){let{pid_file_path:e}=yi(ne.PROCESS_DESCRIPTORS.CLUSTERING_HUB);await sE(e)}a(v0,"reloadNATSHub");async function H0(){let{pid_file_path:e}=yi(ne.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);await sE(e)}a(H0,"reloadNATSLeaf");function q0(e,t,r){let s;switch(e.code){case KA.NoResponders:s=`Unable to ${t}, node '${r}' is not listening.`;break;case KA.Timeout:s=`Unable to ${t}, node '${r}' is listening but did not respond.`;break;default:s=e.message;break}return s}a(q0,"requestErrorHandler");async function G0(e,t){let r=t+te.SERVER_SUFFIX.LEAF;await f0.writeTransaction(ne.SYSTEM_SCHEMA_NAME,ne.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,async()=>{e.subscribe===!0?await np(r,te.WORK_QUEUE_CONSUMER_NAMES.stream_name,e):await ap(r,te.WORK_QUEUE_CONSUMER_NAMES.stream_name,e)})}a(G0,"updateWorkStream");async function cp(e,t){let r=ac.createNatsTableStreamName(e,t),s=await cc(),n=up(e,t,s);await rE(r,[n])}a(cp,"createLocalTableStream");async function F0(e){for(let t=0,r=e.length;t<r;t++){let s=e[t].schema,n=e[t].table;await cp(s,n)}}a(F0,"createTableStreams");async function _p(e,t){if(ir.get(ne.CONFIG_PARAMS.CLUSTERING_ENABLED))try{let r=ac.createNatsTableStreamName(e,t),{jsm:s}=await Mt();await s.streams.purge(r)}catch(r){if(r.message==="stream not found")br.warn(r);else throw r}}a(_p,"purgeTableStream");async function V0(e,t){if(ir.get(ne.CONFIG_PARAMS.CLUSTERING_ENABLED))for(let r=0,s=t.length;r<s;r++)await _p(e,t[r])}a(V0,"purgeSchemaTableStreams");async function k0(e){return(await Rn()).streams.info(e)}a(k0,"getStreamInfo");function up(e,t,r){return`${te.SUBJECT_PREFIXES.TXN}.${e}.${t}.${r}`}a(up,"createSubjectName");async function cc(){if(Ci)return Ci;if(Ci=(await Rn())?.nc?.info?.server_name,Ci===void 0)throw new Error("Unable to get jetstream manager server name");return Ci}a(cc,"getJsmServerName");async function x0(){let e=await Rn(),t=await cc(),r=await sp();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===te.SCHEMA_QUEUE_CONSUMER_NAMES.stream_name){let _=`${te.SCHEMA_QUEUE_CONSUMER_NAMES.deliver_subject}.${t}`;br.trace(`Updating stream subject name from: ${i} to: ${_}`),n.subjects[0]=_}else if(n.name===te.WORK_QUEUE_CONSUMER_NAMES.stream_name){let _=`${te.WORK_QUEUE_CONSUMER_NAMES.stream_name}.${t}`;br.trace(`Updating stream subject name from: ${i} to: ${_}`),n.subjects[0]=_,await e.consumers.update(te.WORK_QUEUE_CONSUMER_NAMES.stream_name,te.WORK_QUEUE_CONSUMER_NAMES.durable_name,{deliver_subject:`${te.WORK_QUEUE_CONSUMER_NAMES.deliver_subject}.${t}`})}else{let _=i.split(".");_[_.length-1]=t;let u=_.join(".");br.trace(`Updating stream subject name from: ${i} to: ${u}`),n.subjects[0]=u}await e.streams.update(n.name,n)}}}a(x0,"updateNodeNameLocalStreams")});var nE=h((v3,Ep)=>{"use strict";var _c=class{constructor(t,r,s){this.timestamp=t,this.user=r,this.node_name=s}};a(_c,"ClusteringOriginObject");Ep.exports=_c});var On=h((H3,Sp)=>{"use strict";var dp=b(),Mi=V(),ue=T(),iE=Se(),An=At(),fe=g(),hp=nE(),$0=$r();Mi.initSync();var pn=iE.SCHEMA_QUEUE_CONSUMER_NAMES.stream_name,Di=iE.SCHEMA_QUEUE_CONSUMER_NAMES.deliver_subject;Sp.exports={sendAttributeTransaction:lc,postOperationHandler:K0};async function lc(e,t,r=[]){if(!!Mi.get(ue.CONFIG_PARAMS.CLUSTERING_ENABLED)&&!dp.isEmptyOrZeroLength(e.new_attributes)&&t.schema!==ue.SYSTEM_SCHEMA_NAME){let s=t.hdb_user?.username,n=Mi.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 hp(e.txn_time,s,n)};fe.trace(`sendAttributeTransaction publishing ${pn}`,o),await An.publishToStream(Di,pn,[o],r)}}}a(lc,"sendAttributeTransaction");async function uc(e,t,r,s=[]){if(e.schema===ue.SYSTEM_SCHEMA_NAME)return;let n=Y0(e,t,r);n&&(fe.trace(`sendOperationTransaction publishing to schema ${e.schema} table ${e.table} following transaction:`,n),await An.publishToStream(`${iE.SUBJECT_PREFIXES.TXN}.${e.schema}.${e.table}`,$0.createNatsTableStreamName(e.schema,e.table),[n],s))}a(uc,"sendOperationTransaction");function Y0(e,t,r){if(dp.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(Y0,"convertCRUDOperationToTransaction");async function K0(e,t,r=[]){if(!Mi.get(ue.CONFIG_PARAMS.CLUSTERING_ENABLED))return;fe.trace(`postOperationHandler called for operation ${e.operation} on schema.table: ${e.schema}.${e.table}`);let s=e.hdb_user?.username,n=Mi.get(ue.CONFIG_PARAMS.CLUSTERING_NODENAME),i=new hp(t.txn_time,s,n);switch(e.operation){case ue.OPERATIONS_ENUM.INSERT:try{await uc(e,t.inserted_hashes,i,r),await lc(t,e,r)}catch(o){fe.error("There was an error calling clustering postOperationHandler for insert."),fe.error(o)}break;case ue.OPERATIONS_ENUM.DELETE:try{await uc(e,t.deleted_hashes,i,r)}catch(o){fe.error("There was an error calling clustering postOperationHandler for delete."),fe.error(o)}break;case ue.OPERATIONS_ENUM.UPDATE:try{await uc(e,t.update_hashes,i,r),await lc(t,e,r)}catch(o){fe.error("There was an error calling clustering postOperationHandler for update."),fe.error(o)}break;case ue.OPERATIONS_ENUM.UPSERT:try{await uc(e,t.upserted_hashes,i,r),await lc(t,e,r)}catch(o){fe.error("There was an error calling clustering postOperationHandler for upsert."),fe.error(o)}break;case ue.OPERATIONS_ENUM.CREATE_SCHEMA:try{let o={operation:ue.OPERATIONS_ENUM.CREATE_SCHEMA,schema:e.schema,__origin:i};await An.publishToStream(Di,pn,[o],r)}catch(o){fe.error("There was an error calling clustering postOperationHandler for create_schema."),fe.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 An.publishToStream(Di,pn,[o],r)}catch(o){fe.error("There was an error calling clustering postOperationHandler for create_table."),fe.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 An.publishToStream(Di,pn,[o],r)}catch(o){fe.error("There was an error calling clustering postOperationHandler for create_attribute."),fe.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 An.publishToStream(Di,pn,[o],r)}catch(o){fe.error("There was an error calling clustering postOperationHandler for csv_data_load."),fe.error(o)}break;default:break}return t}a(K0,"postOperationHandler")});var Ap=h((q3,Rp)=>{"use strict";var Q0=mt(),W0=Kr(),fp=g(),Tp=yt(),J0=ic(),Z0=require("clone"),oE=require("alasql"),X0=yo(),mp=require("util"),z0=mp.promisify(W0.getTableSchema),j0=mp.promisify(Q0.search),eV=T(),aE=b(),tV=On();X0(oE);Rp.exports={update:sV};var rV="There was a problem performing this update. Please check the logs and try again.";async function sV({statement:e,hdb_user:t}){let r=await z0(e.table.databaseid,e.table.tableid),s=nV(e.columns);aE.backtickASTSchemaItems(e);let{table:n,where:i}=e,o=Z0(n),c=aE.isEmpty(i)?"":` WHERE ${i.toString()}`,_=`SELECT ${r.hash_attribute} FROM ${n.toString()} ${c}`,u=oE.parse(_).statements[0],l=await J0.writeTransaction(r.schema,r.name,async()=>{let E=await j0(u),d=iV(s,E);return aV(o,d,t)});return await Tp.flush({schema:r.schema,table:r.name}),l}a(sV,"update");function nV(e){try{let t={};return e.forEach(r=>{"value"in r.expression?t[r.column.columnid]=r.expression.value:t[r.column.columnid]=oE.compile(`SELECT ${r.expression.toString()} AS [${eV.FUNC_VAL}] FROM ?`)}),t}catch(t){throw fp.error(t),new Error(rV)}}a(nV,"createUpdateRecord");function iV(e,t){return aE.isEmptyOrZeroLength(t)?[]:t.map(r=>Object.assign(r,e))}a(iV,"buildUpdateRecords");async function aV(e,t,r){let s={operation:"update",schema:e.databaseid_orig,table:e.tableid_orig,records:t,hdb_user:r};try{let n=await Tp.update(s);await tV.postOperationHandler(s,n);try{delete n.new_attributes,delete n.txn_time}catch(i){fp.error(`Error delete new_attributes from update response: ${i}`)}return n}catch(n){throw n}}a(aV,"updateRecords")});var Op=h((G3,pp)=>{var oV=require("alasql"),cV=mt(),_V=g(),uV=Nr(),_E=require("util"),cE=b(),lV=T(),EV=Kr(),dV=ic(),hV=On(),SV=yt(),fV="record",TV="successfully deleted",mV=_E.callbackify(OV),RV=_E.promisify(cV.search),AV=_E.promisify(EV.getTableSchema);pp.exports={convertDelete:mV};function pV(e){return`${e.deleted_hashes.length} ${fV}${e.deleted_hashes.length===1?"":"s"} ${TV}`}a(pV,"generateReturnMessage");async function OV({statement:e,hdb_user:t}){let r=await AV(e.table.databaseid,e.table.tableid);cE.backtickASTSchemaItems(e);let{table:s,where:n}=e,i=cE.isEmpty(n)?"":` WHERE ${n.toString()}`,o=`SELECT ${r.hash_attribute} FROM ${s.toString()} ${i}`,c=oV.parse(o).statements[0],_={operation:lV.OPERATIONS_ENUM.DELETE,schema:s.databaseid_orig,table:s.tableid_orig,hdb_user:t};try{let u=await dV.writeTransaction(r.schema,r.name,async()=>(_.records=await RV(c),uV.deleteRecords(_)));return await SV.flush({schema:r.schema,table:r.name}),u.deleted_hashes.length>0&&await hV.postOperationHandler(_,u),cE.isEmptyOrZeroLength(u.message)&&(u.message=pV(u)),delete u.txn_time,u}catch(u){throw _V.error(u),u.hdb_code?u.message:u}}a(OV,"convertDelete")});var Ip=h((F3,gp)=>{"use strict";var lE=ms(),{hdb_errors:uE}=D();gp.exports={checkSchemaExists:Np,checkSchemaTableExists:NV,schema_describe:lE};async function Np(e){if(!global.hdb_schema[e])try{let t=await lE.describeSchema({schema:e});global.hdb_schema[e]=t}catch{return uE.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}}a(Np,"checkSchemaExists");async function NV(e,t){let r=await Np(e);if(r)return r;if(!global.hdb_schema[e][t])try{let s=await lE.describeTable({schema:e,table:t});if(!s||Object.keys(s).length===0)return uE.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t);global.hdb_schema[e][t]=s}catch{return uE.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}}a(NV,"checkSchemaTableExists")});var Ec=h((k3,Lp)=>{"use strict";var Nn=Wa(),Is=Ip(),bp=g(),gV=require("uuid").v4,V3=require("clone"),In=js(),bs=T(),IV=require("util"),Cs=Nr(),{handleHDBError:Be,hdb_errors:bV}=D(),{HDB_ERROR_MSGS:gn,HTTP_STATUS_CODES:ve}=bV,{SchemaEventMsg:bn}=Vr(),Cp=At();Lp.exports={createSchema:CV,createSchemaStructure:wp,createTable:wV,createTableStructure:Up,createAttribute:MV,dropSchema:UV,dropTable:LV,dropAttribute:yV};async function CV(e){try{let t=await wp(e);return In.signalSchemaChange(new bn(process.pid,e.operation,e.schema)),t}catch(t){throw t}}a(CV,"createSchema");async function wp(e){let t=Nn.schema_object(e);if(t)throw Be(t,t.message,ve.BAD_REQUEST,void 0,void 0,!0);if(!await Is.checkSchemaExists(e.schema))throw Be(new Error,gn.SCHEMA_EXISTS_ERR(e.schema),ve.BAD_REQUEST,bs.LOG_LEVELS.ERROR,gn.SCHEMA_EXISTS_ERR(e.schema),!0);try{return await Cs.createSchema(e),`schema '${e.schema}' successfully created`}catch(r){throw r}}a(wp,"createSchemaStructure");async function wV(e){try{let t=await Up(e);return In.signalSchemaChange(new bn(process.pid,e.operation,e.schema,e.table)),t}catch(t){throw t}}a(wV,"createTable");async function Up(e){let t=Nn.create_table_object(e);if(t)throw Be(t,t.message,ve.BAD_REQUEST,void 0,void 0,!0);Nn.validateTableResidence(e.residence);let r=await Is.checkSchemaExists(e.schema);if(r)throw Be(new Error,r,ve.NOT_FOUND,bs.LOG_LEVELS.ERROR,r,!0);if(!await Is.checkSchemaTableExists(e.schema,e.table))throw Be(new Error,gn.TABLE_EXISTS_ERR(e.schema,e.table),ve.BAD_REQUEST,bs.LOG_LEVELS.ERROR,gn.TABLE_EXISTS_ERR(e.schema,e.table),!0);let n={name:e.table,schema:e.schema,id:gV(),hash_attribute:e.hash_attribute};try{if(e.residence)if(global.clustering_on)n.residence=e.residence,await Cs.createTable(n,e);else throw Be(new Error,"Clustering does not appear to be enabled. Cannot insert table with property 'residence'.",ve.BAD_REQUEST);else await Cs.createTable(n,e);return`table '${e.schema}.${e.table}' successfully created.`}catch(i){throw i}}a(Up,"createTableStructure");async function UV(e){let t=Nn.schema_object(e);if(t)throw Be(t,t.message,ve.BAD_REQUEST,void 0,void 0,!0);let r=await Is.checkSchemaExists(e.schema);if(r)throw Be(new Error,r,ve.NOT_FOUND,bs.LOG_LEVELS.ERROR,r,!0);let s=await Is.schema_describe.describeSchema({schema:e.schema});global.hdb_schema[e.schema]=s;let n=Object.keys(global.hdb_schema[e.schema]);return await Cs.dropSchema(e),In.signalSchemaChange(new bn(process.pid,e.operation,e.schema)),delete global.hdb_schema[e.schema],await Cp.purgeSchemaTableStreams(e.schema,n),`successfully deleted schema '${e.schema}'`}a(UV,"dropSchema");async function LV(e){let t=Nn.table_object(e);if(t)throw Be(t,t.message,ve.BAD_REQUEST,void 0,void 0,!0);let r=await Is.checkSchemaTableExists(e.schema,e.table);if(r)throw Be(new Error,r,ve.NOT_FOUND,bs.LOG_LEVELS.ERROR,r,!0);return await Cs.dropTable(e),In.signalSchemaChange(new bn(process.pid,e.operation,e.schema,e.table)),await Cp.purgeTableStream(e.schema,e.table),`successfully deleted table '${e.schema}.${e.table}'`}a(LV,"dropTable");async function yV(e){let t=Nn.attribute_object(e);if(t)throw Be(t,t.message,ve.BAD_REQUEST,void 0,void 0,!0);let r=await Is.checkSchemaTableExists(e.schema,e.table);if(r)throw Be(new Error,r,ve.NOT_FOUND,bs.LOG_LEVELS.ERROR,r,!0);if(e.attribute===global.hdb_schema[e.schema][e.table].hash_attribute)throw Be(new Error,"You cannot drop a hash attribute",ve.BAD_REQUEST,void 0,void 0,!0);if(bs.TIME_STAMP_NAMES.indexOf(e.attribute)>=0)throw Be(new Error,`cannot drop internal timestamp attribute: ${e.attribute}`,ve.BAD_REQUEST,void 0,void 0,!0);try{return await Cs.dropAttribute(e),DV(e),In.signalSchemaChange(new bn(process.pid,e.operation,e.schema,e.table,e.attribute)),`successfully deleted attribute '${e.attribute}'`}catch(s){throw bp.error(`Got an error deleting attribute ${IV.inspect(e)}.`),s}}a(yV,"dropAttribute");function DV(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(DV,"dropAttributeFromGlobal");async function MV(e){if(!global.hdb_schema[e.schema])throw Be(new Error,gn.SCHEMA_NOT_FOUND(e.schema),ve.NOT_FOUND,void 0,void 0,!0);if(!global.hdb_schema[e.schema][e.table])throw Be(new Error,gn.TABLE_NOT_FOUND(e.schema,e.table),ve.NOT_FOUND,void 0,void 0,!0);try{return await Cs.createAttribute(e),In.signalSchemaChange(new bn(process.pid,e.operation,e.schema,e.table,e.attribute)),`attribute '${e.schema}.${e.table}.${e.attribute}' successfully created.`}catch(t){throw bp.error(t),t}}a(MV,"createAttribute")});var Dp=h((x3,yp)=>{"use strict";var{OPERATIONS_ENUM:PV}=T(),dc=class{constructor(t,r,s=void 0,n=void 0){this.operation=PV.READ_AUDIT_LOG,this.schema=t,this.table=r,this.search_type=s,this.search_values=n}};a(dc,"ReadAuditLogObject");yp.exports=dc});var EE=h((Y3,Hp)=>{"use strict";var BV=Nr(),$3=Dp(),hc=b(),Sc=T(),vV=V(),{handleHDBError:Mp,hdb_errors:HV}=D(),{HDB_ERROR_MSGS:Pp,HTTP_STATUS_CODES:Bp}=HV,qV=Object.values(Sc.READ_AUDIT_LOG_SEARCH_TYPES_ENUM),vp="To use this operation audit log must be enabled in harperdb-config.yaml";Hp.exports=GV;async function GV(e){if(hc.isEmpty(e.schema))throw new Error(Pp.SCHEMA_REQUIRED_ERR);if(hc.isEmpty(e.table))throw new Error(Pp.TABLE_REQUIRED_ERR);if(!vV.get(Sc.CONFIG_PARAMS.LOGGING_AUDITLOG))throw Mp(new Error,vp,Bp.BAD_REQUEST,Sc.LOG_LEVELS.ERROR,vp,!0);let t=hc.checkSchemaTableExist(e.schema,e.table);if(t)throw Mp(new Error,t,Bp.NOT_FOUND,Sc.LOG_LEVELS.ERROR,t,!0);if(!hc.isEmpty(e.search_type)&&qV.indexOf(e.search_type)<0)throw new Error(`Invalid search_type '${e.search_type}'`);return await BV.readAuditLog(e)}a(GV,"readAuditLog")});var xp=h((K3,kp)=>{var zr=require("validate.js"),Gp=de(),Cn=T(),{handleHDBError:FV,hdb_errors:VV}=D(),{HDB_ERROR_MSGS:le,HTTP_STATUS_CODES:kV}=VV,dE=a(()=>({role:{presence:!0,format:"[\\w\\-\\_]+"},id:{presence:!0,format:"[\\w\\-\\_]+"},permission:{presence:!0}}),"constraintsTemplate"),xV={STRUCTURE_USER:"structure_user"},qp=Object.values(Cn.ROLE_TYPES_ENUM),$V="attribute_permissions",YV="attribute_name",{PERMS_CRUD_ENUM:wn}=Cn,KV=[$V,...Object.values(wn)],Fp=[wn.READ,wn.INSERT,wn.UPDATE],QV=[YV,...Fp];function WV(e){let t=dE();return t.role.presence=!0,t.id.presence=!1,t.permission.presence=!0,Vp(e,t)}a(WV,"addRoleValidation");function JV(e){let t=dE();return t.role.presence=!1,t.id.presence=!0,t.permission.presence=!0,Vp(e,t)}a(JV,"alterRoleValidation");function ZV(e){let t=dE();return t.role.presence=!1,t.id.presence=!0,t.permission.presence=!1,Gp.validateObject(e,t)}a(ZV,"dropRoleValidation");var XV=["operation","role","id","permission","hdb_user","hdb_auth_header"];function Vp(e,t){let r={main_permissions:[],schema_permissions:{}},s=Object.keys(e),n=[];for(let o=0,c=s.length;o<c;o++)XV.includes(s[o])||n.push(s[o]);n.length>0&&Te(le.INVALID_ROLE_JSON_KEYS(n),r);let i=Gp.validateObject(e,t);if(i&&i.message.split(",").forEach(o=>{Te(o,r)}),e.permission){let o=zV(e);o&&Te(o,r),qp.forEach(c=>{e.permission[c]&&!zr.isBoolean(e.permission[c])&&Te(le.SU_CU_ROLE_BOOLEAN_ERROR(c),r)})}for(let o in e.permission)if(qp.indexOf(o)<0){if(o===xV.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]||Te(le.SCHEMA_NOT_FOUND(E),r)}continue}Te(le.STRUCTURE_USER_ROLE_TYPE_ERROR(o),r);continue}let c=e.permission[o];if(!o||!global.hdb_schema[o]){Te(le.SCHEMA_NOT_FOUND(o),r);continue}if(c.tables)for(let _ in c.tables){let u=c.tables[_];if(!_||!global.hdb_schema[o][_]){Te(le.TABLE_NOT_FOUND(o,_),r);continue}if(Object.keys(u).forEach(l=>{KV.includes(l)||Te(le.INVALID_PERM_KEY(l),r,o,_)}),Object.values(wn).forEach(l=>{zr.isDefined(u[l])?zr.isBoolean(u[l])||Te(le.TABLE_PERM_NOT_BOOLEAN(l),r,o,_):Te(le.TABLE_PERM_MISSING(l),r,o,_)}),zr.isDefined(u.attribute_permissions)){if(!zr.isArray(u.attribute_permissions)){Te(le.ATTR_PERMS_NOT_ARRAY,r,o,_);continue}}else{Te(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 S=u.attribute_permissions[d];if(Object.keys(S).forEach(R=>{!QV.includes(R)&&R!==wn.DELETE&&Te(le.INVALID_ATTR_PERM_KEY(R),r,o,_)}),!zr.isDefined(S.attribute_name)){Te(le.ATTR_PERM_MISSING_NAME,r,o,_);continue}let m=S.attribute_name;if(!l.includes(m)){Te(le.INVALID_ATTRIBUTE_IN_PERMS(m),r,o,_);continue}Fp.forEach(R=>{zr.isDefined(S[R])?zr.isBoolean(S[R])||Te(le.ATTR_PERM_NOT_BOOLEAN(R,m),r,o,_):Te(le.ATTR_PERM_MISSING(R,m),r,o,_)}),!E.read&&S.read===!0&&(E.read=!0),!E.insert&&S.insert===!0&&(E.insert=!0),!E.update&&S.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}.${_}`;Te(le.MISMATCHED_TABLE_ATTR_PERMS(d),r,o,_)}}}}return jV(r)}a(Vp,"customValidate");kp.exports={addRoleValidation:WV,alterRoleValidation:JV,dropRoleValidation:ZV};function zV(e){let{operation:t,permission:r}=e;if(t===Cn.OPERATIONS_ENUM.ADD_ROLE||t===Cn.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?Cn.ROLE_TYPES_ENUM.SUPER_USER:Cn.ROLE_TYPES_ENUM.CLUSTER_USER;return le.SU_CU_ROLE_NO_PERMS_ALLOWED(o)}}}return null}a(zV,"validateNoSUPerms");function jV(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 FV(new Error,s,kV.BAD_REQUEST)}else return null}a(jV,"generateRolePermResponse");function Te(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(Te,"addPermError")});var pE=h((Q3,Jp)=>{"use strict";var $p=yt(),Yp=mt(),ek=ps(),fE=xp(),TE=js(),tk=require("uuid").v4,mE=require("util"),rk=pi(),Cr=T(),Kp=b(),RE=mE.promisify(Yp.searchByValue),sk=mE.promisify(Yp.searchByHash),nk=mE.promisify(ek.delete),ik=Qt(),ak=Ss(),{hdb_errors:ok,handleHDBError:Pi}=D(),{HDB_ERROR_MSGS:Qp,HTTP_STATUS_CODES:hE}=ok,{UserEventMsg:AE}=Vr();Jp.exports={addRole:ck,alterRole:uk,dropRole:lk,listRoles:Wp};function SE(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(SE,"scrubRoleDetails");async function ck(e){let t=fE.addRoleValidation(e);if(t)throw t;if(!(await rk.getLicense()).enterprise){let o=await Wp();if(_k(e,o))throw new Error(`Your current license only supports ${Cr.BASIC_LICENSE_MAX_CLUSTER_USER_ROLES} cluster_user role. ${Cr.SUPPORT_HELP_MSG}`);if(o.length>=2)throw new Error(`Your current license only supports ${Cr.BASIC_LICENSE_MAX_NON_CU_ROLES+Cr.BASIC_LICENSE_MAX_CLUSTER_USER_ROLES} roles. ${Cr.SUPPORT_HELP_MSG}`)}e=SE(e);let s={schema:"system",table:"hdb_role",search_attribute:"role",search_value:e.role,hash_attribute:"id",get_attributes:["*"]},n;try{n=await RE(s)}catch(o){throw Pi(o)}if(n&&n.length>0)throw Pi(new Error,Qp.ROLE_ALREADY_EXISTS(e.role),hE.CONFLICT,void 0,void 0,!0);e.id||(e.id=tk());let i={operation:"insert",schema:"system",table:"hdb_role",hash_attribute:"id",records:[e]};return await $p.insert(i),TE.signalUserChange(new AE(process.pid)),e=SE(e),e}a(ck,"addRole");function _k(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(!Kp.isEmpty(i)&&i.cluster_user===!0)return!0}return r}a(_k,"checkClusterUserRole");async function uk(e){let t=fE.alterRoleValidation(e);if(t)throw t;e=SE(e);let r={operation:"update",schema:"system",table:"hdb_role",hash_attribute:"rolename",records:[e]};try{await $p.update(r)}catch(s){throw Pi(s)}return TE.signalUserChange(new AE(process.pid)),e}a(uk,"alterRole");async function lk(e){let t=fE.dropRoleValidation(e);if(t)throw Pi(new Error,t,hE.BAD_REQUEST,void 0,void 0,!0);let r=new ak(Cr.SYSTEM_SCHEMA_NAME,Cr.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME,[e.id],["role"]),s=await sk(r);if(s.length===0)throw Pi(new Error,Qp.ROLE_NOT_FOUND,hE.NOT_FOUND,void 0,void 0,!0);let n=new ik(Cr.SYSTEM_SCHEMA_NAME,Cr.SYSTEM_TABLE_NAMES.USER_TABLE_NAME,"role",e.id,void 0,["username","active"]),i=await RE(n),o=!1;if(Kp.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 nk(c),TE.signalUserChange(new AE(process.pid)),`${s[0].role} successfully deleted`}a(lk,"dropRole");async function Wp(){return RE({table:"hdb_role",schema:"system",hash_attribute:"id",search_attribute:"id",search_value:"*",get_attributes:["*"]})}a(Wp,"listRoles")});var jp=h((W3,zp)=>{"use strict";var Ek=V(),jr=require("joi"),dk=de(),Zp=require("moment"),hk=require("fs-extra"),OE=require("path"),Sk=require("lodash"),Bi=T(),{LOG_LEVELS:ws}=T(),fk="YYYY-MM-DD hh:mm:ss",Tk=OE.resolve(__dirname,"../logs");zp.exports=function(e){return dk.validateBySchema(e,mk)};var mk=jr.object({from:jr.custom(Xp),until:jr.custom(Xp),level:jr.valid(ws.NOTIFY,ws.FATAL,ws.ERROR,ws.WARN,ws.INFO,ws.DEBUG,ws.TRACE),order:jr.valid("asc","desc"),limit:jr.number().min(1),start:jr.number().min(0),log_name:jr.custom(Rk)});function Xp(e,t){if(Zp(e,Zp.ISO_8601).format(fk)==="Invalid date")return t.message(`'${t.state.path[0]}' date '${e}' is invalid.`)}a(Xp,"validateDatetime");function Rk(e,t){if(Sk.invert(Bi.PROCESS_LOG_NAMES)[e]===void 0)return t.message(`'log_name' '${e}' is invalid.`);let s=Ek.get(Bi.HDB_SETTINGS_NAMES.LOG_PATH_KEY),n=e===void 0?Bi.PROCESS_LOG_NAMES.HDB:e,i=n===Bi.PROCESS_LOG_NAMES.INSTALL?OE.join(Tk,Bi.PROCESS_LOG_NAMES.INSTALL):OE.join(s,n);return hk.existsSync(i)?null:t.message(`'log_name' '${e}' does not exist.`)}a(Rk,"validateReadLogPath")});var gE=h((J3,tO)=>{"use strict";var fc=T(),eO=g(),Ak=V(),pk=jp(),NE=require("path"),Ok=require("fs-extra"),Nk=require("readline"),{once:gk}=require("events"),{handleHDBError:Ik,hdb_errors:bk}=D(),{PACKAGE_ROOT:Ck}=T(),wk=NE.join(Ck,"logs"),Uk=1e3;tO.exports=Lk;async function Lk(e){let t=pk(e);if(t)throw Ik(t,t.message,bk.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0);let r=Ak.get(fc.HDB_SETTINGS_NAMES.LOG_PATH_KEY),s=e.log_name===void 0?fc.PROCESS_LOG_NAMES.HDB:e.log_name,n=s===fc.PROCESS_LOG_NAMES.INSTALL?NE.join(wk,fc.PROCESS_LOG_NAMES.INSTALL):NE.join(r,s),i=Ok.createReadStream(n);i.on("error",j=>{eO.error(j)});let o=Nk.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,S=e.limit===void 0?Uk:e.limit,m=e.order===void 0?void 0:e.order,R=e.start===void 0?0:e.start,w=R+S,U=0,B=[];return o.on("line",j=>{let k,J,xe,$e;try{k=JSON.parse(j)}catch(Ea){eO.warn(Ea.message);return}switch(!0){case(c&&u&&E):J=new Date(k.timestamp),xe=new Date(l),$e=new Date(d),k.level===_&&J>=xe&&J<=$e&&U<R?U++:k.level===_&&J>=xe&&J<=$e&&(ts(k,m,B),U++,U===w&&es(o));break;case(c&&u):J=new Date(k.timestamp),xe=new Date(l),k.level===_&&J>=xe&&U<R?U++:k.level===_&&J>=xe&&(ts(k,m,B),U++,U===w&&es(o));break;case(c&&E):J=new Date(k.timestamp),$e=new Date(d),k.level===_&&J<=$e&&U<R?U++:k.level===_&&J<=$e&&(ts(k,m,B),U++,U===w&&es(o));break;case(u&&E):J=new Date(k.timestamp),xe=new Date(l),$e=new Date(d),J>=xe&&J<=$e&&U<R?U++:J>=xe&&J<=$e&&(ts(k,m,B),U++,U===w&&es(o));break;case c:k.level===_&&U<R?U++:k.level===_&&(ts(k,m,B),U++,U===w&&es(o));break;case u:J=new Date(k.timestamp),xe=new Date(l),J>=xe&&U<R?U++:J>=xe&&U>=R&&(ts(k,m,B),U++,U===w&&es(o));break;case E:J=new Date(k.timestamp),$e=new Date(d),J<=$e&&U<R?U++:J<=$e&&U>=R&&(ts(k,m,B),U++,U===w&&es(o));break;default:U<R?U++:(ts(k,m,B),U++,U===w&&es(o))}}),await gk(o,"close"),B}a(Lk,"readLog");function es(e){e.close(),e.removeAllListeners()}a(es,"endReadLine");function ts(e,t,r){t==="desc"?yk(e,r):t==="asc"?Dk(e,r):r.push(e)}a(ts,"pushLineToResult");function yk(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(yk,"insertDescending");function Dk(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(Dk,"insertAscending")});var mc=h((z3,nO)=>{"use strict";var IE=require("joi"),{string:Tc,boolean:rO,date:Mk}=IE.types(),Pk=de(),{validateSchemaExists:Z3,validateTableExists:X3,validateSchemaName:Bk}=Rr(),vk=T(),Hk=Se(),qk=V(),Gk=Tc.invalid(qk.get(vk.CONFIG_PARAMS.CLUSTERING_NODENAME)).pattern(Hk.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(),sO={operation:Tc.valid("add_node","update_node"),node_name:Gk,subscriptions:IE.array().items({table:Tc.required(),schema:Tc.custom(Bk).required(),subscribe:rO.required(),publish:rO.required().custom(Vk),start_time:Mk.iso()}).min(1).required()};function Fk(e){return Pk.validateBySchema(e,IE.object(sO))}a(Fk,"addUpdateNodeValidator");function Vk(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(Vk,"checkForFalsy");nO.exports={addUpdateNodeValidator:Fk,validation_schema:sO}});var Un=h((j3,iO)=>{"use strict";var Rc=class{constructor(t,r,s){this.name=t,this.subscriptions=r,this.system_info=s}};a(Rc,"Node");var Ac=class{constructor(t,r,s,n){this.schema=t,this.table=r,this.publish=s,this.subscribe=n}};a(Ac,"NodeSubscription");iO.exports={Node:Rc,NodeSubscription:Ac}});var oO=h((e2,aO)=>{"use strict";var kk=T().OPERATIONS_ENUM,pc=class{constructor(t,r,s,n=void 0){this.operation=kk.UPSERT,this.schema=t,this.table=r,this.records=s,this.__origin=n}};a(pc,"UpsertObject");aO.exports=pc});var vi=h((t2,cO)=>{"use strict";var Oc=class{constructor(t,r,s,n){this.operation=t,this.node_name=r,this.subscriptions=s,this.system_info=n}};a(Oc,"RemotePayloadObject");var Nc=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(Nc,"RemotePayloadSubscription");cO.exports={RemotePayloadObject:Oc,RemotePayloadSubscription:Nc}});var uO=h((r2,_O)=>{"use strict";var gc=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(gc,"TableSizeObject");_O.exports=gc});var hO=h((s2,dO)=>{"use strict";var xk=uO(),lO=require("path"),EO=re(),$k=Ke(),Ln=X(),Yk=g();dO.exports=Kk;async function Kk(e){let t=new xk;try{let r=lO.join(EO.getBaseSchemaPath(),e.schema.toString()),s=await Ln.openEnvironment(r,e.name),n=Ln.statDBI(s,e.hash_attribute),i=lO.join(EO.getTransactionAuditStorePath(),e.schema.toString()),o=await Ln.openEnvironment(i,e.name,!0),c=Ln.statDBI(o,$k.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP),_=await Ln.environmentDataSize(r,e.name),u=await Ln.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){Yk.warn(`unable to stat table dbi due to ${r}`)}return t}a(Kk,"lmdbGetTableSize")});var fO=h((n2,SO)=>{"use strict";var Qk=T(),Ic=class{constructor(t){this.operator=Qk.OPERATIONS_ENUM.SYSTEM_INFORMATION,this.attributes=t}};a(Ic,"SystemInformationOperation");SO.exports=Ic});var mO=h((i2,TO)=>{"use strict";var bc=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(bc,"SystemInformationObject");TO.exports=bc});var wc=h((o2,RO)=>{"use strict";var He=require("systeminformation"),yn=g(),Wk=T(),Jk=hO(),Zk=ms(),Xk=V();Xk.initSync();var a2=fO(),zk=mO(),Cc;RO.exports={getHDBProcessInfo:UE,getNetworkInfo:yE,getDiskInfo:LE,getMemoryInfo:wE,getCPUInfo:CE,getTimeInfo:bE,getSystemInformation:DE,systemInformation:jk,getTableSize:ME};function bE(){return He.time()}a(bE,"getTimeInfo");async function CE(){try{let{family:e,model:t,stepping:r,revision:s,voltage:n,speedmin:i,speedmax:o,governor:c,socket:_,cache:u,...l}=await He.cpu();l.cpu_speed=await He.cpuCurrentSpeed();let{raw_currentload:E,raw_currentload_idle:d,raw_currentload_irq:S,raw_currentload_nice:m,raw_currentload_system:R,raw_currentload_user:w,cpus:U,...B}=await He.currentLoad();return B.cpus=[],U.forEach(j=>{let{raw_load:k,raw_load_idle:J,raw_load_irq:xe,raw_load_nice:$e,raw_load_system:Ea,raw_load_user:da,...Pr}=j;B.cpus.push(Pr)}),l.current_load=B,l}catch(e){return yn.error(`error in getCPUInfo: ${e}`),{}}}a(CE,"getCPUInfo");async function wE(){try{let{buffers:e,cached:t,slab:r,buffcache:s,...n}=await He.mem();return n}catch(e){return yn.error(`error in getMemoryInfo: ${e}`),{}}}a(wE,"getMemoryInfo");async function UE(){let e={core:[],clustering:[]};try{return(await He.processes()).list.forEach(r=>{r.params.includes(Wk.HDB_PROC_NAME)?e.core.push(r):r.params.includes("socketcluster")&&e.clustering.push(r)}),e}catch(t){return yn.error(`error in getHDBProcessInfo: ${t}`),e}}a(UE,"getHDBProcessInfo");async function LE(){let e={};try{let{rIO_sec:t,wIO_sec:r,tIO_sec:s,ms:n,...i}=await He.disksIO();e.io=i;let{rx_sec:o,tx_sec:c,wx_sec:_,...u}=await He.fsStats();return e.read_write=u,e.size=await He.fsSize(),e}catch(t){return yn.error(`error in getDiskInfo: ${t}`),e}}a(LE,"getDiskInfo");async function yE(){let e={default_interface:null,latency:{},interfaces:[],stats:[],connections:[]};try{return e.default_interface=await He.networkInterfaceDefault(),e.latency=await He.inetChecksite("google.com"),(await He.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 He.networkStats()).forEach(s=>{let{rx_sec:n,tx_sec:i,ms:o,...c}=s;e.stats.push(c)}),e.connections=await He.networkConnections(),e}catch(t){return yn.error(`error in getNetworkInfo: ${t}`),e}}a(yE,"getNetworkInfo");async function DE(){if(Cc!==void 0)return Cc;let e={};try{let{codepage:t,logofile:r,serial:s,build:n,servicepack:i,uefi:o,...c}=await He.osInfo();e=c;let _=await He.versions("node, npm");return e.node_version=_.node,e.npm_version=_.npm,Cc=e,Cc}catch(t){return yn.error(`error in getSystemInformation: ${t}`),e}}a(DE,"getSystemInformation");async function ME(){let e=[],t=await Zk.describeAll();for(let r of Object.values(t))for(let s of Object.values(r))e.push(await Jk(s));return e}a(ME,"getTableSize");async function jk(e){let t=new zk;if(!Array.isArray(e.attributes)||e.attributes.length===0)return t.system=await DE(),t.time=bE(),t.cpu=await CE(),t.memory=await wE(),t.disk=await LE(),t.network=await yE(),t.harperdb_processes=await UE(),t.table_size=await ME(),t;for(let r=0;r<e.attributes.length;r++)switch(e.attributes[r]){case"system":t.system=await DE();break;case"time":t.time=bE();break;case"cpu":t.cpu=await CE();break;case"memory":t.memory=await wE();break;case"disk":t.disk=await LE();break;case"network":t.network=await yE();break;case"harperdb_processes":t.harperdb_processes=await UE();break;case"table_size":t.table_size=await ME();break;default:break}return t}a(jk,"systemInformation")});var PE=h((u2,AO)=>{"use strict";var c2=require("fs-extra"),_2=g();AO.exports={version:ex,printVersion:rx,nodeVersion:tx};var rs=Ql();function ex(){if(rs)return rs.version}a(ex,"version");function tx(){if(rs&&rs.engines&&rs.engines["preferred-node"])return rs.engines["preferred-node"]}a(tx,"nodeVersion");function rx(){rs&&console.log(`HarperDB Version ${rs.version}`)}a(rx,"printVersion")});var Ls=h((d2,gO)=>{"use strict";var sx=yt(),BE=b(),vE=require("util"),Us=T(),pO=V();pO.initSync();var nx=Kl(),OO=mt(),{Node:l2,NodeSubscription:E2}=Un(),ix=Ss(),ax=oO(),{RemotePayloadObject:ox,RemotePayloadSubscription:cx}=vi(),{handleHDBError:_x,hdb_errors:ux}=D(),{HTTP_STATUS_CODES:lx,HDB_ERROR_MSGS:Ex}=ux,dx=Qt(),hx=wc(),Sx=PE(),fx=vE.promisify(nx.authorize),Tx=vE.promisify(OO.searchByHash),mx=vE.promisify(OO.searchByValue);gO.exports={authHeaderToUser:Rx,isEmpty:Ax,getNodeRecord:px,upsertNodeRecord:Ox,buildNodePayloads:Nx,checkClusteringEnabled:gx,getAllNodeRecords:Ix,getSystemInfo:bx,reverseSubscription:NO};async function Rx(e){let t={headers:{authorization:e.hdb_auth_header}};return e.hdb_user=await fx(t,null),e}a(Rx,"authHeaderToUser");function Ax(e){return e==null}a(Ax,"isEmpty");async function px(e){let t=new ix(Us.SYSTEM_SCHEMA_NAME,Us.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[e],["*"]);return Tx(t)}a(px,"getNodeRecord");async function Ox(e){let t=new ax(Us.SYSTEM_SCHEMA_NAME,Us.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[e]);return sx.upsert(t)}a(Ox,"upsertNodeRecord");function NO(e){if(BE.isEmpty(e.subscribe)||BE.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(NO,"reverseSubscription");function Nx(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=BE.getTableHashAttribute(_,u),{subscribe:E,publish:d}=NO(c),S=new cx(_,u,l,d,E,c.start_time);n.push(S)}return new ox(r,t,n,s)}a(Nx,"buildNodePayloads");function gx(){if(!pO.get(Us.CONFIG_PARAMS.CLUSTERING_ENABLED))throw _x(new Error,Ex.CLUSTERING_NOT_ENABLED,lx.BAD_REQUEST,void 0,void 0,!0)}a(gx,"checkClusteringEnabled");async function Ix(){let e=new dx(Us.SYSTEM_SCHEMA_NAME,Us.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,"name","*",void 0,["*"]);return mx(e)}a(Ix,"getAllNodeRecords");async function bx(){let e=await hx.getSystemInformation();return{hdb_version:Sx.version(),node_version:e.node_version,platform:e.platform}}a(bx,"getSystemInfo")});var qE=h((h2,LO)=>{"use strict";var HE=At(),IO=b(),bO=Se(),Cx=T(),Uc=g(),CO=Ec(),wx=sl(),{RemotePayloadObject:Ux}=vi(),{handleHDBError:wO,hdb_errors:Lx}=D(),{HTTP_STATUS_CODES:UO}=Lx,{NodeSubscription:yx}=Un();LO.exports=Dx;async function Dx(e,t){let r;try{r=await HE.request(`${t}.${bO.REQUEST_SUFFIX}`,new Ux(Cx.OPERATIONS_ENUM.DESCRIBE_ALL,t,void 0,void 0)),Uc.trace("Response from remote describe all request:",r)}catch(o){Uc.error(`addNode received error from describe all request to remote node: ${o}`);let c=HE.requestErrorHandler(o,"add_node",t);throw wO(new Error,c,UO.INTERNAL_SERVER_ERROR,"error",c)}if(r.status===bO.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let o=`Error returned from remote node ${t}: ${r.message}`;throw wO(new Error,o,UO.INTERNAL_SERVER_ERROR,"error",o)}let s=r.message,n=[],i=[];for(let o of e){let{schema:c,table:_}=o,u=IO.doesSchemaExist(c),l=s[c]!==void 0,E=IO.doesTableExist(c,_),d=s?.[c]?.[_]!==void 0;if(!u&&!l||!E&&!d){n.push(o);continue}if(!u&&l&&(Uc.trace(`addNode creating schema: ${c}`),await CO.createSchema({operation:"create_schema",schema:c})),!E&&d){Uc.trace(`addNode creating table: ${_} in schema: ${c}`);let m=new wx(c,_,s[c][_].hash_attribute);await CO.createTable(m)}await HE.createLocalTableStream(c,_);let S=new yx(c,_,o.publish,o.subscribe);S.start_time=o.start_time,i.push(S)}return{added:i,skipped:n}}a(Dx,"reviewSubscriptions")});var Dc=h((S2,MO)=>{"use strict";var{handleHDBError:Lc,hdb_errors:Mx}=D(),{HTTP_STATUS_CODES:yc}=Mx,{addUpdateNodeValidator:Px}=mc(),Hi=g(),DO=T(),yO=Se(),Bx=b(),GE=At(),qi=Ls(),vx=V(),Hx=qE(),{Node:qx,NodeSubscription:Gx}=Un(),Fx="Unable to create subscriptions due to schema and/or tables not existing on the local or remote node",Vx="Some subscriptions were unsuccessful due to schema and/or tables not existing on the local or remote node",kx=vx.get(DO.CONFIG_PARAMS.CLUSTERING_NODENAME);MO.exports=xx;async function xx(e,t=!1){Hi.trace("addNode called with:",e),qi.checkClusteringEnabled();let r=Px(e);if(r)throw Lc(r,r.message,yc.BAD_REQUEST,void 0,void 0,!0);let s=e.node_name;if(!t){let E=await qi.getNodeRecord(s);if(!Bx.isEmptyOrZeroLength(E))throw Lc(new Error,`Node '${s}' has already been added, perform update_node to proceed.`,yc.BAD_REQUEST,void 0,void 0,!0)}let{added:n,skipped:i}=await Hx(e.subscriptions,s),o={message:void 0,added:n,skipped:i};if(n.length===0)return o.message=Fx,o;let c=qi.buildNodePayloads(n,kx,DO.OPERATIONS_ENUM.ADD_NODE,await qi.getSystemInfo());Hi.trace("addNode sending remote payload:",c);let _;try{_=await GE.request(`${s}.${yO.REQUEST_SUFFIX}`,c)}catch(E){Hi.error(`addNode received error from request: ${E}`);let d=GE.requestErrorHandler(E,"add_node",s);throw Lc(new Error,d,yc.INTERNAL_SERVER_ERROR,"error",d)}if(_.status===yO.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let E=`Error returned from remote node ${s}: ${_.message}`;throw Lc(new Error,E,yc.INTERNAL_SERVER_ERROR,"error",E)}Hi.trace(_);let u=[];for(let E=0,d=n.length;E<d;E++){let S=n[E];Hi.trace("Add node updating work stream for node:",s,"subscriptions:",S),await GE.updateWorkStream(S,s),n[E].start_time===void 0&&delete n[E].start_time,u.push(new Gx(S.schema,S.table,S.publish,S.subscribe))}let l=new qx(s,u,_.system_info);return await qi.upsertNodeRecord(l),i.length>0?o.message=Vx:o.message=`Successfully added '${s}' to manifest`,o}a(xx,"addNode")});var VE=h((f2,vO)=>{"use strict";var{handleHDBError:Mc,hdb_errors:$x}=D(),{HTTP_STATUS_CODES:Pc}=$x,{addUpdateNodeValidator:Yx}=mc(),Gi=g(),BO=T(),PO=Se(),Kx=b(),FE=At(),Fi=Ls(),Qx=V(),{cloneDeep:Wx}=require("lodash"),Jx=qE(),{NodeSubscription:Zx}=Un(),Xx="Unable to update subscriptions due to schema and/or tables not existing on the local or remote node",zx="Some subscriptions were unsuccessful due to schema and/or tables not existing on the local or remote node",jx=Qx.get(BO.CONFIG_PARAMS.CLUSTERING_NODENAME);vO.exports=e$;async function e$(e){Gi.trace("updateNode called with:",e),Fi.checkClusteringEnabled();let t=Yx(e);if(t)throw Mc(t,t.message,Pc.BAD_REQUEST,void 0,void 0,!0);let r=e.node_name,s=Wx(await Fi.getNodeRecord(r));if(Kx.isEmptyOrZeroLength(s))throw Mc(new Error,`Node '${r}' has not been added, perform add_node to proceed.`,Pc.BAD_REQUEST,void 0,void 0,!0);let{added:n,skipped:i}=await Jx(e.subscriptions,r),o={message:void 0,updated:n,skipped:i};if(n.length===0)return o.message=Xx,o;let c=Fi.buildNodePayloads(n,jx,BO.OPERATIONS_ENUM.UPDATE_NODE,await Fi.getSystemInfo());Gi.trace("updateNode sending remote payload:",c);let _;try{_=await FE.request(`${r}.${PO.REQUEST_SUFFIX}`,c)}catch(u){Gi.error(`updateNode received error from request: ${u}`);let l=FE.requestErrorHandler(u,"update_node",r);throw Mc(new Error,l,Pc.INTERNAL_SERVER_ERROR,"error",l)}if(_.status===PO.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let u=`Error returned from remote node ${r}: ${_.message}`;throw Mc(new Error,u,Pc.INTERNAL_SERVER_ERROR,"error",u)}Gi.trace(_);for(let u=0,l=n.length;u<l;u++){let E=n[u];Gi.trace(`updateNode updating work stream for node: ${r} subscription:`,E),await FE.updateWorkStream(E,r),n[u].start_time===void 0&&delete n[u].start_time}return await t$(s[0],n,_.system_info),i.length>0?o.message=zx:o.message=`Successfully updated '${r}'`,o}a(e$,"updateNode");async function t$(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 Zx(o.schema,o.table,o.publish,o.subscribe))}s.system_info=r,await Fi.upsertNodeRecord(s)}a(t$,"updateNodeTable")});var VO=h((T2,FO)=>{"use strict";var GO=require("joi"),{string:HO}=GO.types(),r$=de(),qO=T(),s$=V(),n$=Se();FO.exports=i$;function i$(e){let t=HO.invalid(s$.get(qO.CONFIG_PARAMS.CLUSTERING_NODENAME)).pattern(n$.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=GO.object({operation:HO.valid(qO.OPERATIONS_ENUM.REMOVE_NODE).required(),node_name:t});return r$.validateBySchema(e,r)}a(i$,"removeNodeValidator")});var vc=h((m2,QO)=>{"use strict";var{handleHDBError:kO,hdb_errors:a$}=D(),{HTTP_STATUS_CODES:xO}=a$,o$=VO(),Vi=g(),$O=Ls(),c$=b(),Bc=T(),YO=Se(),KO=At(),_$=V(),{RemotePayloadObject:u$}=vi(),{NodeSubscription:l$}=Un(),E$=Ei(),d$=ps(),h$=_$.get(Bc.CONFIG_PARAMS.CLUSTERING_NODENAME);QO.exports=S$;async function S$(e){Vi.trace("removeNode called with:",e),$O.checkClusteringEnabled();let t=o$(e);if(t)throw kO(t,t.message,xO.BAD_REQUEST,void 0,void 0,!0);let r=e.node_name,s=await $O.getNodeRecord(r);if(c$.isEmptyOrZeroLength(s))throw kO(new Error,`Node '${r}' was not found.`,xO.BAD_REQUEST,void 0,void 0,!0);s=s[0];let n=new u$(Bc.OPERATIONS_ENUM.REMOVE_NODE,h$,[]),i,o=!1;try{i=await KO.request(`${r}.${YO.REQUEST_SUFFIX}`,n),Vi.trace("Remove node reply from remote node:",r,i)}catch(_){Vi.error("removeNode received error from request:",_),o=!0}for(let _=0,u=s.subscriptions.length;_<u;_++){let l=s.subscriptions[_];Vi.trace(`Remove node removing subscription: ${l.schema}.${l.table} for node: ${r}`);let E=new l$(l.schema,l.table,!1,!1);await KO.updateWorkStream(E,r)}let c=new E$(Bc.SYSTEM_SCHEMA_NAME,Bc.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[r]);return await d$.deleteRecord(c),i?.status===YO.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR||o?(Vi.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(S$,"removeNode")});var ZO=h((R2,JO)=>{"use strict";var WO=require("joi"),{string:f$,array:T$}=WO.types(),m$=de(),R$=mc();JO.exports=A$;function A$(e){let t=WO.object({operation:f$.valid("configure_cluster").required(),connections:T$.items(R$.validation_schema).required()});return m$.validateBySchema(e,t)}a(A$,"configureClusterValidator")});var kE=h((A2,tN)=>{"use strict";var p$=T(),Hc=g(),O$=b(),N$=vc(),g$=Dc(),XO=Ls(),I$=ZO(),{handleHDBError:zO,hdb_errors:b$}=D(),{HTTP_STATUS_CODES:jO}=b$,C$="Configure cluster complete.",w$="Failed to configure the cluster. Check the logs for more details.",U$="Configure cluster was partially successful. Errors occurred when attempting to configure the following nodes. Check the logs for more details.";tN.exports=L$;async function L$(e){Hc.trace("configure cluster called with:",e),XO.checkClusteringEnabled();let t=I$(e);if(t)throw zO(t,t.message,jO.BAD_REQUEST,void 0,void 0,!0);let r=await XO.getAllNodeRecords(),s=[];for(let d=0,S=r.length;d<S;d++)s.push(eN(N$,{operation:p$.OPERATIONS_ENUM.REMOVE_NODE,node_name:r[d].name},r[d].name));let n=await Promise.allSettled(s);Hc.trace("All results from configure_cluster remove node:",n);let i=[],o=e.connections.length;for(let d=0;d<o;d++){let S=e.connections[d];i.push(eN(g$,S,S.node_name))}let c=await Promise.allSettled(i);Hc.trace("All results from configure_cluster add node:",c);let _=[],u=[],l=!1,E=n.concat(c);for(let d=0,S=E.length;d<S;d++){let m=E[d];m.status==="rejected"&&(Hc.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(O$.isEmptyOrZeroLength(_))return{message:C$,connections:u};if(l)return{message:U$,failed_nodes:_,connections:u};throw zO(new Error,w$,jO.INTERNAL_SERVER_ERROR,void 0,void 0,!0)}a(L$,"configureCluster");async function eN(e,t,r){try{return{node_name:r,result:await e(t)}}catch(s){throw{node_name:r,error:s}}}a(eN,"functionWrapper")});var YE=h((p2,oN)=>{"use strict";var $E=Ls(),y$=At(),nN=V(),qc=T(),ys=Se(),D$=b(),xE=g(),{RemotePayloadObject:M$}=vi(),{ErrorCode:rN}=require("nats"),sN=nN.get(qc.CONFIG_PARAMS.CLUSTERING_ENABLED),iN=nN.get(qc.CONFIG_PARAMS.CLUSTERING_NODENAME);oN.exports={clusterStatus:P$,buildNodeStatus:aN};async function P$(){let e={node_name:iN,is_enabled:sN,connections:[]};if(!sN)return e;let t=await $E.getAllNodeRecords();if(D$.isEmptyOrZeroLength(t))return e;let r=[];for(let s=0,n=t.length;s<n;s++)r.push(aN(t[s],e.connections));return await Promise.allSettled(r),e}a(P$,"clusterStatus");async function aN(e,t){let r=e.name,s=new M$(qc.OPERATIONS_ENUM.CLUSTER_STATUS,iN,void 0,await $E.getSystemInfo()),n,i,o=ys.CLUSTER_STATUS_STATUSES.OPEN;try{let _=Date.now();n=await y$.request(ys.REQUEST_SUBJECT(r),s),i=Date.now()-_,n.status===ys.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR&&(o=ys.CLUSTER_STATUS_STATUSES.CLOSED,xE.error(`Error getting node status from ${r} `,n))}catch(_){xE.warn(`Error getting node status from ${r}`,_),_.code===rN.NoResponders?o=ys.CLUSTER_STATUS_STATUSES.NO_RESPONDERS:_.code===rN.Timeout?o=ys.CLUSTER_STATUS_STATUSES.TIMEOUT:o=ys.CLUSTER_STATUS_STATUSES.CLOSED}let c=new B$(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!==qc.PRE_4_0_0_VERSION&&await $E.upsertNodeRecord(_)}catch(_){xE.error("Cluster status encountered an error updating system info for node:",r,_)}t.push(c)}a(aN,"buildNodeStatus");function B$(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(B$,"NodeStatusObject")});var lN=h((O2,uN)=>{"use strict";var KE=require("joi"),cN=de(),{route_constraints:_N}=Eu();uN.exports={setRoutesValidator:v$,deleteRoutesValidator:H$};function v$(e){let t=KE.object({server:KE.valid("hub","leaf").required(),routes:_N.required()});return cN.validateBySchema(e,t)}a(v$,"setRoutesValidator");function H$(e){let t=KE.object({routes:_N.required()});return cN.validateBySchema(e,t)}a(H$,"deleteRoutesValidator")});var WE=h((N2,SN)=>{"use strict";var Ds=Tr(),QE=b(),Gc=T(),EN=lN(),{handleHDBError:dN,hdb_errors:q$}=D(),{HTTP_STATUS_CODES:hN}=q$,G$="cluster routes successfully set",F$="cluster routes successfully deleted";SN.exports={setRoutes:V$,getRoutes:k$,deleteRoutes:x$};function V$(e){let t=EN.setRoutesValidator(e);if(t)throw dN(t,t.message,hN.BAD_REQUEST,void 0,void 0,!0);let r=Ds.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=QE.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"?Ds.updateConfigValue(Gc.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,s):Ds.updateConfigValue(Gc.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,s),{message:G$,set:o,skipped:i}}a(V$,"setRoutes");function k$(){let e=Ds.getClusteringRoutes();return{hub:e.hub_routes,leaf:e.leaf_routes}}a(k$,"getRoutes");function x$(e){let t=EN.deleteRoutesValidator(e);if(t)throw dN(t,t.message,hN.BAD_REQUEST,void 0,void 0,!0);let r=Ds.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 S=0,m=s.length;S<m;S++){let R=s[S];if(E.host===R.host&&E.port===R.port){s.splice(S,1),d=!0,c=!0,i.push(E);break}}if(!d){let S=!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,S=!1,i.push(E);break}}S&&o.push(E)}}return c&&(s=QE.isEmptyOrZeroLength(s)?null:s,Ds.updateConfigValue(Gc.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,s)),_&&(n=QE.isEmptyOrZeroLength(n)?null:n,Ds.updateConfigValue(Gc.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,n)),{message:F$,deleted:i,skipped:o}}a(x$,"deleteRoutes")});var TN=h((g2,fN)=>{"use strict";var ki=require("alasql"),Ms=require("recursive-iterator"),Jt=g(),$$=b(),xi=T(),Fc=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,K$(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=>xi.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=>!xi.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][xi.PERMS_CRUD_ENUM.READ]){let c;t[i].tables[o].attribute_permissions.length>0?c=Y$(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=>!xi.SEARCH_WILDCARDS.includes(u));c.forEach(({attribute_name:u})=>{let l=new ki.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(Fc,"sql_statement_bucket");function Y$(e){return e.filter(t=>t[xi.PERMS_CRUD_ENUM.READ])}a(Y$,"filterReadRestrictedAttrs");function K$(e,t,r,s,n){Q$(e,t,r,s,n)}a(K$,"interpretAST");function $i(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($i,"addSchemaTableToMap");function Q$(e,t,r,s,n){if(!e){Jt.info("getRecordAttributesAST: invalid SQL syntax tree");return}e instanceof ki.yy.Insert?X$(e,t,r):e instanceof ki.yy.Select?W$(e,t,r,s,n):e instanceof ki.yy.Update?J$(e,t,r):e instanceof ki.yy.Delete?Z$(e,t,r):Jt.error("AST in getRecordAttributesAST() is not a valid SQL type.")}a(Q$,"getRecordAttributesAST");function W$(e,t,r,s,n){if(!e){Jt.info("getSelectAttributes: invalid SQL syntax tree");return}if(!e.from||e.from[0]===void 0)return;let i=e.from[0].databaseid;if($$.isEmptyOrZeroLength(i)){Jt.error("No schema specified");return}e.from.forEach(c=>{$i(c,t,r,s,n)}),e.joins&&e.joins.forEach(c=>{c.as&&(c.table.as=c.as),$i(c.table,t,r,s,n)});let o=new Ms(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{Jt.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 Ms(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{Jt.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 Ms(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{Jt.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 Ms(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{Jt.info(`table specified as ${u} not found.`);return}t.get(l).get(u).indexOf(_.columnid)<0&&t.get(l).get(u).push(_.columnid)}}}a(W$,"getSelectAttributes");function J$(e,t,r){if(!e){Jt.info("getUpdateAttributes: invalid SQL syntax tree");return}let s=new Ms(e.columns),n=e.table.databaseid;$i(e.table,t,r);for(let{node:i}of s)i&&i.columnid&&JE(e.table.tableid,n,i.columnid,t,r)}a(J$,"getUpdateAttributes");function Z$(e,t,r){if(!e){Jt.info("getDeleteAttributes: invalid SQL syntax tree");return}let s=new Ms(e.where),n=e.table.databaseid;$i(e.table,t,r);for(let{node:i}of s)i&&i.columnid&&JE(e.table.tableid,n,i.columnid,t,r)}a(Z$,"getDeleteAttributes");function X$(e,t,r){if(!e){Jt.info("getInsertAttributes: invalid SQL syntax tree");return}let s=new Ms(e.columns),n=e.into.databaseid;$i(e.into,t,r);for(let{node:i}of s)i&&i.columnid&&JE(e.into.tableid,n,i.columnid,t,r)}a(X$,"getInsertAttributes");function JE(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(JE,"pushAttribute");fN.exports=Fc});var AN=h((I2,RN)=>{var z$=require("os"),mN=V();RN.exports={checkPermission:j$};function j$(){if(z$.userInfo().username!==mN.get("install_user"))throw new Error(`Error: Must execute as ${mN.get("install_user")}`)}a(j$,"checkPermission")});var XE=h((b2,IN)=>{var kc=pi(),pN=require("chalk"),ar=g(),ON=AN(),NN=require("prompt"),{promisify:eY}=require("util"),Vc=T(),tY=require("fs-extra"),rY=require("path"),sY=b(),nY=PE(),gN=V();gN.initSync();var iY=require("moment"),aY=eY(NN.get),oY=rY.join(gN.getHdbBasePath(),Vc.LICENSE_KEY_DIR_NAME,Vc.LICENSE_FILE_NAME,Vc.LICENSE_FILE_NAME);IN.exports={getFingerprint:_Y,setLicense:cY,parseLicense:ZE,register:uY,getRegistrationInfo:EY};async function cY(e){if(e&&e.key&&e.company){try{ar.info(`parsing license key: ${e.key} and `);let t=e.company.toString();await ZE(e.key.trim(),t.trim())}catch(t){let r="There was an error parsing the license key.";throw ar.error(r),ar.error(t),new Error(r)}return"Wrote license key file. Registration successful."}throw new Error("Invalid key or company specified for license file.")}a(cY,"setLicense");async function _Y(){try{ON.checkPermission()}catch(t){throw ar.error(t),new Error("You do not have permission to generate a fingerprint.")}let e={};try{e=await kc.generateFingerPrint()}catch(t){let r="Error generating fingerprint.";throw ar.error(r),ar.error(t),new Error(r)}return e}a(_Y,"getFingerprint");async function ZE(e,t){if(!e||!t)throw new Error("Invalid entries for License Key and Customer Company");console.log("Validating license input...");let r=kc.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{ar.info("writing license to disk"),await tY.writeFile(oY,JSON.stringify({license_key:e,company:t}))}catch(s){throw ar.error("Failed to write License"),s}return"Registration successful."}a(ZE,"parseLicense");async function uY(){let e=await lY();return ZE(e.HDB_LICENSE,e.CUSTOMER_COMPANY)}a(uY,"register");async function lY(){try{ON.checkPermission()}catch(s){return console.error(s.message)}let e=await kc.generateFingerPrint(),t={properties:{CUSTOMER_COMPANY:{description:pN.magenta("[COMPANY] Please enter your company name"),required:!0},HDB_LICENSE:{description:pN.magenta(`[HDB_LICENSE] Your fingerprint is ${e} Please enter your license key`),required:!0}}};try{NN.start()}catch(s){ar.error(s)}let r;try{r=await aY(t)}catch(s){throw console.error("There was a problem prompting for registration input. Exiting."),s}return r}a(lY,"promptForRegistration");async function EY(){let e={registered:!1,version:null,storage_type:null,ram_allocation:null,license_expiration_date:null},t;try{t=await kc.getLicense()}catch(r){throw ar.error(`There was an error when searching licenses due to: ${r.message}`),r}if(sY.isEmptyOrZeroLength(t))throw new Error("There were no licenses found.");if(e.registered=t.enterprise,e.version=nY.version(),e.storage_type=Vc.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=iY.utc(t.exp_date).format("YYYY-MM-DD");e.license_expiration_date=t.enterprise?r:null}return e}a(EY,"getRegistrationInfo")});var CN=h((C2,bN)=>{"use strict";var dY=Se(),xc=class{constructor(t,r,s,n,i,o,c,_,u,l,E,d,S){this.port=t,this.server_name=r+dY.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:S}},this.system_account="SYS"}};a(xc,"HubConfigObject");bN.exports=xc});var LN=h((w2,UN)=>{"use strict";var wN=Se(),$c=class{constructor(t,r,s,n,i,o,c,_,u,l,E,d){this.port=t,this.server_name=r+wN.SERVER_SUFFIX.LEAF,this.pid_file=s,this.max_payload=1e7,this.jetstream={enabled:!0,store_dir:n,domain:r+wN.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($c,"LeafConfigObject");UN.exports=$c});var DN=h((U2,yN)=>{"use strict";var Yc=class{constructor(t,r){this.user=t,this.password=r}};a(Yc,"HdbUserObject");yN.exports=Yc});var PN=h((L2,MN)=>{"use strict";var hY=Se(),Kc=class{constructor(t,r){this.user=t+hY.SERVER_SUFFIX.ADMIN,this.password=r}};a(Kc,"SysUserObject");MN.exports=Kc});var ed=h((y2,HN)=>{"use strict";var Dn=require("path"),Zc=require("fs-extra"),SY=CN(),fY=LN(),TY=DN(),mY=PN(),zE=gr(),Pn=b(),Pt=Tr(),Jc=T(),Qc=Se(),{CONFIG_PARAMS:we}=Jc,Xc=g(),zc=V(),BN=$r(),jE=At(),Mn="clustering",RY=1e4,vN=5;HN.exports={generateNatsConfig:AY,removeNatsConfig:pY};async function AY(e=!1,t=void 0){zc.initSync();let r=zc.get(we.ROOTPATH),s=Dn.join(r,Mn,Qc.PID_FILES.HUB),n=Dn.join(r,Mn,Qc.PID_FILES.LEAF),i=Dn.join(r,Mn,"leaf"),o=Dn.join(r,Mn,Qc.NATS_CONFIG_FILES.HUB_SERVER),c=Dn.join(r,Mn,Qc.NATS_CONFIG_FILES.LEAF_SERVER),_=Pt.getConfigFromFile(we.CLUSTERING_TLS_CERTIFICATE),u=Pt.getConfigFromFile(we.CLUSTERING_TLS_PRIVATEKEY),l=Pt.getConfigFromFile(we.CLUSTERING_TLS_CERT_AUTH),E=Pt.getConfigFromFile(we.CLUSTERING_TLS_INSECURE),d=Pt.getConfigFromFile(we.CLUSTERING_NODENAME),S=Pt.getConfigFromFile(we.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT);await jE.checkNATSServerInstalled()||jc("nats-server dependency is either missing or the wrong version. Run 'npm install' to fix");let m=await zE.listUsers(),R=Pt.getConfigFromFile(we.CLUSTERING_USER),w=await zE.getClusterUser();(Pn.isEmpty(w)||w.active!==!0)&&jc(`invalid cluster user '${R}'`),e||(await Wc(we.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),await Wc(we.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT),await Wc(we.CLUSTERING_HUBSERVER_NETWORK_PORT),await Wc(we.CLUSTERING_LEAFSERVER_NETWORK_PORT));let U=[],B=[];for(let[da,Pr]of m.entries())Pr.role.role===Jc.ROLE_TYPES_ENUM.CLUSTER_USER&&Pr.active&&(U.push(new mY(Pr.username,BN.decrypt(Pr.hash))),B.push(new TY(Pr.username,BN.decrypt(Pr.hash))));let j=[],{hub_routes:k}=Pt.getClusteringRoutes();if(!Pn.isEmptyOrZeroLength(k))for(let da of k)j.push(`tls://${w.sys_name_encoded}:${w.uri_encoded_d_hash}@${da.host}:${da.port}`);let J=new SY(Pt.getConfigFromFile(we.CLUSTERING_HUBSERVER_NETWORK_PORT),d,s,_,u,l,E,S,Pt.getConfigFromFile(we.CLUSTERING_HUBSERVER_CLUSTER_NAME),Pt.getConfigFromFile(we.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),j,U,B);t=Pn.isEmpty(t)?void 0:t.toLowerCase(),(t===void 0||t===Jc.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase())&&(await Zc.writeJson(o,J),Xc.trace(`Hub server config written to ${o}`));let xe=`tls://${w.sys_name_encoded}:${w.uri_encoded_d_hash}@0.0.0.0:${S}`,$e=`tls://${w.uri_encoded_name}:${w.uri_encoded_d_hash}@0.0.0.0:${S}`,Ea=new fY(Pt.getConfigFromFile(we.CLUSTERING_LEAFSERVER_NETWORK_PORT),d,n,i,[xe],[$e],U,B,_,u,l,E);(t===void 0||t===Jc.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())&&(await Zc.writeJson(c,Ea),Xc.trace(`Leaf server config written to ${c}`))}a(AY,"generateNatsConfig");async function Wc(e){let t=zc.get(e);Pn.isEmpty(t)&&jc(`port undefined for '${e}'`),await Pn.isPortTaken(t)&&jc(`'${e}' port '${t}' is unavailable`)}a(Wc,"isPortAvailable");function jc(e){let t=`Error generating clustering config: ${e}`;Xc.error(t),console.error(t),process.exit(1)}a(jc,"generateNatsConfigError");async function pY(e){let{port:t,config_file:r}=jE.getServerConfig(e),{username:s,decrypt_hash:n}=await zE.getClusterUser(),i=0,o=500;for(;i<vN;){try{let u=await jE.createConnection(t,s,n,!1);if(u.protocol.connected===!0){u.close();break}}catch(u){Xc.trace(`removeNatsConfig waiting for ${e}. Caught and swallowed error ${u}`)}if(i++,i>=vN)throw new Error(`removeNatsConfig timed out waiting to connect to ${e}`);await Pn.async_set_timeout(o*i)}let c="0".repeat(RY),_=Dn.join(zc.get(we.ROOTPATH),Mn,r);await Zc.writeFile(_,c),await Zc.remove(_)}a(pY,"removeNatsConfig")});var t_=h((D2,$N)=>{"use strict";var ie=V(),qN=pi(),C=T(),td=Se(),pe=require("path"),{PACKAGE_ROOT:e_}=T(),Ee="/dev/null",Bn=pe.join(e_,"launchServiceScripts"),GN=pe.join(e_,"utility/scripts"),OY=pe.join(GN,C.HDB_RESTART_SCRIPT),FN=pe.resolve(e_,"dependencies",`${process.platform}-${process.arch}`,td.NATS_BINARY_NAME),qe,Ge;function or(){(qe===void 0||Ge===void 0)&&(ie.initSync(),qe=ie.get(C.HDB_SETTINGS_NAMES.LOG_TO_FILE),Ge=ie.get(C.HDB_SETTINGS_NAMES.LOG_PATH_KEY))}a(or,"initLogConfig");function VN(){or();let e=pe.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 qe||(t.out_file=Ee,t.error_file=Ee),{...t,script:C.SERVICE_SERVERS.IPC}}a(VN,"generateIPCServerConfig");function kN(){or(),ie.initSync(),qe=ie.get(C.HDB_SETTINGS_NAMES.LOG_TO_FILE),Ge=ie.get(C.HDB_SETTINGS_NAMES.LOG_PATH_KEY);let e=pe.join(Ge,C.PROCESS_LOG_NAMES.HDB),t=qN.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:ie.get(C.CONFIG_PARAMS.HTTP_THREADS),node_args:r,cwd:Bn};return qe||(s.out_file=Ee,s.error_file=Ee),s}a(kN,"generateHDBServerConfig");function xN(){or(),ie.initSync(),qe=ie.get(C.HDB_SETTINGS_NAMES.LOG_TO_FILE),Ge=ie.get(C.HDB_SETTINGS_NAMES.LOG_PATH_KEY);let e=pe.join(Ge,C.PROCESS_LOG_NAMES.CUSTOM_FUNCTIONS),t=qN.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:ie.get(C.CONFIG_PARAMS.HTTP_THREADS),node_args:r,cwd:Bn};return qe||(s.out_file=Ee,s.error_file=Ee),s}a(xN,"generateCFServerConfig");function NY(){or(),ie.initSync(),qe=ie.get(C.HDB_SETTINGS_NAMES.LOG_TO_FILE),Ge=ie.get(C.HDB_SETTINGS_NAMES.LOG_PATH_KEY);let e=ie.get(C.CONFIG_PARAMS.ROOTPATH),t=pe.join(e,"clustering",td.NATS_CONFIG_FILES.HUB_SERVER),r=pe.join(Ge,C.PROCESS_LOG_NAMES.CLUSTERING_HUB),s={name:C.PROCESS_DESCRIPTORS.CLUSTERING_HUB,script:FN,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 qe||(s.out_file=Ee,s.error_file=Ee),s}a(NY,"generateNatsHubServerConfig");function gY(){or(),ie.initSync(),qe=ie.get(C.HDB_SETTINGS_NAMES.LOG_TO_FILE),Ge=ie.get(C.HDB_SETTINGS_NAMES.LOG_PATH_KEY);let e=ie.get(C.CONFIG_PARAMS.ROOTPATH),t=pe.join(e,"clustering",td.NATS_CONFIG_FILES.LEAF_SERVER),r=pe.join(Ge,C.PROCESS_LOG_NAMES.CLUSTERING_LEAF),s={name:C.PROCESS_DESCRIPTORS.CLUSTERING_LEAF,script:FN,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 qe||(s.out_file=Ee,s.error_file=Ee),s}a(gY,"generateNatsLeafServerConfig");function IY(){or(),ie.initSync();let e=pe.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:Bn};return qe||(t.out_file=Ee,t.error_file=Ee),t}a(IY,"generateNatsIngestServiceConfig");function bY(){or(),ie.initSync();let e=pe.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:Bn};return qe||(t.out_file=Ee,t.error_file=Ee),t}a(bY,"generateNatsReplyServiceConfig");function CY(){or(),ie.initSync();let e=pe.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:Bn,autorestart:!1};return qe||(t.out_file=Ee,t.error_file=Ee),t}a(CY,"generateClusteringUpgradeV4ServiceConfig");function wY(){or();let e=pe.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:GN};return qe||(t.out_file=Ee,t.error_file=Ee),{...t,script:OY}}a(wY,"generateRestart");function UY(e){or();let t=pe.join(Ge,C.PROCESS_LOG_NAMES.JOBS),r=pe.join(e_,"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:Bn,autorestart:!1};return qe||(s.out_file=Ee,s.error_file=Ee),{...s,script:pe.join(r,"jobProcess.js")}}a(UY,"generateJobConfig");function LY(){return{apps:[VN(),kN(),xN()]}}a(LY,"generateAllServiceConfigs");$N.exports={generateAllServiceConfigs:LY,generateIPCServerConfig:VN,generateHDBServerConfig:kN,generateCFServerConfig:xN,generateRestart:wY,generateNatsHubServerConfig:NY,generateNatsLeafServerConfig:gY,generateNatsIngestServiceConfig:IY,generateNatsReplyServiceConfig:bY,generateClusteringUpgradeV4ServiceConfig:CY,generateJobConfig:UY}});var Ki=h((M2,tg)=>{"use strict";var P=T(),r_=b(),Yi=ed(),s_=At(),yY=Se(),$=require("pm2"),DY=require("fs-extra"),wr=t_(),lt=V(),Ur=g(),MY=t_(),PY=Ls(),BY=require("util"),KN=BY.promisify(require("child_process").exec),QN=require("path");tg.exports={start:Ps,stop:i_,reload:JN,restart:ZN,list:sd,describe:a_,connect:cr,kill:zN,startAllServices:YY,startService:n_,getUniqueServicesList:nd,restartAllServices:KY,stopAllServices:QY,isServiceRegistered:jN,reloadStopStart:rd,restartHdb:XN,deleteProcess:xY,configureLogRotate:ZY,startClustering:eg,isHdbRestartRunning:$Y,isClusteringRunning:zY,stopClustering:XY,reloadClustering:jY};var{PACKAGE_ROOT:vY}=T(),HY="2.7.0",WN=QN.join(vY,"node_modules/pm2/bin/pm2"),qY="Log rotate installed.",GY="Error installing log rotate.",FY="Log rotate updated.",VY="Error updating log rotate.",kY="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 cr(){return new Promise((e,t)=>{$.connect((r,s)=>{r&&t(r),e(s)})})}a(cr,"connect");function Ps(e){return new Promise(async(t,r)=>{try{await cr()}catch(s){r(s)}$.start(e,(s,n)=>{s&&($.disconnect(),r(s)),$.disconnect(),t(n)})})}a(Ps,"start");function i_(e){return new Promise(async(t,r)=>{try{await cr()}catch(s){r(s)}$.stop(e,(s,n)=>{s&&($.disconnect(),r(s)),$.delete(e,(i,o)=>{i&&($.disconnect(),r(s)),$.disconnect(),t(o)})})})}a(i_,"stop");function JN(e){return new Promise(async(t,r)=>{try{await cr()}catch(s){r(s)}$.reload(e,(s,n)=>{s&&($.disconnect(),r(s)),$.disconnect(),t(n)})})}a(JN,"reload");function ZN(e){return new Promise(async(t,r)=>{try{await cr()}catch(s){r(s)}$.restart(e,(s,n)=>{s&&($.disconnect(),r(s)),$.disconnect(),t(n)})})}a(ZN,"restart");function xY(e){return new Promise(async(t,r)=>{try{await cr()}catch(s){r(s)}$.delete(e,(s,n)=>{s&&($.disconnect(),r(s)),$.disconnect(),t(n)})})}a(xY,"deleteProcess");async function XN(){await Ps(MY.generateRestart())}a(XN,"restartHdb");async function $Y(){let e=await sd();for(let t in e)if(e[t].name===P.PROCESS_DESCRIPTORS.RESTART_HDB)return!0;return!1}a($Y,"isHdbRestartRunning");function sd(){return new Promise(async(e,t)=>{try{await cr()}catch(r){t(r)}$.list((r,s)=>{r&&($.disconnect(),t(r)),$.disconnect(),e(s)})})}a(sd,"list");function a_(e){return new Promise(async(t,r)=>{try{await cr()}catch(s){r(s)}$.describe(e,(s,n)=>{s&&($.disconnect(),r(s)),$.disconnect(),t(n)})})}a(a_,"describe");function zN(){return new Promise(async(e,t)=>{try{await cr()}catch(r){t(r)}$.killDaemon((r,s)=>{r&&($.disconnect(),t(r)),$.disconnect(),e(s)})})}a(zN,"kill");async function YY(){try{await eg(),await Ps(wr.generateAllServiceConfigs())}catch(e){throw $.disconnect(),e}}a(YY,"startAllServices");async function n_(e){try{let t;switch(e=e.toLowerCase(),e){case P.PROCESS_DESCRIPTORS.IPC.toLowerCase():t=wr.generateIPCServerConfig();break;case P.PROCESS_DESCRIPTORS.HDB.toLowerCase():t=wr.generateHDBServerConfig();break;case P.PROCESS_DESCRIPTORS.CUSTOM_FUNCTIONS.toLowerCase():t=wr.generateCFServerConfig();break;case P.PROCESS_DESCRIPTORS.CLUSTERING_INGEST_SERVICE.toLowerCase():t=wr.generateNatsIngestServiceConfig();break;case P.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE.toLowerCase():t=wr.generateNatsReplyServiceConfig();break;case P.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase():t=wr.generateNatsHubServerConfig(),await Ps(t),await Yi.removeNatsConfig(e);return;case P.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase():t=wr.generateNatsLeafServerConfig(),await Ps(t),await Yi.removeNatsConfig(e);return;case P.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0.toLowerCase():t=wr.generateClusteringUpgradeV4ServiceConfig();break;default:throw new Error(`Start service called with unknown service config: ${e}`)}await Ps(t)}catch(t){throw $.disconnect(),t}}a(n_,"startService");async function nd(){try{let e=await sd(),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(nd,"getUniqueServicesList");async function KY(e=[]){try{let t=!1,r=await nd();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 rd(o):await ZN(o))}t&&await rd(P.PROCESS_DESCRIPTORS.HDB)}catch(t){throw $.disconnect(),t}}a(KY,"restartAllServices");async function QY(){try{let e=await nd();for(let t=0,r=Object.values(e).length;t<r;t++){let s=Object.values(e)[t];await i_(s.name)}if(await zN(),lt.get(P.CONFIG_PARAMS.OPERATIONSAPI_FOREGROUND)===!0){let t=(await DY.readFile(QN.join(lt.get(P.HDB_SETTINGS_NAMES.HDB_ROOT_KEY),P.FOREGROUND_PID_FILE))).toString();try{process.kill(t,"SIGTERM")}catch(r){Ur.warn(`Error terminating foreground process: ${r}`)}}}catch(e){throw $.disconnect(),e}}a(QY,"stopAllServices");async function jN(e){return!r_.isEmptyOrZeroLength(await a_(e))}a(jN,"isServiceRegistered");async function rd(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 a_(e),s=r_.isEmptyOrZeroLength(r)?0:r.length;t!==s?e===P.PROCESS_DESCRIPTORS.HDB?Ur.error(kY):(await i_(e),await n_(e)):e===P.PROCESS_DESCRIPTORS.HDB?await XN():await JN(e)}a(rd,"reloadStopStart");function WY(){return new Promise(async(e,t)=>{try{await cr()}catch(r){t(r)}$.stop(P.PROCESS_DESCRIPTORS.PM2_LOGROTATE,(r,s)=>{r&&($.disconnect(),t(r)),$.disconnect(),e(s)})})}a(WY,"stopLogrotate");async function JY(){let{stdout:e,stderr:t}=await KN(`${process.platform==="win32"?"node":""} ${WN} install pm2-logrotate@${HY}`);if(Ur.debug(`loadLogRotate stdout: ${e}`),t)throw Ur.error(GY),t;Ur.info(qY)}a(JY,"installLogRotate");async function YN(){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":""} ${WN} set pm2-logrotate:${n} ${e[n]}`,n!=="TZ"&&(t+=" && ");let{stdout:r,stderr:s}=await KN(t);if(Ur.debug(`updateLogRotateConfig stdout: ${r}`),s)throw Ur.error(VY),s;Ur.info(FY)}a(YN,"updateLogRotateConfig");async function ZY(){lt.initSync();let e=r_.autoCastBoolean(lt.get(P.HDB_SETTINGS_NAMES.LOG_ROTATE)),t=await a_(P.PROCESS_DESCRIPTORS.PM2_LOGROTATE),r,s=!1;if(r_.isEmptyOrZeroLength(t)||(s=!0,r=t[0].pm2_env.status),e&&!s){await JY(),await YN();return}if(e&&s){await Ps(P.PROCESS_DESCRIPTORS.PM2_LOGROTATE),await YN();return}!e&&r===P.PM2_PROCESS_STATUSES.ONLINE&&await WY()}a(ZY,"configureLogRotate");async function eg(){for(let t in P.CLUSTERING_PROCESSES){let r=P.CLUSTERING_PROCESSES[t];await n_(r)}await s_.createWorkQueueStream(yY.WORK_QUEUE_CONSUMER_NAMES),await s_.updateNodeNameLocalStreams();let e=await PY.getAllNodeRecords();for(let t=0,r=e.length;t<r;t++)if(e[t].system_info?.hdb_version===P.PRE_4_0_0_VERSION){Ur.info("Starting clustering upgrade 4.0.0 process"),await n_(P.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0);break}}a(eg,"startClustering");async function XY(){for(let e in P.CLUSTERING_PROCESSES){let t=P.CLUSTERING_PROCESSES[e];await i_(t)}}a(XY,"stopClustering");async function zY(){for(let e in P.CLUSTERING_PROCESSES){let t=P.CLUSTERING_PROCESSES[e];if(await jN(t)===!1)return!1}return!0}a(zY,"isClusteringRunning");async function jY(){await Yi.generateNatsConfig(!0),await s_.reloadNATSHub(),await s_.reloadNATSLeaf(),await Yi.removeNatsConfig(P.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase()),await Yi.removeNatsConfig(P.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())}a(jY,"reloadClustering")});var _d=h((P2,ag)=>{"use strict";var y=T(),K=g(),o_=b(),eK=su(),id=ed(),cd=At(),tK=Se(),sg=require("minimist"),{handleHDBError:ad,hdb_errors:rK}=D(),Qi=Tr(),{HTTP_STATUS_CODES:od}=rK,G,rg=`Restarting HarperDB. This may take up to ${y.RESTART_TIMEOUT_MS/1e3} seconds.`,Bs="HarperDB is currently restarting and must complete before another HarperDB restart can be initialized.",sK="Invalid service",nK="'service' is required",iK="Restarting all services",aK="Clustering is not enabled so cannot be restarted";ag.exports={stop:cK,restartProcesses:oK,restartService:ng};async function oK(){K.createLogFile(y.PROCESS_LOG_NAMES.CLI,y.PROCESS_DESCRIPTORS.STOP);try{G===void 0&&(G=Ki());let e=eK(Object.keys(y.CONFIG_PARAM_MAP),!0);o_.isEmptyOrZeroLength(Object.keys(e))||Qi.updateConfigValue(void 0,void 0,e,!0,!0);let t=Qi.getConfigFromFile(y.CONFIG_PARAMS.CLUSTERING_ENABLED),r=Qi.getConfigFromFile(y.CONFIG_PARAMS.CUSTOMFUNCTIONS_ENABLED),s=sg(process.argv);if(!o_.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(Bs),console.error(Bs);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 vn(_);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 ng({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(Bs),console.error(Bs),Bs;console.log(rg),t&&await ig();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(iK),await G.restartAllServices(i),rg}catch(e){let t=`There was an error restarting HarperDB. ${e}`;return K.error(t),t}}a(oK,"restartProcesses");async function ng(e){if(K.createLogFile(y.PROCESS_LOG_NAMES.CLI,y.PROCESS_DESCRIPTORS.STOP),G===void 0&&(G=Ki()),o_.isEmpty(e.service))throw ad(new Error,nK,od.BAD_REQUEST,void 0,void 0,!0);let t=e.service.toLowerCase();if(y.PROCESS_DESCRIPTORS_VALIDATE[t]===void 0)throw ad(new Error,sK,od.BAD_REQUEST,void 0,void 0,!0);let r=Qi.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(Bs),Bs;await G.reloadStopStart(s)}else if(s===y.PROCESS_DESCRIPTORS.PM2_LOGROTATE)await G.configureLogRotate();else if(s.toLowerCase().includes("clustering"))await vn(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),ad(new Error,o,od.BAD_REQUEST,void 0,void 0,!0)}}else await G.restart(s);let n=`Restarting ${s}`;return K.notify(n),n}a(ng,"restartService");async function cK(){K.createLogFile(y.PROCESS_LOG_NAMES.CLI,y.PROCESS_DESCRIPTORS.STOP);try{G===void 0&&(G=Ki());let e=sg(process.argv);if(o_.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(cK,"stop");async function ig(){await vn(y.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await vn(y.PROCESS_DESCRIPTORS.CLUSTERING_LEAF),await vn(y.PROCESS_DESCRIPTORS.CLUSTERING_INGEST_SERVICE),await vn(y.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE),await cd.updateNodeNameLocalStreams(),await cd.closeConnection()}a(ig,"restartAllClusteringServices");async function vn(e){e=y.PROCESS_DESCRIPTORS_VALIDATE[e.toLowerCase()];let t=Qi.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(aK);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 ig();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 id.generateNatsConfig(!0,e),await G.startService(e),K.trace(`Starting ${e}`),e===y.PROCESS_DESCRIPTORS.CLUSTERING_LEAF&&await cd.createWorkQueueStream(tK.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 id.generateNatsConfig(!0,e),await G.restart(e),await id.removeNatsConfig(e));break;default:K.error(`Error restarting ${e}`)}}a(vn,"restartClustering")});var Tg=h((v2,fg)=>{"use strict";var B2=require("lodash"),ze=T(),{handleHDBError:og,hdb_errors:_K}=D(),{HDB_ERROR_MSGS:uK,HTTP_STATUS_CODES:lK}=_K,ud=g();fg.exports={getRolePermissions:dK};var vs=Object.create(null),EK=a(e=>({key:e,perms:{}}),"perms_template_obj"),lg=a((e=!1)=>({describe:e,tables:{}}),"schema_perms_template"),Eg=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"),ld=a((e=!1,t=!1,r=!1,s=!1,n=!1)=>({attribute_permissions:[],describe:e,...Eg(t,r,s,n)}),"table_perms_template"),cg=a((e,t=Eg())=>({attribute_name:e,describe:Sg(t),[Wi]:t[Wi],[Ed]:t[Ed],[dd]:t[dd]}),"attr_perms_template"),_g=a((e,t=!1)=>({attribute_name:e,describe:t,[Wi]:t}),"timestamp_attr_perms_template"),{READ:Wi,INSERT:Ed,UPDATE:dd}=ze.PERMS_CRUD_ENUM,dg=Object.values(ze.PERMS_CRUD_ENUM),hg=[Wi,Ed,dd];function dK(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(vs[t]&&vs[t].key===s)return vs[t].perms;let n=hK(e,r);return vs[t]?vs[t].key=s:vs[t]=EK(s),vs[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 ud.error(s),ud.debug(r),og(new Error,uK.OUTDATED_PERMS_TRANSLATION_ERROR,lK.BAD_REQUEST)}else{let s=`There was an error while translating role permissions for role: ${t}.
|
|
8
|
+
${r.stack}`;throw ud.error(s),og(new Error)}}}a(dK,"getRolePermissions");function hK(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]=SK(t[i]);return}r[i]=lg(),s[i]?Object.keys(t[i]).forEach(o=>{if(s[i].tables[o]){let c=s[i].tables[o],_=t[i][o],u=fK(c,_);r[i].describe||dg.forEach(l=>{u[l]&&(r[i].describe=!0)}),r[i].tables[o]=u}else r[i].tables[o]=ld()}):Object.keys(t[i]).forEach(o=>{r[i].tables[o]=ld()})}),r}a(hK,"translateRolePermissions");function SK(e){let t=lg(!0);return Object.keys(e).forEach(r=>{t.tables[r]=ld(!0,!0,!0,!0,!0)}),t}a(SK,"createStructureUserPermissions");function fK(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=_g(E,l[Wi])),u[E]=d,u},{}),o=t[ze.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_HASH_ATTRIBUTE_KEY],c=!!i[o],_=cg(o);return t.attributes.forEach(({attribute:u})=>{if(i[u]){let l=i[u];l.describe=Sg(l),n.attribute_permissions.push(l),c||TK(l,_)}else if(u!==o){let l;ze.TIME_STAMP_NAMES.includes(u)?l=_g(u):l=cg(u),n.attribute_permissions.push(l)}}),c||n.attribute_permissions.push(_),n.describe=ug(n),n}else return e.describe=ug(e),e}a(fK,"getTableAttrPerms");function ug(e){return dg.filter(t=>e[t]).length>0}a(ug,"getSchemaTableDescribePerm");function Sg(e){return hg.filter(t=>e[t]).length>0}a(Sg,"getAttributeDescribePerm");function TK(e,t){hg.forEach(r=>{e[r]&&!t[r]&&(t[r]=!0,t.describe=!0)})}a(TK,"checkForHashPerms")});var gg=h((H2,Ng)=>{"use strict";var me=require("joi"),mg=require("fs-extra"),Rg=require("path"),Hn=de(),Ag=V(),pg=T(),Og=g(),{hdb_errors:mK}=D(),{HDB_ERROR_MSGS:Et}=mK,ss=/^[a-zA-Z0-9-_]+$/;Ng.exports={getDropCustomFunctionValidator:AK,setCustomFunctionValidator:pK,addCustomFunctionProjectValidator:OK,dropCustomFunctionProjectValidator:NK,packageCustomFunctionProjectValidator:gK,deployCustomFunctionProjectValidator:IK};function Ji(e,t,r){try{let s=Ag.get(pg.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY),n=Rg.join(s,t);return mg.existsSync(n)?e?t:r.message(Et.PROJECT_EXISTS):e?r.message(Et.NO_PROJECT):t}catch(s){return Og.error(s),r.message(Et.VALIDATION_ERR)}}a(Ji,"checkProjectExists");function RK(e,t,r,s){try{let n=Ag.get(pg.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY),i=Rg.join(n,e,t,r+".js");return mg.existsSync(i)?r:s.message(Et.NO_FILE)}catch(n){return Og.error(n),s.message(Et.VALIDATION_ERR)}}a(RK,"checkFileExists");function AK(e){let t=me.object({project:me.string().pattern(ss).custom(Ji.bind(null,!0)).required().messages({"string.pattern.base":Et.BAD_PROJECT_NAME}),type:me.string().valid("helpers","routes").required(),file:me.string().pattern(ss).custom(RK.bind(null,e.project,e.type)).required().messages({"string.pattern.base":Et.BAD_FILE_NAME})});return Hn.validateBySchema(e,t)}a(AK,"getDropCustomFunctionValidator");function pK(e){let t=me.object({project:me.string().pattern(ss).custom(Ji.bind(null,!0)).required().messages({"string.pattern.base":Et.BAD_PROJECT_NAME}),type:me.string().valid("helpers","routes").required(),file:me.string().pattern(ss).required().messages({"string.pattern.base":Et.BAD_FILE_NAME}),function_content:me.string().required()});return Hn.validateBySchema(e,t)}a(pK,"setCustomFunctionValidator");function OK(e){let t=me.object({project:me.string().pattern(ss).custom(Ji.bind(null,!1)).required().messages({"string.pattern.base":Et.BAD_PROJECT_NAME})});return Hn.validateBySchema(e,t)}a(OK,"addCustomFunctionProjectValidator");function NK(e){let t=me.object({project:me.string().pattern(ss).custom(Ji.bind(null,!0)).required().messages({"string.pattern.base":Et.BAD_PROJECT_NAME})});return Hn.validateBySchema(e,t)}a(NK,"dropCustomFunctionProjectValidator");function gK(e){let t=me.object({project:me.string().pattern(ss).custom(Ji.bind(null,!0)).required().messages({"string.pattern.base":Et.BAD_PROJECT_NAME}),skip_node_modules:me.boolean()});return Hn.validateBySchema(e,t)}a(gK,"packageCustomFunctionProjectValidator");function IK(e){let t=me.object({project:me.string().pattern(ss).required().messages({"string.pattern.base":Et.BAD_PROJECT_NAME}),payload:me.string().required().messages({"string.pattern.base":Et.BAD_PACKAGE})});return Hn.validateBySchema(e,t)}a(IK,"deployCustomFunctionProjectValidator")});var fd=h((q2,Cg)=>{"use strict";var Ue=require("fs-extra"),c_=require("fast-glob"),ae=require("path"),Ig=require("tar-fs"),bg=require("uuid").v4,Zi=require("normalize-path"),Hs=gg(),Le=g(),pt=T(),Ot=V(),{PACKAGE_ROOT:bK}=T(),{handleHDBError:je,hdb_errors:CK}=D(),{HDB_ERROR_MSGS:ns,HTTP_STATUS_CODES:et}=CK,wK=ae.join(bK,"custom_function_template"),hd=ae.join(Ot.get(pt.HDB_SETTINGS_NAMES.HDB_ROOT_KEY),"tmp");function Sd(){let e=Ot.get(pt.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_ENABLED_KEY);if(!(e==="true"||e===!0||e==="TRUE"))throw je(new Error,ns.NOT_ENABLED,et.BAD_REQUEST,void 0,void 0,!0)}a(Sd,"isCFEnabled");function UK(){Le.trace("getting custom api status");let e={};try{e={is_enabled:Ot.get(pt.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_ENABLED_KEY),port:Ot.get(pt.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_PORT_KEY),directory:Ot.get(pt.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY)}}catch(t){throw je(new Error,ns.FUNCTION_STATUS,et.INTERNAL_SERVER_ERROR,Le.ERR,t)}return e}a(UK,"customFunctionsStatus");function LK(){Le.trace("getting custom api endpoints");let e={},t=Ot.get(pt.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY);try{c_.sync(Zi(`${t}/*`),{onlyDirectories:!0}).forEach(s=>{let n=s.split("/").pop();e[n]={routes:c_.sync(Zi(`${s}/routes/*.js`)).map(i=>i.split("/").pop().split(".js")[0]),helpers:c_.sync(Zi(`${s}/helpers/*.js`)).map(i=>i.split("/").pop().split(".js")[0]),static:Ue.existsSync(Zi(`${s}/static`))&&c_.sync(Zi(`${s}/static/**/*`)).length}})}catch(r){throw je(new Error,ns.GET_FUNCTIONS,et.INTERNAL_SERVER_ERROR,Le.ERR,r)}return e}a(LK,"getCustomFunctions");function yK(e){e.project&&(e.project=ae.parse(e.project).name),e.file&&(e.file=ae.parse(e.file).name);let t=Hs.getDropCustomFunctionValidator(e);if(t)throw je(t,t.message,et.BAD_REQUEST);Le.trace("getting custom api endpoint file content");let r=Ot.get(pt.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY),{project:s,type:n,file:i}=e,o=ae.join(r,s,n,i+".js");try{return Ue.readFileSync(o,{encoding:"utf8"})}catch(c){throw je(new Error,ns.GET_FUNCTION,et.INTERNAL_SERVER_ERROR,Le.ERR,c)}}a(yK,"getCustomFunction");function DK(e){Sd(),e.project&&(e.project=ae.parse(e.project).name),e.file&&(e.file=ae.parse(e.file).name);let t=Hs.setCustomFunctionValidator(e);if(t)throw je(t,t.message,et.BAD_REQUEST);Le.trace("setting custom function file content");let r=Ot.get(pt.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY),{project:s,type:n,file:i,function_content:o}=e;try{return Ue.outputFileSync(ae.join(r,s,n,i+".js"),o),`Successfully updated custom function: ${i}.js`}catch(c){throw je(new Error,ns.SET_FUNCTION,et.INTERNAL_SERVER_ERROR,Le.ERR,c)}}a(DK,"setCustomFunction");function MK(e){e.project&&(e.project=ae.parse(e.project).name),e.file&&(e.file=ae.parse(e.file).name);let t=Hs.getDropCustomFunctionValidator(e);if(t)throw je(t,t.message,et.BAD_REQUEST);Le.trace("dropping custom function file");let r=Ot.get(pt.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY),{project:s,type:n,file:i}=e;try{return Ue.unlinkSync(ae.join(r,s,n,i+".js")),`Successfully deleted custom function: ${i}.js`}catch(o){throw je(new Error,ns.DROP_FUNCTION,et.INTERNAL_SERVER_ERROR,Le.ERR,o)}}a(MK,"dropCustomFunction");function PK(e){Sd(),e.project&&(e.project=ae.parse(e.project).name);let t=Hs.addCustomFunctionProjectValidator(e);if(t)throw je(t,t.message,et.BAD_REQUEST);Le.trace("adding custom function project");let r=Ot.get(pt.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY),{project:s}=e;try{let n=ae.join(r,s);return Ue.mkdirSync(n,{recursive:!0}),Ue.copySync(wK,n),`Successfully created custom function project: ${s}`}catch(n){throw je(new Error,ns.ADD_FUNCTION,et.INTERNAL_SERVER_ERROR,Le.ERR,n)}}a(PK,"addCustomFunctionProject");function BK(e){e.project&&(e.project=ae.parse(e.project).name);let t=Hs.dropCustomFunctionProjectValidator(e);if(t)throw je(t,t.message,et.BAD_REQUEST);Le.trace("dropping custom function project");let r=Ot.get(pt.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY),{project:s}=e;try{let n=ae.join(r,s);return Ue.rmSync(n,{recursive:!0}),`Successfully deleted project: ${s}`}catch(n){throw je(new Error,ns.DROP_FUNCTION_PROJECT,et.INTERNAL_SERVER_ERROR,Le.ERR,n)}}a(BK,"dropCustomFunctionProject");async function vK(e){e.project&&(e.project=ae.parse(e.project).name);let t=Hs.packageCustomFunctionProjectValidator(e);if(t)throw je(t,t.message,et.BAD_REQUEST);Le.trace("packaging custom function project");let r=Ot.get(pt.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY),{project:s}=e,n=ae.join(r,s),i=bg();if(!Ue.existsSync(n)){let l=`Unable to locate custom function project: ${s}`;throw Le.error(l),l}Ue.ensureDirSync(hd);let c=ae.join(hd,`${i}.tar`),_={};(e.skip_node_modules===!0||e.skip_node_modules==="true")&&(_={ignore:l=>l.includes(ae.join(n,"node_modules"))}),Ig.pack(n,_).pipe(Ue.createWriteStream(c)),await new Promise(l=>setTimeout(l,2e3));let u=Ue.readFileSync(c,{encoding:"base64"});return Ue.unlinkSync(c),{project:s,payload:u,file:c}}a(vK,"packageCustomFunctionProject");async function HK(e){Sd(),e.project&&(e.project=ae.parse(e.project).name);let t=Hs.deployCustomFunctionProjectValidator(e);if(t)throw je(t,t.message,et.BAD_REQUEST);Le.trace("deploying custom function project");let r=Ot.get(pt.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY),{project:s,payload:n,file:i}=e,o=ae.join(r,s);await Ue.ensureDir(o);let c,_;do c=ae.join(hd,bg()+".tar"),_=await Ue.pathExists(c);while(_);await Ue.outputFile(c,n,{encoding:"base64"});let u=Ue.createReadStream(c);return u.pipe(Ig.extract(o)),await new Promise(l=>u.on("end",l)),await Ue.unlink(c),`Successfully deployed project: ${s}`}a(HK,"deployCustomFunctionProject");Cg.exports={customFunctionsStatus:UK,getCustomFunctions:LK,getCustomFunction:yK,setCustomFunction:DK,dropCustomFunction:MK,addCustomFunctionProject:PK,dropCustomFunctionProject:BK,packageCustomFunctionProject:vK,deployCustomFunctionProject:HK}});var Td=h((G2,Ug)=>{"use strict";var _r=require("joi"),wg=de();Ug.exports={readTransactionLogValidator:qK,deleteTransactionLogsBeforeValidator:GK};function qK(e){let t=_r.object({schema:_r.string().required(),table:_r.string().required(),from:_r.date().timestamp(),to:_r.date().timestamp(),limit:_r.number().min(1)});return wg.validateBySchema(e,t)}a(qK,"readTransactionLogValidator");function GK(e){let t=_r.object({schema:_r.string().required(),table:_r.string().required(),timestamp:_r.date().timestamp().required()});return wg.validateBySchema(e,t)}a(GK,"deleteTransactionLogsBeforeValidator")});var u_=h((F2,Pg)=>{"use strict";var md=T(),__=At(),Lg=b(),yg=V(),Dg=$r(),{handleHDBError:qn,hdb_errors:FK}=D(),{HTTP_STATUS_CODES:Gn}=FK,{readTransactionLogValidator:VK,deleteTransactionLogsBeforeValidator:kK}=Td(),Mg="This operation relies on clustering and cannot run with it disable.",xK="Logs successfully deleted from transaction log.",$K="All logs successfully deleted from transaction log.";Pg.exports={readTransactionLog:YK,deleteTransactionLogsBefore:KK};async function YK(e){let t=VK(e);if(t)throw qn(t,t.message,Gn.BAD_REQUEST,void 0,void 0,!0);if(!yg.get(md.CONFIG_PARAMS.CLUSTERING_ENABLED))throw qn(new Error,Mg,Gn.NOT_FOUND,void 0,void 0,!0);let{schema:r,table:s}=e,n=Lg.checkSchemaTableExist(r,s);if(n)throw qn(new Error,n,Gn.NOT_FOUND,void 0,void 0,!0);let i=Dg.createNatsTableStreamName(r,s),o=await __.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===md.OPERATIONS_ENUM.DELETE&&(d.hash_values=l?.entry?.hash_values),c.push(d)}return c}a(YK,"readTransactionLog");async function KK(e){let t=kK(e);if(t)throw qn(t,t.message,Gn.BAD_REQUEST,void 0,void 0,!0);if(!yg.get(md.CONFIG_PARAMS.CLUSTERING_ENABLED))throw qn(new Error,Mg,Gn.NOT_FOUND,void 0,void 0,!0);let{schema:r,table:s,timestamp:n}=e,i=Lg.checkSchemaTableExist(r,s);if(i)throw qn(new Error,i,Gn.NOT_FOUND,void 0,void 0,!0);let o=Dg.createNatsTableStreamName(r,s),{jsm:c}=await __.getNATSReferences(),_=await __.getStreamInfo(o),u=new Date(_.state.first_ts).getTime();if(n<=u)return`No transactions exist before: ${n}`;let l=xK,E,d=new Date(_.state.last_ts).getTime();return n>d?(E=_.state.last_seq+1,l=$K):E=(await __.viewStream(o,parseInt(n),1))[0].nats_sequence,await c.streams.purge(o,{seq:E}),l}a(KK,"deleteTransactionLogsBefore")});var Ad=h((V2,$g)=>{"use strict";var l_=require("joi"),E_=require("path"),Bg=require("fs-extra"),{exec:QK}=require("child_process"),WK=require("util"),vg=WK.promisify(QK),JK=T(),{handleHDBError:Fn,hdb_errors:ZK}=D(),{HTTP_STATUS_CODES:Vn}=ZK,Hg=V(),XK=de(),d_=g();Hg.initSync();var Rd=Hg.get(JK.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY),qg="npm install --omit=dev --json",zK=`${qg} --dry-run`;$g.exports={installModules:jK,auditModules:eQ};async function Gg(e,t=void 0){let{stdout:r,stderr:s}=await vg(e,{cwd:t});if(s)throw new Error(s.replace(`
|
|
9
9
|
`,""));return r.replace(`
|
|
10
|
-
`,"")}a(
|
|
10
|
+
`,"")}a(Gg,"runCommand");async function jK(e){d_.info(`starting installModules for request: ${e}`);let t=xg(e);if(t)throw Fn(t,t.message,Vn.BAD_REQUEST);let{projects:r,dry_run:s}=e,n=s===!0?zK:qg;await Vg(),await kg(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=E_.join(Rd,_),l,E=null;try{let{stdout:d,stderr:S}=await vg(n,{cwd:u});l=d?d.replace(`
|
|
11
11
|
`,""):null,E=S?S.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(Gg,"parseNPMStdErr");async function eQ(e){h_.info(`starting auditModules for request: ${e}`);let t=kg(e);if(t)throw Fn(t,t.message,Vn.BAD_REQUEST);let{projects:r}=e;await Fg(),await Vg(r);let s={};for(let n=0,i=r.length;n<i;n++){let o=r[n],c=d_.join(Rd,o);s[o]={npm_output:null,npm_error:null};try{let _=await qg("npm audit --json",c);s[o].npm_output=JSON.parse(_)}catch(_){s[o].npm_error=Gg(_.stderr)}}return h_.info(`finished auditModules with response ${s}`),s}a(eQ,"auditModules");async function Fg(){try{return await qg("npm -v"),!0}catch{throw Fn(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(Fg,"checkNPMInstalled");async function Vg(e){if(!Array.isArray(e)||e.length===0)throw Fn(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=d_.join(Rd,i.toString());if(!await Pg.pathExists(o)){t.push(i);continue}let _=d_.join(o,"package.json");await Pg.pathExists(_)||r.push(i)}if(t.length>0)throw Fn(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 Fn(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(Vg,"checkProjectPaths");function kg(e){let t=E_.object({projects:E_.array().min(1).items(E_.string()).required(),dry_run:E_.boolean().default(!1)});return XK.validateBySchema(e,t)}a(kg,"modulesValidator")});var Yg=h((k2,$g)=>{"use strict";var S_=class{constructor(t,r,s=[],n=[]){this.schema=t,this.table=r,this.required_table_permissions=s,this.required_attribute_permissions=n}};a(S_,"PermissionTableResponseObject");$g.exports=S_});var Qg=h((x2,Kg)=>{"use strict";var f_=class{constructor(t,r=[]){this.attribute_name=t,this.required_permissions=r}};a(f_,"PermissionAttributeResponseObject");Kg.exports=f_});var pd=h(($2,Jg)=>{"use strict";var Wg=Yg(),tQ=Qg(),{HDB_ERROR_MSGS:rQ}=Qe(),T_=class{constructor(){this.error=rQ.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 Wg(t,r,s),i=`${t}_${r}`;this.unauthorized_access[i]=n}addUnauthorizedAttributes(t,r,s,n){let i=[];t.forEach(c=>{let _=new tQ(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 Wg(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(T_,"PermissionResponseObject");Jg.exports=T_});var p_=h((Y2,uI)=>{"use strict";var Od=yt(),m_=mt(),vt=Ec(),ji=ms(),Nd=ps(),sQ=dE(),ea=gr(),R_=OE(),Ne=g(),nQ=IE(),iQ=Dc(),aQ=kE(),oQ=vc(),cQ=xE(),_Q=KE(),gd=JE(),Lr=b(),uQ=TN(),Id=zE(),zg=ud(),Bt=T(),jg=Tg(),lQ=wc(),eI=nc(),tI=Tr(),yr=fd(),EQ=require("alasql"),rI=l_(),sI=Ad(),nI=pd(),{handleHDBError:dt,hdb_errors:iI}=D(),{HDB_ERROR_MSGS:Fe,HTTP_STATUS_CODES:Xi}=iI,p=new Map,aI="delete",is="insert",ur="read",qs="update",zi="describe",Zg=ji.describeSchema.name,Xg=ji.describeTable.name,oI={delete:!0,deleteRecord:!0,update:!0,updateData:!0,dropAttribute:!0,dropTable:!0,dropSchema:!0,upsert:!0,upsertData:!0},dQ="catchup",hQ="handleGetJob",SQ="handleGetJobsByStartDate",A_={CSV_DATA_LOAD:"csvDataLoad",CSV_URL_LOAD:"csvURLLoad",CSV_FILE_LOAD:"csvFileLoad",IMPORT_FROM_S3:"importFromS3"},fQ=[vt.createTable.name,vt.createAttribute.name,vt.dropTable.name,vt.dropAttribute.name],cI={EXPORT_TO_S3:"export_to_s3",EXPORT_LOCAL:"export_local"},O=class{constructor(t,r){this.requires_su=t,this.perms=r}};a(O,"permission");p.set(Od.insert.name,new O(!1,[is]));p.set(Od.update.name,new O(!1,[qs]));p.set(Od.upsert.name,new O(!1,[is,qs]));p.set(m_.searchByConditions.name,new O(!1,[ur]));p.set(m_.searchByHash.name,new O(!1,[ur]));p.set(m_.searchByValue.name,new O(!1,[ur]));p.set(m_.search.name,new O(!1,[ur]));p.set(vt.createSchema.name,new O(!0,[]));p.set(vt.createTable.name,new O(!0,[]));p.set(vt.createAttribute.name,new O(!1,[is]));p.set(vt.dropSchema.name,new O(!0,[]));p.set(vt.dropTable.name,new O(!0,[]));p.set(vt.dropAttribute.name,new O(!0,[]));p.set(ji.describeSchema.name,new O(!1,[ur]));p.set(ji.describeTable.name,new O(!1,[ur]));p.set(Nd.deleteRecord.name,new O(!1,[aI]));p.set(ea.addUser.name,new O(!0,[]));p.set(ea.alterUser.name,new O(!0,[]));p.set(ea.dropUser.name,new O(!0,[]));p.set(ea.listUsersExternal.name,new O(!0,[]));p.set(R_.listRoles.name,new O(!0,[]));p.set(R_.addRole.name,new O(!0,[]));p.set(R_.alterRole.name,new O(!0,[]));p.set(R_.dropRole.name,new O(!0,[]));p.set(nQ.name,new O(!0,[]));p.set(iQ.name,new O(!0,[]));p.set(aQ.name,new O(!0,[]));p.set(oQ.name,new O(!0,[]));p.set(cQ.name,new O(!0,[]));p.set(gd.setRoutes.name,new O(!0,[]));p.set(gd.getRoutes.name,new O(!0,[]));p.set(gd.deleteRoutes.name,new O(!0,[]));p.set(tI.setConfiguration.name,new O(!0,[]));p.set(_Q.clusterStatus.name,new O(!0,[]));p.set(Id.getFingerprint.name,new O(!0,[]));p.set(Id.setLicense.name,new O(!0,[]));p.set(Nd.deleteFilesBefore.name,new O(!0,[]));p.set(Nd.deleteAuditLogsBefore.name,new O(!0,[]));p.set(zg.restartProcesses.name,new O(!0,[]));p.set(zg.restartService.name,new O(!0,[]));p.set(sQ.name,new O(!0,[]));p.set(lQ.systemInformation.name,new O(!0,[]));p.set(tI.getConfiguration.name,new O(!0,[]));p.set(rI.readTransactionLog.name,new O(!0,[]));p.set(rI.deleteTransactionLogsBefore.name,new O(!0,[]));p.set(sI.installModules.name,new O(!0,[]));p.set(sI.auditModules.name,new O(!0,[]));p.set(eI.createTokens.name,new O(!1,[]));p.set(eI.refreshOperationToken.name,new O(!1,[]));p.set(yr.customFunctionsStatus.name,new O(!0,[]));p.set(yr.getCustomFunctions.name,new O(!0,[]));p.set(yr.getCustomFunction.name,new O(!0,[]));p.set(yr.setCustomFunction.name,new O(!0,[]));p.set(yr.dropCustomFunction.name,new O(!0,[]));p.set(yr.addCustomFunctionProject.name,new O(!0,[]));p.set(yr.dropCustomFunctionProject.name,new O(!0,[]));p.set(yr.packageCustomFunctionProject.name,new O(!0,[]));p.set(yr.deployCustomFunctionProject.name,new O(!0,[]));p.set(Id.getRegistrationInfo.name,new O(!1,[]));p.set(ea.userInfo.name,new O(!1,[]));p.set(ji.describeAll.name,new O(!1,[]));p.set(hQ,new O(!1,[]));p.set(SQ,new O(!0,[]));p.set(dQ,new O(!0,[]));p.set(A_.CSV_DATA_LOAD,new O(!1,[is,qs]));p.set(A_.CSV_URL_LOAD,new O(!1,[is,qs]));p.set(A_.CSV_FILE_LOAD,new O(!1,[is,qs]));p.set(A_.IMPORT_FROM_S3,new O(!1,[is,qs]));p.set(cI.EXPORT_TO_S3,new O(!1,[ur]));p.set(cI.EXPORT_LOCAL,new O(!1,[ur]));p.set(Bt.VALID_SQL_OPS_ENUM.DELETE,new O(!1,[aI]));p.set(Bt.VALID_SQL_OPS_ENUM.SELECT,new O(!1,[ur]));p.set(Bt.VALID_SQL_OPS_ENUM.INSERT,new O(!1,[is]));p.set(Bt.VALID_SQL_OPS_ENUM.UPDATE,new O(!1,[qs]));uI.exports={verifyPerms:mQ,verifyPermsAst:TQ,verifyBulkLoadAttributePerms:AQ};function TQ(e,t,r){if(Lr.isEmptyOrZeroLength(e))throw Ne.info("verify_perms_ast has an empty user parameter"),dt(new Error);if(Lr.isEmptyOrZeroLength(t))throw Ne.info("verify_perms_ast has an empty user parameter"),dt(new Error);if(Lr.isEmptyOrZeroLength(r))throw Ne.info("verify_perms_ast has a null operation parameter"),dt(new Error);try{let s=new nI,n=new uQ(e),i=n.getSchemas(),o=new Map;if((!i||i.length===0)&&n.affected_attributes&&n.affected_attributes.size>0)throw Ne.info("No schemas defined in verifyPermsAst(), will not continue."),dt(new Error);let c=!!t.role.permission.super_user,_=i.includes("system");if(_&&oI[r])throw dt(new Error,Fe.DROP_SYSTEM,Xi.FORBIDDEN);if(c&&!_)return null;let u=jg.getRolePermissions(t.role);t.role.permission=u,!c&&e instanceof EQ.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=_I(t,r,o,s);return l||(o.forEach((E,d)=>{for(let S=0;S<E.length;S++){let m=n.getAttributesBySchemaTableName(d,E[S]),R=Cd(t.role.permission,d,E[S]);bd(m,R,r,E[S],d,s)}}),s.getPermsResponse())}catch(s){throw dt(s)}}a(TQ,"verifyPermsAst");function mQ(e,t){if(e===null||t===null||e.hdb_user===void 0||e.hdb_user===null)throw Ne.info("null required parameter in verifyPerms"),dt(new Error,Fe.DEFAULT_INVALID_REQUEST,Xi.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 nI;if(Lr.isEmptyOrZeroLength(e.hdb_user.role)||Lr.isEmptyOrZeroLength(e.hdb_user.role.permission))return Ne.info(`User ${e.hdb_user.username} has no role or permissions. Please assign the user a valid role.`),c.handleUnauthorizedItem(Fe.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(Bt.SYSTEM_SCHEMA_NAME)||n===Bt.SYSTEM_SCHEMA_NAME;if(l&&oI[r])throw dt(new Error,Fe.DROP_SYSTEM,Xi.FORBIDDEN);if(_&&!l||u===!0&&(r===vt.createSchema.name||r===vt.dropSchema.name))return null;if(fQ.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=jg.getRolePermissions(e.hdb_user.role);if(e.hdb_user.role.permission=E,r===Zg||r===Xg){if(n===Bt.SYSTEM_SCHEMA_NAME)return c.handleUnauthorizedItem(Fe.SCHEMA_PERM_ERROR(n));if(!E.super_user){if(r===Zg&&(!E[n]||!E[n][zi]))return c.handleInvalidItem(Fe.SCHEMA_NOT_FOUND(n));if(r===Xg&&(!E[n]||!E[n].tables[i]||!E[n].tables[i][zi]))return c.handleInvalidItem(Fe.TABLE_NOT_FOUND(n,i))}}let d=_I(e.hdb_user,r,o,c,s);if(d)return d;if(p.get(r)&&p.get(r).perms.length===0)return null;if(!_&&e.get_attributes&&Bt.SEARCH_WILDCARDS.includes(e.get_attributes[0])){let R=[],w=E[n].tables[i];w[Bt.PERMS_CRUD_ENUM.READ]&&(w.attribute_permissions.length>0?w.attribute_permissions.filter(B=>B[Bt.PERMS_CRUD_ENUM.READ]).forEach(B=>{R.push(B.attribute_name)}):R=global.hdb_schema[n][i].attributes.map(U=>U.attribute),e.get_attributes=R)}let S=RQ(e),m=Cd(e.hdb_user.role.permission,n,i);return bd(S,m,r,i,n,c,s),c.getPermsResponse()}a(mQ,"verifyPerms");function _I(e,t,r,s,n){if(Lr.arrayHasEmptyValues([e,t,r]))throw Ne.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(!p.get(t))throw Ne.info(`operation ${t} not found.`),dt(new Error,Fe.OP_NOT_FOUND(t),Xi.BAD_REQUEST);if(p.get(t)&&p.get(t).requires_su)return Ne.info(`operation ${t} requires SU permissions.`),s.handleUnauthorizedItem(Fe.OP_IS_SU_ONLY(t));let c=r.keys();for(let _ of c){try{if(_&&!o[_]||o[_][zi]===!1){s.addInvalidItem(Fe.SCHEMA_NOT_FOUND(_));continue}}catch{s.addInvalidItem(Fe.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(Fe.TABLE_NOT_FOUND(_,l));else try{let d=[],S=p.get(t).perms;!Lr.isEmpty(n)&&S.includes(n)&&(S=[n]);for(let m=0;m<S.length;m++){let R=S[m],w=E[R];(w==null||w===!1)&&(Ne.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 S=Fe.UNKNOWN_OP_AUTH_ERROR(t,_,l);throw Ne.error(S),Ne.error(d),dt(iI.CHECK_LOGS_WRAPPER(S))}}}return r.size<2?s.getPermsResponse():null}a(_I,"hasPermissions");function bd(e,t,r,s,n,i,o){if(!e||!t)throw Ne.info("no attributes specified in checkAttributePerms."),dt(new Error);let c=p.get(r).perms;if(!c||c==="")throw Ne.info(`no permissions found for ${r} in checkAttributePerms().`),dt(new Error);if(Lr.isEmptyOrZeroLength(t))return Ne.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(Fe.ATTR_NOT_FOUND(n,s,l),n,s);continue}if(c)for(let d of c){if(Bt.TIME_STAMP_NAMES.includes(E.attribute_name)&&d!==ur)throw dt(new Error,Fe.SYSTEM_TIMESTAMP_PERMS_ERR,Xi.FORBIDDEN);E[d]===!1&&(_[E.attribute_name]?_[E.attribute_name].push(d):_[E.attribute_name]=[d])}}else i.addInvalidItem(Fe.ATTR_NOT_FOUND(n,s,l),n,s)}let u=Object.keys(_);u.length>0&&i.addUnauthorizedAttributes(u,n,s,_)}a(bd,"checkAttributePerms");function RQ(e){let t=new Set;try{if(e.action)return t;if(e.operation===Bt.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){Ne.info(r)}return t}a(RQ,"getRecordAttributes");function Cd(e,t,r){let s=new Map;if(Lr.isEmpty(e))return Ne.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{Ne.info(`No attribute permissions found for schema ${t} and table ${r}.`)}return s}a(Cd,"getAttributePermissions");function AQ(e,t,r,s,n,i,o){let c=new Set(i),_=Cd(e,s,n);bd(c,_,t,n,s,o,r)}a(AQ,"verifyBulkLoadAttributePerms")});var N_=h((K2,SI)=>{"use strict";SI.exports={evaluateSQL:BQ,processAST:hI,convertSQLToAST:dI,checkASTPermissions:EI};var lI=yt(),Ld=require("util"),pQ=Ld.callbackify(lI.insert),OQ=mt().search,NQ=Ap().update,gQ=Ld.callbackify(NQ),IQ=Op().convertDelete,as=require("alasql"),bQ=p_(),ra=g(),CQ=yo(),wQ=b(),ta=T(),{hdb_errors:UQ,handleHDBError:wd}=D(),{HTTP_STATUS_CODES:Ud}=UQ,LQ=On();function yQ(e,t,r){return Promise.all([LQ.postOperationHandler(e,t,r),lI.flush(e)])}a(yQ,"postWrite");var DQ=Ld.callbackify(yQ);CQ(as);var MQ=403,PQ="There was a problem performing this insert. Please check the logs and try again.",O_=class{constructor(){this.ast=void 0,this.variant=void 0,this.permissions_checked=!1}};a(O_,"ParsedSQLObject");function BQ(e,t){let r=e.parsed_sql_object;if(!r){r=dI(e.sql);let s,n=r.ast.statements[0];if(n instanceof as.yy.Insert?s=n.into.databaseid:n instanceof as.yy.Select?s=n.from?n.from[0].databaseid:null:n instanceof as.yy.Update||n instanceof as.yy.Delete?s=n.table.databaseid:ra.error("AST in evaluateSQL is not a valid SQL type."),!(n instanceof as.yy.Select)&&wQ.isEmptyOrZeroLength(s))return t("No schema specified",null)}hI(e,r,(s,n)=>{if(s)return t(s);t(null,n)})}a(BQ,"evaluateSQL");function EI(e,t){let r;try{r=bQ.verifyPermsAst(t.ast.statements[0],e.hdb_user,t.variant),t.permissions_checked=!0}catch(s){throw s}return r||null}a(EI,"checkASTPermissions");function dI(e){let t=new O_;if(!e)throw wd(new Error,"The 'sql' parameter is missing from the request body",Ud.BAD_REQUEST);try{let r=e.trim(),s=as.parse(r),n=r.split(" ")[0].toLowerCase();t.ast=s,t.variant=n}catch(r){let s=r.message.split(`
|
|
14
|
-
`);throw s[1]?wd(r,`Invalid SQL at: ${s[1]}. Please ensure your SQL is valid. Try adding backticks to reserved words and schema table references.`,Ud.BAD_REQUEST):wd(r,"We had trouble parsing your request. Please ensure your SQL is valid. Try adding backticks to reserved words and schema table references.",Ud.BAD_REQUEST)}return t}a(dI,"convertSQLToAST");function hI(e,t,r){try{let s=vQ;if(!e.bypass_auth&&!t.permissions_checked){let i=EI(e,t);if(i&&i.length>0)return r(MQ,i)}let n={statement:t.ast.statements[0],hdb_user:e.hdb_user};switch(t.variant){case ta.VALID_SQL_OPS_ENUM.SELECT:s=OQ,n=t.ast.statements[0];break;case ta.VALID_SQL_OPS_ENUM.INSERT:s=HQ;break;case ta.VALID_SQL_OPS_ENUM.UPDATE:s=gQ;break;case ta.VALID_SQL_OPS_ENUM.DELETE:s=IQ;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(hI,"processAST");function vQ(e,t){ra.info(e),t("unknown sql statement")}a(vQ,"nullFunction");function HQ({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=qQ(i,e.values)}catch(o){return r(o)}pQ(n,(o,c)=>{if(o)return r(o);DQ(n,c,_=>{_&&ra.error(_)});try{delete c.new_attributes,delete c.txn_time}catch(_){ra.error(`Error delete new_attributes from insert response: ${_}`)}r(null,c)})}a(HQ,"convertInsert");function qQ(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]]=as.compile(`SELECT ${n.toString()} AS [${ta.FUNC_VAL}] FROM ?`)}),s})}catch(r){throw ra.error(r),new Error(PQ)}}a(qQ,"createDataObjects")});var Dd=h((Q2,AI)=>{var w_=require("clone"),U_=he(),GQ=b(),C_=T(),FQ=g(),g_=require("fs"),{hdb_errors:VQ,handleHDBError:sa}=D(),{HDB_ERROR_MSGS:kQ,HTTP_STATUS_CODES:I_}=VQ,{common_validators:b_}=Rr(),fI=1e9,yd=" is required",xQ=["insert","update","upsert"],L_={schema:{presence:!0,format:b_.schema_format,length:b_.schema_length},table:{presence:!0,format:b_.schema_format,length:b_.schema_length},action:{inclusion:{within:xQ,message:"is required and must be either insert, update, or upsert"}},file_path:{},csv_url:{url:{allowLocal:!0}},data:{}},{AWS_ACCESS_KEY:$Q,AWS_SECRET:YQ,AWS_BUCKET:KQ,AWS_FILE_KEY:QQ}=C_.S3_BUCKET_AUTH_KEYS,WQ={s3:{presence:!0},[`s3.${$Q}`]:{presence:!0,type:"String"},[`s3.${YQ}`]:{presence:!0,type:"String"},[`s3.${KQ}`]:{presence:!0,type:"String"},[`s3.${QQ}`]:{presence:!0,type:"String",hasValidFileExt:[".csv",".json"]}},TI=w_(L_);TI.data.presence={message:yd};var mI=w_(L_);mI.file_path.presence={message:yd};var JQ=Object.assign(w_(L_),WQ),RI=w_(L_);RI.csv_url.presence={message:yd};function ZQ(e){let t=U_.validateObject(e,TI);return y_(e,t)}a(ZQ,"dataObject");function XQ(e){let t=U_.validateObject(e,RI);return y_(e,t)}a(XQ,"urlObject");function zQ(e){let t=U_.validateObject(e,mI);return y_(e,t)}a(zQ,"fileObject");function jQ(e){let t=U_.validateObject(e,JQ);return y_(e,t)}a(jQ,"s3FileObject");function y_(e,t){if(!t){let r=GQ.checkGlobalSchemaTable(e.schema,e.table);if(r)return sa(new Error,r,I_.BAD_REQUEST);if(e.operation===C_.OPERATIONS_ENUM.CSV_FILE_LOAD){try{g_.accessSync(e.file_path,g_.constants.R_OK|g_.constants.F_OK)}catch(s){return s.code===C_.NODE_ERROR_CODES.ENOENT?sa(s,`No such file or directory ${s.path}`,I_.BAD_REQUEST):s.code===C_.NODE_ERROR_CODES.EACCES?sa(s,`Permission denied ${s.path}`,I_.BAD_REQUEST):sa(s)}try{let s=g_.statSync(e.file_path).size;if(s>fI)return sa(new Error,kQ.MAX_FILE_SIZE_ERR(s,fI),I_.BAD_REQUEST)}catch(s){FQ.error(s),console.error(s)}}}return t}a(y_,"postValidateChecks");AI.exports={dataObject:ZQ,urlObject:XQ,fileObject:zQ,s3FileObject:jQ}});var Md=h((W2,pI)=>{"use strict";var na=g(),D_=T();async function eW(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===D_.OPERATIONS_ENUM.INSERT||t.operation===D_.OPERATIONS_ENUM.UPDATE||t.operation===D_.OPERATIONS_ENUM.UPSERT?(delete n.new_attributes,delete n.txn_time):t.operation===D_.OPERATIONS_ENUM.DELETE&&delete n.txn_time,n}catch(i){throw i.message&&typeof i.message=="string"&&i.message.includes("already exists")?(na.info(i.message),i):i.http_resp_msg?(na.error(`Error calling operation: ${e.name}`),na.error(i.http_resp_msg),i):(na.error(`Error calling operation: ${e.name}`),na.error(i),i)}}a(eW,"callOperationFunctionAsAwait");pI.exports={callOperationFunctionAsAwait:eW}});var Pd=h((J2,NI)=>{"use strict";var tW=require("aws-sdk/clients/s3");NI.exports={getFileStreamFromS3:rW,getS3AuthObj:OI};function rW(e){let{s3:t}=e,r={Bucket:t.bucket,Key:t.key};return OI(t.aws_access_key_id,t.aws_secret_access_key).getObject(r).createReadStream()}a(rW,"getFileStreamFromS3");function OI(e,t){return new tW({accessKeyId:e,secretAccessKey:t})}a(OI,"getS3AuthObj")});var II=h((Z2,gI)=>{"use strict";var M_=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(M_,"BulkLoadFileObject");var P_=class{constructor(t,r,s,n){this.action=t,this.schema=r,this.table=s,this.data=n}};a(P_,"BulkLoadDataObject");gI.exports={BulkLoadFileObject:M_,BulkLoadDataObject:P_}});var Gd=h((X2,kI)=>{"use strict";var B_=yt(),q_=Dd(),sW=require("needle"),Nt=T(),nW=fe(),ia=b(),{handleHDBError:oe,hdb_errors:PI}=D(),{HTTP_STATUS_CODES:Ve,HDB_ERROR_MSGS:ge,CHECK_LOGS_WRAPPER:Vs}=PI,Fs=g(),v_=require("papaparse");ia.promisifyPapaParse();var Zt=require("fs-extra"),iW=require("path"),{chain:bI}=require("stream-chain"),CI=require("stream-json/streamers/StreamArray"),wI=require("stream-json/utils/Batch"),UI=require("stream-chain/utils/comp"),{finished:LI}=require("stream"),Bd=V(),aW=On(),BI=Md(),oW=Pd(),{BulkLoadFileObject:vd,BulkLoadDataObject:cW}=II(),Hd=pd(),{verifyBulkLoadAttributePerms:vI}=p_(),_W=iE(),uW=At(),lW=$r(),yI="No records parsed from csv file.",Gs=`${Bd.get("HDB_ROOT")}/tmp`,{schema_regex:EW}=Rr(),DI=1024*1024*5,MI=5e3,dW={"text/csv":!0,"application/octet-stream":!0,"text/plain":!0,"application/vnd.ms-excel":!0};kI.exports={csvDataLoad:hW,csvURLLoad:SW,csvFileLoad:fW,importFromS3:TW};async function hW(e,t=[]){let r=q_.dataObject(e);if(r)throw oe(r,r.message,Ve.BAD_REQUEST,void 0,void 0,!0);let s={};try{let n=v_.parse(e.data,{header:!0,skipEmptyLines:!0,dynamicTyping:!0}),i=new Hd;e.hdb_user&&e.hdb_user.role&&e.hdb_user.role.permission&&e.hdb_user.role.permission.super_user!==!0&&vI(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 oe(new Error,o,Ve.BAD_REQUEST,void 0,void 0,!0);let c=new cW(e.action,e.schema,e.table,n.data);return s=await BI.callOperationFunctionAsAwait(GI,c,FI.bind(null,n.meta.fields),t),s.message===yI?yI:VI(s.records,s.number_written)}catch(n){throw ks(n)}}a(hW,"csvDataLoad");async function SW(e){let t=q_.urlObject(e);if(t)throw oe(t,t.message,Ve.BAD_REQUEST,void 0,void 0,!0);let r=`${Date.now()}.csv`,s=`${Gs}/${r}`;try{await mW(e.csv_url,r)}catch(n){throw Fs.error(ge.DOWNLOAD_FILE_ERR(r)+" - "+n),oe(n,Vs(ge.DOWNLOAD_FILE_ERR(r)))}try{let n=new vd(this.job_operation_function.name,e.action,e.schema,e.table,s,Nt.VALID_S3_FILE_TYPES.CSV,e.hdb_user.role.permission),i=await qd(n);return await H_(s),i}catch(n){throw await H_(s),ks(n)}}a(SW,"csvURLLoad");async function fW(e){let t=q_.fileObject(e);if(t)throw oe(t,t.message,Ve.BAD_REQUEST,void 0,void 0,!0);let r=new vd(this.job_operation_function.name,e.action,e.schema,e.table,e.file_path,Nt.VALID_S3_FILE_TYPES.CSV,e.hdb_user.role.permission);try{return await qd(r)}catch(s){throw ks(s)}}a(fW,"csvFileLoad");async function TW(e){let t=q_.s3FileObject(e);if(t)throw oe(t,t.message,Ve.BAD_REQUEST,void 0,void 0,!0);let r;try{let s=iW.extname(e.s3.key),n=`${Date.now()}${s}`;r=`${Gs}/${n}`;let i=new vd(this.job_operation_function.name,e.action,e.schema,e.table,r,s,e.hdb_user.role.permission);await RW(n,e);let o=await qd(i);return await H_(r),o}catch(s){throw await H_(r),ks(s)}}a(TW,"importFromS3");async function mW(e,t){let r;try{r=await sW("get",e)}catch(s){let n=`Error downloading CSV file from ${e}, status code: ${s.statusCode}. Check the log for more information.`;throw oe(s,n,s.statusCode,Nt.LOG_LEVELS.ERROR,"Error downloading CSV file - "+s)}pW(r,e),await AW(t,r.raw)}a(mW,"downloadCSVFile");async function RW(e,t){try{let r=`${Gs}/${e}`;await Zt.mkdirp(Gs),await Zt.writeFile(`${Gs}/${e}`,"",{flag:"a+"});let s=await Zt.createWriteStream(r),n=oW.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(){Fs.info(`${t.s3.key} successfully downloaded to ${r}`),i()})})}catch(r){throw Fs.error(ge.S3_DOWNLOAD_ERR+" - "+r),oe(r,Vs(ge.S3_DOWNLOAD_ERR))}}a(RW,"downloadFileFromS3");async function AW(e,t){try{await Zt.mkdirp(Gs),await Zt.writeFile(`${Gs}/${e}`,t)}catch(r){throw Fs.error(ge.WRITE_TEMP_FILE_ERR),oe(r,Vs(ge.DEFAULT_BULK_LOAD_ERR))}}a(AW,"writeFileToTempFolder");async function H_(e){if(e)try{await Zt.access(e),await Zt.unlink(e)}catch{Fs.warn(`could not delete temp csv file at ${e}, file does not exist`)}}a(H_,"deleteTempFile");function pW(e,t){if(e.statusCode!==PI.HTTP_STATUS_CODES.OK)throw oe(new Error,`CSV Load failed from URL: ${t}, status code: ${e.statusCode}, message: ${e.statusMessage}`,Ve.BAD_REQUEST);if(!dW[e.headers["content-type"]])throw oe(new Error,`CSV Load failed from URL: ${t}, unsupported content type: ${e.headers["content-type"]}`,Ve.BAD_REQUEST);if(!e.raw)throw oe(new Error,`CSV Load failed from URL: ${t}, no csv found at url`,Ve.BAD_REQUEST)}a(pW,"validateURLResponse");async function qd(e){try{let t;switch(e.file_type){case Nt.VALID_S3_FILE_TYPES.CSV:t=await OW(e);break;case Nt.VALID_S3_FILE_TYPES.JSON:t=await NW(e);break;default:throw oe(new Error,ge.DEFAULT_BULK_LOAD_ERR,Ve.BAD_REQUEST,Nt.LOG_LEVELS.ERROR,ge.INVALID_FILE_EXT_ERR(e))}return VI(t.records,t.number_written)}catch(t){throw ks(t)}}a(qd,"fileLoad");async function HI(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 B_.validation(o);e.role_perms&&e.role_perms.super_user!==!0&&vI(e.role_perms,e.op,e.action,e.schema,e.table,c,t),n&&n.resume()}catch(c){let _=oe(c);r(_)}}a(HI,"validateChunk");async function qI(e,t,r,s,n){let i=s.data?s.data:s;if(i.length===0)return;ia.autoCastJSONDeep(i),n&&n.pause();let o=s.meta?s.meta.fields:null;if(o)i.forEach(c=>{!ia.isEmpty(c)&&!ia.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 BI.callOperationFunctionAsAwait(GI,c,FI.bind(null,o));t.records+=_.records,t.number_written+=_.number_written,n&&n.resume()}catch(c){let _=oe(c,Vs(ge.INSERT_CSV_ERR),Ve.INTERNAL_SERVER_ERROR,Nt.LOG_LEVELS.ERROR,ge.INSERT_CSV_ERR+" - "+c);r(_)}}a(qI,"insertChunk");async function OW(e){let t={records:0,number_written:0};try{let r=new Hd,s=Zt.createReadStream(e.file_path,{highWaterMark:DI});s.setEncoding("utf8"),await v_.parsePromise(s,HI.bind(null,e,r));let n=r.getPermsResponse();if(n)throw oe(new Error,n,Ve.BAD_REQUEST);return s=Zt.createReadStream(e.file_path,{highWaterMark:DI}),s.setEncoding("utf8"),await v_.parsePromise(s,qI.bind(null,e,t)),s.destroy(),t}catch(r){throw oe(r,Vs(ge.PAPA_PARSE_ERR),Ve.INTERNAL_SERVER_ERROR,Nt.LOG_LEVELS.ERROR,ge.PAPA_PARSE_ERR+r)}}a(OW,"callPapaParse");async function NW(e){let t={records:0,number_written:0},r=a(s=>{throw s},"throwErr");try{let s=new Hd,n=bI([Zt.createReadStream(e.file_path,{encoding:"utf-8"}),CI.withParser(),c=>c.value,new wI({batchSize:MI}),UI(async c=>{await HI(e,s,r,c)})]);await new Promise((c,_)=>{LI(n,u=>{u?_(u):c()}),n.resume()});let i=s.getPermsResponse();if(i)throw oe(new Error,i,Ve.BAD_REQUEST);let o=bI([Zt.createReadStream(e.file_path,{encoding:"utf-8"}),CI.withParser(),c=>c.value,new wI({batchSize:MI}),UI(async c=>{await qI(e,t,r,c)})]);return await new Promise((c,_)=>{LI(o,u=>{u?_(u):c()}),o.resume()}),t}catch(s){throw oe(s,Vs(ge.INSERT_JSON_ERR),Ve.INTERNAL_SERVER_ERROR,Nt.LOG_LEVELS.ERROR,ge.INSERT_JSON_ERR+s)}}a(NW,"insertJson");async function GI(e){let t={};try{e.data&&e.data.length>0&&gW(e.data[0])?t=await IW(e.data,e.schema,e.table,e.action):(t.message="No records parsed from csv file.",Fs.info(t.message))}catch(r){throw ks(r)}return t}a(GI,"callBulkFileLoad");function gW(e){let t=Object.keys(e);for(let r of t)if(!EW.test(r))throw new Error(`Invalid column name '${r}', cancelling load operation`);return!0}a(gW,"validateColumnNames");async function IW(e,t,r,s){s||(s="insert");let n={operation:s,schema:t,table:r,records:e},i;switch(s){case"insert":i=B_.insert;break;case"update":i=B_.update;break;case"upsert":i=B_.upsert;break;default:throw oe(new Error,ge.INVALID_ACTION_PARAM_ERR(s),Ve.BAD_REQUEST,Nt.LOG_LEVELS.ERROR,ge.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 _=ia.isEmptyOrZeroLength(c)?0:c.length;return{records:e.length,number_written:_,new_attributes:o.new_attributes}}catch(o){throw ks(o)}}a(IW,"bulkFileLoad");async function FI(e,t,r,s=[]){try{if(t.data.length===0||!Bd.get(Nt.CONFIG_PARAMS.CLUSTERING_ENABLED))return;let n=v_.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 _W(r.txn_time,i,Bd.get(Nt.HDB_SETTINGS_NAMES.CLUSTERING_NODE_NAME_KEY))};await uW.publishToStream(`${nW.SUBJECT_PREFIXES.TXN}.${t.schema}.${t.table}`,lW.createNatsTableStreamName(t.schema,t.table),[o],s),await aW.sendAttributeTransaction(r,t,s),delete r.new_attributes}catch(n){Fs.error(n)}}a(FI,"postCSVLoadFunction");function VI(e,t){return`successfully loaded ${t} of ${e} records`}a(VI,"buildResponseMsg");function ks(e){return oe(e,Vs(ge.DEFAULT_BULK_LOAD_ERR),Ve.INTERNAL_SERVER_ERROR,Nt.LOG_LEVELS.ERROR,ge.DEFAULT_BULK_LOAD_ERR+" - "+e)}a(ks,"buildTopLevelErrMsg")});var Vd=h((z2,ZI)=>{"use strict";var YI=mt(),bW=N_(),CW=Pd(),{AsyncParser:wW,Transform:UW}=require("json2csv"),aa=require("stream"),LW=require("events"),Ht=b(),Fd=require("fs-extra"),yW=require("path"),rt=g(),{promisify:G_}=require("util"),oa=b(),{handleHDBError:Ie,hdb_errors:DW}=D(),{HDB_ERROR_MSGS:gt,HTTP_STATUS_CODES:be}=DW,xI=["search_by_value","search_by_hash","sql"],$I=["json","csv"],KI="json",QI="csv",MW="Successfully exported JSON locally.",PW="Successfully exported CSV locally.",BW=1e3,vW=1e3,HW=G_(YI.searchByHash),qW=G_(YI.searchByValue),GW=G_(bW.evaluateSQL),FW=G_(aa.finished);ZI.exports={export_to_s3:$W,export_local:VW};async function VW(e){rt.trace(`export_local request to path: ${e.path}, filename: ${e.filename}, format: ${e.format}`);let t=WI(e);if(!Ht.isEmpty(t))throw rt.error(t),Ie(new Error,t,be.BAD_REQUEST,void 0,void 0,!0);if(Ht.isEmpty(e.path))throw rt.error(gt.MISSING_VALUE("path")),Ie(new Error,gt.MISSING_VALUE("path"),be.BAD_REQUEST,void 0,void 0,!0);let r=(Ht.isEmpty(e.filename)?new Date().getTime():e.filename)+"."+e.format;e.path.endsWith(yW.sep)&&(e.path=e.path.substring(0,e.path.length-1));let s=Ht.buildFolderPath(e.path,r);try{await kW(e.path);let n=await JI(e);return await xW(s,e.format,n)}catch(n){throw rt.error(n),new Error(n)}}a(VW,"export_local");async function kW(e){if(rt.trace("in confirmPath"),Ht.isEmptyOrZeroLength(e))throw Ie(new Error,`Invalid path: ${e}`,be.BAD_REQUEST,void 0,void 0,!0);let t;try{t=await Fd.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,rt.error(s),Ie(new Error,s,be.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 rt.error(r),Ie(new Error,r,be.BAD_REQUEST,void 0,void 0,!0)}return!0}a(kW,"confirmPath");async function xW(e,t,r){if(rt.trace("in saveToLocal"),oa.isEmptyOrZeroLength(e))throw Ie(new Error,gt.INVALID_VALUE("file_path"),be.BAD_REQUEST,void 0,void 0,!0);if(oa.isEmptyOrZeroLength(t))throw Ie(new Error,gt.INVALID_VALUE("Source format"),be.BAD_REQUEST,void 0,void 0,!0);if(oa.isEmpty(r))throw Ie(new Error,gt.NOT_FOUND("Data"),be.BAD_REQUEST,void 0,void 0,!0);if(t===KI){let s=Fd.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%vW===0&&(s.write(i)||await LW.once(s,"drain"),i="");return i.length!==0&&s.write(i),s.write("]"),s.end(),await FW(s),MW}else if(t===QI){let s=Fd.createWriteStream(e),n=aa.Readable.from(r),i={},o={objectMode:!0};return await new wW(i,o).fromInput(n).toOutput(s).promise(!1),PW}throw Ie(new Error,gt.INVALID_VALUE("format"),be.BAD_REQUEST)}a(xW,"saveToLocal");async function $W(e){if(!e.s3||Object.keys(e.s3).length===0)throw Ie(new Error,gt.MISSING_VALUE("S3 object"),be.BAD_REQUEST);if(Ht.isEmptyOrZeroLength(e.s3.aws_access_key_id))throw Ie(new Error,gt.MISSING_VALUE("aws_access_key_id"),be.BAD_REQUEST);if(Ht.isEmptyOrZeroLength(e.s3.aws_secret_access_key))throw Ie(new Error,gt.MISSING_VALUE("aws_secret_access_key"),be.BAD_REQUEST);if(Ht.isEmptyOrZeroLength(e.s3.bucket))throw Ie(new Error,gt.MISSING_VALUE("bucket"),be.BAD_REQUEST);if(Ht.isEmptyOrZeroLength(e.s3.key))throw Ie(new Error,gt.MISSING_VALUE("key"),be.BAD_REQUEST);let t=WI(e);if(!Ht.isEmpty(t))throw Ie(new Error,t,be.BAD_REQUEST);rt.trace(`called export_to_s3 to bucket: ${e.s3.bucket} and query ${e.search_operation.sql}`);let r;try{r=await JI(e)}catch(c){throw rt.error(c),c}let s,n=CW.getS3AuthObj(e.s3.aws_access_key_id,e.s3.aws_secret_access_key),i,o=new aa.PassThrough;if(e.format===QI){i=e.s3.key+".csv";let c=aa.Readable.from(r),_={},u={objectMode:!0},l=new UW(_,u);l.on("error",E=>{throw E}),c.pipe(l).pipe(o)}else if(e.format===KI){i=e.s3.key+".json";let c=new aa.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%BW===0&&(c.push(u),u="");u.length!==0&&c.push(u),c.push("]"),c.push(null)}else throw Ie(new Error,gt.INVALID_VALUE("format"),be.BAD_REQUEST);try{s=await n.upload({Bucket:e.s3.bucket,Key:i,Body:o}).promise()}catch(c){throw rt.error(c),c}return s}a($W,"export_to_s3");function WI(e){if(rt.trace("in exportCoreValidation"),Ht.isEmpty(e.format))return"format missing";if($I.indexOf(e.format)<0)return`format invalid. must be one of the following values: ${$I.join(", ")}`;let t=e.search_operation.operation;if(Ht.isEmpty(t))return"search_operation.operation missing";if(xI.indexOf(t)<0)return`search_operation.operation must be one of the following values: ${xI.join(", ")}`}a(WI,"exportCoreValidation");async function JI(e){rt.trace("in getRecords");let t,r;if(oa.isEmpty(e.search_operation)||oa.isEmptyOrZeroLength(e.search_operation.operation))throw Ie(new Error,gt.INVALID_VALUE("Search operation"),be.BAD_REQUEST);switch(e.search_operation.operation){case"search_by_value":t=qW;break;case"search_by_hash":t=HW;break;case"sql":t=GW;break;default:throw r=`Operation ${e.search_operation.operation} is not support by export.`,rt.error(r),Ie(new Error,r,be.BAD_REQUEST)}e.search_operation.hdb_user=e.hdb_user;try{return t(e.search_operation)}catch(s){throw rt.error(s),s}}a(JI,"getRecords")});var zI=h((j2,XI)=>{"use strict";var F_=class{constructor(t,r){this.operation="sql",this.sql=t,this.hdb_user=r}};a(F_,"SqlSearchObject");XI.exports=F_});var tb=h((ez,eb)=>{"use strict";var YW=T(),jI=require("moment"),KW=require("uuid").v4,V_=class{constructor(){this.id=KW(),this.type=void 0,this.start_datetime=jI().valueOf(),this.created_datetime=jI().valueOf(),this.end_datetime=void 0,this.status=YW.JOB_STATUS_ENUM.CREATED,this.message=void 0,this.user=void 0,this.request=void 0}};a(V_,"JobObject");eb.exports=V_});var xd=h((tz,ob)=>{"use strict";var QW=require("uuid").v4,nb=yt(),ib=mt(),WW=Qt(),JW=Ss(),ZW=zI(),ce=T(),XW=tb(),zW=Vl(),qt=g(),jW=ti(),kn=b(),{promisify:kd}=require("util"),xs=require("moment"),e1=N_(),k_=Dd(),rb=Ol(),{deleteTransactionLogsBeforeValidator:t1}=Td(),{handleHDBError:r1,hdb_errors:s1}=D(),{HTTP_STATUS_CODES:n1}=s1,sb=kd(ib.searchByValue),i1=kd(ib.searchByHash),a1=nb.insert,o1=kd(e1.evaluateSQL),c1=nb.update;ob.exports={addJob:l1,updateJob:d1,handleGetJob:_1,handleGetJobsByStartDate:u1,getJobById:ab};async function _1(e){try{let t=await ab(e.id);return kn.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 qt.error(r),new Error(r)}}a(_1,"handleGetJob");async function u1(e){try{let t=await E1(e);if(qt.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=xs(r.start_datetime)),r.end_datetime&&(r.end_datetime_converted=xs(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 qt.error(r),new Error(r)}}a(u1,"handleGetJobsByStartDate");async function l1(e){let t={message:"",error:"",success:!1,createdJob:void 0};if(!e||Object.keys(e).length===0||kn.isEmptyOrZeroLength(e.operation)){let l="job parameter is invalid";return qt.info(l),t.error=l,t}if(!ce.JOB_TYPE_ENUM[e.operation])return qt.info(`invalid job type specified: ${e.operation}.`),t;let r=e.operation,s;switch(r){case ce.OPERATIONS_ENUM.CSV_FILE_LOAD:s=k_.fileObject(e);break;case ce.OPERATIONS_ENUM.CSV_URL_LOAD:s=k_.urlObject(e);break;case ce.OPERATIONS_ENUM.CSV_DATA_LOAD:s=k_.dataObject(e);break;case ce.OPERATIONS_ENUM.IMPORT_FROM_S3:s=k_.s3FileObject(e);break;case ce.OPERATIONS_ENUM.DELETE_FILES_BEFORE:case ce.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE:s=rb(e,"date");break;case ce.OPERATIONS_ENUM.DELETE_AUDIT_LOGS_BEFORE:s=rb(e,"timestamp");break;case ce.OPERATIONS_ENUM.DELETE_TRANSACTION_LOGS_BEFORE:s=t1(e);break;default:break}if(s)throw r1(s,s.message,n1.BAD_REQUEST,void 0,void 0,!0);let n=new XW;n.type=e.operation===ce.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE?ce.OPERATIONS_ENUM.DELETE_FILES_BEFORE:e.operation,n.type=e.operation,n.user=e.hdb_user.username;let i=new WW(ce.SYSTEM_SCHEMA_NAME,ce.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,"id",n.id,"id",["id"]),o;try{o=await sb(i)}catch(l){let E=`There was an error inserting a new job: ${l}`;return qt.error(E),t}let c=Array.isArray(o)?o:Object.keys(o);if(c&&c.length>0){n.id=QW();try{o=await sb(i)}catch(l){let E=`There was an error inserting a new job: ${l}`;return qt.error(E),t}if(c=Array.isArray(o)?o:Object.keys(o),c&&c.length>0)return qt.error("Error creating a job, could not find a unique job id."),t}n.request=e;let _=new jW(ce.SYSTEM_SCHEMA_NAME,ce.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,"id",[n]),u;try{u=await a1(_)}catch(l){return qt.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,qt.trace(l)}return t}a(l1,"addJob");async function E1(e){let t=xs(e.from_date,xs.ISO_8601),r=xs(e.to_date,xs.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 ZW(s,e.hdb_user);try{return await o1(n)}catch(i){throw qt.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(E1,"getJobsInDateRange");async function ab(e){if(kn.isEmptyOrZeroLength(e))return kn.errorizeMessage("Invalid job ID specified.");let t=new JW(ce.SYSTEM_SCHEMA_NAME,ce.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,[e],["*"]);try{return await i1(t)}catch(r){let s=`There was an error searching for a job by id: ${e} ${r}`;return qt.error(s),kn.errorizeMessage("there was an error searching for jobs. Please check the log for details.")}}a(ab,"getJobById");async function d1(e){if(Object.keys(e).length===0)throw new Error("invalid job object passed to updateJob");if(kn.isEmptyOrZeroLength(e.id))throw new Error("invalid ID passed to updateJob");(e.status===ce.JOB_STATUS_ENUM.COMPLETE||e.status===ce.JOB_STATUS_ENUM.ERROR)&&(e.end_datetime=xs().valueOf());let t=new zW(ce.SYSTEM_SCHEMA_NAME,ce.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,[e]),r;try{r=await c1(t)}catch(s){throw new Error(s)}return r}a(d1,"updateJob")});var db=h((rz,Eb)=>{"use strict";var cb=b(),It=T(),h1=require("moment"),x_=Gd(),$_=g(),_b=xd(),ub=Vd(),lb=ps(),S1=t_(),f1=Ki(),T1=l_(),Y_=class{constructor(t,r){this.job=t,this.json=r}};a(Y_,"RunnerMessage");async function m1(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(cb.isEmptyOrZeroLength(e.json.operation))throw new Error("Invalid operation");if(cb.isEmptyOrZeroLength(e.job.id))throw new Error("Empty job id specified");switch(e.json.operation){case It.JOB_TYPE_ENUM.csv_file_load:await Dr(e,x_.csvFileLoad);break;case It.JOB_TYPE_ENUM.csv_url_load:await Dr(e,x_.csvURLLoad);break;case It.JOB_TYPE_ENUM.csv_data_load:await Dr(e,x_.csvDataLoad);break;case It.JOB_TYPE_ENUM.import_from_s3:await Dr(e,x_.importFromS3);break;case It.JOB_TYPE_ENUM.empty_trash:break;case It.JOB_TYPE_ENUM.export_local:await Dr(e,ub.export_local);break;case It.JOB_TYPE_ENUM.export_to_s3:await Dr(e,ub.export_to_s3);break;case It.JOB_TYPE_ENUM.delete_files_before:case It.JOB_TYPE_ENUM.delete_records_before:await Dr(e,lb.deleteFilesBefore);break;case It.JOB_TYPE_ENUM.delete_audit_logs_before:await Dr(e,lb.deleteAuditLogsBefore);break;case It.JOB_TYPE_ENUM.delete_transaction_logs_before:await Dr(e,T1.deleteTransactionLogsBefore);break;default:return`Invalid operation ${e.json.operation} specified`}}a(m1,"parseMessage");async function Dr(e,t){try{e.job.status=It.JOB_STATUS_ENUM.IN_PROGRESS,e.job.start_datetime=h1().valueOf(),await _b.updateJob(e.job),await R1(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):$_.error(`There was an error running ${t.name} job with id ${e.job.id}`),$_.error(s),e.job.message=s,e.job.status=It.JOB_STATUS_ENUM.ERROR;try{await _b.updateJob(e.job)}catch(n){throw $_.error(`Unable to update job with id ${e.job.id}`),n}throw r}}a(Dr,"runJob");async function R1(e){let t=S1.generateJobConfig(e);$_.trace("launching job process:",e),await f1.start(t)}a(R1,"launchJobProcess");Eb.exports={parseMessage:m1,RunnerMessage:Y_}});var Sb=h((sz,hb)=>{"use strict";var K_=class{constructor(t,r=void 0){this.operation_function=t,this.job_operation_function=r}};a(K_,"OperationFunctionObject");hb.exports=K_});var wb=h((nz,Cb)=>{"use strict";var J_=mt(),Qd=N_(),Q_=Gd(),xn=Ec(),$d=ms(),_a=ps(),A1=dE(),ca=gr(),W_=OE(),Mr=fd(),ke=g(),p1=IE(),O1=Dc(),N1=kE(),g1=vc(),I1=xE(),b1=KE(),Yd=JE(),fb=Vd(),C1=p_(),Wd=xd(),A=T(),{hdb_errors:la,handleHDBError:ua}=D(),{HTTP_STATUS_CODES:Tb}=la,Kd=zE(),mb=ud(),Z_=require("util"),$s=yt(),w1=Kr(),U1=wc(),Ib=On(),Rb=db(),Ab=nc(),pb=Tr(),Ob=l_(),Nb=Ad(),L1=Md(),y1=Z_.promisify(J_.searchByHash),D1=Z_.promisify(J_.searchByValue),M1=Z_.promisify(J_.search),P1=Z_.promisify(Qd.evaluateSQL),B1={[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=Sb();function v1(e,t,r){return Promise.all([Ib.postOperationHandler(e,t,r),e.table?$s.flush(e):null])}a(v1,"postWrite");async function H1(e,t){try{if(e.body.operation!=="read_log"&&(ke.log_level===A.LOG_LEVELS.INFO||ke.log_level===A.LOG_LEVELS.DEBUG||ke.log_level===A.LOG_LEVELS.TRACE)){let{hdb_user:s,hdb_auth_header:n,password:i,...o}=e.body;ke.info(o)}}catch(s){ke.error(s)}let r=A.CLUSTER_OPERATIONS[e.body.operation]===void 0?null:v1;try{let s=await L1.callOperationFunctionAsAwait(t,e.body,r);if(typeof s!="object"&&(s={message:s}),s instanceof Error)throw s;return B1[e.body.operation]&&w1.setSchemaDataToGlobal(n=>{n&&ke.error(n)}),s}catch(s){throw ke.info(s),s}}a(H1,"processLocalTransaction");var gb=F1();Cb.exports={chooseOperation:q1,getOperationFunction:bb,processLocalTransaction:H1};function q1(e){let t;try{t=bb(e)}catch(n){throw ke.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 ke.error(`${Tb.FORBIDDEN} from operation ${e.search_operation}`),ua(new Error,o,la.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=C1.verifyPerms(i,n);if(o)throw ke.error(`${Tb.FORBIDDEN} from operation ${e.operation}`),ua(new Error,o,la.HTTP_STATUS_CODES.FORBIDDEN)}}catch(n){throw ua(n,"There was an error when trying to choose an operation path")}return r}a(q1,"chooseOperation");function bb(e){if(ke.trace(`getOperationFunction with operation: ${e.operation}`),gb.has(e.operation))return gb.get(e.operation);throw ua(new Error,la.HDB_ERROR_MSGS.OP_NOT_FOUND(e.operation),la.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0)}a(bb,"getOperationFunction");async function G1(e){ke.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 $s.insert(i);break;case A.OPERATIONS_ENUM.UPDATE:o=await $s.update(i);break;case A.OPERATIONS_ENUM.UPSERT:o=await $s.upsert(i);break;case A.OPERATIONS_ENUM.DELETE:o=await _a.deleteRecord(i);break;default:ke.warn("invalid operation in catchup");break}await Ib.postOperationHandler(i,o,e)}catch(o){ke.info("Invalid operation in transaction"),ke.error(o)}}a(G1,"catchup");async function lr(e){let t,r;try{r=await Wd.addJob(e),t=r.createdJob;let s=new Rb.RunnerMessage(t,e);return await Rb.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 ke.error(n),ua(s,n)}}a(lr,"executeJob");function F1(){let e=new Map;return e.set(A.OPERATIONS_ENUM.INSERT,new N($s.insert)),e.set(A.OPERATIONS_ENUM.UPDATE,new N($s.update)),e.set(A.OPERATIONS_ENUM.UPSERT,new N($s.upsert)),e.set(A.OPERATIONS_ENUM.SEARCH_BY_CONDITIONS,new N(J_.searchByConditions)),e.set(A.OPERATIONS_ENUM.SEARCH_BY_HASH,new N(y1)),e.set(A.OPERATIONS_ENUM.SEARCH_BY_VALUE,new N(D1)),e.set(A.OPERATIONS_ENUM.SEARCH,new N(M1)),e.set(A.OPERATIONS_ENUM.SQL,new N(P1)),e.set(A.OPERATIONS_ENUM.CSV_DATA_LOAD,new N(lr,Q_.csvDataLoad)),e.set(A.OPERATIONS_ENUM.CSV_FILE_LOAD,new N(lr,Q_.csvFileLoad)),e.set(A.OPERATIONS_ENUM.CSV_URL_LOAD,new N(lr,Q_.csvURLLoad)),e.set(A.OPERATIONS_ENUM.IMPORT_FROM_S3,new N(lr,Q_.importFromS3)),e.set(A.OPERATIONS_ENUM.CREATE_SCHEMA,new N(xn.createSchema)),e.set(A.OPERATIONS_ENUM.CREATE_TABLE,new N(xn.createTable)),e.set(A.OPERATIONS_ENUM.CREATE_ATTRIBUTE,new N(xn.createAttribute)),e.set(A.OPERATIONS_ENUM.DROP_SCHEMA,new N(xn.dropSchema)),e.set(A.OPERATIONS_ENUM.DROP_TABLE,new N(xn.dropTable)),e.set(A.OPERATIONS_ENUM.DROP_ATTRIBUTE,new N(xn.dropAttribute)),e.set(A.OPERATIONS_ENUM.DESCRIBE_SCHEMA,new N($d.describeSchema)),e.set(A.OPERATIONS_ENUM.DESCRIBE_TABLE,new N($d.describeTable)),e.set(A.OPERATIONS_ENUM.DESCRIBE_ALL,new N($d.describeAll)),e.set(A.OPERATIONS_ENUM.DELETE,new N(_a.deleteRecord)),e.set(A.OPERATIONS_ENUM.ADD_USER,new N(ca.addUser)),e.set(A.OPERATIONS_ENUM.ALTER_USER,new N(ca.alterUser)),e.set(A.OPERATIONS_ENUM.DROP_USER,new N(ca.dropUser)),e.set(A.OPERATIONS_ENUM.LIST_USERS,new N(ca.listUsersExternal)),e.set(A.OPERATIONS_ENUM.LIST_ROLES,new N(W_.listRoles)),e.set(A.OPERATIONS_ENUM.ADD_ROLE,new N(W_.addRole)),e.set(A.OPERATIONS_ENUM.ALTER_ROLE,new N(W_.alterRole)),e.set(A.OPERATIONS_ENUM.DROP_ROLE,new N(W_.dropRole)),e.set(A.OPERATIONS_ENUM.USER_INFO,new N(ca.userInfo)),e.set(A.OPERATIONS_ENUM.READ_LOG,new N(p1)),e.set(A.OPERATIONS_ENUM.ADD_NODE,new N(O1)),e.set(A.OPERATIONS_ENUM.UPDATE_NODE,new N(N1)),e.set(A.OPERATIONS_ENUM.REMOVE_NODE,new N(g1)),e.set(A.OPERATIONS_ENUM.CONFIGURE_CLUSTER,new N(I1)),e.set(A.OPERATIONS_ENUM.SET_CONFIGURATION,new N(pb.setConfiguration)),e.set(A.OPERATIONS_ENUM.CLUSTER_STATUS,new N(b1.clusterStatus)),e.set(A.OPERATIONS_ENUM.CLUSTER_SET_ROUTES,new N(Yd.setRoutes)),e.set(A.OPERATIONS_ENUM.CLUSTER_GET_ROUTES,new N(Yd.getRoutes)),e.set(A.OPERATIONS_ENUM.CLUSTER_DELETE_ROUTES,new N(Yd.deleteRoutes)),e.set(A.OPERATIONS_ENUM.EXPORT_TO_S3,new N(lr,fb.export_to_s3)),e.set(A.OPERATIONS_ENUM.DELETE_FILES_BEFORE,new N(lr,_a.deleteFilesBefore)),e.set(A.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE,new N(lr,_a.deleteFilesBefore)),e.set(A.OPERATIONS_ENUM.EXPORT_LOCAL,new N(lr,fb.export_local)),e.set(A.OPERATIONS_ENUM.SEARCH_JOBS_BY_START_DATE,new N(Wd.handleGetJobsByStartDate)),e.set(A.OPERATIONS_ENUM.GET_JOB,new N(Wd.handleGetJob)),e.set(A.OPERATIONS_ENUM.GET_FINGERPRINT,new N(Kd.getFingerprint)),e.set(A.OPERATIONS_ENUM.SET_LICENSE,new N(Kd.setLicense)),e.set(A.OPERATIONS_ENUM.GET_REGISTRATION_INFO,new N(Kd.getRegistrationInfo)),e.set(A.OPERATIONS_ENUM.RESTART,new N(mb.restartProcesses)),e.set(A.OPERATIONS_ENUM.RESTART_SERVICE,new N(mb.restartService)),e.set(A.OPERATIONS_ENUM.CATCHUP,new N(G1)),e.set(A.OPERATIONS_ENUM.SYSTEM_INFORMATION,new N(U1.systemInformation)),e.set(A.OPERATIONS_ENUM.DELETE_AUDIT_LOGS_BEFORE,new N(lr,_a.deleteAuditLogsBefore)),e.set(A.OPERATIONS_ENUM.READ_AUDIT_LOG,new N(A1)),e.set(A.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS,new N(Ab.createTokens)),e.set(A.OPERATIONS_ENUM.REFRESH_OPERATION_TOKEN,new N(Ab.refreshOperationToken)),e.set(A.OPERATIONS_ENUM.GET_CONFIGURATION,new N(pb.getConfiguration)),e.set(A.OPERATIONS_ENUM.CUSTOM_FUNCTIONS_STATUS,new N(Mr.customFunctionsStatus)),e.set(A.OPERATIONS_ENUM.GET_CUSTOM_FUNCTIONS,new N(Mr.getCustomFunctions)),e.set(A.OPERATIONS_ENUM.GET_CUSTOM_FUNCTION,new N(Mr.getCustomFunction)),e.set(A.OPERATIONS_ENUM.SET_CUSTOM_FUNCTION,new N(Mr.setCustomFunction)),e.set(A.OPERATIONS_ENUM.DROP_CUSTOM_FUNCTION,new N(Mr.dropCustomFunction)),e.set(A.OPERATIONS_ENUM.ADD_CUSTOM_FUNCTION_PROJECT,new N(Mr.addCustomFunctionProject)),e.set(A.OPERATIONS_ENUM.DROP_CUSTOM_FUNCTION_PROJECT,new N(Mr.dropCustomFunctionProject)),e.set(A.OPERATIONS_ENUM.PACKAGE_CUSTOM_FUNCTION_PROJECT,new N(Mr.packageCustomFunctionProject)),e.set(A.OPERATIONS_ENUM.DEPLOY_CUSTOM_FUNCTION_PROJECT,new N(Mr.deployCustomFunctionProject)),e.set(A.OPERATIONS_ENUM.READ_TRANSACTION_LOG,new N(Ob.readTransactionLog)),e.set(A.OPERATIONS_ENUM.DELETE_TRANSACTION_LOGS_BEFORE,new N(lr,Ob.deleteTransactionLogsBefore)),e.set(A.OPERATIONS_ENUM.INSTALL_NODE_MODULES,new N(Nb.installModules)),e.set(A.OPERATIONS_ENUM.AUDIT_NODE_MODULES,new N(Nb.auditModules)),e}a(F1,"initializeOperationFunctionMap")});var Zd=h((iz,yb)=>{"use strict";var V1=T(),k1=b(),Er=g(),{handleHDBError:Jd,hdb_errors:X_}=D(),Ub=require("os"),x1=require("util"),$1=Ql(),Y1=x1.promisify($1.authorize),Lb=wb();function K1(e){let t=`Found an uncaught exception with message: ${e.message}. ${Ub.EOL}Stack: ${e.stack} ${Ub.EOL}Terminating HDB.`;console.error(t),Er.fatal(t),process.exit(1)}a(K1,"handleServerUncaughtException");function Q1(){Er.info("beforeExit caught"),process.exit(0)}a(Q1,"handleBeforeExit");function W1(){Er.info("exit caught"),process.exit(0)}a(W1,"handleExit");function J1(){Er.info("SIGINT caught"),process.exit(0)}a(J1,"handleSigint");function Z1(){Er.info("SIGQUIT caught"),process.exit(0)}a(Z1,"handleSigquit");function X1(){Er.info("SIGTERM caught"),process.exit(0)}a(X1,"handleSigterm");function z1(e,t,r){if(Er.error(e),e.http_resp_code)return typeof e.http_resp_msg=="string"?r.code(e.http_resp_code).send({error:e.http_resp_msg}):r.code(e.http_resp_code).send(e.http_resp_msg);let s=e.statusCode?e.statusCode:X_.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR;return typeof e=="string"?r.code(s).send({error:e}):r.code(s).send(e.message?{error:e.message}:e)}a(z1,"serverErrorHandler");function j1(e,t,r){if(!e.body||Object.keys(e.body).length===0||typeof e.body!="object"){let s=Jd(new Error,"Invalid JSON.",X_.HTTP_STATUS_CODES.BAD_REQUEST);r(s,null)}if(k1.isEmpty(e.body.operation)){let s=Jd(new Error,"Request body must include an 'operation' property.",X_.HTTP_STATUS_CODES.BAD_REQUEST);r(s,null)}r()}a(j1,"reqBodyValidationHandler");function eJ(e,t,r){let s;e.body.operation!==V1.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS?Y1(e,t).then(n=>{s=n,e.body.hdb_user=s,e.body.hdb_auth_header=e.headers.authorization,r()}).catch(n=>{Er.warn(n),Er.warn(`{"ip":"${e.socket.remoteAddress}", "error":"${n.stack}"`);let i=typeof n=="string"?{error:n}:{error:n.message};r(Jd(n,i,X_.HTTP_STATUS_CODES.UNAUTHORIZED),null)}):(e.body.hdb_user=null,e.body.hdb_auth_header=e.headers.authorization,r())}a(eJ,"authHandler");async function tJ(e,t=!1){let r;try{return t&&(e.body.operation!=="configure_cluster"||e.body.operation!=="set_configuration")&&(e.body.bypass_auth=t),r=Lb.chooseOperation(e.body),Lb.processLocalTransaction(e,r)}catch(s){throw Er.error(s),s}}a(tJ,"handlePostRequest");yb.exports={authHandler:eJ,handlePostRequest:tJ,handleServerUncaughtException:K1,serverErrorHandler:z1,reqBodyValidationHandler:j1,handleBeforeExit:Q1,handleExit:W1,handleSigint:J1,handleSigquit:Z1,handleSigterm:X1}});var Pb=h((az,Mb)=>{"use strict";var rJ=require("fastify-plugin"),{handlePostRequest:Db,authHandler:sJ,reqBodyValidationHandler:nJ}=Zd();async function iJ(e){e.decorate("hdbCore",{preValidation:[nJ,sJ],request:Db,requestWithoutAuthentication:t=>Db(t,!0)})}a(iJ,"hdbCore");Mb.exports=rJ(iJ)});var vb=h(()=>{"use strict";var aJ=require("util"),oJ=require("path"),oz=require("fast-glob"),z_=require("fs"),cJ=require("fastify"),_J=require("@fastify/cors"),uJ=require("@fastify/static"),lJ=require("@fastify/autoload"),EJ=eh(),Xd=V(),zd=T(),W=g(),dJ=Kr(),hJ=gr(),SJ=SA(),fJ=NA(),{PACKAGE_ROOT:cz}=T(),TJ=bA(),mJ=UA(),RJ=DA(),AJ=aJ.promisify(dJ.setSchemaDataToGlobal),{handleServerUncaughtException:pJ,serverErrorHandler:OJ,handleBeforeExit:NJ,handleExit:gJ,handleSigint:IJ,handleSigquit:bJ,handleSigterm:CJ}=Zd(),wJ="TRUE",j_,Bb=Xd.get(zd.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY);async function UJ(){try{try{global.hdb_ipc=new SJ(process.pid,fJ)}catch(s){throw W.error("Error instantiating new instance of IPC client in Custom Functions server"),W.error(s),s}W.info("In Custom Functions Fastify server"+process.cwd()),W.info(`Custom Functions Running with NODE_ENV set as: ${process.env.NODE_ENV}`),W.debug(`Custom Functions server process ${process.pid} starting up.`),process.on("uncaughtException",pJ),process.on("beforeExit",NJ),process.on("exit",gJ),process.on("SIGINT",IJ),process.on("SIGQUIT",bJ),process.on("SIGTERM",CJ),await LJ();let e=Xd.get(zd.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HTTPS),t=parseInt(Xd.get(zd.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_PORT),10),r=e&&(e===!0||e.toUpperCase()===wJ);try{j_=DJ(r)}catch(s){throw W.error(`Custom Functions buildServer error: ${s}`),s}try{await j_.ready()}catch(s){throw W.error(`Custom Functions server.ready() error: ${s}`),s}try{W.info(`Custom Functions process starting on port ${t}`),await j_.listen({port:t,host:"::"}),W.info(`Custom Functions process running on port ${t}`)}catch(s){throw j_.close(),W.error(`Custom Functions server.listen() error: ${s}`),s}}catch(e){W.error(`Custom Functions ${process.pid} Error: ${e}`),W.error(e),process.exit(1)}}a(UJ,"customFunctionsServer");async function LJ(){try{W.info("Custom Functions starting configuration."),await AJ(),await hJ.setUsersToGlobal(),W.info("Custom Functions completed configuration.")}catch(e){W.error(e)}}a(LJ,"setUp");async function yJ(e){try{W.info("Custom Functions starting buildRoutes"),await e.register(Pb()),await e.after(),z_.readdirSync(Bb,{withFileTypes:!0}).forEach(r=>{if(!r.isDirectory()&&!r.isSymbolicLink())return;let s=r.name,n=oJ.join(Bb,s);W.trace("Loading project folder "+n);let i=`${n}/routes`,o=`${n}/static`,c=`${n}/static/index.html`,_=`/${s}/static`,u=z_.existsSync(i),l=z_.existsSync(o)&&z_.existsSync(c);u&&e.register(lJ,E=>({dir:i,dirNameRoutePrefix:!1,options:{hdbCore:E.hdbCore,logger:W,prefix:`/${s}`}})).after((E,d,S)=>{E&&E.message?W.error(E.message):E&&W.error(E),S()}),l&&(W.info(`Custom Functions setting up webserver for ${s}`),e.register(uJ,{root:o}).after((E,d,S)=>{E&&E.message?W.error(E.message):E&&W.error(E),S()}),e.get(_,(E,d)=>d.sendFile("index.html",o)))}),W.info("Custom Functions completed buildRoutes")}catch(t){W.error(`Custom Functions errored buildRoutes: ${t}`)}}a(yJ,"buildRoutes");function DJ(e){try{W.info("Custom Functions starting buildServer.");let t=TJ(e),r=cJ(t);r.server.headersTimeout=RJ(),r.setErrorHandler(OJ);let s=mJ();return s&&r.register(_J,s),r.register(EJ),r.register(yJ),W.info("Custom Functions completed buildServer."),r}catch(t){W.error(`Custom Functions process ${process.pid} buildServer error: ${t}`),W.fatal(t),process.exit(1)}}a(DJ,"buildServer");(async()=>await UJ())()});vb();
|
|
12
|
+
`,""):null}catch(d){d.stderr?i[_].npm_error=Fg(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 d_.info(`finished installModules with response ${i}`),i}a(jK,"installModules");function Fg(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(Fg,"parseNPMStdErr");async function eQ(e){d_.info(`starting auditModules for request: ${e}`);let t=xg(e);if(t)throw Fn(t,t.message,Vn.BAD_REQUEST);let{projects:r}=e;await Vg(),await kg(r);let s={};for(let n=0,i=r.length;n<i;n++){let o=r[n],c=E_.join(Rd,o);s[o]={npm_output:null,npm_error:null};try{let _=await Gg("npm audit --json",c);s[o].npm_output=JSON.parse(_)}catch(_){s[o].npm_error=Fg(_.stderr)}}return d_.info(`finished auditModules with response ${s}`),s}a(eQ,"auditModules");async function Vg(){try{return await Gg("npm -v"),!0}catch{throw Fn(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(Vg,"checkNPMInstalled");async function kg(e){if(!Array.isArray(e)||e.length===0)throw Fn(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=E_.join(Rd,i.toString());if(!await Bg.pathExists(o)){t.push(i);continue}let _=E_.join(o,"package.json");await Bg.pathExists(_)||r.push(i)}if(t.length>0)throw Fn(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 Fn(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(kg,"checkProjectPaths");function xg(e){let t=l_.object({projects:l_.array().min(1).items(l_.string()).required(),dry_run:l_.boolean().default(!1)});return XK.validateBySchema(e,t)}a(xg,"modulesValidator")});var Kg=h((k2,Yg)=>{"use strict";var h_=class{constructor(t,r,s=[],n=[]){this.schema=t,this.table=r,this.required_table_permissions=s,this.required_attribute_permissions=n}};a(h_,"PermissionTableResponseObject");Yg.exports=h_});var Wg=h((x2,Qg)=>{"use strict";var S_=class{constructor(t,r=[]){this.attribute_name=t,this.required_permissions=r}};a(S_,"PermissionAttributeResponseObject");Qg.exports=S_});var pd=h(($2,Zg)=>{"use strict";var Jg=Kg(),tQ=Wg(),{HDB_ERROR_MSGS:rQ}=Qe(),f_=class{constructor(){this.error=rQ.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 Jg(t,r,s),i=`${t}_${r}`;this.unauthorized_access[i]=n}addUnauthorizedAttributes(t,r,s,n){let i=[];t.forEach(c=>{let _=new tQ(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 Jg(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(f_,"PermissionResponseObject");Zg.exports=f_});var A_=h((Y2,lI)=>{"use strict";var Od=yt(),T_=mt(),vt=Ec(),ji=ms(),Nd=ps(),sQ=EE(),ea=gr(),m_=pE(),Oe=g(),nQ=gE(),iQ=Dc(),aQ=VE(),oQ=vc(),cQ=kE(),_Q=YE(),gd=WE(),Lr=b(),uQ=TN(),Id=XE(),jg=_d(),Bt=T(),eI=Tg(),lQ=wc(),tI=nc(),rI=Tr(),yr=fd(),EQ=require("alasql"),sI=u_(),nI=Ad(),iI=pd(),{handleHDBError:dt,hdb_errors:aI}=D(),{HDB_ERROR_MSGS:Fe,HTTP_STATUS_CODES:Xi}=aI,p=new Map,oI="delete",is="insert",ur="read",qs="update",zi="describe",Xg=ji.describeSchema.name,zg=ji.describeTable.name,cI={delete:!0,deleteRecord:!0,update:!0,updateData:!0,dropAttribute:!0,dropTable:!0,dropSchema:!0,upsert:!0,upsertData:!0},dQ="catchup",hQ="handleGetJob",SQ="handleGetJobsByStartDate",R_={CSV_DATA_LOAD:"csvDataLoad",CSV_URL_LOAD:"csvURLLoad",CSV_FILE_LOAD:"csvFileLoad",IMPORT_FROM_S3:"importFromS3"},fQ=[vt.createTable.name,vt.createAttribute.name,vt.dropTable.name,vt.dropAttribute.name],_I={EXPORT_TO_S3:"export_to_s3",EXPORT_LOCAL:"export_local"},O=class{constructor(t,r){this.requires_su=t,this.perms=r}};a(O,"permission");p.set(Od.insert.name,new O(!1,[is]));p.set(Od.update.name,new O(!1,[qs]));p.set(Od.upsert.name,new O(!1,[is,qs]));p.set(T_.searchByConditions.name,new O(!1,[ur]));p.set(T_.searchByHash.name,new O(!1,[ur]));p.set(T_.searchByValue.name,new O(!1,[ur]));p.set(T_.search.name,new O(!1,[ur]));p.set(vt.createSchema.name,new O(!0,[]));p.set(vt.createTable.name,new O(!0,[]));p.set(vt.createAttribute.name,new O(!1,[is]));p.set(vt.dropSchema.name,new O(!0,[]));p.set(vt.dropTable.name,new O(!0,[]));p.set(vt.dropAttribute.name,new O(!0,[]));p.set(ji.describeSchema.name,new O(!1,[ur]));p.set(ji.describeTable.name,new O(!1,[ur]));p.set(Nd.deleteRecord.name,new O(!1,[oI]));p.set(ea.addUser.name,new O(!0,[]));p.set(ea.alterUser.name,new O(!0,[]));p.set(ea.dropUser.name,new O(!0,[]));p.set(ea.listUsersExternal.name,new O(!0,[]));p.set(m_.listRoles.name,new O(!0,[]));p.set(m_.addRole.name,new O(!0,[]));p.set(m_.alterRole.name,new O(!0,[]));p.set(m_.dropRole.name,new O(!0,[]));p.set(nQ.name,new O(!0,[]));p.set(iQ.name,new O(!0,[]));p.set(aQ.name,new O(!0,[]));p.set(oQ.name,new O(!0,[]));p.set(cQ.name,new O(!0,[]));p.set(gd.setRoutes.name,new O(!0,[]));p.set(gd.getRoutes.name,new O(!0,[]));p.set(gd.deleteRoutes.name,new O(!0,[]));p.set(rI.setConfiguration.name,new O(!0,[]));p.set(_Q.clusterStatus.name,new O(!0,[]));p.set(Id.getFingerprint.name,new O(!0,[]));p.set(Id.setLicense.name,new O(!0,[]));p.set(Nd.deleteFilesBefore.name,new O(!0,[]));p.set(Nd.deleteAuditLogsBefore.name,new O(!0,[]));p.set(jg.restartProcesses.name,new O(!0,[]));p.set(jg.restartService.name,new O(!0,[]));p.set(sQ.name,new O(!0,[]));p.set(lQ.systemInformation.name,new O(!0,[]));p.set(rI.getConfiguration.name,new O(!0,[]));p.set(sI.readTransactionLog.name,new O(!0,[]));p.set(sI.deleteTransactionLogsBefore.name,new O(!0,[]));p.set(nI.installModules.name,new O(!0,[]));p.set(nI.auditModules.name,new O(!0,[]));p.set(tI.createTokens.name,new O(!1,[]));p.set(tI.refreshOperationToken.name,new O(!1,[]));p.set(yr.customFunctionsStatus.name,new O(!0,[]));p.set(yr.getCustomFunctions.name,new O(!0,[]));p.set(yr.getCustomFunction.name,new O(!0,[]));p.set(yr.setCustomFunction.name,new O(!0,[]));p.set(yr.dropCustomFunction.name,new O(!0,[]));p.set(yr.addCustomFunctionProject.name,new O(!0,[]));p.set(yr.dropCustomFunctionProject.name,new O(!0,[]));p.set(yr.packageCustomFunctionProject.name,new O(!0,[]));p.set(yr.deployCustomFunctionProject.name,new O(!0,[]));p.set(Id.getRegistrationInfo.name,new O(!1,[]));p.set(ea.userInfo.name,new O(!1,[]));p.set(ji.describeAll.name,new O(!1,[]));p.set(hQ,new O(!1,[]));p.set(SQ,new O(!0,[]));p.set(dQ,new O(!0,[]));p.set(R_.CSV_DATA_LOAD,new O(!1,[is,qs]));p.set(R_.CSV_URL_LOAD,new O(!1,[is,qs]));p.set(R_.CSV_FILE_LOAD,new O(!1,[is,qs]));p.set(R_.IMPORT_FROM_S3,new O(!1,[is,qs]));p.set(_I.EXPORT_TO_S3,new O(!1,[ur]));p.set(_I.EXPORT_LOCAL,new O(!1,[ur]));p.set(Bt.VALID_SQL_OPS_ENUM.DELETE,new O(!1,[oI]));p.set(Bt.VALID_SQL_OPS_ENUM.SELECT,new O(!1,[ur]));p.set(Bt.VALID_SQL_OPS_ENUM.INSERT,new O(!1,[is]));p.set(Bt.VALID_SQL_OPS_ENUM.UPDATE,new O(!1,[qs]));lI.exports={verifyPerms:mQ,verifyPermsAst:TQ,verifyBulkLoadAttributePerms:AQ};function TQ(e,t,r){if(Lr.isEmptyOrZeroLength(e))throw Oe.info("verify_perms_ast has an empty user parameter"),dt(new Error);if(Lr.isEmptyOrZeroLength(t))throw Oe.info("verify_perms_ast has an empty user parameter"),dt(new Error);if(Lr.isEmptyOrZeroLength(r))throw Oe.info("verify_perms_ast has a null operation parameter"),dt(new Error);try{let s=new iI,n=new uQ(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(_&&cI[r])throw dt(new Error,Fe.DROP_SYSTEM,Xi.FORBIDDEN);if(c&&!_)return null;let u=eI.getRolePermissions(t.role);t.role.permission=u,!c&&e instanceof EQ.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=uI(t,r,o,s);return l||(o.forEach((E,d)=>{for(let S=0;S<E.length;S++){let m=n.getAttributesBySchemaTableName(d,E[S]),R=Cd(t.role.permission,d,E[S]);bd(m,R,r,E[S],d,s)}}),s.getPermsResponse())}catch(s){throw dt(s)}}a(TQ,"verifyPermsAst");function mQ(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,Fe.DEFAULT_INVALID_REQUEST,Xi.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 iI;if(Lr.isEmptyOrZeroLength(e.hdb_user.role)||Lr.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(Fe.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(Bt.SYSTEM_SCHEMA_NAME)||n===Bt.SYSTEM_SCHEMA_NAME;if(l&&cI[r])throw dt(new Error,Fe.DROP_SYSTEM,Xi.FORBIDDEN);if(_&&!l||u===!0&&(r===vt.createSchema.name||r===vt.dropSchema.name))return null;if(fQ.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=eI.getRolePermissions(e.hdb_user.role);if(e.hdb_user.role.permission=E,r===Xg||r===zg){if(n===Bt.SYSTEM_SCHEMA_NAME)return c.handleUnauthorizedItem(Fe.SCHEMA_PERM_ERROR(n));if(!E.super_user){if(r===Xg&&(!E[n]||!E[n][zi]))return c.handleInvalidItem(Fe.SCHEMA_NOT_FOUND(n));if(r===zg&&(!E[n]||!E[n].tables[i]||!E[n].tables[i][zi]))return c.handleInvalidItem(Fe.TABLE_NOT_FOUND(n,i))}}let d=uI(e.hdb_user,r,o,c,s);if(d)return d;if(p.get(r)&&p.get(r).perms.length===0)return null;if(!_&&e.get_attributes&&Bt.SEARCH_WILDCARDS.includes(e.get_attributes[0])){let R=[],w=E[n].tables[i];w[Bt.PERMS_CRUD_ENUM.READ]&&(w.attribute_permissions.length>0?w.attribute_permissions.filter(B=>B[Bt.PERMS_CRUD_ENUM.READ]).forEach(B=>{R.push(B.attribute_name)}):R=global.hdb_schema[n][i].attributes.map(U=>U.attribute),e.get_attributes=R)}let S=RQ(e),m=Cd(e.hdb_user.role.permission,n,i);return bd(S,m,r,i,n,c,s),c.getPermsResponse()}a(mQ,"verifyPerms");function uI(e,t,r,s,n){if(Lr.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(!p.get(t))throw Oe.info(`operation ${t} not found.`),dt(new Error,Fe.OP_NOT_FOUND(t),Xi.BAD_REQUEST);if(p.get(t)&&p.get(t).requires_su)return Oe.info(`operation ${t} requires SU permissions.`),s.handleUnauthorizedItem(Fe.OP_IS_SU_ONLY(t));let c=r.keys();for(let _ of c){try{if(_&&!o[_]||o[_][zi]===!1){s.addInvalidItem(Fe.SCHEMA_NOT_FOUND(_));continue}}catch{s.addInvalidItem(Fe.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(Fe.TABLE_NOT_FOUND(_,l));else try{let d=[],S=p.get(t).perms;!Lr.isEmpty(n)&&S.includes(n)&&(S=[n]);for(let m=0;m<S.length;m++){let R=S[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 S=Fe.UNKNOWN_OP_AUTH_ERROR(t,_,l);throw Oe.error(S),Oe.error(d),dt(aI.CHECK_LOGS_WRAPPER(S))}}}return r.size<2?s.getPermsResponse():null}a(uI,"hasPermissions");function bd(e,t,r,s,n,i,o){if(!e||!t)throw Oe.info("no attributes specified in checkAttributePerms."),dt(new Error);let c=p.get(r).perms;if(!c||c==="")throw Oe.info(`no permissions found for ${r} in checkAttributePerms().`),dt(new Error);if(Lr.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(Fe.ATTR_NOT_FOUND(n,s,l),n,s);continue}if(c)for(let d of c){if(Bt.TIME_STAMP_NAMES.includes(E.attribute_name)&&d!==ur)throw dt(new Error,Fe.SYSTEM_TIMESTAMP_PERMS_ERR,Xi.FORBIDDEN);E[d]===!1&&(_[E.attribute_name]?_[E.attribute_name].push(d):_[E.attribute_name]=[d])}}else i.addInvalidItem(Fe.ATTR_NOT_FOUND(n,s,l),n,s)}let u=Object.keys(_);u.length>0&&i.addUnauthorizedAttributes(u,n,s,_)}a(bd,"checkAttributePerms");function RQ(e){let t=new Set;try{if(e.action)return t;if(e.operation===Bt.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(RQ,"getRecordAttributes");function Cd(e,t,r){let s=new Map;if(Lr.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(Cd,"getAttributePermissions");function AQ(e,t,r,s,n,i,o){let c=new Set(i),_=Cd(e,s,n);bd(c,_,t,n,s,o,r)}a(AQ,"verifyBulkLoadAttributePerms")});var O_=h((K2,fI)=>{"use strict";fI.exports={evaluateSQL:BQ,processAST:SI,convertSQLToAST:hI,checkASTPermissions:dI};var EI=yt(),Ld=require("util"),pQ=Ld.callbackify(EI.insert),OQ=mt().search,NQ=Ap().update,gQ=Ld.callbackify(NQ),IQ=Op().convertDelete,as=require("alasql"),bQ=A_(),ra=g(),CQ=yo(),wQ=b(),ta=T(),{hdb_errors:UQ,handleHDBError:wd}=D(),{HTTP_STATUS_CODES:Ud}=UQ,LQ=On();function yQ(e,t,r){return Promise.all([LQ.postOperationHandler(e,t,r),EI.flush(e)])}a(yQ,"postWrite");var DQ=Ld.callbackify(yQ);CQ(as);var MQ=403,PQ="There was a problem performing this insert. Please check the logs and try again.",p_=class{constructor(){this.ast=void 0,this.variant=void 0,this.permissions_checked=!1}};a(p_,"ParsedSQLObject");function BQ(e,t){let r=e.parsed_sql_object;if(!r){r=hI(e.sql);let s,n=r.ast.statements[0];if(n instanceof as.yy.Insert?s=n.into.databaseid:n instanceof as.yy.Select?s=n.from?n.from[0].databaseid:null:n instanceof as.yy.Update||n instanceof as.yy.Delete?s=n.table.databaseid:ra.error("AST in evaluateSQL is not a valid SQL type."),!(n instanceof as.yy.Select)&&wQ.isEmptyOrZeroLength(s))return t("No schema specified",null)}SI(e,r,(s,n)=>{if(s)return t(s);t(null,n)})}a(BQ,"evaluateSQL");function dI(e,t){let r;try{r=bQ.verifyPermsAst(t.ast.statements[0],e.hdb_user,t.variant),t.permissions_checked=!0}catch(s){throw s}return r||null}a(dI,"checkASTPermissions");function hI(e){let t=new p_;if(!e)throw wd(new Error,"The 'sql' parameter is missing from the request body",Ud.BAD_REQUEST);try{let r=e.trim(),s=as.parse(r),n=r.split(" ")[0].toLowerCase();t.ast=s,t.variant=n}catch(r){let s=r.message.split(`
|
|
14
|
+
`);throw s[1]?wd(r,`Invalid SQL at: ${s[1]}. Please ensure your SQL is valid. Try adding backticks to reserved words and schema table references.`,Ud.BAD_REQUEST):wd(r,"We had trouble parsing your request. Please ensure your SQL is valid. Try adding backticks to reserved words and schema table references.",Ud.BAD_REQUEST)}return t}a(hI,"convertSQLToAST");function SI(e,t,r){try{let s=vQ;if(!e.bypass_auth&&!t.permissions_checked){let i=dI(e,t);if(i&&i.length>0)return r(MQ,i)}let n={statement:t.ast.statements[0],hdb_user:e.hdb_user};switch(t.variant){case ta.VALID_SQL_OPS_ENUM.SELECT:s=OQ,n=t.ast.statements[0];break;case ta.VALID_SQL_OPS_ENUM.INSERT:s=HQ;break;case ta.VALID_SQL_OPS_ENUM.UPDATE:s=gQ;break;case ta.VALID_SQL_OPS_ENUM.DELETE:s=IQ;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(SI,"processAST");function vQ(e,t){ra.info(e),t("unknown sql statement")}a(vQ,"nullFunction");function HQ({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=qQ(i,e.values)}catch(o){return r(o)}pQ(n,(o,c)=>{if(o)return r(o);DQ(n,c,_=>{_&&ra.error(_)});try{delete c.new_attributes,delete c.txn_time}catch(_){ra.error(`Error delete new_attributes from insert response: ${_}`)}r(null,c)})}a(HQ,"convertInsert");function qQ(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]]=as.compile(`SELECT ${n.toString()} AS [${ta.FUNC_VAL}] FROM ?`)}),s})}catch(r){throw ra.error(r),new Error(PQ)}}a(qQ,"createDataObjects")});var Dd=h((Q2,pI)=>{var C_=require("clone"),w_=de(),GQ=b(),b_=T(),FQ=g(),N_=require("fs"),{hdb_errors:VQ,handleHDBError:sa}=D(),{HDB_ERROR_MSGS:kQ,HTTP_STATUS_CODES:g_}=VQ,{common_validators:I_}=Rr(),TI=1e9,yd=" is required",xQ=["insert","update","upsert"],U_={schema:{presence:!0,format:I_.schema_format,length:I_.schema_length},table:{presence:!0,format:I_.schema_format,length:I_.schema_length},action:{inclusion:{within:xQ,message:"is required and must be either insert, update, or upsert"}},file_path:{},csv_url:{url:{allowLocal:!0}},data:{}},{AWS_ACCESS_KEY:$Q,AWS_SECRET:YQ,AWS_BUCKET:KQ,AWS_FILE_KEY:QQ}=b_.S3_BUCKET_AUTH_KEYS,WQ={s3:{presence:!0},[`s3.${$Q}`]:{presence:!0,type:"String"},[`s3.${YQ}`]:{presence:!0,type:"String"},[`s3.${KQ}`]:{presence:!0,type:"String"},[`s3.${QQ}`]:{presence:!0,type:"String",hasValidFileExt:[".csv",".json"]}},mI=C_(U_);mI.data.presence={message:yd};var RI=C_(U_);RI.file_path.presence={message:yd};var JQ=Object.assign(C_(U_),WQ),AI=C_(U_);AI.csv_url.presence={message:yd};function ZQ(e){let t=w_.validateObject(e,mI);return L_(e,t)}a(ZQ,"dataObject");function XQ(e){let t=w_.validateObject(e,AI);return L_(e,t)}a(XQ,"urlObject");function zQ(e){let t=w_.validateObject(e,RI);return L_(e,t)}a(zQ,"fileObject");function jQ(e){let t=w_.validateObject(e,JQ);return L_(e,t)}a(jQ,"s3FileObject");function L_(e,t){if(!t){let r=GQ.checkGlobalSchemaTable(e.schema,e.table);if(r)return sa(new Error,r,g_.BAD_REQUEST);if(e.operation===b_.OPERATIONS_ENUM.CSV_FILE_LOAD){try{N_.accessSync(e.file_path,N_.constants.R_OK|N_.constants.F_OK)}catch(s){return s.code===b_.NODE_ERROR_CODES.ENOENT?sa(s,`No such file or directory ${s.path}`,g_.BAD_REQUEST):s.code===b_.NODE_ERROR_CODES.EACCES?sa(s,`Permission denied ${s.path}`,g_.BAD_REQUEST):sa(s)}try{let s=N_.statSync(e.file_path).size;if(s>TI)return sa(new Error,kQ.MAX_FILE_SIZE_ERR(s,TI),g_.BAD_REQUEST)}catch(s){FQ.error(s),console.error(s)}}}return t}a(L_,"postValidateChecks");pI.exports={dataObject:ZQ,urlObject:XQ,fileObject:zQ,s3FileObject:jQ}});var Md=h((W2,OI)=>{"use strict";var na=g(),y_=T();async function eW(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===y_.OPERATIONS_ENUM.INSERT||t.operation===y_.OPERATIONS_ENUM.UPDATE||t.operation===y_.OPERATIONS_ENUM.UPSERT?(delete n.new_attributes,delete n.txn_time):t.operation===y_.OPERATIONS_ENUM.DELETE&&delete n.txn_time,n}catch(i){throw i.message&&typeof i.message=="string"&&i.message.includes("already exists")?(na.info(i.message),i):i.http_resp_msg?(na.error(`Error calling operation: ${e.name}`),na.error(i.http_resp_msg),i):(na.error(`Error calling operation: ${e.name}`),na.error(i),i)}}a(eW,"callOperationFunctionAsAwait");OI.exports={callOperationFunctionAsAwait:eW}});var Pd=h((J2,gI)=>{"use strict";var tW=require("aws-sdk/clients/s3");gI.exports={getFileStreamFromS3:rW,getS3AuthObj:NI};function rW(e){let{s3:t}=e,r={Bucket:t.bucket,Key:t.key};return NI(t.aws_access_key_id,t.aws_secret_access_key).getObject(r).createReadStream()}a(rW,"getFileStreamFromS3");function NI(e,t){return new tW({accessKeyId:e,secretAccessKey:t})}a(NI,"getS3AuthObj")});var bI=h((Z2,II)=>{"use strict";var D_=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(D_,"BulkLoadFileObject");var M_=class{constructor(t,r,s,n){this.action=t,this.schema=r,this.table=s,this.data=n}};a(M_,"BulkLoadDataObject");II.exports={BulkLoadFileObject:D_,BulkLoadDataObject:M_}});var Gd=h((X2,xI)=>{"use strict";var P_=yt(),H_=Dd(),sW=require("needle"),Nt=T(),nW=Se(),ia=b(),{handleHDBError:oe,hdb_errors:BI}=D(),{HTTP_STATUS_CODES:Ve,HDB_ERROR_MSGS:Ne,CHECK_LOGS_WRAPPER:Vs}=BI,Fs=g(),B_=require("papaparse");ia.promisifyPapaParse();var Zt=require("fs-extra"),iW=require("path"),{chain:CI}=require("stream-chain"),wI=require("stream-json/streamers/StreamArray"),UI=require("stream-json/utils/Batch"),LI=require("stream-chain/utils/comp"),{finished:yI}=require("stream"),Bd=V(),aW=On(),vI=Md(),oW=Pd(),{BulkLoadFileObject:vd,BulkLoadDataObject:cW}=bI(),Hd=pd(),{verifyBulkLoadAttributePerms:HI}=A_(),_W=nE(),uW=At(),lW=$r(),DI="No records parsed from csv file.",Gs=`${Bd.get("HDB_ROOT")}/tmp`,{schema_regex:EW}=Rr(),MI=1024*1024*5,PI=5e3,dW={"text/csv":!0,"application/octet-stream":!0,"text/plain":!0,"application/vnd.ms-excel":!0};xI.exports={csvDataLoad:hW,csvURLLoad:SW,csvFileLoad:fW,importFromS3:TW};async function hW(e,t=[]){let r=H_.dataObject(e);if(r)throw oe(r,r.message,Ve.BAD_REQUEST,void 0,void 0,!0);let s={};try{let n=B_.parse(e.data,{header:!0,skipEmptyLines:!0,dynamicTyping:!0}),i=new Hd;e.hdb_user&&e.hdb_user.role&&e.hdb_user.role.permission&&e.hdb_user.role.permission.super_user!==!0&&HI(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 oe(new Error,o,Ve.BAD_REQUEST,void 0,void 0,!0);let c=new cW(e.action,e.schema,e.table,n.data);return s=await vI.callOperationFunctionAsAwait(FI,c,VI.bind(null,n.meta.fields),t),s.message===DI?DI:kI(s.records,s.number_written)}catch(n){throw ks(n)}}a(hW,"csvDataLoad");async function SW(e){let t=H_.urlObject(e);if(t)throw oe(t,t.message,Ve.BAD_REQUEST,void 0,void 0,!0);let r=`${Date.now()}.csv`,s=`${Gs}/${r}`;try{await mW(e.csv_url,r)}catch(n){throw Fs.error(Ne.DOWNLOAD_FILE_ERR(r)+" - "+n),oe(n,Vs(Ne.DOWNLOAD_FILE_ERR(r)))}try{let n=new vd(this.job_operation_function.name,e.action,e.schema,e.table,s,Nt.VALID_S3_FILE_TYPES.CSV,e.hdb_user.role.permission),i=await qd(n);return await v_(s),i}catch(n){throw await v_(s),ks(n)}}a(SW,"csvURLLoad");async function fW(e){let t=H_.fileObject(e);if(t)throw oe(t,t.message,Ve.BAD_REQUEST,void 0,void 0,!0);let r=new vd(this.job_operation_function.name,e.action,e.schema,e.table,e.file_path,Nt.VALID_S3_FILE_TYPES.CSV,e.hdb_user.role.permission);try{return await qd(r)}catch(s){throw ks(s)}}a(fW,"csvFileLoad");async function TW(e){let t=H_.s3FileObject(e);if(t)throw oe(t,t.message,Ve.BAD_REQUEST,void 0,void 0,!0);let r;try{let s=iW.extname(e.s3.key),n=`${Date.now()}${s}`;r=`${Gs}/${n}`;let i=new vd(this.job_operation_function.name,e.action,e.schema,e.table,r,s,e.hdb_user.role.permission);await RW(n,e);let o=await qd(i);return await v_(r),o}catch(s){throw await v_(r),ks(s)}}a(TW,"importFromS3");async function mW(e,t){let r;try{r=await sW("get",e)}catch(s){let n=`Error downloading CSV file from ${e}, status code: ${s.statusCode}. Check the log for more information.`;throw oe(s,n,s.statusCode,Nt.LOG_LEVELS.ERROR,"Error downloading CSV file - "+s)}pW(r,e),await AW(t,r.raw)}a(mW,"downloadCSVFile");async function RW(e,t){try{let r=`${Gs}/${e}`;await Zt.mkdirp(Gs),await Zt.writeFile(`${Gs}/${e}`,"",{flag:"a+"});let s=await Zt.createWriteStream(r),n=oW.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(){Fs.info(`${t.s3.key} successfully downloaded to ${r}`),i()})})}catch(r){throw Fs.error(Ne.S3_DOWNLOAD_ERR+" - "+r),oe(r,Vs(Ne.S3_DOWNLOAD_ERR))}}a(RW,"downloadFileFromS3");async function AW(e,t){try{await Zt.mkdirp(Gs),await Zt.writeFile(`${Gs}/${e}`,t)}catch(r){throw Fs.error(Ne.WRITE_TEMP_FILE_ERR),oe(r,Vs(Ne.DEFAULT_BULK_LOAD_ERR))}}a(AW,"writeFileToTempFolder");async function v_(e){if(e)try{await Zt.access(e),await Zt.unlink(e)}catch{Fs.warn(`could not delete temp csv file at ${e}, file does not exist`)}}a(v_,"deleteTempFile");function pW(e,t){if(e.statusCode!==BI.HTTP_STATUS_CODES.OK)throw oe(new Error,`CSV Load failed from URL: ${t}, status code: ${e.statusCode}, message: ${e.statusMessage}`,Ve.BAD_REQUEST);if(!dW[e.headers["content-type"]])throw oe(new Error,`CSV Load failed from URL: ${t}, unsupported content type: ${e.headers["content-type"]}`,Ve.BAD_REQUEST);if(!e.raw)throw oe(new Error,`CSV Load failed from URL: ${t}, no csv found at url`,Ve.BAD_REQUEST)}a(pW,"validateURLResponse");async function qd(e){try{let t;switch(e.file_type){case Nt.VALID_S3_FILE_TYPES.CSV:t=await OW(e);break;case Nt.VALID_S3_FILE_TYPES.JSON:t=await NW(e);break;default:throw oe(new Error,Ne.DEFAULT_BULK_LOAD_ERR,Ve.BAD_REQUEST,Nt.LOG_LEVELS.ERROR,Ne.INVALID_FILE_EXT_ERR(e))}return kI(t.records,t.number_written)}catch(t){throw ks(t)}}a(qd,"fileLoad");async function qI(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 P_.validation(o);e.role_perms&&e.role_perms.super_user!==!0&&HI(e.role_perms,e.op,e.action,e.schema,e.table,c,t),n&&n.resume()}catch(c){let _=oe(c);r(_)}}a(qI,"validateChunk");async function GI(e,t,r,s,n){let i=s.data?s.data:s;if(i.length===0)return;ia.autoCastJSONDeep(i),n&&n.pause();let o=s.meta?s.meta.fields:null;if(o)i.forEach(c=>{!ia.isEmpty(c)&&!ia.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 vI.callOperationFunctionAsAwait(FI,c,VI.bind(null,o));t.records+=_.records,t.number_written+=_.number_written,n&&n.resume()}catch(c){let _=oe(c,Vs(Ne.INSERT_CSV_ERR),Ve.INTERNAL_SERVER_ERROR,Nt.LOG_LEVELS.ERROR,Ne.INSERT_CSV_ERR+" - "+c);r(_)}}a(GI,"insertChunk");async function OW(e){let t={records:0,number_written:0};try{let r=new Hd,s=Zt.createReadStream(e.file_path,{highWaterMark:MI});s.setEncoding("utf8"),await B_.parsePromise(s,qI.bind(null,e,r));let n=r.getPermsResponse();if(n)throw oe(new Error,n,Ve.BAD_REQUEST);return s=Zt.createReadStream(e.file_path,{highWaterMark:MI}),s.setEncoding("utf8"),await B_.parsePromise(s,GI.bind(null,e,t)),s.destroy(),t}catch(r){throw oe(r,Vs(Ne.PAPA_PARSE_ERR),Ve.INTERNAL_SERVER_ERROR,Nt.LOG_LEVELS.ERROR,Ne.PAPA_PARSE_ERR+r)}}a(OW,"callPapaParse");async function NW(e){let t={records:0,number_written:0},r=a(s=>{throw s},"throwErr");try{let s=new Hd,n=CI([Zt.createReadStream(e.file_path,{encoding:"utf-8"}),wI.withParser(),c=>c.value,new UI({batchSize:PI}),LI(async c=>{await qI(e,s,r,c)})]);await new Promise((c,_)=>{yI(n,u=>{u?_(u):c()}),n.resume()});let i=s.getPermsResponse();if(i)throw oe(new Error,i,Ve.BAD_REQUEST);let o=CI([Zt.createReadStream(e.file_path,{encoding:"utf-8"}),wI.withParser(),c=>c.value,new UI({batchSize:PI}),LI(async c=>{await GI(e,t,r,c)})]);return await new Promise((c,_)=>{yI(o,u=>{u?_(u):c()}),o.resume()}),t}catch(s){throw oe(s,Vs(Ne.INSERT_JSON_ERR),Ve.INTERNAL_SERVER_ERROR,Nt.LOG_LEVELS.ERROR,Ne.INSERT_JSON_ERR+s)}}a(NW,"insertJson");async function FI(e){let t={};try{e.data&&e.data.length>0&&gW(e.data[0])?t=await IW(e.data,e.schema,e.table,e.action):(t.message="No records parsed from csv file.",Fs.info(t.message))}catch(r){throw ks(r)}return t}a(FI,"callBulkFileLoad");function gW(e){let t=Object.keys(e);for(let r of t)if(!EW.test(r))throw new Error(`Invalid column name '${r}', cancelling load operation`);return!0}a(gW,"validateColumnNames");async function IW(e,t,r,s){s||(s="insert");let n={operation:s,schema:t,table:r,records:e},i;switch(s){case"insert":i=P_.insert;break;case"update":i=P_.update;break;case"upsert":i=P_.upsert;break;default:throw oe(new Error,Ne.INVALID_ACTION_PARAM_ERR(s),Ve.BAD_REQUEST,Nt.LOG_LEVELS.ERROR,Ne.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 _=ia.isEmptyOrZeroLength(c)?0:c.length;return{records:e.length,number_written:_,new_attributes:o.new_attributes}}catch(o){throw ks(o)}}a(IW,"bulkFileLoad");async function VI(e,t,r,s=[]){try{if(t.data.length===0||!Bd.get(Nt.CONFIG_PARAMS.CLUSTERING_ENABLED))return;let n=B_.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 _W(r.txn_time,i,Bd.get(Nt.HDB_SETTINGS_NAMES.CLUSTERING_NODE_NAME_KEY))};await uW.publishToStream(`${nW.SUBJECT_PREFIXES.TXN}.${t.schema}.${t.table}`,lW.createNatsTableStreamName(t.schema,t.table),[o],s),await aW.sendAttributeTransaction(r,t,s),delete r.new_attributes}catch(n){Fs.error(n)}}a(VI,"postCSVLoadFunction");function kI(e,t){return`successfully loaded ${t} of ${e} records`}a(kI,"buildResponseMsg");function ks(e){return oe(e,Vs(Ne.DEFAULT_BULK_LOAD_ERR),Ve.INTERNAL_SERVER_ERROR,Nt.LOG_LEVELS.ERROR,Ne.DEFAULT_BULK_LOAD_ERR+" - "+e)}a(ks,"buildTopLevelErrMsg")});var Vd=h((z2,XI)=>{"use strict";var KI=mt(),bW=O_(),CW=Pd(),{AsyncParser:wW,Transform:UW}=require("json2csv"),aa=require("stream"),LW=require("events"),Ht=b(),Fd=require("fs-extra"),yW=require("path"),tt=g(),{promisify:q_}=require("util"),oa=b(),{handleHDBError:ge,hdb_errors:DW}=D(),{HDB_ERROR_MSGS:gt,HTTP_STATUS_CODES:Ie}=DW,$I=["search_by_value","search_by_hash","sql"],YI=["json","csv"],QI="json",WI="csv",MW="Successfully exported JSON locally.",PW="Successfully exported CSV locally.",BW=1e3,vW=1e3,HW=q_(KI.searchByHash),qW=q_(KI.searchByValue),GW=q_(bW.evaluateSQL),FW=q_(aa.finished);XI.exports={export_to_s3:$W,export_local:VW};async function VW(e){tt.trace(`export_local request to path: ${e.path}, filename: ${e.filename}, format: ${e.format}`);let t=JI(e);if(!Ht.isEmpty(t))throw tt.error(t),ge(new Error,t,Ie.BAD_REQUEST,void 0,void 0,!0);if(Ht.isEmpty(e.path))throw tt.error(gt.MISSING_VALUE("path")),ge(new Error,gt.MISSING_VALUE("path"),Ie.BAD_REQUEST,void 0,void 0,!0);let r=(Ht.isEmpty(e.filename)?new Date().getTime():e.filename)+"."+e.format;e.path.endsWith(yW.sep)&&(e.path=e.path.substring(0,e.path.length-1));let s=Ht.buildFolderPath(e.path,r);try{await kW(e.path);let n=await ZI(e);return await xW(s,e.format,n)}catch(n){throw tt.error(n),new Error(n)}}a(VW,"export_local");async function kW(e){if(tt.trace("in confirmPath"),Ht.isEmptyOrZeroLength(e))throw ge(new Error,`Invalid path: ${e}`,Ie.BAD_REQUEST,void 0,void 0,!0);let t;try{t=await Fd.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,tt.error(s),ge(new Error,s,Ie.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 tt.error(r),ge(new Error,r,Ie.BAD_REQUEST,void 0,void 0,!0)}return!0}a(kW,"confirmPath");async function xW(e,t,r){if(tt.trace("in saveToLocal"),oa.isEmptyOrZeroLength(e))throw ge(new Error,gt.INVALID_VALUE("file_path"),Ie.BAD_REQUEST,void 0,void 0,!0);if(oa.isEmptyOrZeroLength(t))throw ge(new Error,gt.INVALID_VALUE("Source format"),Ie.BAD_REQUEST,void 0,void 0,!0);if(oa.isEmpty(r))throw ge(new Error,gt.NOT_FOUND("Data"),Ie.BAD_REQUEST,void 0,void 0,!0);if(t===QI){let s=Fd.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%vW===0&&(s.write(i)||await LW.once(s,"drain"),i="");return i.length!==0&&s.write(i),s.write("]"),s.end(),await FW(s),MW}else if(t===WI){let s=Fd.createWriteStream(e),n=aa.Readable.from(r),i={},o={objectMode:!0};return await new wW(i,o).fromInput(n).toOutput(s).promise(!1),PW}throw ge(new Error,gt.INVALID_VALUE("format"),Ie.BAD_REQUEST)}a(xW,"saveToLocal");async function $W(e){if(!e.s3||Object.keys(e.s3).length===0)throw ge(new Error,gt.MISSING_VALUE("S3 object"),Ie.BAD_REQUEST);if(Ht.isEmptyOrZeroLength(e.s3.aws_access_key_id))throw ge(new Error,gt.MISSING_VALUE("aws_access_key_id"),Ie.BAD_REQUEST);if(Ht.isEmptyOrZeroLength(e.s3.aws_secret_access_key))throw ge(new Error,gt.MISSING_VALUE("aws_secret_access_key"),Ie.BAD_REQUEST);if(Ht.isEmptyOrZeroLength(e.s3.bucket))throw ge(new Error,gt.MISSING_VALUE("bucket"),Ie.BAD_REQUEST);if(Ht.isEmptyOrZeroLength(e.s3.key))throw ge(new Error,gt.MISSING_VALUE("key"),Ie.BAD_REQUEST);let t=JI(e);if(!Ht.isEmpty(t))throw ge(new Error,t,Ie.BAD_REQUEST);tt.trace(`called export_to_s3 to bucket: ${e.s3.bucket} and query ${e.search_operation.sql}`);let r;try{r=await ZI(e)}catch(c){throw tt.error(c),c}let s,n=CW.getS3AuthObj(e.s3.aws_access_key_id,e.s3.aws_secret_access_key),i,o=new aa.PassThrough;if(e.format===WI){i=e.s3.key+".csv";let c=aa.Readable.from(r),_={},u={objectMode:!0},l=new UW(_,u);l.on("error",E=>{throw E}),c.pipe(l).pipe(o)}else if(e.format===QI){i=e.s3.key+".json";let c=new aa.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%BW===0&&(c.push(u),u="");u.length!==0&&c.push(u),c.push("]"),c.push(null)}else throw ge(new Error,gt.INVALID_VALUE("format"),Ie.BAD_REQUEST);try{s=await n.upload({Bucket:e.s3.bucket,Key:i,Body:o}).promise()}catch(c){throw tt.error(c),c}return s}a($W,"export_to_s3");function JI(e){if(tt.trace("in exportCoreValidation"),Ht.isEmpty(e.format))return"format missing";if(YI.indexOf(e.format)<0)return`format invalid. must be one of the following values: ${YI.join(", ")}`;let t=e.search_operation.operation;if(Ht.isEmpty(t))return"search_operation.operation missing";if($I.indexOf(t)<0)return`search_operation.operation must be one of the following values: ${$I.join(", ")}`}a(JI,"exportCoreValidation");async function ZI(e){tt.trace("in getRecords");let t,r;if(oa.isEmpty(e.search_operation)||oa.isEmptyOrZeroLength(e.search_operation.operation))throw ge(new Error,gt.INVALID_VALUE("Search operation"),Ie.BAD_REQUEST);switch(e.search_operation.operation){case"search_by_value":t=qW;break;case"search_by_hash":t=HW;break;case"sql":t=GW;break;default:throw r=`Operation ${e.search_operation.operation} is not support by export.`,tt.error(r),ge(new Error,r,Ie.BAD_REQUEST)}e.search_operation.hdb_user=e.hdb_user;try{return t(e.search_operation)}catch(s){throw tt.error(s),s}}a(ZI,"getRecords")});var jI=h((j2,zI)=>{"use strict";var G_=class{constructor(t,r){this.operation="sql",this.sql=t,this.hdb_user=r}};a(G_,"SqlSearchObject");zI.exports=G_});var rb=h((ez,tb)=>{"use strict";var YW=T(),eb=require("moment"),KW=require("uuid").v4,F_=class{constructor(){this.id=KW(),this.type=void 0,this.start_datetime=eb().valueOf(),this.created_datetime=eb().valueOf(),this.end_datetime=void 0,this.status=YW.JOB_STATUS_ENUM.CREATED,this.message=void 0,this.user=void 0,this.request=void 0}};a(F_,"JobObject");tb.exports=F_});var xd=h((tz,cb)=>{"use strict";var QW=require("uuid").v4,ib=yt(),ab=mt(),WW=Qt(),JW=Ss(),ZW=jI(),ce=T(),XW=rb(),zW=Fl(),qt=g(),jW=ti(),kn=b(),{promisify:kd}=require("util"),xs=require("moment"),e1=O_(),V_=Dd(),sb=pl(),{deleteTransactionLogsBeforeValidator:t1}=Td(),{handleHDBError:r1,hdb_errors:s1}=D(),{HTTP_STATUS_CODES:n1}=s1,nb=kd(ab.searchByValue),i1=kd(ab.searchByHash),a1=ib.insert,o1=kd(e1.evaluateSQL),c1=ib.update;cb.exports={addJob:l1,updateJob:d1,handleGetJob:_1,handleGetJobsByStartDate:u1,getJobById:ob};async function _1(e){try{let t=await ob(e.id);return kn.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 qt.error(r),new Error(r)}}a(_1,"handleGetJob");async function u1(e){try{let t=await E1(e);if(qt.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=xs(r.start_datetime)),r.end_datetime&&(r.end_datetime_converted=xs(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 qt.error(r),new Error(r)}}a(u1,"handleGetJobsByStartDate");async function l1(e){let t={message:"",error:"",success:!1,createdJob:void 0};if(!e||Object.keys(e).length===0||kn.isEmptyOrZeroLength(e.operation)){let l="job parameter is invalid";return qt.info(l),t.error=l,t}if(!ce.JOB_TYPE_ENUM[e.operation])return qt.info(`invalid job type specified: ${e.operation}.`),t;let r=e.operation,s;switch(r){case ce.OPERATIONS_ENUM.CSV_FILE_LOAD:s=V_.fileObject(e);break;case ce.OPERATIONS_ENUM.CSV_URL_LOAD:s=V_.urlObject(e);break;case ce.OPERATIONS_ENUM.CSV_DATA_LOAD:s=V_.dataObject(e);break;case ce.OPERATIONS_ENUM.IMPORT_FROM_S3:s=V_.s3FileObject(e);break;case ce.OPERATIONS_ENUM.DELETE_FILES_BEFORE:case ce.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE:s=sb(e,"date");break;case ce.OPERATIONS_ENUM.DELETE_AUDIT_LOGS_BEFORE:s=sb(e,"timestamp");break;case ce.OPERATIONS_ENUM.DELETE_TRANSACTION_LOGS_BEFORE:s=t1(e);break;default:break}if(s)throw r1(s,s.message,n1.BAD_REQUEST,void 0,void 0,!0);let n=new XW;n.type=e.operation===ce.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE?ce.OPERATIONS_ENUM.DELETE_FILES_BEFORE:e.operation,n.type=e.operation,n.user=e.hdb_user.username;let i=new WW(ce.SYSTEM_SCHEMA_NAME,ce.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,"id",n.id,"id",["id"]),o;try{o=await nb(i)}catch(l){let E=`There was an error inserting a new job: ${l}`;return qt.error(E),t}let c=Array.isArray(o)?o:Object.keys(o);if(c&&c.length>0){n.id=QW();try{o=await nb(i)}catch(l){let E=`There was an error inserting a new job: ${l}`;return qt.error(E),t}if(c=Array.isArray(o)?o:Object.keys(o),c&&c.length>0)return qt.error("Error creating a job, could not find a unique job id."),t}n.request=e;let _=new jW(ce.SYSTEM_SCHEMA_NAME,ce.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,"id",[n]),u;try{u=await a1(_)}catch(l){return qt.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,qt.trace(l)}return t}a(l1,"addJob");async function E1(e){let t=xs(e.from_date,xs.ISO_8601),r=xs(e.to_date,xs.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 ZW(s,e.hdb_user);try{return await o1(n)}catch(i){throw qt.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(E1,"getJobsInDateRange");async function ob(e){if(kn.isEmptyOrZeroLength(e))return kn.errorizeMessage("Invalid job ID specified.");let t=new JW(ce.SYSTEM_SCHEMA_NAME,ce.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,[e],["*"]);try{return await i1(t)}catch(r){let s=`There was an error searching for a job by id: ${e} ${r}`;return qt.error(s),kn.errorizeMessage("there was an error searching for jobs. Please check the log for details.")}}a(ob,"getJobById");async function d1(e){if(Object.keys(e).length===0)throw new Error("invalid job object passed to updateJob");if(kn.isEmptyOrZeroLength(e.id))throw new Error("invalid ID passed to updateJob");(e.status===ce.JOB_STATUS_ENUM.COMPLETE||e.status===ce.JOB_STATUS_ENUM.ERROR)&&(e.end_datetime=xs().valueOf());let t=new zW(ce.SYSTEM_SCHEMA_NAME,ce.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,[e]),r;try{r=await c1(t)}catch(s){throw new Error(s)}return r}a(d1,"updateJob")});var hb=h((rz,db)=>{"use strict";var _b=b(),It=T(),h1=require("moment"),k_=Gd(),x_=g(),ub=xd(),lb=Vd(),Eb=ps(),S1=t_(),f1=Ki(),T1=u_(),$_=class{constructor(t,r){this.job=t,this.json=r}};a($_,"RunnerMessage");async function m1(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(_b.isEmptyOrZeroLength(e.json.operation))throw new Error("Invalid operation");if(_b.isEmptyOrZeroLength(e.job.id))throw new Error("Empty job id specified");switch(e.json.operation){case It.JOB_TYPE_ENUM.csv_file_load:await Dr(e,k_.csvFileLoad);break;case It.JOB_TYPE_ENUM.csv_url_load:await Dr(e,k_.csvURLLoad);break;case It.JOB_TYPE_ENUM.csv_data_load:await Dr(e,k_.csvDataLoad);break;case It.JOB_TYPE_ENUM.import_from_s3:await Dr(e,k_.importFromS3);break;case It.JOB_TYPE_ENUM.empty_trash:break;case It.JOB_TYPE_ENUM.export_local:await Dr(e,lb.export_local);break;case It.JOB_TYPE_ENUM.export_to_s3:await Dr(e,lb.export_to_s3);break;case It.JOB_TYPE_ENUM.delete_files_before:case It.JOB_TYPE_ENUM.delete_records_before:await Dr(e,Eb.deleteFilesBefore);break;case It.JOB_TYPE_ENUM.delete_audit_logs_before:await Dr(e,Eb.deleteAuditLogsBefore);break;case It.JOB_TYPE_ENUM.delete_transaction_logs_before:await Dr(e,T1.deleteTransactionLogsBefore);break;default:return`Invalid operation ${e.json.operation} specified`}}a(m1,"parseMessage");async function Dr(e,t){try{e.job.status=It.JOB_STATUS_ENUM.IN_PROGRESS,e.job.start_datetime=h1().valueOf(),await ub.updateJob(e.job),await R1(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):x_.error(`There was an error running ${t.name} job with id ${e.job.id}`),x_.error(s),e.job.message=s,e.job.status=It.JOB_STATUS_ENUM.ERROR;try{await ub.updateJob(e.job)}catch(n){throw x_.error(`Unable to update job with id ${e.job.id}`),n}throw r}}a(Dr,"runJob");async function R1(e){let t=S1.generateJobConfig(e);x_.trace("launching job process:",e),await f1.start(t)}a(R1,"launchJobProcess");db.exports={parseMessage:m1,RunnerMessage:$_}});var fb=h((sz,Sb)=>{"use strict";var Y_=class{constructor(t,r=void 0){this.operation_function=t,this.job_operation_function=r}};a(Y_,"OperationFunctionObject");Sb.exports=Y_});var Ub=h((nz,wb)=>{"use strict";var W_=mt(),Qd=O_(),K_=Gd(),xn=Ec(),$d=ms(),_a=ps(),A1=EE(),ca=gr(),Q_=pE(),Mr=fd(),ke=g(),p1=gE(),O1=Dc(),N1=VE(),g1=vc(),I1=kE(),b1=YE(),Yd=WE(),Tb=Vd(),C1=A_(),Wd=xd(),A=T(),{hdb_errors:la,handleHDBError:ua}=D(),{HTTP_STATUS_CODES:mb}=la,Kd=XE(),Rb=_d(),J_=require("util"),$s=yt(),w1=Kr(),U1=wc(),bb=On(),Ab=hb(),pb=nc(),Ob=Tr(),Nb=u_(),gb=Ad(),L1=Md(),y1=J_.promisify(W_.searchByHash),D1=J_.promisify(W_.searchByValue),M1=J_.promisify(W_.search),P1=J_.promisify(Qd.evaluateSQL),B1={[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=fb();function v1(e,t,r){return Promise.all([bb.postOperationHandler(e,t,r),e.table?$s.flush(e):null])}a(v1,"postWrite");async function H1(e,t){try{if(e.body.operation!=="read_log"&&(ke.log_level===A.LOG_LEVELS.INFO||ke.log_level===A.LOG_LEVELS.DEBUG||ke.log_level===A.LOG_LEVELS.TRACE)){let{hdb_user:s,hdb_auth_header:n,password:i,...o}=e.body;ke.info(o)}}catch(s){ke.error(s)}let r=A.CLUSTER_OPERATIONS[e.body.operation]===void 0?null:v1;try{let s=await L1.callOperationFunctionAsAwait(t,e.body,r);if(typeof s!="object"&&(s={message:s}),s instanceof Error)throw s;return B1[e.body.operation]&&w1.setSchemaDataToGlobal(n=>{n&&ke.error(n)}),s}catch(s){throw ke.info(s),s}}a(H1,"processLocalTransaction");var Ib=F1();wb.exports={chooseOperation:q1,getOperationFunction:Cb,processLocalTransaction:H1};function q1(e){let t;try{t=Cb(e)}catch(n){throw ke.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 ke.error(`${mb.FORBIDDEN} from operation ${e.search_operation}`),ua(new Error,o,la.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=C1.verifyPerms(i,n);if(o)throw ke.error(`${mb.FORBIDDEN} from operation ${e.operation}`),ua(new Error,o,la.HTTP_STATUS_CODES.FORBIDDEN)}}catch(n){throw ua(n,"There was an error when trying to choose an operation path")}return r}a(q1,"chooseOperation");function Cb(e){if(ke.trace(`getOperationFunction with operation: ${e.operation}`),Ib.has(e.operation))return Ib.get(e.operation);throw ua(new Error,la.HDB_ERROR_MSGS.OP_NOT_FOUND(e.operation),la.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0)}a(Cb,"getOperationFunction");async function G1(e){ke.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 $s.insert(i);break;case A.OPERATIONS_ENUM.UPDATE:o=await $s.update(i);break;case A.OPERATIONS_ENUM.UPSERT:o=await $s.upsert(i);break;case A.OPERATIONS_ENUM.DELETE:o=await _a.deleteRecord(i);break;default:ke.warn("invalid operation in catchup");break}await bb.postOperationHandler(i,o,e)}catch(o){ke.info("Invalid operation in transaction"),ke.error(o)}}a(G1,"catchup");async function lr(e){let t,r;try{r=await Wd.addJob(e),t=r.createdJob;let s=new Ab.RunnerMessage(t,e);return await Ab.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 ke.error(n),ua(s,n)}}a(lr,"executeJob");function F1(){let e=new Map;return e.set(A.OPERATIONS_ENUM.INSERT,new N($s.insert)),e.set(A.OPERATIONS_ENUM.UPDATE,new N($s.update)),e.set(A.OPERATIONS_ENUM.UPSERT,new N($s.upsert)),e.set(A.OPERATIONS_ENUM.SEARCH_BY_CONDITIONS,new N(W_.searchByConditions)),e.set(A.OPERATIONS_ENUM.SEARCH_BY_HASH,new N(y1)),e.set(A.OPERATIONS_ENUM.SEARCH_BY_VALUE,new N(D1)),e.set(A.OPERATIONS_ENUM.SEARCH,new N(M1)),e.set(A.OPERATIONS_ENUM.SQL,new N(P1)),e.set(A.OPERATIONS_ENUM.CSV_DATA_LOAD,new N(lr,K_.csvDataLoad)),e.set(A.OPERATIONS_ENUM.CSV_FILE_LOAD,new N(lr,K_.csvFileLoad)),e.set(A.OPERATIONS_ENUM.CSV_URL_LOAD,new N(lr,K_.csvURLLoad)),e.set(A.OPERATIONS_ENUM.IMPORT_FROM_S3,new N(lr,K_.importFromS3)),e.set(A.OPERATIONS_ENUM.CREATE_SCHEMA,new N(xn.createSchema)),e.set(A.OPERATIONS_ENUM.CREATE_TABLE,new N(xn.createTable)),e.set(A.OPERATIONS_ENUM.CREATE_ATTRIBUTE,new N(xn.createAttribute)),e.set(A.OPERATIONS_ENUM.DROP_SCHEMA,new N(xn.dropSchema)),e.set(A.OPERATIONS_ENUM.DROP_TABLE,new N(xn.dropTable)),e.set(A.OPERATIONS_ENUM.DROP_ATTRIBUTE,new N(xn.dropAttribute)),e.set(A.OPERATIONS_ENUM.DESCRIBE_SCHEMA,new N($d.describeSchema)),e.set(A.OPERATIONS_ENUM.DESCRIBE_TABLE,new N($d.describeTable)),e.set(A.OPERATIONS_ENUM.DESCRIBE_ALL,new N($d.describeAll)),e.set(A.OPERATIONS_ENUM.DELETE,new N(_a.deleteRecord)),e.set(A.OPERATIONS_ENUM.ADD_USER,new N(ca.addUser)),e.set(A.OPERATIONS_ENUM.ALTER_USER,new N(ca.alterUser)),e.set(A.OPERATIONS_ENUM.DROP_USER,new N(ca.dropUser)),e.set(A.OPERATIONS_ENUM.LIST_USERS,new N(ca.listUsersExternal)),e.set(A.OPERATIONS_ENUM.LIST_ROLES,new N(Q_.listRoles)),e.set(A.OPERATIONS_ENUM.ADD_ROLE,new N(Q_.addRole)),e.set(A.OPERATIONS_ENUM.ALTER_ROLE,new N(Q_.alterRole)),e.set(A.OPERATIONS_ENUM.DROP_ROLE,new N(Q_.dropRole)),e.set(A.OPERATIONS_ENUM.USER_INFO,new N(ca.userInfo)),e.set(A.OPERATIONS_ENUM.READ_LOG,new N(p1)),e.set(A.OPERATIONS_ENUM.ADD_NODE,new N(O1)),e.set(A.OPERATIONS_ENUM.UPDATE_NODE,new N(N1)),e.set(A.OPERATIONS_ENUM.REMOVE_NODE,new N(g1)),e.set(A.OPERATIONS_ENUM.CONFIGURE_CLUSTER,new N(I1)),e.set(A.OPERATIONS_ENUM.SET_CONFIGURATION,new N(Ob.setConfiguration)),e.set(A.OPERATIONS_ENUM.CLUSTER_STATUS,new N(b1.clusterStatus)),e.set(A.OPERATIONS_ENUM.CLUSTER_SET_ROUTES,new N(Yd.setRoutes)),e.set(A.OPERATIONS_ENUM.CLUSTER_GET_ROUTES,new N(Yd.getRoutes)),e.set(A.OPERATIONS_ENUM.CLUSTER_DELETE_ROUTES,new N(Yd.deleteRoutes)),e.set(A.OPERATIONS_ENUM.EXPORT_TO_S3,new N(lr,Tb.export_to_s3)),e.set(A.OPERATIONS_ENUM.DELETE_FILES_BEFORE,new N(lr,_a.deleteFilesBefore)),e.set(A.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE,new N(lr,_a.deleteFilesBefore)),e.set(A.OPERATIONS_ENUM.EXPORT_LOCAL,new N(lr,Tb.export_local)),e.set(A.OPERATIONS_ENUM.SEARCH_JOBS_BY_START_DATE,new N(Wd.handleGetJobsByStartDate)),e.set(A.OPERATIONS_ENUM.GET_JOB,new N(Wd.handleGetJob)),e.set(A.OPERATIONS_ENUM.GET_FINGERPRINT,new N(Kd.getFingerprint)),e.set(A.OPERATIONS_ENUM.SET_LICENSE,new N(Kd.setLicense)),e.set(A.OPERATIONS_ENUM.GET_REGISTRATION_INFO,new N(Kd.getRegistrationInfo)),e.set(A.OPERATIONS_ENUM.RESTART,new N(Rb.restartProcesses)),e.set(A.OPERATIONS_ENUM.RESTART_SERVICE,new N(Rb.restartService)),e.set(A.OPERATIONS_ENUM.CATCHUP,new N(G1)),e.set(A.OPERATIONS_ENUM.SYSTEM_INFORMATION,new N(U1.systemInformation)),e.set(A.OPERATIONS_ENUM.DELETE_AUDIT_LOGS_BEFORE,new N(lr,_a.deleteAuditLogsBefore)),e.set(A.OPERATIONS_ENUM.READ_AUDIT_LOG,new N(A1)),e.set(A.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS,new N(pb.createTokens)),e.set(A.OPERATIONS_ENUM.REFRESH_OPERATION_TOKEN,new N(pb.refreshOperationToken)),e.set(A.OPERATIONS_ENUM.GET_CONFIGURATION,new N(Ob.getConfiguration)),e.set(A.OPERATIONS_ENUM.CUSTOM_FUNCTIONS_STATUS,new N(Mr.customFunctionsStatus)),e.set(A.OPERATIONS_ENUM.GET_CUSTOM_FUNCTIONS,new N(Mr.getCustomFunctions)),e.set(A.OPERATIONS_ENUM.GET_CUSTOM_FUNCTION,new N(Mr.getCustomFunction)),e.set(A.OPERATIONS_ENUM.SET_CUSTOM_FUNCTION,new N(Mr.setCustomFunction)),e.set(A.OPERATIONS_ENUM.DROP_CUSTOM_FUNCTION,new N(Mr.dropCustomFunction)),e.set(A.OPERATIONS_ENUM.ADD_CUSTOM_FUNCTION_PROJECT,new N(Mr.addCustomFunctionProject)),e.set(A.OPERATIONS_ENUM.DROP_CUSTOM_FUNCTION_PROJECT,new N(Mr.dropCustomFunctionProject)),e.set(A.OPERATIONS_ENUM.PACKAGE_CUSTOM_FUNCTION_PROJECT,new N(Mr.packageCustomFunctionProject)),e.set(A.OPERATIONS_ENUM.DEPLOY_CUSTOM_FUNCTION_PROJECT,new N(Mr.deployCustomFunctionProject)),e.set(A.OPERATIONS_ENUM.READ_TRANSACTION_LOG,new N(Nb.readTransactionLog)),e.set(A.OPERATIONS_ENUM.DELETE_TRANSACTION_LOGS_BEFORE,new N(lr,Nb.deleteTransactionLogsBefore)),e.set(A.OPERATIONS_ENUM.INSTALL_NODE_MODULES,new N(gb.installModules)),e.set(A.OPERATIONS_ENUM.AUDIT_NODE_MODULES,new N(gb.auditModules)),e}a(F1,"initializeOperationFunctionMap")});var Zd=h((iz,Db)=>{"use strict";var V1=T(),k1=b(),Er=g(),{handleHDBError:Jd,hdb_errors:Z_}=D(),Lb=require("os"),x1=require("util"),$1=Kl(),Y1=x1.promisify($1.authorize),yb=Ub();function K1(e){let t=`Found an uncaught exception with message: ${e.message}. ${Lb.EOL}Stack: ${e.stack} ${Lb.EOL}Terminating HDB.`;console.error(t),Er.fatal(t),process.exit(1)}a(K1,"handleServerUncaughtException");function Q1(){Er.info("beforeExit caught"),process.exit(0)}a(Q1,"handleBeforeExit");function W1(){Er.info("exit caught"),process.exit(0)}a(W1,"handleExit");function J1(){Er.info("SIGINT caught"),process.exit(0)}a(J1,"handleSigint");function Z1(){Er.info("SIGQUIT caught"),process.exit(0)}a(Z1,"handleSigquit");function X1(){Er.info("SIGTERM caught"),process.exit(0)}a(X1,"handleSigterm");function z1(e,t,r){if(Er.error(e),e.http_resp_code)return typeof e.http_resp_msg=="string"?r.code(e.http_resp_code).send({error:e.http_resp_msg}):r.code(e.http_resp_code).send(e.http_resp_msg);let s=e.statusCode?e.statusCode:Z_.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR;return typeof e=="string"?r.code(s).send({error:e}):r.code(s).send(e.message?{error:e.message}:e)}a(z1,"serverErrorHandler");function j1(e,t,r){if(!e.body||Object.keys(e.body).length===0||typeof e.body!="object"){let s=Jd(new Error,"Invalid JSON.",Z_.HTTP_STATUS_CODES.BAD_REQUEST);r(s,null)}if(k1.isEmpty(e.body.operation)){let s=Jd(new Error,"Request body must include an 'operation' property.",Z_.HTTP_STATUS_CODES.BAD_REQUEST);r(s,null)}r()}a(j1,"reqBodyValidationHandler");function eJ(e,t,r){let s;e.body.operation!==V1.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS?Y1(e,t).then(n=>{s=n,e.body.hdb_user=s,e.body.hdb_auth_header=e.headers.authorization,r()}).catch(n=>{Er.warn(n),Er.warn(`{"ip":"${e.socket.remoteAddress}", "error":"${n.stack}"`);let i=typeof n=="string"?{error:n}:{error:n.message};r(Jd(n,i,Z_.HTTP_STATUS_CODES.UNAUTHORIZED),null)}):(e.body.hdb_user=null,e.body.hdb_auth_header=e.headers.authorization,r())}a(eJ,"authHandler");async function tJ(e,t=!1){let r;try{return t&&(e.body.operation!=="configure_cluster"||e.body.operation!=="set_configuration")&&(e.body.bypass_auth=t),r=yb.chooseOperation(e.body),yb.processLocalTransaction(e,r)}catch(s){throw Er.error(s),s}}a(tJ,"handlePostRequest");Db.exports={authHandler:eJ,handlePostRequest:tJ,handleServerUncaughtException:K1,serverErrorHandler:z1,reqBodyValidationHandler:j1,handleBeforeExit:Q1,handleExit:W1,handleSigint:J1,handleSigquit:Z1,handleSigterm:X1}});var Bb=h((az,Pb)=>{"use strict";var rJ=require("fastify-plugin"),{handlePostRequest:Mb,authHandler:sJ,reqBodyValidationHandler:nJ}=Zd();async function iJ(e){e.decorate("hdbCore",{preValidation:[nJ,sJ],request:Mb,requestWithoutAuthentication:t=>Mb(t,!0)})}a(iJ,"hdbCore");Pb.exports=rJ(iJ)});var Hb=h(()=>{"use strict";var aJ=require("util"),oJ=require("path"),oz=require("fast-glob"),X_=require("fs"),cJ=require("fastify"),_J=require("@fastify/cors"),uJ=require("@fastify/static"),lJ=require("@fastify/autoload"),EJ=eh(),Xd=V(),zd=T(),W=g(),dJ=Kr(),hJ=gr(),SJ=SA(),fJ=NA(),{PACKAGE_ROOT:cz}=T(),TJ=bA(),mJ=UA(),RJ=DA(),AJ=aJ.promisify(dJ.setSchemaDataToGlobal),{handleServerUncaughtException:pJ,serverErrorHandler:OJ,handleBeforeExit:NJ,handleExit:gJ,handleSigint:IJ,handleSigquit:bJ,handleSigterm:CJ}=Zd(),wJ="TRUE",z_,vb=Xd.get(zd.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY);async function UJ(){try{try{global.hdb_ipc=new SJ(process.pid,fJ)}catch(s){throw W.error("Error instantiating new instance of IPC client in Custom Functions server"),W.error(s),s}W.info("In Custom Functions Fastify server"+process.cwd()),W.info(`Custom Functions Running with NODE_ENV set as: ${process.env.NODE_ENV}`),W.debug(`Custom Functions server process ${process.pid} starting up.`),process.on("uncaughtException",pJ),process.on("beforeExit",NJ),process.on("exit",gJ),process.on("SIGINT",IJ),process.on("SIGQUIT",bJ),process.on("SIGTERM",CJ),await LJ();let e=Xd.get(zd.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HTTPS),t=parseInt(Xd.get(zd.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_PORT),10),r=e&&(e===!0||e.toUpperCase()===wJ);try{z_=DJ(r)}catch(s){throw W.error(`Custom Functions buildServer error: ${s}`),s}try{await z_.ready()}catch(s){throw W.error(`Custom Functions server.ready() error: ${s}`),s}try{W.info(`Custom Functions process starting on port ${t}`),await z_.listen({port:t,host:"::"}),W.info(`Custom Functions process running on port ${t}`)}catch(s){throw z_.close(),W.error(`Custom Functions server.listen() error: ${s}`),s}}catch(e){W.error(`Custom Functions ${process.pid} Error: ${e}`),W.error(e),process.exit(1)}}a(UJ,"customFunctionsServer");async function LJ(){try{W.info("Custom Functions starting configuration."),await AJ(),await hJ.setUsersToGlobal(),W.info("Custom Functions completed configuration.")}catch(e){W.error(e)}}a(LJ,"setUp");async function yJ(e){try{W.info("Custom Functions starting buildRoutes"),await e.register(Bb()),await e.after(),X_.readdirSync(vb,{withFileTypes:!0}).forEach(r=>{if(!r.isDirectory()&&!r.isSymbolicLink())return;let s=r.name,n=oJ.join(vb,s);W.trace("Loading project folder "+n);let i=`${n}/routes`,o=`${n}/static`,c=`${n}/static/index.html`,_=`/${s}/static`,u=X_.existsSync(i),l=X_.existsSync(o)&&X_.existsSync(c);u&&e.register(lJ,E=>({dir:i,dirNameRoutePrefix:!1,options:{hdbCore:E.hdbCore,logger:W,prefix:`/${s}`}})).after((E,d,S)=>{E&&E.message?W.error(E.message):E&&W.error(E),S()}),l&&(W.info(`Custom Functions setting up webserver for ${s}`),e.register(uJ,{root:o}).after((E,d,S)=>{E&&E.message?W.error(E.message):E&&W.error(E),S()}),e.get(_,(E,d)=>d.sendFile("index.html",o)))}),W.info("Custom Functions completed buildRoutes")}catch(t){W.error(`Custom Functions errored buildRoutes: ${t}`)}}a(yJ,"buildRoutes");function DJ(e){try{W.info("Custom Functions starting buildServer.");let t=TJ(e),r=cJ(t);r.server.headersTimeout=RJ(),r.setErrorHandler(OJ);let s=mJ();return s&&r.register(_J,s),r.register(EJ),r.register(yJ),W.info("Custom Functions completed buildServer."),r}catch(t){W.error(`Custom Functions process ${process.pid} buildServer error: ${t}`),W.fatal(t),process.exit(1)}}a(DJ,"buildServer");(async()=>await UJ())()});Hb();
|