harperdb 4.3.0-beta.2 → 4.3.0-beta.4
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 +33 -30
- package/bin/lite.js +21 -18
- package/json/systemSchema.json +20 -0
- package/launchServiceScripts/launchInstallNATSServer.js +1 -1
- package/launchServiceScripts/launchNatsIngestService.js +21 -18
- package/launchServiceScripts/launchNatsReplyService.js +21 -18
- package/launchServiceScripts/launchUpdateNodes4-0-0.js +21 -18
- package/npm-shrinkwrap.json +349 -349
- package/package.json +3 -3
- package/server/jobs/jobProcess.js +21 -18
- package/server/threads/threadServer.js +21 -18
- package/studio/build-local/asset-manifest.json +2 -2
- package/studio/build-local/index.html +1 -1
- package/studio/build-local/static/js/{main.55fa2352.js → main.048c8121.js} +2 -2
- package/utility/scripts/restartHdb.js +21 -18
- /package/studio/build-local/static/js/{main.55fa2352.js.LICENSE.txt → main.048c8121.js.LICENSE.txt} +0 -0
|
@@ -1,27 +1,30 @@
|
|
|
1
|
-
"use strict";var jx=Object.create;var Wa=Object.defineProperty;var Xx=Object.getOwnPropertyDescriptor;var Zx=Object.getOwnPropertyNames;var eq=Object.getPrototypeOf,tq=Object.prototype.hasOwnProperty;var a=(e,t)=>Wa(e,"name",{value:t,configurable:!0});var Oe=(e,t)=>()=>(e&&(t=e(e=0)),t);var g=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Ve=(e,t)=>{for(var r in t)Wa(e,r,{get:t[r],enumerable:!0})},OA=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Zx(t))!tq.call(e,s)&&s!==r&&Wa(e,s,{get:()=>t[s],enumerable:!(n=Xx(t,s))||n.enumerable});return e};var B=(e,t,r)=>(r=e!=null?jx(eq(e)):{},OA(t||!e||!e.__esModule?Wa(r,"default",{value:e,enumerable:!0}):r,e)),te=e=>OA(Wa({},"__esModule",{value:!0}),e);var yA=g((kie,NA)=>{var rq=require("fast-glob"),{statSync:XE,existsSync:ZE,readFileSync:nq,writeFileSync:sq}=require("fs"),{spawnSync:iq,spawn:oq,execFileSync:Gie}=require("child_process"),{isMainThread:aq}=require("worker_threads"),{join:Vs,relative:bA}=require("path"),{PACKAGE_ROOT:mn}=M(),{tmpdir:cq,platform:uq}=require("os");require("source-map-support").install();var lq=["resources","server","dataLayer","components"],Qa="ts-build",eh,_q=__filename.endsWith("tsBuild.js");if(_q){if(aq){let r;try{XE(Vs(mn,Qa)),r=!0}catch{}if(r)for(let n of rq.sync(lq.map(s=>s+"/**/*.ts"),{cwd:mn})){let s=0,i=0;try{s=XE(Vs(mn,n)).mtimeMs-5e3,i=XE(Vs(mn,Qa,n.replace(/.ts$/,".js"))).mtimeMs}catch{}if(s>i){console.warn(`TypeScript ${n} is not compiled`+(i?` (TS source file was modified at ${new Date(s)} and compiled file at ${new Date(i)})`:"")+", consider enabling auto-compilation of TypeScript in your IDE), compiling now."),eh=!0;break}}else console.log("TypeScript modules are not compiled, compiling now"),eh=!0;if(eh){let n=Vs(mn,"node_modules/.bin/tsc");uq()==="win32"&&(n+=".cmd");let s=iq(n,{cwd:mn});if(s.stdout.length&&console.log(s.stdout.toString()),s.stderr.length&&console.log(s.stderr.toString()),r){let i=Vs(cq(),"harperdb-tsc.pid"),o;if(ZE(i))try{process.kill(+nq(i,{encoding:"utf8"}),0),o=!0}catch{}if(!o){console.log("starting tsc background process");let c=oq(n,["--watch"],{cwd:mn,detached:!0,stdio:"ignore"});sq(i,c.pid.toString()),c.unref()}}}}let e=NA.constructor,t=e._findPath;e._findPath=function(r,n,s){if(r.startsWith(".")&&!s&&n.length===1&&n[0].startsWith(mn)&&!n[0].includes("node_modules")){let i=bA(mn,n[0]),o;i.startsWith(Qa)?o=Vs(mn,bA(Qa,i)):o=Vs(mn,Qa,i);let c=Vs(o,r),u=c+".js";if(ZE(u))return u;if(c.includes(".")&&ZE(c))return c}return t(r,n,s)}}});var M=g((Yie,FA)=>{"use strict";var Jr=require("path"),dq=require("fs"),{relative:Vie,join:$ie}=Jr,{existsSync:fq}=dq;function Eq(){let e=__dirname;for(;!fq(Jr.join(e,"package.json"));){let t=Jr.dirname(e);if(t===e)throw new Error("Could not find package root");e=t}return e}a(Eq,"getHDBPackageRoot");var $s=Eq(),wA="js",Dl=wA,hq="harperdb-config.yaml",mq="defaultConfig.yaml",pq="hdb",IA=`harperdb.${Dl}`,CA=`customFunctionsServer.${Dl}`,Sq=`restartHdb.${Dl}`,rh="HarperDB",Cl="Custom Functions",Ll="Clustering Hub",Ml="Clustering Leaf",Tq="Clustering Ingest Service",gq="Clustering Reply Service",Rq="foreground.pid",Aq="hdb.pid",Oq="data",bq={HDB:rh,CLUSTERING_HUB:Ll,CLUSTERING_LEAF:Ml,CLUSTERING_INGEST_SERVICE:Tq,CLUSTERING_REPLY_SERVICE:gq,CUSTOM_FUNCTIONS:Cl,RESTART_HDB:"Restart HDB",INSTALL:"Install",RUN:"Run",STOP:"Stop",UPGRADE:"Upgrade",REGISTER:"Register",JOB:"Job",CLUSTERING_UPGRADE_4_0_0:"Upgrade-4-0-0"},Nq={HDB:"hdb.log",INSTALL:"install.log",CLUSTERING_HUB:"clustering_hub.log",CLUSTERING_LEAF:"clustering_leaf.log"},yq={NOTIFY:"notify",FATAL:"fatal",ERROR:"error",WARN:"warn",INFO:"info",DEBUG:"debug",TRACE:"trace"},wq={harperdb:rh,"clustering hub":Ll,"clustering leaf":Ml,"custom functions":Cl,custom_functions:Cl,clustering:"clustering","clustering config":"clustering config",clustering_config:"clustering_config",http_workers:"http_workers"},Iq={CLUSTERING_HUB_PROC_DESCRIPTOR:Ll,CLUSTERING_LEAF_PROC_DESCRIPTOR:Ml},th={HDB:Jr.join($s,"server/harperdb"),CUSTOM_FUNCTIONS:Jr.join($s,"server/customFunctions"),CLUSTERING_HUB:Jr.join($s,"server/nats"),CLUSTERING_LEAF:Jr.join($s,"server/nats")},Cq={HDB:Jr.join(th.HDB,IA),CUSTOM_FUNCTIONS:Jr.join(th.CUSTOM_FUNCTIONS,CA)},Dq={MAIN:"bin/harperdb.js",NATS_INGEST_SERVICE:Jr.join($s,"launchServiceScripts/launchNatsIngestService.js"),NATS_REPLY_SERVICE:Jr.join($s,"launchServiceScripts/launchNatsReplyService.js"),NODES_UPGRADE_4_0_0:Jr.join($s,"launchServiceScripts/launchUpdateNodes4-0-0.js")},Lq={SUPER_USER:"super_user",CLUSTER_USER:"cluster_user"},DA="support@harperdb.io",Mq="customer-success@harperdb.io",LA=1,Uq=4141,MA="https://harperdbhelp.zendesk.com/hc/en-us/requests/new",Pq="https://www.harperdb.io/product",vq=`For support, please submit a request at ${MA} or contact ${DA}`,UA=`For license support, please contact ${Mq}`,Bq="None of the specified records were found.",Hq="hash attribute not found",xq=`Your current license only supports ${LA} role. ${UA}`,qq="Your current license only supports 3 connections to a node.",Fq="127.0.0.1",Gq=1,kq=/^\.$/,Vq=/^\.\.$/,$q="U+002E",Yq=/\//g,Kq="U+002F",Wq=/U\+002F/g,Qq=/^U\+002E$/,zq=/^U\+002EU\+002E$/,Jq="d",jq=999999,Xq="*",Zq="--max-old-space-size=",eF="system",tF="__hdb_hash",rF=".harperdb",nF=".hdb",sF="keys",iF="hdb_boot_properties.file",oF=".updateConfig.json",aF="SIGTSTP",cF=24,uF=6e4,lF=448,_F="blob",dF="trash",fF="database",EF="schema",hF="transactions",mF=".count",pF="id",SF="PROCESS_NAME",PA={SETTINGS_PATH_KEY:"settings_path"},vA=require("lodash"),TF={TC_AGREEMENT:"TC_AGREEMENT",CLUSTERING_USER:"CLUSTERING_USER",CLUSTERING_PASSWORD:"CLUSTERING_PASSWORD",HDB_ADMIN_USERNAME:"HDB_ADMIN_USERNAME",HDB_ADMIN_PASSWORD:"HDB_ADMIN_PASSWORD",OPERATIONSAPI_ROOT:"OPERATIONSAPI_ROOT",ROOTPATH:"ROOTPATH",OPERATIONSAPI_NETWORK_PORT:"OPERATIONSAPI_NETWORK_PORT",CLUSTERING_NODENAME:"CLUSTERING_NODENAME",CLUSTERING_ENABLED:"CLUSTERING_ENABLED",HDB_CONFIG:"HDB_CONFIG",OPERATIONSAPI_NETWORK_SECUREPORT:"OPERATIONSAPI_NETWORK_SECUREPORT",CLUSTERING_PORT:"CLUSTERING_PORT",HDB_ROOT:"HDB_ROOT",SERVER_PORT:"SERVER_PORT",NODE_NAME:"NODE_NAME",CLUSTERING:"CLUSTERING"},gF={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},RF={DATA_VERSION:"data_version",UPGRADE_VERSION:"upgrade_version"},AF={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"},OF={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"},Ar="hdb_internal:",bF={CREATE_SCHEMA:Ar+"create_schema",CREATE_TABLE:Ar+"create_table",CREATE_ATTRIBUTE:Ar+"create_attribute",ADD_USER:Ar+"add_user",ALTER_USER:Ar+"alter_user",DROP_USER:Ar+"drop_user",HDB_NODES:Ar+"hdb_nodes",HDB_USERS:Ar+"hdb_users",HDB_WORKERS:Ar+"hdb_workers",CATCHUP:Ar+"catchup",SCHEMA_CATCHUP:Ar+"schema_catchup",WORKER_ROOM:Ar+"cluster_workers"},NF={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"},yF="060493.ks",wF=".license",IF={CREATED:"CREATED",IN_PROGRESS:"IN_PROGRESS",COMPLETE:"COMPLETE",ERROR:"ERROR"},X={INSERT:"insert",UPDATE:"update",UPSERT:"upsert",SEARCH_BY_CONDITIONS:"search_by_conditions",SEARCH_BY_HASH:"search_by_hash",SEARCH_BY_ID:"search_by_id",SEARCH_BY_VALUE:"search_by_value",SEARCH:"search",SQL:"sql",CSV_DATA_LOAD:"csv_data_load",CSV_FILE_LOAD:"csv_file_load",CSV_URL_LOAD:"csv_url_load",CREATE_SCHEMA:"create_schema",CREATE_DATABASE:"create_database",CREATE_TABLE:"create_table",CREATE_ATTRIBUTE:"create_attribute",DROP_SCHEMA:"drop_schema",DROP_DATABASE:"drop_database",DROP_TABLE:"drop_table",DESCRIBE_SCHEMA:"describe_schema",DESCRIBE_DATABASE:"describe_database",DESCRIBE_TABLE:"describe_table",DESCRIBE_ALL:"describe_all",DELETE:"delete",ADD_USER:"add_user",ALTER_USER:"alter_user",DROP_USER:"drop_user",LIST_USERS:"list_users",LIST_ROLES:"list_roles",ADD_ROLE:"add_role",ALTER_ROLE:"alter_role",DROP_ROLE:"drop_role",USER_INFO:"user_info",READ_LOG:"read_log",ADD_NODE:"add_node",UPDATE_NODE:"update_node",SET_NODE_REPLICATION:"set_node_replication",EXPORT_TO_S3:"export_to_s3",IMPORT_FROM_S3:"import_from_s3",DELETE_FILES_BEFORE:"delete_files_before",DELETE_RECORDS_BEFORE:"delete_records_before",EXPORT_LOCAL:"export_local",SEARCH_JOBS_BY_START_DATE:"search_jobs_by_start_date",GET_JOB:"get_job",DELETE_JOB:"delete_job",UPDATE_JOB:"update_job",GET_FINGERPRINT:"get_fingerprint",SET_LICENSE:"set_license",GET_REGISTRATION_INFO:"registration_info",CONFIGURE_CLUSTER:"configure_cluster",SET_CONFIGURATION:"set_configuration",CLUSTER_STATUS:"cluster_status",CLUSTER_NETWORK:"cluster_network",DROP_ATTRIBUTE:"drop_attribute",REMOVE_NODE:"remove_node",RESTART:"restart",RESTART_SERVICE:"restart_service",CATCHUP:"catchup",SYSTEM_INFORMATION:"system_information",DELETE_AUDIT_LOGS_BEFORE:"delete_audit_logs_before",READ_AUDIT_LOG:"read_audit_log",CREATE_AUTHENTICATION_TOKENS:"create_authentication_tokens",LOGIN:"login",LOGOUT:"logout",REFRESH_OPERATION_TOKEN:"refresh_operation_token",GET_CONFIGURATION:"get_configuration",CUSTOM_FUNCTIONS_STATUS:"custom_functions_status",GET_CUSTOM_FUNCTIONS:"get_custom_functions",GET_CUSTOM_FUNCTION:"get_custom_function",SET_CUSTOM_FUNCTION:"set_custom_function",GET_COMPONENTS:"get_components",GET_COMPONENT_FILE:"get_component_file",SET_COMPONENT_FILE:"set_component_file",DROP_COMPONENT:"drop_component",DROP_CUSTOM_FUNCTION:"drop_custom_function",ADD_CUSTOM_FUNCTION_PROJECT:"add_custom_function_project",ADD_COMPONENT:"add_component",DROP_CUSTOM_FUNCTION_PROJECT:"drop_custom_function_project",PACKAGE_CUSTOM_FUNCTION_PROJECT:"package_custom_function_project",DEPLOY_CUSTOM_FUNCTION_PROJECT:"deploy_custom_function_project",PACKAGE_COMPONENT:"package_component",DEPLOY_COMPONENT:"deploy_component",CLUSTER_SET_ROUTES:"cluster_set_routes",CLUSTER_DELETE_ROUTES:"cluster_delete_routes",CLUSTER_GET_ROUTES:"cluster_get_routes",READ_TRANSACTION_LOG:"read_transaction_log",DELETE_TRANSACTION_LOGS_BEFORE:"delete_transaction_logs_before",INSTALL_NODE_MODULES:"install_node_modules",AUDIT_NODE_MODULES:"audit_node_modules",PURGE_STREAM:"purge_stream",GET_BACKUP:"get_backup"},CF={CSV:".csv",JSON:".json"},DF={AWS_ACCESS_KEY:"aws_access_key_id",AWS_SECRET:"aws_secret_access_key",AWS_BUCKET:"bucket",AWS_FILE_KEY:"key",REGION:"region"},LF={SELECT:"select",INSERT:"insert",UPDATE:"update",DELETE:"delete"},za={};za[X.INSERT]=X.INSERT;za[X.UPDATE]=X.UPDATE;za[X.UPSERT]=X.UPSERT;za[X.DELETE]=X.DELETE;var Be=Object.create(null);Be[X.DESCRIBE_ALL]=X.DESCRIBE_ALL;Be[X.DESCRIBE_TABLE]=X.DESCRIBE_TABLE;Be[X.DESCRIBE_SCHEMA]=X.DESCRIBE_SCHEMA;Be[X.READ_LOG]=X.READ_LOG;Be[X.ADD_NODE]=X.ADD_NODE;Be[X.LIST_USERS]=X.LIST_USERS;Be[X.LIST_ROLES]=X.LIST_ROLES;Be[X.USER_INFO]=X.USER_INFO;Be[X.SQL]=X.SQL;Be[X.GET_JOB]=X.GET_JOB;Be[X.SEARCH_JOBS_BY_START_DATE]=X.SEARCH_JOBS_BY_START_DATE;Be[X.DELETE_FILES_BEFORE]=X.DELETE_FILES_BEFORE;Be[X.EXPORT_LOCAL]=X.EXPORT_LOCAL;Be[X.EXPORT_TO_S3]=X.EXPORT_TO_S3;Be[X.CLUSTER_STATUS]=X.CLUSTER_STATUS;Be[X.REMOVE_NODE]=X.REMOVE_NODE;Be[X.RESTART]=X.RESTART;Be[X.CUSTOM_FUNCTIONS_STATUS]=X.CUSTOM_FUNCTIONS_STATUS;Be[X.GET_CUSTOM_FUNCTIONS]=X.GET_CUSTOM_FUNCTIONS;Be[X.GET_CUSTOM_FUNCTION]=X.GET_CUSTOM_FUNCTION;Be[X.SET_CUSTOM_FUNCTION]=X.SET_CUSTOM_FUNCTION;Be[X.DROP_CUSTOM_FUNCTION]=X.DROP_CUSTOM_FUNCTION;Be[X.ADD_CUSTOM_FUNCTION_PROJECT]=X.ADD_CUSTOM_FUNCTION_PROJECT;Be[X.DROP_CUSTOM_FUNCTION_PROJECT]=X.DROP_CUSTOM_FUNCTION_PROJECT;Be[X.PACKAGE_CUSTOM_FUNCTION_PROJECT]=X.PACKAGE_CUSTOM_FUNCTION_PROJECT;Be[X.DEPLOY_CUSTOM_FUNCTION_PROJECT]=X.DEPLOY_CUSTOM_FUNCTION_PROJECT;var MF={DEV:"dev",RUN:"run",START:"start",INSTALL:"install",REGISTER:"register",STOP:"stop",RESTART:"restart",VERSION:"version",UPGRADE:"upgrade",HELP:"help",STATUS:"status",OPERATION:"operation",RENEWCERTS:"renew-certs"},UF={point:"point",lineString:"lineString",multiLineString:"multiLineString",multiPoint:"multiPoint",multiPolygon:"multiPolygon",polygon:"polygon"},BA={HDB_ROOT_KEY:"HDB_ROOT",SERVER_PORT_KEY:"SERVER_PORT",CERT_KEY:"CERTIFICATE",PRIVATE_KEY_KEY:"PRIVATE_KEY",HTTP_SECURE_ENABLED_KEY:"HTTPS_ON",CORS_ENABLED_KEY:"CORS_ON",CORS_WHITELIST_KEY:"CORS_WHITELIST",LOG_LEVEL_KEY:"LOG_LEVEL",LOGGER_KEY:"LOGGER",LOG_PATH_KEY:"LOG_PATH",LOG_ROTATE:"LOG_ROTATE",LOG_ROTATE_MAX_SIZE:"LOG_ROTATE_MAX_SIZE",LOG_ROTATE_RETAIN:"LOG_ROTATE_RETAIN",LOG_ROTATE_COMPRESS:"LOG_ROTATE_COMPRESS",LOG_ROTATE_DATE_FORMAT:"LOG_ROTATE_DATE_FORMAT",LOG_ROTATE_ROTATE_MODULE:"LOG_ROTATE_ROTATE_MODULE",LOG_ROTATE_WORKER_INTERVAL:"LOG_ROTATE_WORKER_INTERVAL",LOG_ROTATE_ROTATE_INTERVAL:"LOG_ROTATE_ROTATE_INTERVAL",LOG_ROTATE_TIMEZONE:"LOG_ROTATE_TIMEZONE",LOG_DAILY_ROTATE_KEY:"LOG_DAILY_ROTATE",LOG_MAX_DAILY_FILES_KEY:"LOG_MAX_DAILY_FILES",PROPS_ENV_KEY:"NODE_ENV",SETTINGS_PATH_KEY:"settings_path",CLUSTERING_PORT_KEY:"CLUSTERING_PORT",CLUSTERING_NODE_NAME_KEY:"NODE_NAME",CLUSTERING_ENABLED_KEY:"CLUSTERING",ALLOW_SELF_SIGNED_SSL_CERTS:"ALLOW_SELF_SIGNED_SSL_CERTS",MAX_HDB_PROCESSES:"MAX_HDB_PROCESSES",INSTALL_USER:"install_user",CLUSTERING_USER_KEY:"CLUSTERING_USER",MAX_CLUSTERING_PROCESSES:"MAX_CLUSTERING_PROCESSES",SERVER_TIMEOUT_KEY:"SERVER_TIMEOUT_MS",SERVER_KEEP_ALIVE_TIMEOUT_KEY:"SERVER_KEEP_ALIVE_TIMEOUT",SERVER_HEADERS_TIMEOUT_KEY:"SERVER_HEADERS_TIMEOUT",DISABLE_TRANSACTION_LOG_KEY:"DISABLE_TRANSACTION_LOG",OPERATION_TOKEN_TIMEOUT_KEY:"OPERATION_TOKEN_TIMEOUT",REFRESH_TOKEN_TIMEOUT_KEY:"REFRESH_TOKEN_TIMEOUT",CUSTOM_FUNCTIONS_ENABLED_KEY:"CUSTOM_FUNCTIONS",CUSTOM_FUNCTIONS_PORT_KEY:"CUSTOM_FUNCTIONS_PORT",CUSTOM_FUNCTIONS_DIRECTORY_KEY:"CUSTOM_FUNCTIONS_DIRECTORY",MAX_CUSTOM_FUNCTION_PROCESSES:"MAX_CUSTOM_FUNCTION_PROCESSES",LOG_TO_FILE:"LOG_TO_FILE",LOG_TO_STDSTREAMS:"LOG_TO_STDSTREAMS",RUN_IN_FOREGROUND:"RUN_IN_FOREGROUND",LOCAL_STUDIO_ON:"LOCAL_STUDIO_ON",STORAGE_WRITE_ASYNC:"STORAGE_WRITE_ASYNC"},PF=vA.invert(BA),vF={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"},C={ANALYTICS_AGGREGATEPERIOD:"analytics_aggregatePeriod",AUTHENTICATION_AUTHORIZELOCAL:"authentication_authorizeLocal",AUTHENTICATION_CACHETTL:"authentication_cacheTTL",AUTHENTICATION_ENABLESESSIONS:"authentication_enableSessions",AUTHENTICATION_OPERATIONTOKENTIMEOUT:"authentication_operationTokenTimeout",AUTHENTICATION_REFRESHTOKENTIMEOUT:"authentication_refreshTokenTimeout",CLUSTERING_USER:"clustering_user",CLUSTERING_ENABLED:"clustering_enabled",CLUSTERING_HUBSERVER_CLUSTER_NAME:"clustering_hubServer_cluster_name",CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT:"clustering_hubServer_cluster_network_port",CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES:"clustering_hubServer_cluster_network_routes",CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT:"clustering_hubServer_leafNodes_network_port",CLUSTERING_HUBSERVER_NETWORK_PORT:"clustering_hubServer_network_port",CLUSTERING_LEAFSERVER_NETWORK_PORT:"clustering_leafServer_network_port",CLUSTERING_LEAFSERVER_NETWORK_ROUTES:"clustering_leafServer_network_routes",CLUSTERING_LEAFSERVER_STREAMS_MAXAGE:"clustering_leafServer_streams_maxAge",CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES:"clustering_leafServer_streams_maxBytes",CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS:"clustering_leafServer_streams_maxMsgs",CLUSTERING_LEAFSERVER_STREAMS_PATH:"clustering_leafServer_streams_path",CLUSTERING_NODENAME:"clustering_nodeName",CLUSTERING_TLS_CERTIFICATE:"clustering_tls_certificate",CLUSTERING_TLS_PRIVATEKEY:"clustering_tls_privateKey",CLUSTERING_TLS_CERT_AUTH:"clustering_tls_certificateAuthority",CLUSTERING_TLS_INSECURE:"clustering_tls_insecure",CLUSTERING_TLS_VERIFY:"clustering_tls_verify",CLUSTERING_LOGLEVEL:"clustering_logLevel",CLUSTERING_REPUBLISHMESSAGES:"clustering_republishMessages",CLUSTERING_DATABASELEVEL:"clustering_databaseLevel",CUSTOMFUNCTIONS_NETWORK_HTTPS:"customFunctions_network_https",THREADS:"threads",MAXHEAPMEMORY:"maxHeapMemory",HTTP_SESSIONAFFINITY:"http_sessionAffinity",HTTP_COMPRESSIONTHRESHOLD:"http_compressionThreshold",HTTP_CORS:"http_cors",HTTP_CORSACCESSLIST:"http_corsAccessList",HTTP_HEADERSTIMEOUT:"http_headersTimeout",HTTP_KEEPALIVETIMEOUT:"http_keepAliveTimeout",HTTP_TIMEOUT:"http_timeout",HTTP_PORT:"http_port",HTTP_SECUREPORT:"http_securePort",HTTP_MTLS:"http_mtls",HTTP_MTLS_REQUIRED:"http_mtls_required",HTTP_MTLS_USER:"http_mtls_user",LOCALSTUDIO_ENABLED:"localStudio_enabled",LOGGING_FILE:"logging_file",LOGGING_LEVEL:"logging_level",LOGGING_ROOT:"logging_root",LOGGING_ROTATION_ENABLED:"logging_rotation_enabled",LOGGING_ROTATION_COMPRESS:"logging_rotation_compress",LOGGING_ROTATION_INTERVAL:"logging_rotation_interval",LOGGING_ROTATION_MAXSIZE:"logging_rotation_maxSize",LOGGING_ROTATION_PATH:"logging_rotation_path",LOGGING_STDSTREAMS:"logging_stdStreams",LOGGING_AUDITLOG:"logging_auditLog",LOGGING_AUDITRETENTION:"logging_auditRetention",LOGGING_AUDITAUTHEVENTS_LOGFAILED:"logging_auditAuthEvents_logFailed",LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL:"logging_auditAuthEvents_logSuccessful",OPERATIONSAPI_NETWORK_CORS:"operationsApi_network_cors",OPERATIONSAPI_NETWORK_CORSACCESSLIST:"operationsApi_network_corsAccessList",OPERATIONSAPI_NETWORK_HEADERSTIMEOUT:"operationsApi_network_headersTimeout",OPERATIONSAPI_NETWORK_HTTPS:"operationsApi_network_https",OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT:"operationsApi_network_keepAliveTimeout",OPERATIONSAPI_NETWORK_PORT:"operationsApi_network_port",OPERATIONSAPI_NETWORK_DOMAINSOCKET:"operationsApi_network_domainSocket",OPERATIONSAPI_NETWORK_SECUREPORT:"operationsApi_network_securePort",OPERATIONSAPI_TLS_CERTIFICATE:"operationsApi_tls_certificate",OPERATIONSAPI_TLS_PRIVATEKEY:"operationsApi_tls_privateKey",OPERATIONSAPI_TLS_CERTIFICATEAUTHORITY:"operationsApi_tls_certificateAuthority",OPERATIONSAPI_NETWORK_TIMEOUT:"operationsApi_network_timeout",ROOTPATH:"rootPath",SERIALIZATION_BIGINT:"serialization_bigInt",STORAGE_WRITEASYNC:"storage_writeAsync",STORAGE_OVERLAPPINGSYNC:"storage_overlappingSync",STORAGE_CACHING:"storage_caching",STORAGE_COMPRESSION:"storage_compression",STORAGE_NOREADAHEAD:"storage_noReadAhead",STORAGE_PREFETCHWRITES:"storage_prefetchWrites",STORAGE_ENCRYPTION:"storage_encryption",STORAGE_PATH:"storage_path",STORAGE_AUDIT_PATH:"storage_audit_path",DATABASES:"databases",IGNORE_SCRIPTS:"ignoreScripts",MQTT_NETWORK_PORT:"mqtt_network_port",MQTT_WEBSOCKET:"mqtt_webSocket",MQTT_NETWORK_SECUREPORT:"mqtt_network_securePort",MQTT_NETWORK_MTLS:"mqtt_network_mtls",MQTT_NETWORK_MTLS_REQUIRED:"mqtt_network_mtls_required",MQTT_NETWORK_MTLS_CERTIFICATEAUTHORITY:"mqtt_network_mtls_certificateAuthority",MQTT_NETWORK_MTLS_USER:"mqtt_network_mtls_user",MQTT_REQUIREAUTHENTICATION:"mqtt_requireAuthentication",COMPONENTSROOT:"componentsRoot",TLS_CERTIFICATE:"tls_certificate",TLS_PRIVATEKEY:"tls_privateKey",TLS_CERTIFICATEAUTHORITY:"tls_certificateAuthority",TLS_CIPHERS:"tls_ciphers"},HA={settings_path:PA.SETTINGS_PATH_KEY,hdb_root_key:C.ROOTPATH,hdb_root:C.ROOTPATH,rootpath:C.ROOTPATH,server_port_key:C.OPERATIONSAPI_NETWORK_PORT,server_port:C.OPERATIONSAPI_NETWORK_PORT,cert_key:C.TLS_CERTIFICATE,certificate:C.TLS_CERTIFICATE,private_key_key:C.TLS_PRIVATEKEY,private_key:C.TLS_PRIVATEKEY,http_secure_enabled_key:C.OPERATIONSAPI_NETWORK_HTTPS,https_on:C.OPERATIONSAPI_NETWORK_HTTPS,cors_enabled_key:C.OPERATIONSAPI_NETWORK_CORS,cors_on:C.OPERATIONSAPI_NETWORK_CORS,cors_whitelist_key:C.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_whitelist:C.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_accesslist_key:C.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_accesslist:C.OPERATIONSAPI_NETWORK_CORSACCESSLIST,log_level_key:C.LOGGING_LEVEL,log_level:C.LOGGING_LEVEL,log_path_key:C.LOGGING_ROOT,log_path:C.LOGGING_ROOT,clustering_node_name_key:C.CLUSTERING_NODENAME,node_name:C.CLUSTERING_NODENAME,clustering_enabled_key:C.CLUSTERING_ENABLED,clustering:C.CLUSTERING_ENABLED,max_http_threads:C.THREADS,max_hdb_processes:C.THREADS,server_timeout_key:C.OPERATIONSAPI_NETWORK_TIMEOUT,server_timeout_ms:C.OPERATIONSAPI_NETWORK_TIMEOUT,server_keep_alive_timeout_key:C.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT,server_keep_alive_timeout:C.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT,server_headers_timeout_key:C.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT,server_headers_timeout:C.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT,disable_transaction_log_key:C.LOGGING_AUDITLOG,disable_transaction_log:C.LOGGING_AUDITLOG,operation_token_timeout_key:C.AUTHENTICATION_OPERATIONTOKENTIMEOUT,operation_token_timeout:C.AUTHENTICATION_OPERATIONTOKENTIMEOUT,refresh_token_timeout_key:C.AUTHENTICATION_REFRESHTOKENTIMEOUT,refresh_token_timeout:C.AUTHENTICATION_REFRESHTOKENTIMEOUT,custom_functions_port_key:C.HTTP_PORT,custom_functions_port:C.HTTP_PORT,custom_functions_directory_key:C.COMPONENTSROOT,custom_functions_directory:C.COMPONENTSROOT,max_custom_function_processes:C.THREADS,log_to_file:C.LOGGING_FILE,log_to_stdstreams:C.LOGGING_STDSTREAMS,local_studio_on:C.LOCALSTUDIO_ENABLED,clustering_port:C.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT,clustering_user:C.CLUSTERING_USER,clustering_enabled:C.CLUSTERING_ENABLED,clustering_hubserver_cluster_name:C.CLUSTERING_HUBSERVER_CLUSTER_NAME,clustering_hubserver_cluster_network_port:C.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT,clustering_hubserver_cluster_network_routes:C.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,clustering_hubserver_leafnodes_network_port:C.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT,clustering_hubserver_network_port:C.CLUSTERING_HUBSERVER_NETWORK_PORT,clustering_leafserver_network_port:C.CLUSTERING_LEAFSERVER_NETWORK_PORT,clustering_leafserver_network_routes:C.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,clustering_leafserver_streams_maxage:C.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE,clustering_leafserver_streams_maxbytes:C.CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES,clustering_leafserver_streams_maxmsgs:C.CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS,clustering_leafserver_streams_path:C.CLUSTERING_LEAFSERVER_STREAMS_PATH,clustering_nodename:C.CLUSTERING_NODENAME,clustering_tls_certificate:C.CLUSTERING_TLS_CERTIFICATE,clustering_tls_privatekey:C.CLUSTERING_TLS_PRIVATEKEY,clustering_tls_certificateauthority:C.CLUSTERING_TLS_CERT_AUTH,clustering_tls_insecure:C.CLUSTERING_TLS_INSECURE,clustering_tls_verify:C.CLUSTERING_TLS_VERIFY,clustering_loglevel:C.CLUSTERING_LOGLEVEL,clustering_republishmessages:C.CLUSTERING_REPUBLISHMESSAGES,clustering_databaselevel:C.CLUSTERING_DATABASELEVEL,customfunctions_network_port:C.HTTP_PORT,customfunctions_tls_certificate:C.TLS_CERTIFICATE,customfunctions_network_cors:C.HTTP_CORS,customfunctions_network_corsaccesslist:C.HTTP_CORSACCESSLIST,customfunctions_network_headerstimeout:C.HTTP_HEADERSTIMEOUT,customfunctions_network_https:C.CUSTOMFUNCTIONS_NETWORK_HTTPS,customfunctions_network_keepalivetimeout:C.HTTP_KEEPALIVETIMEOUT,customfunctions_tls_privatekey:C.TLS_PRIVATEKEY,customfunctions_tls_certificateauthority:C.TLS_CERTIFICATEAUTHORITY,customfunctions_network_timeout:C.HTTP_TIMEOUT,http_threads:C.THREADS,threads:C.THREADS,maxheapmemory:C.MAXHEAPMEMORY,http_session_affinity:C.HTTP_SESSIONAFFINITY,http_compressionthreshold:C.HTTP_COMPRESSIONTHRESHOLD,http_cors:C.HTTP_CORS,http_corsaccesslist:C.HTTP_CORSACCESSLIST,http_headerstimeout:C.HTTP_HEADERSTIMEOUT,http_keepalivetimeout:C.HTTP_KEEPALIVETIMEOUT,http_timeout:C.HTTP_TIMEOUT,http_port:C.HTTP_PORT,http_secureport:C.HTTP_SECUREPORT,http_mtls:C.HTTP_MTLS,http_mtls_user:C.HTTP_MTLS_USER,http_mtls_required:C.HTTP_MTLS_REQUIRED,customfunctions_processes:C.THREADS,customfunctions_root:C.COMPONENTSROOT,localstudio_enabled:C.LOCALSTUDIO_ENABLED,logging_file:C.LOGGING_FILE,logging_level:C.LOGGING_LEVEL,logging_root:C.LOGGING_ROOT,logging_rotation_enabled:C.LOGGING_ROTATION_ENABLED,logging_rotation_compress:C.LOGGING_ROTATION_COMPRESS,logging_rotation_interval:C.LOGGING_ROTATION_INTERVAL,logging_rotation_maxsize:C.LOGGING_ROTATION_MAXSIZE,logging_rotation_path:C.LOGGING_ROTATION_PATH,logging_stdstreams:C.LOGGING_STDSTREAMS,logging_auditlog:C.LOGGING_AUDITLOG,logging_auditretention:C.LOGGING_AUDITRETENTION,logging_auditauthevents_logfailed:C.LOGGING_AUDITAUTHEVENTS_LOGFAILED,logging_auditauthevents_logsuccessful:C.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL,operationsapi_authentication_operationtokentimeout:C.AUTHENTICATION_OPERATIONTOKENTIMEOUT,operationsapi_authentication_refreshtokentimeout:C.AUTHENTICATION_REFRESHTOKENTIMEOUT,operationsapi_network_cors:C.OPERATIONSAPI_NETWORK_CORS,operationsapi_network_corsaccesslist:C.OPERATIONSAPI_NETWORK_CORSACCESSLIST,operationsapi_network_headerstimeout:C.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT,operationsapi_network_https:C.OPERATIONSAPI_NETWORK_HTTPS,operationsapi_network_keepalivetimeout:C.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT,operationsapi_network_port:C.OPERATIONSAPI_NETWORK_PORT,operationsapi_network_domainsocket:C.OPERATIONSAPI_NETWORK_DOMAINSOCKET,operationsapi_network_secureport:C.OPERATIONSAPI_NETWORK_SECUREPORT,operationsapi_tls_certificate:C.OPERATIONSAPI_TLS_CERTIFICATE,operationsapi_tls_privatekey:C.OPERATIONSAPI_TLS_PRIVATEKEY,operationsapi_tls_certificateauthority:C.OPERATIONSAPI_TLS_CERTIFICATEAUTHORITY,operationsapi_network_timeout:C.OPERATIONSAPI_NETWORK_TIMEOUT,operationsapi_root:C.ROOTPATH,databases:C.DATABASES,storage_path:C.STORAGE_PATH,ignorescripts:C.IGNORE_SCRIPTS,mqtt_network_port:C.MQTT_NETWORK_PORT,mqtt_websocket:C.MQTT_WEBSOCKET,mqtt_network_secureport:C.MQTT_NETWORK_SECUREPORT,mqtt_network_mtls:C.MQTT_NETWORK_MTLS,mqtt_network_mtls_certificateAuthority:C.MQTT_NETWORK_MTLS_CERTIFICATEAUTHORITY,mqtt_network_mtls_user:C.MQTT_NETWORK_MTLS_USER,mqtt_network_mtls_required:C.MQTT_NETWORK_MTLS_REQUIRED,mqtt_requireauthentication:C.MQTT_REQUIREAUTHENTICATION,analytics_aggregatePeriod:C.ANALYTICS_AGGREGATEPERIOD,authentication_authorizelocal:C.AUTHENTICATION_AUTHORIZELOCAL,authentication_cachettl:C.AUTHENTICATION_CACHETTL,authentication_enablesessions:C.AUTHENTICATION_ENABLESESSIONS,authentication_operationtokentimeout:C.AUTHENTICATION_OPERATIONTOKENTIMEOUT,authentication_refreshtokentimeout:C.AUTHENTICATION_REFRESHTOKENTIMEOUT,componentsroot:C.COMPONENTSROOT,tls_certificate:C.TLS_CERTIFICATE,tls_privatekey:C.TLS_PRIVATEKEY,tls_certificateauthority:C.TLS_CERTIFICATEAUTHORITY,tls_ciphers:C.TLS_CIPHERS};for(let e in C){let t=C[e];HA[t.toLowerCase()]=t}var BF={TABLES:"tables",PATH:"path",AUDIT_PATH:"auditPath"},HF={csv_file_load:"csv_file_load",csv_data_load:X.CSV_DATA_LOAD,csv_url_load:X.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"},xF={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"},qF={BIDIRECTIONAL:"BIDIRECTIONAL",OUTBOUND:"OUTBOUND",INBOUND:"INBOUND"},FF={VERSION_DEFAULT:"2.2.0"},GF={DEVELOPMENT:8192,DEFAULT:512},kF={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"},VF={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"},$F={ENOENT:"ENOENT",EACCES:"EACCES",EEXIST:"EEXIST"},xA={CREATED_TIME:"__createdtime__",UPDATED_TIME:"__updatedtime__"},YF=Symbol("metadata"),KF="__clustering__",WF=Object.values(xA),QF=15984864e5,qA={LESS:"<",LESS_OR_EQ:"<=",GREATER:">",GREATER_OR_EQ:">=",BETWEEN:"..."},zF=vA.invert(qA),JF={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"},jF=111,XF=`\r
|
|
2
|
-
`,
|
|
3
|
-
`}a(
|
|
4
|
-
`).slice(1)){s=s.trim();let[i]=s.split(" ",1),o=s.slice(i.length+1).trim();t[i]===void 0&&(t[i]={}),t[i][r]=o}}))}catch(r){throw r}return Object.entries(t).filter(([,r])=>r.comm&&r.args&&r.ppid&&r.uid&&r["%cpu"]&&r["%mem"]&&r.args.includes(e)).map(([r,n])=>({pid:Number.parseInt(r,10),name:LG.basename(n.comm),cmd:n.args,ppid:Number.parseInt(n.ppid,10),uid:Number.parseInt(n.uid,10),cpu:Number.parseFloat(n["%cpu"]),memory:Number.parseFloat(n["%mem"])}))}a(vG,"findPs")});var lt=g((Zie,nO)=>{"use strict";var BG="__dbis__",HG="__txns__",xG="__environment_name__",qG="__dbi_defintion__",FG={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"},GG=["__createdtime__","__updatedtime__"],kG="\uFFFF",rO={TIMESTAMP:"timestamp",HASH_VALUE:"hash_value",USER_NAME:"user_name"},VG=Object.values(rO);nO.exports={AUDIT_STORE_NAME:HG,INTERNAL_DBIS_NAME:BG,DBI_DEFINITION_NAME:qG,SEARCH_TYPES:FG,TIMESTAMP_NAMES:GG,MAX_SEARCH_KEY_LENGTH:256,ENVIRONMENT_NAME_KEY:xG,TRANSACTIONS_DBI_NAMES_ENUM:rO,TRANSACTIONS_DBIS:VG,OVERFLOW_MARKER:kG}});var Or=g((eoe,dO)=>{"use strict";var sO=M(),iO=lt(),oO={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},aO=a(e=>`${e} Check logs and try again.`,"CHECK_LOGS_WRAPPER"),cO={500:aO("There was an error processing your request."),400:"Invalid request"},$G=cO[oO.INTERNAL_SERVER_ERROR],YG={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.`},KG={CONFIG_VALIDATION:e=>`HarperDB config file validation error: ${e}`},WG={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"},QG={BASE_PATH_REQUIRED:"base_path is required",DESTINATION_PATH_REQUIRED:"destination_path is required",ENV_NAME_REQUIRED:"env_name is required",INVALID_BASE_PATH:"invalid base_path",INVALID_DESTINATION_PATH:"invalid destination_path",INVALID_ENVIRONMENT:"invalid environment",ENV_REQUIRED:"env is required",DBI_NAME_REQUIRED:"dbi_name is required",DBI_DOES_NOT_EXIST:"dbi does not exist",HASH_ATTRIBUTE_REQUIRED:"hash_attribute is required",ID_REQUIRED:"id is required",IDS_REQUIRED:"ids is required",IDS_MUST_BE_ITERABLE:"ids must be iterable",FETCH_ATTRIBUTES_REQUIRED:"fetch_attributes is required",FETCH_ATTRIBUTES_MUST_BE_ARRAY:"fetch_attributes must be an array",ATTRIBUTE_REQUIRED:"attribute is required",SEARCH_VALUE_REQUIRED:"search_value is required",SEARCH_VALUE_TOO_LARGE:"search_value is too long",WRITE_ATTRIBUTES_REQUIRED:"write_attributes is required",WRITE_ATTRIBUTES_MUST_BE_ARRAY:"write_attributes must be an array",RECORDS_REQUIRED:"records is required",RECORDS_MUST_BE_ARRAY:"records must be an array",CANNOT_CREATE_INTERNAL_DBIS_NAME:`cannot create a dbi named ${iO.INTERNAL_DBIS_NAME}`,CANNOT_DROP_INTERNAL_DBIS_NAME:`cannot drop a dbi named ${iO.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"},zG={ATTR_NAME_LENGTH_ERR:e=>`transaction aborted due to attribute name ${e} being too long. Attribute names cannot be longer than ${sO.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 ${sO.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"},uO={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"},JG={DEFAULT_INVALID_REQUEST:"Invalid request",OP_AUTH_PERMS_ERROR:"This operation is not authorized due to role restrictions and/or invalid database items",OP_IS_SU_ONLY:e=>`Operation '${e}' is restricted to 'super_user' roles`,OP_NOT_FOUND:e=>`Operation '${e}' not found`,SYSTEM_TIMESTAMP_PERMS_ERR:"Internal timestamp attributes - '__createdtime_' and '__updatedtime__' - cannot be inserted to or updated by HDB users.",UNKNOWN_OP_AUTH_ERROR:(e,t,r)=>`There was an error authorizing ${e} op on table '${t}.${r}'`,USER_HAS_NO_PERMS:e=>`User ${e} has no role or permissions. Please assign the user a valid role.`,DROP_SYSTEM:"The 'system' database, tables and records are used internally by HarperDB and cannot be updated or removed."},jG={ATTR_PERM_MISSING:(e,t)=>`${e.toUpperCase()} attribute permission missing for '${t}'`,ATTR_PERM_MISSING_NAME:"Permission object in 'attribute_permission' missing an 'attribute_name'",ATTR_PERM_NOT_BOOLEAN:(e,t)=>`${e.toUpperCase()} attribute permission for '${t}' must be a boolean`,ATTR_PERMS_ARRAY_MISSING:"Missing 'attribute_permissions' array",ATTR_PERMS_NOT_ARRAY:"Value for 'attribute_permissions' must be an array",INVALID_ATTRIBUTE_IN_PERMS:e=>`Invalid attribute '${e}' in 'attribute_permissions'`,INVALID_PERM_KEY:e=>`Invalid table permission key value '${e}'`,INVALID_ATTR_PERM_KEY:e=>`Invalid attribute permission key value '${e}'`,INVALID_ROLE_JSON_KEYS:e=>`Invalid ${e.length>1?"keys":"key"} in JSON body - '${e.join("', '")}'`,MISMATCHED_TABLE_ATTR_PERMS:e=>`You have a conflict with TABLE permissions for '${e}' being false and ATTRIBUTE permissions being true`,OUTDATED_PERMS_TRANSLATION_ERROR:"This instance was recently upgraded and uses our new role permissions structure. Please login to this instance in HarperDB Studio, go to 'Roles', and click 'Update Role Permission' for all standard roles to migrate them to the new structure.",ROLE_ALREADY_EXISTS:e=>`A role with name '${e}' already exists`,ROLE_NOT_FOUND:"Role not found",ROLE_PERMS_ERROR:"Errors in the role permissions JSON provided",SCHEMA_PERM_ERROR:e=>`Your role does not have permission to view database metadata for '${e}'`,SCHEMA_TABLE_PERM_ERROR:(e,t)=>`Your role does not have permission to view database.table metadata for '${e}.${t}'`,SU_ROLE_MISSING_ERROR:"Missing 'super_user' key/value in permission set",SU_CU_ROLE_BOOLEAN_ERROR:e=>`Value for '${e}' permission must be a boolean`,STRUCTURE_USER_ROLE_TYPE_ERROR:e=>`Value for '${e}' permission must be a boolean or Array`,SU_CU_ROLE_NO_PERMS_ALLOWED:e=>`Roles with '${e}' set to true cannot have other permissions set.`,SU_CU_ROLE_COMBINED_ERROR:"Roles cannot have both 'super_user' and 'cluster_user' values included in their permissions set.",TABLE_PERM_MISSING:e=>`Missing table ${e.toUpperCase()} permission`,TABLE_PERM_NOT_BOOLEAN:e=>`Table ${e.toUpperCase()} permission must be a boolean`},XG={ATTR_NOT_FOUND:(e,t,r)=>`Attribute '${r}' does not exist on '${e}.${t}'`,ATTR_EXISTS_ERR:(e,t,r)=>`Attribute '${r}' already exists in ${e}.${t}'`,DESCRIBE_ALL_ERR:"There was an error during describeAll. Please check the logs and try again.",INVALID_TABLE_ERR:e=>`Invalid table ${JSON.stringify(e)}`,SCHEMA_NOT_FOUND:e=>`database '${e}' does not exist`,SCHEMA_EXISTS_ERR:e=>`database '${e}' already exists`,TABLE_EXISTS_ERR:(e,t)=>`Table '${t}' already exists in '${e}'`,SCHEMA_REQUIRED_ERR:"database is required",TABLE_NOT_FOUND:(e,t)=>`Table '${e}.${t}' does not exist`,TABLE_REQUIRED_ERR:"table is required"},ZG={OUTER_JOIN_TRANSLATION_ERROR:"There was an error translating the final SQL outer join data."},ek={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`},lO={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.`},_O={INVALID_ITC_DATA_TYPE:"Invalid ITC event data type, must be an object",MISSING_TYPE:"ITC event missing 'type'",MISSING_MSG:"ITC event missing 'message'",MISSING_ORIGIN:"ITC event message missing 'originator' property",INVALID_EVENT:e=>`ITC server received invalid event type: ${e}`},tk={FUNCTION_STATUS:"Error getting custom function status, check the log for more details",GET_FUNCTIONS:"Error getting custom functions, check the log for more details",GET_FUNCTION:"Error getting custom function, check the log for more details",SET_FUNCTION:"Error setting custom function, check the log for more details",NO_PROJECT:"Project does not exist. Create one using 'add_custom_function_project'",PROJECT_EXISTS:"Project already exists",VALIDATION_ERR:"Error validating request, check the log for more details",NO_FILE:"File does not exist",BAD_FILE_NAME:"File name can only contain alphanumeric, dash and underscore characters",BAD_PROJECT_NAME:"Project name can only contain alphanumeric, dash and underscores characters",BAD_PACKAGE:"Packaged project must be base64-encoded tar file of project directory",DROP_FUNCTION:"Error dropping custom function, check the log for more details",ADD_FUNCTION:"Error adding custom function project, check the log for more details",DROP_FUNCTION_PROJECT:"Error dropping custom function project, check the log for more details",BAD_FILE_PATH:"Filepath must be valid, and contain the name of the tarball you wish to write",NOT_ENABLED:"Custom functions is not enabled, to enable set fastifyRoutes enabled to true in hdb/harperdb-config.yaml file."},rk={CLUSTERING_NOT_ENABLED:"Clustering must be enabled to perform this operation."},nk={...uO,...WG,...YG,...JG,...jG,...XG,...ZG,...ek,...zG,...lO,..._O,...tk,...rk,...KG};dO.exports={CHECK_LOGS_WRAPPER:aO,HDB_ERROR_MSGS:nk,DEFAULT_ERROR_MSGS:cO,DEFAULT_ERROR_RESP:$G,HTTP_STATUS_CODES:oO,LMDB_ERRORS_ENUM:QG,AUTHENTICATION_ERROR_MSGS:uO,VALIDATION_ERROR_MSGS:lO,ITC_ERRORS:_O}});var ee=g((roe,hO)=>{"use strict";var Mo=Or(),sk=Y(),ik=M(),Hl=class extends Error{static{a(this,"HdbError")}constructor(t,r,n,s,i){super(),Error.captureStackTrace(this,fO),this.statusCode=n||Mo.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR,this.http_resp_msg=r||(Mo.DEFAULT_ERROR_MSGS[n]?Mo.DEFAULT_ERROR_MSGS[n]:Mo.DEFAULT_ERROR_MSGS[Mo.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR]),this.message=t.message?t.message:this.http_resp_msg,this.type=t.name,s&&(this.logLevel=s),typeof this.message!="string"&&(this.stack=t.stack),i&&sk[s](i)}},_h=class extends Error{static{a(this,"ClientError")}constructor(t,r){if(t instanceof Error)return t.statusCode=r||400,t;super(t),this.statusCode=r||400}},dh=class extends Error{static{a(this,"ServerError")}constructor(t,r){super(t),this.statusCode=r||500}};function fO(e,t,r,n=ik.LOG_LEVELS.ERROR,s=null,i=!1){if(EO(e))return e;let o=new Hl(e,t,r,n,s);return i&&delete o.stack,o}a(fO,"handleHDBError");function EO(e){return e.__proto__.constructor.name===Hl.name}a(EO,"isHDBError");hO.exports={isHDBError:EO,handleHDBError:fO,ClientError:_h,ServerError:dh,hdb_errors:Mo}});var pO=g((soe,mO)=>{"use strict";var ok={key:"-----BEGIN RSA PRIVATE KEY-----\rMIIEowIBAAKCAQEArBFJQRfFiJku/KwhV1Ssp7cX61vvuKmd4Rp6A9jB2QLgx8nj\r/+Xhp2hPRkISnOA8BuAxr4dMD9syGJwX4kNy9mbZ5Q0fWZCiEGBpVcU1J+k+N5K4\rSuZ2SqgxeN2IN2RLzt3GyQY4imcdHgNv7aHoXUrEwBx0MeYEw3IIDXtrYKCR2D8I\rvWBfwMUgWa24G8lpWILWA5hd9srRz9NxlAiHSjhbgT7B0xruEpHRCHSyKjvaIJVt\rWBR+amejYsAKVrD/hgrqjsA1123Y6++YqvU6vwg64xhS2kz5r3dkNKhvwbWgpZdI\rIaRvsiB77f4kLGo0vi8RFgJ1ZRjGg3RRK2w1LQIDAQABAoIBAQCEOmh78EOpnGZC\rYBjjHrvrysVD5gvLcfVUtl8Ls7gMB60re1eOIF+PoZZCHKZnDd6zPfiQtj1adg0C\rYnnsM/8VoaZS4gm0b3RLd3ubIQifWhuo40RissY2yxfxlPSH9LhZCY8ojnJG0cTL\resK579E8WCfopjUY33XLqEbN7Ylv39J+DSqInjqV3efJZUa+HqUJ98VxxzodcKMD\rP3bwUU4gHoSSp4pAsOFH5sQhaIWH1IcNjrAwpee2cJQuh4G157RRIuuUpagtaEG/\rXJIiAyBguJyu3JQFnIBQF01N5+omJgXYJ1L0m54543/iIRThmF3zDCDgCyUzmOk+\rH6As9fv1AoGBANOpOtOZLSAScjGsgJamT3ceJ2wCa86g2j8Oxu8lJUmUp5s3tA0v\rBFW5O3S4KR1EXwkLMBUMrfFM8YvzHWxsXBI6XV8azGLvyqPHxr65OhmpGYkGZMXu\rn9okgjkqlewnY2I073gvyK7ppX51UL5y9fF1vlsk+UlW+Rgx/vMHbdcjAoGBANAc\rxRUsxs4QJpbS4zD3JOkHjr24a97TrS3kCybAHUMpR2NrEHPZw9zex0/aphOJUHfL\rIMkOZdpfDqMfxWy4FAEmqBEMkO2SB+h0Wp4P+qp81ax4vGFiB0cD3wtixr11U1tt\rlZ/ZTdv4VDpDFNK1KaplhTDeyuCjeYfS3/GJia9vAoGAcOsAgjBevZR5rXx84WH6\rVO8WUu37u7FenXNxt9VWTinrPMh72uixZFY8nOk+rely1e1NCn3IMko9Ns9NbDFm\r8SaH95vhXArXTYbfxZIlp9jp0YtCqcHDL+p4Oq04bFMbFyJseu7rHj1x18QYfnHw\rOY/6LL/N6k1m+Hx7qgXVmIcCgYB/w0nTCBw84XlvWqSTqQaF8VfWbWP79mP5KmkW\rLxdH5g2noVEGbohqDnK6OXd/wusdwByukiJBf94Skyy25AOT+VFwthA7aU1ljhkb\rtJ+lDuJ28eBkwLPLCzthWBC+u0qjdJFJAzVjd/7tjcU43nNn4s90AzL12iaAFhvZ\rwyA+DQKBgGc/4cdyGJ3YkcA8150gQBawgJZ7q8V1JND87ggWA8wnK3cHn7rMZQl2\r3emDp9HEFXFex5dbGDDqZFAoesZCDxjknIn9oNfW4PvaWS8q7b6ZKLZG1p03Pu7/\rtYaD0kPbo0kysfFT/co+NgHbdykvIyboomfGdNLTUjYuy6lpwpvs\r-----END RSA PRIVATE KEY-----\r".replace(/\r/g,`\r
|
|
1
|
+
"use strict";var eq=Object.create;var Ja=Object.defineProperty;var tq=Object.getOwnPropertyDescriptor;var rq=Object.getOwnPropertyNames;var nq=Object.getPrototypeOf,sq=Object.prototype.hasOwnProperty;var a=(e,t)=>Ja(e,"name",{value:t,configurable:!0});var Oe=(e,t)=>()=>(e&&(t=e(e=0)),t);var T=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),ke=(e,t)=>{for(var r in t)Ja(e,r,{get:t[r],enumerable:!0})},NA=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of rq(t))!sq.call(e,s)&&s!==r&&Ja(e,s,{get:()=>t[s],enumerable:!(n=tq(t,s))||n.enumerable});return e};var x=(e,t,r)=>(r=e!=null?eq(nq(e)):{},NA(t||!e||!e.__esModule?Ja(r,"default",{value:e,enumerable:!0}):r,e)),te=e=>NA(Ja({},"__esModule",{value:!0}),e);var CA=T((kie,IA)=>{var iq=require("fast-glob"),{statSync:jE,existsSync:XE,readFileSync:oq,writeFileSync:aq}=require("fs"),{spawnSync:cq,spawn:uq,execFileSync:Gie}=require("child_process"),{isMainThread:lq}=require("worker_threads"),{join:Ys,relative:wA}=require("path"),{PACKAGE_ROOT:Sn}=U(),{tmpdir:_q,platform:dq}=require("os");require("source-map-support").install();var fq=["resources","server","dataLayer","components"],ja="ts-build",ZE,Eq=__filename.endsWith("tsBuild.js");if(Eq){if(lq){let r;try{jE(Ys(Sn,ja)),r=!0}catch{}if(r)for(let n of iq.sync(fq.map(s=>s+"/**/*.ts"),{cwd:Sn})){let s=0,i=0;try{s=jE(Ys(Sn,n)).mtimeMs-5e3,i=jE(Ys(Sn,ja,n.replace(/.ts$/,".js"))).mtimeMs}catch{}if(s>i){console.warn(`TypeScript ${n} is not compiled`+(i?` (TS source file was modified at ${new Date(s)} and compiled file at ${new Date(i)})`:"")+", consider enabling auto-compilation of TypeScript in your IDE), compiling now."),ZE=!0;break}}else console.log("TypeScript modules are not compiled, compiling now"),ZE=!0;if(ZE){let n=Ys(Sn,"node_modules/.bin/tsc");dq()==="win32"&&(n+=".cmd");let s=cq(n,{cwd:Sn});if(s.stdout.length&&console.log(s.stdout.toString()),s.stderr.length&&console.log(s.stderr.toString()),r){let i=Ys(_q(),"harperdb-tsc.pid"),o;if(XE(i))try{process.kill(+oq(i,{encoding:"utf8"}),0),o=!0}catch{}if(!o){console.log("starting tsc background process");let c=uq(n,["--watch"],{cwd:Sn,detached:!0,stdio:"ignore"});aq(i,c.pid.toString()),c.unref()}}}}let e=IA.constructor,t=e._findPath;e._findPath=function(r,n,s){if(r.startsWith(".")&&!s&&n.length===1&&n[0].startsWith(Sn)&&!n[0].includes("node_modules")){let i=wA(Sn,n[0]),o;i.startsWith(ja)?o=Ys(Sn,wA(ja,i)):o=Ys(Sn,ja,i);let c=Ys(o,r),u=c+".js";if(XE(u))return u;if(c.includes(".")&&XE(c))return c}return t(r,n,s)}}});var U=T((Yie,VA)=>{"use strict";var jr=require("path"),hq=require("fs"),{relative:Vie,join:$ie}=jr,{existsSync:mq}=hq;function pq(){let e=__dirname;for(;!mq(jr.join(e,"package.json"));){let t=jr.dirname(e);if(t===e)throw new Error("Could not find package root");e=t}return e}a(pq,"getHDBPackageRoot");var Ks=pq(),DA="js",Ll=DA,Sq="harperdb-config.yaml",Tq="defaultConfig.yaml",gq="hdb",LA=`harperdb.${Ll}`,MA=`customFunctionsServer.${Ll}`,Rq=`restartHdb.${Ll}`,th="HarperDB",Dl="Custom Functions",Ml="Clustering Hub",Ul="Clustering Leaf",Aq="Clustering Ingest Service",Oq="Clustering Reply Service",bq="foreground.pid",yq="hdb.pid",Nq="data",wq={HDB:th,CLUSTERING_HUB:Ml,CLUSTERING_LEAF:Ul,CLUSTERING_INGEST_SERVICE:Aq,CLUSTERING_REPLY_SERVICE:Oq,CUSTOM_FUNCTIONS:Dl,RESTART_HDB:"Restart HDB",INSTALL:"Install",RUN:"Run",STOP:"Stop",UPGRADE:"Upgrade",REGISTER:"Register",JOB:"Job",CLUSTERING_UPGRADE_4_0_0:"Upgrade-4-0-0"},Iq={HDB:"hdb.log",INSTALL:"install.log",CLUSTERING_HUB:"clustering_hub.log",CLUSTERING_LEAF:"clustering_leaf.log"},Cq={NOTIFY:"notify",FATAL:"fatal",ERROR:"error",WARN:"warn",INFO:"info",DEBUG:"debug",TRACE:"trace"},Dq={harperdb:th,"clustering hub":Ml,"clustering leaf":Ul,"custom functions":Dl,custom_functions:Dl,clustering:"clustering","clustering config":"clustering config",clustering_config:"clustering_config",http_workers:"http_workers"},Lq={CLUSTERING_HUB_PROC_DESCRIPTOR:Ml,CLUSTERING_LEAF_PROC_DESCRIPTOR:Ul},eh={HDB:jr.join(Ks,"server/harperdb"),CUSTOM_FUNCTIONS:jr.join(Ks,"server/customFunctions"),CLUSTERING_HUB:jr.join(Ks,"server/nats"),CLUSTERING_LEAF:jr.join(Ks,"server/nats")},Mq={HDB:jr.join(eh.HDB,LA),CUSTOM_FUNCTIONS:jr.join(eh.CUSTOM_FUNCTIONS,MA)},Uq={MAIN:"bin/harperdb.js",NATS_INGEST_SERVICE:jr.join(Ks,"launchServiceScripts/launchNatsIngestService.js"),NATS_REPLY_SERVICE:jr.join(Ks,"launchServiceScripts/launchNatsReplyService.js"),NODES_UPGRADE_4_0_0:jr.join(Ks,"launchServiceScripts/launchUpdateNodes4-0-0.js")},Pq={SUPER_USER:"super_user",CLUSTER_USER:"cluster_user"},UA="support@harperdb.io",vq="customer-success@harperdb.io",PA=1,Bq=4141,vA="https://harperdbhelp.zendesk.com/hc/en-us/requests/new",Hq="https://www.harperdb.io/product",xq=`For support, please submit a request at ${vA} or contact ${UA}`,BA=`For license support, please contact ${vq}`,qq="None of the specified records were found.",Fq="hash attribute not found",Gq=`Your current license only supports ${PA} role. ${BA}`,kq="Your current license only supports 3 connections to a node.",Vq="127.0.0.1",$q=1,Yq=/^\.$/,Kq=/^\.\.$/,Wq="U+002E",Qq=/\//g,zq="U+002F",Jq=/U\+002F/g,jq=/^U\+002E$/,Xq=/^U\+002EU\+002E$/,Zq="d",eF=999999,tF="*",rF="--max-old-space-size=",nF="system",sF="__hdb_hash",iF=".harperdb",oF=".hdb",aF="keys",cF="hdb_boot_properties.file",uF=".updateConfig.json",lF="SIGTSTP",_F=24,dF=6e4,fF=448,EF="blob",hF="trash",mF="database",pF="schema",SF="transactions",TF=".count",gF="id",RF="PROCESS_NAME",HA={SETTINGS_PATH_KEY:"settings_path"},xA=require("lodash"),AF={TC_AGREEMENT:"TC_AGREEMENT",CLUSTERING_USER:"CLUSTERING_USER",CLUSTERING_PASSWORD:"CLUSTERING_PASSWORD",HDB_ADMIN_USERNAME:"HDB_ADMIN_USERNAME",HDB_ADMIN_PASSWORD:"HDB_ADMIN_PASSWORD",OPERATIONSAPI_ROOT:"OPERATIONSAPI_ROOT",ROOTPATH:"ROOTPATH",OPERATIONSAPI_NETWORK_PORT:"OPERATIONSAPI_NETWORK_PORT",CLUSTERING_NODENAME:"CLUSTERING_NODENAME",CLUSTERING_ENABLED:"CLUSTERING_ENABLED",HDB_CONFIG:"HDB_CONFIG",OPERATIONSAPI_NETWORK_SECUREPORT:"OPERATIONSAPI_NETWORK_SECUREPORT",CLUSTERING_PORT:"CLUSTERING_PORT",HDB_ROOT:"HDB_ROOT",SERVER_PORT:"SERVER_PORT",NODE_NAME:"NODE_NAME",CLUSTERING:"CLUSTERING"},OF={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},bF={DATA_VERSION:"data_version",UPGRADE_VERSION:"upgrade_version"},yF={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"},NF={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"},Or="hdb_internal:",wF={CREATE_SCHEMA:Or+"create_schema",CREATE_TABLE:Or+"create_table",CREATE_ATTRIBUTE:Or+"create_attribute",ADD_USER:Or+"add_user",ALTER_USER:Or+"alter_user",DROP_USER:Or+"drop_user",HDB_NODES:Or+"hdb_nodes",HDB_USERS:Or+"hdb_users",HDB_WORKERS:Or+"hdb_workers",CATCHUP:Or+"catchup",SCHEMA_CATCHUP:Or+"schema_catchup",WORKER_ROOM:Or+"cluster_workers"},IF={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"},CF="060493.ks",DF=".license",LF={CREATED:"CREATED",IN_PROGRESS:"IN_PROGRESS",COMPLETE:"COMPLETE",ERROR:"ERROR"},j={INSERT:"insert",UPDATE:"update",UPSERT:"upsert",SEARCH_BY_CONDITIONS:"search_by_conditions",SEARCH_BY_HASH:"search_by_hash",SEARCH_BY_ID:"search_by_id",SEARCH_BY_VALUE:"search_by_value",SEARCH:"search",SQL:"sql",CSV_DATA_LOAD:"csv_data_load",CSV_FILE_LOAD:"csv_file_load",CSV_URL_LOAD:"csv_url_load",CREATE_SCHEMA:"create_schema",CREATE_DATABASE:"create_database",CREATE_TABLE:"create_table",CREATE_ATTRIBUTE:"create_attribute",DROP_SCHEMA:"drop_schema",DROP_DATABASE:"drop_database",DROP_TABLE:"drop_table",DESCRIBE_SCHEMA:"describe_schema",DESCRIBE_DATABASE:"describe_database",DESCRIBE_TABLE:"describe_table",DESCRIBE_ALL:"describe_all",DELETE:"delete",ADD_USER:"add_user",ALTER_USER:"alter_user",DROP_USER:"drop_user",LIST_USERS:"list_users",LIST_ROLES:"list_roles",ADD_ROLE:"add_role",ALTER_ROLE:"alter_role",DROP_ROLE:"drop_role",USER_INFO:"user_info",READ_LOG:"read_log",ADD_NODE:"add_node",UPDATE_NODE:"update_node",SET_NODE_REPLICATION:"set_node_replication",EXPORT_TO_S3:"export_to_s3",IMPORT_FROM_S3:"import_from_s3",DELETE_FILES_BEFORE:"delete_files_before",DELETE_RECORDS_BEFORE:"delete_records_before",EXPORT_LOCAL:"export_local",SEARCH_JOBS_BY_START_DATE:"search_jobs_by_start_date",GET_JOB:"get_job",DELETE_JOB:"delete_job",UPDATE_JOB:"update_job",GET_FINGERPRINT:"get_fingerprint",SET_LICENSE:"set_license",GET_REGISTRATION_INFO:"registration_info",CONFIGURE_CLUSTER:"configure_cluster",SET_CONFIGURATION:"set_configuration",CLUSTER_STATUS:"cluster_status",CLUSTER_NETWORK:"cluster_network",DROP_ATTRIBUTE:"drop_attribute",REMOVE_NODE:"remove_node",RESTART:"restart",RESTART_SERVICE:"restart_service",CATCHUP:"catchup",SYSTEM_INFORMATION:"system_information",DELETE_AUDIT_LOGS_BEFORE:"delete_audit_logs_before",READ_AUDIT_LOG:"read_audit_log",CREATE_AUTHENTICATION_TOKENS:"create_authentication_tokens",LOGIN:"login",LOGOUT:"logout",REFRESH_OPERATION_TOKEN:"refresh_operation_token",GET_CONFIGURATION:"get_configuration",CUSTOM_FUNCTIONS_STATUS:"custom_functions_status",GET_CUSTOM_FUNCTIONS:"get_custom_functions",GET_CUSTOM_FUNCTION:"get_custom_function",SET_CUSTOM_FUNCTION:"set_custom_function",GET_COMPONENTS:"get_components",GET_COMPONENT_FILE:"get_component_file",SET_COMPONENT_FILE:"set_component_file",DROP_COMPONENT:"drop_component",DROP_CUSTOM_FUNCTION:"drop_custom_function",ADD_CUSTOM_FUNCTION_PROJECT:"add_custom_function_project",ADD_COMPONENT:"add_component",DROP_CUSTOM_FUNCTION_PROJECT:"drop_custom_function_project",PACKAGE_CUSTOM_FUNCTION_PROJECT:"package_custom_function_project",DEPLOY_CUSTOM_FUNCTION_PROJECT:"deploy_custom_function_project",PACKAGE_COMPONENT:"package_component",DEPLOY_COMPONENT:"deploy_component",CLUSTER_SET_ROUTES:"cluster_set_routes",CLUSTER_DELETE_ROUTES:"cluster_delete_routes",CLUSTER_GET_ROUTES:"cluster_get_routes",READ_TRANSACTION_LOG:"read_transaction_log",DELETE_TRANSACTION_LOGS_BEFORE:"delete_transaction_logs_before",INSTALL_NODE_MODULES:"install_node_modules",AUDIT_NODE_MODULES:"audit_node_modules",PURGE_STREAM:"purge_stream",GET_BACKUP:"get_backup"},MF={CSV:".csv",JSON:".json"},UF={AWS_ACCESS_KEY:"aws_access_key_id",AWS_SECRET:"aws_secret_access_key",AWS_BUCKET:"bucket",AWS_FILE_KEY:"key",REGION:"region"},PF={SELECT:"select",INSERT:"insert",UPDATE:"update",DELETE:"delete"},Xa={};Xa[j.INSERT]=j.INSERT;Xa[j.UPDATE]=j.UPDATE;Xa[j.UPSERT]=j.UPSERT;Xa[j.DELETE]=j.DELETE;var Be=Object.create(null);Be[j.DESCRIBE_ALL]=j.DESCRIBE_ALL;Be[j.DESCRIBE_TABLE]=j.DESCRIBE_TABLE;Be[j.DESCRIBE_SCHEMA]=j.DESCRIBE_SCHEMA;Be[j.READ_LOG]=j.READ_LOG;Be[j.ADD_NODE]=j.ADD_NODE;Be[j.LIST_USERS]=j.LIST_USERS;Be[j.LIST_ROLES]=j.LIST_ROLES;Be[j.USER_INFO]=j.USER_INFO;Be[j.SQL]=j.SQL;Be[j.GET_JOB]=j.GET_JOB;Be[j.SEARCH_JOBS_BY_START_DATE]=j.SEARCH_JOBS_BY_START_DATE;Be[j.DELETE_FILES_BEFORE]=j.DELETE_FILES_BEFORE;Be[j.EXPORT_LOCAL]=j.EXPORT_LOCAL;Be[j.EXPORT_TO_S3]=j.EXPORT_TO_S3;Be[j.CLUSTER_STATUS]=j.CLUSTER_STATUS;Be[j.REMOVE_NODE]=j.REMOVE_NODE;Be[j.RESTART]=j.RESTART;Be[j.CUSTOM_FUNCTIONS_STATUS]=j.CUSTOM_FUNCTIONS_STATUS;Be[j.GET_CUSTOM_FUNCTIONS]=j.GET_CUSTOM_FUNCTIONS;Be[j.GET_CUSTOM_FUNCTION]=j.GET_CUSTOM_FUNCTION;Be[j.SET_CUSTOM_FUNCTION]=j.SET_CUSTOM_FUNCTION;Be[j.DROP_CUSTOM_FUNCTION]=j.DROP_CUSTOM_FUNCTION;Be[j.ADD_CUSTOM_FUNCTION_PROJECT]=j.ADD_CUSTOM_FUNCTION_PROJECT;Be[j.DROP_CUSTOM_FUNCTION_PROJECT]=j.DROP_CUSTOM_FUNCTION_PROJECT;Be[j.PACKAGE_CUSTOM_FUNCTION_PROJECT]=j.PACKAGE_CUSTOM_FUNCTION_PROJECT;Be[j.DEPLOY_CUSTOM_FUNCTION_PROJECT]=j.DEPLOY_CUSTOM_FUNCTION_PROJECT;var vF={DEV:"dev",RUN:"run",START:"start",INSTALL:"install",REGISTER:"register",STOP:"stop",RESTART:"restart",VERSION:"version",UPGRADE:"upgrade",HELP:"help",STATUS:"status",OPERATION:"operation",RENEWCERTS:"renew-certs"},BF={point:"point",lineString:"lineString",multiLineString:"multiLineString",multiPoint:"multiPoint",multiPolygon:"multiPolygon",polygon:"polygon"},qA={HDB_ROOT_KEY:"HDB_ROOT",SERVER_PORT_KEY:"SERVER_PORT",CERT_KEY:"CERTIFICATE",PRIVATE_KEY_KEY:"PRIVATE_KEY",HTTP_SECURE_ENABLED_KEY:"HTTPS_ON",CORS_ENABLED_KEY:"CORS_ON",CORS_WHITELIST_KEY:"CORS_WHITELIST",LOG_LEVEL_KEY:"LOG_LEVEL",LOGGER_KEY:"LOGGER",LOG_PATH_KEY:"LOG_PATH",LOG_ROTATE:"LOG_ROTATE",LOG_ROTATE_MAX_SIZE:"LOG_ROTATE_MAX_SIZE",LOG_ROTATE_RETAIN:"LOG_ROTATE_RETAIN",LOG_ROTATE_COMPRESS:"LOG_ROTATE_COMPRESS",LOG_ROTATE_DATE_FORMAT:"LOG_ROTATE_DATE_FORMAT",LOG_ROTATE_ROTATE_MODULE:"LOG_ROTATE_ROTATE_MODULE",LOG_ROTATE_WORKER_INTERVAL:"LOG_ROTATE_WORKER_INTERVAL",LOG_ROTATE_ROTATE_INTERVAL:"LOG_ROTATE_ROTATE_INTERVAL",LOG_ROTATE_TIMEZONE:"LOG_ROTATE_TIMEZONE",LOG_DAILY_ROTATE_KEY:"LOG_DAILY_ROTATE",LOG_MAX_DAILY_FILES_KEY:"LOG_MAX_DAILY_FILES",PROPS_ENV_KEY:"NODE_ENV",SETTINGS_PATH_KEY:"settings_path",CLUSTERING_PORT_KEY:"CLUSTERING_PORT",CLUSTERING_NODE_NAME_KEY:"NODE_NAME",CLUSTERING_ENABLED_KEY:"CLUSTERING",ALLOW_SELF_SIGNED_SSL_CERTS:"ALLOW_SELF_SIGNED_SSL_CERTS",MAX_HDB_PROCESSES:"MAX_HDB_PROCESSES",INSTALL_USER:"install_user",CLUSTERING_USER_KEY:"CLUSTERING_USER",MAX_CLUSTERING_PROCESSES:"MAX_CLUSTERING_PROCESSES",SERVER_TIMEOUT_KEY:"SERVER_TIMEOUT_MS",SERVER_KEEP_ALIVE_TIMEOUT_KEY:"SERVER_KEEP_ALIVE_TIMEOUT",SERVER_HEADERS_TIMEOUT_KEY:"SERVER_HEADERS_TIMEOUT",DISABLE_TRANSACTION_LOG_KEY:"DISABLE_TRANSACTION_LOG",OPERATION_TOKEN_TIMEOUT_KEY:"OPERATION_TOKEN_TIMEOUT",REFRESH_TOKEN_TIMEOUT_KEY:"REFRESH_TOKEN_TIMEOUT",CUSTOM_FUNCTIONS_ENABLED_KEY:"CUSTOM_FUNCTIONS",CUSTOM_FUNCTIONS_PORT_KEY:"CUSTOM_FUNCTIONS_PORT",CUSTOM_FUNCTIONS_DIRECTORY_KEY:"CUSTOM_FUNCTIONS_DIRECTORY",MAX_CUSTOM_FUNCTION_PROCESSES:"MAX_CUSTOM_FUNCTION_PROCESSES",LOG_TO_FILE:"LOG_TO_FILE",LOG_TO_STDSTREAMS:"LOG_TO_STDSTREAMS",RUN_IN_FOREGROUND:"RUN_IN_FOREGROUND",LOCAL_STUDIO_ON:"LOCAL_STUDIO_ON",STORAGE_WRITE_ASYNC:"STORAGE_WRITE_ASYNC"},HF=xA.invert(qA),xF={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"},C={ANALYTICS_AGGREGATEPERIOD:"analytics_aggregatePeriod",AUTHENTICATION_AUTHORIZELOCAL:"authentication_authorizeLocal",AUTHENTICATION_CACHETTL:"authentication_cacheTTL",AUTHENTICATION_ENABLESESSIONS:"authentication_enableSessions",AUTHENTICATION_OPERATIONTOKENTIMEOUT:"authentication_operationTokenTimeout",AUTHENTICATION_REFRESHTOKENTIMEOUT:"authentication_refreshTokenTimeout",CLUSTERING_USER:"clustering_user",CLUSTERING_ENABLED:"clustering_enabled",CLUSTERING_HUBSERVER_CLUSTER_NAME:"clustering_hubServer_cluster_name",CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT:"clustering_hubServer_cluster_network_port",CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES:"clustering_hubServer_cluster_network_routes",CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT:"clustering_hubServer_leafNodes_network_port",CLUSTERING_HUBSERVER_NETWORK_PORT:"clustering_hubServer_network_port",CLUSTERING_LEAFSERVER_NETWORK_PORT:"clustering_leafServer_network_port",CLUSTERING_LEAFSERVER_NETWORK_ROUTES:"clustering_leafServer_network_routes",CLUSTERING_LEAFSERVER_STREAMS_MAXAGE:"clustering_leafServer_streams_maxAge",CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES:"clustering_leafServer_streams_maxBytes",CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS:"clustering_leafServer_streams_maxMsgs",CLUSTERING_LEAFSERVER_STREAMS_PATH:"clustering_leafServer_streams_path",CLUSTERING_NODENAME:"clustering_nodeName",CLUSTERING_TLS_CERTIFICATE:"clustering_tls_certificate",CLUSTERING_TLS_PRIVATEKEY:"clustering_tls_privateKey",CLUSTERING_TLS_CERT_AUTH:"clustering_tls_certificateAuthority",CLUSTERING_TLS_INSECURE:"clustering_tls_insecure",CLUSTERING_TLS_VERIFY:"clustering_tls_verify",CLUSTERING_LOGLEVEL:"clustering_logLevel",CLUSTERING_REPUBLISHMESSAGES:"clustering_republishMessages",CLUSTERING_DATABASELEVEL:"clustering_databaseLevel",CUSTOMFUNCTIONS_NETWORK_HTTPS:"customFunctions_network_https",THREADS:"threads",MAXHEAPMEMORY:"maxHeapMemory",HTTP_SESSIONAFFINITY:"http_sessionAffinity",HTTP_COMPRESSIONTHRESHOLD:"http_compressionThreshold",HTTP_CORS:"http_cors",HTTP_CORSACCESSLIST:"http_corsAccessList",HTTP_HEADERSTIMEOUT:"http_headersTimeout",HTTP_KEEPALIVETIMEOUT:"http_keepAliveTimeout",HTTP_TIMEOUT:"http_timeout",HTTP_PORT:"http_port",HTTP_SECUREPORT:"http_securePort",HTTP_MTLS:"http_mtls",HTTP_MTLS_REQUIRED:"http_mtls_required",HTTP_MTLS_USER:"http_mtls_user",LOCALSTUDIO_ENABLED:"localStudio_enabled",LOGGING_FILE:"logging_file",LOGGING_LEVEL:"logging_level",LOGGING_ROOT:"logging_root",LOGGING_ROTATION_ENABLED:"logging_rotation_enabled",LOGGING_ROTATION_COMPRESS:"logging_rotation_compress",LOGGING_ROTATION_INTERVAL:"logging_rotation_interval",LOGGING_ROTATION_MAXSIZE:"logging_rotation_maxSize",LOGGING_ROTATION_PATH:"logging_rotation_path",LOGGING_STDSTREAMS:"logging_stdStreams",LOGGING_AUDITLOG:"logging_auditLog",LOGGING_AUDITRETENTION:"logging_auditRetention",LOGGING_AUDITAUTHEVENTS_LOGFAILED:"logging_auditAuthEvents_logFailed",LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL:"logging_auditAuthEvents_logSuccessful",OPERATIONSAPI_NETWORK_CORS:"operationsApi_network_cors",OPERATIONSAPI_NETWORK_CORSACCESSLIST:"operationsApi_network_corsAccessList",OPERATIONSAPI_NETWORK_HEADERSTIMEOUT:"operationsApi_network_headersTimeout",OPERATIONSAPI_NETWORK_HTTPS:"operationsApi_network_https",OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT:"operationsApi_network_keepAliveTimeout",OPERATIONSAPI_NETWORK_PORT:"operationsApi_network_port",OPERATIONSAPI_NETWORK_DOMAINSOCKET:"operationsApi_network_domainSocket",OPERATIONSAPI_NETWORK_SECUREPORT:"operationsApi_network_securePort",OPERATIONSAPI_TLS_CERTIFICATE:"operationsApi_tls_certificate",OPERATIONSAPI_TLS_PRIVATEKEY:"operationsApi_tls_privateKey",OPERATIONSAPI_TLS_CERTIFICATEAUTHORITY:"operationsApi_tls_certificateAuthority",OPERATIONSAPI_NETWORK_TIMEOUT:"operationsApi_network_timeout",ROOTPATH:"rootPath",SERIALIZATION_BIGINT:"serialization_bigInt",STORAGE_WRITEASYNC:"storage_writeAsync",STORAGE_OVERLAPPINGSYNC:"storage_overlappingSync",STORAGE_CACHING:"storage_caching",STORAGE_COMPRESSION:"storage_compression",STORAGE_NOREADAHEAD:"storage_noReadAhead",STORAGE_PREFETCHWRITES:"storage_prefetchWrites",STORAGE_ENCRYPTION:"storage_encryption",STORAGE_PATH:"storage_path",STORAGE_AUDIT_PATH:"storage_audit_path",DATABASES:"databases",IGNORE_SCRIPTS:"ignoreScripts",MQTT_NETWORK_PORT:"mqtt_network_port",MQTT_WEBSOCKET:"mqtt_webSocket",MQTT_NETWORK_SECUREPORT:"mqtt_network_securePort",MQTT_NETWORK_MTLS:"mqtt_network_mtls",MQTT_NETWORK_MTLS_REQUIRED:"mqtt_network_mtls_required",MQTT_NETWORK_MTLS_CERTIFICATEAUTHORITY:"mqtt_network_mtls_certificateAuthority",MQTT_NETWORK_MTLS_USER:"mqtt_network_mtls_user",MQTT_REQUIREAUTHENTICATION:"mqtt_requireAuthentication",COMPONENTSROOT:"componentsRoot",TLS_CERTIFICATE:"tls_certificate",TLS_PRIVATEKEY:"tls_privateKey",TLS_CERTIFICATEAUTHORITY:"tls_certificateAuthority",TLS_CIPHERS:"tls_ciphers"},FA={settings_path:HA.SETTINGS_PATH_KEY,hdb_root_key:C.ROOTPATH,hdb_root:C.ROOTPATH,rootpath:C.ROOTPATH,server_port_key:C.OPERATIONSAPI_NETWORK_PORT,server_port:C.OPERATIONSAPI_NETWORK_PORT,cert_key:C.TLS_CERTIFICATE,certificate:C.TLS_CERTIFICATE,private_key_key:C.TLS_PRIVATEKEY,private_key:C.TLS_PRIVATEKEY,http_secure_enabled_key:C.OPERATIONSAPI_NETWORK_HTTPS,https_on:C.OPERATIONSAPI_NETWORK_HTTPS,cors_enabled_key:C.OPERATIONSAPI_NETWORK_CORS,cors_on:C.OPERATIONSAPI_NETWORK_CORS,cors_whitelist_key:C.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_whitelist:C.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_accesslist_key:C.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_accesslist:C.OPERATIONSAPI_NETWORK_CORSACCESSLIST,log_level_key:C.LOGGING_LEVEL,log_level:C.LOGGING_LEVEL,log_path_key:C.LOGGING_ROOT,log_path:C.LOGGING_ROOT,clustering_node_name_key:C.CLUSTERING_NODENAME,node_name:C.CLUSTERING_NODENAME,clustering_enabled_key:C.CLUSTERING_ENABLED,clustering:C.CLUSTERING_ENABLED,max_http_threads:C.THREADS,max_hdb_processes:C.THREADS,server_timeout_key:C.OPERATIONSAPI_NETWORK_TIMEOUT,server_timeout_ms:C.OPERATIONSAPI_NETWORK_TIMEOUT,server_keep_alive_timeout_key:C.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT,server_keep_alive_timeout:C.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT,server_headers_timeout_key:C.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT,server_headers_timeout:C.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT,disable_transaction_log_key:C.LOGGING_AUDITLOG,disable_transaction_log:C.LOGGING_AUDITLOG,operation_token_timeout_key:C.AUTHENTICATION_OPERATIONTOKENTIMEOUT,operation_token_timeout:C.AUTHENTICATION_OPERATIONTOKENTIMEOUT,refresh_token_timeout_key:C.AUTHENTICATION_REFRESHTOKENTIMEOUT,refresh_token_timeout:C.AUTHENTICATION_REFRESHTOKENTIMEOUT,custom_functions_port_key:C.HTTP_PORT,custom_functions_port:C.HTTP_PORT,custom_functions_directory_key:C.COMPONENTSROOT,custom_functions_directory:C.COMPONENTSROOT,max_custom_function_processes:C.THREADS,log_to_file:C.LOGGING_FILE,log_to_stdstreams:C.LOGGING_STDSTREAMS,local_studio_on:C.LOCALSTUDIO_ENABLED,clustering_port:C.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT,clustering_user:C.CLUSTERING_USER,clustering_enabled:C.CLUSTERING_ENABLED,clustering_hubserver_cluster_name:C.CLUSTERING_HUBSERVER_CLUSTER_NAME,clustering_hubserver_cluster_network_port:C.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT,clustering_hubserver_cluster_network_routes:C.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,clustering_hubserver_leafnodes_network_port:C.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT,clustering_hubserver_network_port:C.CLUSTERING_HUBSERVER_NETWORK_PORT,clustering_leafserver_network_port:C.CLUSTERING_LEAFSERVER_NETWORK_PORT,clustering_leafserver_network_routes:C.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,clustering_leafserver_streams_maxage:C.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE,clustering_leafserver_streams_maxbytes:C.CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES,clustering_leafserver_streams_maxmsgs:C.CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS,clustering_leafserver_streams_path:C.CLUSTERING_LEAFSERVER_STREAMS_PATH,clustering_nodename:C.CLUSTERING_NODENAME,clustering_tls_certificate:C.CLUSTERING_TLS_CERTIFICATE,clustering_tls_privatekey:C.CLUSTERING_TLS_PRIVATEKEY,clustering_tls_certificateauthority:C.CLUSTERING_TLS_CERT_AUTH,clustering_tls_insecure:C.CLUSTERING_TLS_INSECURE,clustering_tls_verify:C.CLUSTERING_TLS_VERIFY,clustering_loglevel:C.CLUSTERING_LOGLEVEL,clustering_republishmessages:C.CLUSTERING_REPUBLISHMESSAGES,clustering_databaselevel:C.CLUSTERING_DATABASELEVEL,customfunctions_network_port:C.HTTP_PORT,customfunctions_tls_certificate:C.TLS_CERTIFICATE,customfunctions_network_cors:C.HTTP_CORS,customfunctions_network_corsaccesslist:C.HTTP_CORSACCESSLIST,customfunctions_network_headerstimeout:C.HTTP_HEADERSTIMEOUT,customfunctions_network_https:C.CUSTOMFUNCTIONS_NETWORK_HTTPS,customfunctions_network_keepalivetimeout:C.HTTP_KEEPALIVETIMEOUT,customfunctions_tls_privatekey:C.TLS_PRIVATEKEY,customfunctions_tls_certificateauthority:C.TLS_CERTIFICATEAUTHORITY,customfunctions_network_timeout:C.HTTP_TIMEOUT,http_threads:C.THREADS,threads:C.THREADS,maxheapmemory:C.MAXHEAPMEMORY,http_session_affinity:C.HTTP_SESSIONAFFINITY,http_compressionthreshold:C.HTTP_COMPRESSIONTHRESHOLD,http_cors:C.HTTP_CORS,http_corsaccesslist:C.HTTP_CORSACCESSLIST,http_headerstimeout:C.HTTP_HEADERSTIMEOUT,http_keepalivetimeout:C.HTTP_KEEPALIVETIMEOUT,http_timeout:C.HTTP_TIMEOUT,http_port:C.HTTP_PORT,http_secureport:C.HTTP_SECUREPORT,http_mtls:C.HTTP_MTLS,http_mtls_user:C.HTTP_MTLS_USER,http_mtls_required:C.HTTP_MTLS_REQUIRED,customfunctions_processes:C.THREADS,customfunctions_root:C.COMPONENTSROOT,localstudio_enabled:C.LOCALSTUDIO_ENABLED,logging_file:C.LOGGING_FILE,logging_level:C.LOGGING_LEVEL,logging_root:C.LOGGING_ROOT,logging_rotation_enabled:C.LOGGING_ROTATION_ENABLED,logging_rotation_compress:C.LOGGING_ROTATION_COMPRESS,logging_rotation_interval:C.LOGGING_ROTATION_INTERVAL,logging_rotation_maxsize:C.LOGGING_ROTATION_MAXSIZE,logging_rotation_path:C.LOGGING_ROTATION_PATH,logging_stdstreams:C.LOGGING_STDSTREAMS,logging_auditlog:C.LOGGING_AUDITLOG,logging_auditretention:C.LOGGING_AUDITRETENTION,logging_auditauthevents_logfailed:C.LOGGING_AUDITAUTHEVENTS_LOGFAILED,logging_auditauthevents_logsuccessful:C.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL,operationsapi_authentication_operationtokentimeout:C.AUTHENTICATION_OPERATIONTOKENTIMEOUT,operationsapi_authentication_refreshtokentimeout:C.AUTHENTICATION_REFRESHTOKENTIMEOUT,operationsapi_network_cors:C.OPERATIONSAPI_NETWORK_CORS,operationsapi_network_corsaccesslist:C.OPERATIONSAPI_NETWORK_CORSACCESSLIST,operationsapi_network_headerstimeout:C.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT,operationsapi_network_https:C.OPERATIONSAPI_NETWORK_HTTPS,operationsapi_network_keepalivetimeout:C.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT,operationsapi_network_port:C.OPERATIONSAPI_NETWORK_PORT,operationsapi_network_domainsocket:C.OPERATIONSAPI_NETWORK_DOMAINSOCKET,operationsapi_network_secureport:C.OPERATIONSAPI_NETWORK_SECUREPORT,operationsapi_tls_certificate:C.OPERATIONSAPI_TLS_CERTIFICATE,operationsapi_tls_privatekey:C.OPERATIONSAPI_TLS_PRIVATEKEY,operationsapi_tls_certificateauthority:C.OPERATIONSAPI_TLS_CERTIFICATEAUTHORITY,operationsapi_network_timeout:C.OPERATIONSAPI_NETWORK_TIMEOUT,operationsapi_root:C.ROOTPATH,databases:C.DATABASES,storage_path:C.STORAGE_PATH,ignorescripts:C.IGNORE_SCRIPTS,mqtt_network_port:C.MQTT_NETWORK_PORT,mqtt_websocket:C.MQTT_WEBSOCKET,mqtt_network_secureport:C.MQTT_NETWORK_SECUREPORT,mqtt_network_mtls:C.MQTT_NETWORK_MTLS,mqtt_network_mtls_certificateAuthority:C.MQTT_NETWORK_MTLS_CERTIFICATEAUTHORITY,mqtt_network_mtls_user:C.MQTT_NETWORK_MTLS_USER,mqtt_network_mtls_required:C.MQTT_NETWORK_MTLS_REQUIRED,mqtt_requireauthentication:C.MQTT_REQUIREAUTHENTICATION,analytics_aggregatePeriod:C.ANALYTICS_AGGREGATEPERIOD,authentication_authorizelocal:C.AUTHENTICATION_AUTHORIZELOCAL,authentication_cachettl:C.AUTHENTICATION_CACHETTL,authentication_enablesessions:C.AUTHENTICATION_ENABLESESSIONS,authentication_operationtokentimeout:C.AUTHENTICATION_OPERATIONTOKENTIMEOUT,authentication_refreshtokentimeout:C.AUTHENTICATION_REFRESHTOKENTIMEOUT,componentsroot:C.COMPONENTSROOT,tls_certificate:C.TLS_CERTIFICATE,tls_privatekey:C.TLS_PRIVATEKEY,tls_certificateauthority:C.TLS_CERTIFICATEAUTHORITY,tls_ciphers:C.TLS_CIPHERS};for(let e in C){let t=C[e];FA[t.toLowerCase()]=t}var qF={TABLES:"tables",PATH:"path",AUDIT_PATH:"auditPath"},FF={csv_file_load:"csv_file_load",csv_data_load:j.CSV_DATA_LOAD,csv_url_load:j.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"},GF={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"},kF={BIDIRECTIONAL:"BIDIRECTIONAL",OUTBOUND:"OUTBOUND",INBOUND:"INBOUND"},VF={VERSION_DEFAULT:"2.2.0"},$F={DEVELOPMENT:8192,DEFAULT:512},YF={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"},KF={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"},WF={ENOENT:"ENOENT",EACCES:"EACCES",EEXIST:"EEXIST"},GA={CREATED_TIME:"__createdtime__",UPDATED_TIME:"__updatedtime__"},QF=Symbol("metadata"),zF="__clustering__",JF=Object.values(GA),jF=15984864e5,kA={LESS:"<",LESS_OR_EQ:"<=",GREATER:">",GREATER_OR_EQ:">=",BETWEEN:"..."},XF=xA.invert(kA),ZF={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"},eG=111,tG=`\r
|
|
2
|
+
`,rG={READ:"read",INSERT:"insert",UPDATE:"update",DELETE:"delete"},nG=["*","%"],sG="unauthorized_access",iG="func_val",oG={HASH_VALUE:"hash_value",TIMESTAMP:"timestamp",USERNAME:"username"},aG={JWT_PRIVATE_KEY_NAME:".jwtPrivate.key",JWT_PUBLIC_KEY_NAME:".jwtPublic.key",JWT_PASSPHRASE_NAME:".jwtPass"},cG={SHUTDOWN:"shutdown",CHILD_STARTED:"child_started",CHILD_STOPPED:"child_stopped",SCHEMA:"schema",USER:"user",CLUSTER_STATUS_RESPONSE:"cluster_status_response",CLUSTER_STATUS_REQUEST:"cluster_status_request",METRICS:"metrics",GET_METRICS:"get_metrics",RESTART:"restart"},uG={HDB_CORE:"hdb_core",CUSTOM_FUNCTIONS:"custom_functions"},lG={HTTP:"http"},_G={STOPPED:"stopped",ONLINE:"online"},dG="3.x.x",fG={SUCCESS:"success",FAILURE:"failure"},EG={AUTHENTICATION:"authentication",AUTHORIZATION:"authorization"};VA.exports={LOCAL_HARPERDB_OPERATIONS:Be,HDB_SUPPORT_ADDRESS:UA,HDB_SUPPORT_URL:vA,HDB_PRICING_URL:Hq,SUPPORT_HELP_MSG:xq,LICENSE_HELP_MSG:BA,HDB_PROC_NAME:LA,HDB_PROC_DESCRIPTOR:th,CLUSTERING_LEAF_PROC_DESCRIPTOR:Ul,CLUSTERING_HUB_PROC_DESCRIPTOR:Ml,SYSTEM_SCHEMA_NAME:nF,HASH_FOLDER_NAME:sF,HDB_HOME_DIR_NAME:iF,UPDATE_FILE_NAME:uF,LICENSE_KEY_DIR_NAME:aF,BOOT_PROPS_FILE_NAME:cF,JOB_TYPE_ENUM:FF,JOB_STATUS_ENUM:LF,SYSTEM_TABLE_NAMES:yF,SYSTEM_TABLE_HASH_ATTRIBUTES:NF,OPERATIONS_ENUM:j,VALID_S3_FILE_TYPES:MF,S3_BUCKET_AUTH_KEYS:UF,VALID_SQL_OPS_ENUM:PF,GEO_CONVERSION_ENUM:BF,HDB_SETTINGS_NAMES:qA,HDB_SETTINGS_NAMES_REVERSE_LOOKUP:HF,SERVICE_ACTIONS_ENUM:vF,CLUSTER_MESSAGE_TYPE_ENUM:GF,CLUSTER_CONNECTION_DIRECTION_ENUM:kF,CLUSTER_EVENTS_DEFS_ENUM:YF,PERIOD_REGEX:Yq,DOUBLE_PERIOD_REGEX:Kq,UNICODE_PERIOD:Wq,FORWARD_SLASH_REGEX:Qq,UNICODE_FORWARD_SLASH:zq,ESCAPED_FORWARD_SLASH_REGEX:Jq,ESCAPED_PERIOD_REGEX:jq,ESCAPED_DOUBLE_PERIOD_REGEX:Xq,REG_KEY_FILE_NAME:CF,RESTART_TIMEOUT_MS:dF,HDB_FILE_PERMISSIONS:fF,DATABASES_DIR_NAME:mF,LEGACY_DATABASES_DIR_NAME:pF,TRANSACTIONS_DIR_NAME:SF,LIMIT_COUNT_NAME:TF,ID_ATTRIBUTE_STRING:gF,INSERT_MODULE_ENUM:OF,UPGRADE_JSON_FIELD_NAMES_ENUM:bF,RESTART_CODE:lF,RESTART_CODE_NUM:_F,CLUSTER_OPERATIONS:Xa,SYSTEM_DEFAULT_ATTRIBUTE_NAMES:IF,HDB_INTERNAL_SC_CHANNEL_PREFIX:Or,INTERNAL_SC_CHANNELS:wF,CLUSTERING_MESSAGE_TYPES:ZF,HDB_FILE_SUFFIX:oF,BLOB_FOLDER_NAME:EF,HDB_TRASH_DIR:hF,ORIGINATOR_SET_VALUE:eG,LICENSE_VALUES:VF,RAM_ALLOCATION_ENUM:$F,TIME_STAMP_NAMES_ENUM:GA,TIME_STAMP_NAMES:JF,PERMS_UPDATE_RELEASE_TIMESTAMP:jF,SEARCH_NOT_FOUND_MESSAGE:qq,SEARCH_ATTRIBUTE_NOT_FOUND:Fq,LICENSE_ROLE_DENIED_RESPONSE:Gq,LICENSE_MAX_CONNS_REACHED:kq,BASIC_LICENSE_MAX_NON_CU_ROLES:PA,BASIC_LICENSE_CLUSTER_CONNECTION_LIMIT_WS_ERROR_CODE:Bq,VALUE_SEARCH_COMPARATORS:kA,VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP:XF,LICENSE_FILE_NAME:DF,WEBSOCKET_CLOSE_CODE_DESCRIPTION_LOOKUP:KF,NEW_LINE:tG,BASIC_LICENSE_MAX_CLUSTER_USER_ROLES:$q,MOMENT_DAYS_TAG:Zq,API_TURNOVER_SEC:eF,LOOPBACK:Vq,CODE_EXTENSION:Ll,WILDCARD_SEARCH_VALUE:tF,NODE_ERROR_CODES:WF,JAVASCRIPT_EXTENSION:DA,PERMS_CRUD_ENUM:rG,UNAUTHORIZED_PERMISSION_NAME:sG,SEARCH_WILDCARDS:nG,FUNC_VAL:iG,READ_AUDIT_LOG_SEARCH_TYPES_ENUM:oG,JWT_ENUM:aG,CLUSTERING_FLAG:zF,ITC_EVENT_TYPES:cG,CUSTOM_FUNCTION_PROC_NAME:MA,CUSTOM_FUNCTION_PROC_DESCRIPTOR:Dl,SERVICES:uG,THREAD_TYPES:lG,MEM_SETTING_KEY:rF,HDB_RESTART_SCRIPT:Rq,PROCESS_DESCRIPTORS:wq,SERVICE_SERVERS:Mq,SERVICE_SERVERS_CWD:eh,PROCESS_DESCRIPTORS_VALIDATE:Dq,LAUNCH_SERVICE_SCRIPTS:Uq,LOG_LEVELS:Cq,PROCESS_NAME_ENV_PROP:RF,LOG_NAMES:Iq,PM2_PROCESS_STATUSES:_G,CONFIG_PARAM_MAP:FA,CONFIG_PARAMS:C,HDB_CONFIG_FILE:Sq,HDB_DEFAULT_CONFIG_FILE:Tq,ROLE_TYPES_ENUM:Pq,BOOT_PROP_PARAMS:HA,INSTALL_PROMPTS:AF,HDB_ROOT_DIR_NAME:gq,CLUSTERING_PROCESSES:Lq,FOREGROUND_PID_FILE:bq,PACKAGE_ROOT:Ks,PRE_4_0_0_VERSION:dG,DATABASES_PARAM_CONFIG:qF,METADATA_PROPERTY:QF,AUTH_AUDIT_STATUS:fG,AUTH_AUDIT_TYPES:EG,HDB_PID_FILE:yq,DEFAULT_DATABASE_NAME:Nq,LEGACY_CONFIG_PARAMS:xF};CA()});var rh=T((Wie,KA)=>{"use strict";var $A=require("minimist");KA.exports=hG;function hG(e=[],t=!1){if(!Array.isArray(e))return{};let r,n;t?(r=YA(process.env),n=YA($A(process.argv))):(r=process.env,n=$A(process.argv));let s={};for(let i=0,o=e.length;i<o;i++){let c=e[i];n[c]!==void 0?s[c]=n[c].toString().trim():r[c]!==void 0&&(s[c]=r[c].toString().trim())}return s}a(hG,"assignCMDENVVariables");function YA(e){let t,r=Object.keys(e),n=r.length,s={};for(;n--;)t=r[n],s[t.toLowerCase()]=e[t];return s}a(YA,"objKeysToLowerCase")});var K=T((zie,uh)=>{"use strict";var yi=require("fs-extra"),{workerData:mG,threadId:pG}=require("worker_threads"),_s=require("path"),zA=require("yaml"),JA=require("properties-reader"),gt=U(),WA=rh(),SG=require("os"),{PACKAGE_ROOT:sh}=U(),{_assignPackageExport:TG}=require("../../index"),ec={};for(let e in console)ec[e]||(ec[e]=console[e]);var Jt={notify:7,fatal:6,error:5,warn:4,info:3,debug:2,trace:1},jA={STDOUT:"stdOut",STDERR:"stdErr"},gG=_s.join(sh,"logs"),RG=_s.join(sh,"config/yaml/",gt.HDB_DEFAULT_CONFIG_FILE),AG=1e4,ls,Fn,zt,Pl,vl,tc,Uo,Za;Za===void 0&&XA();uh.exports={notify:tO,fatal:rO,error:rc,warn:ch,info:Bl,debug:ah,trace:oh,setLogLevel:CG,log_level:zt,loggerWithTag:OG,suppressLogging:bG,initLogSettings:XA,setupConsoleLogging:ZA,logCustomLevel:wG,closeLogFile:ih,getLogFilePath:()=>tc,OUTPUTS:jA,AuthAuditLog:MG};TG("logger",uh.exports);function XA(e=!1){try{if(Za===void 0||e){ih();let t=IG(),r=WA(["ROOTPATH"]);try{Za=JA(t)}catch(n){if(!r.ROOTPATH||r.ROOTPATH&&!yi.pathExistsSync(_s.join(r.ROOTPATH,gt.HDB_CONFIG_FILE)))throw n}({level:zt,config_log_path:vl,to_file:ls,to_stream:Fn}=DG(r.ROOTPATH?_s.join(r.ROOTPATH,gt.HDB_CONFIG_FILE):Za.get("settings_path"))),Pl=gt.LOG_NAMES.HDB,tc=_s.join(vl,Pl)}}catch(t){if(Za=void 0,t.code===gt.NODE_ERROR_CODES.ENOENT){let r=WA(Object.keys(gt.CONFIG_PARAM_MAP),!0);for(let o in r){let c=gt.CONFIG_PARAM_MAP[o];c&&c.toLowerCase();let u=r[o];if(c===gt.CONFIG_PARAMS.LOGGING_LEVEL){zt=u;continue}if(c===gt.CONFIG_PARAMS.LOGGING_STDSTREAMS){Fn=u;continue}c===gt.CONFIG_PARAMS.LOGGING_FILE&&(ls=c)}let{default_level:n,default_to_file:s,default_to_stream:i}=LG();ls=ls===void 0?s:ls,ls=QA(ls),Fn=Fn===void 0?i:Fn,Fn=QA(Fn),zt=zt===void 0?n:zt,vl=gG,Pl=gt.LOG_NAMES.INSTALL,tc=_s.join(vl,Pl);return}throw rc("Error initializing log settings"),rc(t),t}process.env.DEV_MODE&&(Fn=!0),ZA()}a(XA,"initLogSettings");var nh=!0;function ZA(){Mo("error",rc),Mo("warn",ch),Mo("log",Bl),Mo("info",Bl),Mo("debug",ah),Mo("trace",oh)}a(ZA,"setupConsoleLogging");function Mo(e,t){console[e]=function(...r){if(nh&&t(...r),!/PM2 log:|App \[/.test(r[0]))return ec[e](...r)}}a(Mo,"logConsole");function OG(e){let t={tagName:e.replace(/ /g,"-")};return{notify:r(tO),fatal:r(rO),error:r(rc),warn:r(ch),info:r(Bl),debug:r(ah),trace:r(oh)};function r(n){return function(...s){return n(t,...s)}}}a(OG,"loggerWithTag");function bG(e){try{nh=!1,e()}finally{nh=!0}}a(bG,"suppressLogging");var yG=mG?.name?.replace(/ /g,"-")||"main";function ds(e,t){let r=new Date(Date.now()).toISOString(),n="",s=t.length,i=s-1,o=[e],c=0,u;for(typeof t[0]=="object"&&(t[0]?.tagName?(o.push(t[0]?.tagName),c++):t[0]?.serviceName&&(u=t[0]?.serviceName,c++)),o.unshift(u||yG+"/"+pG);c<s;c++){let _=t[c];_ instanceof Error&&_.stack?n+=_.stack:typeof _=="object"?n+=JSON.stringify(_):n+=_,c<i&&(n+=" ")}return`${r} [${o.join("] [")}]: ${n}
|
|
3
|
+
`}a(ds,"createLogRecord");function nc(e){ls&&eO(e),Fn&&process.stdout.write(e)}a(nc,"logStdOut");function Hl(e){ls&&eO(e),Fn&&process.stderr.write(e)}a(Hl,"logStdErr");function eO(e){NG(),Uo?yi.appendFileSync(Uo,e):ec.log(e)}a(eO,"logToFile");function ih(){try{yi.closeSync(Uo)}catch{}Uo=null}a(ih,"closeLogFile");function NG(){if(!Uo){try{if(!tc)debugger;Uo=yi.openSync(tc,"a")}catch(e){ec.error(e)}setTimeout(()=>{ih()},AG).unref()}}a(NG,"openLogFile");function Bl(...e){Jt[zt]<=Jt.info&&nc(ds("info",e))}a(Bl,"info");function oh(...e){Jt[zt]<=Jt.trace&&nc(ds("trace",e))}a(oh,"trace");function rc(...e){Jt[zt]<=Jt.error&&Hl(ds("error",e))}a(rc,"error");function ah(...e){Jt[zt]<=Jt.debug&&nc(ds("debug",e))}a(ah,"debug");function tO(...e){Jt[zt]<=Jt.notify&&nc(ds("notify",e))}a(tO,"notify");function rO(...e){Jt[zt]<=Jt.fatal&&Hl(ds("fatal",e))}a(rO,"fatal");function ch(...e){Jt[zt]<=Jt.warn&&Hl(ds("warn",e))}a(ch,"warn");function wG(e,t,...r){t===jA.STDERR?Hl(ds(e,r)):nc(ds(e,r))}a(wG,"logCustomLevel");function IG(){let e;try{e=SG.homedir()}catch{e=process.env.HOME}e||(e="~/");let t=_s.join(e,gt.HDB_HOME_DIR_NAME,gt.BOOT_PROPS_FILE_NAME);return yi.existsSync(t)||(t=_s.join(sh,"utility/hdb_boot_properties.file")),t}a(IG,"getPropsFilePath");function CG(e){zt=e}a(CG,"setLogLevel");function QA(e){return e===!0||typeof e=="string"&&e.toLowerCase()==="true"}a(QA,"autoCastBoolean");function DG(e){try{if(e.includes("config/settings.js")){let o=JA(e);return{level:o.get(gt.HDB_SETTINGS_NAMES.LOG_LEVEL_KEY),config_log_path:_s.dirname(o.get(gt.HDB_SETTINGS_NAMES.LOG_PATH_KEY)),to_file:o.get(gt.HDB_SETTINGS_NAMES.LOG_TO_FILE),to_stream:o.get(gt.HDB_SETTINGS_NAMES.LOG_TO_STDSTREAMS)}}let t=zA.parseDocument(yi.readFileSync(e,"utf8")),r=t.getIn(["logging","level"]),n=t.getIn(["logging","root"]),s=t.getIn(["logging","file"]),i=t.getIn(["logging","stdStreams"]);return{level:r,config_log_path:n,to_file:s,to_stream:i}}catch(t){if(t.code===gt.NODE_ERROR_CODES.ENOENT)throw t;console.error("Error accessing config file for logging"),console.error(t)}}a(DG,"getLogConfig");function LG(){try{let e=zA.parseDocument(yi.readFileSync(RG,"utf8")),t=e.getIn(["logging","level"]),r=e.getIn(["logging","file"]),n=e.getIn(["logging","stdStreams"]);return{default_level:t,default_to_file:r,default_to_stream:n}}catch(e){console.error("Error accessing default config file for logging"),console.error(e)}}a(LG,"getDefaultConfig");function MG(e,t,r,n,s,i){this.username=e,this.status=t,this.type=r,this.originating_ip=n,this.request_method=s,this.path=i}a(MG,"AuthAuditLog")});var sO=T((jie,nO)=>{"use strict";var UG=require("util"),PG=require("path"),vG=require("child_process"),BG=UG.promisify(vG.execFile),HG=1e3*1e3*10;nO.exports={findPs:xG};async function xG(e){let t={};try{await Promise.all(["comm","args","ppid","uid","%cpu","%mem"].map(async r=>{let{stdout:n}=await BG("ps",["wwxo",`pid,${r}`],{maxBuffer:HG});for(let s of n.trim().split(`
|
|
4
|
+
`).slice(1)){s=s.trim();let[i]=s.split(" ",1),o=s.slice(i.length+1).trim();t[i]===void 0&&(t[i]={}),t[i][r]=o}}))}catch(r){throw r}return Object.entries(t).filter(([,r])=>r.comm&&r.args&&r.ppid&&r.uid&&r["%cpu"]&&r["%mem"]&&r.args.includes(e)).map(([r,n])=>({pid:Number.parseInt(r,10),name:PG.basename(n.comm),cmd:n.args,ppid:Number.parseInt(n.ppid,10),uid:Number.parseInt(n.uid,10),cpu:Number.parseFloat(n["%cpu"]),memory:Number.parseFloat(n["%mem"])}))}a(xG,"findPs")});var lt=T((Zie,oO)=>{"use strict";var qG="__dbis__",FG="__txns__",GG="__environment_name__",kG="__dbi_defintion__",VG={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"},$G=["__createdtime__","__updatedtime__"],YG="\uFFFF",iO={TIMESTAMP:"timestamp",HASH_VALUE:"hash_value",USER_NAME:"user_name"},KG=Object.values(iO);oO.exports={AUDIT_STORE_NAME:FG,INTERNAL_DBIS_NAME:qG,DBI_DEFINITION_NAME:kG,SEARCH_TYPES:VG,TIMESTAMP_NAMES:$G,MAX_SEARCH_KEY_LENGTH:256,ENVIRONMENT_NAME_KEY:GG,TRANSACTIONS_DBI_NAMES_ENUM:iO,TRANSACTIONS_DBIS:KG,OVERFLOW_MARKER:YG}});var br=T((eoe,hO)=>{"use strict";var aO=U(),cO=lt(),uO={CONTINUE:100,OK:200,CREATED:201,BAD_REQUEST:400,UNAUTHORIZED:401,FORBIDDEN:403,NOT_FOUND:404,METHOD_NOT_ALLOWED:405,REQUEST_TIMEOUT:408,CONFLICT:409,TOO_MANY_REQUESTS:429,INTERNAL_SERVER_ERROR:500,NOT_IMPLEMENTED:501,BAD_GATEWAY:502,SERVICE_UNAVAILABLE:503,GATEWAY_TIMEOUT:504,HTTP_VERSION_NOT_SUPPORTED:505,INSUFFICIENT_STORAGE:507,NETWORK_AUTHENTICATION_REQUIRED:511},lO=a(e=>`${e} Check logs and try again.`,"CHECK_LOGS_WRAPPER"),_O={500:lO("There was an error processing your request."),400:"Invalid request"},WG=_O[uO.INTERNAL_SERVER_ERROR],QG={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.`},zG={CONFIG_VALIDATION:e=>`HarperDB config file validation error: ${e}`},JG={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"},jG={BASE_PATH_REQUIRED:"base_path is required",DESTINATION_PATH_REQUIRED:"destination_path is required",ENV_NAME_REQUIRED:"env_name is required",INVALID_BASE_PATH:"invalid base_path",INVALID_DESTINATION_PATH:"invalid destination_path",INVALID_ENVIRONMENT:"invalid environment",ENV_REQUIRED:"env is required",DBI_NAME_REQUIRED:"dbi_name is required",DBI_DOES_NOT_EXIST:"dbi does not exist",HASH_ATTRIBUTE_REQUIRED:"hash_attribute is required",ID_REQUIRED:"id is required",IDS_REQUIRED:"ids is required",IDS_MUST_BE_ITERABLE:"ids must be iterable",FETCH_ATTRIBUTES_REQUIRED:"fetch_attributes is required",FETCH_ATTRIBUTES_MUST_BE_ARRAY:"fetch_attributes must be an array",ATTRIBUTE_REQUIRED:"attribute is required",SEARCH_VALUE_REQUIRED:"search_value is required",SEARCH_VALUE_TOO_LARGE:"search_value is too long",WRITE_ATTRIBUTES_REQUIRED:"write_attributes is required",WRITE_ATTRIBUTES_MUST_BE_ARRAY:"write_attributes must be an array",RECORDS_REQUIRED:"records is required",RECORDS_MUST_BE_ARRAY:"records must be an array",CANNOT_CREATE_INTERNAL_DBIS_NAME:`cannot create a dbi named ${cO.INTERNAL_DBIS_NAME}`,CANNOT_DROP_INTERNAL_DBIS_NAME:`cannot drop a dbi named ${cO.INTERNAL_DBIS_NAME}`,START_VALUE_REQUIRED:"start_value is required",END_VALUE_REQUIRED:"end_value is required",CANNOT_COMPARE_STRING_TO_NUMERIC_KEYS:"cannot compare a string to numeric keys",END_VALUE_MUST_BE_GREATER_THAN_START_VALUE:"end_value must be greater than or equal to start_value",UNKNOWN_SEARCH_TYPE:"unknown search type",CANNOT_DROP_TABLE_HASH_ATTRIBUTE:"cannot drop a table's hash attribute"},XG={ATTR_NAME_LENGTH_ERR:e=>`transaction aborted due to attribute name ${e} being too long. Attribute names cannot be longer than ${aO.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 ${aO.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"},dO={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"},ZG={DEFAULT_INVALID_REQUEST:"Invalid request",OP_AUTH_PERMS_ERROR:"This operation is not authorized due to role restrictions and/or invalid database items",OP_IS_SU_ONLY:e=>`Operation '${e}' is restricted to 'super_user' roles`,OP_NOT_FOUND:e=>`Operation '${e}' not found`,SYSTEM_TIMESTAMP_PERMS_ERR:"Internal timestamp attributes - '__createdtime_' and '__updatedtime__' - cannot be inserted to or updated by HDB users.",UNKNOWN_OP_AUTH_ERROR:(e,t,r)=>`There was an error authorizing ${e} op on table '${t}.${r}'`,USER_HAS_NO_PERMS:e=>`User ${e} has no role or permissions. Please assign the user a valid role.`,DROP_SYSTEM:"The 'system' database, tables and records are used internally by HarperDB and cannot be updated or removed."},ek={ATTR_PERM_MISSING:(e,t)=>`${e.toUpperCase()} attribute permission missing for '${t}'`,ATTR_PERM_MISSING_NAME:"Permission object in 'attribute_permission' missing an 'attribute_name'",ATTR_PERM_NOT_BOOLEAN:(e,t)=>`${e.toUpperCase()} attribute permission for '${t}' must be a boolean`,ATTR_PERMS_ARRAY_MISSING:"Missing 'attribute_permissions' array",ATTR_PERMS_NOT_ARRAY:"Value for 'attribute_permissions' must be an array",INVALID_ATTRIBUTE_IN_PERMS:e=>`Invalid attribute '${e}' in 'attribute_permissions'`,INVALID_PERM_KEY:e=>`Invalid table permission key value '${e}'`,INVALID_ATTR_PERM_KEY:e=>`Invalid attribute permission key value '${e}'`,INVALID_ROLE_JSON_KEYS:e=>`Invalid ${e.length>1?"keys":"key"} in JSON body - '${e.join("', '")}'`,MISMATCHED_TABLE_ATTR_PERMS:e=>`You have a conflict with TABLE permissions for '${e}' being false and ATTRIBUTE permissions being true`,OUTDATED_PERMS_TRANSLATION_ERROR:"This instance was recently upgraded and uses our new role permissions structure. Please login to this instance in HarperDB Studio, go to 'Roles', and click 'Update Role Permission' for all standard roles to migrate them to the new structure.",ROLE_ALREADY_EXISTS:e=>`A role with name '${e}' already exists`,ROLE_NOT_FOUND:"Role not found",ROLE_PERMS_ERROR:"Errors in the role permissions JSON provided",SCHEMA_PERM_ERROR:e=>`Your role does not have permission to view database metadata for '${e}'`,SCHEMA_TABLE_PERM_ERROR:(e,t)=>`Your role does not have permission to view database.table metadata for '${e}.${t}'`,SU_ROLE_MISSING_ERROR:"Missing 'super_user' key/value in permission set",SU_CU_ROLE_BOOLEAN_ERROR:e=>`Value for '${e}' permission must be a boolean`,STRUCTURE_USER_ROLE_TYPE_ERROR:e=>`Value for '${e}' permission must be a boolean or Array`,SU_CU_ROLE_NO_PERMS_ALLOWED:e=>`Roles with '${e}' set to true cannot have other permissions set.`,SU_CU_ROLE_COMBINED_ERROR:"Roles cannot have both 'super_user' and 'cluster_user' values included in their permissions set.",TABLE_PERM_MISSING:e=>`Missing table ${e.toUpperCase()} permission`,TABLE_PERM_NOT_BOOLEAN:e=>`Table ${e.toUpperCase()} permission must be a boolean`},tk={ATTR_NOT_FOUND:(e,t,r)=>`Attribute '${r}' does not exist on '${e}.${t}'`,ATTR_EXISTS_ERR:(e,t,r)=>`Attribute '${r}' already exists in ${e}.${t}'`,DESCRIBE_ALL_ERR:"There was an error during describeAll. Please check the logs and try again.",INVALID_TABLE_ERR:e=>`Invalid table ${JSON.stringify(e)}`,SCHEMA_NOT_FOUND:e=>`database '${e}' does not exist`,SCHEMA_EXISTS_ERR:e=>`database '${e}' already exists`,TABLE_EXISTS_ERR:(e,t)=>`Table '${t}' already exists in '${e}'`,SCHEMA_REQUIRED_ERR:"database is required",TABLE_NOT_FOUND:(e,t)=>`Table '${e}.${t}' does not exist`,TABLE_REQUIRED_ERR:"table is required"},rk={OUTER_JOIN_TRANSLATION_ERROR:"There was an error translating the final SQL outer join data."},nk={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`},fO={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.`},EO={INVALID_ITC_DATA_TYPE:"Invalid ITC event data type, must be an object",MISSING_TYPE:"ITC event missing 'type'",MISSING_MSG:"ITC event missing 'message'",MISSING_ORIGIN:"ITC event message missing 'originator' property",INVALID_EVENT:e=>`ITC server received invalid event type: ${e}`},sk={FUNCTION_STATUS:"Error getting custom function status, check the log for more details",GET_FUNCTIONS:"Error getting custom functions, check the log for more details",GET_FUNCTION:"Error getting custom function, check the log for more details",SET_FUNCTION:"Error setting custom function, check the log for more details",NO_PROJECT:"Project does not exist. Create one using 'add_custom_function_project'",PROJECT_EXISTS:"Project already exists",VALIDATION_ERR:"Error validating request, check the log for more details",NO_FILE:"File does not exist",BAD_FILE_NAME:"File name can only contain alphanumeric, dash and underscore characters",BAD_PROJECT_NAME:"Project name can only contain alphanumeric, dash and underscores characters",BAD_PACKAGE:"Packaged project must be base64-encoded tar file of project directory",DROP_FUNCTION:"Error dropping custom function, check the log for more details",ADD_FUNCTION:"Error adding custom function project, check the log for more details",DROP_FUNCTION_PROJECT:"Error dropping custom function project, check the log for more details",BAD_FILE_PATH:"Filepath must be valid, and contain the name of the tarball you wish to write",NOT_ENABLED:"Custom functions is not enabled, to enable set fastifyRoutes enabled to true in hdb/harperdb-config.yaml file."},ik={CLUSTERING_NOT_ENABLED:"Clustering must be enabled to perform this operation."},ok={...dO,...JG,...QG,...ZG,...ek,...tk,...rk,...nk,...XG,...fO,...EO,...sk,...ik,...zG};hO.exports={CHECK_LOGS_WRAPPER:lO,HDB_ERROR_MSGS:ok,DEFAULT_ERROR_MSGS:_O,DEFAULT_ERROR_RESP:WG,HTTP_STATUS_CODES:uO,LMDB_ERRORS_ENUM:jG,AUTHENTICATION_ERROR_MSGS:dO,VALIDATION_ERROR_MSGS:fO,ITC_ERRORS:EO}});var ee=T((roe,SO)=>{"use strict";var Po=br(),ak=K(),ck=U(),xl=class extends Error{static{a(this,"HdbError")}constructor(t,r,n,s,i){super(),Error.captureStackTrace(this,mO),this.statusCode=n||Po.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR,this.http_resp_msg=r||(Po.DEFAULT_ERROR_MSGS[n]?Po.DEFAULT_ERROR_MSGS[n]:Po.DEFAULT_ERROR_MSGS[Po.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR]),this.message=t.message?t.message:this.http_resp_msg,this.type=t.name,s&&(this.logLevel=s),typeof this.message!="string"&&(this.stack=t.stack),i&&ak[s](i)}},lh=class extends Error{static{a(this,"ClientError")}constructor(t,r){if(t instanceof Error)return t.statusCode=r||400,t;super(t),this.statusCode=r||400}},_h=class extends Error{static{a(this,"ServerError")}constructor(t,r){super(t),this.statusCode=r||500}};function mO(e,t,r,n=ck.LOG_LEVELS.ERROR,s=null,i=!1){if(pO(e))return e;let o=new xl(e,t,r,n,s);return i&&delete o.stack,o}a(mO,"handleHDBError");function pO(e){return e.__proto__.constructor.name===xl.name}a(pO,"isHDBError");SO.exports={isHDBError:pO,handleHDBError:mO,ClientError:lh,ServerError:_h,hdb_errors:Po}});var gO=T((soe,TO)=>{"use strict";var uk={key:"-----BEGIN RSA PRIVATE KEY-----\rMIIEowIBAAKCAQEArBFJQRfFiJku/KwhV1Ssp7cX61vvuKmd4Rp6A9jB2QLgx8nj\r/+Xhp2hPRkISnOA8BuAxr4dMD9syGJwX4kNy9mbZ5Q0fWZCiEGBpVcU1J+k+N5K4\rSuZ2SqgxeN2IN2RLzt3GyQY4imcdHgNv7aHoXUrEwBx0MeYEw3IIDXtrYKCR2D8I\rvWBfwMUgWa24G8lpWILWA5hd9srRz9NxlAiHSjhbgT7B0xruEpHRCHSyKjvaIJVt\rWBR+amejYsAKVrD/hgrqjsA1123Y6++YqvU6vwg64xhS2kz5r3dkNKhvwbWgpZdI\rIaRvsiB77f4kLGo0vi8RFgJ1ZRjGg3RRK2w1LQIDAQABAoIBAQCEOmh78EOpnGZC\rYBjjHrvrysVD5gvLcfVUtl8Ls7gMB60re1eOIF+PoZZCHKZnDd6zPfiQtj1adg0C\rYnnsM/8VoaZS4gm0b3RLd3ubIQifWhuo40RissY2yxfxlPSH9LhZCY8ojnJG0cTL\resK579E8WCfopjUY33XLqEbN7Ylv39J+DSqInjqV3efJZUa+HqUJ98VxxzodcKMD\rP3bwUU4gHoSSp4pAsOFH5sQhaIWH1IcNjrAwpee2cJQuh4G157RRIuuUpagtaEG/\rXJIiAyBguJyu3JQFnIBQF01N5+omJgXYJ1L0m54543/iIRThmF3zDCDgCyUzmOk+\rH6As9fv1AoGBANOpOtOZLSAScjGsgJamT3ceJ2wCa86g2j8Oxu8lJUmUp5s3tA0v\rBFW5O3S4KR1EXwkLMBUMrfFM8YvzHWxsXBI6XV8azGLvyqPHxr65OhmpGYkGZMXu\rn9okgjkqlewnY2I073gvyK7ppX51UL5y9fF1vlsk+UlW+Rgx/vMHbdcjAoGBANAc\rxRUsxs4QJpbS4zD3JOkHjr24a97TrS3kCybAHUMpR2NrEHPZw9zex0/aphOJUHfL\rIMkOZdpfDqMfxWy4FAEmqBEMkO2SB+h0Wp4P+qp81ax4vGFiB0cD3wtixr11U1tt\rlZ/ZTdv4VDpDFNK1KaplhTDeyuCjeYfS3/GJia9vAoGAcOsAgjBevZR5rXx84WH6\rVO8WUu37u7FenXNxt9VWTinrPMh72uixZFY8nOk+rely1e1NCn3IMko9Ns9NbDFm\r8SaH95vhXArXTYbfxZIlp9jp0YtCqcHDL+p4Oq04bFMbFyJseu7rHj1x18QYfnHw\rOY/6LL/N6k1m+Hx7qgXVmIcCgYB/w0nTCBw84XlvWqSTqQaF8VfWbWP79mP5KmkW\rLxdH5g2noVEGbohqDnK6OXd/wusdwByukiJBf94Skyy25AOT+VFwthA7aU1ljhkb\rtJ+lDuJ28eBkwLPLCzthWBC+u0qjdJFJAzVjd/7tjcU43nNn4s90AzL12iaAFhvZ\rwyA+DQKBgGc/4cdyGJ3YkcA8150gQBawgJZ7q8V1JND87ggWA8wnK3cHn7rMZQl2\r3emDp9HEFXFex5dbGDDqZFAoesZCDxjknIn9oNfW4PvaWS8q7b6ZKLZG1p03Pu7/\rtYaD0kPbo0kysfFT/co+NgHbdykvIyboomfGdNLTUjYuy6lpwpvs\r-----END RSA PRIVATE KEY-----\r".replace(/\r/g,`\r
|
|
5
5
|
`),cert:"-----BEGIN CERTIFICATE-----\rMIIDXDCCAkSgAwIBAgIFNTE4MzQwDQYJKoZIhvcNAQELBQAwXTEXMBUGA1UEAxMO\rSGFycGVyREIsIEluYy4xCzAJBgNVBAYTAlVTMQswCQYDVQQIEwJDTzEPMA0GA1UE\rBxMGRGVudmVyMRcwFQYDVQQKEw5IYXJwZXJEQiwgSW5jLjAeFw0yMjAzMTEyMzAz\rNDlaFw0yNzAzMTAyMzAzNDlaMF0xFzAVBgNVBAMTDkhhcnBlckRCLCBJbmMuMQsw\rCQYDVQQGEwJVUzELMAkGA1UECBMCQ08xDzANBgNVBAcTBkRlbnZlcjEXMBUGA1UE\rChMOSGFycGVyREIsIEluYy4wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIB\rAQCsEUlBF8WImS78rCFXVKyntxfrW++4qZ3hGnoD2MHZAuDHyeP/5eGnaE9GQhKc\r4DwG4DGvh0wP2zIYnBfiQ3L2ZtnlDR9ZkKIQYGlVxTUn6T43krhK5nZKqDF43Yg3\rZEvO3cbJBjiKZx0eA2/toehdSsTAHHQx5gTDcggNe2tgoJHYPwi9YF/AxSBZrbgb\ryWlYgtYDmF32ytHP03GUCIdKOFuBPsHTGu4SkdEIdLIqO9oglW1YFH5qZ6NiwApW\rsP+GCuqOwDXXbdjr75iq9Tq/CDrjGFLaTPmvd2Q0qG/BtaCll0ghpG+yIHvt/iQs\rajS+LxEWAnVlGMaDdFErbDUtAgMBAAGjIzAhMA8GA1UdEwEB/wQFMAMBAf8wDgYD\rVR0PAQH/BAQDAgIEMA0GCSqGSIb3DQEBCwUAA4IBAQASR4YW/rPK7PNArHVe9zzM\rb0rKNX/2T9/0nybRhmE/+hdlSgliTAeebmwkUS2APckmekYt/q2ZY2NS65Fo/jjp\rG8TJrtcF4h+ylVqUp0ZXQLFtIsr7r2JZA7hJ6njW6G4DHSZ0gxtECLi4CBlTjzm5\rNmnmIDObvGRTuqmcdAZmXeObbta/He2XIzietukPAYX062pNM+G5XT5UM1eG/Vlp\rN86vjhpyI+ffKy+C60SJqxmKM3ydgN7oLscE7+2wLPN25XqN4W99OwGsp5dTdu/f\r5lPtFayXdJ55e/sNQKmGN+UGLrL05c2MWgjb8U/LFilnupUianceoeSERZmVjzKX\r-----END CERTIFICATE-----\r".replace(/\r/g,`\r
|
|
6
|
-
`)},ak="certificate.pem",ck="privateKey.pem",uk="ca.pem";mO.exports={CERTIFICATE_VALUES:ok,CERTIFICATE_PEM_NAME:ak,PRIVATEKEY_PEM_NAME:ck,CA_PEM_NAME:uk}});var je=g((ioe,SO)=>{"use strict";var Xt=require("validate.js");Xt.validators.type=function(e,t,r,n){return e===null||typeof e>"u"||Xt.validators.type.checks[t](e)?null:` must be a '${t}' value`};Xt.validators.type.checks={Object:function(e){return Xt.isObject(e)&&!Xt.isArray(e)},Array:Xt.isArray,Integer:Xt.isInteger,Number:Xt.isNumber,String:Xt.isString,Date:Xt.isDate,Boolean:function(e){return typeof e=="boolean"}};Xt.validators.hasValidFileExt=function(e,t){return Xt.isString(e)?e===""?"can't be blank":t.filter(r=>e.endsWith(r)).length>0?null:`must include one of the following valid file extensions - '${t.join("', '")}'`:null};SO.exports={validateObject:lk,validateObjectAsync:_k,validateBySchema:dk};function lk(e,t){if(!e||!t)return new Error("validateObject parameters were null");let r=Xt(e,t,{format:"flat"});return r?new Error(r):null}a(lk,"validateObject");async function _k(e,t){if(!e||!t)return new Error("validateObject parameters were null");try{await Xt.async(e,t,{format:"flat"})}catch(r){let n=r.join(",");return new Error(n)}return null}a(_k,"validateObjectAsync");function dk(e,t){let r=t.validate(e,{allowUnknown:!0,abortEarly:!1,errors:{wrap:{label:"'"}}});if(r.error)return new Error(r.error.message)}a(dk,"validateBySchema")});var Eh=g((coe,OO)=>{"use strict";var AO=require("fs-extra"),ce=require("joi"),fk=require("os"),{boolean:De,string:br,number:It,array:fh}=ce.types(),{totalmem:TO}=require("os"),bi=require("path"),Ek=Y(),xl=J(),aoe=pO(),gO=M(),hk=je(),RO="log",mk="components",pk="Invalid logging.rotation.maxSize unit. Available units are G, M or K",Sk="Invalid logging.rotation.interval unit. Available units are D, H or M (minutes)",Tk="Invalid logging.rotation.maxSize value. Value should be a number followed by unit e.g. '10M'",gk="Invalid logging.rotation.interval value. Value should be a number followed by unit e.g. '10D'",Rk="rootPath config parameter is undefined",Ak="clustering.enabled config parameter is undefined",Ni=It.min(0).required(),ql=fh.items({host:br.required(),port:Ni}).empty(null),qn;OO.exports={configValidator:Ok,routesValidator:Ck,route_constraints:ql};function Ok(e){if(qn=e.rootPath,xl.isEmpty(qn))throw Rk;let t=De.required(),r=It.min(0).max(1e3).empty(null).default(Ik),n=br.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path").empty(null).default(tc),s=br.optional().empty(null),i=br.pattern(/^[^\s.,*>]+$/).messages({"string.pattern.base":"{:#label} invalid, must not contain ., * or >"}).empty(null).required(),o=ce.string().empty(null).default(tc),c=ce.custom(Nk).empty(null).default(tc),u=e.clustering?.enabled;if(xl.isEmpty(u))throw Ak;let _;return u===!0?_=ce.object({enabled:t,hubServer:ce.object({cluster:ce.object({name:ce.required().empty(null),network:ce.object({port:Ni,routes:ql}).required()}).required(),leafNodes:ce.object({network:ce.object({port:Ni}).required()}).required(),network:ce.object({port:Ni}).required()}).required(),leafServer:ce.object({network:ce.object({port:Ni,routes:ql}).required(),streams:ce.object({maxAge:It.min(120).allow(null).optional(),maxBytes:It.min(1).allow(null).optional(),maxMsgs:It.min(1).allow(null).optional(),path:o}).required()}).required(),logLevel:ce.valid("error","warn","info","debug","trace"),nodeName:i,republishMessages:De.optional(),databaseLevel:De.optional(),tls:ce.object({certificate:s,certificateAuthority:s,privateKey:s,insecure:De.required(),verify:De.optional()}),user:br.optional().empty(null)}).required():_=ce.object({enabled:t,tls:ce.object({certificate:s,certificateAuthority:s,privateKey:s,insecure:De.required()})}).required(),ce.object({authentication:ce.object({authorizeLocal:De,cacheTTL:It.required(),enableSessions:De}),analytics:ce.object({aggregatePeriod:It}),componentsRoot:n.optional(),clustering:_,localStudio:ce.object({enabled:t}).required(),logging:ce.object({auditAuthEvents:ce.object({logFailed:De,logSuccessful:De}),file:De.required(),level:ce.valid("notify","fatal","error","warn","info","debug","trace"),rotation:ce.object({enabled:De.optional(),compress:De.optional(),interval:br.custom(wk).optional().empty(null),maxSize:br.custom(yk).optional().empty(null),path:br.optional().empty(null).default(tc)}).required(),root:n,stdStreams:De.required(),auditLog:De.required()}).required(),operationsApi:ce.object({network:ce.object({cors:De.optional(),corsAccessList:fh.optional(),headersTimeout:It.min(1).optional(),keepAliveTimeout:It.min(1).optional(),port:It.optional().empty(null),domainSocket:ce.optional().empty("hdb/operations-server").default(tc),securePort:It.optional().empty(null),timeout:It.min(1).optional()}).optional(),tls:ce.object({certificate:s,certificateAuthority:s,privateKey:s})}).required(),rootPath:br.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path").required(),mqtt:ce.object({network:ce.object({port:Ni,securePort:Ni,mtls:ce.alternatives([De.optional(),ce.object({user:br.optional(),certificateAuthority:s,required:De.optional()})])}).required(),webSocket:De.optional(),requireAuthentication:De.optional()}),http:ce.object({compressionThreshold:It.optional(),cors:De.optional(),corsAccessList:fh.optional(),headersTimeout:It.min(1).optional(),port:It.min(0).optional().empty(null),securePort:It.min(0).optional().empty(null),mtls:ce.alternatives([De.optional(),ce.object({user:br.optional(),certificateAuthority:s,required:De.optional()})])}).required(),threads:r.optional(),maxHeapMemory:It.min(0).optional(),storage:ce.object({writeAsync:De.required(),overlappingSync:De.optional(),caching:De.optional(),compression:De.optional(),noReadAhead:De.optional(),path:c,prefetchWrites:De.optional()}).required(),ignoreScripts:De.optional(),tls:ce.object({certificate:s.optional(),certificateAuthority:s.optional(),privateKey:s.optional(),ciphers:br.optional()})}).validate(e,{allowUnknown:!0,abortEarly:!1,errors:{wrap:{label:"'"}}})}a(Ok,"configValidator");function bk(e){return AO.existsSync(e)?null:`Specified path ${e} does not exist.`}a(bk,"doesPathExist");function Nk(e,t){ce.assert(e,br.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path"));let r=bk(e);if(r)return t.message(r)}a(Nk,"validatePath");function yk(e,t){let r=e.slice(-1);if(r!=="G"&&r!=="M"&&r!=="K")return t.message(pk);let n=e.slice(0,-1);return isNaN(parseInt(n))?t.message(Tk):e}a(yk,"validateRotationMaxSize");function wk(e,t){let r=e.slice(-1);if(r!=="D"&&r!=="H"&&r!=="M")return t.message(Sk);let n=e.slice(0,-1);return isNaN(parseInt(n))?t.message(gk):e}a(wk,"validateRotationInterval");function Ik(e,t){let r=t.state.path.join("."),n=fk.cpus().length,s=n-1;s<=2&&(s=2);let i=process.constrainedMemory?.()||TO();return i=Math.round(Math.min(i,TO())/1e6),s=Math.max(Math.min(s,Math.round((i-750)/300)),1),Ek.info(`Detected ${n} cores and ${i}MB on this machine, defaulting ${r} to ${s}`),s}a(Ik,"setDefaultThreads");function tc(e,t){let r=t.state.path.join(".");if(!xl.isEmpty(t.original)&&r!=="operationsApi.network.domainSocket")return t.original;if(xl.isEmpty(qn))throw new Error(`Error setting default root for: ${r}. HDB root is not defined`);switch(r){case"componentsRoot":return bi.join(qn,mk);case"logging.root":return bi.join(qn,RO);case"clustering.leafServer.streams.path":return bi.join(qn,"clustering","leaf");case"storage.path":let n=bi.join(qn,gO.LEGACY_DATABASES_DIR_NAME);return AO.existsSync(n)?n:bi.join(qn,gO.DATABASES_DIR_NAME);case"logging.rotation.path":return bi.join(qn,RO);case"operationsApi.network.domainSocket":return r==null?null:bi.join(qn,"operations-server");default:throw new Error(`Error setting default root for config parameter: ${r}. Unrecognized config parameter`)}}a(tc,"setDefaultRoot");function Ck(e){let t=ce.object({routes:ql});return hk.validateBySchema({routes:e},t)}a(Ck,"routesValidator")});var yi={};Ve(yi,{server:()=>Xe});var bO,Xe,Zt=Oe(()=>{bO=require("../../index"),Xe={};(0,bO._assignPackageExport)("server",Xe)});var wr=g((_oe,UO)=>{"use strict";var yr=M(),Ct=J(),gt=Y(),{configValidator:Dk,routesValidator:NO}=Eh(),er=require("fs-extra"),Lk=require("yaml"),pn=require("path"),Mk=require("is-number"),wO=require("properties-reader"),Uk=require("lodash"),{handleHDBError:Pk}=ee(),{HTTP_STATUS_CODES:vk,HDB_ERROR_MSGS:Fl}=Or(),loe=require("minimist"),{server:Bk}=(Zt(),te(yi)),{DATABASES_PARAM_CONFIG:rc,CONFIG_PARAMS:Nr,CONFIG_PARAM_MAP:Sn}=yr,Hk="Unable to get config value because config is uninitialized",xk="Config successfully initialized",qk="Error backing up config file",Fk="Empty parameter sent to getConfigValue",IO=pn.join(yr.PACKAGE_ROOT,"config","yaml",yr.HDB_DEFAULT_CONFIG_FILE),Gk="Configuration successfully set. You must restart HarperDB for new config settings to take effect.",yO={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"},Gl,Rt,kl;UO.exports={createConfigFile:kk,getDefaultConfig:Vk,getConfigValue:DO,initConfig:mh,flattenConfig:Uo,updateConfigValue:LO,updateConfigObject:Yk,getConfiguration:Qk,setConfiguration:zk,readConfigFile:Sh,getClusteringRoutes:Jk,initOldConfig:MO,getConfigFromFile:jk,getConfigFilePath:wi,addConfig:Xk,deleteConfigFromFile:Zk,getConfigObj:eV};function kk(e){let t=Ys(IO);Gl=Uo(t.toJSON());let r;for(let o in e){let c=Sn[o.toLowerCase()];if(c===Nr.DATABASES){r=e[o];continue}if(!c&&o.endsWith("_package")&&(c=o),c!==void 0){let u=c.split("_"),_=hh(c,e[o]);c==="rootPath"&&_?.endsWith("/")&&(_=_.slice(0,-1));try{t.setIn([...u],_)}catch(l){gt.error(l)}}}r&&CO(t,r),ph(t);let n=t.toJSON();Rt=Uo(n);let s=t.getIn(["rootPath"]),i=pn.join(s,yr.HDB_CONFIG_FILE);er.createFileSync(i),er.writeFileSync(i,String(t)),gt.trace(`Config file written to ${i}`)}a(kk,"createConfigFile");function CO(e,t){let r;try{try{r=JSON.parse(t)}catch(n){if(!Ct.isObject(t))throw n;r=t}for(let n of r){let s=Object.keys(n)[0];if(n[s].hasOwnProperty(rc.TABLES))for(let i in n[s][rc.TABLES])for(let o in n[s][rc.TABLES][i]){let c=n[s][rc.TABLES][i][o],u=[Nr.DATABASES,s,rc.TABLES,i,o];e.hasIn(u)?e.setIn(u,c):e.addIn(u,c)}else for(let i in n[s]){let o=n[s][i],c=[Nr.DATABASES,s,i];e.hasIn(c)?e.setIn(c,o):e.addIn(c,o)}}}catch(n){gt.error("Error parsing schemas CLI/env config arguments",n)}}a(CO,"setSchemasConfig");function Vk(e){if(Gl===void 0){let r=Ys(IO);Gl=Uo(r.toJSON())}let t=Sn[e.toLowerCase()];if(t!==void 0)return Gl[t.toLowerCase()]}a(Vk,"getDefaultConfig");function DO(e){if(e==null){gt.error(Fk);return}if(Rt===void 0){gt.trace(Hk);return}let t=Sn[e.toLowerCase()];if(t!==void 0)return Rt[t.toLowerCase()]}a(DO,"getConfigValue");function wi(e=Ct.getPropsFilePath()){let t=Ct.getEnvCliRootPath();return t?pn.join(t,yr.HDB_CONFIG_FILE):wO(e).get(yr.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY)}a(wi,"getConfigFilePath");function mh(e=!1){if(Rt===void 0||e){let t;if(!Ct.noBootFile()){t=Ct.getPropsFilePath();try{er.accessSync(t,er.constants.F_OK|er.constants.R_OK)}catch(i){throw gt.error(i),new Error(`HarperDB properties file at path ${t} does not exist`)}}let r=wi(t),n;if(r.includes("config/settings.js"))try{MO(r);return}catch(i){if(i.code!==yr.NODE_ERROR_CODES.ENOENT)throw i}try{n=Ys(r)}catch(i){if(i.code===yr.NODE_ERROR_CODES.ENOENT){gt.trace(`HarperDB config file not found at ${r}.
|
|
7
|
-
This can occur during early stages of install where the config file has not yet been created`);return}else throw gt.error(i),new Error(`Error reading HarperDB config file at ${r}`)}$k(n,r),ph(n);let s=n.toJSON();if(Bk.config=s,Rt=Uo(s),Rt.logging_rotation_rotate)for(let i in yO)Rt[i]&>.error(`Config ${yO[i]} has been deprecated. Please check https://docs.harperdb.io/docs/ for further details.`);gt.trace(xk)}}a(mh,"initConfig");function $k(e,t){let r=e.getIn(["rootPath"]),n=!1;e.hasIn(["storage","path"])||(e.setIn(["storage","path"],pn.join(r,"database")),n=!0),e.hasIn(["clustering","leafServer","streams","path"])||(e.setIn(["clustering","leafServer","streams","path"],pn.join(r,"clustering","leaf")),n=!0),e.hasIn(["logging","rotation","path"])||(e.setIn(["logging","rotation","path"],pn.join(r,"log")),n=!0),e.hasIn(["clustering","tls","verify"])||(e.setIn(["clustering","tls","verify"],!0),n=!0),n&&(gt.trace("Updating config file with missing config params"),er.writeFileSync(t,String(e)))}a($k,"checkForUpdatedConfig");function ph(e){let t=e.toJSON();t.componentsRoot=t.componentsRoot??t?.customFunctions?.root,t.threads=t.threads??t?.http?.threads;let r=Dk(t);if(r.error)throw Fl.CONFIG_VALIDATION(r.error.message);e.setIn(["threads"],r.value.threads),e.setIn(["componentsRoot"],r.value.componentsRoot),e.setIn(["logging","root"],r.value.logging.root),e.setIn(["storage","path"],r.value.storage.path),e.setIn(["logging","rotation","path"],r.value.logging.rotation.path),e.setIn(["clustering","leafServer","streams","path"],r.value.clustering.leafServer.streams?.path),e.setIn(["operationsApi","network","domainSocket"],r.value?.operationsApi?.network?.domainSocket)}a(ph,"validateConfig");function Yk(e,t){Rt===void 0&&(Rt={});let r=Sn[e.toLowerCase()];if(r===void 0){gt.trace(`Unable to update config object because config param '${e}' does not exist`);return}Rt[r.toLowerCase()]=t}a(Yk,"updateConfigObject");function LO(e,t,r=void 0,n=!1,s=!1,i=!1){Rt===void 0&&mh();let o=DO(Sn.hdb_root),c=pn.join(o,yr.HDB_CONFIG_FILE),u=Ys(c),_;if(r===void 0&&e.toLowerCase()===Nr.DATABASES)_=t;else if(r===void 0){let f;if(i)f=e;else if(f=Sn[e.toLowerCase()],f===void 0)throw new Error(`Unable to update config, unrecognized config parameter: ${e}`);let E=f.split("_"),h=hh(f,t);u.setIn([...E],h)}else for(let f in r){let E=Sn[f.toLowerCase()];if(E===Nr.HTTP_SECUREPORT&&r[f]===Rt[Nr.HTTP_PORT]?.toString()&&u.setIn(["http","port"],null),E===Nr.OPERATIONSAPI_NETWORK_SECUREPORT&&r[f]===Rt[Nr.OPERATIONSAPI_NETWORK_PORT.toLowerCase()]?.toString()&&u.setIn(["operationsApi","network","port"],null),E===Nr.DATABASES){_=r[f];continue}if(!E&&f.endsWith("_package")&&(E=f),E!==void 0){let h=E.split("_"),p=yr.LEGACY_CONFIG_PARAMS[f.toUpperCase()];p&&p.startsWith("customFunctions")&&u.hasIn(p.split("_"))&&(E=p,h=p.split("_"));let S=hh(E,r[f]);E==="rootPath"&&S?.endsWith("/")&&(S=S.slice(0,-1));try{h.length>1&&typeof u.getIn(h.slice(0,-1))=="boolean"&&u.deleteIn(h.slice(0,-1)),u.setIn([...h],S)}catch(T){gt.error(T)}}}_&&CO(u,_),ph(u);let l=u.getIn(["rootPath"]),d=pn.join(l,yr.HDB_CONFIG_FILE);n===!0&&Kk(c,l),er.writeFileSync(d,String(u)),s&&(Rt=Uo(u.toJSON())),gt.trace(`Config parameter: ${e} updated with value: ${t}`)}a(LO,"updateConfigValue");function Kk(e,t){try{let r=pn.join(t,"backup",`${yr.HDB_CONFIG_FILE}.bak`);er.copySync(e,r),gt.trace(`Config file: ${e} backed up to: ${r}`)}catch(r){gt.error(qk),gt.error(r)}}a(Kk,"backupConfigFile");var Wk=["databases"];function Uo(e){return e.http&&Object.assign(e.http,e?.customFunctions?.network),e?.operationsApi?.network&&(e.operationsApi.network=Object.assign({},e.http,e.operationsApi.network)),e?.operationsApi&&(e.operationsApi.tls=Object.assign({},e.tls,e.operationsApi.tls)),kl=e,r(e);function r(n){let s={};for(let i in n)if(n.hasOwnProperty(i)){if(typeof n[i]=="object"&&n[i]!==null&&!Array.isArray(n[i])&&!Wk.includes(i)){let o=r(n[i]);for(let c in o){if(!o.hasOwnProperty(c))continue;c!=="package"&&(i=i.toLowerCase());let u=i+"_"+c;!Nr[u.toUpperCase()]&&Sn[u]&&(s[Sn[u].toLowerCase()]=o[c]),s[u]=o[c]}}n[i]!==void 0&&(s[i.toLowerCase()]=n[i])}return s}a(r,"squashObj")}a(Uo,"flattenConfig");function hh(e,t){if(e===Nr.CLUSTERING_NODENAME||e===Nr.CLUSTERING_USER){if(t==null)return t;if(!isNaN(t))return t.toString();if(typeof t=="string"&&t.toLowerCase()==="true"||typeof t=="string"&&t.toLowerCase()==="false")return t}else{if(Mk(t))return parseFloat(t);if(t===!0||t===!1||Array.isArray(t)||Ct.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 Ct.autoCast(t)}a(hh,"castConfigValue");function Qk(){let e=Ct.getPropsFilePath(),t=wi(e);return Ys(t).toJSON()}a(Qk,"getConfiguration");async function zk(e){let{operation:t,hdb_user:r,hdb_auth_header:n,...s}=e;try{return LO(void 0,void 0,s,!0),Gk}catch(i){throw typeof i=="string"||i instanceof String?Pk(i,i,vk.BAD_REQUEST,void 0,void 0,!0):i}}a(zk,"setConfiguration");function Sh(){let e=Ct.getPropsFilePath();try{er.accessSync(e,er.constants.F_OK|er.constants.R_OK)}catch(n){if(!Ct.noBootFile())throw gt.error(n),new Error(`HarperDB properties file at path ${e} does not exist`)}let t=wi(e);return Ys(t).toJSON()}a(Sh,"readConfigFile");function Ys(e){return Lk.parseDocument(er.readFileSync(e,"utf8"),{simpleKeys:!0})}a(Ys,"parseYamlDoc");function Jk(){let e=Sh(),t=e?.clustering?.hubServer?.cluster?.network?.routes;t=Ct.isEmptyOrZeroLength(t)?[]:t;let r=NO(t);if(r)throw Fl.CONFIG_VALIDATION(r.message);let n=e?.clustering?.leafServer?.network?.routes;n=Ct.isEmptyOrZeroLength(n)?[]:n;let s=NO(n);if(s)throw Fl.CONFIG_VALIDATION(s.message);if(!Ct.isEmptyOrZeroLength(n)&&!Ct.isEmptyOrZeroLength(t)){let i=t.filter(o=>n.some(c=>c.host===o.host&&c.port===o.port));if(!Ct.isEmptyOrZeroLength(i)){let o=`Duplicate hub and leaf routes found ${JSON.stringify(i)}`;throw Fl.CONFIG_VALIDATION(o)}}return{hub_routes:t,leaf_routes:n}}a(Jk,"getClusteringRoutes");function MO(e){let t=wO(e);Rt={};for(let r in Sn){let n=t.get(r.toUpperCase());if(Ct.isEmpty(n)||typeof n=="string"&&n.trim().length===0)continue;let s=Sn[r].toLowerCase();s===Nr.LOGGING_ROOT?Rt[s]=pn.dirname(n):Rt[s]=n}return Rt}a(MO,"initOldConfig");function jk(e){let t=Sh();return Uk.get(t,e.replaceAll("_","."))}a(jk,"getConfigFromFile");async function Xk(e,t){let r=Ys(wi());r.hasIn([e])?r.setIn([e],t):r.addIn([e],t),await er.writeFile(wi(),String(r))}a(Xk,"addConfig");function Zk(e){let t=wi(Ct.getPropsFilePath()),r=Ys(t);r.deleteIn(e);let n=r.getIn(["rootPath"]),s=pn.join(n,yr.HDB_CONFIG_FILE);er.writeFileSync(s,String(r))}a(Zk,"deleteConfigFromFile");function eV(){return kl||(mh(),kl)}a(eV,"getConfigObj")});var Z=g((foe,HO)=>{"use strict";var Th=require("fs-extra"),Ii=require("path"),PO=require("os"),tV=require("properties-reader"),sc=Y(),nc=J(),ue=M(),Vl=wr(),rV="Error initializing environment manager",$l="BOOT_PROPS_FILE_PATH",vO=!1,nV={[ue.HDB_SETTINGS_NAMES.INSTALL_USER]:!0,[ue.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY]:!0,[ue.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]:!0,BOOT_PROPS_FILE_PATH:!0},_s={};HO.exports={BOOT_PROPS_FILE_PATH:$l,getHdbBasePath:sV,setHdbBasePath:iV,get:BO,initSync:aV,setProperty:Le,initTestEnvironment:cV};function sV(){return _s[ue.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]}a(sV,"getHdbBasePath");function iV(e){_s[ue.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=e}a(iV,"setHdbBasePath");function BO(e){let t=Vl.getConfigValue(e);return t===void 0?_s[e]:t}a(BO,"get");function Le(e,t){nV[e]&&(_s[e]=t),Vl.updateConfigObject(e,t)}a(Le,"setProperty");function oV(){let e;try{e=nc.getPropsFilePath(),Th.accessSync(e,Th.constants.F_OK|Th.constants.R_OK),vO=!0;let t=tV(e);return _s[ue.HDB_SETTINGS_NAMES.INSTALL_USER]=t.get(ue.HDB_SETTINGS_NAMES.INSTALL_USER),_s[ue.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY]=t.get(ue.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY),_s[$l]=e,!0}catch{return sc.trace(`Environment manager found no properties file at ${e}`),!1}}a(oV,"doesPropFileExist");function aV(e=!1){try{(vO||oV()||nc.noBootFile())&&(Vl.initConfig(e),_s[ue.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=Vl.getConfigValue(ue.HDB_SETTINGS_NAMES.HDB_ROOT_KEY))}catch(t){sc.error(rV),sc.error(t),console.error(t),process.exit(1)}}a(aV,"initSync");function cV(e={}){try{let{keep_alive_timeout:t,headers_timeout:r,server_timeout:n,https_enabled:s,cors_enabled:i,cors_accesslist:o,local_studio_on:c}=e,u=Ii.join(__dirname,"../../","unitTests");_s[$l]=Ii.join(u,"hdb_boot_properties.file"),Le(ue.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY,Ii.join(u,"settings.test")),Le(ue.HDB_SETTINGS_NAMES.INSTALL_USER,PO.userInfo()?PO.userInfo().username:void 0),Le(ue.HDB_SETTINGS_NAMES.LOG_LEVEL_KEY,"debug"),Le(ue.HDB_SETTINGS_NAMES.LOG_PATH_KEY,Ii.join(u,"envDir","log")),Le(ue.HDB_SETTINGS_NAMES.LOG_DAILY_ROTATE_KEY,!1),Le(ue.HDB_SETTINGS_NAMES.CLUSTERING_ENABLED_KEY,!0),Le(ue.HDB_SETTINGS_NAMES.CLUSTERING_NODE_NAME_KEY,"1231412de213"),Le(ue.HDB_SETTINGS_NAMES.HDB_ROOT_KEY,Ii.join(u,"envDir")),Le(ue.CONFIG_PARAMS.STORAGE_PATH,Ii.join(u,"envDir")),s&&(Le(ue.CONFIG_PARAMS.HTTP_SECUREPORT,BO(ue.CONFIG_PARAMS.HTTP_PORT)),Le(ue.CONFIG_PARAMS.HTTP_PORT,null)),Le(ue.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HTTPS,!!s),Le(ue.HDB_SETTINGS_NAMES.SERVER_PORT_KEY,9925),Le(ue.HDB_SETTINGS_NAMES.CORS_ENABLED_KEY,nc.isEmpty(i)?!1:i),Le(ue.CONFIG_PARAMS.HTTP_CORS,nc.isEmpty(i)?!1:i),Le(ue.HDB_SETTINGS_NAMES.MAX_CUSTOM_FUNCTION_PROCESSES,2),Le(ue.HDB_SETTINGS_NAMES.MAX_HDB_PROCESSES,4),Le(ue.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_PORT_KEY,9926),Le(ue.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_ENABLED_KEY,!0),Le(ue.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY,Ii.resolve(__dirname,"../../unitTests/server/fastifyRoutes/custom_functions")),Le(ue.HDB_SETTINGS_NAMES.LOCAL_STUDIO_ON,nc.isEmpty(c)?!1:c),o&&(Le("CORS_ACCESSLIST",o),Le(ue.CONFIG_PARAMS.HTTP_CORSACCESSLIST,o)),n&&(Le(ue.HDB_SETTINGS_NAMES.SERVER_TIMEOUT_KEY,n),Le(ue.CONFIG_PARAMS.HTTP_TIMEOUT,n)),t&&(Le(ue.HDB_SETTINGS_NAMES.SERVER_KEEP_ALIVE_TIMEOUT_KEY,t),Le(ue.CONFIG_PARAMS.HTTP_KEEPALIVETIMEOUT,t)),r&&(Le(ue.HDB_SETTINGS_NAMES.SERVER_HEADERS_TIMEOUT_KEY,r),Le(ue.CONFIG_PARAMS.HTTP_HEADERSTIMEOUT,r))}catch(t){let r=`Error reading in HDB environment variables from path ${$l}. Please check your boot props and settings files`;sc.fatal(r),sc.error(t)}}a(cV,"initTestEnvironment")});var Ke=g((hoe,$O)=>{"use strict";var uc=M(),uV=J(),tr=Z(),lc=require("path"),lV=require("minimist"),xO=require("fs-extra"),qO=require("lodash");tr.initSync();var{CONFIG_PARAMS:Ks,DATABASES_PARAM_CONFIG:ic,SYSTEM_SCHEMA_NAME:Yl}=uc,oc,ac,cc;function FO(){if(oc!==void 0)return oc;if(tr.getHdbBasePath()!==void 0)return oc=tr.get(Ks.STORAGE_PATH)||lc.join(tr.getHdbBasePath(),uc.DATABASES_DIR_NAME),oc}a(FO,"getBaseSchemaPath");function GO(){if(ac!==void 0)return ac;if(tr.getHdbBasePath()!==void 0)return ac=VO(Yl),ac}a(GO,"getSystemSchemaPath");function kO(){if(cc!==void 0)return cc;if(tr.getHdbBasePath()!==void 0)return cc=tr.get(uc.CONFIG_PARAMS.STORAGE_AUDIT_PATH)||lc.join(tr.getHdbBasePath(),uc.TRANSACTIONS_DIR_NAME),cc}a(kO,"getTransactionAuditStoreBasePath");function _V(e,t){let r=tr.get(Ks.DATABASES)?.[e];return t&&r?.tables?.[t]?.auditPath||r?.auditPath||lc.join(kO(),e.toString())}a(_V,"getTransactionAuditStorePath");function VO(e,t){e=e.toString(),t=t&&t.toString();let r=tr.get(uc.CONFIG_PARAMS.DATABASES)?.[e];return t&&r?.tables?.[t]?.path||r?.path||lc.join(FO(),e)}a(VO,"getSchemaPath");function dV(e,t){e=e.toString(),t=t.toString();let r=process.env;Object.assign(r,lV(process.argv));let n=r[Ks.DATABASES.toUpperCase()];if(n){let i;try{i=JSON.parse(n)}catch(o){if(!uV.isObject(n))throw o;i=n}for(let o of i){let c=o[Yl];if(!c)continue;let u=tr.get(Ks.DATABASES);u=u??{};let _=c?.tables?.[t]?.[ic.PATH];if(_)return qO.set(u,[Yl,ic.TABLES,t,ic.PATH],_),tr.setProperty(Ks.DATABASES,u),_;let l=c?.[ic.PATH];if(l)return qO.set(u,[Yl,ic.PATH],l),tr.setProperty(Ks.DATABASES,u),l}}let s=r[Ks.STORAGE_PATH.toUpperCase()];if(s){if(!xO.pathExistsSync(s))throw new Error(s+" does not exist");let i=lc.join(s,e);return xO.mkdirsSync(i),tr.setProperty(Ks.STORAGE_PATH,s),i}return GO()}a(dV,"initSystemSchemaPaths");function fV(){oc=void 0,ac=void 0,cc=void 0}a(fV,"resetPaths");$O.exports={getBaseSchemaPath:FO,getSystemSchemaPath:GO,getTransactionAuditStorePath:_V,getTransactionAuditStoreBasePath:kO,getSchemaPath:VO,initSystemSchemaPaths:dV,resetPaths:fV}});var Ir=g((Toe,zO)=>{"use strict";var EV=Or().LMDB_ERRORS_ENUM,poe=require("lmdb"),hV=lt(),Soe=require("buffer").Buffer,{OVERFLOW_MARKER:YO,MAX_SEARCH_KEY_LENGTH:Kl}=hV,KO=["number","string","symbol","boolean","bigint"];function mV(e){if(e=e?.primaryStore||e,!e)throw new Error(EV.ENV_REQUIRED)}a(mV,"validateEnv");function pV(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(pV,"stringifyData");function SV(e){return e instanceof Date?e.valueOf():e}a(SV,"convertKeyValueToWrite");function TV(e,t){if(e===null)return t?[null]:void 0;if(e===void 0)return;if(KO.includes(typeof e))return e.length>Kl?[e.slice(0,Kl)+YO]:[e];let r;if(Array.isArray(e)){r=[];for(let n=0,s=e.length;n<s;n++){let i=e[n];if(KO.includes(typeof i))i.length>Kl?r.push(i.slice(0,Kl)+YO):r.push(i);else{if(i===null&&t)return r.push(null);if(i instanceof Date)return r.push(i.getTime())}}}else if(e instanceof Date)return[e.getTime()];return r}a(TV,"getIndexedValues");var Wl=0,WO=0;function QO(){WO=Date.now()-performance.now()}a(QO,"adjustStartTime");QO();var gV=6e4;setInterval(QO,gV).unref();function RV(){let e=performance.now()+WO;return e>Wl?(Wl=e,e):(Wl+=488e-6,Wl)}a(RV,"getNextMonotonicTime");zO.exports={validateEnv:mV,stringifyData:pV,convertKeyValueToWrite:SV,getNextMonotonicTime:RV,getIndexedValues:TV}});var JO,Tn,gh,_c=Oe(()=>{JO=require("events"),Tn=class extends JO.EventEmitter{static{a(this,"IterableEventQueue")}resolveNext;queue;hasDataListeners;[Symbol.asyncIterator](){let t=new gh;return t.queue=this,t}push(t){this.send(t)}send(t){this.resolveNext?(this.resolveNext({value:t}),this.resolveNext=null):this.hasDataListeners?this.emit("data",t):(this.queue||(this.queue=[]),this.queue.push(t))}getNextMessage(){return this.queue?.shift()}on(t,r){if(t==="data"&&!this.hasDataListeners)for(this.hasDataListeners=!0;this.queue?.length>0;)r(this.queue.shift());return super.on(t,r)}},gh=class{static{a(this,"EventQueueIterator")}queue;push(t){this.queue.send(t)}next(){let t=this.queue.getNextMessage();return t?{value:t}:new Promise(r=>this.queue.resolveNext=r)}return(t){return this.queue.emit("close"),{value:t,done:!0}}throw(t){return this.queue.emit("close",t),{done:!0}}}});var Ah={};Ve(Ah,{loadGQLSchema:()=>bV,start:()=>Rh,startOnMainThread:()=>OV});function Rh({ensureTable:e}){return{handleFile:t,setupFile:t};async function t(r,n,s,i){let{parse:o,Source:c,Kind:u,NamedTypeNode:_,StringValueNode:l}=await import("graphql"),d=o(new c(r.toString(),s)),f=new Map,E=[],h;for(let S of d.definitions)switch(S.kind){case u.OBJECT_TYPE_DEFINITION:let q=function(v){if(v.kind==="NonNullType"){let W=q(v.type);return W.nullable=!1,W}if(v.kind==="ListType")return{type:"array",elements:q(v.type)};let z={type:v.name?.value};return Object.defineProperty(z,"location",{value:v.loc.startToken}),z};a(q,"getProperty");let T=S.name.value,A=[],b={table:null,database:null,properties:A};f.set(T,b);for(let v of S.directives){if(v.name.value==="table"){for(let P of v.arguments)b[P.name.value]=P.value.value;b.schema&&(b.database=b.schema),b.table||(b.table=T),b.audit&&(b.audit=b.audit!=="false"),b.attributes=b.properties,E.push(b)}if(v.name.value==="sealed"&&(b.sealed=!0),v.name.value==="export"){b.export=!0;for(let P of v.arguments)P.name.value==="name"&&(b.export={name:P.value.value})}}let H=!1;for(let v of S.fields){let P=q(v.type);P.name=v.name.value,A.push(P);for(let z of v.directives)if(z.name.value==="primaryKey")H?console.warn("Can not define two attributes as a primary key"):(P.isPrimaryKey=!0,H=!0);else if(z.name.value==="indexed")P.indexed=!0;else if(z.name.value==="relationship"){let W={};for(let Q of z.arguments)W[Q.name.value]=Q.value.value;P.relationship=W}else if(z.name.value==="createdTime")P.assignCreatedTime=!0;else if(z.name.value==="updatedTime")P.assignUpdatedTime=!0;else if(z.name.value==="expiresAt")P.expiresAt=!0;else if(z.name.value==="allow"){let W=P.authorizedRoles=[];for(let Q of z.arguments)Q.name.value==="role"&&W.push(Q.value.value)}}b.type=T,T==="Query"&&(h=b)}function p(S){let T=f.get(S.type);T?(Object.defineProperty(S,"properties",{value:T.properties}),Object.defineProperty(S,"definition",{value:T})):S.type==="array"?p(S.elements):AV.includes(S.type)||(0,jO.getWorkerIndex)()===0&&console.error(`The type ${S.type} is unknown at line ${S.location.line}, column ${S.location.column}, in ${s}`)}a(p,"connectPropertyType");for(let S of f.values())for(let T of S.properties)p(T);for(let S of E)S.tableClass=e(S),S.export&&(S.export.name===""?i.set((0,Ql.dirname)(n),S.tableClass):i.set((0,Ql.dirname)(n)+"/"+(S.export.name||S.type),S.tableClass));if(h)for(let S of h.properties){let T=f.get(S.type);if(!T)throw new Error(`${S.type} was not found as a Query export`);i.set((0,Ql.dirname)(n)+"/"+S.name,T.tableClass)}}}var Ql,jO,AV,OV,bV,XO=Oe(()=>{Ql=require("path");be();jO=B(Ze()),AV=["ID","Int","Float","Long","String","Boolean","Date","Bytes","Any","BigInt"];a(Rh,"start");OV=Rh,bV=Rh({ensureTable:ot}).handleFile});async function zl(e){return NV?(dc||(dc=yV(IV)),(await(await dc).import(e)).namespace):import(e)}async function yV(e){let{StaticModuleRecord:t}=await import("@endo/static-module-record");return require("ses"),lockdown({domainTaming:"unsafe",consoleTaming:"unsafe",errorTaming:"unsafe",errorTrapping:"none",stackFiltering:"verbose"}),dc=new Compartment({console,Math,Date,fetch:wV,...e()},{},{name:"h-dapp",resolveHook(r,n){return r==="harperdb"?"harperdb":(r=new URL(r,n).toString(),(0,eb.extname)(r)||(r+=".js"),r)},importHook:async r=>{if(r==="harperdb")return{imports:[],exports:["Resource","tables","databases"],execute(s){Object.assign(s,{Resource:Bt,tables:Cr,databases:et})}};let n=await(0,ZO.readFile)(new URL(r),{encoding:"utf-8"});return new t(n,r)}}),dc}function wV(e,t){let r=typeof e=="string"||e.url;if(new URL(r).protocol!="https")throw new Error("Only https is allowed in fetch");return fetch(e,t)}function IV(){return{Resource:Bt,tables:Cr}}var ZO,eb,NV,dc,Oh=Oe(()=>{gn();be();ZO=require("fs/promises"),eb=require("path"),NV=!1;a(zl,"secureImport");a(yV,"getCompartment");a(wV,"secureOnlyFetch");a(IV,"getGlobalVars")});var Nh={};Ve(Nh,{handleFile:()=>CV});async function CV(e,t,r,n){let s=new Map,i=(0,tb.pathToFileURL)(r).toString(),o=await zl(i);u(o.default)&&n.set((0,bh.dirname)(t),o.default),c(o,(0,bh.dirname)(t));function c(_,l){for(let d in _){let f=_[d];u(f)?n.set(l+"/"+d,f):typeof f=="object"&&c(f,l+"/"+d)}}a(c,"recurseForResources");function u(_){return typeof _=="function"&&(_.get||_.put||_.post||_.delete)}return a(u,"isResource"),s}var tb,bh,rb=Oe(()=>{tb=require("url");Oh();bh=require("path");a(CV,"handleFile")});var wh={};Ve(wh,{start:()=>DV});function DV({resources:e}){e.set("login",yh),e.loginPath=t=>"/login?redirect="+encodeURIComponent(t.url)}var yh,nb=Oe(()=>{gn();a(DV,"start");yh=class extends Bt{static{a(this,"Login")}static async get(t,r,n){}static async post(t,r,n){let{username:s,password:i,redirect:o}=r;return{data:await n.login(s,i)}}}});var lb={};Ve(lb,{parse:()=>Ch,streamAsJSON:()=>fc,stringify:()=>Ci});function fc(e){return new Ih({value:e})}function sb(e){return console.error(e),JSON.stringify(e.toString())}function ib(e,t,r){return e?.then?r?e.then(t,r):e.then(t):t(e)}function Ci(e){try{return JSON.stringify(e)??"null"}catch(t){if(t===cb)return ub(e);if(t.resolution)return t.resolution.then(()=>Ci(e));throw t}}function ub(e){let t=typeof e;if(t==="object"){if(e===null)return"null";e.toJSON&&(e=e.toJSON());let r;if(Array.isArray(e)){r="[";for(let n=0;n<e.length;n++)n>0&&(r+=","),r+=ub(e[n]);return r+"]"}else{r="{";let n=!0;for(let s in e)n?n=!1:r+=",",r+=JSON.stringify(s)+":"+Ci(e[s]);return r+"}"}}else{if(t==="string")return JSON.stringify(e);if(t==="undefined")return"null"}return e.toString()}function Ch(e){return UV.test(e)?LV.parse(e):JSON.parse(e)}var ob,ab,LV,MV,cb,Ih,UV,Dh=Oe(()=>{ob=require("stream"),ab=B(require("json-bigint-fixes")),LV=(0,ab.default)({useNativeBigInt:!0}),MV=1e4,cb={};BigInt.prototype.toJSON=function(){throw cb};a(fc,"streamAsJSON");Ih=class extends ob.Readable{static{a(this,"JSONStream")}constructor(t){super(t),this.buffer=[],this.bufferSize=0,this.iterator=this.serialize(t.value,!0),this.activeIterators=[]}*serialize(t){if(t&&typeof t=="object"){let r=t[Symbol.asyncIterator],n=t[Symbol.iterator];if((n||r)&&!t.then){yield"[";let s=!0;if((r||n)&&!(t instanceof Array)){let i=r?t[Symbol.asyncIterator]():t[Symbol.iterator]();this.activeIterators.push(i);let o;for(;;)if(o=i.next(),o.then&&(yield o.then(c=>(o=c,""))),o.done){this.activeIterators.splice(this.activeIterators.indexOf(i),1),yield"]";return}else s?s=!1:yield",",yield*this.serialize(o.value)}for(let i of t)s?s=!1:yield",",yield*this.serialize(i);yield"]";return}if(t.then)try{yield t.then(s=>this.serialize(s),sb)}catch(s){yield sb(s)}else yield Ci(t)}else yield Ci(t)}_read(){if(!this._amReading){if(this._amReading=!0,this.done)return this.push(null);ib(this.readIterator(this.iterator),t=>{t?(this.done=!0,this.push(null)):this._amReading=!1},t=>{console.error(t),this.done=!0,this.push(t.toString()),this.push(null)})}}push(t){return t===null||t instanceof Buffer?(this.bufferSize>0&&this.flush(),super.push(t)):(this.bufferSize+=t.length||t.toString().length,this.buffer.push(t),this.bufferSize>MV?this.flush():!0)}flush(){let t=super.push(this.buffer.join(""));return this.buffer=[],this.bufferSize=0,t}readIterator(t){try{let r;if(t.childIterator)return ib(this.readIterator(t.childIterator),n=>{if(n)return t.childIterator=null,this.readIterator(t)});do{let n=t.next();if(n.done)return!0;if(r=n.value,r==null)r="null";else{if(r.then)return this.flush(),Promise.resolve(r).then(s=>{if(s&&typeof s.return=="function")return t.childIterator=s,this.readIterator(t);if(this.push(s+""))return this.readIterator(t)});if(typeof r.return=="function")return t.childIterator=r,this.readIterator(t)}}while(this.push(r))}catch(r){return console.error(r),this.push(r.toString()),this.push(null),!0}}_destroy(t,r){for(let n of this.activeIterators)t?n.throw(t):n.return();r()}};a(sb,"handleError");a(ib,"when");a(Ci,"stringify");a(ub,"jsStringify");UV=/-?\d{16,}/;a(Ch,"parse")});var Ob=g((voe,Ab)=>{"use strict";var Lh=require("recursive-iterator"),PV=require("alasql"),Mh=require("clone"),_b=J(),{handleHDBError:db,hdb_errors:vV}=ee(),{HDB_ERROR_MSGS:fb,HTTP_STATUS_CODES:Eb}=vV,{getDatabases:BV}=(be(),te(qe)),HV=["DISTINCT_ARRAY"],hb=Symbol("validateTables"),Uh=Symbol("validateTable"),Poe=Symbol("getAllColumns"),mb=Symbol("validateAllColumns"),Jl=Symbol("findColumn"),pb=Symbol("validateOrderBy"),Ec=Symbol("validateSegment"),Ph=Symbol("validateColumn"),Sb=Symbol("setColumnsForTable"),Tb=Symbol("checkColumnsForAsterisk"),gb=Symbol("validateGroupBy"),Rb=Symbol("hasColumns"),vh=class{static{a(this,"SelectValidator")}constructor(t){this.statement=t,this.attributes=[]}validate(){if(!this.statement)throw new Error("invalid sql statement");this[hb](),this[Tb](),this[mb]()}[hb](){if(this[Rb]()){if(!this.statement.from||this.statement.from.length===0)throw"no from clause";this.statement.from.forEach(t=>{this[Uh](t)}),this.statement.joins&&this.statement.joins.forEach(t=>{t.table.as=t.as,this[Uh](t.table)})}}[Rb](){let t=!1,r=new Lh(this.statement);for(let{node:n,path:s}of r)if(n&&n.columnid){t=!0;break}return t}[Uh](t){if(!t.databaseid)throw`schema not defined for table ${t.tableid}`;let r=BV();if(!r[t.databaseid])throw db(new Error,fb.SCHEMA_NOT_FOUND(t.databaseid),Eb.NOT_FOUND);if(!r[t.databaseid][t.tableid])throw db(new Error,fb.TABLE_NOT_FOUND(t.databaseid,t.tableid),Eb.NOT_FOUND);r[t.databaseid][t.tableid].attributes.forEach(s=>{let i=Mh(s);i.table=Mh(t),this.attributes.push(i)})}[Jl](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)}[Tb](){let t=new Lh(this.statement.columns);for(let{node:r,path:n}of t)r&&r.columnid==="*"&&n.indexOf("expression")<0&&this[Sb](r.tableid)}[Sb](t){this.attributes.forEach(r=>{(!t||t&&(r.table.tableid===t||r.table.as===t))&&!r.relation&&this.statement.columns.push(new PV.yy.Column({columnid:r.attribute,tableid:r.table.as?r.table.as:r.table.tableid}))})}[mb](){this[Ec](this.statement.columns,!1),this[Ec](this.statement.joins,!1),this[Ec](this.statement.where,!1),this[gb](this.statement.group,!1),this[Ec](this.statement.order,!0)}[Ec](t,r){if(!t)return;let n=new Lh(t),s=[];for(let{node:i,path:o}of n)!_b.isEmpty(i)&&!_b.isEmpty(i.columnid)&&i.columnid!=="*"&&(r?this[pb](i):s.push(this[Ph](i)));return s}[gb](t){if(!t)return;let r=[];if(this.statement.columns.forEach(n=>{if(!(n.funcid&&HV.indexOf(n.funcid.toUpperCase())>=0)){if(!n.aggregatorid&&!n.columnid){let s=Mh(n);delete s.as,r.push(s)}else if(n.columnid){let s=this[Jl](n)[0];s&&r.push(s)}}}),this.statement.group.forEach(n=>{let s=null;if(!n.columnid)r.forEach((i,o)=>{if(i.toString()===n.toString()){s=i,r.splice(o,1);return}});else{let i=this[Jl](n);if(!i||i.length===0)throw`unknown column '${n.toString()}' in group by`;if(i.length>1)throw`ambiguously defined column '${n.toString()}' in group by`;r.forEach((o,c)=>{if(o.attribute===i[0].attribute&&o.table.tableid===i[0].table.tableid){s=o,r.splice(c,1);return}})}if(!s)throw`group by column '${n.toString()}' must be in select`}),r.length>0)throw`select column '${r[0].attribute?r[0].attribute:r[0].toString()}' must be in group by`}[pb](t){let r=this.statement.columns.filter(n=>n.as===t.columnid);if(r.length>1)throw`ambiguous column reference ${(t.tableid?t.tableid+".":"")+t.columnid} in order by`;r.length===0&&this[Ph](t)}[Ph](t){let r=this[Jl](t),n=(t.tableid?t.tableid+".":"")+t.columnid;if(r.length===0)throw`unknown column ${n}`;if(r.length>1)throw`ambiguous column reference ${n}`;return r[0]}};Ab.exports=vh});var Nb=g((Hoe,bb)=>{"use strict";var Bh=class{static{a(this,"BridgeMethods")}createSchema(){throw new Error("createSchema bridge method is not defined")}dropSchema(){throw new Error("dropSchema bridge method is not defined")}createTable(){throw new Error("createTable bridge method is not defined")}dropTable(){throw new Error("dropTable bridge method is not defined")}createRecords(){throw new Error("createRecords bridge method is not defined")}updateRecords(){throw new Error("updateRecords bridge method is not defined")}async upsertRecords(){throw new Error("upsertRecords bridge method is not defined")}deleteRecords(){throw new Error("deleteRecords bridge method is not defined")}createAttribute(){throw new Error("createAttribute bridge method is not defined")}dropAttribute(){throw new Error("dropAttribute bridge method is not defined")}searchByConditions(){throw new Error("searchByConditions bridge method is not defined")}searchByHash(){throw new Error("searchByHash bridge method is not defined")}searchByValue(){throw new Error("searchByValue bridge method is not defined")}getDataByHash(){throw new Error("getDataByHash bridge method is not defined")}getDataByValue(){throw new Error("getDataByValue bridge method is not defined")}deleteRecordsBefore(){throw new Error("deleteRecordsBefore bridge method is not defined")}deleteAuditLogsBefore(){throw new Error("deleteAuditLogsBefore bridge method is not defined")}async readAuditLog(){throw new Error("readAuditLog bridge method is not defined")}};bb.exports=Bh});var wb=g((qoe,yb)=>{"use strict";var Hh=class{static{a(this,"DBIDefinition")}constructor(t=!1,r=!1){this.dup_sort=t,this.is_hash_attribute=r,this.useVersions=r}};yb.exports=Hh});var Lb={};Ve(Lb,{HAS_EXPIRATION:()=>Yh,LAST_TIMESTAMP_PLACEHOLDER:()=>pc,LOCAL_TIMESTAMP:()=>xV,METADATA:()=>hc,NO_TIMESTAMP:()=>qh,PENDING_LOCAL_TIME:()=>Kh,PREVIOUS_TIMESTAMP_PLACEHOLDER:()=>$h,RecordEncoder:()=>kh,TIMESTAMP_ASSIGN_LAST:()=>FV,TIMESTAMP_ASSIGN_NEW:()=>Cb,TIMESTAMP_ASSIGN_PREVIOUS:()=>Db,TIMESTAMP_PLACEHOLDER:()=>jl,TIMESTAMP_RECORD_PREVIOUS:()=>Fh,fromResource:()=>t_,getUpdateRecord:()=>Wh,handleLocalTimeForGets:()=>r_});function kV(){return mc[0]=mc[0]^64,qV.getFloat64(0)}function t_(e){Vh=!0;try{return e()}finally{Vh=!1}}function r_(e){let t=e.getEntry;e.readCount=0,e.cachePuts=!1,e.getEntry=function(i,o){e.readCount++;let c=t.call(this,i,o),u=c?.value,_=u?.[hc];return _>=0&&(c.metadataFlags=_,c.localTime=u.localTime,c.value=u.value,u.expiresAt>0&&(c.expiresAt=u.expiresAt)),c&&(c.key=i),c};let r=e.get;e.get=function(i,o){let c=r.call(this,i,o);return c?.[hc]>=0?c.value:c};let n=e.getRange;e.getRange=function(i){let o=n.call(this,i);return i.valuesForKey?o.map(c=>c?.value):i.values===!1||i.onlyCount?o:o.map(c=>{let u=c.value,_=u[hc];return _>=0&&(c.metadataFlags=_,c.localTime=u.localTime,c.value=u.value,u.expiresAt>0&&(c.expiresAt=u.expiresAt)),c})};let s=e.useReadTransaction();if(s.done(),!s.done.isTracked){let i=s.constructor,o=s.use,c=s.done;i.prototype.use=function(){if(this.timerTracked||(this.timerTracked=!0,Di.push(new WeakRef(this))),!Vh)try{throw new Error("Read transaction used outside of resource")}catch(u){this.readStack=u.stack}o.call(this)},i.prototype.done=function(){if(c.call(this),this.isDone)for(let u=0;u<Di.length;u++){let _=Di[u].deref();(!_||_.isDone||_.isCommitted)&&Di.splice(u--,1)}},i.prototype.done.isTracked=!0}return e}function Wh(e,t,r){return function(n,s,i,o,c=-1,u,_,l,d="put",f,E){if(f||u==null?Po=i?.localTime?Fh|Db:qh:Po=u?i?.localTime?Fh|16384:Cb|16384:qh,l>0&&(c|=Yh),Zl=c,Gh=l,i?.version===o&&u===!1)throw new Error("Must retain local time if version is not changed");let h={version:o,instructedWrite:Po>0},p;try{f&&(h.ifVersion=p=i?.version??null);let S=e.put(n,s,h);if(u){let T=_?.user?.username;if(E&&(Xl=e.encoder.encode(E)),f&&i?.localTime){let A=i?.localTime,b=r.get(A);if(b){let H=Dt(b).previousLocalTime;return r.put(A,e_(o,t,n,H,T,d,Xl),{ifVersion:p}),S}}r.put(pc,e_(o,t,n,i?.localTime?1:0,T,d,Xl),{append:d!=="invalidate",instructedWrite:!0,ifVersion:p})}return S}catch(S){throw S.message+=" id: "+n+" options: "+h,S}}}var Ib,xh,jl,pc,$h,xV,hc,mc,qV,qh,Cb,FV,Db,Fh,Yh,Kh,GV,Xl,Po,Zl,Gh,kh,koe,Vh,Di,vo=Oe(()=>{Ib=require("msgpackr");Li();xh=B(Y()),jl=new Uint8Array([1,1,1,1,4,64,0,0]),pc=new Uint8Array([1,1,1,1,1,0,0,0]),$h=new Uint8Array([1,1,1,1,3,64,0,0]),xV=Symbol("local-timestamp"),hc=Symbol("metadata"),mc=new Uint8Array(8),qV=new DataView(mc.buffer,0,8),qh=0,Cb=0,FV=1,Db=3,Fh=4,Yh=16,Kh=1,Po=0,Zl=-1,Gh=0,kh=class extends Ib.Encoder{static{a(this,"RecordEncoder")}constructor(t){t.useBigIntExtension=!0,super(t);let r=this.encode;this.encode=function(n,s){if(Po||Zl>=0){let i=0,o=Po;o&&(i+=8,Po=0);let c=Zl,u=Gh;c>=0&&(i+=2,Zl=-1,u&&(i+=8,Gh=0));let _=GV=r.call(this,n,s|2048|i);Xl=_.subarray((_.start||0)+i,_.end);let l=_.start||0;return o&&(jl[4]=o,jl[5]=o>>8,_.set(jl,l),l+=8),c>=0&&(_[l++]=c,_[l++]=0,u&&(_.dataView||(_.dataView=new DataView(_.buffer,_.byteOffset,_.byteLength))).setFloat64(l,u)),_}else return r.call(this,n,s)}}decode(t,r){let n=r?.start||0,s=r>-1?r:r?.end||t.length,i=t[n],o=0;try{if(i<32&&s>2){let c=n,u;if(i===2){if(t.copy)t.copy(mc,0,c),c+=8;else for(let d=0;d<8;d++)mc[d]=t[c++];u=kV(),i=t[c]}let _;i<32&&(o=i,c+=2,o&Yh&&(_=(t.dataView||(t.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength))).getFloat64(c),c+=8));let l=super.decode(t.subarray(c,s),s-c);return{localTime:u,value:l,[hc]:o,expiresAt:_}}return super.decode(t,r)}catch(c){throw c.message+=", data: "+t.slice(0,40).toString("hex"),c}}};a(kV,"getTimestamp");koe=Map.prototype.get;a(t_,"fromResource");a(r_,"handleLocalTimeForGets");Di=[];setInterval(()=>{for(let e=0;e<Di.length;e++){let t=Di[e].deref();!t||t.isDone||t.isCommitted?Di.splice(e--,1):t.notCurrent&&(t.openTimer?(t.openTimer>3&&(t.openTimer>60?(xh.error("Read transaction detected that has been open too long (over 15 minutes), ending transaction",t),t.done()):xh.error("Read transaction detected that has been open too long (over one minute), make sure read transactions are quickly closed",t)),t.openTimer++):t.openTimer=1)}},15e3).unref();a(Wh,"getUpdateRecord")});var n_=g(($oe,Mb)=>{"use strict";var zh=Z(),Jh=M(),{RecordEncoder:VV}=(vo(),te(Lb));zh.initSync();var $V=zh.get(Jh.CONFIG_PARAMS.STORAGE_COMPRESSION),YV=zh.get(Jh.CONFIG_PARAMS.STORAGE_CACHING)!==!1,KV=Jh.UPDATES_PROPERTY,Qh=class{static{a(this,"OpenDBIObject")}constructor(t,r=!1){this.dupSort=t===!0,this.encoding=t?"ordered-binary":"msgpack",this.useVersions=r,this.compression=$V&&r&&{startingOffset:32},this.sharedStructuresKey=Symbol.for("structures"),r&&(this.cache=YV&&{validated:!0},this.randomAccessStructure=!0,this.freezeData=!0,this.encoder={Encoder:VV},this.alwaysLazyProperty=n=>n===KV)}};Mb.exports=Qh});var i_=g((Koe,Pb)=>{"use strict";var Bo=Z(),Sc=M();Bo.initSync();var WV=Bo.get(Sc.CONFIG_PARAMS.STORAGE_WRITEASYNC)===!0||Bo.get(Sc.CONFIG_PARAMS.STORAGE_WRITEASYNC)==="true"||Bo.get(Sc.CONFIG_PARAMS.STORAGE_WRITEASYNC)==="TRUE",Ub=Bo.get(Sc.CONFIG_PARAMS.STORAGE_OVERLAPPINGSYNC),QV=Bo.get(Sc.CONFIG_PARAMS.STORAGE_NOREADAHEAD),s_=class{static{a(this,"OpenEnvironmentObject")}constructor(t,r=!1){this.path=t,this.mapSize=1073741824,this.maxDbs=1e4,this.maxReaders=1e3,this.sharedStructuresKey=Symbol.for("structures"),this.readOnly=r,this.trackMetrics=!0,this.noSync=WV,this.noFSAccess=!0,Ub!==void 0&&(this.overlappingSync=Ub),this.noReadAhead=QV}};Pb.exports=s_;s_.MAX_DBS=1e4});var $e=g((Qoe,$b)=>{"use strict";var Xh=require("lmdb"),Rn=require("fs-extra"),Dr=require("path"),o_=Ir(),Hb=Y(),rr=Or().LMDB_ERRORS_ENUM,a_=wb(),Zh=n_(),xb=i_(),Ws=lt(),vb=M(),{table:zV,resetDatabases:JV}=(be(),te(qe)),Bb=Z(),An=Ws.INTERNAL_DBIS_NAME,qb=Ws.DBI_DEFINITION_NAME,jV="data.mdb",XV="lock.mdb",Tc=".mdb",ZV="-lock",jh=class{static{a(this,"TransactionCursor")}constructor(t,r,n=!1){this.dbi=jr(t,r),this.key_type=this.dbi[Ws.DBI_DEFINITION_NAME].key_type,this.is_hash_attribute=this.dbi[Ws.DBI_DEFINITION_NAME].is_hash_attribute,this.txn=t.beginTxn({readOnly:n===!1}),this.cursor=new Xh.Cursor(this.txn,this.dbi)}close(){this.cursor.close(),this.txn.abort()}commit(){this.cursor.close(),this.txn.commit()}};function c_(e,t){if(e===void 0)throw new Error(rr.BASE_PATH_REQUIRED);if(t===void 0)throw new Error(rr.ENV_NAME_REQUIRED)}a(c_,"pathEnvNameValidation");async function em(e,t,r=!0){try{await Rn.access(e)}catch(n){throw n.code==="ENOENT"?new Error(rr.INVALID_BASE_PATH):n}try{let n=Dr.join(e,t+Tc);return await Rn.access(n,Rn.constants.R_OK|Rn.constants.F_OK),n}catch(n){if(n.code==="ENOENT")if(r)try{return await Rn.access(Dr.join(e,t,jV),Rn.constants.R_OK|Rn.constants.F_OK),Dr.join(e,t)}catch(s){if(s.code==="ENOENT")throw new Error(rr.INVALID_ENVIRONMENT)}else throw new Error(rr.INVALID_ENVIRONMENT);throw n}}a(em,"validateEnvironmentPath");function u_(e,t){if(o_.validateEnv(e),t===void 0)throw new Error(rr.DBI_NAME_REQUIRED)}a(u_,"validateEnvDBIName");async function e$(e,t,r=!1,n=!1){c_(e,t);let s=Dr.basename(e);t=t.toString();let i=Bb.get(vb.CONFIG_PARAMS.DATABASES);i||Bb.setProperty(vb.CONFIG_PARAMS.DATABASES,i={}),i[s]||(i[s]={}),i[s].path=e;try{return await em(e,t,n),Fb(e,t,r)}catch(o){if(o.message===rr.INVALID_ENVIRONMENT){let c=Dr.join(e,t);await Rn.mkdirp(n?c:e);let u=new xb(n?c:c+Tc,!1),_=Xh.open(u);_.dbis=Object.create(null);let l=new Zh(!1);_.openDB(An,l),global.lmdb_map===void 0&&(global.lmdb_map=Object.create(null));let d=tm(e,t,r);return _[Ws.ENVIRONMENT_NAME_KEY]=d,global.lmdb_map[d]=_,_}throw o}}a(e$,"createEnvironment");async function t$(e,t,r,n=!0){c_(e,t),t=t.toString();let s=Dr.join(e,t);return zV({table:t,database:Dr.parse(e).name,path:s,attributes:[{name:"id",isPrimaryKey:!0}]})}a(t$,"copyEnvironment");async function Fb(e,t,r=!1){c_(e,t),t=t.toString();let n=tm(e,t,r);if(global.lmdb_map===void 0&&(global.lmdb_map=Object.create(null)),global.lmdb_map[n]!==void 0)return global.lmdb_map[n];let s=await em(e,t),i=Dr.join(e,t+Tc),o=s!=i,c=new xb(s,o),u=Xh.open(c);u.dbis=Object.create(null);let _=kb(u);for(let l=0;l<_.length;l++)jr(u,_[l]);return u[Ws.ENVIRONMENT_NAME_KEY]=n,global.lmdb_map[n]=u,u}a(Fb,"openEnvironment");async function r$(e,t,r=!1){c_(e,t),t=t.toString();let n=Dr.join(e,t+Tc),s=await em(e,t);if(global.lmdb_map!==void 0){let i=tm(e,t,r);if(global.lmdb_map[i]){let o=global.lmdb_map[i];await Gb(o),delete global.lmdb_map[i]}}await Rn.remove(s),await Rn.remove(s===n?s+ZV:Dr.join(Dr.dirname(s),XV))}a(r$,"deleteEnvironment");async function Gb(e){o_.validateEnv(e);let t=e[Ws.ENVIRONMENT_NAME_KEY];await e.close(),t!==void 0&&global.lmdb_map!==void 0&&delete global.lmdb_map[t]}a(Gb,"closeEnvironment");function tm(e,t,r=!1){let s=`${Dr.basename(e)}.${t}`;return r===!0&&(s=`txn.${s}`),s}a(tm,"getCachedEnvironmentName");function n$(e){o_.validateEnv(e);let t=Object.create(null),r=jr(e,An);for(let{key:n,value:s}of r.getRange({start:!1}))if(n!==An)try{t[n]=Object.assign(new a_,s)}catch{Hb.warn(`an internal error occurred: unable to parse DBI Definition for ${n}`)}return t}a(n$,"listDBIDefinitions");function kb(e){o_.validateEnv(e);let t=[],r=jr(e,An);for(let{key:n}of r.getRange({start:!1}))n!==An&&t.push(n);return t}a(kb,"listDBIs");function s$(e,t){let n=jr(e,An).getEntry(t),s=new a_;if(n!==void 0){try{s=Object.assign(s,n.value)}catch{Hb.warn(`an internal error occurred: unable to parse DBI Definition for ${n}`)}return s}}a(s$,"getDBIDefinition");function Vb(e,t,r,n=!r){if(u_(e,t),t=t.toString(),t===An)throw new Error(rr.CANNOT_CREATE_INTERNAL_DBIS_NAME);try{return jr(e,t)}catch(s){if(s.message===rr.DBI_DOES_NOT_EXIST){let i=new Zh(r,n===!0),o=e.openDB(t,i),c=new a_(r===!0,n);return o[qb]=c,jr(e,An).putSync(t,c),e.dbis[t]=o,o}throw s}}a(Vb,"createDBI");function jr(e,t){if(u_(e,t),t=t.toString(),e.dbis[t]!==void 0)return e.dbis[t];let r;if(t!==An?r=s$(e,t):r=new a_,r===void 0)throw new Error(rr.DBI_DOES_NOT_EXIST);let n;try{let s=new Zh(r.dup_sort,r.useVersions);if(n=e.openDB(t,s),n.db===void 0)throw new Error("MDB_NOTFOUND")}catch(s){throw s.message.includes("MDB_NOTFOUND")===!0?new Error(rr.DBI_DOES_NOT_EXIST):s}return n[qb]=r,e.dbis[t]=n,n}a(jr,"openDBI");function i$(e,t){u_(e,t),t=t.toString();let r=jr(e,t),n=r.getStats();return r[Ws.DBI_DEFINITION_NAME].is_hash_attribute&&n.entryCount>0&&n.entryCount--,n}a(i$,"statDBI");async function o$(e,t){try{let r=Dr.join(e,t+Tc);return(await Rn.stat(r)).size}catch{throw new Error(rr.INVALID_ENVIRONMENT)}}a(o$,"environmentDataSize");function a$(e,t){if(u_(e,t),t=t.toString(),t===An)throw new Error(rr.CANNOT_DROP_INTERNAL_DBIS_NAME);jr(e,t).dropSync(),e.dbis!==void 0&&delete e.dbis[t],jr(e,An).removeSync(t)}a(a$,"dropDBI");function c$(e,t,r){let n;for(let s=0;s<r.length;s++){let i=r[s];if(!e.dbis[i])try{jr(e,i)}catch(o){if(o.message===rr.DBI_DOES_NOT_EXIST)Vb(e,i,i!==t,i===t),n=!0;else throw o}}n&&JV()}a(c$,"initializeDBIs");$b.exports={openDBI:jr,openEnvironment:Fb,createEnvironment:e$,listDBIs:kb,listDBIDefinitions:n$,createDBI:Vb,dropDBI:a$,statDBI:i$,deleteEnvironment:r$,initializeDBIs:c$,TransactionCursor:jh,environmentDataSize:o$,copyEnvironment:t$,closeEnvironment:Gb}});var Kb=g((Joe,Yb)=>{"use strict";var rm=class{static{a(this,"InsertRecordsResponseObject")}constructor(t=[],r=[],n=void 0){this.written_hashes=t,this.skipped_hashes=r,this.txn_time=n}};Yb.exports=rm});var Qb=g((Xoe,Wb)=>{"use strict";var nm=class{static{a(this,"UpdateRecordsResponseObject")}constructor(t=[],r=[],n=void 0,s=[]){this.written_hashes=t,this.skipped_hashes=r,this.txn_time=n,this.original_records=s}};Wb.exports=nm});var Jb=g((eae,zb)=>{"use strict";var sm=class{static{a(this,"UpsertRecordsResponseObject")}constructor(t=[],r=void 0,n=[]){this.written_hashes=t,this.txn_time=r,this.original_records=n}};zb.exports=sm});var Ho=g((iae,Zb)=>{"use strict";var u$=$e(),l$=Kb(),_$=Qb(),d$=Jb(),Fn=Ir(),gc=Or().LMDB_ERRORS_ENUM,f$=lt(),ds=M(),E$=J(),h$=require("uuid"),rae=require("lmdb"),{handleHDBError:m$,hdb_errors:p$}=ee(),{OVERFLOW_MARKER:nae,MAX_SEARCH_KEY_LENGTH:sae}=f$,jb=Z();jb.initSync();var l_=jb.get(ds.CONFIG_PARAMS.STORAGE_PREFETCHWRITES),im=ds.TIME_STAMP_NAMES_ENUM.CREATED_TIME,Mi=ds.TIME_STAMP_NAMES_ENUM.UPDATED_TIME;async function S$(e,t,r,n,s=Fn.getNextMonotonicTime()){um(e,t,r,n),om(e,t,r);let i=new l$,o=[],c=[];for(let u=0;u<n.length;u++){let _=n[u];Xb(_,!0,s);let l=T$(e,t,r,_),d=_[t];o.push(l),c.push(d)}return am(o,c,n,i,s)}a(S$,"insertRecords");function T$(e,t,r,n){let s=n[t];return e.dbis[t].ifNoExists(s,()=>{for(let i=0;i<r.length;i++){let o=r[i];if(o===t||n.hasOwnProperty(o)===!1)continue;let c=n[o];if(typeof c=="function"){let l=c([[{}]]);Array.isArray(l)&&(c=l[0][ds.FUNC_VAL],n[o]=c)}let u=Fn.getIndexedValues(c),_=e.dbis[o];if(u){l_&&_.prefetch(u.map(l=>({key:l,value:s})),__);for(let l=0,d=u.length;l<d;l++)_.put(u[l],s)}}l_&&e.dbis[t].prefetch([s],__),e.dbis[t].put(s,n,n[Mi])})}a(T$,"insertRecord");function g$(e,t=[]){let r=0;for(let n=0;n<t.length;n++){let s=t[n];e.splice(s-r,1),r++}}a(g$,"removeSkippedRecords");function Xb(e,t,r){let n=r>0;(n||!Number.isInteger(e[Mi]))&&(e[Mi]=r||(r=Fn.getNextMonotonicTime())),t===!0?(n||!Number.isInteger(e[im]))&&(e[im]=r||Fn.getNextMonotonicTime()):delete e[im]}a(Xb,"setTimestamps");function om(e,t,r){r.indexOf(ds.TIME_STAMP_NAMES_ENUM.CREATED_TIME)<0&&r.push(ds.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.indexOf(ds.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)<0&&r.push(ds.TIME_STAMP_NAMES_ENUM.UPDATED_TIME),u$.initializeDBIs(e,t,r)}a(om,"initializeTransaction");async function R$(e,t,r,n,s=Fn.getNextMonotonicTime()){um(e,t,r,n),om(e,t,r);let i=new _$,o=[],c=[],u=[];for(let _=0;_<n.length;_++){let l=n[_],d=l[t],f;try{f=cm(e,t,l,d,i,!0,s)}catch{i.skipped_hashes.push(d),o.push(_);continue}c.push(f),u.push(d)}return am(c,u,n,i,s,o)}a(R$,"updateRecords");async function A$(e,t,r,n,s=Fn.getNextMonotonicTime()){try{um(e,t,r,n)}catch(u){throw m$(u,u.message,p$.HTTP_STATUS_CODES.BAD_REQUEST)}om(e,t,r);let i=new d$,o=[],c=[];for(let u=0;u<n.length;u++){let _=n[u],l;E$.isEmpty(_[t])?(l=h$.v4(),_[t]=l):l=_[t];let d=cm(e,t,_,l,i,!1,s);o.push(d),c.push(l)}return am(o,c,n,i,s)}a(A$,"upsertRecords");async function am(e,t,r,n,s,i=[]){let o=await Promise.all(e);for(let c=0,u=o.length;c<u;c++)o[c]===!0?n.written_hashes.push(t[c]):(n.skipped_hashes.push(t[c]),i.push(c));return n.txn_time=s||Fn.getNextMonotonicTime(),g$(r,i),n}a(am,"finalizeWrite");function cm(e,t,r,n,s,i=!1,o){let c=e.dbis[t],u=c.getEntry(n),_=u?.value,l=_;if(!_){if(i)return!1;_={}}if(Xb(r,!l,o),Number.isInteger(r[Mi])&&_[Mi]>r[Mi])return!1;l&&s.original_records.push(_);let d,f=a(()=>{for(let h in r){if(!r.hasOwnProperty(h)||h===t)continue;let p=r[h],S=e.dbis[h];if(S===void 0)continue;let T=_[h];if(typeof p=="function"){let b=p([[_]]);Array.isArray(b)&&(p=b[0][ds.FUNC_VAL],r[h]=p)}if(p===T)continue;let A=Fn.getIndexedValues(T);if(A){l_&&S.prefetch(A.map(b=>({key:b,value:n})),__);for(let b=0,H=A.length;b<H;b++)S.remove(A[b],n)}if(A=Fn.getIndexedValues(p),A){l_&&S.prefetch(A.map(b=>({key:b,value:n})),__);for(let b=0,H=A.length;b<H;b++)S.put(A[b],n)}}let E=Object.assign({},_,r);c.put(n,E,E[Mi])},"do_put");return u?d=c.ifVersion(n,u.version,f):d=c.ifNoExists(n,f),d.then(E=>E?!0:cm(e,t,r,n,s,i,o))}a(cm,"updateUpsertRecord");function O$(e,t,r){if(Fn.validateEnv(e),t===void 0)throw new Error(gc.HASH_ATTRIBUTE_REQUIRED);if(!Array.isArray(r))throw r===void 0?new Error(gc.WRITE_ATTRIBUTES_REQUIRED):new Error(gc.WRITE_ATTRIBUTES_MUST_BE_ARRAY)}a(O$,"validateBasic");function um(e,t,r,n){if(O$(e,t,r),!Array.isArray(n))throw n===void 0?new Error(gc.RECORDS_REQUIRED):new Error(gc.RECORDS_MUST_BE_ARRAY)}a(um,"validateWrite");function __(){}a(__,"noop");Zb.exports={insertRecords:S$,updateRecords:R$,upsertRecords:A$}});var Ui=g((aae,b$)=>{b$.exports={hdb_table:{hash_attribute:"id",name:"hdb_table",schema:"system",residence:["*"],attributes:[{attribute:"id"},{attribute:"name"},{attribute:"hash_attribute"},{attribute:"schema"},{attribute:"residence"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_attribute:{hash_attribute:"id",name:"hdb_attribute",schema:"system",residence:["*"],attributes:[{attribute:"id"},{attribute:"schema"},{attribute:"table"},{attribute:"attribute"},{attribute:"schema_table"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_schema:{hash_attribute:"name",name:"hdb_schema",schema:"system",residence:["*"],attributes:[{attribute:"name"},{attribute:"createddate"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_user:{hash_attribute:"username",name:"hdb_user",schema:"system",residence:["*"],attributes:[{attribute:"username"},{attribute:"password"},{attribute:"role"},{attribute:"active"},{attribute:"hash"},{attribute:"refresh_token"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_role:{hash_attribute:"id",name:"hdb_role",schema:"system",attributes:[{attribute:"id"},{attribute:"role"},{attribute:"permission"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}],residence:["*"]},hdb_job:{hash_attribute:"id",name:"hdb_job",schema:"system",attributes:[{attribute:"id"},{attribute:"user"},{attribute:"type"},{attribute:"status"},{attribute:"start_datetime"},{attribute:"end_datetime"},{attribute:"message"},{attribute:"created_datetime"},{attribute:"request"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_license:{hash_attribute:"license_key",name:"hdb_license",schema:"system",attributes:[{attribute:"license_key"},{attribute:"company"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_info:{hash_attribute:"info_id",name:"hdb_info",schema:"system",attributes:[{attribute:"info_id"},{attribute:"data_version_num"},{attribute:"hdb_version_num"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_nodes:{hash_attribute:"name",name:"hdb_nodes",schema:"system",attributes:[{attribute:"name"},{attribute:"subscriptions"},{attribute:"system_info"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_analytics:{hash_attribute:"id",name:"hdb_analytics",schema:"system",audit:!1,attributes:[{attribute:"id"},{attribute:"time"},{attribute:"metric"}]},hdb_raw_analytics:{hash_attribute:"id",name:"hdb_raw_analytics",schema:"system",audit:!1,attributes:[{attribute:"id"},{attribute:"time"},{attribute:"metrics"}]},hdb_temp:{hash_attribute:"id",name:"hdb_temp",schema:"system",attributes:[{attribute:"id"}]}}});var kn=g((cae,rN)=>{"use strict";var tN=J(),eN=M(),xo=/^[\x20-\x2E|\x30-\x5F|\x61-\x7E]*$/,Gn=require("joi"),Qs={schema_format:{pattern:xo,message:"names cannot include backticks or forward slashes"},schema_length:{minimum:1,maximum:250,tooLong:"cannot exceed 250 characters"}},N$=Gn.alternatives(Gn.string().min(1).max(Qs.schema_length.maximum).pattern(xo).messages({"string.pattern.base":"{:#label} "+Qs.schema_format.message}),Gn.number(),Gn.array()).required(),y$=Gn.alternatives(Gn.string().min(1).max(Qs.schema_length.maximum).pattern(xo).messages({"string.pattern.base":"{:#label} "+Qs.schema_format.message}),Gn.number()),w$=Gn.alternatives(Gn.string().min(1).max(Qs.schema_length.maximum).pattern(xo).messages({"string.pattern.base":"{:#label} "+Qs.schema_format.message}),Gn.number()).required();function I$(e,t){return t?typeof t!="string"?`'${e}' must be a string`:t.length?t.length>Qs.schema_length.maximum?`'${e}' maximum of 250 characters`:xo.test(t)?"":`'${e}' has illegal characters`:`'${e}' must be at least one character`:`'${e}' is required`}a(I$,"checkValidTable");function C$(e,t){return tN.doesSchemaExist(e)?e:t.message(`Database '${e}' does not exist`)}a(C$,"validateSchemaExists");function D$(e,t){let r=t.state.ancestors[0].schema;return tN.doesTableExist(r,e)?e:t.message(`Table '${e}' does not exist`)}a(D$,"validateTableExists");function L$(e,t){return e.toLowerCase()===eN.SYSTEM_SCHEMA_NAME?t.message(`'subscriptions[${t.state.path[1]}]' invalid database name, '${eN.SYSTEM_SCHEMA_NAME}' name is reserved`):e}a(L$,"validateSchemaName");rN.exports={common_validators:Qs,schema_regex:xo,hdb_schema_table:N$,validateSchemaExists:C$,validateTableExists:D$,validateSchemaName:L$,checkValidTable:I$,hdb_database:y$,hdb_table:w$}});var d_=g((lae,nN)=>{var{common_validators:Vn}=kn(),Ac=je(),Rc="is required",_t={database:{presence:!1,format:Vn.schema_format,length:Vn.schema_length},schema:{presence:!1,format:Vn.schema_format,length:Vn.schema_length},table:{presence:!0,format:Vn.schema_format,length:Vn.schema_length},attribute:{presence:!0,format:Vn.schema_format,length:Vn.schema_length},hash_attribute:{presence:!0,format:Vn.schema_format,length:Vn.schema_length}};function Oc(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(Oc,"makeAttributesStrings");function M$(e){return e=Oc(e),_t.table.presence=!1,_t.attribute.presence=!1,_t.hash_attribute.presence=!1,Ac.validateObject(e,_t)}a(M$,"schema_object");function U$(e){return e=Oc(e),_t.table.presence={message:Rc},_t.attribute.presence=!1,_t.hash_attribute.presence=!1,Ac.validateObject(e,_t)}a(U$,"table_object");function P$(e){return e=Oc(e),_t.table.presence={message:Rc},_t.attribute.presence=!1,Ac.validateObject(e,_t)}a(P$,"create_table_object");function v$(e){return e=Oc(e),_t.table.presence={message:Rc},_t.attribute.presence={message:Rc},_t.hash_attribute.presence=!1,Ac.validateObject(e,_t)}a(v$,"attribute_object");function B$(e){return e=Oc(e),_t.table.presence={message:Rc},_t.attribute.presence=!1,_t.hash_attribute.presence=!1,Ac.validateObject(e,_t)}a(B$,"describe_table");function H$(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(H$,"validateTableResidence");nN.exports={schema_object:M$,create_table_object:P$,table_object:U$,attribute_object:v$,describe_table:B$,validateTableResidence:H$}});var iN=g((dae,sN)=>{"use strict";var x$=require("uuid"),lm=class{static{a(this,"CreateAttributeObject")}constructor(t,r,n,s){this.schema=t,this.table=r,this.attribute=n,this.id=s||x$.v4(),this.schema_table=`${this.schema}.${this.table}`}};sN.exports=lm});var f_=g((Eae,oN)=>{"use strict";var q$=iN(),_m=class extends q${static{a(this,"LMDBCreateAttributeObject")}constructor(t,r,n,s,i=!0,o=!1){super(t,r,n,s),this.dup_sort=i,this.is_hash_attribute=o}};oN.exports=_m});var cN=g((mae,aN)=>{"use strict";aN.exports=G$;var F$="inserted";function G$(e,t,r,n){let s={message:`${e} ${t.length} of ${r.records.length} records`,skipped_hashes:n};return e===F$?(s.inserted_hashes=t,s):(s.update_hashes=t,s)}a(G$,"returnObject")});var E_=g((Sae,fN)=>{"use strict";var k$=M(),dm=$e(),V$=Ho(),{getSystemSchemaPath:$$,getSchemaPath:Y$}=Ke(),K$=Ui(),W$=d_(),Q$=f_(),z$=cN(),{handleHDBError:uN,hdb_errors:_N}=ee(),lN=J(),{HTTP_STATUS_CODES:J$}=_N,fm=K$.hdb_attribute,dN=[];for(let e=0;e<fm.attributes.length;e++)dN.push(fm.attributes[e].attribute);var j$="inserted";fN.exports=X$;async function X$(e){let t=W$.attribute_object(e);if(t)throw uN(new Error,t.message,_N.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0);let r=!e.skip_table_check&&lN.checkGlobalSchemaTable(e.schema,e.table);if(r)throw uN(new Error,r,J$.NOT_FOUND);e.is_hash_attribute=e.is_hash_attribute=="true",e.dup_sort=lN.isEmpty(e.dup_sort)||e.dup_sort=="true";let n=[];if(global.hdb_schema[e.schema]&&global.hdb_schema[e.schema][e.table]&&(n=global.hdb_schema[e.schema][e.table].attributes),Array.isArray(n)&&n.length>0){for(let i of n)if(i.attribute===e.attribute)throw new Error(`attribute '${i.attribute}' already exists in ${e.schema}.${e.table}`)}let s=new Q$(e.schema,e.table,e.attribute,e.id);try{let i=await dm.openEnvironment(Y$(e.schema,e.table),e.table);if(i.dbis[e.attribute]!==void 0)throw new Error(`attribute '${e.attribute}' already exists in ${e.schema}.${e.table}`);dm.createDBI(i,e.attribute,e.dup_sort,e.is_hash_attribute);let o=await dm.openEnvironment($$(),k$.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME),{written_hashes:c,skipped_hashes:u}=await V$.insertRecords(o,fm.hash_attribute,dN,[s]);return z$(j$,c,{records:[s]},u)}catch(i){throw i}}a(X$,"lmdbCreateAttribute")});var hm=g((gae,hN)=>{var{hdb_table:Z$,hdb_database:EN}=kn(),e1=je(),Em=require("joi"),t1={undefined:"undefined",null:"null"},r1=a((e,t)=>{let r=Object.keys(e),n=r.length,s;for(let i=0;i<n;i++){let o=r[i];(!o||o.length===0||t1[o]!==void 0)&&(s===void 0?s=`Invalid attribute name: '${o}'`:s+=`. Invalid attribute name: '${o}'`)}return s?t.message(s):e},"custom_records_val"),n1=Em.object({database:EN,schema:EN,table:Z$,records:Em.array().items(Em.object().custom(r1)).required()});hN.exports=function(e){return e1.validateBySchema(e,n1)}});var bc=g((Oae,pN)=>{"use strict";var Es=J(),mN=Y(),Aae=hm(),{getDatabases:s1}=(be(),te(qe)),{ClientError:Pi}=ee();pN.exports=i1;function i1(e){if(Es.isEmpty(e))throw new Pi("invalid update parameters defined.");if(Es.isEmptyOrZeroLength(e.schema))throw new Pi("invalid schema specified.");if(Es.isEmptyOrZeroLength(e.table))throw new Pi("invalid table specified.");if(!Array.isArray(e.records))throw new Pi("records must be an array");let t=s1()[e.schema]?.[e.table];if(Es.isEmpty(t))throw new Pi(`could not retrieve schema:${e.schema} and table ${e.table}`);let r=t.primaryKey,n=new Set,s={},i=!1;return e.operation==="update"&&(i=!0),e.records.forEach(o=>{if(i&&Es.isEmptyOrZeroLength(o[r]))throw mN.error("a valid hash attribute must be provided with update record:",o),new Pi("a valid hash attribute must be provided with update record, check log for more info");if(!Es.isEmptyOrZeroLength(o[r])&&(o[r]==="null"||o[r]==="undefined"))throw mN.error(`a valid hash value must be provided with ${e.operation} record:`,o),new Pi(`Invalid hash value: '${o[r]}' is not a valid hash attribute value, check log for more info`);!Es.isEmpty(o[r])&&o[r]!==""&&n.has(Es.autoCast(o[r]))&&(o.skip=!0),n.add(Es.autoCast(o[r]));for(let c in o)s[c]=1}),s[r]=1,{schema_table:t,hashes:Array.from(n),attributes:Object.keys(s)}}a(i1,"insertUpdateValidate")});var Nc=g((Nae,SN)=>{"use strict";var o1=M().OPERATIONS_ENUM,mm=class{static{a(this,"InsertObject")}constructor(t,r,n,s,i=void 0){this.operation=o1.INSERT,this.schema=t,this.table=r,this.hash_attribute=n,this.records=s,this.__origin=i}};SN.exports=mm});var Cc=g((Iae,TN)=>{"use strict";var wae=Nc(),h_=M(),Sm=J(),pm=Y(),a1=require("uuid"),{handleHDBError:yc,hdb_errors:c1}=ee(),{HDB_ERROR_MSGS:wc,HTTP_STATUS_CODES:Ic}=c1;TN.exports=u1;function u1(e,t,r){for(let s=0;s<t.length;s++)l1(t[s]);let{records:n}=e;for(let s=0;s<n.length;s++){let i=n[s];_1(i,r,e.operation)}}a(u1,"processRows");function l1(e){if(Buffer.byteLength(String(e))>h_.INSERT_MODULE_ENUM.MAX_CHARACTER_SIZE)throw yc(new Error,wc.ATTR_NAME_LENGTH_ERR(e),Ic.BAD_REQUEST,void 0,void 0,!0);if(Sm.isEmptyOrZeroLength(e)||Sm.isEmpty(e.trim()))throw yc(new Error,wc.ATTR_NAME_NULLISH_ERR,Ic.BAD_REQUEST,void 0,void 0,!0)}a(l1,"validateAttribute");function _1(e,t,r){if(!e.hasOwnProperty(t)||Sm.isEmptyOrZeroLength(e[t])){if(r===h_.OPERATIONS_ENUM.INSERT||r===h_.OPERATIONS_ENUM.UPSERT){e[t]=a1.v4();return}throw pm.error("Update transaction aborted due to record with no hash value:",e),yc(new Error,wc.RECORD_MISSING_HASH_ERR,Ic.BAD_REQUEST,void 0,void 0,!0)}if(Buffer.byteLength(String(e[t]))>h_.INSERT_MODULE_ENUM.MAX_CHARACTER_SIZE)throw pm.error(e),yc(new Error,wc.HASH_VAL_LENGTH_ERR,Ic.BAD_REQUEST,void 0,void 0,!0);if(isNaN(e[t])&&e[t].includes("/"))throw pm.error(e),yc(new Error,wc.INVALID_FORWARD_SLASH_IN_HASH_ERR,Ic.BAD_REQUEST,void 0,void 0,!0)}a(_1,"validateHash")});var RN=g((Dae,gN)=>{"use strict";var Tm=class{static{a(this,"ITCEventObject")}constructor(t,r){this.type=t,this.message=r}};gN.exports=Tm});var bN=g((Mae,ON)=>{"use strict";var gm=$e(),d1=Y(),AN=Or().LMDB_ERRORS_ENUM;ON.exports=f1;async function f1(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 gm.closeEnvironment(global.lmdb_map[o])}catch(c){if(c.message!==AN.ENV_REQUIRED)throw c}}break;case"drop_table":let n=`${e.schema}.${e.table}`,s=`txn.${n}`;try{await gm.closeEnvironment(global.lmdb_map[n]),await gm.closeEnvironment(global.lmdb_map[s])}catch(i){if(i.message!==AN.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){d1.error(t)}}a(f1,"cleanLMDBMap")});var hs=g((Pae,IN)=>{"use strict";var Dc=require("crypto"),E1=Z(),{CONFIG_PARAMS:h1}=M(),yN="aes-256-cbc",m1=32,p1=16,Rm=64,wN=32,S1=Rm+wN,NN=new Map;IN.exports={encrypt:T1,decrypt:g1,createNatsTableStreamName:R1};function T1(e){let t=Dc.randomBytes(m1),r=Dc.randomBytes(p1),n=Dc.createCipheriv(yN,Buffer.from(t),r),s=n.update(e);s=Buffer.concat([s,n.final()]);let i=t.toString("hex"),o=r.toString("hex"),c=s.toString("hex");return i+o+c}a(T1,"encrypt");function g1(e){let t=e.substr(0,Rm),r=e.substr(Rm,wN),n=e.substr(S1,e.length),s=Buffer.from(r,"hex"),i=Buffer.from(n,"hex"),o=Dc.createDecipheriv(yN,Buffer.from(t,"hex"),s),c=o.update(i);return c=Buffer.concat([c,o.final()]),c.toString()}a(g1,"decrypt");function R1(e,t){let r=E1.get(h1.CLUSTERING_DATABASELEVEL)?e:`${e}.${t}`,n=NN.get(r);return n||(n=Dc.createHash("md5").update(r).digest("hex"),NN.set(r,n)),n}a(R1,"createNatsTableStreamName")});var vi=g((Hae,DN)=>{"use strict";var Bae=Xr(),m_=Y(),CN=d_(),A1=hs(),p_=J(),{handleHDBError:S_,hdb_errors:O1}=ee(),{HDB_ERROR_MSGS:T_,HTTP_STATUS_CODES:Am}=O1,b1=Z();b1.initSync();var{getDatabases:Om}=(be(),te(qe));DN.exports={describeAll:N1,describeTable:g_,describeSchema:y1};async function N1(e){try{let t=p_.isEmptyOrZeroLength(e),r,n;t||(r=e.hdb_user.role.permission,n=r.super_user||r.cluster_user);let s=Om(),i={},o={},c=[],u=e?.exact_count;for(let l in s){i[l]=!0,!t&&!n&&(o[l]=e.hdb_user.role.permission[l].describe);let d=s[l];for(let f in d)try{let E;if(t||n)E=await g_({schema:l,table:f,exact_count:u});else if(r&&r[l].describe&&r[l].tables[f].describe){let h=r[l].tables[f].attribute_permissions;E=await g_({schema:l,table:f,exact_count:u},h)}E&&c.push(E)}catch(E){m_.error(E)}}let _={};for(let l in c)t||n?(_[c[l].schema]==null&&(_[c[l].schema]={}),_[c[l].schema][c[l].name]=c[l],i[c[l].schema]&&delete i[c[l].schema]):o[c[l].schema]&&(_[c[l].schema]==null&&(_[c[l].schema]={}),_[c[l].schema][c[l].name]=c[l],i[c[l].schema]&&delete i[c[l].schema]);for(let l in i)t||n?_[l]={}:o[l]&&(_[l]={});return _}catch(t){return m_.error("Got an error in describeAll"),m_.error(t),S_(new Error,T_.DESCRIBE_ALL_ERR)}}a(N1,"describeAll");async function g_(e,t){p_.transformReq(e);let{schema:r,table:n}=e;r=r?.toString(),n=n?.toString();let s=t;e.hdb_user&&!e.hdb_user.role.permission.super_user&&(s=e.hdb_user.role.permission[r].tables[n].attribute_permissions);let i=CN.describe_table(e);if(i)throw i;let c=Om()[r];if(!c)throw S_(new Error,T_.SCHEMA_NOT_FOUND(e.schema),Am.NOT_FOUND);let u=c[n];if(!u)throw S_(new Error,T_.TABLE_NOT_FOUND(e.schema,e.table),Am.NOT_FOUND);function _(f){l.push(Object.assign({},{attribute:f.attribute,type:f.type,elements:f.elements?.type,indexed:f.indexed,is_primary_key:f.isPrimaryKey,assigned_created_time:f.assignCreatedTime,assigned_updated_time:f.assignUpdatedTime,nullable:f.nullable,properties:f.properties?f.properties.map(E=>({type:E.type,name:E.name})):void 0}))}a(_,"pushAtt");let l=[];if(s){let f={};s.forEach(E=>{E.describe&&(f[E.attribute_name]=!0)}),u.attributes.forEach(E=>{f[E.name]&&_(E)})}else u.attributes?.forEach(f=>_(f));let d={schema:r,name:u.tableName,hash_attribute:u.attributes.find(f=>f.isPrimaryKey||f.is_hash_attribute)?.name,audit:u.audit,schema_defined:u.schemaDefined,attributes:l};d.clustering_stream_name=A1.createNatsTableStreamName(d.schema,d.name);try{let f=u.getRecordCount({exactCount:e.exact_count==="true"});d.record_count=f.recordCount,d.estimated_record_range=f.estimatedRange;let E=u.auditStore;if(E)for(let h of E.getKeys({reverse:!0,limit:1}))d.last_updated_record=h[0];if(!d.last_updated_record&&u.indices.__updatedtime__)for(let h of u.indices.__updatedtime__.getKeys({reverse:!0,limit:1}))d.last_updated_record=h}catch(f){m_.warn(`unable to stat table dbi due to ${f}`)}return d}a(g_,"descTable");async function y1(e){p_.transformReq(e);let t=CN.schema_object(e);if(t)throw t;let r;e.hdb_user&&!e.hdb_user.role.permission.super_user&&(r=e.hdb_user.role.permission[e.schema]);let n=e.schema.toString(),i=Om()[n];if(!i)throw S_(new Error,T_.SCHEMA_NOT_FOUND(e.schema),Am.NOT_FOUND);let o={};for(let c in i){let u;if(r&&r.tables[c]&&(u=r.tables[c]),p_.isEmpty(u)||u.describe){let _=await g_({schema:e.schema,table:c,exact_count:e.exact_count},u?u.attribute_permissions:null);_&&(o[_.name]=_)}}return o}a(y1,"describeSchema")});var ms=g((Gae,vN)=>{var w1=Ui(),{callbackify:MN,promisify:I1}=require("util"),{getDatabases:UN}=(be(),te(qe));vN.exports={setSchemaDataToGlobal:LN,getTableSchema:C1,getSystemSchema:D1,setSchemaDataToGlobalAsync:I1(LN)};var PN=vi(),qae=MN(PN.describeAll),Fae=MN(PN.describeTable);function LN(e){global.hdb_schema=UN(),e&&e()}a(LN,"setSchemaDataToGlobal");function C1(e,t,r){let n=UN()[e];if(!n)return r(`schema ${e} does not exist`);let s=n[t];return s?r(null,{schema:e,name:t,hash_attribute:s.primaryKey}):r(`table ${e}.${t} does not exist`)}a(C1,"getTableSchema");function D1(){return w1}a(D1,"getSystemSchema")});var Zr=g((Vae,qN)=>{"use strict";var A_=hm(),Ht=J(),L1=require("util"),O_=On(),M1=ms(),BN=Y(),{handleHDBError:Bi,hdb_errors:U1}=ee(),{HTTP_STATUS_CODES:Hi}=U1,P1=L1.promisify(M1.getTableSchema),v1="updated",HN="inserted",xN="upserted";qN.exports={insert:H1,update:x1,upsert:q1,validation:B1,flush:F1};async function B1(e){if(Ht.isEmpty(e))throw new Error("invalid update parameters defined.");if(Ht.isEmptyOrZeroLength(e.schema))throw new Error("invalid database specified.");if(Ht.isEmptyOrZeroLength(e.table))throw new Error("invalid table specified.");let t=await P1(e.schema,e.table),r=A_(e);if(r)throw r;if(!Array.isArray(e.records))throw new Error("records must be an array");let n=t.hash_attribute,s=new Set,i={},o=!1;return e.operation==="update"&&(o=!0),e.records.forEach(c=>{if(o&&Ht.isEmptyOrZeroLength(c[n]))throw BN.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(!Ht.isEmptyOrZeroLength(c[n])&&(c[n]==="null"||c[n]==="undefined"))throw BN.error(`a valid hash value must be provided with ${e.operation} record:`,c),new Error(`"${c[n]}" is not a valid hash attribute value`);!Ht.isEmpty(c[n])&&c[n]!==""&&s.has(Ht.autoCast(c[n]))&&(c.skip=!0),s.add(Ht.autoCast(c[n]));for(let u in c)i[u]=1}),i[n]=1,{schema_table:t,hashes:Array.from(s),attributes:Object.keys(i)}}a(B1,"validation");async function H1(e){if(e.operation!=="insert")throw new Error("invalid operation, must be insert");let t=A_(e);if(t)throw Bi(new Error,t.message,Hi.BAD_REQUEST);Ht.transformReq(e);let r=Ht.checkSchemaTableExist(e.schema,e.table);if(r)throw Bi(new Error,r,Hi.BAD_REQUEST);let n=await O_.createRecords(e);return R_(HN,n.written_hashes,e,n.skipped_hashes,n.new_attributes,n.txn_time)}a(H1,"insertData");async function x1(e){if(e.operation!=="update")throw new Error("invalid operation, must be update");let t=A_(e);if(t)throw Bi(new Error,t.message,Hi.BAD_REQUEST);Ht.transformReq(e);let r=Ht.checkSchemaTableExist(e.schema,e.table);if(r)throw Bi(new Error,r,Hi.BAD_REQUEST);let n=await O_.updateRecords(e);return Ht.isEmpty(n.existing_rows)?R_(v1,n.written_hashes,e,n.skipped_hashes,n.new_attributes,n.txn_time):R_(n.update_action,[],e,n.hashes,void 0,n.txn_time)}a(x1,"updateData");async function q1(e){if(e.operation!=="upsert")throw Bi(new Error,"invalid operation, must be upsert",Hi.INTERNAL_SERVER_ERROR);let t=A_(e);if(t)throw Bi(new Error,t.message,Hi.BAD_REQUEST);Ht.transformReq(e);let r=Ht.checkSchemaTableExist(e.schema,e.table);if(r)throw Bi(new Error,r,Hi.BAD_REQUEST);let n=await O_.upsertRecords(e);return R_(xN,n.written_hashes,e,[],n.new_attributes,n.txn_time)}a(q1,"upsertData");function R_(e,t,r,n,s,i){let o={message:`${e} ${t.length} of ${t.length+n.length} records`,new_attributes:s,txn_time:i};return e===HN?(o.inserted_hashes=t,o.skipped_hashes=n,o):e===xN?(o.upserted_hashes=t,o):(o.update_hashes=t,o.skipped_hashes=n,o)}a(R_,"returnObject");function F1(e){return Ht.transformReq(e),O_.flush(e.schema,e.table)}a(F1,"flush")});var Nm=g((Yae,kN)=>{var G1=je(),bm=require("joi"),{hdb_table:k1,hdb_database:FN}=kn(),GN={schema:FN,database:FN,table:k1},V1={date:bm.date().iso().required()},$1={timestamp:bm.date().timestamp().required().messages({"date.format":"'timestamp' is invalid"})};kN.exports=function(e,t){let r=t==="timestamp"?{...GN,...$1}:{...GN,...V1},n=bm.object(r);return G1.validateBySchema(e,n)}});var YN=g((Kae,$N)=>{var Y1=je(),ym=require("joi"),{hdb_table:K1,hdb_database:VN}=kn(),W1=ym.object({schema:VN,database:VN,table:K1,hash_values:ym.array().required(),ids:ym.array()});$N.exports=function(e){return Y1.validateBySchema(e,W1)}});var WN=g((Wae,KN)=>{"use strict";var wm=class{static{a(this,"InsertObject")}constructor(t,r,n,s,i){this.operation=t,this.schema=r,this.table=n,this.hash_attribute=s,this.records=i}},Im=class{static{a(this,"NoSQLSeachObject")}constructor(t,r,n,s,i,o){this.schema=t,this.table=r,this.search_attribute=n,this.hash_attribute=s,this.get_attributes=i,this.search_value=o}},Cm=class{static{a(this,"DeleteResponseObject")}constructor(){this.message=void 0,this.deleted_hashes=[],this.skipped_hashes=[]}};KN.exports={InsertObject:wm,NoSQLSeachObject:Im,DeleteResponseObject:Cm}});var Fi=g((zae,XN)=>{"use strict";var zN=Nm(),Q1=YN(),xi=J(),QN=require("moment"),JN=Y(),{promisify:z1,callbackify:J1}=require("util"),qi=M(),j1=ms(),Dm=z1(j1.getTableSchema),Lm=On(),{DeleteResponseObject:X1}=WN(),{handleHDBError:zs,hdb_errors:Z1}=ee(),{HDB_ERROR_MSGS:b_,HTTP_STATUS_CODES:Js}=Z1,eY="records successfully deleted",tY=J1(jN);XN.exports={delete:tY,deleteRecord:jN,deleteFilesBefore:rY,deleteAuditLogsBefore:nY};async function rY(e){let t=zN(e,"date");if(t)throw zs(t,t.message,Js.BAD_REQUEST,void 0,void 0,!0);if(xi.transformReq(e),!QN(e.date,QN.ISO_8601).isValid())throw zs(new Error,b_.INVALID_DATE,Js.BAD_REQUEST,qi.LOG_LEVELS.ERROR,b_.INVALID_DATE,!0);let n=xi.checkSchemaTableExist(e.schema,e.table);if(n)throw zs(new Error,n,Js.NOT_FOUND,qi.LOG_LEVELS.ERROR,n,!0);let s=await Lm.deleteRecordsBefore(e);if(await Dm(e.schema,e.table),JN.info(`Finished deleting files before ${e.date}`),s&&s.message)return s.message}a(rY,"deleteFilesBefore");async function nY(e){let t=zN(e,"timestamp");if(t)throw zs(t,t.message,Js.BAD_REQUEST,void 0,void 0,!0);if(xi.transformReq(e),isNaN(e.timestamp))throw zs(new Error,b_.INVALID_VALUE("Timestamp"),Js.BAD_REQUEST,qi.LOG_LEVELS.ERROR,b_.INVALID_VALUE("Timestamp"),!0);let r=xi.checkSchemaTableExist(e.schema,e.table);if(r)throw zs(new Error,r,Js.NOT_FOUND,qi.LOG_LEVELS.ERROR,r,!0);let n=await Lm.deleteAuditLogsBefore(e);return await Dm(e.schema,e.table),JN.info(`Finished deleting audit logs before ${e.timestamp}`),n}a(nY,"deleteAuditLogsBefore");async function jN(e){e.ids&&(e.hash_values=e.ids);let t=Q1(e);if(t)throw zs(t,t.message,Js.BAD_REQUEST,void 0,void 0,!0);xi.transformReq(e);let r=xi.checkSchemaTableExist(e.schema,e.table);if(r)throw zs(new Error,r,Js.NOT_FOUND,qi.LOG_LEVELS.ERROR,r,!0);try{await Dm(e.schema,e.table);let n=await Lm.deleteRecords(e);return xi.isEmptyOrZeroLength(n.message)&&(n.message=`${n.deleted_hashes.length} of ${e.hash_values.length} ${eY}`),n}catch(n){if(n.message===qi.SEARCH_NOT_FOUND_MESSAGE){let s=new X1;return s.message=qi.SEARCH_NOT_FOUND_MESSAGE,s.skipped_hashes=e.hash_values.length,s.deleted_hashes=0,s}throw n}}a(jN,"deleteRecord")});var N_=g((jae,ty)=>{var sY=require("crypto"),ZN=9;function iY(e){let t=aY(ZN),r=ey(e+t);return t+r}a(iY,"createHash");function oY(e,t){let r=e?.substr(0,ZN),n=r+ey(t+r);return e===n}a(oY,"validateHash");function aY(e){let t="0123456789abcdefghijklmnopqurstuvwxyzABCDEFGHIJKLMNOPQURSTUVWXYZ",r=t.length,n="";for(let s=0;s<e;s++){let i=Math.floor(Math.random()*r);n+=t[i]}return n}a(aY,"generateSalt");function ey(e){return sY.createHash("md5").update(e).digest("hex")}a(ey,"md5");ty.exports={hash:iY,validate:oY}});var ny=g((Zae,ry)=>{var Mm=je(),$t={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 cY(e){return $t.password.presence=!0,$t.username.presence=!0,$t.role.presence=!0,$t.active.presence=!0,Mm.validateObject(e,$t)}a(cY,"addUserValidation");function uY(e){return $t.password.presence=!1,$t.username.presence=!0,$t.role.presence=!1,$t.active.presence=!1,Mm.validateObject(e,$t)}a(uY,"alterUserValidation");function lY(e){return $t.password.presence=!1,$t.username.presence=!0,$t.role.presence=!1,$t.active.presence=!1,Mm.validateObject(e,$t)}a(lY,"dropUserValidation");ry.exports={addUserValidation:cY,alterUserValidation:uY,dropUserValidation:lY}});var tt=g((rce,iy)=>{"use strict";var{platform:tce}=require("os"),_Y="nats-server.zip",Um="nats-server",dY=process.platform==="win32"?`${Um}.exe`:Um,Pm="HDB",fY=/^[^\s.,*>]+$/,sy="__request__",EY=a(e=>`${e}.${sy}`,"REQUEST_SUBJECT"),hY={NATS_MSG_ID:"Nats-Msg-Id",ORIGIN:"origin",TRANSACTED_NODES:"transacted_nodes"},mY={HUB_SERVER:"hub.json",LEAF_SERVER:"leaf.json"},pY={HUB:"hub.pid",LEAF:"leaf.pid"},SY={HUB:"-hub",LEAF:"-leaf",ADMIN:"-admin"},TY={stream_name:"__HARPERDB_WORK_QUEUE__",durable_name:"HDB_WORK_QUEUE",deliver_group:Pm,deliver_subject:"__HDB__.WORKQUEUE"},gY={stream_name:"__HARPERDB_SCHEMA_QUEUE__",durable_name:"HDB_SCHEMA_QUEUE",deliver_group:Pm,deliver_subject:"HDB.SCHEMAQUEUE"},RY={stream_name:"__HARPERDB_USER_QUEUE__",durable_name:"HDB_USER_QUEUE",deliver_group:Pm,deliver_subject:"HDB.USERQUEUE"},AY={SUCCESS:"success",ERROR:"error"},OY={OPEN:"open",CLOSED:"closed",NO_RESPONDERS:"NoResponders",TIMEOUT:"Timeout"},bY={TXN:"txn",MSGID:"msgid"},qo={ERR:"error",WRN:"warn",INF:"info",DBG:"debug",TRC:"trace"},NY={[qo.ERR]:1,[qo.WRN]:2,[qo.INF]:3,[qo.DBG]:4,[qo.TRC]:5},yY={debug:"-D",trace:"-DVV"};iy.exports={NATS_SERVER_ZIP:_Y,NATS_SERVER_NAME:Um,NATS_BINARY_NAME:dY,PID_FILES:pY,NATS_CONFIG_FILES:mY,SERVER_SUFFIX:SY,WORK_QUEUE_CONSUMER_NAMES:TY,SCHEMA_QUEUE_CONSUMER_NAMES:gY,USER_QUEUE_CONSUMER_NAMES:RY,NATS_TERM_CONSTRAINTS_RX:fY,REQUEST_SUFFIX:sy,UPDATE_REMOTE_RESPONSE_STATUSES:AY,CLUSTER_STATUS_STATUSES:OY,REQUEST_SUBJECT:EY,SUBJECT_PREFIXES:bY,MSG_HEADERS:hY,LOG_LEVELS:qo,LOG_LEVEL_FLAGS:yY,LOG_LEVEL_HIERARCHY:NY}});var ay=g((sce,oy)=>{"use strict";var y_=M(),w_=class{static{a(this,"BaseLicense")}constructor(t=0,r=y_.RAM_ALLOCATION_ENUM.DEFAULT,n=y_.LICENSE_VALUES.VERSION_DEFAULT,s){this.exp_date=t,this.ram_allocation=r,this.version=n,this.fingerprint=s}},vm=class extends w_{static{a(this,"ExtendedLicense")}constructor(t=0,r=y_.RAM_ALLOCATION_ENUM.DEFAULT,n=y_.LICENSE_VALUES.VERSION_DEFAULT,s,i=!1){super(t,r,n,s),this.enterprise=i}};oy.exports={BaseLicense:w_,ExtendedLicense:vm}});var Gi=g((oce,fy)=>{"use strict";var Go=require("fs-extra"),uy=N_(),ly=require("crypto"),wY=require("moment"),IY=require("uuid").v4,Yt=Y(),Hm=require("path"),CY=J(),js=M(),{totalmem:cy}=require("os"),DY=ay().ExtendedLicense,Fo="invalid license key format",LY="061183",MY="mofi25",UY="aes-256-cbc",PY=16,vY=32,_y=Z();_y.initSync();var Bm;fy.exports={validateLicense:dy,generateFingerPrint:HY,licenseSearch:Fm,getLicense:FY,checkMemoryLimit:GY};function xm(){return Hm.join(_y.getHdbBasePath(),js.LICENSE_KEY_DIR_NAME,js.LICENSE_FILE_NAME)}a(xm,"getLicenseDirPath");function BY(){let e=xm();return Hm.join(e,js.LICENSE_FILE_NAME)}a(BY,"getLicenseFilePath");function qm(){let e=xm();return Hm.join(e,js.REG_KEY_FILE_NAME)}a(qm,"getFingerPrintFilePath");async function HY(){let e=qm();try{return await Go.readFile(e,"utf8")}catch(t){if(t.code==="ENOENT")return await xY();throw Yt.error(`Error writing fingerprint file to ${e}`),Yt.error(t),new Error("There was an error generating the fingerprint")}}a(HY,"generateFingerPrint");async function xY(){let e=IY(),t=uy.hash(e),r=qm();try{await Go.mkdirp(xm()),await Go.writeFile(r,t)}catch(n){if(n.code==="EEXIST")return t;throw Yt.error(`Error writing fingerprint file to ${r}`),Yt.error(n),new Error("There was an error generating the fingerprint")}return t}a(xY,"writeFingerprint");function dy(e,t){let r={valid_license:!1,valid_date:!1,valid_machine:!1,exp_date:null,ram_allocation:js.RAM_ALLOCATION_ENUM.DEFAULT,version:js.LICENSE_VALUES.VERSION_DEFAULT};if(!e)return Yt.error("empty license key passed to validate."),r;let n=qm(),s=!1;try{s=Go.statSync(n)}catch(i){Yt.error(i)}if(s){let i;try{i=Go.readFileSync(n,"utf8")}catch{Yt.error("error validating this machine in the license"),r.valid_machine=!1;return}let o=e.split(MY),c=o[1];c=Buffer.concat([Buffer.from(c)],PY);let u=Buffer.concat([Buffer.from(i)],vY),_=ly.createDecipheriv(UY,u,c);r.valid_date=!0,r.valid_license=!0,r.valid_machine=!0;let l=null;try{l=_.update(o[0],"hex","utf8"),l.trim(),l+=_.final("utf8")}catch{let E=qY(o[0],i);if(E)l=E;else throw r.valid_license=!1,r.valid_machine=!1,console.error(Fo),Yt.error(Fo),new Error(Fo)}let d;if(isNaN(l))try{d=JSON.parse(l),r.version=d.version,r.exp_date=d.exp_date,isNaN(r.exp_date)&&(r.exp_date=new Date(r.exp_date).getTime()),d.ram_allocation&&(r.ram_allocation=d.ram_allocation)}catch{throw console.error(Fo),Yt.error(Fo),new Error(Fo)}else r.exp_date=l;r.exp_date<wY().valueOf()&&(r.valid_date=!1),uy.validate(o[1],`${LY}${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||Yt.error("Invalid licence"),r}a(dy,"validateLicense");function qY(e,t){try{let r=ly.createDecipher("aes192",t),n=r.update(e,"hex","utf8");return n.trim(),n+=r.final("utf8"),n}catch{Yt.warn("Check old license failed")}}a(qY,"checkOldLicense");function Fm(){let e=new DY,t=[];try{t=Go.readFileSync(BY(),"utf-8").split(js.NEW_LINE)}catch(r){r.code==="ENOENT"?Yt.info("no license file found"):Yt.error(`could not search for licenses due to: '${r.message}`)}for(let r=0;r<t.length;++r){let n=t[r];try{if(CY.isEmptyOrZeroLength(n))continue;let s=JSON.parse(n),i=dy(s.license_key,s.company);i.valid_machine===!0&&i.valid_date===!0&&i.valid_machine===!0&&(e.exp_date=i.exp_date>e.exp_date?i.exp_date:e.exp_date,e.ram_allocation=i.ram_allocation,e.enterprise=!0)}catch(s){Yt.error("There was an error parsing the license string."),Yt.error(s),e.ram_allocation=js.RAM_ALLOCATION_ENUM.DEFAULT,e.enterprise=!1}}return Bm=e,e}a(Fm,"licenseSearch");async function FY(){return Bm||await Fm(),Bm}a(FY,"getLicense");function GY(){let e=Fm().ram_allocation,t=process.constrainedMemory?.()||cy();if(t=Math.round(Math.min(t,cy())/2**20),t>e)return`This server has more memory (${t}MB) than HarperDB is licensed for (${e}MB), this should only be used for educational and development purposes.`}a(GY,"checkMemoryLimit")});var Mr=g((_ce,Cy)=>{"use strict";var py="username is required",Sy="nothing to update, must supply active, role or password to update",Ty="password cannot be an empty string",gy="If role is specified, it cannot be empty.",Ry="active must be true or false";Cy.exports={addUser:JY,alterUser:jY,dropUser:ZY,getSuperUser:nK,userInfo:eK,listUsers:C_,listUsersExternal:tK,setUsersToGlobal:Vo,findAndValidateUser:wy,getClusterUser:sK,USERNAME_REQUIRED:py,ALTERUSER_NOTHING_TO_UPDATE:Sy,EMPTY_PASSWORD:Ty,EMPTY_ROLE:gy,ACTIVE_BOOLEAN:Ry};var Ay=Zr(),kY=Fi(),Vm=N_(),Oy=ny(),by=Xr(),$m=ps(),Lr=J(),Ny=require("validate.js"),Ae=Y(),{promisify:VY}=require("util"),Ym=hs(),Ey=M(),hy=tt(),$Y=wr(),cce=Z(),uce=Gi(),YY=Ui(),{table:lce}=(be(),te(qe)),{handleHDBError:$n,hdb_errors:KY}=ee(),{HTTP_STATUS_CODES:Yn,AUTHENTICATION_ERROR_MSGS:Gm,HDB_ERROR_MSGS:ko}=KY,{UserEventMsg:Km}=bn(),km=require("lodash"),{server:Wm}=(Zt(),te(yi)),WY=Y();Wm.getUser=(e,t)=>wy(e,t,t!=null);var yy={username:!0,active:!0,role:!0,password:!0},my=new Map,I_=by.searchByValue,QY=by.searchByHash,zY=VY(kY.delete);async function JY(e){let t=Ny.cleanAttributes(e,yy),r=Oy.addUserValidation(t);if(r)throw $n(new Error,r.message,Yn.BAD_REQUEST,void 0,void 0,!0);let n={schema:"system",table:"hdb_role",search_attribute:"role",search_value:t.role,get_attributes:["id","permission","role"]},s;try{s=await I_(n),s=s&&Array.from(s)}catch(u){throw Ae.error("There was an error searching for a role in add user"),Ae.error(u),u}if(!s||s.length<1)throw $n(new Error,ko.ROLE_NAME_NOT_FOUND(t.role),Yn.NOT_FOUND,void 0,void 0,!0);if(s.length>1)throw $n(new Error,ko.DUP_ROLES_FOUND(t.role),Yn.CONFLICT,void 0,void 0,!0);s[0].permission.cluster_user===!0&&(t.hash=Ym.encrypt(t.password)),t.password=Vm.hash(t.password),t.role=s[0].id;let i={operation:"insert",schema:"system",table:"hdb_user",records:[t]},o;try{o=await Ay.insert(i)}catch(u){throw Ae.error("There was an error searching for a user."),Ae.error(u),u}Ae.debug(o);try{await Vo()}catch(u){throw Ae.error("Got an error setting users to global"),Ae.error(u),u}if(o.skipped_hashes.length===1)throw $n(new Error,ko.USER_ALREADY_EXISTS(t.username),Yn.CONFLICT,void 0,void 0,!0);let c=Object.assign({},t);return c.role=s[0],$m.signalUserChange(new Km(process.pid)),`${c.username} successfully added`}a(JY,"addUser");async function jY(e){let t=Ny.cleanAttributes(e,yy);if(Lr.isEmptyOrZeroLength(t.username))throw new Error(py);if(Lr.isEmptyOrZeroLength(t.password)&&Lr.isEmptyOrZeroLength(t.role)&&Lr.isEmptyOrZeroLength(t.active))throw new Error(Sy);if(!Lr.isEmpty(t.password)&&Lr.isEmptyOrZeroLength(t.password.trim()))throw new Error(Ty);if(!Lr.isEmpty(t.active)&&!Lr.isBoolean(t.active))throw new Error(Ry);let r=XY(t.username);if(!Lr.isEmpty(t.password)&&!Lr.isEmptyOrZeroLength(t.password.trim())&&(r&&(t.hash=Ym.encrypt(t.password)),t.password=Vm.hash(t.password)),t.role==="")throw new Error(gy);if(t.role){let i={schema:"system",table:"hdb_role",search_attribute:"role",search_value:t.role,get_attributes:["*"]},o;try{o=Array.from(await I_(i)||[])}catch(c){throw Ae.error("Got an error searching for a role."),Ae.error(c),c}if(!o||o.length===0){let c=ko.ALTER_USER_ROLE_NOT_FOUND(t.role);throw Ae.error(c),$n(new Error,c,Yn.NOT_FOUND,void 0,void 0,!0)}if(o.length>1){let c=ko.ALTER_USER_DUP_ROLES(t.role);throw Ae.error(c),$n(new Error,c,Yn.CONFLICT,void 0,void 0,!0)}t.role=o[0].id}let n={operation:"update",schema:"system",table:"hdb_user",records:[t]},s;try{s=await Ay.update(n)}catch(i){throw Ae.error("Error during update."),Ae.error(i),i}try{await Vo()}catch(i){throw Ae.error("Got an error setting users to global"),Ae.error(i),i}return $m.signalUserChange(new Km(process.pid)),s}a(jY,"alterUser");function XY(e){let t=!1,r=global.hdb_users.get(e);return r&&r.role.permission.cluster_user===!0&&(t=!0),t}a(XY,"isClusterUser");async function ZY(e){try{let t=Oy.dropUserValidation(e);if(t)throw new Error(t);let r={table:"hdb_user",schema:"system",hash_values:[e.username]};if(Lr.isEmpty(global.hdb_users.get(e.username)))throw $n(new Error,ko.USER_NOT_EXIST(e.username),Yn.NOT_FOUND,void 0,void 0,!0);let n;try{n=await zY(r)}catch(s){throw Ae.error("Got an error deleting a user."),Ae.error(s),s}Ae.debug(n);try{await Vo()}catch(s){throw Ae.error("Got an error setting users to global."),Ae.error(s),s}return $m.signalUserChange(new Km(process.pid)),`${e.username} successfully deleted`}catch(t){throw t}}a(ZY,"dropUser");async function eK(e){let t={};try{if(!e||!e.hdb_user)return"There was no user info in the body";t=km.cloneDeep(e.hdb_user);let r={schema:"system",table:"hdb_role",hash_values:[t.role.id],get_attributes:["*"]},n;try{n=await QY(r)}catch(s){throw Ae.error("Got an error searching for a role."),Ae.error(s),s}t.role=n[0],delete t.password,delete t.refresh_token,delete t.hash}catch(r){throw Ae.error(r),r}return t}a(eK,"userInfo");async function tK(){let e;try{e=await C_()}catch(t){throw Ae.error("Got an error listing users."),Ae.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(tK,"listUsersExternal");async function C_(){try{let e={schema:"system",table:"hdb_role",search_value:"*",search_attribute:"role",get_attributes:["*"]},t;try{t=await I_(e)}catch(o){throw Ae.error("Got an error searching for roles."),Ae.error(o),o}let r={};for(let o of t)r[o.id]=km.cloneDeep(o);if(Object.keys(r).length===0)return null;let n={schema:"system",table:"hdb_user",search_value:"*",search_attribute:"username",get_attributes:["*"]},s;try{s=await I_(n)}catch(o){throw Ae.error("Got an error searching for users."),Ae.error(o),o}let i=new Map;for(let o of s)o=km.cloneDeep(o),o.role=r[o.role],rK(o.role),i.set(o.username,o);return i}catch(e){throw Ae.error("got an error listing users"),Ae.error(e),Lr.errorizeMessage(e)}return null}a(C_,"listUsers");function rK(e){try{if(!e){Ae.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(YY)){let r={read:!!e.permission.super_user,insert:!1,update:!1,delete:!1,attribute_permissions:[]};e.permission.system.tables[t]=r}}catch(t){Ae.error("Got an error trying to set system permissions."),Ae.error(t)}}a(rK,"appendSystemTablesToRole");async function Vo(){try{let e=await C_();global.hdb_users=e}catch(e){throw Ae.error(e),e}}a(Vo,"setUsersToGlobal");async function wy(e,t,r=!0){global.hdb_users||await Vo();let n=global.hdb_users.get(e);if(!n){if(!r)return{username:e};throw $n(new Error,Gm.GENERIC_AUTH_FAIL,Yn.UNAUTHORIZED,void 0,void 0,!0)}if(n&&!n.active)throw $n(new Error,Gm.USER_INACTIVE,Yn.UNAUTHORIZED,void 0,void 0,!0);let s={active:n.active,username:n.username};if(n.refresh_token&&(s.refresh_token=n.refresh_token),n.role&&(s.role=n.role),r===!0){if(my.get(t)===n.password)return s;if(Vm.validate(n.password,t))my.set(t,n.password);else throw $n(new Error,Gm.GENERIC_AUTH_FAIL,Yn.UNAUTHORIZED,void 0,void 0,!0)}return s}a(wy,"findAndValidateUser");async function nK(){global.hdb_users||await Vo();for(let[,e]of global.hdb_users)if(e.role.role==="super_user")return e}a(nK,"getSuperUser");async function sK(){let e=await C_(),t=$Y.getConfigFromFile(Ey.CONFIG_PARAMS.CLUSTERING_USER),r=e.get(t);if(!Lr.isEmpty(r)&&r?.role?.role===Ey.ROLE_TYPES_ENUM.CLUSTER_USER)return r.decrypt_hash=Ym.decrypt(r.hash),r.uri_encoded_d_hash=encodeURIComponent(r.decrypt_hash),r.uri_encoded_name=encodeURIComponent(r.username),r.sys_name=r.username+hy.SERVER_SUFFIX.ADMIN,r.sys_name_encoded=r.uri_encoded_name+hy.SERVER_SUFFIX.ADMIN,r}a(sK,"getClusterUser");var Iy=[];Wm.invalidateUser=function(e){for(let t of Iy)try{t(e)}catch(r){WY.error("Error invalidating user",r)}};Wm.onInvalidatedUser=function(e){Iy.push(e)}});var Mc=g((hce,Uy)=>{"use strict";var ki=Y(),Ur=M(),iK=bN(),fce=ms(),Ece=vi(),oK=Mr(),{validateEvent:Dy}=bn(),Lc=On(),aK=require("process"),{resetDatabases:cK}=(be(),te(qe)),uK={[Ur.ITC_EVENT_TYPES.SCHEMA]:lK,[Ur.ITC_EVENT_TYPES.USER]:My};async function lK(e){let t=Dy(e);if(t){ki.error(t);return}ki.trace("ITC schemaHandler received schema event:",e),await iK(e.message),await _K(e.message)}a(lK,"schemaHandler");async function _K(e){try{Lc.resetReadTxn(Ur.SYSTEM_SCHEMA_NAME,Ur.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME),Lc.resetReadTxn(Ur.SYSTEM_SCHEMA_NAME,Ur.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME),Lc.resetReadTxn(Ur.SYSTEM_SCHEMA_NAME,Ur.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME);let t=cK();e.table&&e.database&&await t[e.database][e.table].put(Symbol.for("write-verify"),null)}catch(t){ki.error(t)}}a(_K,"syncSchemaMetadata");var Ly=[];async function My(e){try{try{Lc.resetReadTxn(Ur.SYSTEM_SCHEMA_NAME,Ur.SYSTEM_TABLE_NAMES.USER_TABLE_NAME),Lc.resetReadTxn(Ur.SYSTEM_SCHEMA_NAME,Ur.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME)}catch(r){ki.warn(r)}let t=Dy(e);if(t){ki.error(t);return}ki.trace(`ITC userHandler ${Ur.HDB_ITC_CLIENT_PREFIX}${aK.pid} received user event:`,e),await oK.setUsersToGlobal();for(let r of Ly)r()}catch(t){ki.error(t)}}a(My,"userHandler");My.addListener=function(e){Ly.push(e)};Uy.exports=uK});var bn=g((Rce,vy)=>{"use strict";var pce=Y(),Qm=J(),dK=M(),{ITC_ERRORS:Uc}=Or(),{parentPort:Sce,threadId:fK,isMainThread:EK,workerData:Tce}=require("worker_threads"),{onMessageFromWorkers:hK,broadcast:gce,broadcastWithAcknowledgement:mK}=Ze();vy.exports={sendItcEvent:pK,validateEvent:Py,SchemaEventMsg:SK,UserEventMsg:TK};var D_;hK(async(e,t)=>{D_=D_||Mc(),Py(e),D_[e.type]&&await D_[e.type](e),e.requestId&&t&&t.postMessage({type:"ack",id:e.requestId})});function pK(e){return!EK&&e.message&&(e.message.originator=fK),mK(e)}a(pK,"sendItcEvent");function Py(e){if(typeof e!="object")return Uc.INVALID_ITC_DATA_TYPE;if(!e.hasOwnProperty("type")||Qm.isEmpty(e.type))return Uc.MISSING_TYPE;if(!e.hasOwnProperty("message")||Qm.isEmpty(e.message))return Uc.MISSING_MSG;if(!e.message.hasOwnProperty("originator")||Qm.isEmpty(e.message.originator))return Uc.MISSING_ORIGIN;if(dK.ITC_EVENT_TYPES[e.type.toUpperCase()]===void 0)return Uc.INVALID_EVENT(e.type)}a(Py,"validateEvent");function SK(e,t,r,n=void 0,s=void 0){this.originator=e,this.operation=t,this.schema=r,this.table=n,this.attribute=s}a(SK,"SchemaEventMsg");function TK(e){this.originator=e}a(TK,"UserEventMsg")});var ps=g((bce,qy)=>{"use strict";var By=M(),Oce=J(),L_=Y(),Hy=RN(),$o,{sendItcEvent:xy}=bn();function gK(e){try{L_.trace("signalSchemaChange called with message:",e),$o=$o||Mc();let t=new Hy(By.ITC_EVENT_TYPES.SCHEMA,e);return $o.schema(t),xy(t)}catch(t){L_.error(t)}}a(gK,"signalSchemaChange");function RK(e){try{L_.trace("signalUserChange called with message:",e),$o=$o||Mc();let t=new Hy(By.ITC_EVENT_TYPES.USER,e);return $o.user(t),xy(t)}catch(t){L_.error(t)}}a(RK,"signalUserChange");qy.exports={signalSchemaChange:gK,signalUserChange:RK}});var M_=g((yce,Gy)=>{"use strict";var Fy=J(),AK=M(),OK=Y(),bK=E_(),NK=f_(),yK=ps(),{SchemaEventMsg:wK}=bn(),IK="already exists in";Gy.exports=CK;async function CK(e,t,r){if(Fy.isEmptyOrZeroLength(r))return r;let n=[];Fy.isEmptyOrZeroLength(t.attributes)||t.attributes.forEach(i=>{n.push(i.attribute)});let s=r.filter(i=>n.indexOf(i)<0);return s.length===0||await Promise.all(s.map(async i=>{await DK(e,t.schema,t.name,i)})),s}a(CK,"lmdbCheckForNewAttributes");async function DK(e,t,r,n){let s=new NK(t,r,n,void 0,!0);e&&(s.hdb_auth_header=e);try{await LK(s)}catch(i){if(typeof i=="object"&&i.message!==void 0&&i.message.includes(IK))OK.warn(`attribute ${t}.${r}.${n} already exists`);else throw i}}a(DK,"createNewAttribute");async function LK(e){let t;return t=await bK(e),yK.signalSchemaChange(new wK(process.pid,AK.OPERATIONS_ENUM.CREATE_ATTRIBUTE,e.schema,e.table,e.attribute)),t}a(LK,"createAttribute")});var Yo=g((Ice,ky)=>{"use strict";var zm=class{static{a(this,"LMDBTransactionObject")}constructor(t,r,n,s,i=void 0){this.operation=t,this.user_name=r,this.timestamp=n,this.hash_values=s,this.origin=i}};ky.exports=zm});var $y=g((Dce,Vy)=>{"use strict";var MK=Yo(),UK=M().OPERATIONS_ENUM,Jm=class extends MK{static{a(this,"LMDBInsertTransactionObject")}constructor(t,r,n,s,i=void 0){super(UK.INSERT,r,n,s,i),this.records=t}};Vy.exports=Jm});var Ky=g((Mce,Yy)=>{"use strict";var PK=Yo(),vK=M().OPERATIONS_ENUM,jm=class extends PK{static{a(this,"LMDBUpdateTransactionObject")}constructor(t,r,n,s,i,o=void 0){super(vK.UPDATE,n,s,i,o),this.records=t,this.original_records=r}};Yy.exports=jm});var Qy=g((Pce,Wy)=>{"use strict";var BK=Yo(),HK=M().OPERATIONS_ENUM,Xm=class extends BK{static{a(this,"LMDBUpsertTransactionObject")}constructor(t,r,n,s,i,o=void 0){super(HK.UPSERT,n,s,i,o),this.records=t,this.original_records=r}};Wy.exports=Xm});var Jy=g((Bce,zy)=>{"use strict";var xK=Yo(),qK=M().OPERATIONS_ENUM,Zm=class extends xK{static{a(this,"LMDBDeleteTransactionObject")}constructor(t,r,n,s,i=void 0){super(qK.DELETE,n,s,t,i),this.original_records=r}};zy.exports=Zm});var Pc=g((qce,ew)=>{"use strict";var xce=require("path"),jy=$e(),FK=$y(),GK=Ky(),kK=Qy(),VK=Jy(),Ko=lt(),Xy=J(),{CONFIG_PARAMS:$K}=M(),Zy=Z();Zy.initSync();var U_=M().OPERATIONS_ENUM,{getTransactionAuditStorePath:YK}=Ke();ew.exports=KK;async function KK(e,t){if(Zy.get($K.LOGGING_AUDITLOG)===!1)return;let r=YK(e.schema,e.table),n=await jy.openEnvironment(r,e.table,!0),s=WK(e,t);if(!(s===void 0||s.hash_values.length===0)&&n!==void 0){jy.initializeDBIs(n,Ko.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,Ko.TRANSACTIONS_DBIS);let i=s.timestamp;return await n.dbis[Ko.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP].ifNoExists(i,()=>{n.dbis[Ko.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP].put(i,s),Xy.isEmpty(s.user_name)||n.dbis[Ko.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].put(s.user_name,i);for(let o=0;o<s.hash_values.length;o++)n.dbis[Ko.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE].put(s.hash_values[o],i)})}}a(KK,"writeTransaction");function WK(e,t){let r=Xy.isEmpty(e.hdb_user)?void 0:e.hdb_user.username;if(e.operation===U_.INSERT)return new FK(e.records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===U_.UPDATE)return new GK(e.records,t.original_records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===U_.UPSERT)return new kK(e.records,t.original_records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===U_.DELETE)return new VK(t.deleted,t.original_records,r,t.txn_time,e.__origin)}a(WK,"createTransactionObject")});var ep=g((kce,tw)=>{"use strict";var QK=bc(),Gce=Nc(),vc=M(),zK=Cc(),JK=Ho().insertRecords,jK=$e(),XK=Y(),ZK=M_(),{getSchemaPath:eW}=Ke(),tW=Pc();tw.exports=rW;async function rW(e){try{let{schema_table:t,attributes:r}=QK(e);zK(e,r,t.hash_attribute),e.schema!==vc.SYSTEM_SCHEMA_NAME&&(r.includes(vc.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||r.push(vc.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.includes(vc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||r.push(vc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let n=await ZK(e.hdb_auth_header,t,r),s=eW(e.schema,e.table),i=await jK.openEnvironment(s,e.table),o=await JK(i,t.hash_attribute,r,e.records,e.__origin?.timestamp);try{await tW(e,o)}catch(c){XK.error(`unable to write transaction due to ${c.message}`)}return{written_hashes:o.written_hashes,skipped_hashes:o.skipped_hashes,schema_table:t,new_attributes:n,txn_time:o.txn_time}}catch(t){throw t}}a(rW,"lmdbCreateRecords")});var sw=g(($ce,nw)=>{"use strict";var rw=M(),nW=ep(),sW=Nc(),iW=require("fs-extra"),{getSchemaPath:oW}=Ke();nw.exports=aW;async function aW(e){let t=[{name:e.schema,createddate:Date.now()}],r=new sW(rw.SYSTEM_SCHEMA_NAME,rw.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,void 0,t);await nW(r),await iW.mkdirp(oW(e.schema))}a(aW,"lmdbCreateSchema")});var ow=g((Kce,iw)=>{"use strict";var tp=class{static{a(this,"DeleteRecordsResponseObject")}constructor(t=[],r=[],n=void 0,s=[]){this.deleted=t,this.skipped=r,this.txn_time=n,this.original_records=s}};iw.exports=tp});var lw=g((jce,uw)=>{"use strict";var aw=$e(),rp=Ir(),np=Or().LMDB_ERRORS_ENUM,cW=lt(),cw=Y(),Qce=J(),uW=require("lmdb"),lW=ow(),_W=M(),{OVERFLOW_MARKER:zce,MAX_SEARCH_KEY_LENGTH:Jce}=cW,dW=_W.TIME_STAMP_NAMES_ENUM.UPDATED_TIME;async function fW(e,t,r,n){if(rp.validateEnv(e),t===void 0)throw new Error(np.HASH_ATTRIBUTE_REQUIRED);if(!Array.isArray(r))throw r===void 0?new Error(np.IDS_REQUIRED):new Error(np.IDS_MUST_BE_ITERABLE);try{let s=aw.listDBIs(e);aw.initializeDBIs(e,t,s);let i=new lW,o,c=[],u=[];for(let f=0,E=r.length;f<E;f++)try{o=r[f];let h=e.dbis[t].get(o);if(!h||n&&h[dW]>n){i.skipped.push(o);continue}let p=e.dbis[t].ifVersion(o,uW.IF_EXISTS,()=>{e.dbis[t].remove(o);for(let S=0;S<s.length;S++){let T=s[S];if(!h.hasOwnProperty(T)||T===t)continue;let A=e.dbis[T],b=h[T];if(b!=null)try{let H=rp.getIndexedValues(b);if(H)for(let q=0,v=H.length;q<v;q++)A.remove(H[q],o)}catch{cw.warn(`cannot delete from attribute: ${T}, ${b}:${o}`)}}});c.push(p),u.push(o),i.original_records.push(h)}catch(h){cw.warn(h),i.skipped.push(o)}let _=[],l=await Promise.all(c);for(let f=0,E=l.length;f<E;f++)l[f]===!0?i.deleted.push(u[f]):(i.skipped.push(u[f]),_.push(f));let d=0;for(let f=0;f<_.length;f++){let E=_[f];i.original_records.splice(E-d,1),d++}return i.txn_time=rp.getNextMonotonicTime(),i}catch(s){throw s}}a(fW,"deleteRecords");uw.exports={deleteRecords:fW}});var Bc=g((Zce,dw)=>{"use strict";var Wo=J(),EW=lw(),hW=$e(),{getSchemaPath:mW}=Ke(),pW=Pc(),SW=Y();dw.exports=TW;async function TW(e,t=!0){let n=global.hdb_schema[e.schema][e.table].hash_attribute;if(Wo.isEmpty(n))throw new Error(`could not retrieve hash attribute for schema:${e.schema} and table ${e.table}`);try{if(Wo.isEmptyOrZeroLength(e.hash_values)&&!Wo.isEmptyOrZeroLength(e.records)){e.hash_values=[];for(let c=0;c<e.records.length;c++){let u=e.records[c][n];Wo.isEmpty(u)||e.hash_values.push(u)}}if(Wo.isEmptyOrZeroLength(e.hash_values))return _w([],[]);if(!Array.isArray(e.hash_values))throw new Error("hash_values must be an array");if(Wo.isEmptyOrZeroLength(e.records)){e.records=[];for(let c=0;c<e.hash_values.length;c++)e.records[c]={[n]:e.hash_values[c]}}let s=mW(e.schema,e.table),i=await hW.openEnvironment(s,e.table),o=await EW.deleteRecords(i,n,e.hash_values,e.__origin?.timestamp);try{t===!0&&await pW(e,o)}catch(c){SW.error(`unable to write transaction due to ${c.message}`)}return _w(o.deleted,o.skipped,o.txn_time)}catch(s){throw s}}a(TW,"lmdbDeleteRecords");function _w(e,t,r){let n=e.length+t.length,s=n===1?"record":"records";return{message:`${e.length} of ${n} ${s} successfully deleted`,deleted_hashes:e,skipped_hashes:t,txn_time:r}}a(_w,"createDeleteResponse")});var ip=g((rue,fw)=>{"use strict";var gW=M(),tue=Ir();function sp(e,t){let r=Object.create(null);if(t.length===1&&gW.SEARCH_WILDCARDS.indexOf(t[0])>=0)Object.assign(r,e);else for(let n=0;n<t.length;n++){let s=t[n],i=e[s];r[s]=i===void 0?null:i}return r}a(sp,"parseRow");function RW(e,t,r,n){let s=sp(r,e);n.push(s)}a(RW,"searchAll");function AW(e,t,r,n){let s=sp(r,e);n[t]=s}a(AW,"searchAllToMap");function OW(e,t,r){r[e]===void 0&&(r[e]=[]),r[e].push(t)}a(OW,"iterateDBI");function Vi(e,t,r,n,s){let i=Object.create(null);i[s]=e;let o;n===s?o=e:(o=t,n!==void 0&&(i[n]=o)),r[0].push(o),r[1].push(i)}a(Vi,"pushResults");function bW(e,t,r,n,s,i){t.toString().endsWith(e)&&Vi(t,r,n,s,i)}a(bW,"endsWith");function NW(e,t,r,n,s,i){t.toString().includes(e)&&Vi(t,r,n,s,i)}a(NW,"contains");function yW(e,t,r,n,s,i){t>e&&Vi(t,r,n,s,i)}a(yW,"greaterThanCompare");function wW(e,t,r,n,s,i){t>=e&&Vi(t,r,n,s,i)}a(wW,"greaterThanEqualCompare");function IW(e,t,r,n,s,i){t<e&&Vi(t,r,n,s,i)}a(IW,"lessThanCompare");function CW(e,t,r,n,s,i){t<=e&&Vi(t,r,n,s,i)}a(CW,"lessThanEqualCompare");fw.exports={parseRow:sp,searchAll:RW,searchAllToMap:AW,iterateDBI:OW,endsWith:bW,contains:NW,greaterThanCompare:yW,greaterThanEqualCompare:wW,lessThanCompare:IW,lessThanEqualCompare:CW,pushResults:Vi}});var Qo=g((aue,gw)=>{"use strict";var Xs=$e(),sue=Y(),Pr=Ir(),P_=lt(),at=Or().LMDB_ERRORS_ENUM,iue=J(),DW=M(),v_=ip(),{parseRow:LW}=v_,oue=require("lmdb"),{OVERFLOW_MARKER:Ew,MAX_SEARCH_KEY_LENGTH:MW}=P_;function hw(e,t,r,n=!1,s=void 0,i=void 0){return $i(e,t,r,(o,c)=>c.getRange({transaction:o,start:n?void 0:!1,end:n?!1:void 0,limit:s,offset:i,reverse:n}))}a(hw,"iterateFullIndex");function Hc(e,t,r,n,s,i=!1,o=void 0,c=void 0,u=!1,_=!1){return $i(e,t,r,(l,d,f,E)=>{let A={transaction:l,start:i===!0?s:n,end:i===!0?n:s,reverse:i,limit:o,offset:c,inclusiveEnd:i===!0?!u:!_,exclusiveStart:i===!0?_:u};return E===r?(A.values=!1,d.getRange(A).map(b=>({value:b}))):d.getRange(A)})}a(Hc,"iterateRangeBetween");function $i(e,t,r,n){let s=e.database||e,i=Xs.openDBI(s,r);i[P_.DBI_DEFINITION_NAME].is_hash_attribute?t=r:t&&Xs.openDBI(s,t);let o;e.database?o=e:(o=e.useReadTransaction(),o.database=e);let c=n(o,i,s,t);return c.transaction=o,e.database||(c.onDone=()=>{o.done()}),c}a($i,"setupTransaction");function mw(e,t,r,n){let s;return function(i,o){if(typeof i=="string"&&i.endsWith(Ew)){if(!s)if(r)s=Xs.openDBI(e,r);else{let u=Xs.listDBIs(e);for(let _=0,l=u.length;_<l&&(s=Xs.openDBI(e,u[_]),!s[P_.DBI_DEFINITION_NAME].is_hash_attribute);_++);}i=s.get(o,{transaction:t,lazy:!0})[n]}return i}}a(mw,"getOverflowCheck");function UW(e,t,r,n=!1,s=void 0,i=void 0){if(Pr.validateEnv(e),t===void 0)throw new Error(at.HASH_ATTRIBUTE_REQUIRED);return $i(e,t,t,(o,c,u)=>(B_(r),r=xc(u,r),c.getRange({transaction:o,start:n?void 0:!1,end:n?!1:void 0,limit:s,offset:i,reverse:n}).map(_=>LW(_.value,r))))}a(UW,"searchAll");function PW(e,t,r,n=!1,s=void 0,i=void 0){if(Pr.validateEnv(e),t===void 0)throw new Error(at.HASH_ATTRIBUTE_REQUIRED);B_(r),r=xc(e.database||e,r);let o=new Map;for(let{key:c,value:u}of hw(e,t,t,n,s,i))o.set(c,v_.parseRow(u,r));return o}a(PW,"searchAllToMap");function vW(e,t,r=!1,n=void 0,s=void 0){if(Pr.validateEnv(e),t===void 0)throw new Error(at.ATTRIBUTE_REQUIRED);let i=Object.create(null),o=hw(e,void 0,t,r,n,s),c=o.transaction,u=mw(c.database,c,void 0,t);for(let{key:_,value:l}of o){let d=u(_,l);i[d]===void 0&&(i[d]=[]),i[d].push(l)}return i}a(vW,"iterateDBI");function BW(e,t){if(Pr.validateEnv(e),t===void 0)throw new Error(at.HASH_ATTRIBUTE_REQUIRED);return Xs.statDBI(e,t).entryCount}a(BW,"countAll");function HW(e,t,r,n,s=!1,i=void 0,o=void 0){return Zs(e,r,n),$i(e,t,r,(c,u,_,l)=>(n=Pr.convertKeyValueToWrite(n),l===r?u.get(n,{transaction:c,lazy:!0})===void 0?[]:[{key:n,value:n}]:u.getValues(n,{transaction:c,reverse:s,limit:i,offset:o}).map(d=>({key:n,value:d}))))}a(HW,"equals");function xW(e,t,r){return Zs(e,t,r),Xs.openDBI(e,t).getValuesCount(r)}a(xW,"count");function qW(e,t,r,n,s=!1,i=void 0,o=void 0){return Zs(e,r,n),$i(e,null,r,(c,u)=>{n=Pr.convertKeyValueToWrite(n);let _=!0;typeof n=="number"&&(_=!1);let l;if(s===!0){let d;for(let f of u.getKeys({transaction:c,start:n}))if(!f.startsWith(n)){d=f;break}return d!==void 0&&(Number.isInteger(o)?o++:i++),l=u.getRange({transaction:c,start:d,end:void 0,reverse:s,limit:i,offset:o}).map(f=>{let{key:E}=f;if(E!==d){if(E.toString().startsWith(n))return f;if(_===!0)return l.DONE}}),l.filter(f=>f)}else return l=u.getRange({transaction:c,start:n,reverse:s,limit:i,offset:o}).map(d=>{if(d.key.toString().startsWith(n))return d;if(_===!0)return l.DONE}),_?l:l.filter(d=>d)})}a(qW,"startsWith");function FW(e,t,r,n,s=!1,i=void 0,o=void 0){return pw(e,t,r,n,s,i,o,!0)}a(FW,"endsWith");function pw(e,t,r,n,s=!1,i=void 0,o=void 0,c=!1){return Zs(e,r,n),$i(e,null,r,(u,_,l,d)=>{let f=mw(l,u,d,r);return o=Number.isInteger(o)?o:0,_.getKeys({transaction:u,end:s?!1:void 0,reverse:s}).flatMap(E=>{let h=E.toString();return h.endsWith(Ew)?_.getValues(E,{transaction:u}).map(p=>{let S=f(E,p);if(c?S.endsWith(n):S.includes(n))return{key:S,value:p}}).filter(p=>p):(c?h.endsWith(n):h.includes(n))?_[P_.DBI_DEFINITION_NAME].is_hash_attribute?{key:E,value:E}:_.getValues(E,{transaction:u}).map(p=>({key:E,value:p})):[]}).slice(o,i===void 0?void 0:i+(o||0))})}a(pw,"contains");function GW(e,t,r,n,s=!1,i=void 0,o=void 0){Zs(e,r,n);let c=typeof n,u;return c==="string"?u="\uFFFF":c==="number"?u=1/0:c==="boolean"&&(u=!0),Hc(e,t,r,n,u,s,i,o,!0,!1)}a(GW,"greaterThan");function kW(e,t,r,n,s=!1,i=void 0,o=void 0){Zs(e,r,n);let c=typeof n,u;return c==="string"?u="\uFFFF":c==="number"?u=1/0:c==="boolean"&&(u=!0),Hc(e,t,r,n,u,s,i,o,!1,!1)}a(kW,"greaterThanEqual");function VW(e,t,r,n,s=!1,i=void 0,o=void 0){Zs(e,r,n);let c=typeof n,u;return c==="string"?u="\0":c==="number"?u=-1/0:c==="boolean"&&(u=!1),Hc(e,t,r,u,n,s,i,o,!1,!0)}a(VW,"lessThan");function $W(e,t,r,n,s=!1,i=void 0,o=void 0){Zs(e,r,n);let c=typeof n,u;return c==="string"?u="\0":c==="number"?u=-1/0:c==="boolean"&&(u=!1),Hc(e,t,r,u,n,s,i,o,!1,!1)}a($W,"lessThanEqual");function YW(e,t,r,n,s,i=!1,o=void 0,c=void 0){if(Pr.validateEnv(e),r===void 0)throw new Error(at.ATTRIBUTE_REQUIRED);if(n===void 0)throw new Error(at.START_VALUE_REQUIRED);if(s===void 0)throw new Error(at.END_VALUE_REQUIRED);if(n=Pr.convertKeyValueToWrite(n),s=Pr.convertKeyValueToWrite(s),n>s)throw new Error(at.END_VALUE_MUST_BE_GREATER_THAN_START_VALUE);return Hc(e,t,r,n,s,i,o,c)}a(YW,"between");function KW(e,t,r,n){Pr.validateEnv(e);let s=e.database||e,i=e.database?e:null;if(t===void 0)throw new Error(at.HASH_ATTRIBUTE_REQUIRED);if(B_(r),r=xc(s,r),n===void 0)throw new Error(at.ID_REQUIRED);let o=null,c=s.dbis[t].get(n,{transaction:i,lazy:r.length<3});return c&&(o=v_.parseRow(c,r)),o}a(KW,"searchByHash");function WW(e,t,r){Pr.validateEnv(e);let n=e.database||e,s=e.database?e:null;if(t===void 0)throw new Error(at.HASH_ATTRIBUTE_REQUIRED);if(r===void 0)throw new Error(at.ID_REQUIRED);let i=!0;return n.dbis[t].get(r,{transaction:s,lazy:!0})===void 0&&(i=!1),i}a(WW,"checkHashExists");function QW(e,t,r,n,s=[]){return Tw(e,t,r,n,s),Sw(e,t,r,n,s).map(i=>i[1])}a(QW,"batchSearchByHash");function zW(e,t,r,n,s=[]){Tw(e,t,r,n,s);let i=new Map;for(let[o,c]of Sw(e,t,r,n,s))i.set(o,c);return i}a(zW,"batchSearchByHashToMap");function Sw(e,t,r,n,s=[]){return $i(e,t,t,(i,o,c)=>{r=xc(c,r);let u=r.length<3;return n.map(_=>{let l=c.dbis[t].get(_,{transaction:i,lazy:u});if(l)return[_,v_.parseRow(l,r)];s.push(_)}).filter(_=>_)})}a(Sw,"batchHashSearch");function Tw(e,t,r,n,s){if(Pr.validateEnv(e),t===void 0)throw new Error(at.HASH_ATTRIBUTE_REQUIRED);if(B_(r),n==null)throw new Error(at.IDS_REQUIRED);if(!n[Symbol.iterator])throw new Error(at.IDS_MUST_BE_ITERABLE)}a(Tw,"initializeBatchSearchByHash");function B_(e){if(!Array.isArray(e))throw e===void 0?new Error(at.FETCH_ATTRIBUTES_REQUIRED):new Error(at.FETCH_ATTRIBUTES_MUST_BE_ARRAY)}a(B_,"validateFetchAttributes");function Zs(e,t,r){if(Pr.validateEnv(e),t===void 0)throw new Error(at.ATTRIBUTE_REQUIRED);if(r===void 0)throw new Error(at.SEARCH_VALUE_REQUIRED);if(r?.length>MW)throw new Error(at.SEARCH_VALUE_TOO_LARGE)}a(Zs,"validateComparisonFunctions");function xc(e,t){return t.length===1&&DW.SEARCH_WILDCARDS.indexOf(t[0])>=0&&(t=Xs.listDBIs(e)),t}a(xc,"setGetWholeRowAttributes");gw.exports={searchAll:UW,searchAllToMap:PW,count:xW,countAll:BW,equals:HW,startsWith:qW,endsWith:FW,contains:pw,searchByHash:KW,setGetWholeRowAttributes:xc,batchSearchByHash:QW,batchSearchByHashToMap:zW,checkHashExists:WW,iterateDBI:vW,greaterThan:GW,greaterThanEqual:kW,lessThan:VW,lessThanEqual:$W,between:YW}});var zo=g((uue,Nw)=>{var Rw=require("lodash"),Aw=je(),Ee=require("joi"),JW=J(),{hdb_schema_table:qc,checkValidTable:Ow,hdb_table:bw,hdb_database:H_}=kn(),{handleHDBError:jW,hdb_errors:XW}=ee(),{getDatabases:ZW}=(be(),te(qe)),{HTTP_STATUS_CODES:eQ}=XW,tQ=Ee.object({database:H_,schema:H_,table:bw,search_attribute:qc,search_value:Ee.any().required(),get_attributes:Ee.array().min(1).items(Ee.alternatives(qc,Ee.object())).optional(),desc:Ee.bool(),limit:Ee.number().integer().min(1),offset:Ee.number().integer().min(0)}),rQ=Ee.object({database:H_,schema:H_,table:bw,operator:Ee.string().valid("and","or").default("and").lowercase(),offset:Ee.number().integer().min(0),limit:Ee.number().integer().min(1),get_attributes:Ee.array().min(1).items(Ee.alternatives(qc,Ee.object())).optional(),sort:Ee.object({attribute:Ee.alternatives(qc,Ee.array().min(1)),descending:Ee.bool().optional()}).optional(),conditions:Ee.array().min(1).items(Ee.alternatives(Ee.object({operator:Ee.string().valid("and","or").default("and").lowercase(),conditions:Ee.array()}),Ee.object({search_attribute:Ee.alternatives(qc,Ee.array().min(1)),search_type:Ee.string().valid("equals","contains","starts_with","ends_with","greater_than","greater_than_equal","less_than","less_than_equal","between","not_equal").optional(),search_value:Ee.when("search_type",{switch:[{is:"equals",then:Ee.any()},{is:"between",then:Ee.array().items(Ee.alternatives([Ee.string(),Ee.number()])).length(2)}],otherwise:Ee.alternatives(Ee.string(),Ee.number())}).required()}))).required()});Nw.exports=function(e,t){let r=null;switch(t){case"value":r=Aw.validateBySchema(e,tQ);break;case"hashes":let i=function(o){s?s+=". "+o:s=o};var n=i;a(i,"addError");let s;i(Ow("database",e.schema)),i(Ow("table",e.table)),e.hash_values?Array.isArray(e.hash_values)?e.hash_values.every(o=>typeof o=="string"||typeof o=="number")||i("'hash_values' must be strings or numbers"):i("'hash_values' must be an array"):i("'hash_values' is required"),e.get_attributes?Array.isArray(e.get_attributes)?e.get_attributes.length===0?i("'get_attributes' must contain at least 1 item"):e.get_attributes.every(o=>typeof o=="string"||typeof o=="number")||i("'get_attributes' must be strings or numbers"):i("'get_attributes' must be an array"):i("'get_attributes' is required"),s&&(r=new Error(s.trim()));break;case"conditions":r=Aw.validateBySchema(e,rQ);break;default:throw new Error(`Error validating search, unknown type: ${t}`)}if(!r&&e.schema!=="system"){let s=JW.checkGlobalSchemaTable(e.schema,e.table);if(s)return jW(new Error,s,eQ.NOT_FOUND);let o=ZW()[e.schema][e.table].attributes,c=e.get_attributes?[...e.get_attributes]:[];t==="value"&&c.push(e.search_attribute);let u=a(l=>{for(let d=0,f=l.conditions.length;d<f;d++){let E=l.conditions[d];E.conditions?u(E):c.push(E.search_attribute)}},"addConditions");t==="conditions"&&u(e);let _=Rw.filter(c,l=>l!=="*"&&l.attribute!=="*"&&!Array.isArray(l)&&!Rw.some(o,d=>d===l||d.attribute===l||d.attribute===l.attribute));if(_&&_.length>0){let l=_.join(", ");return l=l.replace(/,([^,]*)$/," and$1"),new Error(`unknown attribute '${l}'`)}}return r}});var op=g((_ue,yw)=>{"use strict";var nQ=$e(),sQ=zo(),{getSchemaPath:iQ}=Ke();yw.exports=oQ;function oQ(e){let t=sQ(e,"hashes");if(t)throw t;let r=iQ(e.schema,e.table);return nQ.openEnvironment(r,e.table)}a(oQ,"initialize")});var ap=g((fue,ww)=>{"use strict";var aQ=Qo(),cQ=op();ww.exports=uQ;async function uQ(e){let t=await cQ(e),r=t.useReadTransaction();r.database=t;let n=global.hdb_schema[e.schema][e.table];try{return aQ.batchSearchByHashToMap(r,n.hash_attribute,e.get_attributes,e.hash_values)}finally{r.done()}}a(uQ,"lmdbGetDataByHash")});var Jo=g((hue,Iw)=>{"use strict";var cp=class{static{a(this,"SearchByHashObject")}constructor(t,r,n,s){this.schema=t,this.table=r,this.hash_values=n,this.get_attributes=s}};Iw.exports=cp});var Dw=g((Sue,Cw)=>{"use strict";var pue=Jo(),lQ=Qo(),_Q=op();Cw.exports=dQ;async function dQ(e){let t=await _Q(e),r=global.hdb_schema[e.schema][e.table];return lQ.batchSearchByHash(t,r.hash_attribute,e.get_attributes,e.hash_values)}a(dQ,"lmdbSearchByHash")});var Kn=g((gue,Lw)=>{"use strict";var up=class{static{a(this,"SearchObject")}constructor(t,r,n,s,i,o,c,u=!1,_=void 0,l=void 0){this.schema=t,this.table=r,this.search_attribute=n,this.search_value=s,this.hash_attribute=i,this.get_attributes=o,this.end_value=c,this.reverse=u,this.limit=_,this.offset=l}};Lw.exports=up});var x_=g((Aue,Hw)=>{"use strict";var Kt=Qo(),fQ=$e(),EQ=J(),he=lt(),Yi=M(),hQ=Ui(),Mw=Or().LMDB_ERRORS_ENUM,{getSchemaPath:mQ}=Ke(),Ss=Yi.SEARCH_WILDCARDS;async function pQ(e,t,r){let n;e.schema===Yi.SYSTEM_SCHEMA_NAME?n=hQ[e.table]:n=global.hdb_schema[e.schema][e.table];let s=Bw(e,n.hash_attribute,r,t);return Pw(e,s,n.hash_attribute,r)}a(pQ,"prepSearch");async function Pw(e,t,r,n){let s=mQ(e.schema,e.table),i=await fQ.openEnvironment(s,e.table),o=vw(i,e,t,r),c=o.transaction||i;if([he.SEARCH_TYPES.BATCH_SEARCH_BY_HASH,he.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP,he.SEARCH_TYPES.SEARCH_ALL,he.SEARCH_TYPES.SEARCH_ALL_TO_MAP].indexOf(t)>=0)return o;if(SQ(e,r)===!1){let l=e.search_attribute;if(l===r)return n?Uw(o,()=>!0):o.map(f=>({[r]:f.key}));let d=a(f=>({[r]:f.value,[l]:f.key}),"toObject");return n?Uw(o,d):o.map(d)}let _=e.search_attribute===r?o.map(l=>l.key):o.map(l=>l.value);return n===!0?Kt.batchSearchByHashToMap(c,r,e.get_attributes,_):Kt.batchSearchByHash(c,r,e.get_attributes,_)}a(Pw,"executeSearch");function vw(e,t,r,n){let s,i=n;t.get_attributes.indexOf(n)<0&&(i=void 0);let{reverse:o,limit:c,offset:u}=t;switch(o=typeof o=="boolean"?o:!1,c=Number.isInteger(c)?c:void 0,u=Number.isInteger(u)?u:void 0,r){case he.SEARCH_TYPES.EQUALS:s=Kt.equals(e,i,t.search_attribute,t.search_value,o,c,u);break;case he.SEARCH_TYPES.CONTAINS:s=Kt.contains(e,i,t.search_attribute,t.search_value,o,c,u);break;case he.SEARCH_TYPES.ENDS_WITH:case he.SEARCH_TYPES._ENDS_WITH:s=Kt.endsWith(e,i,t.search_attribute,t.search_value,o,c,u);break;case he.SEARCH_TYPES.STARTS_WITH:case he.SEARCH_TYPES._STARTS_WITH:s=Kt.startsWith(e,i,t.search_attribute,t.search_value,o,c,u);break;case he.SEARCH_TYPES.BATCH_SEARCH_BY_HASH:return Kt.batchSearchByHash(e,t.search_attribute,t.get_attributes,[t.search_value]);case he.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP:return Kt.batchSearchByHashToMap(e,t.search_attribute,t.get_attributes,[t.search_value]);case he.SEARCH_TYPES.SEARCH_ALL:return Kt.searchAll(e,n,t.get_attributes,o,c,u);case he.SEARCH_TYPES.SEARCH_ALL_TO_MAP:return Kt.searchAllToMap(e,n,t.get_attributes,o,c,u);case he.SEARCH_TYPES.BETWEEN:s=Kt.between(e,i,t.search_attribute,t.search_value,t.end_value,o,c,u);break;case he.SEARCH_TYPES.GREATER_THAN:case he.SEARCH_TYPES._GREATER_THAN:s=Kt.greaterThan(e,i,t.search_attribute,t.search_value,o,c,u);break;case he.SEARCH_TYPES.GREATER_THAN_EQUAL:case he.SEARCH_TYPES._GREATER_THAN_EQUAL:s=Kt.greaterThanEqual(e,i,t.search_attribute,t.search_value,o,c,u);break;case he.SEARCH_TYPES.LESS_THAN:case he.SEARCH_TYPES._LESS_THAN:s=Kt.lessThan(e,i,t.search_attribute,t.search_value,o,c,u);break;case he.SEARCH_TYPES.LESS_THAN_EQUAL:case he.SEARCH_TYPES._LESS_THAN_EQUAL:s=Kt.lessThanEqual(e,i,t.search_attribute,t.search_value,o,c,u);break;default:return Object.create(null)}return s}a(vw,"searchByType");function Uw(e,t){let r=new Map;for(let n of e)r.set(n.value,t(n));return r}a(Uw,"createMapFromIterable");function SQ(e,t){if(e.get_attributes.length===1&&e.get_attributes[0]==="*")return!0;let r=[e.search_attribute];e.get_attributes.indexOf(t)>=0&&r.push(t);let n=!1;for(let s=0;s<e.get_attributes.length;s++)if(r.indexOf(e.get_attributes[s])<0){n=!0;break}return n}a(SQ,"checkToFetchMore");function Bw(e,t,r,n){if(EQ.isEmpty(n)){let s=e.search_value;typeof s=="object"?s=JSON.stringify(s):s=s.toString();let i=s.charAt(0),o=s.charAt(s.length-1),c=!1;if(e.search_attribute===t&&(c=!0),Ss.indexOf(s)>-1)return r===!0?he.SEARCH_TYPES.SEARCH_ALL_TO_MAP:he.SEARCH_TYPES.SEARCH_ALL;if(s.indexOf(Ss[0])<0&&s.indexOf(Ss[1])<0)return c===!0?r===!0?he.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP:he.SEARCH_TYPES.BATCH_SEARCH_BY_HASH:he.SEARCH_TYPES.EQUALS;if(Ss.indexOf(i)>=0&&Ss.indexOf(o)>=0)return e.search_value=e.search_value.slice(1,-1),he.SEARCH_TYPES.CONTAINS;if(Ss.indexOf(i)>=0)return e.search_value=e.search_value.substr(1),he.SEARCH_TYPES.ENDS_WITH;if(Ss.indexOf(o)>=0)return e.search_value=e.search_value.slice(0,-1),he.SEARCH_TYPES.STARTS_WITH;if(s.includes(Ss[0])||s.includes(Ss[1]))return he.SEARCH_TYPES.EQUALS;throw new Error(Mw.UNKNOWN_SEARCH_TYPE)}else switch(n){case Yi.VALUE_SEARCH_COMPARATORS.BETWEEN:return he.SEARCH_TYPES.BETWEEN;case Yi.VALUE_SEARCH_COMPARATORS.GREATER:return he.SEARCH_TYPES.GREATER_THAN;case Yi.VALUE_SEARCH_COMPARATORS.GREATER_OR_EQ:return he.SEARCH_TYPES.GREATER_THAN_EQUAL;case Yi.VALUE_SEARCH_COMPARATORS.LESS:return he.SEARCH_TYPES.LESS_THAN;case Yi.VALUE_SEARCH_COMPARATORS.LESS_OR_EQ:return he.SEARCH_TYPES.LESS_THAN_EQUAL;default:throw new Error(Mw.UNKNOWN_SEARCH_TYPE)}}a(Bw,"createSearchTypeFromSearchObject");Hw.exports={executeSearch:Pw,createSearchTypeFromSearchObject:Bw,prepSearch:pQ,searchByType:vw}});var qw=g((Nue,xw)=>{"use strict";var bue=Kn(),TQ=zo(),gQ=J(),RQ=M(),AQ=x_();xw.exports=OQ;function OQ(e,t){if(!gQ.isEmpty(t)&&RQ.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[t]===void 0)throw new Error(`Value search comparator - ${t} - is not valid`);let n=TQ(e,"value");if(n)throw n;return AQ.prepSearch(e,t,!0)}a(OQ,"lmdbGetDataByValue")});var Fc=g((Iue,Fw)=>{"use strict";var wue=Kn(),bQ=zo(),NQ=J(),yQ=M(),wQ=x_();Fw.exports=IQ;async function IQ(e,t){if(!NQ.isEmpty(t)&&yQ.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[t]===void 0)throw new Error(`Value search comparator - ${t} - is not valid`);let n=bQ(e,"value");if(n)throw n;return wQ.prepSearch(e,t,!1)}a(IQ,"lmdbSearchByValue")});var kw=g((Lue,Gw)=>{"use strict";var Due=lt(),lp=class{static{a(this,"SearchByConditionsObject")}constructor(t,r,n,s,i=void 0,o=void 0,c="and"){this.schema=t,this.table=r,this.get_attributes=n,this.limit=i,this.offset=o,this.conditions=s,this.operator=c}},_p=class{static{a(this,"SearchCondition")}constructor(t,r,n){this.search_attribute=t,this.search_type=r,this.search_value=n}},dp=class{static{a(this,"SortAttribute")}constructor(t,r){this.attribute=t,this.desc=r}};Gw.exports={SearchByConditionsObject:lp,SearchCondition:_p,SortAttribute:dp}});var Ww=g((vue,Kw)=>{"use strict";var Uue=kw().SearchByConditionsObject,CQ=Kn(),DQ=zo(),fp=Qo(),q_=lt(),{Resource:Pue}=(gn(),te(Ep)),Yw=x_(),LQ=ip(),MQ=require("lodash"),{getSchemaPath:UQ}=Ke(),Vw=$e(),{handleHDBError:PQ,hdb_errors:vQ}=ee(),{HTTP_STATUS_CODES:BQ}=vQ,HQ=1e8;Kw.exports=xQ;async function xQ(e){let t=DQ(e,"conditions");if(t)throw PQ(t,t.message,BQ.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=UQ(e.schema,e.table),n=await Vw.openEnvironment(r,e.table),s=global.hdb_schema[e.schema][e.table];for(let _ of e.conditions)Vw.openDBI(n,_.search_attribute);let i=MQ.sortBy(e.conditions,_=>{if(_.estimated_count===void 0){let l=_.search_type;l===q_.SEARCH_TYPES.EQUALS?_.estimated_count=fp.count(n,_.search_attribute,_.search_value):l===q_.SEARCH_TYPES.CONTAINS||l===q_.SEARCH_TYPES.ENDS_WITH?_.estimated_count=1/0:_.estimated_count=HQ}return _.estimated_count}),o=n.useReadTransaction();o.database=n;let c=await $w(o,e,i[0],s.hash_attribute),u;if(!e.operator||e.operator.toLowerCase()==="and"){let _=n.dbis[s.hash_attribute],l=i.slice(1).map(Yw.filterByType),d=l.length,f=fp.setGetWholeRowAttributes(n,e.get_attributes);u=c.map(E=>_.get(E,{transaction:o,lazy:!0})),d>0&&(u=u.filter(E=>{for(let h=0;h<d;h++)if(!l[h](E))return!1;return!0})),(e.offset||e.limit!==void 0)&&(u=u.slice(e.offset,e.limit!==void 0?(e.offset||0)+e.limit:void 0)),u=u.map(E=>LQ.parseRow(E,f))}else{for(let d=1;d<i.length;d++){let f=i[d],E=await $w(o,e,f,s.hash_attribute);c=c.concat(E)}let _=new Set,l=e.offset||0;c=c.filter(d=>_.has(d)?!1:(_.add(d),!0)).slice(l,e.limit&&e.limit+l),u=fp.batchSearchByHash(o,s.hash_attribute,e.get_attributes,c)}return u.onDone=()=>{o.done()},u}a(xQ,"lmdbSearchByConditions");async function $w(e,t,r,n){let s=new CQ(t.schema,t.table,void 0,void 0,n,t.get_attributes),i=r.search_type;return s.search_attribute=r.search_attribute,i===q_.SEARCH_TYPES.BETWEEN?(s.search_value=r.search_value[0],s.end_value=r.search_value[1]):s.search_value=r.search_value,Yw.searchByType(e,s,i,n).map(o=>o.value)}a($w,"executeConditionSearch")});var Gc=g((Hue,Qw)=>{"use strict";var qQ=M().OPERATIONS_ENUM,hp=class{static{a(this,"DeleteObject")}constructor(t,r,n,s=void 0){this.operation=qQ.DELETE,this.schema=t,this.table=r,this.hash_values=n,this.__origin=s}};Qw.exports=hp});var mp=g((que,rI)=>{"use strict";var Xw=Kn(),Zw=Gc(),eI=Fc(),tI=Bc(),nr=M(),zw=J(),Jw=$e(),{getTransactionAuditStorePath:FQ,getSchemaPath:GQ}=Ke(),jw=Y();rI.exports=kQ;async function kQ(e){try{if(zw.isEmpty(global.hdb_schema[e.schema])||zw.isEmpty(global.hdb_schema[e.schema][e.table]))throw new Error(`unknown schema:${e.schema} and table ${e.table}`);await VQ(e),await $Q(e);let t=GQ(e.schema,e.table);try{await Jw.deleteEnvironment(t,e.table)}catch(r){if(r.message==="invalid environment")jw.warn(`cannot delete environment for ${e.schema}.${e.table}, environment not found`);else throw r}try{let r=FQ(e.schema,e.table);await Jw.deleteEnvironment(r,e.table,!0)}catch(r){if(r.message==="invalid environment")jw.warn(`cannot delete environment for ${e.schema}.${e.table}, environment not found`);else throw r}}catch(t){throw t}}a(kQ,"lmdbDropTable");async function VQ(e){let t=new Xw(nr.SYSTEM_SCHEMA_NAME,nr.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,nr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_TABLE_KEY,`${e.schema}.${e.table}`,void 0,[nr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),r=Array.from(await eI(t)),n=[];for(let i=0;i<r.length;i++){let o=r[i];n.push(o.id)}if(n.length===0)return;let s=new Zw(nr.SYSTEM_SCHEMA_NAME,nr.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,n);await tI(s)}a(VQ,"deleteAttributesFromSystem");async function $Q(e){let t=new Xw(nr.SYSTEM_SCHEMA_NAME,nr.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,nr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY,e.table,void 0,[nr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY,nr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_KEY,nr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),r,n;try{r=Array.from(await eI(t))}catch(i){throw i}for(let i=0;i<r.length;i++){let o=r[i];o.name===e.table&&o.schema===e.schema&&(n=o)}if(!n)throw new Error(`${e.schema}.${e.table} was not found`);let s=new Zw(nr.SYSTEM_SCHEMA_NAME,nr.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,[n.id]);try{await tI(s)}catch(i){throw i}}a($Q,"dropTableFromSystem")});var sI=g((Gue,nI)=>{"use strict";var YQ=require("fs-extra"),KQ=Kn(),WQ=Jo(),QQ=Gc(),zQ=mp(),JQ=Bc(),jQ=ap(),XQ=Fc(),Ts=M(),{getSchemaPath:ZQ}=Ke(),{handleHDBError:ez,hdb_errors:tz}=ee(),{HDB_ERROR_MSGS:rz,HTTP_STATUS_CODES:nz}=tz;nI.exports=sz;async function sz(e){let t;try{t=await iz(e.schema);let r=new KQ(Ts.SYSTEM_SCHEMA_NAME,Ts.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,Ts.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_KEY,t,void 0,[Ts.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY]),n=Array.from(await XQ(r));for(let o=0;o<n.length;o++){let c={schema:t,table:n[o].name};try{await zQ(c)}catch(u){if(u.message!=="invalid environment")throw u}}let s=new QQ(Ts.SYSTEM_SCHEMA_NAME,Ts.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,[t]);await JQ(s);let i=ZQ(t);await YQ.remove(i)}catch(r){throw r}}a(sz,"lmdbDropSchema");async function iz(e){let t=new WQ(Ts.SYSTEM_SCHEMA_NAME,Ts.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,[e],[Ts.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY]),r,n;try{r=Array.from(await jQ(t))}catch(s){throw s}for(let[,s]of r)s.name===e&&(n=e);if(!n)throw ez(new Error,rz.SCHEMA_NOT_FOUND(e),nz.NOT_FOUND,void 0,void 0,!0);return n}a(iz,"validateDropSchema")});var Sp=g((Vue,iI)=>{"use strict";var pp=class{static{a(this,"CreateTableObject")}constructor(t,r,n){this.schema=t,this.table=r,this.hash_attribute=n}};iI.exports=pp});var aI=g((Kue,oI)=>{"use strict";var oz=require("fs-extra"),F_=$e(),{getTransactionAuditStorePath:az}=Ke(),Tp=lt(),Yue=Sp();oI.exports=cz;async function cz(e){let t;try{let r=az(e.schema,e.table);await oz.mkdirp(r),t=await F_.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{F_.createDBI(t,Tp.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,!1,!0),F_.createDBI(t,Tp.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE,!0,!1),F_.createDBI(t,Tp.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(cz,"createTransactionsAuditEnvironment")});var _I=g((Que,lI)=>{"use strict";var gp=M(),cI=$e(),uz=Ho(),{getSystemSchemaPath:lz,getSchemaPath:_z}=Ke(),dz=Ui(),fz=E_(),Rp=f_(),Ez=Y(),hz=aI(),Op=dz.hdb_table,uI=[];for(let e=0;e<Op.attributes.length;e++)uI.push(Op.attributes[e].attribute);lI.exports=mz;async function mz(e,t){let r=_z(t.schema,t.table),n=new Rp(t.schema,t.table,gp.TIME_STAMP_NAMES_ENUM.CREATED_TIME,void 0,!0),s=new Rp(t.schema,t.table,gp.TIME_STAMP_NAMES_ENUM.UPDATED_TIME,void 0,!0),i=new Rp(t.schema,t.table,t.hash_attribute,void 0,!1,!0);try{if(await cI.createEnvironment(r,t.table),e!==void 0){let o=await cI.openEnvironment(lz(),gp.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME);await uz.insertRecords(o,Op.hash_attribute,uI,[e]),n.skip_table_check=!0,s.skip_table_check=!0,i.skip_table_check=!0,await Ap(n),await Ap(s),await Ap(i)}await hz(t)}catch(o){throw o}}a(mz,"lmdbCreateTable");async function Ap(e){try{await fz(e)}catch(t){Ez.warn(`failed to create attribute ${e.attribute} due to ${t.message}`)}}a(Ap,"createAttribute")});var fI=g((Jue,dI)=>{"use strict";var pz=bc(),Sz=Cc(),Tz=M_(),kc=M(),gz=Ho().updateRecords,Rz=$e(),{getSchemaPath:Az}=Ke(),Oz=Pc(),bz=Y();dI.exports=Nz;async function Nz(e){try{let{schema_table:t,attributes:r}=pz(e);Sz(e,r,t.hash_attribute),e.schema!==kc.SYSTEM_SCHEMA_NAME&&(r.includes(kc.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||r.push(kc.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.includes(kc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||r.push(kc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let n=await Tz(e.hdb_auth_header,t,r),s=Az(e.schema,e.table),i=await Rz.openEnvironment(s,e.table),o=await gz(i,t.hash_attribute,r,e.records,e.__origin?.timestamp);try{await Oz(e,o)}catch(c){bz.error(`unable to write transaction due to ${c.message}`)}return{written_hashes:o.written_hashes,skipped_hashes:o.skipped_hashes,schema_table:t,new_attributes:n,txn_time:o.txn_time}}catch(t){throw t}}a(Nz,"lmdbUpdateRecords")});var hI=g((Xue,EI)=>{"use strict";var yz=M().OPERATIONS_ENUM,bp=class{static{a(this,"UpsertObject")}constructor(t,r,n,s=void 0){this.operation=yz.UPSERT,this.schema=t,this.table=r,this.records=n,this.__origin=s}};EI.exports=bp});var pI=g((tle,mI)=>{"use strict";var ele=hI(),wz=bc(),Iz=Cc(),Cz=M_(),Vc=M(),Dz=Ho().upsertRecords,Lz=$e(),{getSchemaPath:Mz}=Ke(),Uz=Pc(),Pz=Y(),{handleHDBError:vz,hdb_errors:Bz}=ee();mI.exports=Hz;async function Hz(e){let t;try{t=wz(e)}catch(u){throw vz(u,u.message,Bz.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0)}let{schema_table:r,attributes:n}=t;Iz(e,n,r.hash_attribute),e.schema!==Vc.SYSTEM_SCHEMA_NAME&&(n.includes(Vc.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||n.push(Vc.TIME_STAMP_NAMES_ENUM.CREATED_TIME),n.includes(Vc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||n.push(Vc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let s=await Cz(e.hdb_auth_header,r,n),i=Mz(e.schema,e.table),o=await Lz.openEnvironment(i,e.table),c=await Dz(o,r.hash_attribute,n,e.records,e.__origin?.timestamp);try{await Uz(e,c)}catch(u){Pz.error(`unable to write transaction due to ${u.message}`)}return{written_hashes:c.written_hashes,schema_table:r,new_attributes:s,txn_time:c.txn_time}}a(Hz,"lmdbUpsertRecords")});var TI=g((nle,SI)=>{"use strict";var Np=class{static{a(this,"DeleteBeforeObject")}constructor(t,r,n){this.schema=t,this.table=r,this.timestamp=n}};SI.exports=Np});var RI=g((ile,gI)=>{"use strict";var yp=class{static{a(this,"DeleteAuditLogsBeforeResults")}constructor(t=void 0,r=void 0,n=0){this.start_timestamp=t,this.end_timestamp=r,this.transactions_deleted=n}};gI.exports=yp});var bI=g((cle,OI)=>{"use strict";var wp=$e(),{getTransactionAuditStorePath:xz}=Ke(),ale=TI(),$c=lt(),qz=J(),AI=RI(),Fz=require("util").promisify,Gz=Fz(setTimeout),kz=1e4,Vz=100;OI.exports=$z;async function $z(e){let t=xz(e.schema,e.table),r=await wp.openEnvironment(t,e.table,!0),n=wp.listDBIs(r);wp.initializeDBIs(r,$c.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,n);let s,i=new AI;do s=await Yz(r,e.timestamp),i.start_timestamp===void 0&&(i.start_timestamp=s.start_timestamp),s.end_timestamp!==void 0&&(i.end_timestamp=s.end_timestamp),i.transactions_deleted+=s.transactions_deleted,await Gz(Vz);while(s.transactions_deleted>0);return i}a($z,"deleteAuditLogsBefore");async function Yz(e,t){let r=new AI;try{let n=e.dbis[$c.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP],s;for(let{key:i,value:o}of n.getRange({start:!1})){if(i>=t)break;r.start_timestamp===void 0&&(r.start_timestamp=i),s=n.remove(i);let c=o[$c.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME];qz.isEmpty(c)||(s=e.dbis[$c.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].remove(c,i));for(let u=0;u<o.hash_values.length;u++)s=e.dbis[$c.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE].remove(o.hash_values[u],i);if(r.transactions_deleted++,r.end_timestamp=i,r.transactions_deleted>kz)break}return await s,r}catch(n){throw n}}a(Yz,"deleteTransactions")});var yI=g((lle,NI)=>{"use strict";var Ip=class{static{a(this,"DropAttributeObject")}constructor(t,r,n){this.schema=t,this.table=r,this.attribute=n}};NI.exports=Ip});var II=g((fle,wI)=>{"use strict";var Kz=Kn(),Wz=Gc(),dle=yI(),Wn=M(),Qz=J(),Cp=$e(),zz=Ui(),Jz=Fc(),jz=Bc(),{getSchemaPath:Xz}=Ke();wI.exports=Zz;async function Zz(e,t=!0){let r;e.schema===Wn.SYSTEM_SCHEMA_NAME?r=zz[e.table]:r=global.hdb_schema[e.schema][e.table];let n=await tJ(e),s=Xz(e.schema,e.table),i=await Cp.openEnvironment(s,e.table);return t===!0&&await eJ(e,i,r.hash_attribute),Cp.dropDBI(i,e.attribute),n}a(Zz,"lmdbDropAttribute");async function eJ(e,t,r){let n=Cp.openDBI(t,r),s,i=e.attribute;for(let{key:o,value:c,version:u}of n.getRange({start:!1,versions:!0})){let _={};for(let l in c)l!==i&&(_[l]=c[l]);s=t.dbis[r].put(o,_,u)}await s}a(eJ,"removeAttributeFromAllObjects");async function tJ(e){let t=new Kz(Wn.SYSTEM_SCHEMA_NAME,Wn.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,Wn.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_TABLE_KEY,`${e.schema}.${e.table}`,void 0,[Wn.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY,Wn.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ATTRIBUTE_KEY]),n=Array.from(await Jz(t)).filter(o=>o[Wn.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ATTRIBUTE_KEY]===e.attribute);if(Qz.isEmptyOrZeroLength(n))throw new Error(`Attribute '${e.attribute}' was not found in '${e.schema}.${e.table}'`);let s=n.map(o=>o[Wn.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),i=new Wz(Wn.SYSTEM_SCHEMA_NAME,Wn.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,s);return jz(i)}a(tJ,"dropAttributeFromSystem")});var PI=g((mle,UI)=>{"use strict";var Dp=$e(),jo=lt(),hle=Ir(),Lp=M(),CI=J(),{getTransactionAuditStorePath:rJ}=Ke(),nJ=Qo(),G_=Yo(),sJ=Y();UI.exports=iJ;async function iJ(e){let t=rJ(e.schema,e.table),r=await Dp.openEnvironment(t,e.table,!0),n=Dp.listDBIs(r);Dp.initializeDBIs(r,jo.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,n);let s;switch(e.search_type){case Lp.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.TIMESTAMP:return DI(r,e.search_values);case Lp.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.HASH_VALUE:return s=global.hdb_schema[e.schema][e.table].hash_attribute,aJ(r,e.search_values,s);case Lp.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.USERNAME:return oJ(r,e.search_values);default:return DI(r)}}a(iJ,"readAuditLog");function DI(e,t=[0,Date.now()]){CI.isEmpty(t[0])&&(t[0]=0),CI.isEmpty(t[1])&&(t[1]=Date.now());let r=e.dbis[jo.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP],n;for(let s of r.getKeys({start:t[1]}))if(s!==t[1]){n=s;break}return r.getRange({start:t[0],end:n}).map(({value:s})=>Object.assign(new G_,s))}a(DI,"searchTransactionsByTimestamp");function oJ(e,t=[]){let r=new Map;for(let n=0;n<t.length;n++){let s=t[n],i=[];for(let o of e.dbis[jo.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].getValues(s))i.push(o);r.set(s,MI(e,i))}return Object.fromEntries(r)}a(oJ,"searchTransactionsByUsername");function aJ(e,t,r){let n=new Map;for(let c=0,u=t.length;c<u;c++){let _=t[c],l=nJ.equals(e,jo.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,jo.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE,_);for(let{value:d}of l){let f=Number(d);n.has(f)?n.get(f).push(_.toString()):n.set(f,[_.toString()])}}let s=Array.from(n.keys()),i=MI(e,s),o=new Map;for(let c=0;c<i.length;c++){let u=i[c],_=u.timestamp,l=n.get(_);LI(u,"records",r,l,o),LI(u,"original_records",r,l,o)}return Object.fromEntries(o)}a(aJ,"searchTransactionsByHashValues");function LI(e,t,r,n,s){let i=e.timestamp;if(e[t])for(let o=0;o<e[t].length;o++){let c=e[t][o],u=c[r].toString();if(n.indexOf(u)>=0)if(s.has(u)){let _=s.get(u),l=_[_.length-1];if(l.timestamp===i)l[t]=[c];else{let d=new G_(e.operation,e.user_name,i,void 0);d[t]=[c],_.push(d)}}else{let _=new G_(e.operation,e.user_name,i,void 0);_[t]=[c],s.set(u,[_])}}}a(LI,"loopRecords");function MI(e,t){let r=[];try{let n=e.dbis[jo.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP];for(let s=0;s<t.length;s++)try{let i=n.get(t[s]);if(i){let o=Object.assign(new G_,i);r.push(o)}}catch(i){sJ.warn(i)}return r}catch(n){throw n}}a(MI,"batchSearchTransactions")});var BI=g((gle,vI)=>{"use strict";var{getSchemaPath:Sle}=Ke(),Tle=$e(),{database:cJ}=(be(),te(qe));vI.exports={writeTransaction:uJ};async function uJ(e,t,r){return cJ({database:e,table:t}).transaction(r)}a(uJ,"writeTransaction")});var FI=g((Ale,qI)=>{"use strict";var{getSchemaPath:HI}=Ke(),xI=$e();qI.exports={flush:lJ,resetReadTxn:_J};async function lJ(e,t){return(await xI.openEnvironment(HI(e,t),t.toString())).flushed}a(lJ,"flush");async function _J(e,t){try{(await xI.openEnvironment(HI(e,t),t.toString())).resetReadTxn()}catch{}}a(_J,"resetReadTxn")});var $I=g((ble,VI)=>{"use strict";var{Readable:dJ}=require("stream"),{getDatabases:fJ}=(be(),te(qe)),{readSync:EJ,openSync:hJ,createReadStream:GI}=require("fs"),{open:mJ}=require("lmdb"),kI=n_(),pJ=i_(),{AUDIT_STORE_OPTIONS:SJ}=(Li(),te(YI)),{INTERNAL_DBIS_NAME:TJ,AUDIT_STORE_NAME:gJ}=lt();VI.exports=AJ;var Mp=32768,RJ=100;async function AJ(e){let t=e.database||e.schema||"data",r=fJ()[t],n=new Date().toISOString(),s=e.tables||e.table&&[e.table];if(s){let _=r[s[0]];if(!_)throw new Error(`Can not find table ${s[0]}`);let l=_.dbisDB,d=mJ({noSync:!0,maxDbs:pJ.MAX_DBS}),f,E=d.openDB(TJ,new kI(!1)),h=l.useReadTransaction(),p=0,S=a(async function(A,b){b.encoding="binary",b.encoder=void 0;let H=d.openDB(A,b),q=l.openDB(A,b);for(let{key:v,version:P,value:z}of q.getRange({transaction:h,versions:q.useVersions}))f=H.put(v,z,P),p++%RJ===0&&(await new Promise(W=>setTimeout(W,20)),h.openTimer&&(h.openTimer=0))},"copyDatabase");for(let{key:A,value:b}of l.getRange({transaction:h,start:!1}))if(s.some(H=>A.startsWith?.(H+"/"))){E.put(A,b);let[,H]=A.split("/"),q=!H,v=new kI(!q,q);await S(A,v)}e.include_audit&&await S(gJ,Object.assign({},SJ)),await f;let T=GI(d.path);return T.headers=u(),T.on("close",()=>{h.done(),d.close()}),T}let o=r[Object.keys(r)[0]].primaryStore,c=hJ(o.path);return o.transaction(()=>{let _=Buffer.alloc(Mp);EJ(c,_,0,Mp),o.resetReadTxn();let l=o.useReadTransaction();l.renew();let d=GI(null,{fd:c,start:Mp}),f=new dJ.from(async function*(){yield _;for await(let E of d)l.openTimer&&(l.openTimer=0),yield E;l.done()}());return f.headers=u(),f});function u(){let _=new Map;return _.set("content-type","application/octet-stream"),_.set("content-disposition",`attachment; filename="${t}"`),_.set("date",n),_}}a(AJ,"getBackup")});var QI=g((yle,WI)=>{"use strict";var OJ=Y(),{handleHDBError:bJ}=ee(),NJ=Nb(),yJ=E_(),wJ=ep(),IJ=sw(),CJ=Bc(),DJ=ap(),LJ=Dw(),MJ=qw(),UJ=Fc(),PJ=Ww(),vJ=sI(),BJ=_I(),HJ=fI(),xJ=pI(),qJ=bI(),FJ=mp(),GJ=II(),kJ=PI(),VJ=BI(),KI=FI(),$J=$I(),Up=class extends NJ{static{a(this,"LMDBBridge")}async searchByConditions(t){return PJ(t)}async getDataByHash(t){return await DJ(t)}async searchByHash(t){return await LJ(t)}async getDataByValue(t,r){return await MJ(t,r)}async searchByValue(t){return await UJ(t)}async createSchema(t){return await IJ(t)}async dropSchema(t){return await vJ(t)}async createTable(t,r){return await BJ(t,r)}async dropTable(t){return await FJ(t)}async createAttribute(t){return await yJ(t)}async createRecords(t){return await wJ(t)}async updateRecords(t){return await HJ(t)}async upsertRecords(t){try{return await xJ(t)}catch(r){throw bJ(r,null,null,OJ.ERR,r)}}async deleteRecords(t){return await CJ(t)}async dropAttribute(t){return await GJ(t)}async deleteAuditLogsBefore(t){return await qJ(t)}async readAuditLog(t){return await kJ(t)}writeTransaction(t,r,n){return VJ.writeTransaction(t,r,n)}flush(t,r){return KI.flush(t,r)}resetReadTxn(t,r){return KI.resetReadTxn(t,r)}getBackup(t){return $J(t)}};WI.exports=Up});function QJ(){WJ=setInterval(function(){for(let e of Pp)if(e.stale){let t=e[Ne]?.url;zI.error(`Transaction was open too long and has been aborted, from table: ${e.lmdbDb?.name+(t?" path: "+t:"")}`),e.abort()}else e.stale=!0},KJ).unref()}var vp,zI,YJ,Pp,Ki,k_,KJ,WJ,Bp=Oe(()=>{vp=B(Ir()),zI=B(Y());gn();vo();YJ=100,Pp=new Set,Ki=class{static{a(this,"DatabaseTransaction")}writes=[];lmdbDb;readTxn;readTxnRefCount;readTxnsUsed;validated=0;timestamp=0;open=!0;getReadTxn(){if(this.readTxnRefCount=(this.readTxnRefCount||0)+1,this.stale&&(this.stale=!1),this.readTxn)return this.readTxn.openTimer&&(this.readTxn.openTimer=0),this.readTxn;if(!this.open)throw new Error("Can not start a read on a transaction that is no longer open");return this.readTxnsUsed=1,t_(()=>{this.readTxn=this.lmdbDb.useReadTransaction(),this.readTxn.openTimer&&(this.readTxn.openTimer=0)}),Pp.add(this),this.readTxn}useReadTxn(){return this.getReadTxn(),t_(()=>{this.readTxn.use()}),this.readTxnsUsed++,this.readTxn}doneReadTxn(){this.readTxn&&(this.readTxn.done(),--this.readTxnsUsed===0&&(Pp.delete(this),this.readTxn=null))}disregardReadTxn(){--this.readTxnRefCount===0&&this.readTxnsUsed===1&&this.doneReadTxn()}addWrite(t){if(!this.open&&!this.autoCommitMode)throw new Error("Can not use a transaction that is no longer open");this.writes.push(t),this.autoCommitMode&&this.commit()}removeWrite(t){let r=this.writes.indexOf(t);r>-1&&(this.writes[r]=null)}commit(t={}){let r=this.timestamp;r||(r=this.timestamp=t.timestamp=t.timestamp||(0,vp.getNextMonotonicTime)());let n=t.retries||0;if(this.validated<this.writes.length)try{let l=this.validated;this.validated=this.writes.length;for(let f=l;f<this.validated;f++)this.writes[f]?.validate?.(this.timestamp);let d;for(let f=l;f<this.validated;f++){let E=this.writes[f];E&&(E.before||E.beforeIntermediate)&&(d=!0)}if(d)return(async()=>{try{for(let f=0;f<2;f++){let E;for(let h=l;h<this.validated;h++){let p=this.writes[h];if(!p)continue;let S=p[f===0?"before":"beforeIntermediate"];if(S){let T=S();E?E.push?E.push(T):E=[E,T]:E=T}}E&&await(E.push?Promise.all(E):E)}}catch(f){throw this.abort(),f}return this.commit(t)})()}catch(l){throw this.abort(),l}n||this.doneReadTxn(),t?.prepared?.(),this.open=!1;let s,i=[],o=0;this.writes=this.writes.filter(l=>l);let c=a(l=>{l.commit(r,l.entry,n)},"doWrite"),u=a(()=>{let l=this.writes[o++];if(l)if(l.key){n>0&&(l.entry=l.store.getEntry(l.key));let d=l.store.ifVersion(l.key,l.entry?.version??null,u);s=s||d}else u();else for(let d of this.writes)c(d)},"nextCondition");if(this.writes.length<YJ>>n?u():s=this.writes[0].store.transaction(()=>{for(let l of this.writes)l.entry=l.store.getEntry(l.key),c(l);return!0}),s)return s.then(l=>l?(this.next&&i.push(this.next.commit(t)),t?.flush&&i.push(this.writes[0].store.flushed),this.writes=[],this.next=null,Promise.all(i).then(()=>({txnTime:r}))):(t?t.retries=n+1:t={retries:1},this.commit(t)));let _={txnTime:r};if(this.next){let l=this.next?.commit(t);if(l?.then)return l?.then(d=>({txnTime:r,next:d}));_.next=l}return _}abort(){for(;this.readTxnsUsed>0;)this.doneReadTxn();this.open=!1,this.writes=[]}},k_=class extends Ki{static{a(this,"ImmediateTransaction")}_timestamp;addWrite(t){super.addWrite(t),this.commit()}get timestamp(){return this._timestamp||(this._timestamp=(0,vp.getNextMonotonicTime)())}getReadTxn(){}},KJ=3e4;a(QJ,"startMonitoringTxns");QJ()});function We(e,t,r){if(!t)t=e,e={};else if(!e)e={};else if(e?.transaction?.open&&typeof t=="function")return t(e.transaction);if(typeof t!="function")throw new Error("Callback function must be provided to transaction");let n=e.transaction=new Ki;e.timestamp&&(n.timestamp=e.timestamp),n[Ne]=e,e.resourceCache||(e.resourceCache=[]);let s;try{if(s=t(n),s?.then)return s.then(i,o)}catch(c){o(c)}return i(s);function i(c){let u=n.commit(r?.resetTransaction?{prepared(){n.autoCommitMode=!0}}:{});return u.then?u.then(()=>c):c}function o(c){throw n.abort({}),c}}var JI,Wi=Oe(()=>{JI=require("../../index");gn();Bp();a(We,"transaction");(0,JI._assignPackageExport)("transaction",We);We.commit=function(e){let t=(e[Ne]||e)?.transaction;if(!t)throw new Error("No active transaction is available to commit");return t.commit()};We.abort=function(e){let t=(e[Ne]||e)?.transaction;if(!t)throw new Error("No active transaction is available to abort");return t.abort()}});var iC={};Ve(iC,{ResourceBridge:()=>qp});function Fp({get_attributes:e},t){if(e){if(e[0]==="*"){if(t.schemaDefined)return;e=t.attributes.map(r=>r.name)}return e.forceNulls=!0,e}}function XI(e,t){let r=Qn(e),n=Fp(e,r);if(!r)throw new Nn.ClientError(`Table ${e.table} not found`);let s;n&&r.attributes.length-n.length>2&&n.length<5&&(s=!0);let i={user:e.hdb_user},o;We(i,()=>new Promise(_=>o=_));let c=e.ids||e.hash_values,u=0;return{[Symbol.asyncIterator](){return{async next(){if(u<c.length){let _=c[u++],l=await r.get({id:_,lazy:s,select:n},i);return l=l&&$_(l),t?{value:{key:_,value:l}}:{value:l}}else return o(),{done:!0}},return(_){return o(),{value:_,done:!0}},throw(_){return o(),{done:!0}}}}}}function Qn(e){let t=e.database||e.schema||JJ,r=yn()[t];if(!r)throw(0,Nn.handleHDBError)(new Error,zJ.SCHEMA_NOT_FOUND(t),404);return r[e.table]}function ZI(e,t,r){let n=e.length+t.length,s=n===1?"record":"records";return{message:`${e.length} of ${n} ${s} successfully deleted`,deleted_hashes:e,skipped_hashes:t,txn_time:r}}async function*eC(e,t,r){let n;for await(let s of e.getHistory(t,r)){let i=s.type;i==="put"&&(i="upsert");let{id:o,version:c,value:u}=s;n?.timestamp===c?(n.hash_values.push(o),n.records.push(u)):(n&&(yield n),n={operation:i,user_name:s.user,timestamp:c,hash_values:[o],records:[u]})}n&&(yield n)}var tC,V_,Nn,rC,nC,wn,Hp,xp,sC,zJ,JJ,jJ,XJ,jI,qp,oC=Oe(()=>{"use strict";tC=B(QI()),V_=B(zo()),Nn=B(ee());be();rC=B(bc()),nC=B(Cc()),wn=B(M()),Hp=B(ps()),xp=B(bn()),sC=B(J());Wi();Y_();({HDB_ERROR_MSGS:zJ}=Nn.hdb_errors),JJ="data",jJ=1e4,XJ=10,qp=class extends tC.default{static{a(this,"ResourceBridge")}constructor(t){super(t),jI=this}async searchByConditions(t){t.select!==void 0&&(t.get_attributes=t.select);for(let o of t.conditions||[])o?.attribute!==void 0&&(o.search_attribute=o.attribute),o?.comparator!==void 0&&(o.search_type=o.comparator),o?.value!==void 0&&(o.search_value=o.value);let r=(0,V_.default)(t,"conditions");if(r)throw(0,Nn.handleHDBError)(r,r.message,400,void 0,void 0,!0);let n=Qn(t);if(!n)throw new Nn.ClientError(`Table ${t.table} not found`);let s=t.conditions.map(i);function i(o){return o.conditions?(o.conditions=o.conditions.map(i),o):{attribute:o.search_attribute??o.attribute,comparator:o.search_type??o.comparator,value:o.search_value!==void 0?o.search_value:o.value}}return a(i,"mapCondition"),n.search({conditions:s,operator:t.operator?t.operator.toLowerCase():void 0,limit:t.limit,offset:t.offset,reverse:t.reverse,select:Fp(t,n),sort:t.sort,allowFullScan:!0})}async createTable(t,r){let n=r.attributes,s=!!n,i=r.primary_key||r.hash_attribute;if(n)for(let o of n)o.is_primary_key?(o.isPrimaryKey=!0,delete o.is_primary_key):o.name===i&&i&&(o.isPrimaryKey=!0);else{if(!i)throw new Nn.ClientError("A primary key must be specified with a `primary_key` property or with `attributes`");n=[{name:i,isPrimaryKey:!0},{name:"__createdtime__",indexed:!0},{name:"__updatedtime__",indexed:!0}]}ot({database:r.schema,table:r.table,attributes:n,schemaDefined:s,expiration:r.expiration})}async createAttribute(t){return await Qn(t).addAttributes([{name:t.attribute,indexed:t.indexed??!0}]),`attribute ${t.schema}.${t.table}.${t.attribute} successfully created.`}async dropAttribute(t){let r=Qn(t);if(await r.removeAttributes([t.attribute]),!r.schemaDefined){let n=t.attribute,s,i=a((o,c,u)=>(c=Object.assign({},c),delete c[n],r.primaryStore.ifVersion(o,u,()=>r.primaryStore.put(o,c,u)).then(_=>{if(!_){let{value:l,version:d}=r.primaryStore.getEntry(o);return i(o,l,d)}})),"deleteRecord");for(let{key:o,value:c,version:u}of r.primaryStore.getRange({start:!0,versions:!0}))s=i(o,c,u),await new Promise(_=>setImmediate(_));await s}return`successfully deleted ${t.schema}.${t.table}.${t.attribute}`}dropTable(t){Qn(t).dropTable()}createSchema(t){return Yc({database:t.schema,table:null}),Hp.signalSchemaChange(new xp.SchemaEventMsg(process.pid,wn.OPERATIONS_ENUM.CREATE_SCHEMA,t.schema))}async dropSchema(t){await Gp(t.schema),Hp.signalSchemaChange(new xp.SchemaEventMsg(process.pid,wn.OPERATIONS_ENUM.DROP_SCHEMA,t.schema))}async updateRecords(t){return t.requires_existing=!0,this.upsertRecords(t)}async createRecords(t){return t.requires_no_existing=!0,jI.upsertRecords(t)}async upsertRecords(t){let{schema_table:r,attributes:n}=(0,rC.default)(t);(0,nC.default)(t,n,r.primaryKey);let s,i=yn()[t.schema][t.table],o={user:t.hdb_user,expiresAt:t.expiresAt};return We(o,async c=>{if(!i.schemaDefined){s=[];for(let l of n)i.attributes.find(f=>f.name==l)||s.push(l);s.length>0&&await i.addAttributes(s.map(l=>({name:l,indexed:!0})))}let u=[],_=[];for(let l of t.records){let d=await i.get(l[i.primaryKey],o);if(t.requires_existing&&!d||t.requires_no_existing&&d){_.push(l[i.primaryKey]);continue}d&&(d=$_(d));for(let f in l)if(Object.prototype.hasOwnProperty.call(l,f)){let E=l[f];if(typeof E=="function")try{let h=E([[d]]);Array.isArray(h)&&(E=h[0].func_val,l[f]=E)}catch(h){throw h.message+="Trying to set key "+f+" on object"+JSON.stringify(l),h}}if(d)for(let f in d)Object.prototype.hasOwnProperty.call(l,f)||(l[f]=d[f]);await i.put(l,o),u.push(l[i.primaryKey])}return{txn_time:c.timestamp,written_hashes:u,new_attributes:s,skipped_hashes:_}})}async deleteRecords(t){let r=yn()[t.schema][t.table],n={user:t.hdb_user};return We(n,async s=>{let i=t.hash_values||t.records.map(u=>u[r.primaryKey]),o=[],c=[];for(let u of i)await r.delete(u,n)?o.push(u):c.push(u);return ZI(o,c,s.timestamp)})}async deleteRecordsBefore(t){let r=yn()[t.schema][t.table];if(!r.createdTimeProperty)throw new Nn.ClientError("Table must have a '__createdtime__' attribute or @createdTime timestamp defined to perform this operation");let n=await r.search({conditions:[{attribute:r.createdTimeProperty.name,value:Date.parse(t.date),comparator:wn.VALUE_SEARCH_COMPARATORS.LESS}]}),s=!1,i=[],o=[],c=0,u=[],_=a(async()=>{let l=await this.deleteRecords({schema:t.schema,table:t.table,hash_values:u});i.push(...l.deleted_hashes),o.push(...l.skipped_hashes),await(0,sC.async_set_timeout)(XJ),u=[],s=!0},"chunkDelete");for await(let l of n)u.push(l[r.primaryKey]),c++,c%jJ===0&&await _();return u.length>0&&await _(),s?ZI(i,o,void 0):{message:"No records found to delete"}}searchByHash(t){t.select!==void 0&&(t.get_attributes=t.select);let r=(0,V_.default)(t,"hashes");if(r)throw r;return XI(t)}async getDataByHash(t){let r=new Map;t._returnKeyValue=!0;for await(let{key:n,value:s}of XI(t,!0))r.set(n,s);return r}searchByValue(t,r){if(r&&wn.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[r]===void 0)throw new Error(`Value search comparator - ${r} - is not valid`);t.select!==void 0&&(t.get_attributes=t.select),t.attribute!==void 0&&(t.search_attribute=condition.attribute),t.value!==void 0&&(t.search_value=condition.value);let n=(0,V_.default)(t,"value");if(n)throw n;let s=Qn(t);if(!s)throw new Nn.ClientError(`Table ${t.table} not found`);let i=t.search_value;i.includes?.("*")&&(i.startsWith("*")?i.endsWith("*")?i!=="*"&&(r="contains",i=i.slice(1,-1)):(r="ends_with",i=i.slice(1)):i.endsWith("*")&&(r="starts_with",i=i.slice(0,-1))),r===wn.VALUE_SEARCH_COMPARATORS.BETWEEN&&(i=[i,t.end_value]);let o=i==="*"?[]:[{attribute:t.search_attribute,value:i,comparator:r}];return s.search({conditions:o,allowFullScan:!0,limit:t.limit,offset:t.offset,reverse:t.reverse,select:Fp(t,s)})}async getDataByValue(t,r){let n=new Map,s=Qn(t);t.get_attributes&&!t.get_attributes.includes(s.primaryKey)&&t.get_attributes[0]!=="*"&&t.get_attributes.push(s.primaryKey);for await(let i of this.searchByValue(t,r))n.set(i[s.primaryKey],i);return n}resetReadTxn(t,r){Qn({schema:t,table:r})?.primaryStore.resetReadTxn()}async deleteAuditLogsBefore(t){return Qn(t).deleteHistory(t.timestamp)}async readAuditLog(t){let r=Qn(t),n={};switch(t.search_type){case wn.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.HASH_VALUE:for(let i of t.search_values)n[i]=(await r.getHistoryOfRecord(i)).map(o=>{let c=o.type;return c==="put"&&(c="upsert"),{operation:c,timestamp:o.version,user_name:o.user,hash_values:[i],records:[o.value]}});return n;case wn.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.USERNAME:let s=t.search_values;for await(let i of eC(r))s.includes(i.user_name)&&(n[i.user_name]||(n[i.user_name]=[])).push(i);return n;default:return eC(r,t.search_values?.[0],t.search_values?.[1])}}};a(Fp,"getSelect");a(XI,"getRecords");a(Qn,"getTable");a(ZI,"createDeleteResponse");a(eC,"groupRecordsInHistory")});var On=g((Gle,aC)=>{"use strict";var{ResourceBridge:ZJ}=(oC(),te(iC)),e2=Z();e2.initSync();var K_;function t2(){return K_||(K_=new ZJ,K_)}a(t2,"getBridge");aC.exports=t2()});var _C=g((Vle,lC)=>{"use strict";var cC=require("lodash"),Kc=require("mathjs"),r2=require("jsonata"),uC=J();lC.exports={distinct_array:e=>Array.isArray(e)&&e.length>1?cC.uniqWith(e,cC.isEqual):e,searchJSON:n2,mad:Wc.bind(null,Kc.mad),mean:Wc.bind(null,Kc.mean),mode:Wc.bind(null,Kc.mode),prod:Wc.bind(null,Kc.prod),median:Wc.bind(null,Kc.median)};function Wc(e,t,r,n){return n===1?t==null?[]:[t]:n===2?(t!=null&&r.push(t),r):r!=null&&r.length>0?e(r):null}a(Wc,"aggregateFunction");function n2(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(uC.isEmpty(this.__ala__.res)&&(this.__ala__.res={}),uC.isEmpty(this.__ala__.res[r])){let n=r2(e);this.__ala__.res[r]=n}return this.__ala__.res[r].evaluate(t)}a(n2,"searchJSON")});var fC=g((Yle,dC)=>{"use strict";var dt=require("moment"),kp="YYYY-MM-DDTHH:mm:ss.SSSZZ";dt.suppressDeprecationWarnings=!0;dC.exports={current_date:()=>dt().utc().format("YYYY-MM-DD"),current_time:()=>dt().utc().format("HH:mm:ss.SSS"),extract:(e,t)=>{switch(t.toLowerCase()){case"year":return dt(e).utc().format("YYYY");case"month":return dt(e).utc().format("MM");case"day":return dt(e).utc().format("DD");case"hour":return dt(e).utc().format("HH");case"minute":return dt(e).utc().format("mm");case"second":return dt(e).utc().format("ss");case"millisecond":return dt(e).utc().format("SSS");default:break}},date:e=>dt(e).utc().format(kp),date_format:(e,t)=>dt(e).utc().format(t),date_add:(e,t,r)=>dt(e).utc().add(t,r).valueOf(),date_sub:(e,t,r)=>dt(e).utc().subtract(t,r).valueOf(),date_diff:(e,t,r)=>{let n=dt(e).utc(),s=dt(t).utc();return r?n.diff(s,r,!0):n.diff(s)},now:()=>dt().utc().valueOf(),get_server_time:()=>dt().format(kp),offset_utc:(e,t)=>dt(e).utc().utcOffset(t).format(kp)}});var pC=g((Kle,mC)=>{"use strict";var s2=require("@turf/area"),i2=require("@turf/length"),o2=require("@turf/circle"),a2=require("@turf/difference"),c2=require("@turf/distance"),u2=require("@turf/boolean-contains"),l2=require("@turf/boolean-equal"),_2=require("@turf/boolean-disjoint"),d2=require("@turf/helpers"),EC=M(),Te=J(),gs=Y();mC.exports={geoArea:f2,geoLength:E2,geoCircle:h2,geoDifference:m2,geoDistance:hC,geoNear:p2,geoContains:S2,geoEqual:T2,geoCrosses:g2,geoConvert:R2};function f2(e){if(Te.isEmpty(e))return NaN;typeof e=="string"&&(e=Te.autoCastJSON(e));try{return s2.default(e)}catch(t){return gs.trace(t,e),NaN}}a(f2,"geoArea");function E2(e,t){if(Te.isEmpty(e))return NaN;typeof e=="string"&&(e=Te.autoCastJSON(e));try{return i2.default(e,{units:t||"kilometers"})}catch(r){return gs.trace(r,e),NaN}}a(E2,"geoLength");function h2(e,t,r){if(Te.isEmpty(e))return NaN;if(Te.isEmpty(t))return NaN;typeof e=="string"&&(e=Te.autoCastJSON(e));try{return o2.default(e,t,{units:r||"kilometers"})}catch(n){return gs.trace(n,e,t),NaN}}a(h2,"geoCircle");function m2(e,t){if(Te.isEmpty(e))return NaN;if(Te.isEmpty(t))return NaN;typeof e=="string"&&(e=Te.autoCastJSON(e)),typeof t=="string"&&(t=Te.autoCastJSON(t));try{return a2(e,t)}catch(r){return gs.trace(r,e,t),NaN}}a(m2,"geoDifference");function hC(e,t,r){if(Te.isEmpty(e))return NaN;if(Te.isEmpty(t))return NaN;typeof e=="string"&&(e=Te.autoCastJSON(e)),typeof t=="string"&&(t=Te.autoCastJSON(t));try{return c2.default(e,t,{units:r||"kilometers"})}catch(n){return gs.trace(n,e,t),NaN}}a(hC,"geoDistance");function p2(e,t,r,n){if(Te.isEmpty(e)||Te.isEmpty(t))return!1;if(Te.isEmpty(r))throw new Error("distance is required");if(typeof e=="string"&&(e=Te.autoCastJSON(e)),typeof t=="string"&&(t=Te.autoCastJSON(t)),isNaN(r))throw new Error("distance must be a number");try{return hC(e,t,n)<=r}catch(s){return gs.trace(s,e,t),!1}}a(p2,"geoNear");function S2(e,t){if(Te.isEmpty(e)||Te.isEmpty(t)||e.coordinates&&e.coordinates.includes?.(null)||t.coordinates&&t.coordinates.includes?.(null))return!1;typeof e=="string"&&(e=Te.autoCastJSON(e)),typeof t=="string"&&(t=Te.autoCastJSON(t));try{return u2.default(e,t)}catch(r){return gs.trace(r,e,t),!1}}a(S2,"geoContains");function T2(e,t){if(Te.isEmpty(e)||Te.isEmpty(t)||e.coordinates&&e.coordinates.includes?.(null)||t.coordinates&&t.coordinates.includes?.(null))return!1;typeof e=="string"&&(e=Te.autoCastJSON(e)),typeof t=="string"&&(t=Te.autoCastJSON(t));try{return l2.default(e,t)}catch(r){return gs.trace(r,e,t),!1}}a(T2,"geoEqual");function g2(e,t){if(Te.isEmpty(e)||Te.isEmpty(t)||e.coordinates&&e.coordinates.includes?.(null)||t.coordinates&&t.coordinates.includes?.(null))return!1;typeof e=="string"&&(e=Te.autoCastJSON(e)),typeof t=="string"&&(t=Te.autoCastJSON(t));try{return!_2.default(e,t)}catch(r){return gs.trace(r,e,t),!1}}a(g2,"geoCrosses");function R2(e,t,r){if(Te.isEmptyOrZeroLength(e))throw new Error("coordinates is required");if(Te.isEmpty(t))throw new Error("geo_type is required");if(Te.isEmpty(EC.GEO_CONVERSION_ENUM[t]))throw new Error(`geo_type of ${t} is invalid please use one of the following types: ${Object.keys(EC.GEO_CONVERSION_ENUM).join(",")}`);return typeof e=="string"&&(e=Te.autoCastJSON(e)),d2[t](e,r)}a(R2,"geoConvert")});var W_=g((Qle,SC)=>{var Qi=_C(),vr=fC(),zn=pC();SC.exports=e=>{e.aggr.mad=e.aggr.MAD=Qi.mad,e.aggr.mean=e.aggr.MEAN=Qi.mean,e.aggr.mode=e.aggr.MODE=Qi.mode,e.aggr.prod=e.aggr.PROD=Qi.prod,e.aggr.median=e.aggr.MEDIAN=Qi.median,e.fn.distinct_array=e.fn.DISTINCT_ARRAY=Qi.distinct_array,e.fn.search_json=e.fn.SEARCH_JSON=Qi.searchJSON,e.fn.__ala__=e,e.fn.current_date=e.fn.CURRENT_DATE=vr.current_date,e.fn.current_time=e.fn.CURRENT_TIME=vr.current_time,e.fn.extract=e.fn.EXTRACT=vr.extract,e.fn.date=e.fn.DATE=vr.date,e.fn.date_format=e.fn.DATE_FORMAT=vr.date_format,e.fn.date_add=e.fn.DATE_ADD=vr.date_add,e.fn.date_sub=e.fn.DATE_SUB=vr.date_sub,e.fn.date_diff=e.fn.DATE_DIFF=e.fn.datediff=e.fn.DATEDIFF=vr.date_diff,e.fn.now=e.fn.NOW=vr.now,e.fn.offset_utc=e.fn.OFFSET_UTC=vr.offset_utc,e.fn.get_server_time=e.fn.GET_SERVER_TIME=vr.get_server_time,e.fn.getdate=e.fn.GETDATE=vr.now,e.fn.current_timestamp=e.fn.CURRENT_TIMESTAMP=vr.now,e.fn.geoarea=e.fn.GEOAREA=e.fn.geoArea=zn.geoArea,e.fn.geocircle=e.fn.GEOCIRCLE=e.fn.geoCircle=zn.geoCircle,e.fn.geocontains=e.fn.GEOCONTAINS=e.fn.geoContains=zn.geoContains,e.fn.geoconvert=e.fn.GEOCONVERT=e.fn.geoConvert=zn.geoConvert,e.fn.geocrosses=e.fn.GEOCROSSES=e.fn.geoCrosses=zn.geoCrosses,e.fn.geodifference=e.fn.GEODIFFERENCE=e.fn.geoDifference=zn.geoDifference,e.fn.geodistance=e.fn.GEODISTANCE=e.fn.geoDistance=zn.geoDistance,e.fn.geoequal=e.fn.GEOEQUAL=e.fn.geoEqual=zn.geoEqual,e.fn.geolength=e.fn.GEOLENGTH=e.fn.geoLength=zn.geoLength,e.fn.geonear=e.fn.GEONEAR=e.fn.geoNear=zn.geoNear}});var AC=g((zle,RC)=>{"use strict";var Qc=require("lodash"),sr=require("alasql");sr.options.cache=!1;var A2=W_(),TC=require("clone"),Q_=require("recursive-iterator"),fe=Y(),Ce=J(),Xo=On(),O2=M(),{hdb_errors:b2}=ee(),{getDatabases:gC}=(be(),te(qe)),N2="IS NULL",In="There was a problem performing this search. Please check the logs and try again.";A2(sr);var Vp=class{static{a(this,"SQLSearch")}constructor(t,r){if(Ce.isEmpty(t))throw fe.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(),Ce.backtickASTSchemaItems(this.statement)}async search(){let t;try{let n=await this._checkEmptySQL();if(!Ce.isEmptyOrZeroLength(n))return fe.trace("No results returned from checkEmptySQL SQLSearch method."),n}catch(n){throw fe.error("Error thrown from checkEmptySQL in SQLSearch class method search."),fe.error(n),new Error(In)}try{let n=await this._getFetchAttributeValues();if(n)return n}catch(n){throw fe.error("Error thrown from getFetchAttributeValues in SQLSearch class method search."),fe.error(n),new Error(In)}if(Object.keys(this.data).length===0)return fe.trace('SQLSearch class field: "data" is empty.'),[];let r;try{r=await this._processJoins()}catch(n){throw fe.error("Error thrown from processJoins in SQLSearch class method search."),fe.error(n),new Error(In)}try{await this._getFinalAttributeData(r.existing_attributes,r.joined_length)}catch(n){throw fe.error("Error thrown from getFinalAttributeData in SQLSearch class method search."),fe.error(n),new Error(In)}try{return t=await this._finalSQL(),t}catch(n){throw fe.error("Error thrown from finalSQL in SQLSearch class method search."),fe.error(n),new Error(In)}}_getColumns(){let t=new Q_(this.statement);for(let{node:r,path:n}of t)r&&r.columnid&&(this.columns[n[0]]||(this.columns[n[0]]=[]),this.columns[n[0]].push(TC(r)))}_getTables(){let t=[];this.all_table_attributes.forEach(r=>{t.push(r.table)}),this.tables=Qc.uniqBy(t,r=>[r.databaseid,r.tableid,r.as].join()),this.tables.forEach(r=>{let n=`${r.databaseid}_${r.as?r.as:r.tableid}`;this.data[n]={},this.data[n].__hash_name=gC()[r.databaseid][r.tableid].primaryKey,this.data[n].__merged_data={},this.data[n].__merged_attributes=[],this.data[n].__merged_attr_map={}})}_conditionsToFetchAttributeValues(){if(Ce.isEmpty(this.statement.where)){fe.trace('AST "where" statement is empty.');return}let t=!1;for(let{node:r}of new Q_(this.statement.where))if(r&&r.op&&r.op==="OR"&&(t=!0),!Ce.isEmpty(r)&&r.right)if(Ce.isNotEmptyAndHasValue(r.right.value)){let n=Ce.autoCast(r.right.value);[!0,!1].indexOf(n)>=0&&(r.right=new sr.yy.LogicValue({value:n}))}else Array.isArray(r.right)&&r.right.forEach((n,s)=>{let i=Ce.autoCast(n.value);[!0,!1].indexOf(i)>=0?r.right[s]=new sr.yy.LogicValue({value:i}):n instanceof sr.yy.StringValue&&Ce.autoCasterIsNumberCheck(i.toString())&&(r.right[s]=new sr.yy.NumValue({value:i}))});if(t){fe.trace('Where clause contains "OR", exact match search not performed on attributes.');return}for(let{node:r}of new Q_(this.statement.where))if(r&&r.left&&r.right&&(r.left.columnid||r.right.value)&&r.op){let n=new Set,s=r.left.columnid?r.left:r.right,i=this._findColumn(s);if(!i)continue;let o=[i.table.databaseid,i.table.tableid,i.attribute].join("/");if(!Ce.isEmpty(O2.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[r.op])){if(Ce.isEmpty(this.comparator_search_values[o])&&(this.comparator_search_values[o]={ignore:!1,comparators:[]}),!this.comparator_search_values[o].ignore){if(Ce.isEmptyOrZeroLength(r.left.columnid)||Ce.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(Ce.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"=":!Ce.isEmpty(r.right.value)||!Ce.isEmpty(r.left.value)?n.add(Ce.isEmpty(r.right.value)?r.left.value:r.right.value):c=!0;break;case"IN":let u=Array.isArray(r.right)?r.right:r.left;for(let _=0;_<u.length;_++)if(u[_].value)n.add(u[_].value);else{c=!0;break}break;default:c=!0;break}this.exact_search_values[o].ignore=c,c?this.exact_search_values[o].values=new Set:this.exact_search_values[o].values=new Set([...this.exact_search_values[o].values,...n])}}}_setAliasesForColumns(){if(Ce.isEmptyOrZeroLength(this.all_table_attributes)&&Ce.isEmptyOrZeroLength(this.statement.from)&&Ce.isEmptyOrZeroLength(this.columns.columns))return;let t=[],r={};this.statement.columns.forEach((n,s)=>{if(n.columnid==="*"){t.push(s);return}if(n.aggregatorid&&(this.has_aggregator=!0),!n.aggregatorid&&!n.funcid)if(n.as_orig=n.as?n.as:n.columnid,this.statement.joins)if(r[n.as_orig]>=0){let i=r[n.as_orig]+1;n.as=`[${n.as_orig+i}]`,r[n.as_orig]=i}else n.as=`[${n.as_orig}]`,r[n.as_orig]=0;else n.as=`[${n.as_orig}]`;!n.aggregatorid&&n.funcid&&n.args&&(n.as_orig=n.as?n.as:n.toString().replace(/'/g,'"'),n.as=`[${n.as_orig}]`),n.aggregatorid&&n.expression.columnid!=="*"&&(n.as_orig=n.as?n.as:n.expression.tableid?`${n.aggregatorid}(${n.expression.tableid}.${n.expression.columnid})`:`${n.aggregatorid}(${n.expression.columnid})`,n.as=`[${n.as_orig}]`)}),this.statement.columns.length>1&&t.length>0&&Qc.pullAt(this.statement.columns,t)}_findColumn(t){let r=this.all_table_attributes.filter(n=>{if(t.columnid_orig&&t.tableid_orig)return(n.table.as===t.tableid_orig||n.table.tableid===t.tableid_orig)&&n.attribute===t.columnid_orig;if(t.tableid)return(n.table.as===t.tableid||n.table.tableid===t.tableid)&&n.attribute===t.columnid;let s=t.columnid_orig?t.columnid_orig:t.columnid;return n.attribute===s});if(Ce.isEmptyOrZeroLength(r)){let n=this.columns.columns.filter(s=>s.as?t.columnid===s.as:!1);Ce.isEmptyOrZeroLength(n)||(r=this.all_table_attributes.filter(s=>s.attribute===n[0].columnid&&n[0].tableid&&n[0].tableid===(s.table.as?s.table.as:s.table.tableid)))}return r[0]}async _checkEmptySQL(){let t=[];if(Ce.isEmptyOrZeroLength(this.all_table_attributes)&&!Ce.isEmptyOrZeroLength(this.columns.columns))return t;if(Ce.isEmptyOrZeroLength(this.all_table_attributes)&&Ce.isEmptyOrZeroLength(this.statement.from))try{let r=this._buildSQL(!1);t=await sr.promise(r)}catch(r){throw fe.error("Error thrown from AlaSQL in SQLSearch class method checkEmptySQL."),fe.error(r),new Error("There was a problem with the SQL statement")}return t}_addFetchColumns(t){t&&t.length>0&&t.forEach(r=>{let n=this._findColumn(r);n&&this.fetch_attributes.push(TC(n))})}_addColumnToMergedAttributes(t,r){this.data[t].__merged_attributes.push(r),this.data[t].__merged_attr_map[r]=this.data[t].__merged_attributes.length-1}_setMergedHashAttribute(t,r){this.data[t].__merged_data[r].splice(0,1,r)}_updateMergedAttribute(t,r,n,s){let i=this.data[t].__merged_attr_map[n];this.data[t].__merged_data[r].splice(i,1,s)}async _getFetchAttributeValues(){if(Ce.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(N2)>-1&&this.tables.forEach(s=>{let i={columnid:gC()[s.databaseid][s.tableid].primaryKey,tableid:s.tableid};this._addFetchColumns([i])}),this.statement.order&&(this._updateOrderByToAliases(),this._addNonAggregatorsToFetchColumns()),this.fetch_attributes=Qc.uniqBy(this.fetch_attributes,s=>[s.table.databaseid,s.table.as?s.table.as:s.table.tableid,s.attribute].join()),r)return await this._simpleSQLQuery();let n=this.fetch_attributes.reduce((s,i)=>{let o=`${i.table.databaseid}_${i.table.as?i.table.as:i.table.tableid}`,c=this.data[o].__hash_name;return s[o]||(s[o]=[],s[o].push(null),this._addColumnToMergedAttributes(o,c)),i.attribute!==c&&(s[o].push(null),this._addColumnToMergedAttributes(o,i.attribute)),s},{});for(let s of this.fetch_attributes){let i=`${s.table.databaseid}_${s.table.as?s.table.as:s.table.tableid}`,o=this.data[i].__hash_name,c={schema:s.table.databaseid,table:s.table.tableid,get_attributes:[s.attribute]},u=!1,_=[s.table.databaseid,s.table.tableid,s.attribute].join("/");if(s.attribute===o&&(u=!0),!Ce.isEmpty(this.exact_search_values[_])&&!this.exact_search_values[_].ignore&&!Ce.isEmptyOrZeroLength(this.exact_search_values[_].values))if(u)try{c.hash_values=Array.from(this.exact_search_values[_].values);let l=await Xo.getDataByHash(c);for(let d of c.hash_values)l.get(d)&&!this.data[i].__merged_data[d]&&(this.data[i].__merged_data[d]=[...n[i]],this._setMergedHashAttribute(i,d))}catch(l){throw fe.error("Error thrown from getDataByHash function in SQLSearch class method getFetchAttributeValues exact match."),fe.error(l),new Error(In)}else try{c.search_attribute=s.attribute,await Promise.all(Array.from(this.exact_search_values[_].values).map(async l=>{let d=Object.assign({},c);d.search_value=l;let f=await Xo.getDataByValue(d);for(let[E,h]of f)this.data[i].__merged_data[E]?this._updateMergedAttribute(i,E,s.attribute,h[s.attribute]):(this.data[i].__merged_data[E]=[...n[i]],this._updateMergedAttribute(i,E,s.attribute,h[s.attribute]),this._setMergedHashAttribute(i,E))}))}catch(l){throw fe.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues exact match."),fe.error(l),new Error(In)}else if(!Ce.isEmpty(this.comparator_search_values[_])&&!this.comparator_search_values[_].ignore&&!Ce.isEmptyOrZeroLength(this.comparator_search_values[_].comparators))try{let l=this.comparator_search_values[_].comparators;for(let d=0,f=l.length;d<f;d++){let E=l[d];c.search_attribute=E.attribute,c.search_value=E.search_value;let h=await Xo.getDataByValue(c,E.operation);if(u)for(let[p]of h)this.data[i].__merged_data[p]||(this.data[i].__merged_data[p]=[...n[i]],this._setMergedHashAttribute(i,p));else for(let[p,S]of h)this.data[i].__merged_data[p]?this._updateMergedAttribute(i,p,s.attribute,S[s.attribute]):(this.data[i].__merged_data[p]=[...n[i]],this._updateMergedAttribute(i,p,s.attribute,S[s.attribute]),this._setMergedHashAttribute(i,p))}}catch(l){throw fe.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues comparator search values."),fe.error(l),new Error(In)}else try{c.search_attribute=s.attribute,c.search_value="*";let l=await Xo.getDataByValue(c);if(u)for(let[d]of l)this.data[i].__merged_data[d]||(this.data[i].__merged_data[d]=[...n[i]],this._setMergedHashAttribute(i,d));else for(let[d,f]of l)this.data[i].__merged_data[d]?this._updateMergedAttribute(i,d,s.attribute,f[s.attribute]):(this.data[i].__merged_data[d]=[...n[i]],this._updateMergedAttribute(i,d,s.attribute,f[s.attribute]),this._setMergedHashAttribute(i,d))}catch(l){throw fe.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues no comparator search values."),fe.error(l),new Error(In)}}}_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 sr.yy.Column||(t=!1)}),t)}_updateOrderByToAliases(){this.statement.order.forEach(t=>{if(t.expression.aggregatorid){t.is_aggregator=!0;return}if(t.expression.value){t.is_ordinal=!0,this.has_ordinal=!0;return}else t.is_ordinal=!1;let r=this.statement.columns.filter(s=>{let i=s.aggregatorid?s.expression:s,o=s.aggregatorid?s.as_orig:i.as_orig;return t.expression.tableid?i.columnid_orig===t.expression.columnid_orig&&i.tableid_orig===t.expression.tableid_orig:i.columnid_orig===t.expression.columnid_orig||t.expression.columnid_orig===o});r[0]||r.push(this._findColumn(t.expression));let n=r[0];if(t.is_func=!!n.funcid,t.is_aggregator=!!n.aggregatorid,n.as)if(n.as&&!t.expression.tableid)t.expression.columnid=n.as,t.expression.columnid_orig=n.as_orig;else{let s=new sr.yy.Column;s.columnid=n.as,s.columnid_orig=n.as_orig,t.expression=s}else{t.initial_select_column=Object.assign(new sr.yy.Column,t.expression),t.initial_select_column.as=`[${t.expression.columnid_orig}]`,t.expression.columnid=t.initial_select_column.as;return}if(!t.is_aggregator){let s=t.is_func?new sr.yy.FuncValue:new sr.yy.Column;t.initial_select_column=Object.assign(s,n)}})}_addNonAggregatorsToFetchColumns(){let r=this.statement.order.filter(n=>!n.is_aggregator&&!n.is_ordinal).map(n=>n.is_func?{columnid:n.initial_select_column.args.filter(i=>!!i.columnid_orig)[0].columnid_orig}:{columnid:n.expression.columnid_orig});this._addFetchColumns(r)}async _processJoins(){let t=[],r=[],n=this.statement.from[0],s=[n],i=["? "+(n.as?" AS "+n.as:n.tableid)];t.push(Object.values(this.data[`${n.databaseid_orig}_${n.as?n.as_orig:n.tableid_orig}`].__merged_data)),this.statement.joins&&this.statement.joins.forEach(E=>{E.joinmode&&E.joinmode!=="INNER"&&(this.has_outer_join=!0),s.push(E.table);let h=E.joinmode+" JOIN ? AS "+(E.as?E.as:E.table.tableid);E.on&&(h+=" ON "+E.on.toString()),i.push(h),t.push(Object.values(this.data[`${E.table.databaseid_orig}_${E.table.as?E.table.as_orig:E.table.tableid_orig}`].__merged_data))});let o=[],c={};s.forEach(E=>{let h=this.data[`${E.databaseid_orig}_${E.as?E.as_orig:E.tableid_orig}`].__hash_name,p=E.as?E.as_orig:E.tableid_orig;o.push({key:`'${p}.${h}'`,schema:E.databaseid_orig,table:E.as?E.as_orig:E.tableid_orig,keys:new Set}),r.push(`${E.as?E.as:E.tableid}.\`${h}\` AS "${p}.${h}"`),c[E.as?E.as_orig:E.tableid_orig]=this.data[`${E.databaseid_orig}_${E.as?E.as_orig:E.tableid_orig}`].__merged_attributes});let u=this.statement.where?"WHERE "+this.statement.where:"";u=u.replace(/NOT\(NULL\)/g,"NOT NULL");let _="";this.statement.order&&!this.has_ordinal&&!this.has_aggregator&&!this.statement.group&&this.statement.limit&&(_="ORDER BY "+this.statement.order.toString(),this.statement.order.forEach(E=>{E.is_func?r.push(E.initial_select_column.toString()):E.initial_select_column.tableid?r.push(`${E.initial_select_column.tableid}.${E.initial_select_column.columnid} AS ${E.expression.columnid}`):r.push(`${E.initial_select_column.columnid} AS ${E.expression.columnid}`)}));let l="",d="";!this.has_aggregator&&!this.statement.group&&!this.has_ordinal&&!this.statement.joins&&(l=this.statement.limit?"LIMIT "+this.statement.limit:"",d=this.statement.offset?"OFFSET "+this.statement.offset:"");let f=[];try{let E=`SELECT ${r.join(", ")} FROM ${i.join(" ")} ${u} ${_} ${l} ${d}`,h=this._convertColumnsToIndexes(E,s);f=await sr.promise(h,t),t=null}catch(E){throw fe.error("Error thrown from AlaSQL in SQLSearch class method processJoins."),fe.error(E),new Error("There was a problem processing the data.")}if(f&&f.length>0){for(let E=0,h=f.length;E<h;E++){let p=f[E];o.forEach(S=>{p[S.key]!==null&&p[S.key]!==void 0&&S.keys.add(p[S.key])})}o.forEach(E=>{let h=Object.keys(this.data[`${E.schema}_${E.table}`].__merged_data),p=Qc.difference(h,[...E.keys].map(S=>S.toString()));for(let S=0,T=p.length;S<T;S++){let A=p[S];delete this.data[`${E.schema}_${E.table}`].__merged_data[A]}})}return{existing_attributes:c,joined_length:f?f.length:0}}async _getFinalAttributeData(t,r){if(r===0)return;let n=[],s=new Q_(this.columns);for(let{node:i}of s)if(i&&i.columnid){let o=this._findColumn(i);if(o){let c=o.table.as?o.table.as:o.table.tableid;(!t[c]||t[c].indexOf(o.attribute)<0)&&n.push(o)}}n=Qc.uniqBy(n,i=>[i.table.databaseid,i.table.as?i.table.as:i.table.tableid,i.attribute].join());try{await this._getData(n)}catch(i){throw fe.error("Error thrown from getData in SQLSearch class method getFinalAttributeData."),fe.error(i),new Error(In)}}async _getData(t){try{let r=t.reduce((n,s)=>{let i=`${s.table.databaseid}_${s.table.as?s.table.as:s.table.tableid}`;return n[i]?n[i].columns.push(s.attribute):n[i]={schema:s.table.databaseid,table:s.table.tableid,columns:[s.attribute]},n},{});for(let n in r){let s=r[n],i=this.data[n].__merged_data,o=[];for(let l in i)o.push(i[l][0]);this.data[n].__merged_attributes.push(...s.columns);let c={schema:s.schema,table:s.table,hash_values:o,get_attributes:s.columns},u=await Xo.getDataByHash(c),_=s.columns.length;for(let l=0,d=o.length;l<d;l++){let f=o[l],E=u.get(f);for(let h=0;h<_;h++){let p=s.columns[h],S=E[p]===void 0?null:E[p];this.data[n].__merged_data[f].push(S)}}}}catch(r){throw fe.error("Error thrown from getDataByHash function in SQLSearch class method getData."),fe.error(r),r}}async _finalSQL(){let t=[],r=this.statement.from[0];t.push(Object.values(this.data[`${r.databaseid_orig}_${r.as?r.as_orig:r.tableid_orig}`].__merged_data)),r.as=r.as?r.as:r.tableid,r.databaseid="",r.tableid="?",this.statement.joins&&this.statement.joins.forEach(s=>{s.as=s.as?s.as:s.table.tableid,t.push(Object.values(this.data[`${s.table.databaseid_orig}_${s.table.as?s.table.as_orig:s.table.tableid_orig}`].__merged_data)),s.table.databaseid="",s.table.tableid="?"}),this.statement.order&&this.statement.order.forEach(s=>{if(s.is_ordinal)return;this.statement.columns.filter(o=>{let c=o.aggregatorid?o.expression:o,u=o.aggregatorid?o.as_orig:c.as_orig;return s.expression.tableid?c.columnid_orig===s.expression.columnid_orig&&c.tableid_orig===s.expression.tableid_orig:c.columnid_orig===s.expression.columnid_orig||s.expression.columnid_orig===u}).length===0&&(s.expression.columnid=s.initial_select_column.columnid)}),!this.has_aggregator&&!this.statement.group&&!this.has_ordinal&&this.statement.limit&&!this.statement.joins&&(delete this.statement.limit,delete this.statement.offset);let n;try{let s=this._buildSQL();fe.trace(`Final SQL: ${s}`),n=await sr.promise(s,t),this.has_outer_join&&(n=this._translateUndefinedValues(n)),fe.trace(`Final AlaSQL results data included ${n.length} rows`)}catch(s){throw fe.error("Error thrown from AlaSQL in SQLSearch class method finalSQL."),fe.error(s),new Error("There was a problem running the generated sql.")}return n}_translateUndefinedValues(t){try{let r=[];for(let n of t){let s=Object.create(null);Object.keys(n).forEach(i=>{n[i]===void 0?s[i]=null:s[i]=n[i]}),r.push(s)}return r}catch(r){return fe.error(b2.HDB_ERROR_MSGS.OUTER_JOIN_TRANSLATION_ERROR),fe.trace(r.stack),t}}_buildSQL(t=!0){let r=this.statement.toString();return r=r.replace(/NOT\(NULL\)/g,"NOT NULL"),this.statement.columns.forEach(n=>{if(n.funcid&&n.as){let s=n.toString().replace(" AS "+n.as,"");r=r.replace(n.toString(),s)}}),t===!0?this._convertColumnsToIndexes(r,this.tables):r}_convertColumnsToIndexes(t,r){let n=t,s={};r.forEach(i=>{i.databaseid_orig?s[`${i.databaseid_orig}_${i.as?i.as_orig:i.tableid_orig}`]=i.as?i.as:i.tableid:s[`${i.databaseid}_${i.as?i.as:i.tableid}`]=`\`${i.as?i.as:i.tableid}\``});for(let i in this.data)this.data[i].__merged_attributes.forEach((o,c)=>{let u=s[i],_=new RegExp(`${u}.\`${o}\``,"g"),l=`${u}.[${c}]`;n=n.replace(_,l)});for(let i in this.data)this.data[i].__merged_attributes.forEach((o,c)=>{let u=new RegExp(`\`${o}\``,"g"),_=`[${c}]`;n=n.replace(u,_)});return n}async _simpleSQLQuery(){let t=this.statement.columns.reduce((n,s)=>(s.as_orig&&s.as_orig!=s.columnid_orig?n[s.columnid_orig]=s.as_orig:n[s.columnid_orig]||(n[s.columnid_orig]=s.columnid_orig),n),{}),r=this.fetch_attributes.reduce((n,s)=>{let i=`${s.table.databaseid}_${s.table.as?s.table.as:s.table.tableid}`;return n[i]||(n[i]={}),n[i][t[s.attribute]]=null,n},{});for(let n of this.fetch_attributes){let s=`${n.table.databaseid}_${n.table.as?n.table.as:n.table.tableid}`,i={schema:n.table.databaseid,table:n.table.tableid,get_attributes:[n.attribute]};try{i.search_attribute=n.attribute,i.search_value="*";let o=await Xo.getDataByValue(i);for(let[c,u]of o)this.data[s].__merged_data[c]||(u[n.attribute]===void 0&&(u[n.attribute]=null),this.data[s].__merged_data[c]=Object.assign({},r[s])),this.data[s].__merged_data[c][t[n.attribute]]=u[n.attribute]??null}catch(o){throw fe.error("There was an error when processing this SQL operation. Check your logs"),fe.error(o),new Error(In)}}return Object.values(Object.values(this.data)[0].__merged_data)}};RC.exports=Vp});var Xr=g((jle,OC)=>{"use strict";var y2=Ob();OC.exports={searchByConditions:I2,searchByHash:C2,searchByValue:D2,search:L2};var $p=On(),{transformReq:Yp}=J(),w2=AC();async function I2(e){return Yp(e),$p.searchByConditions(e)}a(I2,"searchByConditions");async function C2(e){Yp(e),e.ids&&(e.hash_values=e.ids);let t=[];for await(let r of $p.searchByHash(e))r&&t.push(r);return t}a(C2,"searchByHash");async function D2(e){Yp(e),e.hasOwnProperty("desc")===!0&&(e.reverse=e.desc);let t=[];for await(let r of $p.searchByValue(e))t.push(r);return t}a(D2,"searchByValue");function L2(e,t){try{let r=new y2(e);r.validate(),new w2(r.statement,r.attributes).search().then(s=>{t(null,s)}).catch(s=>{t(s,null)})}catch(r){return t(r)}}a(L2,"search")});var z_=g((Zle,bC)=>{"use strict";var M2=On();bC.exports={writeTransaction:U2};function U2(e,t,r){return M2.writeTransaction(e,t,r)}a(U2,"writeTransaction")});var IC=g((r_e,wC)=>{"use strict";var P2=Xr(),v2=ms(),NC=Y(),B2=Zr(),t_e=z_(),H2=require("clone"),Wp=require("alasql"),x2=W_(),yC=require("util"),q2=yC.promisify(v2.getTableSchema),F2=yC.promisify(P2.search),G2=M(),Kp=J();x2(Wp);wC.exports={update:V2};var k2="There was a problem performing this update. Please check the logs and try again.";async function V2({statement:e,hdb_user:t}){let r=await q2(e.table.databaseid,e.table.tableid),n=$2(e.columns);Kp.backtickASTSchemaItems(e);let{table:s,where:i}=e,o=H2(s),c=Kp.isEmpty(i)?"":` WHERE ${i.toString()}`,u=`SELECT ${r.hash_attribute} FROM ${s.toString()} ${c}`,_=Wp.parse(u).statements[0],l=await F2(_),d=Y2(n,l);return K2(o,d,t)}a(V2,"update");function $2(e){try{let t={};return e.forEach(r=>{"value"in r.expression?t[r.column.columnid]=r.expression.value??null:t[r.column.columnid]=Wp.compile(`SELECT ${r.expression.toString()} AS [${G2.FUNC_VAL}] FROM ?`)}),t}catch(t){throw NC.error(t),new Error(k2)}}a($2,"createUpdateRecord");function Y2(e,t){return Kp.isEmptyOrZeroLength(t)?[]:t.map(r=>Object.assign(r,e))}a(Y2,"buildUpdateRecords");async function K2(e,t,r){let n={operation:"update",schema:e.databaseid_orig,table:e.tableid_orig,records:t,hdb_user:r},s=await B2.update(n);try{delete s.new_attributes,delete s.txn_time}catch(i){NC.error(`Error delete new_attributes from update response: ${i}`)}return s}a(K2,"updateRecords")});var DC=g((o_e,CC)=>{var W2=require("alasql"),Q2=Xr(),z2=Y(),J2=On(),zp=require("util"),Qp=J(),j2=M(),X2=ms(),s_e=z_(),i_e=Zr(),Z2="record",e4="successfully deleted",t4=zp.callbackify(i4),r4=zp.promisify(Q2.search),n4=zp.promisify(X2.getTableSchema);CC.exports={convertDelete:t4};function s4(e){return`${e.deleted_hashes.length} ${Z2}${e.deleted_hashes.length===1?"":"s"} ${e4}`}a(s4,"generateReturnMessage");async function i4({statement:e,hdb_user:t}){let r=await n4(e.table.databaseid,e.table.tableid);Qp.backtickASTSchemaItems(e);let{table:n,where:s}=e,i=Qp.isEmpty(s)?"":` WHERE ${s.toString()}`,o=`SELECT ${r.hash_attribute} FROM ${n.toString()} ${i}`,c=W2.parse(o).statements[0],u={operation:j2.OPERATIONS_ENUM.DELETE,schema:n.databaseid_orig,table:n.tableid_orig,hdb_user:t};try{u.records=await r4(c);let _=await J2.deleteRecords(u);return Qp.isEmptyOrZeroLength(_.message)&&(_.message=s4(_)),delete _.txn_time,_}catch(_){throw z2.error(_),_.hdb_code?_.message:_}}a(i4,"convertDelete")});var vC=g((c_e,PC)=>{"use strict";var o4=vi(),{hdb_errors:LC}=ee(),{getDatabases:MC}=(be(),te(qe));PC.exports={checkSchemaExists:UC,checkSchemaTableExists:a4,schema_describe:o4};async function UC(e){if(!MC()[e])return LC.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}a(UC,"checkSchemaExists");async function a4(e,t){let r=await UC(e);if(r)return r;if(!MC()[e][t])return LC.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(a4,"checkSchemaTableExists")});var zc=g((l_e,c4)=>{c4.exports={name:"harperdb",version:"4.3.0-beta.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:{"minimum-node":"16.0.0","go-lang":"1.21.1","nats-server":"2.10.1"},exports:{".":"./index.js"},homepage:"https://www.harperdb.io/",bugs:"support@harperdb.io",author:{name:"HarperDB",email:"support@harperdb.io"},license:"SEE LICENSE IN LICENSE",scripts:{submodules:"git submodule update --init --recursive",build:"eslint -c ./.eslintbuild bin/ dataLayer/ security/ server/ sqlTranslator/ upgrade/ utility/ validation/",pretty:"eslint --fix bin/ dataLayer/ security/ server/ sqlTranslator/ upgrade/ utility/ validation/","cover:test":"pm2 kill && rimraf ./.nyc_output/* && node utility/devops/register.js --reset_license && nyc --no-clean --reporter=lcovonly npm run test:apitests && nyc --no-clean --reporter=lcovonly npm run test:resources && nyc --no-clean --reporter=lcovonly npm run test:logging && nyc --no-clean --reporter=lcovonly npm run test:upgrade && nyc --no-clean --reporter=lcovonly npm run test:nats && nyc --no-clean --reporter=lcovonly npm run test:cfserver && nyc --no-clean --reporter=lcovonly npm run test:hdbserver && nyc --no-clean --reporter=lcovonly npm run test:bin && nyc --no-clean --reporter=lcovonly npm run test:main && nyc merge .nyc_output coverage.json && node ./utility/devops/register.js --reset_license",test:"pm2 kill && rimraf ./.nyc_output/* && node utility/devops/register.js --reset_license && npm run test:apitests && npm run test:resources && npm run test:logging && npm run test:upgrade && npm run test:nats && npm run test:cfserver && npm run test:hdbserver && npm run test:bin && npm run test:main && nyc merge .nyc_output coverage.json && node ./utility/devops/register.js --reset_license","test:resources":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/resources/**/*.js' --config '../unitTests/.mocharc.json'","test:bin":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/bin/**/*.js' --config '../unitTests/.mocharc.json'","test:main":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/**/*.js' --config '../unitTests/.mocharc-main.json'","test:lmdbbridge":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/dataLayer/harperBridge/lmdbBridge/**/*.js' --config '../unitTests/.mocharc.json'","test:lmdbutility":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/utility/lmdb/**/*.js' --config '../unitTests/.mocharc.json'","test:hdbserver":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/server/harperdb/hdbServer-test.js' --config '../unitTests/.mocharc.json'","test:cfserver":"npm run submodules && cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/server/fastifyRoutes/customFunctionsServer-test.js' --config '../unitTests/.mocharc.json'","test:nats":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/server/nats/**/*.js' --config '../unitTests/.mocharc.json'","test:upgrade":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/upgrade/**/*.js' --config '../unitTests/.mocharc.json'","test:apitests":"pm2 kill && cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/apiTests/**/*-test.mjs' --config '../unitTests/.mocharc.json'","test:logging":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/utility/logging/*.js' --config '../unitTests/.mocharc.json'","test:ci":" cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/**/*.js' --retries 3 --config '../unitTests/.mocharc-main.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/dataLayer/harperBridge/lmdbBridge/**/*.js' --parallel --retries 3 --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/utility/lmdb/**/*.js' --parallel --retries 3 --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/server/harperdb/hdbServer-test.js' --parallel --retries 3 --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/server/customFunctions/customFunctionsServer-test.js' --parallel --retries 3 --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/upgrade/**/*.js' --parallel --retries 3 --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/server/nats/**/*.js' --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter","hdb-check":"./utility/devops/hdb-check.sh","download-prebuilds":"node ./utility/devops/build/download-prebuilds.js",prebuild:"date",postinstall:"node ./launchServiceScripts/launchInstallNATSServer.js",build_nats_dependency:"node ./utility/devops/nats/builder.js",coverage:"nyc --reporter=lcov npm test"},dependencies:{"@aws-sdk/abort-controller":"3.374.0","@aws-sdk/client-s3":"3.477.0","@aws-sdk/lib-storage":"3.477.0","@endo/static-module-record":"^1.0.0","@fastify/autoload":"5.7.1","@fastify/compress":"~6.5.0","@fastify/cors":"~8.5.0","@fastify/static":"~6.11.2","@turf/area":"6.5.0","@turf/boolean-contains":"6.5.0","@turf/boolean-disjoint":"6.5.0","@turf/boolean-equal":"6.5.0","@turf/circle":"6.5.0","@turf/difference":"6.5.0","@turf/distance":"6.5.0","@turf/helpers":"6.5.0","@turf/length":"6.5.0",alasql:"4.1.10","cbor-x":"1.5.4",chalk:"4.1.2","cli-progress":"3.12.0",clone:"2.1.2","fast-glob":"3.3.1",fastify:"~4.25.1","fastify-plugin":"~4.5.1","fs-extra":"11.2.0",graphql:"^16.8.1","human-readable-ids":"1.0.4",inquirer:"8.2.6","is-number":"7.0.0",joi:"17.11.0","json-bigint-fixes":"1.1.0",json2csv:"5.0.7",jsonata:"1.8.6",jsonwebtoken:"9.0.2",lmdb:"2.9.3-beta.5-debug",lodash:"4.17.21",mathjs:"11.11.2",minimist:"1.2.8",mkcert:"1.5.1",moment:"2.29.4","mqtt-packet":"~8.2.1",msgpackr:"1.10.1",nats:"2.17.0",needle:"3.2.0","node-stream-zip":"1.15.0","node-unix-socket":"0.2.5","normalize-path":"^3.0.0",ora:"5.4.1","ordered-binary":"1.5.1",papaparse:"5.4.1",passport:"0.6.0","passport-http":"0.3.0","passport-local":"1.0.0",pino:"8.16.0",pm2:"5.3.0",prompt:"1.3.0","properties-reader":"2.3.0","recursive-iterator":"3.3.0",semver:"7.5.4",send:"^0.18.0","serve-static":"1.15.0",ses:"1.0.0","stream-chain":"2.2.5","stream-json":"1.8.0",systeminformation:"5.21.20","tar-fs":"2.1.1",ulidx:"0.5.0",uuid:"9.0.1","validate.js":"0.13.1",ws:"8.15.1",yaml:"2.3.4"},devDependencies:{"@tsconfig/node16":"^1.0.3","@types/node":"latest","@typescript-eslint/eslint-plugin":"^5.55.0","@typescript-eslint/parser":"^5.55.0",axios:"1.6.2",chai:"4.3.7","chai-integer":"0.1.0",esbuild:"^0.19.1",eslint:"8.22.0","eslint-config-prettier":"8.3.0","eslint-plugin-prettier":"3.4.1","eslint-plugin-radar":"0.2.1",eventsource:"^2.0.2","hook-std":"3.0.0","intercept-stdout":"0.1.2",mocha:"^10.2.0","mocha-teamcity-reporter":"3.0.0","mock-require":"3.0.3","mock-stdin":"1.0.0",mqtt:"~4.3.7",newman:"5.3.2","newman-reporter-html":"1.0.5","newman-reporter-htmlextra":"^1.22.11","newman-reporter-teamcity":"^0.1.12","node-fetch":"2.6.7",nyc:"15.1.0",prettier:"2.8.4",rewire:"5.0.0",rimraf:"3.0.2",sinon:"10.0.0","sinon-chai":"3.7.0","source-map-support":"^0.5.21",typescript:"^5.3.3","why-is-node-still-running":"^1.0.0"},overrides:{"eslint-plugin-radar":{eslint:"8.22.0"},"newman-reporter-html":{newman:"5.3.2"},alasql:{xlsx:"0.18.5"}},optionalDependencies:{bufferutil:"^4.0.7","utf-8-validate":"^5.0.10"}}});var Zc={};Ve(Zc,{addAnalyticsListener:()=>Xc,recordAction:()=>Br,recordActionBinary:()=>en,setAnalyticsEnabled:()=>u4});function u4(e){YC=e}function Br(e,t,r,n,s){if(!YC)return;let i=t+(r?"-"+r:"");n!==void 0&&(i+="-"+n),s!==void 0&&(i+="-"+s);let o=X_.get(i);if(o)if(typeof e=="number"){let c=o.values,u=c.index++;if(u>=c.length){let _=c;o.values=c=new Float32Array(u*2),c.set(_),c.index=u+1}c[u]=e,o.total+=e}else if(typeof e=="boolean")e&&o.total++,o.count++;else if(typeof e=="function")o.count++;else throw new TypeError("Invalid metric value type "+typeof e);else{if(typeof e=="number")o={total:e,values:new Float32Array(4)},o.values.index=1,o.values[0]=e,o.total=e;else if(typeof e=="boolean")o={},o.total=e?1:0,o.count=1;else if(typeof e=="function")o={},o.count=1,o.callback=e;else throw new TypeError("Invalid metric value type "+typeof e);o.description={metric:t,path:r,method:n,type:s},X_.set(i,o)}J_||l4()}function en(e,t,r,n,s){Br(!!e,t,r,n,s)}function Xc(e){QC.push(e)}function l4(){J_=performance.now(),setTimeout(async()=>{let e=performance.now()-J_;J_=0;let t=[],r={time:Date.now(),period:e,threadId:zi.threadId,metrics:t};for(let[s,i]of X_){if(i.values){let o=i.values.subarray(0,i.values.index);o.sort();let c=o.length,u=0,_=[],l;for(let d of zC){let f=Math.floor(c*d),E=o[f-1];if(f>u){let h=f-u;if(E===l){let p=_[_.length-1];typeof p=="number"?_[_.length-1]={value:p,count:1+h}:p.count+=h}else _.push(h>1?{value:E,count:h}:E),l=E;u=f}}t.push(Object.assign(i.description,{mean:i.total/c,distribution:_,count:c}))}else i.callback?t.push(Object.assign(i.description,i.callback(i))):t.push(Object.assign(i.description,{total:i.total,count:i.count}));await JC()}let n=process.memoryUsage();t.push({metric:"memory",threadId:zi.threadId,byThread:!0,...n});for(let s of QC)s(t);X_=new Map,zi.parentPort?zi.parentPort.postMessage({type:WC,report:r}):ZC({report:r})},KC).unref()}async function _4(e,t=6e4){let r=Xp(),n=jC(),s;for(let h of n.primaryStore.getRange({start:1/0,end:!1,reverse:!0}))if(h.value?.time){s=h.value.time;break}if(Date.now()-t<s)return;let i,o=new Map,c=new Map,u=[],_;for(let{key:h,value:p}of r.primaryStore.getRange({start:s||!1,exclusiveStart:!0,end:1/0})){if(!p)continue;if(i){if(h>i+t)break}else i=h;_=h;let{metrics:S,threadId:T}=p;for(let A of S||[]){let{path:b,method:H,type:q,metric:v,count:P,total:z,distribution:W,threads:Q,...se}=A;P||(P=1);let pe=v+(b?"-"+b:"");H!==void 0&&(pe+="-"+H),q!==void 0&&(pe+="-"+q);let oe=o.get(pe);if(oe){if(oe.threads){let le=oe.threads[T];if(le)oe=le;else{oe.threads[T]=Object.assign({},se);continue}}oe.count||(oe.count=1);let xe=oe.count;for(let le in se){let wt=se[le];typeof wt=="number"&&(oe[le]=(oe[le]*xe+wt*P)/(xe+P))}oe.count+=P,z>=0&&(oe.total+=z,oe.ratio=oe.total/oe.count)}else oe=Object.assign({period:t},A),delete oe.distribution,o.set(pe,oe),oe.byThread&&(oe.threads=[],oe.threads[T]=Object.assign({},se),u.push(oe));if(W){W=W.map(le=>typeof le=="number"?{value:le,count:1}:le);let xe=c.get(pe);xe?xe.push(...W):c.set(pe,W)}}await JC()}for(let h of u){let{path:p,method:S,type:T,metric:A,count:b,total:H,distribution:q,threads:v,...P}=h;v=v.filter(z=>z);for(let z in P){if(typeof h[z]!="number")continue;let W=0;for(let Q of v){let se=Q[z];typeof se=="number"&&(W+=se)}h[z]=W}h.count=v.length,delete h.threads,delete h.byThread}for(let[h,p]of c){let S=o.get(h);p.sort((le,wt)=>le.value>wt.value?1:-1);let T=S.count-1,A=[],b=0,H=0,q;for(let le of zC){let wt=T*le;for(;b<wt;)q=p[H++],b+=q.count,H===1&&b--;let Nl=p[H>1?H-2:0];q||(q=p[0]),A.push(q.value-(q.value-Nl.value)*(b-wt)/q.count)}let[v,P,z,W,Q,se,pe,oe,xe]=A;Object.assign(S,{p1:v,p10:P,p25:z,median:W,p75:Q,p90:se,p95:pe,p99:oe,p999:xe})}let l;for(let[h,p]of o)p.id=(0,j_.getNextMonotonicTime)(),p.time=_,n.primaryStore.put(p.id,p,{append:!0}).then(S=>{S||n.primaryStore.put(p.id,p)}),l=!0;let d=Date.now(),{idle:f,active:E}=performance.eventLoopUtilization();if(l||E*10>f){let h=(0,j_.getNextMonotonicTime)(),p={id:h,metric:"main-thread-utilization",idle:f-BC,active:E-HC,time:d,...process.memoryUsage()};n.primaryStore.put(h,p,{append:!0}).then(S=>{S||n.primaryStore.put(h,p)})}BC=f,HC=E}async function xC(e,t){let r=Date.now()-t;for(let n of e.primaryStore.getKeys({start:!1,end:r}))e.primaryStore.remove(n)}function Xp(){return qC||(qC=ot({table:"hdb_raw_analytics",database:"system",audit:!1,trackDeletes:!1,attributes:[{name:"id",isPrimaryKey:!0},{name:"action"},{name:"metrics"}]}))}function jC(){return FC||(FC=ot({table:"hdb_analytics",database:"system",audit:!1,trackDeletes:!1,attributes:[{name:"id",isPrimaryKey:!0},{name:"metric"},{name:"path"},{name:"method"},{name:"type"}]}))}function E4(){XC=!0;let e=(0,jc.get)(jp.CONFIG_PARAMS.ANALYTICS_AGGREGATEPERIOD)*1e3;e&&setInterval(async()=>{await _4(KC,e),await xC(Xp(),d4),await xC(jC(),f4)},Math.min(e/2,2147483647)).unref()}function ZC(e,t){let r=e.report;r.threadId=t?.threadId||zi.threadId;for(let n of r.metrics)n.metric==="bytes-sent"&&(GC+=n.mean*n.count);r.totalBytesProcessed=GC,t&&(r.metrics.push({metric:"utilization",...t.performance.eventLoopUtilization(kC.get(t))}),kC.set(t,t.performance.eventLoopUtilization())),r.id=(0,j_.getNextMonotonicTime)(),Xp().primaryStore.put(r.id,r),XC||E4(),h4&&(eD=p4(r))}async function p4(e){if(await eD,!ei){let r=(0,Jc.dirname)((0,$C.getLogFilePath)());try{ei=await(0,Jp.open)((0,Jc.join)(r,"analytics.log"),"r+")}catch{ei=await(0,Jp.open)((0,Jc.join)(r,"analytics.log"),"w+")}}let t=(await ei.stat()).size;if(t>m4){let r=Buffer.alloc(t);await ei.read(r,{position:0}),r=r.subarray(r.indexOf(10,r.length/2)+1),await ei.write(r,{position:0}),await ei.truncate(r.length),t=r.length}await ei.write(JSON.stringify(e)+`
|
|
8
|
-
`,t)}var
|
|
6
|
+
`)},lk="certificate.pem",_k="privateKey.pem",dk="ca.pem";TO.exports={CERTIFICATE_VALUES:uk,CERTIFICATE_PEM_NAME:lk,PRIVATEKEY_PEM_NAME:_k,CA_PEM_NAME:dk}});var je=T((ioe,RO)=>{"use strict";var jt=require("validate.js");jt.validators.type=function(e,t,r,n){return e===null||typeof e>"u"||jt.validators.type.checks[t](e)?null:` must be a '${t}' value`};jt.validators.type.checks={Object:function(e){return jt.isObject(e)&&!jt.isArray(e)},Array:jt.isArray,Integer:jt.isInteger,Number:jt.isNumber,String:jt.isString,Date:jt.isDate,Boolean:function(e){return typeof e=="boolean"}};jt.validators.hasValidFileExt=function(e,t){return jt.isString(e)?e===""?"can't be blank":t.filter(r=>e.endsWith(r)).length>0?null:`must include one of the following valid file extensions - '${t.join("', '")}'`:null};RO.exports={validateObject:fk,validateObjectAsync:Ek,validateBySchema:hk};function fk(e,t){if(!e||!t)return new Error("validateObject parameters were null");let r=jt(e,t,{format:"flat"});return r?new Error(r):null}a(fk,"validateObject");async function Ek(e,t){if(!e||!t)return new Error("validateObject parameters were null");try{await jt.async(e,t,{format:"flat"})}catch(r){let n=r.join(",");return new Error(n)}return null}a(Ek,"validateObjectAsync");function hk(e,t){let r=t.validate(e,{allowUnknown:!0,abortEarly:!1,errors:{wrap:{label:"'"}}});if(r.error)return new Error(r.error.message)}a(hk,"validateBySchema")});var fh=T((coe,NO)=>{"use strict";var yO=require("fs-extra"),ue=require("joi"),mk=require("os"),{boolean:De,string:yr,number:Ct,array:dh}=ue.types(),{totalmem:AO}=require("os"),Ni=require("path"),pk=K(),ql=J(),aoe=gO(),OO=U(),Sk=je(),bO="log",Tk="components",gk="Invalid logging.rotation.maxSize unit. Available units are G, M or K",Rk="Invalid logging.rotation.interval unit. Available units are D, H or M (minutes)",Ak="Invalid logging.rotation.maxSize value. Value should be a number followed by unit e.g. '10M'",Ok="Invalid logging.rotation.interval value. Value should be a number followed by unit e.g. '10D'",bk="rootPath config parameter is undefined",yk="clustering.enabled config parameter is undefined",wi=Ct.min(0).required(),Fl=dh.items({host:yr.required(),port:wi}).empty(null),Gn;NO.exports={configValidator:Nk,routesValidator:Mk,route_constraints:Fl};function Nk(e){if(Gn=e.rootPath,ql.isEmpty(Gn))throw bk;let t=De.required(),r=Ct.min(0).max(1e3).empty(null).default(Lk),n=yr.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path").empty(null).default(sc),s=yr.optional().empty(null),i=yr.pattern(/^[^\s.,*>]+$/).messages({"string.pattern.base":"{:#label} invalid, must not contain ., * or >"}).empty(null).required(),o=ue.string().empty(null).default(sc),c=ue.custom(Ik).empty(null).default(sc),u=e.clustering?.enabled;if(ql.isEmpty(u))throw yk;let _;return u===!0?_=ue.object({enabled:t,hubServer:ue.object({cluster:ue.object({name:ue.required().empty(null),network:ue.object({port:wi,routes:Fl}).required()}).required(),leafNodes:ue.object({network:ue.object({port:wi}).required()}).required(),network:ue.object({port:wi}).required()}).required(),leafServer:ue.object({network:ue.object({port:wi,routes:Fl}).required(),streams:ue.object({maxAge:Ct.min(120).allow(null).optional(),maxBytes:Ct.min(1).allow(null).optional(),maxMsgs:Ct.min(1).allow(null).optional(),path:o}).required()}).required(),logLevel:ue.valid("error","warn","info","debug","trace"),nodeName:i,republishMessages:De.optional(),databaseLevel:De.optional(),tls:ue.object({certificate:s,certificateAuthority:s,privateKey:s,insecure:De.required(),verify:De.optional()}),user:yr.optional().empty(null)}).required():_=ue.object({enabled:t,tls:ue.object({certificate:s,certificateAuthority:s,privateKey:s,insecure:De.required()})}).required(),ue.object({authentication:ue.object({authorizeLocal:De,cacheTTL:Ct.required(),enableSessions:De}),analytics:ue.object({aggregatePeriod:Ct}),componentsRoot:n.optional(),clustering:_,localStudio:ue.object({enabled:t}).required(),logging:ue.object({auditAuthEvents:ue.object({logFailed:De,logSuccessful:De}),file:De.required(),level:ue.valid("notify","fatal","error","warn","info","debug","trace"),rotation:ue.object({enabled:De.optional(),compress:De.optional(),interval:yr.custom(Dk).optional().empty(null),maxSize:yr.custom(Ck).optional().empty(null),path:yr.optional().empty(null).default(sc)}).required(),root:n,stdStreams:De.required(),auditLog:De.required()}).required(),operationsApi:ue.object({network:ue.object({cors:De.optional(),corsAccessList:dh.optional(),headersTimeout:Ct.min(1).optional(),keepAliveTimeout:Ct.min(1).optional(),port:Ct.optional().empty(null),domainSocket:ue.optional().empty("hdb/operations-server").default(sc),securePort:Ct.optional().empty(null),timeout:Ct.min(1).optional()}).optional(),tls:ue.object({certificate:s,certificateAuthority:s,privateKey:s})}).required(),rootPath:yr.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path").required(),mqtt:ue.object({network:ue.object({port:wi,securePort:wi,mtls:ue.alternatives([De.optional(),ue.object({user:yr.optional(),certificateAuthority:s,required:De.optional()})])}).required(),webSocket:De.optional(),requireAuthentication:De.optional()}),http:ue.object({compressionThreshold:Ct.optional(),cors:De.optional(),corsAccessList:dh.optional(),headersTimeout:Ct.min(1).optional(),port:Ct.min(0).optional().empty(null),securePort:Ct.min(0).optional().empty(null),mtls:ue.alternatives([De.optional(),ue.object({user:yr.optional(),certificateAuthority:s,required:De.optional()})])}).required(),threads:r.optional(),maxHeapMemory:Ct.min(0).optional(),storage:ue.object({writeAsync:De.required(),overlappingSync:De.optional(),caching:De.optional(),compression:De.optional(),noReadAhead:De.optional(),path:c,prefetchWrites:De.optional()}).required(),ignoreScripts:De.optional(),tls:ue.object({certificate:s.optional(),certificateAuthority:s.optional(),privateKey:s.optional(),ciphers:yr.optional()})}).validate(e,{allowUnknown:!0,abortEarly:!1,errors:{wrap:{label:"'"}}})}a(Nk,"configValidator");function wk(e){return yO.existsSync(e)?null:`Specified path ${e} does not exist.`}a(wk,"doesPathExist");function Ik(e,t){ue.assert(e,yr.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path"));let r=wk(e);if(r)return t.message(r)}a(Ik,"validatePath");function Ck(e,t){let r=e.slice(-1);if(r!=="G"&&r!=="M"&&r!=="K")return t.message(gk);let n=e.slice(0,-1);return isNaN(parseInt(n))?t.message(Ak):e}a(Ck,"validateRotationMaxSize");function Dk(e,t){let r=e.slice(-1);if(r!=="D"&&r!=="H"&&r!=="M")return t.message(Rk);let n=e.slice(0,-1);return isNaN(parseInt(n))?t.message(Ok):e}a(Dk,"validateRotationInterval");function Lk(e,t){let r=t.state.path.join("."),n=mk.cpus().length,s=n-1;s<=2&&(s=2);let i=process.constrainedMemory?.()||AO();return i=Math.round(Math.min(i,AO())/1e6),s=Math.max(Math.min(s,Math.round((i-750)/300)),1),pk.info(`Detected ${n} cores and ${i}MB on this machine, defaulting ${r} to ${s}`),s}a(Lk,"setDefaultThreads");function sc(e,t){let r=t.state.path.join(".");if(!ql.isEmpty(t.original)&&r!=="operationsApi.network.domainSocket")return t.original;if(ql.isEmpty(Gn))throw new Error(`Error setting default root for: ${r}. HDB root is not defined`);switch(r){case"componentsRoot":return Ni.join(Gn,Tk);case"logging.root":return Ni.join(Gn,bO);case"clustering.leafServer.streams.path":return Ni.join(Gn,"clustering","leaf");case"storage.path":let n=Ni.join(Gn,OO.LEGACY_DATABASES_DIR_NAME);return yO.existsSync(n)?n:Ni.join(Gn,OO.DATABASES_DIR_NAME);case"logging.rotation.path":return Ni.join(Gn,bO);case"operationsApi.network.domainSocket":return r==null?null:Ni.join(Gn,"operations-server");default:throw new Error(`Error setting default root for config parameter: ${r}. Unrecognized config parameter`)}}a(sc,"setDefaultRoot");function Mk(e){let t=ue.object({routes:Fl});return Sk.validateBySchema({routes:e},t)}a(Mk,"routesValidator")});var Ii={};ke(Ii,{server:()=>Xe});var wO,Xe,Xt=Oe(()=>{wO=require("../../index"),Xe={};(0,wO._assignPackageExport)("server",Xe)});var Ir=T((_oe,BO)=>{"use strict";var wr=U(),Dt=J(),Rt=K(),{configValidator:Uk,routesValidator:IO}=fh(),Zt=require("fs-extra"),Pk=require("yaml"),Tn=require("path"),vk=require("is-number"),DO=require("properties-reader"),Bk=require("lodash"),{handleHDBError:Hk}=ee(),{HTTP_STATUS_CODES:xk,HDB_ERROR_MSGS:Gl}=br(),loe=require("minimist"),{server:qk}=(Xt(),te(Ii)),{DATABASES_PARAM_CONFIG:ic,CONFIG_PARAMS:Nr,CONFIG_PARAM_MAP:gn}=wr,Fk="Unable to get config value because config is uninitialized",Gk="Config successfully initialized",kk="Error backing up config file",Vk="Empty parameter sent to getConfigValue",LO=Tn.join(wr.PACKAGE_ROOT,"config","yaml",wr.HDB_DEFAULT_CONFIG_FILE),$k="Configuration successfully set. You must restart HarperDB for new config settings to take effect.",CO={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"},kl,At,Vl;BO.exports={createConfigFile:Yk,getDefaultConfig:Kk,getConfigValue:UO,initConfig:hh,flattenConfig:vo,updateConfigValue:PO,updateConfigObject:Qk,getConfiguration:jk,setConfiguration:Xk,readConfigFile:ph,getClusteringRoutes:Zk,initOldConfig:vO,getConfigFromFile:eV,getConfigFilePath:Ci,addConfig:tV,deleteConfigFromFile:rV,getConfigObj:nV};function Yk(e){let t=Ws(LO);kl=vo(t.toJSON());let r;for(let o in e){let c=gn[o.toLowerCase()];if(c===Nr.DATABASES){r=e[o];continue}if(!c&&o.endsWith("_package")&&(c=o),c!==void 0){let u=c.split("_"),_=Eh(c,e[o]);c==="rootPath"&&_?.endsWith("/")&&(_=_.slice(0,-1));try{t.setIn([...u],_)}catch(l){Rt.error(l)}}}r&&MO(t,r),mh(t);let n=t.toJSON();At=vo(n);let s=t.getIn(["rootPath"]),i=Tn.join(s,wr.HDB_CONFIG_FILE);Zt.createFileSync(i),Zt.writeFileSync(i,String(t)),Rt.trace(`Config file written to ${i}`)}a(Yk,"createConfigFile");function MO(e,t){let r;try{try{r=JSON.parse(t)}catch(n){if(!Dt.isObject(t))throw n;r=t}for(let n of r){let s=Object.keys(n)[0];if(n[s].hasOwnProperty(ic.TABLES))for(let i in n[s][ic.TABLES])for(let o in n[s][ic.TABLES][i]){let c=n[s][ic.TABLES][i][o],u=[Nr.DATABASES,s,ic.TABLES,i,o];e.hasIn(u)?e.setIn(u,c):e.addIn(u,c)}else for(let i in n[s]){let o=n[s][i],c=[Nr.DATABASES,s,i];e.hasIn(c)?e.setIn(c,o):e.addIn(c,o)}}}catch(n){Rt.error("Error parsing schemas CLI/env config arguments",n)}}a(MO,"setSchemasConfig");function Kk(e){if(kl===void 0){let r=Ws(LO);kl=vo(r.toJSON())}let t=gn[e.toLowerCase()];if(t!==void 0)return kl[t.toLowerCase()]}a(Kk,"getDefaultConfig");function UO(e){if(e==null){Rt.error(Vk);return}if(At===void 0){Rt.trace(Fk);return}let t=gn[e.toLowerCase()];if(t!==void 0)return At[t.toLowerCase()]}a(UO,"getConfigValue");function Ci(e=Dt.getPropsFilePath()){let t=Dt.getEnvCliRootPath();return t?Tn.join(t,wr.HDB_CONFIG_FILE):DO(e).get(wr.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY)}a(Ci,"getConfigFilePath");function hh(e=!1){if(At===void 0||e){let t;if(!Dt.noBootFile()){t=Dt.getPropsFilePath();try{Zt.accessSync(t,Zt.constants.F_OK|Zt.constants.R_OK)}catch(i){throw Rt.error(i),new Error(`HarperDB properties file at path ${t} does not exist`)}}let r=Ci(t),n;if(r.includes("config/settings.js"))try{vO(r);return}catch(i){if(i.code!==wr.NODE_ERROR_CODES.ENOENT)throw i}try{n=Ws(r)}catch(i){if(i.code===wr.NODE_ERROR_CODES.ENOENT){Rt.trace(`HarperDB config file not found at ${r}.
|
|
7
|
+
This can occur during early stages of install where the config file has not yet been created`);return}else throw Rt.error(i),new Error(`Error reading HarperDB config file at ${r}`)}Wk(n,r),mh(n);let s=n.toJSON();if(qk.config=s,At=vo(s),At.logging_rotation_rotate)for(let i in CO)At[i]&&Rt.error(`Config ${CO[i]} has been deprecated. Please check https://docs.harperdb.io/docs/ for further details.`);Rt.trace(Gk)}}a(hh,"initConfig");function Wk(e,t){let r=e.getIn(["rootPath"]),n=!1;e.hasIn(["storage","path"])||(e.setIn(["storage","path"],Tn.join(r,"database")),n=!0),e.hasIn(["clustering","leafServer","streams","path"])||(e.setIn(["clustering","leafServer","streams","path"],Tn.join(r,"clustering","leaf")),n=!0),e.hasIn(["logging","rotation","path"])||(e.setIn(["logging","rotation","path"],Tn.join(r,"log")),n=!0),e.hasIn(["clustering","tls","verify"])||(e.setIn(["clustering","tls","verify"],!0),n=!0),n&&(Rt.trace("Updating config file with missing config params"),Zt.writeFileSync(t,String(e)))}a(Wk,"checkForUpdatedConfig");function mh(e){let t=e.toJSON();t.componentsRoot=t.componentsRoot??t?.customFunctions?.root,t.threads=t.threads??t?.http?.threads;let r=Uk(t);if(r.error)throw Gl.CONFIG_VALIDATION(r.error.message);e.setIn(["threads"],r.value.threads),e.setIn(["componentsRoot"],r.value.componentsRoot),e.setIn(["logging","root"],r.value.logging.root),e.setIn(["storage","path"],r.value.storage.path),e.setIn(["logging","rotation","path"],r.value.logging.rotation.path),e.setIn(["clustering","leafServer","streams","path"],r.value.clustering.leafServer.streams?.path),e.setIn(["operationsApi","network","domainSocket"],r.value?.operationsApi?.network?.domainSocket)}a(mh,"validateConfig");function Qk(e,t){At===void 0&&(At={});let r=gn[e.toLowerCase()];if(r===void 0){Rt.trace(`Unable to update config object because config param '${e}' does not exist`);return}At[r.toLowerCase()]=t}a(Qk,"updateConfigObject");function PO(e,t,r=void 0,n=!1,s=!1,i=!1){At===void 0&&hh();let o=UO(gn.hdb_root),c=Tn.join(o,wr.HDB_CONFIG_FILE),u=Ws(c),_;if(r===void 0&&e.toLowerCase()===Nr.DATABASES)_=t;else if(r===void 0){let f;if(i)f=e;else if(f=gn[e.toLowerCase()],f===void 0)throw new Error(`Unable to update config, unrecognized config parameter: ${e}`);let E=f.split("_"),h=Eh(f,t);u.setIn([...E],h)}else for(let f in r){let E=gn[f.toLowerCase()];if(E===Nr.HTTP_SECUREPORT&&r[f]===At[Nr.HTTP_PORT]?.toString()&&u.setIn(["http","port"],null),E===Nr.OPERATIONSAPI_NETWORK_SECUREPORT&&r[f]===At[Nr.OPERATIONSAPI_NETWORK_PORT.toLowerCase()]?.toString()&&u.setIn(["operationsApi","network","port"],null),E===Nr.DATABASES){_=r[f];continue}if(!E&&f.endsWith("_package")&&(E=f),E!==void 0){let h=E.split("_"),p=wr.LEGACY_CONFIG_PARAMS[f.toUpperCase()];p&&p.startsWith("customFunctions")&&u.hasIn(p.split("_"))&&(E=p,h=p.split("_"));let S=Eh(E,r[f]);E==="rootPath"&&S?.endsWith("/")&&(S=S.slice(0,-1));try{h.length>1&&typeof u.getIn(h.slice(0,-1))=="boolean"&&u.deleteIn(h.slice(0,-1)),u.setIn([...h],S)}catch(O){Rt.error(O)}}}_&&MO(u,_),mh(u);let l=u.getIn(["rootPath"]),d=Tn.join(l,wr.HDB_CONFIG_FILE);n===!0&&zk(c,l),Zt.writeFileSync(d,String(u)),s&&(At=vo(u.toJSON())),Rt.trace(`Config parameter: ${e} updated with value: ${t}`)}a(PO,"updateConfigValue");function zk(e,t){try{let r=Tn.join(t,"backup",`${wr.HDB_CONFIG_FILE}.bak`);Zt.copySync(e,r),Rt.trace(`Config file: ${e} backed up to: ${r}`)}catch(r){Rt.error(kk),Rt.error(r)}}a(zk,"backupConfigFile");var Jk=["databases"];function vo(e){return e.http&&Object.assign(e.http,e?.customFunctions?.network),e?.operationsApi?.network&&(e.operationsApi.network=Object.assign({},e.http,e.operationsApi.network)),e?.operationsApi&&(e.operationsApi.tls=Object.assign({},e.tls,e.operationsApi.tls)),Vl=e,r(e);function r(n){let s={};for(let i in n)if(n.hasOwnProperty(i)){if(typeof n[i]=="object"&&n[i]!==null&&!Array.isArray(n[i])&&!Jk.includes(i)){let o=r(n[i]);for(let c in o){if(!o.hasOwnProperty(c))continue;c!=="package"&&(i=i.toLowerCase());let u=i+"_"+c;!Nr[u.toUpperCase()]&&gn[u]&&(s[gn[u].toLowerCase()]=o[c]),s[u]=o[c]}}n[i]!==void 0&&(s[i.toLowerCase()]=n[i])}return s}a(r,"squashObj")}a(vo,"flattenConfig");function Eh(e,t){if(e===Nr.CLUSTERING_NODENAME||e===Nr.CLUSTERING_USER){if(t==null)return t;if(!isNaN(t))return t.toString();if(typeof t=="string"&&t.toLowerCase()==="true"||typeof t=="string"&&t.toLowerCase()==="false")return t}else{if(vk(t))return parseFloat(t);if(t===!0||t===!1||Array.isArray(t)||Dt.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 Dt.autoCast(t)}a(Eh,"castConfigValue");function jk(){let e=Dt.getPropsFilePath(),t=Ci(e);return Ws(t).toJSON()}a(jk,"getConfiguration");async function Xk(e){let{operation:t,hdb_user:r,hdb_auth_header:n,...s}=e;try{return PO(void 0,void 0,s,!0),$k}catch(i){throw typeof i=="string"||i instanceof String?Hk(i,i,xk.BAD_REQUEST,void 0,void 0,!0):i}}a(Xk,"setConfiguration");function ph(){let e=Dt.getPropsFilePath();try{Zt.accessSync(e,Zt.constants.F_OK|Zt.constants.R_OK)}catch(n){if(!Dt.noBootFile())throw Rt.error(n),new Error(`HarperDB properties file at path ${e} does not exist`)}let t=Ci(e);return Ws(t).toJSON()}a(ph,"readConfigFile");function Ws(e){return Pk.parseDocument(Zt.readFileSync(e,"utf8"),{simpleKeys:!0})}a(Ws,"parseYamlDoc");function Zk(){let e=ph(),t=e?.clustering?.hubServer?.cluster?.network?.routes;t=Dt.isEmptyOrZeroLength(t)?[]:t;let r=IO(t);if(r)throw Gl.CONFIG_VALIDATION(r.message);let n=e?.clustering?.leafServer?.network?.routes;n=Dt.isEmptyOrZeroLength(n)?[]:n;let s=IO(n);if(s)throw Gl.CONFIG_VALIDATION(s.message);if(!Dt.isEmptyOrZeroLength(n)&&!Dt.isEmptyOrZeroLength(t)){let i=t.filter(o=>n.some(c=>c.host===o.host&&c.port===o.port));if(!Dt.isEmptyOrZeroLength(i)){let o=`Duplicate hub and leaf routes found ${JSON.stringify(i)}`;throw Gl.CONFIG_VALIDATION(o)}}return{hub_routes:t,leaf_routes:n}}a(Zk,"getClusteringRoutes");function vO(e){let t=DO(e);At={};for(let r in gn){let n=t.get(r.toUpperCase());if(Dt.isEmpty(n)||typeof n=="string"&&n.trim().length===0)continue;let s=gn[r].toLowerCase();s===Nr.LOGGING_ROOT?At[s]=Tn.dirname(n):At[s]=n}return At}a(vO,"initOldConfig");function eV(e){let t=ph();return Bk.get(t,e.replaceAll("_","."))}a(eV,"getConfigFromFile");async function tV(e,t){let r=Ws(Ci());r.hasIn([e])?r.setIn([e],t):r.addIn([e],t),await Zt.writeFile(Ci(),String(r))}a(tV,"addConfig");function rV(e){let t=Ci(Dt.getPropsFilePath()),r=Ws(t);r.deleteIn(e);let n=r.getIn(["rootPath"]),s=Tn.join(n,wr.HDB_CONFIG_FILE);Zt.writeFileSync(s,String(r))}a(rV,"deleteConfigFromFile");function nV(){return Vl||(hh(),Vl)}a(nV,"getConfigObj")});var Z=T((foe,FO)=>{"use strict";var Sh=require("fs-extra"),Di=require("path"),HO=require("os"),sV=require("properties-reader"),ac=K(),oc=J(),_e=U(),$l=Ir(),iV="Error initializing environment manager",Yl="BOOT_PROPS_FILE_PATH",xO=!1,oV={[_e.HDB_SETTINGS_NAMES.INSTALL_USER]:!0,[_e.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY]:!0,[_e.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]:!0,BOOT_PROPS_FILE_PATH:!0},Es={};FO.exports={BOOT_PROPS_FILE_PATH:Yl,getHdbBasePath:aV,setHdbBasePath:cV,get:qO,initSync:lV,setProperty:Le,initTestEnvironment:_V};function aV(){return Es[_e.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]}a(aV,"getHdbBasePath");function cV(e){Es[_e.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=e}a(cV,"setHdbBasePath");function qO(e){let t=$l.getConfigValue(e);return t===void 0?Es[e]:t}a(qO,"get");function Le(e,t){oV[e]&&(Es[e]=t),$l.updateConfigObject(e,t)}a(Le,"setProperty");function uV(){let e;try{e=oc.getPropsFilePath(),Sh.accessSync(e,Sh.constants.F_OK|Sh.constants.R_OK),xO=!0;let t=sV(e);return Es[_e.HDB_SETTINGS_NAMES.INSTALL_USER]=t.get(_e.HDB_SETTINGS_NAMES.INSTALL_USER),Es[_e.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY]=t.get(_e.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY),Es[Yl]=e,!0}catch{return ac.trace(`Environment manager found no properties file at ${e}`),!1}}a(uV,"doesPropFileExist");function lV(e=!1){try{(xO||uV()||oc.noBootFile())&&($l.initConfig(e),Es[_e.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=$l.getConfigValue(_e.HDB_SETTINGS_NAMES.HDB_ROOT_KEY))}catch(t){ac.error(iV),ac.error(t),console.error(t),process.exit(1)}}a(lV,"initSync");function _V(e={}){try{let{keep_alive_timeout:t,headers_timeout:r,server_timeout:n,https_enabled:s,cors_enabled:i,cors_accesslist:o,local_studio_on:c}=e,u=Di.join(__dirname,"../../","unitTests");Es[Yl]=Di.join(u,"hdb_boot_properties.file"),Le(_e.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY,Di.join(u,"settings.test")),Le(_e.HDB_SETTINGS_NAMES.INSTALL_USER,HO.userInfo()?HO.userInfo().username:void 0),Le(_e.HDB_SETTINGS_NAMES.LOG_LEVEL_KEY,"debug"),Le(_e.HDB_SETTINGS_NAMES.LOG_PATH_KEY,Di.join(u,"envDir","log")),Le(_e.HDB_SETTINGS_NAMES.LOG_DAILY_ROTATE_KEY,!1),Le(_e.HDB_SETTINGS_NAMES.CLUSTERING_ENABLED_KEY,!0),Le(_e.HDB_SETTINGS_NAMES.CLUSTERING_NODE_NAME_KEY,"1231412de213"),Le(_e.HDB_SETTINGS_NAMES.HDB_ROOT_KEY,Di.join(u,"envDir")),Le(_e.CONFIG_PARAMS.STORAGE_PATH,Di.join(u,"envDir")),s&&(Le(_e.CONFIG_PARAMS.HTTP_SECUREPORT,qO(_e.CONFIG_PARAMS.HTTP_PORT)),Le(_e.CONFIG_PARAMS.HTTP_PORT,null)),Le(_e.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HTTPS,!!s),Le(_e.HDB_SETTINGS_NAMES.SERVER_PORT_KEY,9925),Le(_e.HDB_SETTINGS_NAMES.CORS_ENABLED_KEY,oc.isEmpty(i)?!1:i),Le(_e.CONFIG_PARAMS.HTTP_CORS,oc.isEmpty(i)?!1:i),Le(_e.HDB_SETTINGS_NAMES.MAX_CUSTOM_FUNCTION_PROCESSES,2),Le(_e.HDB_SETTINGS_NAMES.MAX_HDB_PROCESSES,4),Le(_e.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_PORT_KEY,9926),Le(_e.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_ENABLED_KEY,!0),Le(_e.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY,Di.resolve(__dirname,"../../unitTests/server/fastifyRoutes/custom_functions")),Le(_e.HDB_SETTINGS_NAMES.LOCAL_STUDIO_ON,oc.isEmpty(c)?!1:c),o&&(Le("CORS_ACCESSLIST",o),Le(_e.CONFIG_PARAMS.HTTP_CORSACCESSLIST,o)),n&&(Le(_e.HDB_SETTINGS_NAMES.SERVER_TIMEOUT_KEY,n),Le(_e.CONFIG_PARAMS.HTTP_TIMEOUT,n)),t&&(Le(_e.HDB_SETTINGS_NAMES.SERVER_KEEP_ALIVE_TIMEOUT_KEY,t),Le(_e.CONFIG_PARAMS.HTTP_KEEPALIVETIMEOUT,t)),r&&(Le(_e.HDB_SETTINGS_NAMES.SERVER_HEADERS_TIMEOUT_KEY,r),Le(_e.CONFIG_PARAMS.HTTP_HEADERSTIMEOUT,r))}catch(t){let r=`Error reading in HDB environment variables from path ${Yl}. Please check your boot props and settings files`;ac.fatal(r),ac.error(t)}}a(_V,"initTestEnvironment")});var Ye=T((hoe,WO)=>{"use strict";var dc=U(),dV=J(),er=Z(),fc=require("path"),fV=require("minimist"),GO=require("fs-extra"),kO=require("lodash");er.initSync();var{CONFIG_PARAMS:Qs,DATABASES_PARAM_CONFIG:cc,SYSTEM_SCHEMA_NAME:Kl}=dc,uc,lc,_c;function VO(){if(uc!==void 0)return uc;if(er.getHdbBasePath()!==void 0)return uc=er.get(Qs.STORAGE_PATH)||fc.join(er.getHdbBasePath(),dc.DATABASES_DIR_NAME),uc}a(VO,"getBaseSchemaPath");function $O(){if(lc!==void 0)return lc;if(er.getHdbBasePath()!==void 0)return lc=KO(Kl),lc}a($O,"getSystemSchemaPath");function YO(){if(_c!==void 0)return _c;if(er.getHdbBasePath()!==void 0)return _c=er.get(dc.CONFIG_PARAMS.STORAGE_AUDIT_PATH)||fc.join(er.getHdbBasePath(),dc.TRANSACTIONS_DIR_NAME),_c}a(YO,"getTransactionAuditStoreBasePath");function EV(e,t){let r=er.get(Qs.DATABASES)?.[e];return t&&r?.tables?.[t]?.auditPath||r?.auditPath||fc.join(YO(),e.toString())}a(EV,"getTransactionAuditStorePath");function KO(e,t){e=e.toString(),t=t&&t.toString();let r=er.get(dc.CONFIG_PARAMS.DATABASES)?.[e];return t&&r?.tables?.[t]?.path||r?.path||fc.join(VO(),e)}a(KO,"getSchemaPath");function hV(e,t){e=e.toString(),t=t.toString();let r=process.env;Object.assign(r,fV(process.argv));let n=r[Qs.DATABASES.toUpperCase()];if(n){let i;try{i=JSON.parse(n)}catch(o){if(!dV.isObject(n))throw o;i=n}for(let o of i){let c=o[Kl];if(!c)continue;let u=er.get(Qs.DATABASES);u=u??{};let _=c?.tables?.[t]?.[cc.PATH];if(_)return kO.set(u,[Kl,cc.TABLES,t,cc.PATH],_),er.setProperty(Qs.DATABASES,u),_;let l=c?.[cc.PATH];if(l)return kO.set(u,[Kl,cc.PATH],l),er.setProperty(Qs.DATABASES,u),l}}let s=r[Qs.STORAGE_PATH.toUpperCase()];if(s){if(!GO.pathExistsSync(s))throw new Error(s+" does not exist");let i=fc.join(s,e);return GO.mkdirsSync(i),er.setProperty(Qs.STORAGE_PATH,s),i}return $O()}a(hV,"initSystemSchemaPaths");function mV(){uc=void 0,lc=void 0,_c=void 0}a(mV,"resetPaths");WO.exports={getBaseSchemaPath:VO,getSystemSchemaPath:$O,getTransactionAuditStorePath:EV,getTransactionAuditStoreBasePath:YO,getSchemaPath:KO,initSystemSchemaPaths:hV,resetPaths:mV}});var Cr=T((Toe,XO)=>{"use strict";var pV=br().LMDB_ERRORS_ENUM,poe=require("lmdb"),SV=lt(),Soe=require("buffer").Buffer,{OVERFLOW_MARKER:QO,MAX_SEARCH_KEY_LENGTH:Wl}=SV,zO=["number","string","symbol","boolean","bigint"];function TV(e){if(e=e?.primaryStore||e,!e)throw new Error(pV.ENV_REQUIRED)}a(TV,"validateEnv");function gV(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(gV,"stringifyData");function RV(e){return e instanceof Date?e.valueOf():e}a(RV,"convertKeyValueToWrite");function AV(e,t){if(e===null)return t?[null]:void 0;if(e===void 0)return;if(zO.includes(typeof e))return e.length>Wl?[e.slice(0,Wl)+QO]:[e];let r;if(Array.isArray(e)){r=[];for(let n=0,s=e.length;n<s;n++){let i=e[n];if(zO.includes(typeof i))i.length>Wl?r.push(i.slice(0,Wl)+QO):r.push(i);else{if(i===null&&t)return r.push(null);if(i instanceof Date)return r.push(i.getTime())}}}else if(e instanceof Date)return[e.getTime()];return r}a(AV,"getIndexedValues");var Ql=0,JO=0;function jO(){JO=Date.now()-performance.now()}a(jO,"adjustStartTime");jO();var OV=6e4;setInterval(jO,OV).unref();function bV(){let e=performance.now()+JO;return e>Ql?(Ql=e,e):(Ql+=488e-6,Ql)}a(bV,"getNextMonotonicTime");XO.exports={validateEnv:TV,stringifyData:gV,convertKeyValueToWrite:RV,getNextMonotonicTime:bV,getIndexedValues:AV}});var ZO,Rn,Th,Ec=Oe(()=>{ZO=require("events"),Rn=class extends ZO.EventEmitter{static{a(this,"IterableEventQueue")}resolveNext;queue;hasDataListeners;[Symbol.asyncIterator](){let t=new Th;return t.queue=this,t}push(t){this.send(t)}send(t){this.resolveNext?(this.resolveNext({value:t}),this.resolveNext=null):this.hasDataListeners?this.emit("data",t):(this.queue||(this.queue=[]),this.queue.push(t))}getNextMessage(){return this.queue?.shift()}on(t,r){if(t==="data"&&!this.hasDataListeners)for(this.hasDataListeners=!0;this.queue?.length>0;)r(this.queue.shift());return super.on(t,r)}},Th=class{static{a(this,"EventQueueIterator")}queue;push(t){this.queue.send(t)}next(){let t=this.queue.getNextMessage();return t?{value:t}:new Promise(r=>this.queue.resolveNext=r)}return(t){return this.queue.emit("close"),{value:t,done:!0}}throw(t){return this.queue.emit("close",t),{done:!0}}}});var Ah={};ke(Ah,{loadGQLSchema:()=>wV,start:()=>Rh,startOnMainThread:()=>NV});function Rh({ensureTable:e}){return{handleFile:t,setupFile:t};async function t(r,n,s,i){let{parse:o,Source:c,Kind:u,NamedTypeNode:_,StringValueNode:l}=await import("graphql"),d=o(new c(r.toString(),s)),f=new Map,E=[],h;for(let S of d.definitions)switch(S.kind){case u.OBJECT_TYPE_DEFINITION:let H=function(v){if(v.kind==="NonNullType"){let W=H(v.type);return W.nullable=!1,W}if(v.kind==="ListType")return{type:"array",elements:H(v.type)};let $={type:v.name?.value};return Object.defineProperty($,"location",{value:v.loc.startToken}),$};a(H,"getProperty");let O=S.name.value,g=[],R={table:null,database:null,properties:g};f.set(O,R);for(let v of S.directives){if(v.name.value==="table"){for(let M of v.arguments)R[M.name.value]=M.value.value;R.schema&&(R.database=R.schema),R.table||(R.table=O),R.audit&&(R.audit=R.audit!=="false"),R.attributes=R.properties,E.push(R)}if(v.name.value==="sealed"&&(R.sealed=!0),v.name.value==="export"){R.export=!0;for(let M of v.arguments)M.name.value==="name"&&(R.export={name:M.value.value})}}let B=!1;for(let v of S.fields){let M=H(v.type);M.name=v.name.value,g.push(M);for(let $ of v.directives)if($.name.value==="primaryKey")B?console.warn("Can not define two attributes as a primary key"):(M.isPrimaryKey=!0,B=!0);else if($.name.value==="indexed")M.indexed=!0;else if($.name.value==="relationship"){let W={};for(let z of $.arguments)W[z.name.value]=z.value.value;M.relationship=W}else if($.name.value==="createdTime")M.assignCreatedTime=!0;else if($.name.value==="updatedTime")M.assignUpdatedTime=!0;else if($.name.value==="expiresAt")M.expiresAt=!0;else if($.name.value==="allow"){let W=M.authorizedRoles=[];for(let z of $.arguments)z.name.value==="role"&&W.push(z.value.value)}}R.type=O,O==="Query"&&(h=R)}function p(S){let O=f.get(S.type);O?(Object.defineProperty(S,"properties",{value:O.properties}),Object.defineProperty(S,"definition",{value:O})):S.type==="array"?p(S.elements):yV.includes(S.type)||(0,eb.getWorkerIndex)()===0&&console.error(`The type ${S.type} is unknown at line ${S.location.line}, column ${S.location.column}, in ${s}`)}a(p,"connectPropertyType");for(let S of f.values())for(let O of S.properties)p(O);for(let S of E)S.tableClass=e(S),S.export&&(S.export.name===""?i.set((0,gh.dirname)(n),S.tableClass):i.set((0,gh.dirname)(n)+"/"+(S.export.name||S.type),S.tableClass))}}var gh,eb,yV,NV,wV,tb=Oe(()=>{gh=require("path");be();eb=x(Ze()),yV=["ID","Int","Float","Long","String","Boolean","Date","Bytes","Any","BigInt"];a(Rh,"start");NV=Rh,wV=Rh({ensureTable:ot}).handleFile});async function zl(e){return IV?(hc||(hc=CV(LV)),(await(await hc).import(e)).namespace):import(e)}async function CV(e){let{StaticModuleRecord:t}=await import("@endo/static-module-record");return require("ses"),lockdown({domainTaming:"unsafe",consoleTaming:"unsafe",errorTaming:"unsafe",errorTrapping:"none",stackFiltering:"verbose"}),hc=new Compartment({console,Math,Date,fetch:DV,...e()},{},{name:"h-dapp",resolveHook(r,n){return r==="harperdb"?"harperdb":(r=new URL(r,n).toString(),(0,nb.extname)(r)||(r+=".js"),r)},importHook:async r=>{if(r==="harperdb")return{imports:[],exports:["Resource","tables","databases"],execute(s){Object.assign(s,{Resource:vt,tables:Dr,databases:et})}};let n=await(0,rb.readFile)(new URL(r),{encoding:"utf-8"});return new t(n,r)}}),hc}function DV(e,t){let r=typeof e=="string"||e.url;if(new URL(r).protocol!="https")throw new Error("Only https is allowed in fetch");return fetch(e,t)}function LV(){return{Resource:vt,tables:Dr}}var rb,nb,IV,hc,Oh=Oe(()=>{An();be();rb=require("fs/promises"),nb=require("path"),IV=!1;a(zl,"secureImport");a(CV,"getCompartment");a(DV,"secureOnlyFetch");a(LV,"getGlobalVars")});var yh={};ke(yh,{handleFile:()=>MV});async function MV(e,t,r,n){let s=new Map,i=(0,sb.pathToFileURL)(r).toString(),o=await zl(i);u(o.default)&&n.set((0,bh.dirname)(t),o.default),c(o,(0,bh.dirname)(t));function c(_,l){for(let d in _){let f=_[d];u(f)?n.set(l+"/"+d,f):typeof f=="object"&&c(f,l+"/"+d)}}a(c,"recurseForResources");function u(_){return typeof _=="function"&&(_.get||_.put||_.post||_.delete)}return a(u,"isResource"),s}var sb,bh,ib=Oe(()=>{sb=require("url");Oh();bh=require("path");a(MV,"handleFile")});var wh={};ke(wh,{start:()=>UV});function UV({resources:e}){e.set("login",Nh),e.loginPath=t=>"/login?redirect="+encodeURIComponent(t.url)}var Nh,ob=Oe(()=>{An();a(UV,"start");Nh=class extends vt{static{a(this,"Login")}static async get(t,r,n){}static async post(t,r,n){let{username:s,password:i,redirect:o}=r;return{data:await n.login(s,i)}}}});var fb={};ke(fb,{parse:()=>Ch,streamAsJSON:()=>mc,stringify:()=>Li});function mc(e){return new Ih({value:e})}function ab(e){return console.error(e),JSON.stringify(e.toString())}function cb(e,t,r){return e?.then?r?e.then(t,r):e.then(t):t(e)}function Li(e){try{return JSON.stringify(e)??"null"}catch(t){if(t===_b)return db(e);if(t.resolution)return t.resolution.then(()=>Li(e));throw t}}function db(e){let t=typeof e;if(t==="object"){if(e===null)return"null";e.toJSON&&(e=e.toJSON());let r;if(Array.isArray(e)){r="[";for(let n=0;n<e.length;n++)n>0&&(r+=","),r+=db(e[n]);return r+"]"}else{r="{";let n=!0;for(let s in e)n?n=!1:r+=",",r+=JSON.stringify(s)+":"+Li(e[s]);return r+"}"}}else{if(t==="string")return JSON.stringify(e);if(t==="undefined")return"null"}return e.toString()}function Ch(e){return BV.test(e)?PV.parse(e):JSON.parse(e)}var ub,lb,PV,vV,_b,Ih,BV,Dh=Oe(()=>{ub=require("stream"),lb=x(require("json-bigint-fixes")),PV=(0,lb.default)({useNativeBigInt:!0}),vV=1e4,_b={};BigInt.prototype.toJSON=function(){throw _b};a(mc,"streamAsJSON");Ih=class extends ub.Readable{static{a(this,"JSONStream")}constructor(t){super(t),this.buffer=[],this.bufferSize=0,this.iterator=this.serialize(t.value,!0),this.activeIterators=[]}*serialize(t){if(t&&typeof t=="object"){let r=t[Symbol.asyncIterator],n=t[Symbol.iterator];if((n||r)&&!t.then){yield"[";let s=!0;if((r||n)&&!(t instanceof Array)){let i=r?t[Symbol.asyncIterator]():t[Symbol.iterator]();this.activeIterators.push(i);let o;for(;;)if(o=i.next(),o.then&&(yield o.then(c=>(o=c,""))),o.done){this.activeIterators.splice(this.activeIterators.indexOf(i),1),yield"]";return}else s?s=!1:yield",",yield*this.serialize(o.value)}for(let i of t)s?s=!1:yield",",yield*this.serialize(i);yield"]";return}if(t.then)try{yield t.then(s=>this.serialize(s),ab)}catch(s){yield ab(s)}else yield Li(t)}else yield Li(t)}_read(){if(!this._amReading){if(this._amReading=!0,this.done)return this.push(null);cb(this.readIterator(this.iterator),t=>{t?(this.done=!0,this.push(null)):this._amReading=!1},t=>{console.error(t),this.done=!0,this.push(t.toString()),this.push(null)})}}push(t){return t===null||t instanceof Buffer?(this.bufferSize>0&&this.flush(),super.push(t)):(this.bufferSize+=t.length||t.toString().length,this.buffer.push(t),this.bufferSize>vV?this.flush():!0)}flush(){let t=super.push(this.buffer.join(""));return this.buffer=[],this.bufferSize=0,t}readIterator(t){try{let r;if(t.childIterator)return cb(this.readIterator(t.childIterator),n=>{if(n)return t.childIterator=null,this.readIterator(t)});do{let n=t.next();if(n.done)return!0;if(r=n.value,r==null)r="null";else{if(r.then)return this.flush(),Promise.resolve(r).then(s=>{if(s&&typeof s.return=="function")return t.childIterator=s,this.readIterator(t);if(this.push(s+""))return this.readIterator(t)});if(typeof r.return=="function")return t.childIterator=r,this.readIterator(t)}}while(this.push(r))}catch(r){return console.error(r),this.push(r.toString()),this.push(null),!0}}_destroy(t,r){for(let n of this.activeIterators)t?n.throw(t):n.return();r()}};a(ab,"handleError");a(cb,"when");a(Li,"stringify");a(db,"jsStringify");BV=/-?\d{16,}/;a(Ch,"parse")});var Nb=T((voe,yb)=>{"use strict";var Lh=require("recursive-iterator"),HV=require("alasql"),Mh=require("clone"),Eb=J(),{handleHDBError:hb,hdb_errors:xV}=ee(),{HDB_ERROR_MSGS:mb,HTTP_STATUS_CODES:pb}=xV,{getDatabases:qV}=(be(),te(qe)),FV=["DISTINCT_ARRAY"],Sb=Symbol("validateTables"),Uh=Symbol("validateTable"),Poe=Symbol("getAllColumns"),Tb=Symbol("validateAllColumns"),Jl=Symbol("findColumn"),gb=Symbol("validateOrderBy"),pc=Symbol("validateSegment"),Ph=Symbol("validateColumn"),Rb=Symbol("setColumnsForTable"),Ab=Symbol("checkColumnsForAsterisk"),Ob=Symbol("validateGroupBy"),bb=Symbol("hasColumns"),vh=class{static{a(this,"SelectValidator")}constructor(t){this.statement=t,this.attributes=[]}validate(){if(!this.statement)throw new Error("invalid sql statement");this[Sb](),this[Ab](),this[Tb]()}[Sb](){if(this[bb]()){if(!this.statement.from||this.statement.from.length===0)throw"no from clause";this.statement.from.forEach(t=>{this[Uh](t)}),this.statement.joins&&this.statement.joins.forEach(t=>{t.table.as=t.as,this[Uh](t.table)})}}[bb](){let t=!1,r=new Lh(this.statement);for(let{node:n,path:s}of r)if(n&&n.columnid){t=!0;break}return t}[Uh](t){if(!t.databaseid)throw`schema not defined for table ${t.tableid}`;let r=qV();if(!r[t.databaseid])throw hb(new Error,mb.SCHEMA_NOT_FOUND(t.databaseid),pb.NOT_FOUND);if(!r[t.databaseid][t.tableid])throw hb(new Error,mb.TABLE_NOT_FOUND(t.databaseid,t.tableid),pb.NOT_FOUND);r[t.databaseid][t.tableid].attributes.forEach(s=>{let i=Mh(s);i.table=Mh(t),this.attributes.push(i)})}[Jl](t){return this.attributes.filter(r=>t.tableid?(r.table.as===t.tableid||r.table.tableid===t.tableid)&&r.attribute===t.columnid:r.attribute===t.columnid)}[Ab](){let t=new Lh(this.statement.columns);for(let{node:r,path:n}of t)r&&r.columnid==="*"&&n.indexOf("expression")<0&&this[Rb](r.tableid)}[Rb](t){this.attributes.forEach(r=>{(!t||t&&(r.table.tableid===t||r.table.as===t))&&!r.relation&&this.statement.columns.push(new HV.yy.Column({columnid:r.attribute,tableid:r.table.as?r.table.as:r.table.tableid}))})}[Tb](){this[pc](this.statement.columns,!1),this[pc](this.statement.joins,!1),this[pc](this.statement.where,!1),this[Ob](this.statement.group,!1),this[pc](this.statement.order,!0)}[pc](t,r){if(!t)return;let n=new Lh(t),s=[];for(let{node:i,path:o}of n)!Eb.isEmpty(i)&&!Eb.isEmpty(i.columnid)&&i.columnid!=="*"&&(r?this[gb](i):s.push(this[Ph](i)));return s}[Ob](t){if(!t)return;let r=[];if(this.statement.columns.forEach(n=>{if(!(n.funcid&&FV.indexOf(n.funcid.toUpperCase())>=0)){if(!n.aggregatorid&&!n.columnid){let s=Mh(n);delete s.as,r.push(s)}else if(n.columnid){let s=this[Jl](n)[0];s&&r.push(s)}}}),this.statement.group.forEach(n=>{let s=null;if(!n.columnid)r.forEach((i,o)=>{if(i.toString()===n.toString()){s=i,r.splice(o,1);return}});else{let i=this[Jl](n);if(!i||i.length===0)throw`unknown column '${n.toString()}' in group by`;if(i.length>1)throw`ambiguously defined column '${n.toString()}' in group by`;r.forEach((o,c)=>{if(o.attribute===i[0].attribute&&o.table.tableid===i[0].table.tableid){s=o,r.splice(c,1);return}})}if(!s)throw`group by column '${n.toString()}' must be in select`}),r.length>0)throw`select column '${r[0].attribute?r[0].attribute:r[0].toString()}' must be in group by`}[gb](t){let r=this.statement.columns.filter(n=>n.as===t.columnid);if(r.length>1)throw`ambiguous column reference ${(t.tableid?t.tableid+".":"")+t.columnid} in order by`;r.length===0&&this[Ph](t)}[Ph](t){let r=this[Jl](t),n=(t.tableid?t.tableid+".":"")+t.columnid;if(r.length===0)throw`unknown column ${n}`;if(r.length>1)throw`ambiguous column reference ${n}`;return r[0]}};yb.exports=vh});var Ib=T((Hoe,wb)=>{"use strict";var Bh=class{static{a(this,"BridgeMethods")}createSchema(){throw new Error("createSchema bridge method is not defined")}dropSchema(){throw new Error("dropSchema bridge method is not defined")}createTable(){throw new Error("createTable bridge method is not defined")}dropTable(){throw new Error("dropTable bridge method is not defined")}createRecords(){throw new Error("createRecords bridge method is not defined")}updateRecords(){throw new Error("updateRecords bridge method is not defined")}async upsertRecords(){throw new Error("upsertRecords bridge method is not defined")}deleteRecords(){throw new Error("deleteRecords bridge method is not defined")}createAttribute(){throw new Error("createAttribute bridge method is not defined")}dropAttribute(){throw new Error("dropAttribute bridge method is not defined")}searchByConditions(){throw new Error("searchByConditions bridge method is not defined")}searchByHash(){throw new Error("searchByHash bridge method is not defined")}searchByValue(){throw new Error("searchByValue bridge method is not defined")}getDataByHash(){throw new Error("getDataByHash bridge method is not defined")}getDataByValue(){throw new Error("getDataByValue bridge method is not defined")}deleteRecordsBefore(){throw new Error("deleteRecordsBefore bridge method is not defined")}deleteAuditLogsBefore(){throw new Error("deleteAuditLogsBefore bridge method is not defined")}async readAuditLog(){throw new Error("readAuditLog bridge method is not defined")}};wb.exports=Bh});var Db=T((qoe,Cb)=>{"use strict";var Hh=class{static{a(this,"DBIDefinition")}constructor(t=!1,r=!1){this.dup_sort=t,this.is_hash_attribute=r,this.useVersions=r}};Cb.exports=Hh});var Pb={};ke(Pb,{HAS_EXPIRATION:()=>Yh,LAST_TIMESTAMP_PLACEHOLDER:()=>gc,LOCAL_TIMESTAMP:()=>GV,METADATA:()=>Sc,NO_TIMESTAMP:()=>qh,PENDING_LOCAL_TIME:()=>Kh,PREVIOUS_TIMESTAMP_PLACEHOLDER:()=>$h,RecordEncoder:()=>kh,TIMESTAMP_ASSIGN_LAST:()=>VV,TIMESTAMP_ASSIGN_NEW:()=>Mb,TIMESTAMP_ASSIGN_PREVIOUS:()=>Ub,TIMESTAMP_PLACEHOLDER:()=>jl,TIMESTAMP_RECORD_PREVIOUS:()=>Fh,fromResource:()=>t_,getUpdateRecord:()=>Wh,handleLocalTimeForGets:()=>r_});function YV(){return Tc[0]=Tc[0]^64,kV.getFloat64(0)}function t_(e){Vh=!0;try{return e()}finally{Vh=!1}}function r_(e){let t=e.getEntry;e.readCount=0,e.cachePuts=!1,e.getEntry=function(i,o){e.readCount++;let c=t.call(this,i,o),u=c?.value,_=u?.[Sc];return _>=0&&(c.metadataFlags=_,c.localTime=u.localTime,c.value=u.value,u.expiresAt>0&&(c.expiresAt=u.expiresAt)),c&&(c.key=i),c};let r=e.get;e.get=function(i,o){let c=r.call(this,i,o);return c?.[Sc]>=0?c.value:c};let n=e.getRange;e.getRange=function(i){let o=n.call(this,i);return i.valuesForKey?o.map(c=>c?.value):i.values===!1||i.onlyCount?o:o.map(c=>{let u=c.value,_=u[Sc];return _>=0&&(c.metadataFlags=_,c.localTime=u.localTime,c.value=u.value,u.expiresAt>0&&(c.expiresAt=u.expiresAt)),c})};let s=e.useReadTransaction();if(s.done(),!s.done.isTracked){let i=s.constructor,o=s.use,c=s.done;i.prototype.use=function(){if(this.timerTracked||(this.timerTracked=!0,Mi.push(new WeakRef(this))),!Vh)try{throw new Error("Read transaction used outside of resource")}catch(u){this.readStack=u.stack}o.call(this)},i.prototype.done=function(){if(c.call(this),this.isDone)for(let u=0;u<Mi.length;u++){let _=Mi[u].deref();(!_||_.isDone||_.isCommitted)&&Mi.splice(u--,1)}},i.prototype.done.isTracked=!0}return e}function Wh(e,t,r){return function(n,s,i,o,c=-1,u,_,l,d="put",f,E){if(f||u==null?Bo=i?.localTime?Fh|Ub:qh:Bo=u?i?.localTime?Fh|16384:Mb|16384:qh,l>0&&(c|=Yh),Zl=c,Gh=l,i?.version===o&&u===!1)throw new Error("Must retain local time if version is not changed");let h={version:o,instructedWrite:Bo>0},p;try{f&&(h.ifVersion=p=i?.version??null);let S=e.put(n,s,h);if(u){let O=_?.user?.username;if(E&&(Xl=e.encoder.encode(E)),f&&i?.localTime){let g=i?.localTime,R=r.get(g);if(R){let B=Lt(R).previousLocalTime;return r.put(g,e_(o,t,n,B,O,d,Xl),{ifVersion:p}),S}}r.put(gc,e_(o,t,n,i?.localTime?1:0,O,d,Xl),{append:d!=="invalidate",instructedWrite:!0,ifVersion:p})}return S}catch(S){throw S.message+=" id: "+n+" options: "+h,S}}}var Lb,xh,jl,gc,$h,GV,Sc,Tc,kV,qh,Mb,VV,Ub,Fh,Yh,Kh,$V,Xl,Bo,Zl,Gh,kh,koe,Vh,Mi,Ho=Oe(()=>{Lb=require("msgpackr");Ui();xh=x(K()),jl=new Uint8Array([1,1,1,1,4,64,0,0]),gc=new Uint8Array([1,1,1,1,1,0,0,0]),$h=new Uint8Array([1,1,1,1,3,64,0,0]),GV=Symbol("local-timestamp"),Sc=Symbol("metadata"),Tc=new Uint8Array(8),kV=new DataView(Tc.buffer,0,8),qh=0,Mb=0,VV=1,Ub=3,Fh=4,Yh=16,Kh=1,Bo=0,Zl=-1,Gh=0,kh=class extends Lb.Encoder{static{a(this,"RecordEncoder")}constructor(t){t.useBigIntExtension=!0,super(t);let r=this.encode;this.encode=function(n,s){if(Bo||Zl>=0){let i=0,o=Bo;o&&(i+=8,Bo=0);let c=Zl,u=Gh;c>=0&&(i+=2,Zl=-1,u&&(i+=8,Gh=0));let _=$V=r.call(this,n,s|2048|i);Xl=_.subarray((_.start||0)+i,_.end);let l=_.start||0;return o&&(jl[4]=o,jl[5]=o>>8,_.set(jl,l),l+=8),c>=0&&(_[l++]=c,_[l++]=0,u&&(_.dataView||(_.dataView=new DataView(_.buffer,_.byteOffset,_.byteLength))).setFloat64(l,u)),_}else return r.call(this,n,s)}}decode(t,r){let n=r?.start||0,s=r>-1?r:r?.end||t.length,i=t[n],o=0;try{if(i<32&&s>2){let c=n,u;if(i===2){if(t.copy)t.copy(Tc,0,c),c+=8;else for(let d=0;d<8;d++)Tc[d]=t[c++];u=YV(),i=t[c]}let _;i<32&&(o=i,c+=2,o&Yh&&(_=(t.dataView||(t.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength))).getFloat64(c),c+=8));let l=super.decode(t.subarray(c,s),s-c);return{localTime:u,value:l,[Sc]:o,expiresAt:_}}return super.decode(t,r)}catch(c){throw c.message+=", data: "+t.slice(0,40).toString("hex"),c}}};a(YV,"getTimestamp");koe=Map.prototype.get;a(t_,"fromResource");a(r_,"handleLocalTimeForGets");Mi=[];setInterval(()=>{for(let e=0;e<Mi.length;e++){let t=Mi[e].deref();!t||t.isDone||t.isCommitted?Mi.splice(e--,1):t.notCurrent&&(t.openTimer?(t.openTimer>3&&(t.openTimer>60?(xh.error("Read transaction detected that has been open too long (over 15 minutes), ending transaction",t),t.done()):xh.error("Read transaction detected that has been open too long (over one minute), make sure read transactions are quickly closed",t)),t.openTimer++):t.openTimer=1)}},15e3).unref();a(Wh,"getUpdateRecord")});var n_=T(($oe,vb)=>{"use strict";var zh=Z(),Jh=U(),{RecordEncoder:KV}=(Ho(),te(Pb));zh.initSync();var WV=zh.get(Jh.CONFIG_PARAMS.STORAGE_COMPRESSION),QV=zh.get(Jh.CONFIG_PARAMS.STORAGE_CACHING)!==!1,zV=Jh.UPDATES_PROPERTY,Qh=class{static{a(this,"OpenDBIObject")}constructor(t,r=!1){this.dupSort=t===!0,this.encoding=t?"ordered-binary":"msgpack",this.useVersions=r,this.compression=WV&&r&&{startingOffset:32},this.sharedStructuresKey=Symbol.for("structures"),r&&(this.cache=QV&&{validated:!0},this.randomAccessStructure=!0,this.freezeData=!0,this.encoder={Encoder:KV},this.alwaysLazyProperty=n=>n===zV)}};vb.exports=Qh});var i_=T((Koe,Hb)=>{"use strict";var xo=Z(),Rc=U();xo.initSync();var JV=xo.get(Rc.CONFIG_PARAMS.STORAGE_WRITEASYNC)===!0||xo.get(Rc.CONFIG_PARAMS.STORAGE_WRITEASYNC)==="true"||xo.get(Rc.CONFIG_PARAMS.STORAGE_WRITEASYNC)==="TRUE",Bb=xo.get(Rc.CONFIG_PARAMS.STORAGE_OVERLAPPINGSYNC),jV=xo.get(Rc.CONFIG_PARAMS.STORAGE_NOREADAHEAD),s_=class{static{a(this,"OpenEnvironmentObject")}constructor(t,r=!1){this.path=t,this.mapSize=1073741824,this.maxDbs=1e4,this.maxReaders=1e3,this.sharedStructuresKey=Symbol.for("structures"),this.readOnly=r,this.trackMetrics=!0,this.noSync=JV,this.noFSAccess=!0,Bb!==void 0&&(this.overlappingSync=Bb),this.noReadAhead=jV}};Hb.exports=s_;s_.MAX_DBS=1e4});var Ve=T((Qoe,Wb)=>{"use strict";var Xh=require("lmdb"),On=require("fs-extra"),Lr=require("path"),o_=Cr(),Fb=K(),tr=br().LMDB_ERRORS_ENUM,a_=Db(),Zh=n_(),Gb=i_(),zs=lt(),xb=U(),{table:XV,resetDatabases:ZV}=(be(),te(qe)),qb=Z(),bn=zs.INTERNAL_DBIS_NAME,kb=zs.DBI_DEFINITION_NAME,e$="data.mdb",t$="lock.mdb",Ac=".mdb",r$="-lock",jh=class{static{a(this,"TransactionCursor")}constructor(t,r,n=!1){this.dbi=Xr(t,r),this.key_type=this.dbi[zs.DBI_DEFINITION_NAME].key_type,this.is_hash_attribute=this.dbi[zs.DBI_DEFINITION_NAME].is_hash_attribute,this.txn=t.beginTxn({readOnly:n===!1}),this.cursor=new Xh.Cursor(this.txn,this.dbi)}close(){this.cursor.close(),this.txn.abort()}commit(){this.cursor.close(),this.txn.commit()}};function c_(e,t){if(e===void 0)throw new Error(tr.BASE_PATH_REQUIRED);if(t===void 0)throw new Error(tr.ENV_NAME_REQUIRED)}a(c_,"pathEnvNameValidation");async function em(e,t,r=!0){try{await On.access(e)}catch(n){throw n.code==="ENOENT"?new Error(tr.INVALID_BASE_PATH):n}try{let n=Lr.join(e,t+Ac);return await On.access(n,On.constants.R_OK|On.constants.F_OK),n}catch(n){if(n.code==="ENOENT")if(r)try{return await On.access(Lr.join(e,t,e$),On.constants.R_OK|On.constants.F_OK),Lr.join(e,t)}catch(s){if(s.code==="ENOENT")throw new Error(tr.INVALID_ENVIRONMENT)}else throw new Error(tr.INVALID_ENVIRONMENT);throw n}}a(em,"validateEnvironmentPath");function u_(e,t){if(o_.validateEnv(e),t===void 0)throw new Error(tr.DBI_NAME_REQUIRED)}a(u_,"validateEnvDBIName");async function n$(e,t,r=!1,n=!1){c_(e,t);let s=Lr.basename(e);t=t.toString();let i=qb.get(xb.CONFIG_PARAMS.DATABASES);i||qb.setProperty(xb.CONFIG_PARAMS.DATABASES,i={}),i[s]||(i[s]={}),i[s].path=e;try{return await em(e,t,n),Vb(e,t,r)}catch(o){if(o.message===tr.INVALID_ENVIRONMENT){let c=Lr.join(e,t);await On.mkdirp(n?c:e);let u=new Gb(n?c:c+Ac,!1),_=Xh.open(u);_.dbis=Object.create(null);let l=new Zh(!1);_.openDB(bn,l),global.lmdb_map===void 0&&(global.lmdb_map=Object.create(null));let d=tm(e,t,r);return _[zs.ENVIRONMENT_NAME_KEY]=d,global.lmdb_map[d]=_,_}throw o}}a(n$,"createEnvironment");async function s$(e,t,r,n=!0){c_(e,t),t=t.toString();let s=Lr.join(e,t);return XV({table:t,database:Lr.parse(e).name,path:s,attributes:[{name:"id",isPrimaryKey:!0}]})}a(s$,"copyEnvironment");async function Vb(e,t,r=!1){c_(e,t),t=t.toString();let n=tm(e,t,r);if(global.lmdb_map===void 0&&(global.lmdb_map=Object.create(null)),global.lmdb_map[n]!==void 0)return global.lmdb_map[n];let s=await em(e,t),i=Lr.join(e,t+Ac),o=s!=i,c=new Gb(s,o),u=Xh.open(c);u.dbis=Object.create(null);let _=Yb(u);for(let l=0;l<_.length;l++)Xr(u,_[l]);return u[zs.ENVIRONMENT_NAME_KEY]=n,global.lmdb_map[n]=u,u}a(Vb,"openEnvironment");async function i$(e,t,r=!1){c_(e,t),t=t.toString();let n=Lr.join(e,t+Ac),s=await em(e,t);if(global.lmdb_map!==void 0){let i=tm(e,t,r);if(global.lmdb_map[i]){let o=global.lmdb_map[i];await $b(o),delete global.lmdb_map[i]}}await On.remove(s),await On.remove(s===n?s+r$:Lr.join(Lr.dirname(s),t$))}a(i$,"deleteEnvironment");async function $b(e){o_.validateEnv(e);let t=e[zs.ENVIRONMENT_NAME_KEY];await e.close(),t!==void 0&&global.lmdb_map!==void 0&&delete global.lmdb_map[t]}a($b,"closeEnvironment");function tm(e,t,r=!1){let s=`${Lr.basename(e)}.${t}`;return r===!0&&(s=`txn.${s}`),s}a(tm,"getCachedEnvironmentName");function o$(e){o_.validateEnv(e);let t=Object.create(null),r=Xr(e,bn);for(let{key:n,value:s}of r.getRange({start:!1}))if(n!==bn)try{t[n]=Object.assign(new a_,s)}catch{Fb.warn(`an internal error occurred: unable to parse DBI Definition for ${n}`)}return t}a(o$,"listDBIDefinitions");function Yb(e){o_.validateEnv(e);let t=[],r=Xr(e,bn);for(let{key:n}of r.getRange({start:!1}))n!==bn&&t.push(n);return t}a(Yb,"listDBIs");function a$(e,t){let n=Xr(e,bn).getEntry(t),s=new a_;if(n!==void 0){try{s=Object.assign(s,n.value)}catch{Fb.warn(`an internal error occurred: unable to parse DBI Definition for ${n}`)}return s}}a(a$,"getDBIDefinition");function Kb(e,t,r,n=!r){if(u_(e,t),t=t.toString(),t===bn)throw new Error(tr.CANNOT_CREATE_INTERNAL_DBIS_NAME);try{return Xr(e,t)}catch(s){if(s.message===tr.DBI_DOES_NOT_EXIST){let i=new Zh(r,n===!0),o=e.openDB(t,i),c=new a_(r===!0,n);return o[kb]=c,Xr(e,bn).putSync(t,c),e.dbis[t]=o,o}throw s}}a(Kb,"createDBI");function Xr(e,t){if(u_(e,t),t=t.toString(),e.dbis[t]!==void 0)return e.dbis[t];let r;if(t!==bn?r=a$(e,t):r=new a_,r===void 0)throw new Error(tr.DBI_DOES_NOT_EXIST);let n;try{let s=new Zh(r.dup_sort,r.useVersions);if(n=e.openDB(t,s),n.db===void 0)throw new Error("MDB_NOTFOUND")}catch(s){throw s.message.includes("MDB_NOTFOUND")===!0?new Error(tr.DBI_DOES_NOT_EXIST):s}return n[kb]=r,e.dbis[t]=n,n}a(Xr,"openDBI");function c$(e,t){u_(e,t),t=t.toString();let r=Xr(e,t),n=r.getStats();return r[zs.DBI_DEFINITION_NAME].is_hash_attribute&&n.entryCount>0&&n.entryCount--,n}a(c$,"statDBI");async function u$(e,t){try{let r=Lr.join(e,t+Ac);return(await On.stat(r)).size}catch{throw new Error(tr.INVALID_ENVIRONMENT)}}a(u$,"environmentDataSize");function l$(e,t){if(u_(e,t),t=t.toString(),t===bn)throw new Error(tr.CANNOT_DROP_INTERNAL_DBIS_NAME);Xr(e,t).dropSync(),e.dbis!==void 0&&delete e.dbis[t],Xr(e,bn).removeSync(t)}a(l$,"dropDBI");function _$(e,t,r){let n;for(let s=0;s<r.length;s++){let i=r[s];if(!e.dbis[i])try{Xr(e,i)}catch(o){if(o.message===tr.DBI_DOES_NOT_EXIST)Kb(e,i,i!==t,i===t),n=!0;else throw o}}n&&ZV()}a(_$,"initializeDBIs");Wb.exports={openDBI:Xr,openEnvironment:Vb,createEnvironment:n$,listDBIs:Yb,listDBIDefinitions:o$,createDBI:Kb,dropDBI:l$,statDBI:c$,deleteEnvironment:i$,initializeDBIs:_$,TransactionCursor:jh,environmentDataSize:u$,copyEnvironment:s$,closeEnvironment:$b}});var zb=T((Joe,Qb)=>{"use strict";var rm=class{static{a(this,"InsertRecordsResponseObject")}constructor(t=[],r=[],n=void 0){this.written_hashes=t,this.skipped_hashes=r,this.txn_time=n}};Qb.exports=rm});var jb=T((Xoe,Jb)=>{"use strict";var nm=class{static{a(this,"UpdateRecordsResponseObject")}constructor(t=[],r=[],n=void 0,s=[]){this.written_hashes=t,this.skipped_hashes=r,this.txn_time=n,this.original_records=s}};Jb.exports=nm});var Zb=T((eae,Xb)=>{"use strict";var sm=class{static{a(this,"UpsertRecordsResponseObject")}constructor(t=[],r=void 0,n=[]){this.written_hashes=t,this.txn_time=r,this.original_records=n}};Xb.exports=sm});var qo=T((iae,ry)=>{"use strict";var d$=Ve(),f$=zb(),E$=jb(),h$=Zb(),kn=Cr(),Oc=br().LMDB_ERRORS_ENUM,m$=lt(),hs=U(),p$=J(),S$=require("uuid"),rae=require("lmdb"),{handleHDBError:T$,hdb_errors:g$}=ee(),{OVERFLOW_MARKER:nae,MAX_SEARCH_KEY_LENGTH:sae}=m$,ey=Z();ey.initSync();var l_=ey.get(hs.CONFIG_PARAMS.STORAGE_PREFETCHWRITES),im=hs.TIME_STAMP_NAMES_ENUM.CREATED_TIME,Pi=hs.TIME_STAMP_NAMES_ENUM.UPDATED_TIME;async function R$(e,t,r,n,s=kn.getNextMonotonicTime()){um(e,t,r,n),om(e,t,r);let i=new f$,o=[],c=[];for(let u=0;u<n.length;u++){let _=n[u];ty(_,!0,s);let l=A$(e,t,r,_),d=_[t];o.push(l),c.push(d)}return am(o,c,n,i,s)}a(R$,"insertRecords");function A$(e,t,r,n){let s=n[t];return e.dbis[t].ifNoExists(s,()=>{for(let i=0;i<r.length;i++){let o=r[i];if(o===t||n.hasOwnProperty(o)===!1)continue;let c=n[o];if(typeof c=="function"){let l=c([[{}]]);Array.isArray(l)&&(c=l[0][hs.FUNC_VAL],n[o]=c)}let u=kn.getIndexedValues(c),_=e.dbis[o];if(u){l_&&_.prefetch(u.map(l=>({key:l,value:s})),__);for(let l=0,d=u.length;l<d;l++)_.put(u[l],s)}}l_&&e.dbis[t].prefetch([s],__),e.dbis[t].put(s,n,n[Pi])})}a(A$,"insertRecord");function O$(e,t=[]){let r=0;for(let n=0;n<t.length;n++){let s=t[n];e.splice(s-r,1),r++}}a(O$,"removeSkippedRecords");function ty(e,t,r){let n=r>0;(n||!Number.isInteger(e[Pi]))&&(e[Pi]=r||(r=kn.getNextMonotonicTime())),t===!0?(n||!Number.isInteger(e[im]))&&(e[im]=r||kn.getNextMonotonicTime()):delete e[im]}a(ty,"setTimestamps");function om(e,t,r){r.indexOf(hs.TIME_STAMP_NAMES_ENUM.CREATED_TIME)<0&&r.push(hs.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.indexOf(hs.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)<0&&r.push(hs.TIME_STAMP_NAMES_ENUM.UPDATED_TIME),d$.initializeDBIs(e,t,r)}a(om,"initializeTransaction");async function b$(e,t,r,n,s=kn.getNextMonotonicTime()){um(e,t,r,n),om(e,t,r);let i=new E$,o=[],c=[],u=[];for(let _=0;_<n.length;_++){let l=n[_],d=l[t],f;try{f=cm(e,t,l,d,i,!0,s)}catch{i.skipped_hashes.push(d),o.push(_);continue}c.push(f),u.push(d)}return am(c,u,n,i,s,o)}a(b$,"updateRecords");async function y$(e,t,r,n,s=kn.getNextMonotonicTime()){try{um(e,t,r,n)}catch(u){throw T$(u,u.message,g$.HTTP_STATUS_CODES.BAD_REQUEST)}om(e,t,r);let i=new h$,o=[],c=[];for(let u=0;u<n.length;u++){let _=n[u],l;p$.isEmpty(_[t])?(l=S$.v4(),_[t]=l):l=_[t];let d=cm(e,t,_,l,i,!1,s);o.push(d),c.push(l)}return am(o,c,n,i,s)}a(y$,"upsertRecords");async function am(e,t,r,n,s,i=[]){let o=await Promise.all(e);for(let c=0,u=o.length;c<u;c++)o[c]===!0?n.written_hashes.push(t[c]):(n.skipped_hashes.push(t[c]),i.push(c));return n.txn_time=s||kn.getNextMonotonicTime(),O$(r,i),n}a(am,"finalizeWrite");function cm(e,t,r,n,s,i=!1,o){let c=e.dbis[t],u=c.getEntry(n),_=u?.value,l=_;if(!_){if(i)return!1;_={}}if(ty(r,!l,o),Number.isInteger(r[Pi])&&_[Pi]>r[Pi])return!1;l&&s.original_records.push(_);let d,f=a(()=>{for(let h in r){if(!r.hasOwnProperty(h)||h===t)continue;let p=r[h],S=e.dbis[h];if(S===void 0)continue;let O=_[h];if(typeof p=="function"){let R=p([[_]]);Array.isArray(R)&&(p=R[0][hs.FUNC_VAL],r[h]=p)}if(p===O)continue;let g=kn.getIndexedValues(O);if(g){l_&&S.prefetch(g.map(R=>({key:R,value:n})),__);for(let R=0,B=g.length;R<B;R++)S.remove(g[R],n)}if(g=kn.getIndexedValues(p),g){l_&&S.prefetch(g.map(R=>({key:R,value:n})),__);for(let R=0,B=g.length;R<B;R++)S.put(g[R],n)}}let E=Object.assign({},_,r);c.put(n,E,E[Pi])},"do_put");return u?d=c.ifVersion(n,u.version,f):d=c.ifNoExists(n,f),d.then(E=>E?!0:cm(e,t,r,n,s,i,o))}a(cm,"updateUpsertRecord");function N$(e,t,r){if(kn.validateEnv(e),t===void 0)throw new Error(Oc.HASH_ATTRIBUTE_REQUIRED);if(!Array.isArray(r))throw r===void 0?new Error(Oc.WRITE_ATTRIBUTES_REQUIRED):new Error(Oc.WRITE_ATTRIBUTES_MUST_BE_ARRAY)}a(N$,"validateBasic");function um(e,t,r,n){if(N$(e,t,r),!Array.isArray(n))throw n===void 0?new Error(Oc.RECORDS_REQUIRED):new Error(Oc.RECORDS_MUST_BE_ARRAY)}a(um,"validateWrite");function __(){}a(__,"noop");ry.exports={insertRecords:R$,updateRecords:b$,upsertRecords:y$}});var vi=T((aae,w$)=>{w$.exports={hdb_table:{hash_attribute:"id",name:"hdb_table",schema:"system",residence:["*"],attributes:[{attribute:"id"},{attribute:"name"},{attribute:"hash_attribute"},{attribute:"schema"},{attribute:"residence"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_attribute:{hash_attribute:"id",name:"hdb_attribute",schema:"system",residence:["*"],attributes:[{attribute:"id"},{attribute:"schema"},{attribute:"table"},{attribute:"attribute"},{attribute:"schema_table"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_schema:{hash_attribute:"name",name:"hdb_schema",schema:"system",residence:["*"],attributes:[{attribute:"name"},{attribute:"createddate"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_user:{hash_attribute:"username",name:"hdb_user",schema:"system",residence:["*"],attributes:[{attribute:"username"},{attribute:"password"},{attribute:"role"},{attribute:"active"},{attribute:"hash"},{attribute:"refresh_token"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_role:{hash_attribute:"id",name:"hdb_role",schema:"system",attributes:[{attribute:"id"},{attribute:"role"},{attribute:"permission"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}],residence:["*"]},hdb_job:{hash_attribute:"id",name:"hdb_job",schema:"system",attributes:[{attribute:"id"},{attribute:"user"},{attribute:"type"},{attribute:"status"},{attribute:"start_datetime"},{attribute:"end_datetime"},{attribute:"message"},{attribute:"created_datetime"},{attribute:"request"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_license:{hash_attribute:"license_key",name:"hdb_license",schema:"system",attributes:[{attribute:"license_key"},{attribute:"company"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_info:{hash_attribute:"info_id",name:"hdb_info",schema:"system",attributes:[{attribute:"info_id"},{attribute:"data_version_num"},{attribute:"hdb_version_num"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_nodes:{hash_attribute:"name",name:"hdb_nodes",schema:"system",attributes:[{attribute:"name"},{attribute:"subscriptions"},{attribute:"system_info"},{attribute:"__createdtime__"},{attribute:"__updatedtime__"}]},hdb_analytics:{hash_attribute:"id",name:"hdb_analytics",schema:"system",audit:!1,attributes:[{attribute:"id"},{attribute:"time"},{attribute:"metric"}]},hdb_raw_analytics:{hash_attribute:"id",name:"hdb_raw_analytics",schema:"system",audit:!1,attributes:[{attribute:"id"},{attribute:"time"},{attribute:"metrics"}]},hdb_temp:{hash_attribute:"id",name:"hdb_temp",schema:"system",attributes:[{attribute:"id"}]},hdb_durable_session:{hash_attribute:"id",name:"hdb_durable_session",schema:"system",attributes:[{attribute:"id"}]},hdb_session_will:{hash_attribute:"id",name:"hdb_session_will",schema:"system",attributes:[{attribute:"id"}]}}});var $n=T((cae,iy)=>{"use strict";var sy=J(),ny=U(),Fo=/^[\x20-\x2E|\x30-\x5F|\x61-\x7E]*$/,Vn=require("joi"),Js={schema_format:{pattern:Fo,message:"names cannot include backticks or forward slashes"},schema_length:{minimum:1,maximum:250,tooLong:"cannot exceed 250 characters"}},I$=Vn.alternatives(Vn.string().min(1).max(Js.schema_length.maximum).pattern(Fo).messages({"string.pattern.base":"{:#label} "+Js.schema_format.message}),Vn.number(),Vn.array()).required(),C$=Vn.alternatives(Vn.string().min(1).max(Js.schema_length.maximum).pattern(Fo).messages({"string.pattern.base":"{:#label} "+Js.schema_format.message}),Vn.number()),D$=Vn.alternatives(Vn.string().min(1).max(Js.schema_length.maximum).pattern(Fo).messages({"string.pattern.base":"{:#label} "+Js.schema_format.message}),Vn.number()).required();function L$(e,t){return t?typeof t!="string"?`'${e}' must be a string`:t.length?t.length>Js.schema_length.maximum?`'${e}' maximum of 250 characters`:Fo.test(t)?"":`'${e}' has illegal characters`:`'${e}' must be at least one character`:`'${e}' is required`}a(L$,"checkValidTable");function M$(e,t){return sy.doesSchemaExist(e)?e:t.message(`Database '${e}' does not exist`)}a(M$,"validateSchemaExists");function U$(e,t){let r=t.state.ancestors[0].schema;return sy.doesTableExist(r,e)?e:t.message(`Table '${e}' does not exist`)}a(U$,"validateTableExists");function P$(e,t){return e.toLowerCase()===ny.SYSTEM_SCHEMA_NAME?t.message(`'subscriptions[${t.state.path[1]}]' invalid database name, '${ny.SYSTEM_SCHEMA_NAME}' name is reserved`):e}a(P$,"validateSchemaName");iy.exports={common_validators:Js,schema_regex:Fo,hdb_schema_table:I$,validateSchemaExists:M$,validateTableExists:U$,validateSchemaName:P$,checkValidTable:L$,hdb_database:C$,hdb_table:D$}});var d_=T((lae,oy)=>{var{common_validators:Yn}=$n(),yc=je(),bc="is required",_t={database:{presence:!1,format:Yn.schema_format,length:Yn.schema_length},schema:{presence:!1,format:Yn.schema_format,length:Yn.schema_length},table:{presence:!0,format:Yn.schema_format,length:Yn.schema_length},attribute:{presence:!0,format:Yn.schema_format,length:Yn.schema_length},hash_attribute:{presence:!0,format:Yn.schema_format,length:Yn.schema_length}};function Nc(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(Nc,"makeAttributesStrings");function v$(e){return e=Nc(e),_t.table.presence=!1,_t.attribute.presence=!1,_t.hash_attribute.presence=!1,yc.validateObject(e,_t)}a(v$,"schema_object");function B$(e){return e=Nc(e),_t.table.presence={message:bc},_t.attribute.presence=!1,_t.hash_attribute.presence=!1,yc.validateObject(e,_t)}a(B$,"table_object");function H$(e){return e=Nc(e),_t.table.presence={message:bc},_t.attribute.presence=!1,yc.validateObject(e,_t)}a(H$,"create_table_object");function x$(e){return e=Nc(e),_t.table.presence={message:bc},_t.attribute.presence={message:bc},_t.hash_attribute.presence=!1,yc.validateObject(e,_t)}a(x$,"attribute_object");function q$(e){return e=Nc(e),_t.table.presence={message:bc},_t.attribute.presence=!1,_t.hash_attribute.presence=!1,yc.validateObject(e,_t)}a(q$,"describe_table");function F$(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(F$,"validateTableResidence");oy.exports={schema_object:v$,create_table_object:H$,table_object:B$,attribute_object:x$,describe_table:q$,validateTableResidence:F$}});var cy=T((dae,ay)=>{"use strict";var G$=require("uuid"),lm=class{static{a(this,"CreateAttributeObject")}constructor(t,r,n,s){this.schema=t,this.table=r,this.attribute=n,this.id=s||G$.v4(),this.schema_table=`${this.schema}.${this.table}`}};ay.exports=lm});var f_=T((Eae,uy)=>{"use strict";var k$=cy(),_m=class extends k${static{a(this,"LMDBCreateAttributeObject")}constructor(t,r,n,s,i=!0,o=!1){super(t,r,n,s),this.dup_sort=i,this.is_hash_attribute=o}};uy.exports=_m});var _y=T((mae,ly)=>{"use strict";ly.exports=$$;var V$="inserted";function $$(e,t,r,n){let s={message:`${e} ${t.length} of ${r.records.length} records`,skipped_hashes:n};return e===V$?(s.inserted_hashes=t,s):(s.update_hashes=t,s)}a($$,"returnObject")});var E_=T((Sae,my)=>{"use strict";var Y$=U(),dm=Ve(),K$=qo(),{getSystemSchemaPath:W$,getSchemaPath:Q$}=Ye(),z$=vi(),J$=d_(),j$=f_(),X$=_y(),{handleHDBError:dy,hdb_errors:Ey}=ee(),fy=J(),{HTTP_STATUS_CODES:Z$}=Ey,fm=z$.hdb_attribute,hy=[];for(let e=0;e<fm.attributes.length;e++)hy.push(fm.attributes[e].attribute);var e1="inserted";my.exports=t1;async function t1(e){let t=J$.attribute_object(e);if(t)throw dy(new Error,t.message,Ey.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0);let r=!e.skip_table_check&&fy.checkGlobalSchemaTable(e.schema,e.table);if(r)throw dy(new Error,r,Z$.NOT_FOUND);e.is_hash_attribute=e.is_hash_attribute=="true",e.dup_sort=fy.isEmpty(e.dup_sort)||e.dup_sort=="true";let n=[];if(global.hdb_schema[e.schema]&&global.hdb_schema[e.schema][e.table]&&(n=global.hdb_schema[e.schema][e.table].attributes),Array.isArray(n)&&n.length>0){for(let i of n)if(i.attribute===e.attribute)throw new Error(`attribute '${i.attribute}' already exists in ${e.schema}.${e.table}`)}let s=new j$(e.schema,e.table,e.attribute,e.id);try{let i=await dm.openEnvironment(Q$(e.schema,e.table),e.table);if(i.dbis[e.attribute]!==void 0)throw new Error(`attribute '${e.attribute}' already exists in ${e.schema}.${e.table}`);dm.createDBI(i,e.attribute,e.dup_sort,e.is_hash_attribute);let o=await dm.openEnvironment(W$(),Y$.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME),{written_hashes:c,skipped_hashes:u}=await K$.insertRecords(o,fm.hash_attribute,hy,[s]);return X$(e1,c,{records:[s]},u)}catch(i){throw i}}a(t1,"lmdbCreateAttribute")});var hm=T((gae,Sy)=>{var{hdb_table:r1,hdb_database:py}=$n(),n1=je(),Em=require("joi"),s1={undefined:"undefined",null:"null"},i1=a((e,t)=>{let r=Object.keys(e),n=r.length,s;for(let i=0;i<n;i++){let o=r[i];(!o||o.length===0||s1[o]!==void 0)&&(s===void 0?s=`Invalid attribute name: '${o}'`:s+=`. Invalid attribute name: '${o}'`)}return s?t.message(s):e},"custom_records_val"),o1=Em.object({database:py,schema:py,table:r1,records:Em.array().items(Em.object().custom(i1)).required()});Sy.exports=function(e){return n1.validateBySchema(e,o1)}});var wc=T((Oae,gy)=>{"use strict";var ms=J(),Ty=K(),Aae=hm(),{getDatabases:a1}=(be(),te(qe)),{ClientError:Bi}=ee();gy.exports=c1;function c1(e){if(ms.isEmpty(e))throw new Bi("invalid update parameters defined.");if(ms.isEmptyOrZeroLength(e.schema))throw new Bi("invalid schema specified.");if(ms.isEmptyOrZeroLength(e.table))throw new Bi("invalid table specified.");if(!Array.isArray(e.records))throw new Bi("records must be an array");let t=a1()[e.schema]?.[e.table];if(ms.isEmpty(t))throw new Bi(`could not retrieve schema:${e.schema} and table ${e.table}`);let r=t.primaryKey,n=new Set,s={},i=!1;return e.operation==="update"&&(i=!0),e.records.forEach(o=>{if(i&&ms.isEmptyOrZeroLength(o[r]))throw Ty.error("a valid hash attribute must be provided with update record:",o),new Bi("a valid hash attribute must be provided with update record, check log for more info");if(!ms.isEmptyOrZeroLength(o[r])&&(o[r]==="null"||o[r]==="undefined"))throw Ty.error(`a valid hash value must be provided with ${e.operation} record:`,o),new Bi(`Invalid hash value: '${o[r]}' is not a valid hash attribute value, check log for more info`);!ms.isEmpty(o[r])&&o[r]!==""&&n.has(ms.autoCast(o[r]))&&(o.skip=!0),n.add(ms.autoCast(o[r]));for(let c in o)s[c]=1}),s[r]=1,{schema_table:t,hashes:Array.from(n),attributes:Object.keys(s)}}a(c1,"insertUpdateValidate")});var Ic=T((yae,Ry)=>{"use strict";var u1=U().OPERATIONS_ENUM,mm=class{static{a(this,"InsertObject")}constructor(t,r,n,s,i=void 0){this.operation=u1.INSERT,this.schema=t,this.table=r,this.hash_attribute=n,this.records=s,this.__origin=i}};Ry.exports=mm});var Mc=T((Iae,Ay)=>{"use strict";var wae=Ic(),h_=U(),Sm=J(),pm=K(),l1=require("uuid"),{handleHDBError:Cc,hdb_errors:_1}=ee(),{HDB_ERROR_MSGS:Dc,HTTP_STATUS_CODES:Lc}=_1;Ay.exports=d1;function d1(e,t,r){for(let s=0;s<t.length;s++)f1(t[s]);let{records:n}=e;for(let s=0;s<n.length;s++){let i=n[s];E1(i,r,e.operation)}}a(d1,"processRows");function f1(e){if(Buffer.byteLength(String(e))>h_.INSERT_MODULE_ENUM.MAX_CHARACTER_SIZE)throw Cc(new Error,Dc.ATTR_NAME_LENGTH_ERR(e),Lc.BAD_REQUEST,void 0,void 0,!0);if(Sm.isEmptyOrZeroLength(e)||Sm.isEmpty(e.trim()))throw Cc(new Error,Dc.ATTR_NAME_NULLISH_ERR,Lc.BAD_REQUEST,void 0,void 0,!0)}a(f1,"validateAttribute");function E1(e,t,r){if(!e.hasOwnProperty(t)||Sm.isEmptyOrZeroLength(e[t])){if(r===h_.OPERATIONS_ENUM.INSERT||r===h_.OPERATIONS_ENUM.UPSERT){e[t]=l1.v4();return}throw pm.error("Update transaction aborted due to record with no hash value:",e),Cc(new Error,Dc.RECORD_MISSING_HASH_ERR,Lc.BAD_REQUEST,void 0,void 0,!0)}if(Buffer.byteLength(String(e[t]))>h_.INSERT_MODULE_ENUM.MAX_CHARACTER_SIZE)throw pm.error(e),Cc(new Error,Dc.HASH_VAL_LENGTH_ERR,Lc.BAD_REQUEST,void 0,void 0,!0);if(isNaN(e[t])&&e[t].includes("/"))throw pm.error(e),Cc(new Error,Dc.INVALID_FORWARD_SLASH_IN_HASH_ERR,Lc.BAD_REQUEST,void 0,void 0,!0)}a(E1,"validateHash")});var by=T((Dae,Oy)=>{"use strict";var Tm=class{static{a(this,"ITCEventObject")}constructor(t,r){this.type=t,this.message=r}};Oy.exports=Tm});var wy=T((Mae,Ny)=>{"use strict";var gm=Ve(),h1=K(),yy=br().LMDB_ERRORS_ENUM;Ny.exports=m1;async function m1(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 gm.closeEnvironment(global.lmdb_map[o])}catch(c){if(c.message!==yy.ENV_REQUIRED)throw c}}break;case"drop_table":let n=`${e.schema}.${e.table}`,s=`txn.${n}`;try{await gm.closeEnvironment(global.lmdb_map[n]),await gm.closeEnvironment(global.lmdb_map[s])}catch(i){if(i.message!==yy.ENV_REQUIRED)throw i}break;case"drop_attribute":r=global.lmdb_map[`${e.schema}.${e.table}`],r!==void 0&&typeof r.dbis=="object"&&r.dbis[`${e.attribute}`]!==void 0&&delete r.dbis[`${e.attribute}`];break;default:break}}}catch(t){h1.error(t)}}a(m1,"cleanLMDBMap")});var ps=T((Pae,Ly)=>{"use strict";var Uc=require("crypto"),p1=Z(),{CONFIG_PARAMS:S1}=U(),Cy="aes-256-cbc",T1=32,g1=16,Rm=64,Dy=32,R1=Rm+Dy,Iy=new Map;Ly.exports={encrypt:A1,decrypt:O1,createNatsTableStreamName:b1};function A1(e){let t=Uc.randomBytes(T1),r=Uc.randomBytes(g1),n=Uc.createCipheriv(Cy,Buffer.from(t),r),s=n.update(e);s=Buffer.concat([s,n.final()]);let i=t.toString("hex"),o=r.toString("hex"),c=s.toString("hex");return i+o+c}a(A1,"encrypt");function O1(e){let t=e.substr(0,Rm),r=e.substr(Rm,Dy),n=e.substr(R1,e.length),s=Buffer.from(r,"hex"),i=Buffer.from(n,"hex"),o=Uc.createDecipheriv(Cy,Buffer.from(t,"hex"),s),c=o.update(i);return c=Buffer.concat([c,o.final()]),c.toString()}a(O1,"decrypt");function b1(e,t){let r=p1.get(S1.CLUSTERING_DATABASELEVEL)?e:`${e}.${t}`,n=Iy.get(r);return n||(n=Uc.createHash("md5").update(r).digest("hex"),Iy.set(r,n)),n}a(b1,"createNatsTableStreamName")});var Hi=T((Hae,Uy)=>{"use strict";var Bae=Zr(),m_=K(),My=d_(),y1=ps(),p_=J(),{handleHDBError:S_,hdb_errors:N1}=ee(),{HDB_ERROR_MSGS:T_,HTTP_STATUS_CODES:Am}=N1,w1=Z();w1.initSync();var{getDatabases:Om}=(be(),te(qe));Uy.exports={describeAll:I1,describeTable:g_,describeSchema:C1};async function I1(e){try{let t=p_.isEmptyOrZeroLength(e),r,n;t||(r=e.hdb_user.role.permission,n=r.super_user||r.cluster_user);let s=Om(),i={},o={},c=[],u=e?.exact_count;for(let l in s){i[l]=!0,!t&&!n&&(o[l]=e.hdb_user.role.permission[l].describe);let d=s[l];for(let f in d)try{let E;if(t||n)E=await g_({schema:l,table:f,exact_count:u});else if(r&&r[l].describe&&r[l].tables[f].describe){let h=r[l].tables[f].attribute_permissions;E=await g_({schema:l,table:f,exact_count:u},h)}E&&c.push(E)}catch(E){m_.error(E)}}let _={};for(let l in c)t||n?(_[c[l].schema]==null&&(_[c[l].schema]={}),_[c[l].schema][c[l].name]=c[l],i[c[l].schema]&&delete i[c[l].schema]):o[c[l].schema]&&(_[c[l].schema]==null&&(_[c[l].schema]={}),_[c[l].schema][c[l].name]=c[l],i[c[l].schema]&&delete i[c[l].schema]);for(let l in i)t||n?_[l]={}:o[l]&&(_[l]={});return _}catch(t){return m_.error("Got an error in describeAll"),m_.error(t),S_(new Error,T_.DESCRIBE_ALL_ERR)}}a(I1,"describeAll");async function g_(e,t){p_.transformReq(e);let{schema:r,table:n}=e;r=r?.toString(),n=n?.toString();let s=t;e.hdb_user&&!e.hdb_user.role.permission.super_user&&(s=e.hdb_user.role.permission[r].tables[n].attribute_permissions);let i=My.describe_table(e);if(i)throw i;let c=Om()[r];if(!c)throw S_(new Error,T_.SCHEMA_NOT_FOUND(e.schema),Am.NOT_FOUND);let u=c[n];if(!u)throw S_(new Error,T_.TABLE_NOT_FOUND(e.schema,e.table),Am.NOT_FOUND);function _(f){l.push(Object.assign({},{attribute:f.attribute,type:f.type,elements:f.elements?.type,indexed:f.indexed,is_primary_key:f.isPrimaryKey,assigned_created_time:f.assignCreatedTime,assigned_updated_time:f.assignUpdatedTime,nullable:f.nullable,properties:f.properties?f.properties.map(E=>({type:E.type,name:E.name})):void 0}))}a(_,"pushAtt");let l=[];if(s){let f={};s.forEach(E=>{E.describe&&(f[E.attribute_name]=!0)}),u.attributes.forEach(E=>{f[E.name]&&_(E)})}else u.attributes?.forEach(f=>_(f));let d={schema:r,name:u.tableName,hash_attribute:u.attributes.find(f=>f.isPrimaryKey||f.is_hash_attribute)?.name,audit:u.audit,schema_defined:u.schemaDefined,attributes:l};d.clustering_stream_name=y1.createNatsTableStreamName(d.schema,d.name);try{let f=u.getRecordCount({exactCount:e.exact_count==="true"});d.record_count=f.recordCount,d.estimated_record_range=f.estimatedRange;let E=u.auditStore;if(E)for(let h of E.getKeys({reverse:!0,limit:1}))d.last_updated_record=h[0];if(!d.last_updated_record&&u.indices.__updatedtime__)for(let h of u.indices.__updatedtime__.getKeys({reverse:!0,limit:1}))d.last_updated_record=h}catch(f){m_.warn(`unable to stat table dbi due to ${f}`)}return d}a(g_,"descTable");async function C1(e){p_.transformReq(e);let t=My.schema_object(e);if(t)throw t;let r;e.hdb_user&&!e.hdb_user.role.permission.super_user&&(r=e.hdb_user.role.permission[e.schema]);let n=e.schema.toString(),i=Om()[n];if(!i)throw S_(new Error,T_.SCHEMA_NOT_FOUND(e.schema),Am.NOT_FOUND);let o={};for(let c in i){let u;if(r&&r.tables[c]&&(u=r.tables[c]),p_.isEmpty(u)||u.describe){let _=await g_({schema:e.schema,table:c,exact_count:e.exact_count},u?u.attribute_permissions:null);_&&(o[_.name]=_)}}return o}a(C1,"describeSchema")});var Ss=T((Gae,xy)=>{var D1=vi(),{callbackify:vy,promisify:L1}=require("util"),{getDatabases:By}=(be(),te(qe));xy.exports={setSchemaDataToGlobal:Py,getTableSchema:M1,getSystemSchema:U1,setSchemaDataToGlobalAsync:L1(Py)};var Hy=Hi(),qae=vy(Hy.describeAll),Fae=vy(Hy.describeTable);function Py(e){global.hdb_schema=By(),e&&e()}a(Py,"setSchemaDataToGlobal");function M1(e,t,r){let n=By()[e];if(!n)return r(`schema ${e} does not exist`);let s=n[t];return s?r(null,{schema:e,name:t,hash_attribute:s.primaryKey}):r(`table ${e}.${t} does not exist`)}a(M1,"getTableSchema");function U1(){return D1}a(U1,"getSystemSchema")});var en=T((Vae,ky)=>{"use strict";var A_=hm(),Bt=J(),P1=require("util"),O_=yn(),v1=Ss(),qy=K(),{handleHDBError:xi,hdb_errors:B1}=ee(),{HTTP_STATUS_CODES:qi}=B1,H1=P1.promisify(v1.getTableSchema),x1="updated",Fy="inserted",Gy="upserted";ky.exports={insert:F1,update:G1,upsert:k1,validation:q1,flush:V1};async function q1(e){if(Bt.isEmpty(e))throw new Error("invalid update parameters defined.");if(Bt.isEmptyOrZeroLength(e.schema))throw new Error("invalid database specified.");if(Bt.isEmptyOrZeroLength(e.table))throw new Error("invalid table specified.");let t=await H1(e.schema,e.table),r=A_(e);if(r)throw r;if(!Array.isArray(e.records))throw new Error("records must be an array");let n=t.hash_attribute,s=new Set,i={},o=!1;return e.operation==="update"&&(o=!0),e.records.forEach(c=>{if(o&&Bt.isEmptyOrZeroLength(c[n]))throw qy.error("a valid hash attribute must be provided with update record:",c),new Error("a valid hash attribute must be provided with update record");if(!Bt.isEmptyOrZeroLength(c[n])&&(c[n]==="null"||c[n]==="undefined"))throw qy.error(`a valid hash value must be provided with ${e.operation} record:`,c),new Error(`"${c[n]}" is not a valid hash attribute value`);!Bt.isEmpty(c[n])&&c[n]!==""&&s.has(Bt.autoCast(c[n]))&&(c.skip=!0),s.add(Bt.autoCast(c[n]));for(let u in c)i[u]=1}),i[n]=1,{schema_table:t,hashes:Array.from(s),attributes:Object.keys(i)}}a(q1,"validation");async function F1(e){if(e.operation!=="insert")throw new Error("invalid operation, must be insert");let t=A_(e);if(t)throw xi(new Error,t.message,qi.BAD_REQUEST);Bt.transformReq(e);let r=Bt.checkSchemaTableExist(e.schema,e.table);if(r)throw xi(new Error,r,qi.BAD_REQUEST);let n=await O_.createRecords(e);return R_(Fy,n.written_hashes,e,n.skipped_hashes,n.new_attributes,n.txn_time)}a(F1,"insertData");async function G1(e){if(e.operation!=="update")throw new Error("invalid operation, must be update");let t=A_(e);if(t)throw xi(new Error,t.message,qi.BAD_REQUEST);Bt.transformReq(e);let r=Bt.checkSchemaTableExist(e.schema,e.table);if(r)throw xi(new Error,r,qi.BAD_REQUEST);let n=await O_.updateRecords(e);return Bt.isEmpty(n.existing_rows)?R_(x1,n.written_hashes,e,n.skipped_hashes,n.new_attributes,n.txn_time):R_(n.update_action,[],e,n.hashes,void 0,n.txn_time)}a(G1,"updateData");async function k1(e){if(e.operation!=="upsert")throw xi(new Error,"invalid operation, must be upsert",qi.INTERNAL_SERVER_ERROR);let t=A_(e);if(t)throw xi(new Error,t.message,qi.BAD_REQUEST);Bt.transformReq(e);let r=Bt.checkSchemaTableExist(e.schema,e.table);if(r)throw xi(new Error,r,qi.BAD_REQUEST);let n=await O_.upsertRecords(e);return R_(Gy,n.written_hashes,e,[],n.new_attributes,n.txn_time)}a(k1,"upsertData");function R_(e,t,r,n,s,i){let o={message:`${e} ${t.length} of ${t.length+n.length} records`,new_attributes:s,txn_time:i};return e===Fy?(o.inserted_hashes=t,o.skipped_hashes=n,o):e===Gy?(o.upserted_hashes=t,o):(o.update_hashes=t,o.skipped_hashes=n,o)}a(R_,"returnObject");function V1(e){return Bt.transformReq(e),O_.flush(e.schema,e.table)}a(V1,"flush")});var ym=T((Yae,Yy)=>{var $1=je(),bm=require("joi"),{hdb_table:Y1,hdb_database:Vy}=$n(),$y={schema:Vy,database:Vy,table:Y1},K1={date:bm.date().iso().required()},W1={timestamp:bm.date().timestamp().required().messages({"date.format":"'timestamp' is invalid"})};Yy.exports=function(e,t){let r=t==="timestamp"?{...$y,...W1}:{...$y,...K1},n=bm.object(r);return $1.validateBySchema(e,n)}});var Qy=T((Kae,Wy)=>{var Q1=je(),Nm=require("joi"),{hdb_table:z1,hdb_database:Ky}=$n(),J1=Nm.object({schema:Ky,database:Ky,table:z1,hash_values:Nm.array().required(),ids:Nm.array()});Wy.exports=function(e){return Q1.validateBySchema(e,J1)}});var Jy=T((Wae,zy)=>{"use strict";var wm=class{static{a(this,"InsertObject")}constructor(t,r,n,s,i){this.operation=t,this.schema=r,this.table=n,this.hash_attribute=s,this.records=i}},Im=class{static{a(this,"NoSQLSeachObject")}constructor(t,r,n,s,i,o){this.schema=t,this.table=r,this.search_attribute=n,this.hash_attribute=s,this.get_attributes=i,this.search_value=o}},Cm=class{static{a(this,"DeleteResponseObject")}constructor(){this.message=void 0,this.deleted_hashes=[],this.skipped_hashes=[]}};zy.exports={InsertObject:wm,NoSQLSeachObject:Im,DeleteResponseObject:Cm}});var ki=T((zae,tN)=>{"use strict";var Xy=ym(),j1=Qy(),Fi=J(),jy=require("moment"),Zy=K(),{promisify:X1,callbackify:Z1}=require("util"),Gi=U(),eY=Ss(),Dm=X1(eY.getTableSchema),Lm=yn(),{DeleteResponseObject:tY}=Jy(),{handleHDBError:js,hdb_errors:rY}=ee(),{HDB_ERROR_MSGS:b_,HTTP_STATUS_CODES:Xs}=rY,nY="records successfully deleted",sY=Z1(eN);tN.exports={delete:sY,deleteRecord:eN,deleteFilesBefore:iY,deleteAuditLogsBefore:oY};async function iY(e){let t=Xy(e,"date");if(t)throw js(t,t.message,Xs.BAD_REQUEST,void 0,void 0,!0);if(Fi.transformReq(e),!jy(e.date,jy.ISO_8601).isValid())throw js(new Error,b_.INVALID_DATE,Xs.BAD_REQUEST,Gi.LOG_LEVELS.ERROR,b_.INVALID_DATE,!0);let n=Fi.checkSchemaTableExist(e.schema,e.table);if(n)throw js(new Error,n,Xs.NOT_FOUND,Gi.LOG_LEVELS.ERROR,n,!0);let s=await Lm.deleteRecordsBefore(e);if(await Dm(e.schema,e.table),Zy.info(`Finished deleting files before ${e.date}`),s&&s.message)return s.message}a(iY,"deleteFilesBefore");async function oY(e){let t=Xy(e,"timestamp");if(t)throw js(t,t.message,Xs.BAD_REQUEST,void 0,void 0,!0);if(Fi.transformReq(e),isNaN(e.timestamp))throw js(new Error,b_.INVALID_VALUE("Timestamp"),Xs.BAD_REQUEST,Gi.LOG_LEVELS.ERROR,b_.INVALID_VALUE("Timestamp"),!0);let r=Fi.checkSchemaTableExist(e.schema,e.table);if(r)throw js(new Error,r,Xs.NOT_FOUND,Gi.LOG_LEVELS.ERROR,r,!0);let n=await Lm.deleteAuditLogsBefore(e);return await Dm(e.schema,e.table),Zy.info(`Finished deleting audit logs before ${e.timestamp}`),n}a(oY,"deleteAuditLogsBefore");async function eN(e){e.ids&&(e.hash_values=e.ids);let t=j1(e);if(t)throw js(t,t.message,Xs.BAD_REQUEST,void 0,void 0,!0);Fi.transformReq(e);let r=Fi.checkSchemaTableExist(e.schema,e.table);if(r)throw js(new Error,r,Xs.NOT_FOUND,Gi.LOG_LEVELS.ERROR,r,!0);try{await Dm(e.schema,e.table);let n=await Lm.deleteRecords(e);return Fi.isEmptyOrZeroLength(n.message)&&(n.message=`${n.deleted_hashes.length} of ${e.hash_values.length} ${nY}`),n}catch(n){if(n.message===Gi.SEARCH_NOT_FOUND_MESSAGE){let s=new tY;return s.message=Gi.SEARCH_NOT_FOUND_MESSAGE,s.skipped_hashes=e.hash_values.length,s.deleted_hashes=0,s}throw n}}a(eN,"deleteRecord")});var y_=T((jae,sN)=>{var aY=require("crypto"),rN=9;function cY(e){let t=lY(rN),r=nN(e+t);return t+r}a(cY,"createHash");function uY(e,t){let r=e?.substr(0,rN),n=r+nN(t+r);return e===n}a(uY,"validateHash");function lY(e){let t="0123456789abcdefghijklmnopqurstuvwxyzABCDEFGHIJKLMNOPQURSTUVWXYZ",r=t.length,n="";for(let s=0;s<e;s++){let i=Math.floor(Math.random()*r);n+=t[i]}return n}a(lY,"generateSalt");function nN(e){return aY.createHash("md5").update(e).digest("hex")}a(nN,"md5");sN.exports={hash:cY,validate:uY}});var oN=T((Zae,iN)=>{var Mm=je(),Vt={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 _Y(e){return Vt.password.presence=!0,Vt.username.presence=!0,Vt.role.presence=!0,Vt.active.presence=!0,Mm.validateObject(e,Vt)}a(_Y,"addUserValidation");function dY(e){return Vt.password.presence=!1,Vt.username.presence=!0,Vt.role.presence=!1,Vt.active.presence=!1,Mm.validateObject(e,Vt)}a(dY,"alterUserValidation");function fY(e){return Vt.password.presence=!1,Vt.username.presence=!0,Vt.role.presence=!1,Vt.active.presence=!1,Mm.validateObject(e,Vt)}a(fY,"dropUserValidation");iN.exports={addUserValidation:_Y,alterUserValidation:dY,dropUserValidation:fY}});var tt=T((rce,cN)=>{"use strict";var{platform:tce}=require("os"),EY="nats-server.zip",Um="nats-server",hY=process.platform==="win32"?`${Um}.exe`:Um,Pm="HDB",mY=/^[^\s.,*>]+$/,aN="__request__",pY=a(e=>`${e}.${aN}`,"REQUEST_SUBJECT"),SY={NATS_MSG_ID:"Nats-Msg-Id",ORIGIN:"origin",TRANSACTED_NODES:"transacted_nodes"},TY={HUB_SERVER:"hub.json",LEAF_SERVER:"leaf.json"},gY={HUB:"hub.pid",LEAF:"leaf.pid"},RY={HUB:"-hub",LEAF:"-leaf",ADMIN:"-admin"},AY={stream_name:"__HARPERDB_WORK_QUEUE__",durable_name:"HDB_WORK_QUEUE",deliver_group:Pm,deliver_subject:"__HDB__.WORKQUEUE"},OY={stream_name:"__HARPERDB_SCHEMA_QUEUE__",durable_name:"HDB_SCHEMA_QUEUE",deliver_group:Pm,deliver_subject:"HDB.SCHEMAQUEUE"},bY={stream_name:"__HARPERDB_USER_QUEUE__",durable_name:"HDB_USER_QUEUE",deliver_group:Pm,deliver_subject:"HDB.USERQUEUE"},yY={SUCCESS:"success",ERROR:"error"},NY={OPEN:"open",CLOSED:"closed",NO_RESPONDERS:"NoResponders",TIMEOUT:"Timeout"},wY={TXN:"txn",MSGID:"msgid"},Go={ERR:"error",WRN:"warn",INF:"info",DBG:"debug",TRC:"trace"},IY={[Go.ERR]:1,[Go.WRN]:2,[Go.INF]:3,[Go.DBG]:4,[Go.TRC]:5},CY={debug:"-D",trace:"-DVV"};cN.exports={NATS_SERVER_ZIP:EY,NATS_SERVER_NAME:Um,NATS_BINARY_NAME:hY,PID_FILES:gY,NATS_CONFIG_FILES:TY,SERVER_SUFFIX:RY,WORK_QUEUE_CONSUMER_NAMES:AY,SCHEMA_QUEUE_CONSUMER_NAMES:OY,USER_QUEUE_CONSUMER_NAMES:bY,NATS_TERM_CONSTRAINTS_RX:mY,REQUEST_SUFFIX:aN,UPDATE_REMOTE_RESPONSE_STATUSES:yY,CLUSTER_STATUS_STATUSES:NY,REQUEST_SUBJECT:pY,SUBJECT_PREFIXES:wY,MSG_HEADERS:SY,LOG_LEVELS:Go,LOG_LEVEL_FLAGS:CY,LOG_LEVEL_HIERARCHY:IY}});var lN=T((sce,uN)=>{"use strict";var N_=U(),w_=class{static{a(this,"BaseLicense")}constructor(t=0,r=N_.RAM_ALLOCATION_ENUM.DEFAULT,n=N_.LICENSE_VALUES.VERSION_DEFAULT,s){this.exp_date=t,this.ram_allocation=r,this.version=n,this.fingerprint=s}},vm=class extends w_{static{a(this,"ExtendedLicense")}constructor(t=0,r=N_.RAM_ALLOCATION_ENUM.DEFAULT,n=N_.LICENSE_VALUES.VERSION_DEFAULT,s,i=!1){super(t,r,n,s),this.enterprise=i}};uN.exports={BaseLicense:w_,ExtendedLicense:vm}});var Vi=T((oce,mN)=>{"use strict";var Vo=require("fs-extra"),dN=y_(),fN=require("crypto"),DY=require("moment"),LY=require("uuid").v4,$t=K(),Hm=require("path"),MY=J(),Zs=U(),{totalmem:_N}=require("os"),UY=lN().ExtendedLicense,ko="invalid license key format",PY="061183",vY="mofi25",BY="aes-256-cbc",HY=16,xY=32,EN=Z();EN.initSync();var Bm;mN.exports={validateLicense:hN,generateFingerPrint:FY,licenseSearch:Fm,getLicense:VY,checkMemoryLimit:$Y};function xm(){return Hm.join(EN.getHdbBasePath(),Zs.LICENSE_KEY_DIR_NAME,Zs.LICENSE_FILE_NAME)}a(xm,"getLicenseDirPath");function qY(){let e=xm();return Hm.join(e,Zs.LICENSE_FILE_NAME)}a(qY,"getLicenseFilePath");function qm(){let e=xm();return Hm.join(e,Zs.REG_KEY_FILE_NAME)}a(qm,"getFingerPrintFilePath");async function FY(){let e=qm();try{return await Vo.readFile(e,"utf8")}catch(t){if(t.code==="ENOENT")return await GY();throw $t.error(`Error writing fingerprint file to ${e}`),$t.error(t),new Error("There was an error generating the fingerprint")}}a(FY,"generateFingerPrint");async function GY(){let e=LY(),t=dN.hash(e),r=qm();try{await Vo.mkdirp(xm()),await Vo.writeFile(r,t)}catch(n){if(n.code==="EEXIST")return t;throw $t.error(`Error writing fingerprint file to ${r}`),$t.error(n),new Error("There was an error generating the fingerprint")}return t}a(GY,"writeFingerprint");function hN(e,t){let r={valid_license:!1,valid_date:!1,valid_machine:!1,exp_date:null,ram_allocation:Zs.RAM_ALLOCATION_ENUM.DEFAULT,version:Zs.LICENSE_VALUES.VERSION_DEFAULT};if(!e)return $t.error("empty license key passed to validate."),r;let n=qm(),s=!1;try{s=Vo.statSync(n)}catch(i){$t.error(i)}if(s){let i;try{i=Vo.readFileSync(n,"utf8")}catch{$t.error("error validating this machine in the license"),r.valid_machine=!1;return}let o=e.split(vY),c=o[1];c=Buffer.concat([Buffer.from(c)],HY);let u=Buffer.concat([Buffer.from(i)],xY),_=fN.createDecipheriv(BY,u,c);r.valid_date=!0,r.valid_license=!0,r.valid_machine=!0;let l=null;try{l=_.update(o[0],"hex","utf8"),l.trim(),l+=_.final("utf8")}catch{let E=kY(o[0],i);if(E)l=E;else throw r.valid_license=!1,r.valid_machine=!1,console.error(ko),$t.error(ko),new Error(ko)}let d;if(isNaN(l))try{d=JSON.parse(l),r.version=d.version,r.exp_date=d.exp_date,isNaN(r.exp_date)&&(r.exp_date=new Date(r.exp_date).getTime()),d.ram_allocation&&(r.ram_allocation=d.ram_allocation)}catch{throw console.error(ko),$t.error(ko),new Error(ko)}else r.exp_date=l;r.exp_date<DY().valueOf()&&(r.valid_date=!1),dN.validate(o[1],`${PY}${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||$t.error("Invalid licence"),r}a(hN,"validateLicense");function kY(e,t){try{let r=fN.createDecipher("aes192",t),n=r.update(e,"hex","utf8");return n.trim(),n+=r.final("utf8"),n}catch{$t.warn("Check old license failed")}}a(kY,"checkOldLicense");function Fm(){let e=new UY,t=[];try{t=Vo.readFileSync(qY(),"utf-8").split(Zs.NEW_LINE)}catch(r){r.code==="ENOENT"?$t.info("no license file found"):$t.error(`could not search for licenses due to: '${r.message}`)}for(let r=0;r<t.length;++r){let n=t[r];try{if(MY.isEmptyOrZeroLength(n))continue;let s=JSON.parse(n),i=hN(s.license_key,s.company);i.valid_machine===!0&&i.valid_date===!0&&i.valid_machine===!0&&(e.exp_date=i.exp_date>e.exp_date?i.exp_date:e.exp_date,e.ram_allocation=i.ram_allocation,e.enterprise=!0)}catch(s){$t.error("There was an error parsing the license string."),$t.error(s),e.ram_allocation=Zs.RAM_ALLOCATION_ENUM.DEFAULT,e.enterprise=!1}}return Bm=e,e}a(Fm,"licenseSearch");async function VY(){return Bm||await Fm(),Bm}a(VY,"getLicense");function $Y(){let e=Fm().ram_allocation,t=process.constrainedMemory?.()||_N();if(t=Math.round(Math.min(t,_N())/2**20),t>e)return`This server has more memory (${t}MB) than HarperDB is licensed for (${e}MB), this should only be used for educational and development purposes.`}a($Y,"checkMemoryLimit")});var Ur=T((_ce,MN)=>{"use strict";var gN="username is required",RN="nothing to update, must supply active, role or password to update",AN="password cannot be an empty string",ON="If role is specified, it cannot be empty.",bN="active must be true or false";MN.exports={addUser:ZY,alterUser:eK,dropUser:rK,getSuperUser:oK,userInfo:nK,listUsers:C_,listUsersExternal:sK,setUsersToGlobal:Yo,findAndValidateUser:DN,getClusterUser:aK,USERNAME_REQUIRED:gN,ALTERUSER_NOTHING_TO_UPDATE:RN,EMPTY_PASSWORD:AN,EMPTY_ROLE:ON,ACTIVE_BOOLEAN:bN};var yN=en(),YY=ki(),Vm=y_(),NN=oN(),wN=Zr(),$m=Ts(),Mr=J(),IN=require("validate.js"),Ae=K(),{promisify:KY}=require("util"),Ym=ps(),pN=U(),SN=tt(),WY=Ir(),cce=Z(),uce=Vi(),QY=vi(),{table:lce}=(be(),te(qe)),{handleHDBError:Kn,hdb_errors:zY}=ee(),{HTTP_STATUS_CODES:Wn,AUTHENTICATION_ERROR_MSGS:Gm,HDB_ERROR_MSGS:$o}=zY,{UserEventMsg:Km}=Nn(),km=require("lodash"),{server:Wm}=(Xt(),te(Ii)),JY=K();Wm.getUser=(e,t)=>DN(e,t,t!=null);var CN={username:!0,active:!0,role:!0,password:!0},TN=new Map,I_=wN.searchByValue,jY=wN.searchByHash,XY=KY(YY.delete);async function ZY(e){let t=IN.cleanAttributes(e,CN),r=NN.addUserValidation(t);if(r)throw Kn(new Error,r.message,Wn.BAD_REQUEST,void 0,void 0,!0);let n={schema:"system",table:"hdb_role",search_attribute:"role",search_value:t.role,get_attributes:["id","permission","role"]},s;try{s=await I_(n),s=s&&Array.from(s)}catch(u){throw Ae.error("There was an error searching for a role in add user"),Ae.error(u),u}if(!s||s.length<1)throw Kn(new Error,$o.ROLE_NAME_NOT_FOUND(t.role),Wn.NOT_FOUND,void 0,void 0,!0);if(s.length>1)throw Kn(new Error,$o.DUP_ROLES_FOUND(t.role),Wn.CONFLICT,void 0,void 0,!0);s[0].permission.cluster_user===!0&&(t.hash=Ym.encrypt(t.password)),t.password=Vm.hash(t.password),t.role=s[0].id;let i={operation:"insert",schema:"system",table:"hdb_user",records:[t]},o;try{o=await yN.insert(i)}catch(u){throw Ae.error("There was an error searching for a user."),Ae.error(u),u}Ae.debug(o);try{await Yo()}catch(u){throw Ae.error("Got an error setting users to global"),Ae.error(u),u}if(o.skipped_hashes.length===1)throw Kn(new Error,$o.USER_ALREADY_EXISTS(t.username),Wn.CONFLICT,void 0,void 0,!0);let c=Object.assign({},t);return c.role=s[0],$m.signalUserChange(new Km(process.pid)),`${c.username} successfully added`}a(ZY,"addUser");async function eK(e){let t=IN.cleanAttributes(e,CN);if(Mr.isEmptyOrZeroLength(t.username))throw new Error(gN);if(Mr.isEmptyOrZeroLength(t.password)&&Mr.isEmptyOrZeroLength(t.role)&&Mr.isEmptyOrZeroLength(t.active))throw new Error(RN);if(!Mr.isEmpty(t.password)&&Mr.isEmptyOrZeroLength(t.password.trim()))throw new Error(AN);if(!Mr.isEmpty(t.active)&&!Mr.isBoolean(t.active))throw new Error(bN);let r=tK(t.username);if(!Mr.isEmpty(t.password)&&!Mr.isEmptyOrZeroLength(t.password.trim())&&(r&&(t.hash=Ym.encrypt(t.password)),t.password=Vm.hash(t.password)),t.role==="")throw new Error(ON);if(t.role){let i={schema:"system",table:"hdb_role",search_attribute:"role",search_value:t.role,get_attributes:["*"]},o;try{o=Array.from(await I_(i)||[])}catch(c){throw Ae.error("Got an error searching for a role."),Ae.error(c),c}if(!o||o.length===0){let c=$o.ALTER_USER_ROLE_NOT_FOUND(t.role);throw Ae.error(c),Kn(new Error,c,Wn.NOT_FOUND,void 0,void 0,!0)}if(o.length>1){let c=$o.ALTER_USER_DUP_ROLES(t.role);throw Ae.error(c),Kn(new Error,c,Wn.CONFLICT,void 0,void 0,!0)}t.role=o[0].id}let n={operation:"update",schema:"system",table:"hdb_user",records:[t]},s;try{s=await yN.update(n)}catch(i){throw Ae.error("Error during update."),Ae.error(i),i}try{await Yo()}catch(i){throw Ae.error("Got an error setting users to global"),Ae.error(i),i}return $m.signalUserChange(new Km(process.pid)),s}a(eK,"alterUser");function tK(e){let t=!1,r=global.hdb_users.get(e);return r&&r.role.permission.cluster_user===!0&&(t=!0),t}a(tK,"isClusterUser");async function rK(e){try{let t=NN.dropUserValidation(e);if(t)throw new Error(t);let r={table:"hdb_user",schema:"system",hash_values:[e.username]};if(Mr.isEmpty(global.hdb_users.get(e.username)))throw Kn(new Error,$o.USER_NOT_EXIST(e.username),Wn.NOT_FOUND,void 0,void 0,!0);let n;try{n=await XY(r)}catch(s){throw Ae.error("Got an error deleting a user."),Ae.error(s),s}Ae.debug(n);try{await Yo()}catch(s){throw Ae.error("Got an error setting users to global."),Ae.error(s),s}return $m.signalUserChange(new Km(process.pid)),`${e.username} successfully deleted`}catch(t){throw t}}a(rK,"dropUser");async function nK(e){let t={};try{if(!e||!e.hdb_user)return"There was no user info in the body";t=km.cloneDeep(e.hdb_user);let r={schema:"system",table:"hdb_role",hash_values:[t.role.id],get_attributes:["*"]},n;try{n=await jY(r)}catch(s){throw Ae.error("Got an error searching for a role."),Ae.error(s),s}t.role=n[0],delete t.password,delete t.refresh_token,delete t.hash}catch(r){throw Ae.error(r),r}return t}a(nK,"userInfo");async function sK(){let e;try{e=await C_()}catch(t){throw Ae.error("Got an error listing users."),Ae.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(sK,"listUsersExternal");async function C_(){try{let e={schema:"system",table:"hdb_role",search_value:"*",search_attribute:"role",get_attributes:["*"]},t;try{t=await I_(e)}catch(o){throw Ae.error("Got an error searching for roles."),Ae.error(o),o}let r={};for(let o of t)r[o.id]=km.cloneDeep(o);if(Object.keys(r).length===0)return null;let n={schema:"system",table:"hdb_user",search_value:"*",search_attribute:"username",get_attributes:["*"]},s;try{s=await I_(n)}catch(o){throw Ae.error("Got an error searching for users."),Ae.error(o),o}let i=new Map;for(let o of s)o=km.cloneDeep(o),o.role=r[o.role],iK(o.role),i.set(o.username,o);return i}catch(e){throw Ae.error("got an error listing users"),Ae.error(e),Mr.errorizeMessage(e)}return null}a(C_,"listUsers");function iK(e){try{if(!e){Ae.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(QY)){let r={read:!!e.permission.super_user,insert:!1,update:!1,delete:!1,attribute_permissions:[]};e.permission.system.tables[t]=r}}catch(t){Ae.error("Got an error trying to set system permissions."),Ae.error(t)}}a(iK,"appendSystemTablesToRole");async function Yo(){try{let e=await C_();global.hdb_users=e}catch(e){throw Ae.error(e),e}}a(Yo,"setUsersToGlobal");async function DN(e,t,r=!0){global.hdb_users||await Yo();let n=global.hdb_users.get(e);if(!n){if(!r)return{username:e};throw Kn(new Error,Gm.GENERIC_AUTH_FAIL,Wn.UNAUTHORIZED,void 0,void 0,!0)}if(n&&!n.active)throw Kn(new Error,Gm.USER_INACTIVE,Wn.UNAUTHORIZED,void 0,void 0,!0);let s={active:n.active,username:n.username};if(n.refresh_token&&(s.refresh_token=n.refresh_token),n.role&&(s.role=n.role),r===!0){if(TN.get(t)===n.password)return s;if(Vm.validate(n.password,t))TN.set(t,n.password);else throw Kn(new Error,Gm.GENERIC_AUTH_FAIL,Wn.UNAUTHORIZED,void 0,void 0,!0)}return s}a(DN,"findAndValidateUser");async function oK(){global.hdb_users||await Yo();for(let[,e]of global.hdb_users)if(e.role.role==="super_user")return e}a(oK,"getSuperUser");async function aK(){let e=await C_(),t=WY.getConfigFromFile(pN.CONFIG_PARAMS.CLUSTERING_USER),r=e.get(t);if(!Mr.isEmpty(r)&&r?.role?.role===pN.ROLE_TYPES_ENUM.CLUSTER_USER)return r.decrypt_hash=Ym.decrypt(r.hash),r.uri_encoded_d_hash=encodeURIComponent(r.decrypt_hash),r.uri_encoded_name=encodeURIComponent(r.username),r.sys_name=r.username+SN.SERVER_SUFFIX.ADMIN,r.sys_name_encoded=r.uri_encoded_name+SN.SERVER_SUFFIX.ADMIN,r}a(aK,"getClusterUser");var LN=[];Wm.invalidateUser=function(e){for(let t of LN)try{t(e)}catch(r){JY.error("Error invalidating user",r)}};Wm.onInvalidatedUser=function(e){LN.push(e)}});var vc=T((hce,BN)=>{"use strict";var $i=K(),Pr=U(),cK=wy(),fce=Ss(),Ece=Hi(),uK=Ur(),{validateEvent:UN}=Nn(),Pc=yn(),lK=require("process"),{resetDatabases:_K}=(be(),te(qe)),dK={[Pr.ITC_EVENT_TYPES.SCHEMA]:fK,[Pr.ITC_EVENT_TYPES.USER]:vN};async function fK(e){let t=UN(e);if(t){$i.error(t);return}$i.trace("ITC schemaHandler received schema event:",e),await cK(e.message),await EK(e.message)}a(fK,"schemaHandler");async function EK(e){try{Pc.resetReadTxn(Pr.SYSTEM_SCHEMA_NAME,Pr.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME),Pc.resetReadTxn(Pr.SYSTEM_SCHEMA_NAME,Pr.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME),Pc.resetReadTxn(Pr.SYSTEM_SCHEMA_NAME,Pr.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME);let t=_K();e.table&&e.database&&await t[e.database][e.table].put(Symbol.for("write-verify"),null)}catch(t){$i.error(t)}}a(EK,"syncSchemaMetadata");var PN=[];async function vN(e){try{try{Pc.resetReadTxn(Pr.SYSTEM_SCHEMA_NAME,Pr.SYSTEM_TABLE_NAMES.USER_TABLE_NAME),Pc.resetReadTxn(Pr.SYSTEM_SCHEMA_NAME,Pr.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME)}catch(r){$i.warn(r)}let t=UN(e);if(t){$i.error(t);return}$i.trace(`ITC userHandler ${Pr.HDB_ITC_CLIENT_PREFIX}${lK.pid} received user event:`,e),await uK.setUsersToGlobal();for(let r of PN)r()}catch(t){$i.error(t)}}a(vN,"userHandler");vN.addListener=function(e){PN.push(e)};BN.exports=dK});var Nn=T((Rce,xN)=>{"use strict";var pce=K(),Qm=J(),hK=U(),{ITC_ERRORS:Bc}=br(),{parentPort:Sce,threadId:mK,isMainThread:pK,workerData:Tce}=require("worker_threads"),{onMessageFromWorkers:SK,broadcast:gce,broadcastWithAcknowledgement:TK}=Ze();xN.exports={sendItcEvent:gK,validateEvent:HN,SchemaEventMsg:RK,UserEventMsg:AK};var D_;SK(async(e,t)=>{D_=D_||vc(),HN(e),D_[e.type]&&await D_[e.type](e),e.requestId&&t&&t.postMessage({type:"ack",id:e.requestId})});function gK(e){return!pK&&e.message&&(e.message.originator=mK),TK(e)}a(gK,"sendItcEvent");function HN(e){if(typeof e!="object")return Bc.INVALID_ITC_DATA_TYPE;if(!e.hasOwnProperty("type")||Qm.isEmpty(e.type))return Bc.MISSING_TYPE;if(!e.hasOwnProperty("message")||Qm.isEmpty(e.message))return Bc.MISSING_MSG;if(!e.message.hasOwnProperty("originator")||Qm.isEmpty(e.message.originator))return Bc.MISSING_ORIGIN;if(hK.ITC_EVENT_TYPES[e.type.toUpperCase()]===void 0)return Bc.INVALID_EVENT(e.type)}a(HN,"validateEvent");function RK(e,t,r,n=void 0,s=void 0){this.originator=e,this.operation=t,this.schema=r,this.table=n,this.attribute=s}a(RK,"SchemaEventMsg");function AK(e){this.originator=e}a(AK,"UserEventMsg")});var Ts=T((bce,kN)=>{"use strict";var qN=U(),Oce=J(),L_=K(),FN=by(),Ko,{sendItcEvent:GN}=Nn();function OK(e){try{L_.trace("signalSchemaChange called with message:",e),Ko=Ko||vc();let t=new FN(qN.ITC_EVENT_TYPES.SCHEMA,e);return Ko.schema(t),GN(t)}catch(t){L_.error(t)}}a(OK,"signalSchemaChange");function bK(e){try{L_.trace("signalUserChange called with message:",e),Ko=Ko||vc();let t=new FN(qN.ITC_EVENT_TYPES.USER,e);return Ko.user(t),GN(t)}catch(t){L_.error(t)}}a(bK,"signalUserChange");kN.exports={signalSchemaChange:OK,signalUserChange:bK}});var M_=T((Nce,$N)=>{"use strict";var VN=J(),yK=U(),NK=K(),wK=E_(),IK=f_(),CK=Ts(),{SchemaEventMsg:DK}=Nn(),LK="already exists in";$N.exports=MK;async function MK(e,t,r){if(VN.isEmptyOrZeroLength(r))return r;let n=[];VN.isEmptyOrZeroLength(t.attributes)||t.attributes.forEach(i=>{n.push(i.attribute)});let s=r.filter(i=>n.indexOf(i)<0);return s.length===0||await Promise.all(s.map(async i=>{await UK(e,t.schema,t.name,i)})),s}a(MK,"lmdbCheckForNewAttributes");async function UK(e,t,r,n){let s=new IK(t,r,n,void 0,!0);e&&(s.hdb_auth_header=e);try{await PK(s)}catch(i){if(typeof i=="object"&&i.message!==void 0&&i.message.includes(LK))NK.warn(`attribute ${t}.${r}.${n} already exists`);else throw i}}a(UK,"createNewAttribute");async function PK(e){let t;return t=await wK(e),CK.signalSchemaChange(new DK(process.pid,yK.OPERATIONS_ENUM.CREATE_ATTRIBUTE,e.schema,e.table,e.attribute)),t}a(PK,"createAttribute")});var Wo=T((Ice,YN)=>{"use strict";var zm=class{static{a(this,"LMDBTransactionObject")}constructor(t,r,n,s,i=void 0){this.operation=t,this.user_name=r,this.timestamp=n,this.hash_values=s,this.origin=i}};YN.exports=zm});var WN=T((Dce,KN)=>{"use strict";var vK=Wo(),BK=U().OPERATIONS_ENUM,Jm=class extends vK{static{a(this,"LMDBInsertTransactionObject")}constructor(t,r,n,s,i=void 0){super(BK.INSERT,r,n,s,i),this.records=t}};KN.exports=Jm});var zN=T((Mce,QN)=>{"use strict";var HK=Wo(),xK=U().OPERATIONS_ENUM,jm=class extends HK{static{a(this,"LMDBUpdateTransactionObject")}constructor(t,r,n,s,i,o=void 0){super(xK.UPDATE,n,s,i,o),this.records=t,this.original_records=r}};QN.exports=jm});var jN=T((Pce,JN)=>{"use strict";var qK=Wo(),FK=U().OPERATIONS_ENUM,Xm=class extends qK{static{a(this,"LMDBUpsertTransactionObject")}constructor(t,r,n,s,i,o=void 0){super(FK.UPSERT,n,s,i,o),this.records=t,this.original_records=r}};JN.exports=Xm});var ZN=T((Bce,XN)=>{"use strict";var GK=Wo(),kK=U().OPERATIONS_ENUM,Zm=class extends GK{static{a(this,"LMDBDeleteTransactionObject")}constructor(t,r,n,s,i=void 0){super(kK.DELETE,n,s,t,i),this.original_records=r}};XN.exports=Zm});var Hc=T((qce,nw)=>{"use strict";var xce=require("path"),ew=Ve(),VK=WN(),$K=zN(),YK=jN(),KK=ZN(),Qo=lt(),tw=J(),{CONFIG_PARAMS:WK}=U(),rw=Z();rw.initSync();var U_=U().OPERATIONS_ENUM,{getTransactionAuditStorePath:QK}=Ye();nw.exports=zK;async function zK(e,t){if(rw.get(WK.LOGGING_AUDITLOG)===!1)return;let r=QK(e.schema,e.table),n=await ew.openEnvironment(r,e.table,!0),s=JK(e,t);if(!(s===void 0||s.hash_values.length===0)&&n!==void 0){ew.initializeDBIs(n,Qo.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,Qo.TRANSACTIONS_DBIS);let i=s.timestamp;return await n.dbis[Qo.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP].ifNoExists(i,()=>{n.dbis[Qo.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP].put(i,s),tw.isEmpty(s.user_name)||n.dbis[Qo.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].put(s.user_name,i);for(let o=0;o<s.hash_values.length;o++)n.dbis[Qo.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE].put(s.hash_values[o],i)})}}a(zK,"writeTransaction");function JK(e,t){let r=tw.isEmpty(e.hdb_user)?void 0:e.hdb_user.username;if(e.operation===U_.INSERT)return new VK(e.records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===U_.UPDATE)return new $K(e.records,t.original_records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===U_.UPSERT)return new YK(e.records,t.original_records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===U_.DELETE)return new KK(t.deleted,t.original_records,r,t.txn_time,e.__origin)}a(JK,"createTransactionObject")});var ep=T((kce,sw)=>{"use strict";var jK=wc(),Gce=Ic(),xc=U(),XK=Mc(),ZK=qo().insertRecords,eW=Ve(),tW=K(),rW=M_(),{getSchemaPath:nW}=Ye(),sW=Hc();sw.exports=iW;async function iW(e){try{let{schema_table:t,attributes:r}=jK(e);XK(e,r,t.hash_attribute),e.schema!==xc.SYSTEM_SCHEMA_NAME&&(r.includes(xc.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||r.push(xc.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.includes(xc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||r.push(xc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let n=await rW(e.hdb_auth_header,t,r),s=nW(e.schema,e.table),i=await eW.openEnvironment(s,e.table),o=await ZK(i,t.hash_attribute,r,e.records,e.__origin?.timestamp);try{await sW(e,o)}catch(c){tW.error(`unable to write transaction due to ${c.message}`)}return{written_hashes:o.written_hashes,skipped_hashes:o.skipped_hashes,schema_table:t,new_attributes:n,txn_time:o.txn_time}}catch(t){throw t}}a(iW,"lmdbCreateRecords")});var aw=T(($ce,ow)=>{"use strict";var iw=U(),oW=ep(),aW=Ic(),cW=require("fs-extra"),{getSchemaPath:uW}=Ye();ow.exports=lW;async function lW(e){let t=[{name:e.schema,createddate:Date.now()}],r=new aW(iw.SYSTEM_SCHEMA_NAME,iw.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,void 0,t);await oW(r),await cW.mkdirp(uW(e.schema))}a(lW,"lmdbCreateSchema")});var uw=T((Kce,cw)=>{"use strict";var tp=class{static{a(this,"DeleteRecordsResponseObject")}constructor(t=[],r=[],n=void 0,s=[]){this.deleted=t,this.skipped=r,this.txn_time=n,this.original_records=s}};cw.exports=tp});var fw=T((jce,dw)=>{"use strict";var lw=Ve(),rp=Cr(),np=br().LMDB_ERRORS_ENUM,_W=lt(),_w=K(),Qce=J(),dW=require("lmdb"),fW=uw(),EW=U(),{OVERFLOW_MARKER:zce,MAX_SEARCH_KEY_LENGTH:Jce}=_W,hW=EW.TIME_STAMP_NAMES_ENUM.UPDATED_TIME;async function mW(e,t,r,n){if(rp.validateEnv(e),t===void 0)throw new Error(np.HASH_ATTRIBUTE_REQUIRED);if(!Array.isArray(r))throw r===void 0?new Error(np.IDS_REQUIRED):new Error(np.IDS_MUST_BE_ITERABLE);try{let s=lw.listDBIs(e);lw.initializeDBIs(e,t,s);let i=new fW,o,c=[],u=[];for(let f=0,E=r.length;f<E;f++)try{o=r[f];let h=e.dbis[t].get(o);if(!h||n&&h[hW]>n){i.skipped.push(o);continue}let p=e.dbis[t].ifVersion(o,dW.IF_EXISTS,()=>{e.dbis[t].remove(o);for(let S=0;S<s.length;S++){let O=s[S];if(!h.hasOwnProperty(O)||O===t)continue;let g=e.dbis[O],R=h[O];if(R!=null)try{let B=rp.getIndexedValues(R);if(B)for(let H=0,v=B.length;H<v;H++)g.remove(B[H],o)}catch{_w.warn(`cannot delete from attribute: ${O}, ${R}:${o}`)}}});c.push(p),u.push(o),i.original_records.push(h)}catch(h){_w.warn(h),i.skipped.push(o)}let _=[],l=await Promise.all(c);for(let f=0,E=l.length;f<E;f++)l[f]===!0?i.deleted.push(u[f]):(i.skipped.push(u[f]),_.push(f));let d=0;for(let f=0;f<_.length;f++){let E=_[f];i.original_records.splice(E-d,1),d++}return i.txn_time=rp.getNextMonotonicTime(),i}catch(s){throw s}}a(mW,"deleteRecords");dw.exports={deleteRecords:mW}});var qc=T((Zce,hw)=>{"use strict";var zo=J(),pW=fw(),SW=Ve(),{getSchemaPath:TW}=Ye(),gW=Hc(),RW=K();hw.exports=AW;async function AW(e,t=!0){let n=global.hdb_schema[e.schema][e.table].hash_attribute;if(zo.isEmpty(n))throw new Error(`could not retrieve hash attribute for schema:${e.schema} and table ${e.table}`);try{if(zo.isEmptyOrZeroLength(e.hash_values)&&!zo.isEmptyOrZeroLength(e.records)){e.hash_values=[];for(let c=0;c<e.records.length;c++){let u=e.records[c][n];zo.isEmpty(u)||e.hash_values.push(u)}}if(zo.isEmptyOrZeroLength(e.hash_values))return Ew([],[]);if(!Array.isArray(e.hash_values))throw new Error("hash_values must be an array");if(zo.isEmptyOrZeroLength(e.records)){e.records=[];for(let c=0;c<e.hash_values.length;c++)e.records[c]={[n]:e.hash_values[c]}}let s=TW(e.schema,e.table),i=await SW.openEnvironment(s,e.table),o=await pW.deleteRecords(i,n,e.hash_values,e.__origin?.timestamp);try{t===!0&&await gW(e,o)}catch(c){RW.error(`unable to write transaction due to ${c.message}`)}return Ew(o.deleted,o.skipped,o.txn_time)}catch(s){throw s}}a(AW,"lmdbDeleteRecords");function Ew(e,t,r){let n=e.length+t.length,s=n===1?"record":"records";return{message:`${e.length} of ${n} ${s} successfully deleted`,deleted_hashes:e,skipped_hashes:t,txn_time:r}}a(Ew,"createDeleteResponse")});var ip=T((rue,mw)=>{"use strict";var OW=U(),tue=Cr();function sp(e,t){let r=Object.create(null);if(t.length===1&&OW.SEARCH_WILDCARDS.indexOf(t[0])>=0)Object.assign(r,e);else for(let n=0;n<t.length;n++){let s=t[n],i=e[s];r[s]=i===void 0?null:i}return r}a(sp,"parseRow");function bW(e,t,r,n){let s=sp(r,e);n.push(s)}a(bW,"searchAll");function yW(e,t,r,n){let s=sp(r,e);n[t]=s}a(yW,"searchAllToMap");function NW(e,t,r){r[e]===void 0&&(r[e]=[]),r[e].push(t)}a(NW,"iterateDBI");function Yi(e,t,r,n,s){let i=Object.create(null);i[s]=e;let o;n===s?o=e:(o=t,n!==void 0&&(i[n]=o)),r[0].push(o),r[1].push(i)}a(Yi,"pushResults");function wW(e,t,r,n,s,i){t.toString().endsWith(e)&&Yi(t,r,n,s,i)}a(wW,"endsWith");function IW(e,t,r,n,s,i){t.toString().includes(e)&&Yi(t,r,n,s,i)}a(IW,"contains");function CW(e,t,r,n,s,i){t>e&&Yi(t,r,n,s,i)}a(CW,"greaterThanCompare");function DW(e,t,r,n,s,i){t>=e&&Yi(t,r,n,s,i)}a(DW,"greaterThanEqualCompare");function LW(e,t,r,n,s,i){t<e&&Yi(t,r,n,s,i)}a(LW,"lessThanCompare");function MW(e,t,r,n,s,i){t<=e&&Yi(t,r,n,s,i)}a(MW,"lessThanEqualCompare");mw.exports={parseRow:sp,searchAll:bW,searchAllToMap:yW,iterateDBI:NW,endsWith:wW,contains:IW,greaterThanCompare:CW,greaterThanEqualCompare:DW,lessThanCompare:LW,lessThanEqualCompare:MW,pushResults:Yi}});var Jo=T((aue,Ow)=>{"use strict";var ei=Ve(),sue=K(),vr=Cr(),P_=lt(),at=br().LMDB_ERRORS_ENUM,iue=J(),UW=U(),v_=ip(),{parseRow:PW}=v_,oue=require("lmdb"),{OVERFLOW_MARKER:pw,MAX_SEARCH_KEY_LENGTH:vW}=P_;function Sw(e,t,r,n=!1,s=void 0,i=void 0){return Ki(e,t,r,(o,c)=>c.getRange({transaction:o,start:n?void 0:!1,end:n?!1:void 0,limit:s,offset:i,reverse:n}))}a(Sw,"iterateFullIndex");function Fc(e,t,r,n,s,i=!1,o=void 0,c=void 0,u=!1,_=!1){return Ki(e,t,r,(l,d,f,E)=>{let g={transaction:l,start:i===!0?s:n,end:i===!0?n:s,reverse:i,limit:o,offset:c,inclusiveEnd:i===!0?!u:!_,exclusiveStart:i===!0?_:u};return E===r?(g.values=!1,d.getRange(g).map(R=>({value:R}))):d.getRange(g)})}a(Fc,"iterateRangeBetween");function Ki(e,t,r,n){let s=e.database||e,i=ei.openDBI(s,r);i[P_.DBI_DEFINITION_NAME].is_hash_attribute?t=r:t&&ei.openDBI(s,t);let o;e.database?o=e:(o=e.useReadTransaction(),o.database=e);let c=n(o,i,s,t);return c.transaction=o,e.database||(c.onDone=()=>{o.done()}),c}a(Ki,"setupTransaction");function Tw(e,t,r,n){let s;return function(i,o){if(typeof i=="string"&&i.endsWith(pw)){if(!s)if(r)s=ei.openDBI(e,r);else{let u=ei.listDBIs(e);for(let _=0,l=u.length;_<l&&(s=ei.openDBI(e,u[_]),!s[P_.DBI_DEFINITION_NAME].is_hash_attribute);_++);}i=s.get(o,{transaction:t,lazy:!0})[n]}return i}}a(Tw,"getOverflowCheck");function BW(e,t,r,n=!1,s=void 0,i=void 0){if(vr.validateEnv(e),t===void 0)throw new Error(at.HASH_ATTRIBUTE_REQUIRED);return Ki(e,t,t,(o,c,u)=>(B_(r),r=Gc(u,r),c.getRange({transaction:o,start:n?void 0:!1,end:n?!1:void 0,limit:s,offset:i,reverse:n}).map(_=>PW(_.value,r))))}a(BW,"searchAll");function HW(e,t,r,n=!1,s=void 0,i=void 0){if(vr.validateEnv(e),t===void 0)throw new Error(at.HASH_ATTRIBUTE_REQUIRED);B_(r),r=Gc(e.database||e,r);let o=new Map;for(let{key:c,value:u}of Sw(e,t,t,n,s,i))o.set(c,v_.parseRow(u,r));return o}a(HW,"searchAllToMap");function xW(e,t,r=!1,n=void 0,s=void 0){if(vr.validateEnv(e),t===void 0)throw new Error(at.ATTRIBUTE_REQUIRED);let i=Object.create(null),o=Sw(e,void 0,t,r,n,s),c=o.transaction,u=Tw(c.database,c,void 0,t);for(let{key:_,value:l}of o){let d=u(_,l);i[d]===void 0&&(i[d]=[]),i[d].push(l)}return i}a(xW,"iterateDBI");function qW(e,t){if(vr.validateEnv(e),t===void 0)throw new Error(at.HASH_ATTRIBUTE_REQUIRED);return ei.statDBI(e,t).entryCount}a(qW,"countAll");function FW(e,t,r,n,s=!1,i=void 0,o=void 0){return ti(e,r,n),Ki(e,t,r,(c,u,_,l)=>(n=vr.convertKeyValueToWrite(n),l===r?u.get(n,{transaction:c,lazy:!0})===void 0?[]:[{key:n,value:n}]:u.getValues(n,{transaction:c,reverse:s,limit:i,offset:o}).map(d=>({key:n,value:d}))))}a(FW,"equals");function GW(e,t,r){return ti(e,t,r),ei.openDBI(e,t).getValuesCount(r)}a(GW,"count");function kW(e,t,r,n,s=!1,i=void 0,o=void 0){return ti(e,r,n),Ki(e,null,r,(c,u)=>{n=vr.convertKeyValueToWrite(n);let _=!0;typeof n=="number"&&(_=!1);let l;if(s===!0){let d;for(let f of u.getKeys({transaction:c,start:n}))if(!f.startsWith(n)){d=f;break}return d!==void 0&&(Number.isInteger(o)?o++:i++),l=u.getRange({transaction:c,start:d,end:void 0,reverse:s,limit:i,offset:o}).map(f=>{let{key:E}=f;if(E!==d){if(E.toString().startsWith(n))return f;if(_===!0)return l.DONE}}),l.filter(f=>f)}else return l=u.getRange({transaction:c,start:n,reverse:s,limit:i,offset:o}).map(d=>{if(d.key.toString().startsWith(n))return d;if(_===!0)return l.DONE}),_?l:l.filter(d=>d)})}a(kW,"startsWith");function VW(e,t,r,n,s=!1,i=void 0,o=void 0){return gw(e,t,r,n,s,i,o,!0)}a(VW,"endsWith");function gw(e,t,r,n,s=!1,i=void 0,o=void 0,c=!1){return ti(e,r,n),Ki(e,null,r,(u,_,l,d)=>{let f=Tw(l,u,d,r);return o=Number.isInteger(o)?o:0,_.getKeys({transaction:u,end:s?!1:void 0,reverse:s}).flatMap(E=>{let h=E.toString();return h.endsWith(pw)?_.getValues(E,{transaction:u}).map(p=>{let S=f(E,p);if(c?S.endsWith(n):S.includes(n))return{key:S,value:p}}).filter(p=>p):(c?h.endsWith(n):h.includes(n))?_[P_.DBI_DEFINITION_NAME].is_hash_attribute?{key:E,value:E}:_.getValues(E,{transaction:u}).map(p=>({key:E,value:p})):[]}).slice(o,i===void 0?void 0:i+(o||0))})}a(gw,"contains");function $W(e,t,r,n,s=!1,i=void 0,o=void 0){ti(e,r,n);let c=typeof n,u;return c==="string"?u="\uFFFF":c==="number"?u=1/0:c==="boolean"&&(u=!0),Fc(e,t,r,n,u,s,i,o,!0,!1)}a($W,"greaterThan");function YW(e,t,r,n,s=!1,i=void 0,o=void 0){ti(e,r,n);let c=typeof n,u;return c==="string"?u="\uFFFF":c==="number"?u=1/0:c==="boolean"&&(u=!0),Fc(e,t,r,n,u,s,i,o,!1,!1)}a(YW,"greaterThanEqual");function KW(e,t,r,n,s=!1,i=void 0,o=void 0){ti(e,r,n);let c=typeof n,u;return c==="string"?u="\0":c==="number"?u=-1/0:c==="boolean"&&(u=!1),Fc(e,t,r,u,n,s,i,o,!1,!0)}a(KW,"lessThan");function WW(e,t,r,n,s=!1,i=void 0,o=void 0){ti(e,r,n);let c=typeof n,u;return c==="string"?u="\0":c==="number"?u=-1/0:c==="boolean"&&(u=!1),Fc(e,t,r,u,n,s,i,o,!1,!1)}a(WW,"lessThanEqual");function QW(e,t,r,n,s,i=!1,o=void 0,c=void 0){if(vr.validateEnv(e),r===void 0)throw new Error(at.ATTRIBUTE_REQUIRED);if(n===void 0)throw new Error(at.START_VALUE_REQUIRED);if(s===void 0)throw new Error(at.END_VALUE_REQUIRED);if(n=vr.convertKeyValueToWrite(n),s=vr.convertKeyValueToWrite(s),n>s)throw new Error(at.END_VALUE_MUST_BE_GREATER_THAN_START_VALUE);return Fc(e,t,r,n,s,i,o,c)}a(QW,"between");function zW(e,t,r,n){vr.validateEnv(e);let s=e.database||e,i=e.database?e:null;if(t===void 0)throw new Error(at.HASH_ATTRIBUTE_REQUIRED);if(B_(r),r=Gc(s,r),n===void 0)throw new Error(at.ID_REQUIRED);let o=null,c=s.dbis[t].get(n,{transaction:i,lazy:r.length<3});return c&&(o=v_.parseRow(c,r)),o}a(zW,"searchByHash");function JW(e,t,r){vr.validateEnv(e);let n=e.database||e,s=e.database?e:null;if(t===void 0)throw new Error(at.HASH_ATTRIBUTE_REQUIRED);if(r===void 0)throw new Error(at.ID_REQUIRED);let i=!0;return n.dbis[t].get(r,{transaction:s,lazy:!0})===void 0&&(i=!1),i}a(JW,"checkHashExists");function jW(e,t,r,n,s=[]){return Aw(e,t,r,n,s),Rw(e,t,r,n,s).map(i=>i[1])}a(jW,"batchSearchByHash");function XW(e,t,r,n,s=[]){Aw(e,t,r,n,s);let i=new Map;for(let[o,c]of Rw(e,t,r,n,s))i.set(o,c);return i}a(XW,"batchSearchByHashToMap");function Rw(e,t,r,n,s=[]){return Ki(e,t,t,(i,o,c)=>{r=Gc(c,r);let u=r.length<3;return n.map(_=>{let l=c.dbis[t].get(_,{transaction:i,lazy:u});if(l)return[_,v_.parseRow(l,r)];s.push(_)}).filter(_=>_)})}a(Rw,"batchHashSearch");function Aw(e,t,r,n,s){if(vr.validateEnv(e),t===void 0)throw new Error(at.HASH_ATTRIBUTE_REQUIRED);if(B_(r),n==null)throw new Error(at.IDS_REQUIRED);if(!n[Symbol.iterator])throw new Error(at.IDS_MUST_BE_ITERABLE)}a(Aw,"initializeBatchSearchByHash");function B_(e){if(!Array.isArray(e))throw e===void 0?new Error(at.FETCH_ATTRIBUTES_REQUIRED):new Error(at.FETCH_ATTRIBUTES_MUST_BE_ARRAY)}a(B_,"validateFetchAttributes");function ti(e,t,r){if(vr.validateEnv(e),t===void 0)throw new Error(at.ATTRIBUTE_REQUIRED);if(r===void 0)throw new Error(at.SEARCH_VALUE_REQUIRED);if(r?.length>vW)throw new Error(at.SEARCH_VALUE_TOO_LARGE)}a(ti,"validateComparisonFunctions");function Gc(e,t){return t.length===1&&UW.SEARCH_WILDCARDS.indexOf(t[0])>=0&&(t=ei.listDBIs(e)),t}a(Gc,"setGetWholeRowAttributes");Ow.exports={searchAll:BW,searchAllToMap:HW,count:GW,countAll:qW,equals:FW,startsWith:kW,endsWith:VW,contains:gw,searchByHash:zW,setGetWholeRowAttributes:Gc,batchSearchByHash:jW,batchSearchByHashToMap:XW,checkHashExists:JW,iterateDBI:xW,greaterThan:$W,greaterThanEqual:YW,lessThan:KW,lessThanEqual:WW,between:QW}});var jo=T((uue,Iw)=>{var bw=require("lodash"),yw=je(),me=require("joi"),ZW=J(),{hdb_schema_table:kc,checkValidTable:Nw,hdb_table:ww,hdb_database:H_}=$n(),{handleHDBError:eQ,hdb_errors:tQ}=ee(),{getDatabases:rQ}=(be(),te(qe)),{HTTP_STATUS_CODES:nQ}=tQ,sQ=me.object({database:H_,schema:H_,table:ww,search_attribute:kc,search_value:me.any().required(),get_attributes:me.array().min(1).items(me.alternatives(kc,me.object())).optional(),desc:me.bool(),limit:me.number().integer().min(1),offset:me.number().integer().min(0)}),iQ=me.object({database:H_,schema:H_,table:ww,operator:me.string().valid("and","or").default("and").lowercase(),offset:me.number().integer().min(0),limit:me.number().integer().min(1),get_attributes:me.array().min(1).items(me.alternatives(kc,me.object())).optional(),sort:me.object({attribute:me.alternatives(kc,me.array().min(1)),descending:me.bool().optional()}).optional(),conditions:me.array().min(1).items(me.alternatives(me.object({operator:me.string().valid("and","or").default("and").lowercase(),conditions:me.array()}),me.object({search_attribute:me.alternatives(kc,me.array().min(1)),search_type:me.string().valid("equals","contains","starts_with","ends_with","greater_than","greater_than_equal","less_than","less_than_equal","between","not_equal").optional(),search_value:me.when("search_type",{switch:[{is:"equals",then:me.any()},{is:"between",then:me.array().items(me.alternatives([me.string(),me.number()])).length(2)}],otherwise:me.alternatives(me.string(),me.number())}).required()}))).required()});Iw.exports=function(e,t){let r=null;switch(t){case"value":r=yw.validateBySchema(e,sQ);break;case"hashes":let i=function(o){s?s+=". "+o:s=o};var n=i;a(i,"addError");let s;i(Nw("database",e.schema)),i(Nw("table",e.table)),e.hash_values?Array.isArray(e.hash_values)?e.hash_values.every(o=>typeof o=="string"||typeof o=="number")||i("'hash_values' must be strings or numbers"):i("'hash_values' must be an array"):i("'hash_values' is required"),e.get_attributes?Array.isArray(e.get_attributes)?e.get_attributes.length===0?i("'get_attributes' must contain at least 1 item"):e.get_attributes.every(o=>typeof o=="string"||typeof o=="number")||i("'get_attributes' must be strings or numbers"):i("'get_attributes' must be an array"):i("'get_attributes' is required"),s&&(r=new Error(s.trim()));break;case"conditions":r=yw.validateBySchema(e,iQ);break;default:throw new Error(`Error validating search, unknown type: ${t}`)}if(!r&&e.schema!=="system"){let s=ZW.checkGlobalSchemaTable(e.schema,e.table);if(s)return eQ(new Error,s,nQ.NOT_FOUND);let o=rQ()[e.schema][e.table].attributes,c=e.get_attributes?[...e.get_attributes]:[];t==="value"&&c.push(e.search_attribute);let u=a(l=>{for(let d=0,f=l.conditions.length;d<f;d++){let E=l.conditions[d];E.conditions?u(E):c.push(E.search_attribute)}},"addConditions");t==="conditions"&&u(e);let _=bw.filter(c,l=>l!=="*"&&l.attribute!=="*"&&!Array.isArray(l)&&!bw.some(o,d=>d===l||d.attribute===l||d.attribute===l.attribute));if(_&&_.length>0){let l=_.join(", ");return l=l.replace(/,([^,]*)$/," and$1"),new Error(`unknown attribute '${l}'`)}}return r}});var op=T((_ue,Cw)=>{"use strict";var oQ=Ve(),aQ=jo(),{getSchemaPath:cQ}=Ye();Cw.exports=uQ;function uQ(e){let t=aQ(e,"hashes");if(t)throw t;let r=cQ(e.schema,e.table);return oQ.openEnvironment(r,e.table)}a(uQ,"initialize")});var ap=T((fue,Dw)=>{"use strict";var lQ=Jo(),_Q=op();Dw.exports=dQ;async function dQ(e){let t=await _Q(e),r=t.useReadTransaction();r.database=t;let n=global.hdb_schema[e.schema][e.table];try{return lQ.batchSearchByHashToMap(r,n.hash_attribute,e.get_attributes,e.hash_values)}finally{r.done()}}a(dQ,"lmdbGetDataByHash")});var Xo=T((hue,Lw)=>{"use strict";var cp=class{static{a(this,"SearchByHashObject")}constructor(t,r,n,s){this.schema=t,this.table=r,this.hash_values=n,this.get_attributes=s}};Lw.exports=cp});var Uw=T((Sue,Mw)=>{"use strict";var pue=Xo(),fQ=Jo(),EQ=op();Mw.exports=hQ;async function hQ(e){let t=await EQ(e),r=global.hdb_schema[e.schema][e.table];return fQ.batchSearchByHash(t,r.hash_attribute,e.get_attributes,e.hash_values)}a(hQ,"lmdbSearchByHash")});var Qn=T((gue,Pw)=>{"use strict";var up=class{static{a(this,"SearchObject")}constructor(t,r,n,s,i,o,c,u=!1,_=void 0,l=void 0){this.schema=t,this.table=r,this.search_attribute=n,this.search_value=s,this.hash_attribute=i,this.get_attributes=o,this.end_value=c,this.reverse=u,this.limit=_,this.offset=l}};Pw.exports=up});var x_=T((Aue,Fw)=>{"use strict";var Yt=Jo(),mQ=Ve(),pQ=J(),pe=lt(),Wi=U(),SQ=vi(),vw=br().LMDB_ERRORS_ENUM,{getSchemaPath:TQ}=Ye(),gs=Wi.SEARCH_WILDCARDS;async function gQ(e,t,r){let n;e.schema===Wi.SYSTEM_SCHEMA_NAME?n=SQ[e.table]:n=global.hdb_schema[e.schema][e.table];let s=qw(e,n.hash_attribute,r,t);return Hw(e,s,n.hash_attribute,r)}a(gQ,"prepSearch");async function Hw(e,t,r,n){let s=TQ(e.schema,e.table),i=await mQ.openEnvironment(s,e.table),o=xw(i,e,t,r),c=o.transaction||i;if([pe.SEARCH_TYPES.BATCH_SEARCH_BY_HASH,pe.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP,pe.SEARCH_TYPES.SEARCH_ALL,pe.SEARCH_TYPES.SEARCH_ALL_TO_MAP].indexOf(t)>=0)return o;if(RQ(e,r)===!1){let l=e.search_attribute;if(l===r)return n?Bw(o,()=>!0):o.map(f=>({[r]:f.key}));let d=a(f=>({[r]:f.value,[l]:f.key}),"toObject");return n?Bw(o,d):o.map(d)}let _=e.search_attribute===r?o.map(l=>l.key):o.map(l=>l.value);return n===!0?Yt.batchSearchByHashToMap(c,r,e.get_attributes,_):Yt.batchSearchByHash(c,r,e.get_attributes,_)}a(Hw,"executeSearch");function xw(e,t,r,n){let s,i=n;t.get_attributes.indexOf(n)<0&&(i=void 0);let{reverse:o,limit:c,offset:u}=t;switch(o=typeof o=="boolean"?o:!1,c=Number.isInteger(c)?c:void 0,u=Number.isInteger(u)?u:void 0,r){case pe.SEARCH_TYPES.EQUALS:s=Yt.equals(e,i,t.search_attribute,t.search_value,o,c,u);break;case pe.SEARCH_TYPES.CONTAINS:s=Yt.contains(e,i,t.search_attribute,t.search_value,o,c,u);break;case pe.SEARCH_TYPES.ENDS_WITH:case pe.SEARCH_TYPES._ENDS_WITH:s=Yt.endsWith(e,i,t.search_attribute,t.search_value,o,c,u);break;case pe.SEARCH_TYPES.STARTS_WITH:case pe.SEARCH_TYPES._STARTS_WITH:s=Yt.startsWith(e,i,t.search_attribute,t.search_value,o,c,u);break;case pe.SEARCH_TYPES.BATCH_SEARCH_BY_HASH:return Yt.batchSearchByHash(e,t.search_attribute,t.get_attributes,[t.search_value]);case pe.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP:return Yt.batchSearchByHashToMap(e,t.search_attribute,t.get_attributes,[t.search_value]);case pe.SEARCH_TYPES.SEARCH_ALL:return Yt.searchAll(e,n,t.get_attributes,o,c,u);case pe.SEARCH_TYPES.SEARCH_ALL_TO_MAP:return Yt.searchAllToMap(e,n,t.get_attributes,o,c,u);case pe.SEARCH_TYPES.BETWEEN:s=Yt.between(e,i,t.search_attribute,t.search_value,t.end_value,o,c,u);break;case pe.SEARCH_TYPES.GREATER_THAN:case pe.SEARCH_TYPES._GREATER_THAN:s=Yt.greaterThan(e,i,t.search_attribute,t.search_value,o,c,u);break;case pe.SEARCH_TYPES.GREATER_THAN_EQUAL:case pe.SEARCH_TYPES._GREATER_THAN_EQUAL:s=Yt.greaterThanEqual(e,i,t.search_attribute,t.search_value,o,c,u);break;case pe.SEARCH_TYPES.LESS_THAN:case pe.SEARCH_TYPES._LESS_THAN:s=Yt.lessThan(e,i,t.search_attribute,t.search_value,o,c,u);break;case pe.SEARCH_TYPES.LESS_THAN_EQUAL:case pe.SEARCH_TYPES._LESS_THAN_EQUAL:s=Yt.lessThanEqual(e,i,t.search_attribute,t.search_value,o,c,u);break;default:return Object.create(null)}return s}a(xw,"searchByType");function Bw(e,t){let r=new Map;for(let n of e)r.set(n.value,t(n));return r}a(Bw,"createMapFromIterable");function RQ(e,t){if(e.get_attributes.length===1&&e.get_attributes[0]==="*")return!0;let r=[e.search_attribute];e.get_attributes.indexOf(t)>=0&&r.push(t);let n=!1;for(let s=0;s<e.get_attributes.length;s++)if(r.indexOf(e.get_attributes[s])<0){n=!0;break}return n}a(RQ,"checkToFetchMore");function qw(e,t,r,n){if(pQ.isEmpty(n)){let s=e.search_value;typeof s=="object"?s=JSON.stringify(s):s=s.toString();let i=s.charAt(0),o=s.charAt(s.length-1),c=!1;if(e.search_attribute===t&&(c=!0),gs.indexOf(s)>-1)return r===!0?pe.SEARCH_TYPES.SEARCH_ALL_TO_MAP:pe.SEARCH_TYPES.SEARCH_ALL;if(s.indexOf(gs[0])<0&&s.indexOf(gs[1])<0)return c===!0?r===!0?pe.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP:pe.SEARCH_TYPES.BATCH_SEARCH_BY_HASH:pe.SEARCH_TYPES.EQUALS;if(gs.indexOf(i)>=0&&gs.indexOf(o)>=0)return e.search_value=e.search_value.slice(1,-1),pe.SEARCH_TYPES.CONTAINS;if(gs.indexOf(i)>=0)return e.search_value=e.search_value.substr(1),pe.SEARCH_TYPES.ENDS_WITH;if(gs.indexOf(o)>=0)return e.search_value=e.search_value.slice(0,-1),pe.SEARCH_TYPES.STARTS_WITH;if(s.includes(gs[0])||s.includes(gs[1]))return pe.SEARCH_TYPES.EQUALS;throw new Error(vw.UNKNOWN_SEARCH_TYPE)}else switch(n){case Wi.VALUE_SEARCH_COMPARATORS.BETWEEN:return pe.SEARCH_TYPES.BETWEEN;case Wi.VALUE_SEARCH_COMPARATORS.GREATER:return pe.SEARCH_TYPES.GREATER_THAN;case Wi.VALUE_SEARCH_COMPARATORS.GREATER_OR_EQ:return pe.SEARCH_TYPES.GREATER_THAN_EQUAL;case Wi.VALUE_SEARCH_COMPARATORS.LESS:return pe.SEARCH_TYPES.LESS_THAN;case Wi.VALUE_SEARCH_COMPARATORS.LESS_OR_EQ:return pe.SEARCH_TYPES.LESS_THAN_EQUAL;default:throw new Error(vw.UNKNOWN_SEARCH_TYPE)}}a(qw,"createSearchTypeFromSearchObject");Fw.exports={executeSearch:Hw,createSearchTypeFromSearchObject:qw,prepSearch:gQ,searchByType:xw}});var kw=T((yue,Gw)=>{"use strict";var bue=Qn(),AQ=jo(),OQ=J(),bQ=U(),yQ=x_();Gw.exports=NQ;function NQ(e,t){if(!OQ.isEmpty(t)&&bQ.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[t]===void 0)throw new Error(`Value search comparator - ${t} - is not valid`);let n=AQ(e,"value");if(n)throw n;return yQ.prepSearch(e,t,!0)}a(NQ,"lmdbGetDataByValue")});var Vc=T((Iue,Vw)=>{"use strict";var wue=Qn(),wQ=jo(),IQ=J(),CQ=U(),DQ=x_();Vw.exports=LQ;async function LQ(e,t){if(!IQ.isEmpty(t)&&CQ.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[t]===void 0)throw new Error(`Value search comparator - ${t} - is not valid`);let n=wQ(e,"value");if(n)throw n;return DQ.prepSearch(e,t,!1)}a(LQ,"lmdbSearchByValue")});var Yw=T((Lue,$w)=>{"use strict";var Due=lt(),lp=class{static{a(this,"SearchByConditionsObject")}constructor(t,r,n,s,i=void 0,o=void 0,c="and"){this.schema=t,this.table=r,this.get_attributes=n,this.limit=i,this.offset=o,this.conditions=s,this.operator=c}},_p=class{static{a(this,"SearchCondition")}constructor(t,r,n){this.search_attribute=t,this.search_type=r,this.search_value=n}},dp=class{static{a(this,"SortAttribute")}constructor(t,r){this.attribute=t,this.desc=r}};$w.exports={SearchByConditionsObject:lp,SearchCondition:_p,SortAttribute:dp}});var Jw=T((vue,zw)=>{"use strict";var Uue=Yw().SearchByConditionsObject,MQ=Qn(),UQ=jo(),fp=Jo(),q_=lt(),{Resource:Pue}=(An(),te(Ep)),Qw=x_(),PQ=ip(),vQ=require("lodash"),{getSchemaPath:BQ}=Ye(),Kw=Ve(),{handleHDBError:HQ,hdb_errors:xQ}=ee(),{HTTP_STATUS_CODES:qQ}=xQ,FQ=1e8;zw.exports=GQ;async function GQ(e){let t=UQ(e,"conditions");if(t)throw HQ(t,t.message,qQ.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=BQ(e.schema,e.table),n=await Kw.openEnvironment(r,e.table),s=global.hdb_schema[e.schema][e.table];for(let _ of e.conditions)Kw.openDBI(n,_.search_attribute);let i=vQ.sortBy(e.conditions,_=>{if(_.estimated_count===void 0){let l=_.search_type;l===q_.SEARCH_TYPES.EQUALS?_.estimated_count=fp.count(n,_.search_attribute,_.search_value):l===q_.SEARCH_TYPES.CONTAINS||l===q_.SEARCH_TYPES.ENDS_WITH?_.estimated_count=1/0:_.estimated_count=FQ}return _.estimated_count}),o=n.useReadTransaction();o.database=n;let c=await Ww(o,e,i[0],s.hash_attribute),u;if(!e.operator||e.operator.toLowerCase()==="and"){let _=n.dbis[s.hash_attribute],l=i.slice(1).map(Qw.filterByType),d=l.length,f=fp.setGetWholeRowAttributes(n,e.get_attributes);u=c.map(E=>_.get(E,{transaction:o,lazy:!0})),d>0&&(u=u.filter(E=>{for(let h=0;h<d;h++)if(!l[h](E))return!1;return!0})),(e.offset||e.limit!==void 0)&&(u=u.slice(e.offset,e.limit!==void 0?(e.offset||0)+e.limit:void 0)),u=u.map(E=>PQ.parseRow(E,f))}else{for(let d=1;d<i.length;d++){let f=i[d],E=await Ww(o,e,f,s.hash_attribute);c=c.concat(E)}let _=new Set,l=e.offset||0;c=c.filter(d=>_.has(d)?!1:(_.add(d),!0)).slice(l,e.limit&&e.limit+l),u=fp.batchSearchByHash(o,s.hash_attribute,e.get_attributes,c)}return u.onDone=()=>{o.done()},u}a(GQ,"lmdbSearchByConditions");async function Ww(e,t,r,n){let s=new MQ(t.schema,t.table,void 0,void 0,n,t.get_attributes),i=r.search_type;return s.search_attribute=r.search_attribute,i===q_.SEARCH_TYPES.BETWEEN?(s.search_value=r.search_value[0],s.end_value=r.search_value[1]):s.search_value=r.search_value,Qw.searchByType(e,s,i,n).map(o=>o.value)}a(Ww,"executeConditionSearch")});var $c=T((Hue,jw)=>{"use strict";var kQ=U().OPERATIONS_ENUM,hp=class{static{a(this,"DeleteObject")}constructor(t,r,n,s=void 0){this.operation=kQ.DELETE,this.schema=t,this.table=r,this.hash_values=n,this.__origin=s}};jw.exports=hp});var mp=T((que,iI)=>{"use strict";var tI=Qn(),rI=$c(),nI=Vc(),sI=qc(),rr=U(),Xw=J(),Zw=Ve(),{getTransactionAuditStorePath:VQ,getSchemaPath:$Q}=Ye(),eI=K();iI.exports=YQ;async function YQ(e){try{if(Xw.isEmpty(global.hdb_schema[e.schema])||Xw.isEmpty(global.hdb_schema[e.schema][e.table]))throw new Error(`unknown schema:${e.schema} and table ${e.table}`);await KQ(e),await WQ(e);let t=$Q(e.schema,e.table);try{await Zw.deleteEnvironment(t,e.table)}catch(r){if(r.message==="invalid environment")eI.warn(`cannot delete environment for ${e.schema}.${e.table}, environment not found`);else throw r}try{let r=VQ(e.schema,e.table);await Zw.deleteEnvironment(r,e.table,!0)}catch(r){if(r.message==="invalid environment")eI.warn(`cannot delete environment for ${e.schema}.${e.table}, environment not found`);else throw r}}catch(t){throw t}}a(YQ,"lmdbDropTable");async function KQ(e){let t=new tI(rr.SYSTEM_SCHEMA_NAME,rr.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,rr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_TABLE_KEY,`${e.schema}.${e.table}`,void 0,[rr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),r=Array.from(await nI(t)),n=[];for(let i=0;i<r.length;i++){let o=r[i];n.push(o.id)}if(n.length===0)return;let s=new rI(rr.SYSTEM_SCHEMA_NAME,rr.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,n);await sI(s)}a(KQ,"deleteAttributesFromSystem");async function WQ(e){let t=new tI(rr.SYSTEM_SCHEMA_NAME,rr.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,rr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY,e.table,void 0,[rr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY,rr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_KEY,rr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),r,n;try{r=Array.from(await nI(t))}catch(i){throw i}for(let i=0;i<r.length;i++){let o=r[i];o.name===e.table&&o.schema===e.schema&&(n=o)}if(!n)throw new Error(`${e.schema}.${e.table} was not found`);let s=new rI(rr.SYSTEM_SCHEMA_NAME,rr.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,[n.id]);try{await sI(s)}catch(i){throw i}}a(WQ,"dropTableFromSystem")});var aI=T((Gue,oI)=>{"use strict";var QQ=require("fs-extra"),zQ=Qn(),JQ=Xo(),jQ=$c(),XQ=mp(),ZQ=qc(),ez=ap(),tz=Vc(),Rs=U(),{getSchemaPath:rz}=Ye(),{handleHDBError:nz,hdb_errors:sz}=ee(),{HDB_ERROR_MSGS:iz,HTTP_STATUS_CODES:oz}=sz;oI.exports=az;async function az(e){let t;try{t=await cz(e.schema);let r=new zQ(Rs.SYSTEM_SCHEMA_NAME,Rs.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,Rs.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_KEY,t,void 0,[Rs.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY]),n=Array.from(await tz(r));for(let o=0;o<n.length;o++){let c={schema:t,table:n[o].name};try{await XQ(c)}catch(u){if(u.message!=="invalid environment")throw u}}let s=new jQ(Rs.SYSTEM_SCHEMA_NAME,Rs.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,[t]);await ZQ(s);let i=rz(t);await QQ.remove(i)}catch(r){throw r}}a(az,"lmdbDropSchema");async function cz(e){let t=new JQ(Rs.SYSTEM_SCHEMA_NAME,Rs.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,[e],[Rs.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY]),r,n;try{r=Array.from(await ez(t))}catch(s){throw s}for(let[,s]of r)s.name===e&&(n=e);if(!n)throw nz(new Error,iz.SCHEMA_NOT_FOUND(e),oz.NOT_FOUND,void 0,void 0,!0);return n}a(cz,"validateDropSchema")});var Sp=T((Vue,cI)=>{"use strict";var pp=class{static{a(this,"CreateTableObject")}constructor(t,r,n){this.schema=t,this.table=r,this.hash_attribute=n}};cI.exports=pp});var lI=T((Kue,uI)=>{"use strict";var uz=require("fs-extra"),F_=Ve(),{getTransactionAuditStorePath:lz}=Ye(),Tp=lt(),Yue=Sp();uI.exports=_z;async function _z(e){let t;try{let r=lz(e.schema,e.table);await uz.mkdirp(r),t=await F_.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{F_.createDBI(t,Tp.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,!1,!0),F_.createDBI(t,Tp.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE,!0,!1),F_.createDBI(t,Tp.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(_z,"createTransactionsAuditEnvironment")});var EI=T((Que,fI)=>{"use strict";var gp=U(),_I=Ve(),dz=qo(),{getSystemSchemaPath:fz,getSchemaPath:Ez}=Ye(),hz=vi(),mz=E_(),Rp=f_(),pz=K(),Sz=lI(),Op=hz.hdb_table,dI=[];for(let e=0;e<Op.attributes.length;e++)dI.push(Op.attributes[e].attribute);fI.exports=Tz;async function Tz(e,t){let r=Ez(t.schema,t.table),n=new Rp(t.schema,t.table,gp.TIME_STAMP_NAMES_ENUM.CREATED_TIME,void 0,!0),s=new Rp(t.schema,t.table,gp.TIME_STAMP_NAMES_ENUM.UPDATED_TIME,void 0,!0),i=new Rp(t.schema,t.table,t.hash_attribute,void 0,!1,!0);try{if(await _I.createEnvironment(r,t.table),e!==void 0){let o=await _I.openEnvironment(fz(),gp.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME);await dz.insertRecords(o,Op.hash_attribute,dI,[e]),n.skip_table_check=!0,s.skip_table_check=!0,i.skip_table_check=!0,await Ap(n),await Ap(s),await Ap(i)}await Sz(t)}catch(o){throw o}}a(Tz,"lmdbCreateTable");async function Ap(e){try{await mz(e)}catch(t){pz.warn(`failed to create attribute ${e.attribute} due to ${t.message}`)}}a(Ap,"createAttribute")});var mI=T((Jue,hI)=>{"use strict";var gz=wc(),Rz=Mc(),Az=M_(),Yc=U(),Oz=qo().updateRecords,bz=Ve(),{getSchemaPath:yz}=Ye(),Nz=Hc(),wz=K();hI.exports=Iz;async function Iz(e){try{let{schema_table:t,attributes:r}=gz(e);Rz(e,r,t.hash_attribute),e.schema!==Yc.SYSTEM_SCHEMA_NAME&&(r.includes(Yc.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||r.push(Yc.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.includes(Yc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||r.push(Yc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let n=await Az(e.hdb_auth_header,t,r),s=yz(e.schema,e.table),i=await bz.openEnvironment(s,e.table),o=await Oz(i,t.hash_attribute,r,e.records,e.__origin?.timestamp);try{await Nz(e,o)}catch(c){wz.error(`unable to write transaction due to ${c.message}`)}return{written_hashes:o.written_hashes,skipped_hashes:o.skipped_hashes,schema_table:t,new_attributes:n,txn_time:o.txn_time}}catch(t){throw t}}a(Iz,"lmdbUpdateRecords")});var SI=T((Xue,pI)=>{"use strict";var Cz=U().OPERATIONS_ENUM,bp=class{static{a(this,"UpsertObject")}constructor(t,r,n,s=void 0){this.operation=Cz.UPSERT,this.schema=t,this.table=r,this.records=n,this.__origin=s}};pI.exports=bp});var gI=T((tle,TI)=>{"use strict";var ele=SI(),Dz=wc(),Lz=Mc(),Mz=M_(),Kc=U(),Uz=qo().upsertRecords,Pz=Ve(),{getSchemaPath:vz}=Ye(),Bz=Hc(),Hz=K(),{handleHDBError:xz,hdb_errors:qz}=ee();TI.exports=Fz;async function Fz(e){let t;try{t=Dz(e)}catch(u){throw xz(u,u.message,qz.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0)}let{schema_table:r,attributes:n}=t;Lz(e,n,r.hash_attribute),e.schema!==Kc.SYSTEM_SCHEMA_NAME&&(n.includes(Kc.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||n.push(Kc.TIME_STAMP_NAMES_ENUM.CREATED_TIME),n.includes(Kc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||n.push(Kc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let s=await Mz(e.hdb_auth_header,r,n),i=vz(e.schema,e.table),o=await Pz.openEnvironment(i,e.table),c=await Uz(o,r.hash_attribute,n,e.records,e.__origin?.timestamp);try{await Bz(e,c)}catch(u){Hz.error(`unable to write transaction due to ${u.message}`)}return{written_hashes:c.written_hashes,schema_table:r,new_attributes:s,txn_time:c.txn_time}}a(Fz,"lmdbUpsertRecords")});var AI=T((nle,RI)=>{"use strict";var yp=class{static{a(this,"DeleteBeforeObject")}constructor(t,r,n){this.schema=t,this.table=r,this.timestamp=n}};RI.exports=yp});var bI=T((ile,OI)=>{"use strict";var Np=class{static{a(this,"DeleteAuditLogsBeforeResults")}constructor(t=void 0,r=void 0,n=0){this.start_timestamp=t,this.end_timestamp=r,this.transactions_deleted=n}};OI.exports=Np});var wI=T((cle,NI)=>{"use strict";var wp=Ve(),{getTransactionAuditStorePath:Gz}=Ye(),ale=AI(),Wc=lt(),kz=J(),yI=bI(),Vz=require("util").promisify,$z=Vz(setTimeout),Yz=1e4,Kz=100;NI.exports=Wz;async function Wz(e){let t=Gz(e.schema,e.table),r=await wp.openEnvironment(t,e.table,!0),n=wp.listDBIs(r);wp.initializeDBIs(r,Wc.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,n);let s,i=new yI;do s=await Qz(r,e.timestamp),i.start_timestamp===void 0&&(i.start_timestamp=s.start_timestamp),s.end_timestamp!==void 0&&(i.end_timestamp=s.end_timestamp),i.transactions_deleted+=s.transactions_deleted,await $z(Kz);while(s.transactions_deleted>0);return i}a(Wz,"deleteAuditLogsBefore");async function Qz(e,t){let r=new yI;try{let n=e.dbis[Wc.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP],s;for(let{key:i,value:o}of n.getRange({start:!1})){if(i>=t)break;r.start_timestamp===void 0&&(r.start_timestamp=i),s=n.remove(i);let c=o[Wc.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME];kz.isEmpty(c)||(s=e.dbis[Wc.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].remove(c,i));for(let u=0;u<o.hash_values.length;u++)s=e.dbis[Wc.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE].remove(o.hash_values[u],i);if(r.transactions_deleted++,r.end_timestamp=i,r.transactions_deleted>Yz)break}return await s,r}catch(n){throw n}}a(Qz,"deleteTransactions")});var CI=T((lle,II)=>{"use strict";var Ip=class{static{a(this,"DropAttributeObject")}constructor(t,r,n){this.schema=t,this.table=r,this.attribute=n}};II.exports=Ip});var LI=T((fle,DI)=>{"use strict";var zz=Qn(),Jz=$c(),dle=CI(),zn=U(),jz=J(),Cp=Ve(),Xz=vi(),Zz=Vc(),eJ=qc(),{getSchemaPath:tJ}=Ye();DI.exports=rJ;async function rJ(e,t=!0){let r;e.schema===zn.SYSTEM_SCHEMA_NAME?r=Xz[e.table]:r=global.hdb_schema[e.schema][e.table];let n=await sJ(e),s=tJ(e.schema,e.table),i=await Cp.openEnvironment(s,e.table);return t===!0&&await nJ(e,i,r.hash_attribute),Cp.dropDBI(i,e.attribute),n}a(rJ,"lmdbDropAttribute");async function nJ(e,t,r){let n=Cp.openDBI(t,r),s,i=e.attribute;for(let{key:o,value:c,version:u}of n.getRange({start:!1,versions:!0})){let _={};for(let l in c)l!==i&&(_[l]=c[l]);s=t.dbis[r].put(o,_,u)}await s}a(nJ,"removeAttributeFromAllObjects");async function sJ(e){let t=new zz(zn.SYSTEM_SCHEMA_NAME,zn.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,zn.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_TABLE_KEY,`${e.schema}.${e.table}`,void 0,[zn.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY,zn.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ATTRIBUTE_KEY]),n=Array.from(await Zz(t)).filter(o=>o[zn.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ATTRIBUTE_KEY]===e.attribute);if(jz.isEmptyOrZeroLength(n))throw new Error(`Attribute '${e.attribute}' was not found in '${e.schema}.${e.table}'`);let s=n.map(o=>o[zn.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),i=new Jz(zn.SYSTEM_SCHEMA_NAME,zn.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,s);return eJ(i)}a(sJ,"dropAttributeFromSystem")});var HI=T((mle,BI)=>{"use strict";var Dp=Ve(),Zo=lt(),hle=Cr(),Lp=U(),MI=J(),{getTransactionAuditStorePath:iJ}=Ye(),oJ=Jo(),G_=Wo(),aJ=K();BI.exports=cJ;async function cJ(e){let t=iJ(e.schema,e.table),r=await Dp.openEnvironment(t,e.table,!0),n=Dp.listDBIs(r);Dp.initializeDBIs(r,Zo.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,n);let s;switch(e.search_type){case Lp.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.TIMESTAMP:return UI(r,e.search_values);case Lp.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.HASH_VALUE:return s=global.hdb_schema[e.schema][e.table].hash_attribute,lJ(r,e.search_values,s);case Lp.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.USERNAME:return uJ(r,e.search_values);default:return UI(r)}}a(cJ,"readAuditLog");function UI(e,t=[0,Date.now()]){MI.isEmpty(t[0])&&(t[0]=0),MI.isEmpty(t[1])&&(t[1]=Date.now());let r=e.dbis[Zo.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP],n;for(let s of r.getKeys({start:t[1]}))if(s!==t[1]){n=s;break}return r.getRange({start:t[0],end:n}).map(({value:s})=>Object.assign(new G_,s))}a(UI,"searchTransactionsByTimestamp");function uJ(e,t=[]){let r=new Map;for(let n=0;n<t.length;n++){let s=t[n],i=[];for(let o of e.dbis[Zo.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].getValues(s))i.push(o);r.set(s,vI(e,i))}return Object.fromEntries(r)}a(uJ,"searchTransactionsByUsername");function lJ(e,t,r){let n=new Map;for(let c=0,u=t.length;c<u;c++){let _=t[c],l=oJ.equals(e,Zo.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,Zo.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE,_);for(let{value:d}of l){let f=Number(d);n.has(f)?n.get(f).push(_.toString()):n.set(f,[_.toString()])}}let s=Array.from(n.keys()),i=vI(e,s),o=new Map;for(let c=0;c<i.length;c++){let u=i[c],_=u.timestamp,l=n.get(_);PI(u,"records",r,l,o),PI(u,"original_records",r,l,o)}return Object.fromEntries(o)}a(lJ,"searchTransactionsByHashValues");function PI(e,t,r,n,s){let i=e.timestamp;if(e[t])for(let o=0;o<e[t].length;o++){let c=e[t][o],u=c[r].toString();if(n.indexOf(u)>=0)if(s.has(u)){let _=s.get(u),l=_[_.length-1];if(l.timestamp===i)l[t]=[c];else{let d=new G_(e.operation,e.user_name,i,void 0);d[t]=[c],_.push(d)}}else{let _=new G_(e.operation,e.user_name,i,void 0);_[t]=[c],s.set(u,[_])}}}a(PI,"loopRecords");function vI(e,t){let r=[];try{let n=e.dbis[Zo.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP];for(let s=0;s<t.length;s++)try{let i=n.get(t[s]);if(i){let o=Object.assign(new G_,i);r.push(o)}}catch(i){aJ.warn(i)}return r}catch(n){throw n}}a(vI,"batchSearchTransactions")});var qI=T((gle,xI)=>{"use strict";var{getSchemaPath:Sle}=Ye(),Tle=Ve(),{database:_J}=(be(),te(qe));xI.exports={writeTransaction:dJ};async function dJ(e,t,r){return _J({database:e,table:t}).transaction(r)}a(dJ,"writeTransaction")});var VI=T((Ale,kI)=>{"use strict";var{getSchemaPath:FI}=Ye(),GI=Ve();kI.exports={flush:fJ,resetReadTxn:EJ};async function fJ(e,t){return(await GI.openEnvironment(FI(e,t),t.toString())).flushed}a(fJ,"flush");async function EJ(e,t){try{(await GI.openEnvironment(FI(e,t),t.toString())).resetReadTxn()}catch{}}a(EJ,"resetReadTxn")});var WI=T((ble,KI)=>{"use strict";var{Readable:hJ}=require("stream"),{getDatabases:mJ}=(be(),te(qe)),{readSync:pJ,openSync:SJ,createReadStream:$I}=require("fs"),{open:TJ}=require("lmdb"),YI=n_(),gJ=i_(),{AUDIT_STORE_OPTIONS:RJ}=(Ui(),te(QI)),{INTERNAL_DBIS_NAME:AJ,AUDIT_STORE_NAME:OJ}=lt();KI.exports=yJ;var Mp=32768,bJ=100;async function yJ(e){let t=e.database||e.schema||"data",r=mJ()[t],n=new Date().toISOString(),s=e.tables||e.table&&[e.table];if(s){let _=r[s[0]];if(!_)throw new Error(`Can not find table ${s[0]}`);let l=_.dbisDB,d=TJ({noSync:!0,maxDbs:gJ.MAX_DBS}),f,E=d.openDB(AJ,new YI(!1)),h=l.useReadTransaction(),p=0,S=a(async function(g,R){R.encoding="binary",R.encoder=void 0;let B=d.openDB(g,R),H=l.openDB(g,R);for(let{key:v,version:M,value:$}of H.getRange({transaction:h,versions:H.useVersions}))f=B.put(v,$,M),p++%bJ===0&&(await new Promise(W=>setTimeout(W,20)),h.openTimer&&(h.openTimer=0))},"copyDatabase");for(let{key:g,value:R}of l.getRange({transaction:h,start:!1}))if(s.some(B=>g.startsWith?.(B+"/"))){E.put(g,R);let[,B]=g.split("/"),H=!B,v=new YI(!H,H);await S(g,v)}e.include_audit&&await S(OJ,Object.assign({},RJ)),await f;let O=$I(d.path);return O.headers=u(),O.on("close",()=>{h.done(),d.close()}),O}let o=r[Object.keys(r)[0]].primaryStore,c=SJ(o.path);return o.transaction(()=>{let _=Buffer.alloc(Mp);pJ(c,_,0,Mp),o.resetReadTxn();let l=o.useReadTransaction();l.renew();let d=$I(null,{fd:c,start:Mp}),f=new hJ.from(async function*(){yield _;for await(let E of d)l.openTimer&&(l.openTimer=0),yield E;l.done()}());return f.headers=u(),f});function u(){let _=new Map;return _.set("content-type","application/octet-stream"),_.set("content-disposition",`attachment; filename="${t}"`),_.set("date",n),_}}a(yJ,"getBackup")});var jI=T((Nle,JI)=>{"use strict";var NJ=K(),{handleHDBError:wJ}=ee(),IJ=Ib(),CJ=E_(),DJ=ep(),LJ=aw(),MJ=qc(),UJ=ap(),PJ=Uw(),vJ=kw(),BJ=Vc(),HJ=Jw(),xJ=aI(),qJ=EI(),FJ=mI(),GJ=gI(),kJ=wI(),VJ=mp(),$J=LI(),YJ=HI(),KJ=qI(),zI=VI(),WJ=WI(),Up=class extends IJ{static{a(this,"LMDBBridge")}async searchByConditions(t){return HJ(t)}async getDataByHash(t){return await UJ(t)}async searchByHash(t){return await PJ(t)}async getDataByValue(t,r){return await vJ(t,r)}async searchByValue(t){return await BJ(t)}async createSchema(t){return await LJ(t)}async dropSchema(t){return await xJ(t)}async createTable(t,r){return await qJ(t,r)}async dropTable(t){return await VJ(t)}async createAttribute(t){return await CJ(t)}async createRecords(t){return await DJ(t)}async updateRecords(t){return await FJ(t)}async upsertRecords(t){try{return await GJ(t)}catch(r){throw wJ(r,null,null,NJ.ERR,r)}}async deleteRecords(t){return await MJ(t)}async dropAttribute(t){return await $J(t)}async deleteAuditLogsBefore(t){return await kJ(t)}async readAuditLog(t){return await YJ(t)}writeTransaction(t,r,n){return KJ.writeTransaction(t,r,n)}flush(t,r){return zI.flush(t,r)}resetReadTxn(t,r){return zI.resetReadTxn(t,r)}getBackup(t){return WJ(t)}};JI.exports=Up});function jJ(){JJ=setInterval(function(){for(let e of Pp)if(e.stale){let t=e[ye]?.url;XI.error(`Transaction was open too long and has been aborted, from table: ${e.lmdbDb?.name+(t?" path: "+t:"")}`),e.abort()}else e.stale=!0},zJ).unref()}var vp,XI,QJ,Pp,Qi,k_,zJ,JJ,Bp=Oe(()=>{vp=x(Cr()),XI=x(K());An();Ho();QJ=100,Pp=new Set,Qi=class{static{a(this,"DatabaseTransaction")}writes=[];lmdbDb;readTxn;readTxnRefCount;readTxnsUsed;validated=0;timestamp=0;open=!0;getReadTxn(){if(this.readTxnRefCount=(this.readTxnRefCount||0)+1,this.stale&&(this.stale=!1),this.readTxn)return this.readTxn.openTimer&&(this.readTxn.openTimer=0),this.readTxn;if(!this.open)throw new Error("Can not start a read on a transaction that is no longer open");return this.readTxnsUsed=1,t_(()=>{this.readTxn=this.lmdbDb.useReadTransaction(),this.readTxn.openTimer&&(this.readTxn.openTimer=0)}),Pp.add(this),this.readTxn}useReadTxn(){return this.getReadTxn(),t_(()=>{this.readTxn.use()}),this.readTxnsUsed++,this.readTxn}doneReadTxn(){this.readTxn&&(this.readTxn.done(),--this.readTxnsUsed===0&&(Pp.delete(this),this.readTxn=null))}disregardReadTxn(){--this.readTxnRefCount===0&&this.readTxnsUsed===1&&this.doneReadTxn()}addWrite(t){if(!this.open&&!this.autoCommitMode)throw new Error("Can not use a transaction that is no longer open");this.writes.push(t),this.autoCommitMode&&this.commit()}removeWrite(t){let r=this.writes.indexOf(t);r>-1&&(this.writes[r]=null)}commit(t={}){let r=this.timestamp;r||(r=this.timestamp=t.timestamp=t.timestamp||(0,vp.getNextMonotonicTime)());let n=t.retries||0;if(this.validated<this.writes.length)try{let l=this.validated;this.validated=this.writes.length;for(let f=l;f<this.validated;f++)this.writes[f]?.validate?.(this.timestamp);let d;for(let f=l;f<this.validated;f++){let E=this.writes[f];E&&(E.before||E.beforeIntermediate)&&(d=!0)}if(d)return(async()=>{try{for(let f=0;f<2;f++){let E;for(let h=l;h<this.validated;h++){let p=this.writes[h];if(!p)continue;let S=p[f===0?"before":"beforeIntermediate"];if(S){let O=S();E?E.push?E.push(O):E=[E,O]:E=O}}E&&await(E.push?Promise.all(E):E)}}catch(f){throw this.abort(),f}return this.commit(t)})()}catch(l){throw this.abort(),l}n||this.doneReadTxn(),t?.prepared?.(),this.open=!1;let s,i=[],o=0;this.writes=this.writes.filter(l=>l);let c=a(l=>{l.commit(r,l.entry,n)},"doWrite"),u=a(()=>{let l=this.writes[o++];if(l)if(l.key){n>0&&(l.entry=l.store.getEntry(l.key));let d=l.store.ifVersion(l.key,l.entry?.version??null,u);s=s||d}else u();else for(let d of this.writes)c(d)},"nextCondition");if(this.writes.length<QJ>>n?u():s=this.writes[0].store.transaction(()=>{for(let l of this.writes)l.entry=l.store.getEntry(l.key),c(l);return!0}),s)return s.then(l=>l?(this.next&&i.push(this.next.commit(t)),t?.flush&&i.push(this.writes[0].store.flushed),this.writes=[],this.next=null,Promise.all(i).then(()=>({txnTime:r}))):(t?t.retries=n+1:t={retries:1},this.commit(t)));let _={txnTime:r};if(this.next){let l=this.next?.commit(t);if(l?.then)return l?.then(d=>({txnTime:r,next:d}));_.next=l}return _}abort(){for(;this.readTxnsUsed>0;)this.doneReadTxn();this.open=!1,this.writes=[]}},k_=class extends Qi{static{a(this,"ImmediateTransaction")}_timestamp;addWrite(t){super.addWrite(t),this.commit()}get timestamp(){return this._timestamp||(this._timestamp=(0,vp.getNextMonotonicTime)())}getReadTxn(){}},zJ=3e4;a(jJ,"startMonitoringTxns");jJ()});function Ke(e,t,r){if(!t)t=e,e={};else if(!e)e={};else if(e?.transaction?.open&&typeof t=="function")return t(e.transaction);if(typeof t!="function")throw new Error("Callback function must be provided to transaction");let n=e.transaction=new Qi;e.timestamp&&(n.timestamp=e.timestamp),n[ye]=e,e.resourceCache||(e.resourceCache=[]);let s;try{if(s=t(n),s?.then)return s.then(i,o)}catch(c){o(c)}return i(s);function i(c){let u=n.commit(r?.resetTransaction?{prepared(){n.autoCommitMode=!0}}:{});return u.then?u.then(()=>c):c}function o(c){throw n.abort({}),c}}var ZI,zi=Oe(()=>{ZI=require("../../index");An();Bp();a(Ke,"transaction");(0,ZI._assignPackageExport)("transaction",Ke);Ke.commit=function(e){let t=(e[ye]||e)?.transaction;if(!t)throw new Error("No active transaction is available to commit");return t.commit()};Ke.abort=function(e){let t=(e[ye]||e)?.transaction;if(!t)throw new Error("No active transaction is available to abort");return t.abort()}});var cC={};ke(cC,{ResourceBridge:()=>qp});function Fp({get_attributes:e},t){if(e){if(e[0]==="*"){if(t.schemaDefined)return;e=t.attributes.map(r=>r.name)}return e.forceNulls=!0,e}}function tC(e,t){let r=Jn(e),n=Fp(e,r);if(!r)throw new wn.ClientError(`Table ${e.table} not found`);let s;n&&r.attributes.length-n.length>2&&n.length<5&&(s=!0);let i={user:e.hdb_user},o;Ke(i,()=>new Promise(_=>o=_));let c=e.ids||e.hash_values,u=0;return{[Symbol.asyncIterator](){return{async next(){if(u<c.length){let _=c[u++],l=await r.get({id:_,lazy:s,select:n},i);return l=l&&$_(l),t?{value:{key:_,value:l}}:{value:l}}else return o(),{done:!0}},return(_){return o(),{value:_,done:!0}},throw(_){return o(),{done:!0}}}}}}function Jn(e){let t=e.database||e.schema||ZJ,r=In()[t];if(!r)throw(0,wn.handleHDBError)(new Error,XJ.SCHEMA_NOT_FOUND(t),404);return r[e.table]}function rC(e,t,r){let n=e.length+t.length,s=n===1?"record":"records";return{message:`${e.length} of ${n} ${s} successfully deleted`,deleted_hashes:e,skipped_hashes:t,txn_time:r}}async function*nC(e,t,r){let n;for await(let s of e.getHistory(t,r)){let i=s.type;i==="put"&&(i="upsert");let{id:o,version:c,value:u}=s;n?.timestamp===c?(n.hash_values.push(o),n.records.push(u)):(n&&(yield n),n={operation:i,user_name:s.user,timestamp:c,hash_values:[o],records:[u]})}n&&(yield n)}var sC,V_,wn,iC,oC,Cn,Hp,xp,aC,XJ,ZJ,e2,t2,eC,qp,uC=Oe(()=>{"use strict";sC=x(jI()),V_=x(jo()),wn=x(ee());be();iC=x(wc()),oC=x(Mc()),Cn=x(U()),Hp=x(Ts()),xp=x(Nn()),aC=x(J());zi();Y_();({HDB_ERROR_MSGS:XJ}=wn.hdb_errors),ZJ="data",e2=1e4,t2=10,qp=class extends sC.default{static{a(this,"ResourceBridge")}constructor(t){super(t),eC=this}async searchByConditions(t){t.select!==void 0&&(t.get_attributes=t.select);for(let o of t.conditions||[])o?.attribute!==void 0&&(o.search_attribute=o.attribute),o?.comparator!==void 0&&(o.search_type=o.comparator),o?.value!==void 0&&(o.search_value=o.value);let r=(0,V_.default)(t,"conditions");if(r)throw(0,wn.handleHDBError)(r,r.message,400,void 0,void 0,!0);let n=Jn(t);if(!n)throw new wn.ClientError(`Table ${t.table} not found`);let s=t.conditions.map(i);function i(o){return o.conditions?(o.conditions=o.conditions.map(i),o):{attribute:o.search_attribute??o.attribute,comparator:o.search_type??o.comparator,value:o.search_value!==void 0?o.search_value:o.value}}return a(i,"mapCondition"),n.search({conditions:s,operator:t.operator?t.operator.toLowerCase():void 0,limit:t.limit,offset:t.offset,reverse:t.reverse,select:Fp(t,n),sort:t.sort,allowFullScan:!0})}async createTable(t,r){let n=r.attributes,s=!!n,i=r.primary_key||r.hash_attribute;if(n)for(let o of n)o.is_primary_key?(o.isPrimaryKey=!0,delete o.is_primary_key):o.name===i&&i&&(o.isPrimaryKey=!0);else{if(!i)throw new wn.ClientError("A primary key must be specified with a `primary_key` property or with `attributes`");n=[{name:i,isPrimaryKey:!0},{name:"__createdtime__",indexed:!0},{name:"__updatedtime__",indexed:!0}]}ot({database:r.schema,table:r.table,attributes:n,schemaDefined:s,expiration:r.expiration})}async createAttribute(t){return await Jn(t).addAttributes([{name:t.attribute,indexed:t.indexed??!0}]),`attribute ${t.schema}.${t.table}.${t.attribute} successfully created.`}async dropAttribute(t){let r=Jn(t);if(await r.removeAttributes([t.attribute]),!r.schemaDefined){let n=t.attribute,s,i=a((o,c,u)=>(c=Object.assign({},c),delete c[n],r.primaryStore.ifVersion(o,u,()=>r.primaryStore.put(o,c,u)).then(_=>{if(!_){let{value:l,version:d}=r.primaryStore.getEntry(o);return i(o,l,d)}})),"deleteRecord");for(let{key:o,value:c,version:u}of r.primaryStore.getRange({start:!0,versions:!0}))s=i(o,c,u),await new Promise(_=>setImmediate(_));await s}return`successfully deleted ${t.schema}.${t.table}.${t.attribute}`}dropTable(t){Jn(t).dropTable()}createSchema(t){return Qc({database:t.schema,table:null}),Hp.signalSchemaChange(new xp.SchemaEventMsg(process.pid,Cn.OPERATIONS_ENUM.CREATE_SCHEMA,t.schema))}async dropSchema(t){await Gp(t.schema),Hp.signalSchemaChange(new xp.SchemaEventMsg(process.pid,Cn.OPERATIONS_ENUM.DROP_SCHEMA,t.schema))}async updateRecords(t){return t.requires_existing=!0,this.upsertRecords(t)}async createRecords(t){return t.requires_no_existing=!0,eC.upsertRecords(t)}async upsertRecords(t){let{schema_table:r,attributes:n}=(0,iC.default)(t);(0,oC.default)(t,n,r.primaryKey);let s,i=In()[t.schema][t.table],o={user:t.hdb_user,expiresAt:t.expiresAt};return Ke(o,async c=>{if(!i.schemaDefined){s=[];for(let l of n)i.attributes.find(f=>f.name==l)||s.push(l);s.length>0&&await i.addAttributes(s.map(l=>({name:l,indexed:!0})))}let u=[],_=[];for(let l of t.records){let d=await i.get(l[i.primaryKey],o);if(t.requires_existing&&!d||t.requires_no_existing&&d){_.push(l[i.primaryKey]);continue}d&&(d=$_(d));for(let f in l)if(Object.prototype.hasOwnProperty.call(l,f)){let E=l[f];if(typeof E=="function")try{let h=E([[d]]);Array.isArray(h)&&(E=h[0].func_val,l[f]=E)}catch(h){throw h.message+="Trying to set key "+f+" on object"+JSON.stringify(l),h}}if(d)for(let f in d)Object.prototype.hasOwnProperty.call(l,f)||(l[f]=d[f]);await i.put(l,o),u.push(l[i.primaryKey])}return{txn_time:c.timestamp,written_hashes:u,new_attributes:s,skipped_hashes:_}})}async deleteRecords(t){let r=In()[t.schema][t.table],n={user:t.hdb_user};return Ke(n,async s=>{let i=t.hash_values||t.records.map(u=>u[r.primaryKey]),o=[],c=[];for(let u of i)await r.delete(u,n)?o.push(u):c.push(u);return rC(o,c,s.timestamp)})}async deleteRecordsBefore(t){let r=In()[t.schema][t.table];if(!r.createdTimeProperty)throw new wn.ClientError("Table must have a '__createdtime__' attribute or @createdTime timestamp defined to perform this operation");let n=await r.search({conditions:[{attribute:r.createdTimeProperty.name,value:Date.parse(t.date),comparator:Cn.VALUE_SEARCH_COMPARATORS.LESS}]}),s=!1,i=[],o=[],c=0,u=[],_=a(async()=>{let l=await this.deleteRecords({schema:t.schema,table:t.table,hash_values:u});i.push(...l.deleted_hashes),o.push(...l.skipped_hashes),await(0,aC.async_set_timeout)(t2),u=[],s=!0},"chunkDelete");for await(let l of n)u.push(l[r.primaryKey]),c++,c%e2===0&&await _();return u.length>0&&await _(),s?rC(i,o,void 0):{message:"No records found to delete"}}searchByHash(t){t.select!==void 0&&(t.get_attributes=t.select);let r=(0,V_.default)(t,"hashes");if(r)throw r;return tC(t)}async getDataByHash(t){let r=new Map;t._returnKeyValue=!0;for await(let{key:n,value:s}of tC(t,!0))r.set(n,s);return r}searchByValue(t,r){if(r&&Cn.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[r]===void 0)throw new Error(`Value search comparator - ${r} - is not valid`);t.select!==void 0&&(t.get_attributes=t.select),t.attribute!==void 0&&(t.search_attribute=condition.attribute),t.value!==void 0&&(t.search_value=condition.value);let n=(0,V_.default)(t,"value");if(n)throw n;let s=Jn(t);if(!s)throw new wn.ClientError(`Table ${t.table} not found`);let i=t.search_value;i.includes?.("*")&&(i.startsWith("*")?i.endsWith("*")?i!=="*"&&(r="contains",i=i.slice(1,-1)):(r="ends_with",i=i.slice(1)):i.endsWith("*")&&(r="starts_with",i=i.slice(0,-1))),r===Cn.VALUE_SEARCH_COMPARATORS.BETWEEN&&(i=[i,t.end_value]);let o=i==="*"?[]:[{attribute:t.search_attribute,value:i,comparator:r}];return s.search({conditions:o,allowFullScan:!0,limit:t.limit,offset:t.offset,reverse:t.reverse,select:Fp(t,s)})}async getDataByValue(t,r){let n=new Map,s=Jn(t);t.get_attributes&&!t.get_attributes.includes(s.primaryKey)&&t.get_attributes[0]!=="*"&&t.get_attributes.push(s.primaryKey);for await(let i of this.searchByValue(t,r))n.set(i[s.primaryKey],i);return n}resetReadTxn(t,r){Jn({schema:t,table:r})?.primaryStore.resetReadTxn()}async deleteAuditLogsBefore(t){return Jn(t).deleteHistory(t.timestamp)}async readAuditLog(t){let r=Jn(t),n={};switch(t.search_type){case Cn.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.HASH_VALUE:for(let i of t.search_values)n[i]=(await r.getHistoryOfRecord(i)).map(o=>{let c=o.type;return c==="put"&&(c="upsert"),{operation:c,timestamp:o.version,user_name:o.user,hash_values:[i],records:[o.value]}});return n;case Cn.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.USERNAME:let s=t.search_values;for await(let i of nC(r))s.includes(i.user_name)&&(n[i.user_name]||(n[i.user_name]=[])).push(i);return n;default:return nC(r,t.search_values?.[0],t.search_values?.[1])}}};a(Fp,"getSelect");a(tC,"getRecords");a(Jn,"getTable");a(rC,"createDeleteResponse");a(nC,"groupRecordsInHistory")});var yn=T((Gle,lC)=>{"use strict";var{ResourceBridge:r2}=(uC(),te(cC)),n2=Z();n2.initSync();var K_;function s2(){return K_||(K_=new r2,K_)}a(s2,"getBridge");lC.exports=s2()});var EC=T((Vle,fC)=>{"use strict";var _C=require("lodash"),zc=require("mathjs"),i2=require("jsonata"),dC=J();fC.exports={distinct_array:e=>Array.isArray(e)&&e.length>1?_C.uniqWith(e,_C.isEqual):e,searchJSON:o2,mad:Jc.bind(null,zc.mad),mean:Jc.bind(null,zc.mean),mode:Jc.bind(null,zc.mode),prod:Jc.bind(null,zc.prod),median:Jc.bind(null,zc.median)};function Jc(e,t,r,n){return n===1?t==null?[]:[t]:n===2?(t!=null&&r.push(t),r):r!=null&&r.length>0?e(r):null}a(Jc,"aggregateFunction");function o2(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(dC.isEmpty(this.__ala__.res)&&(this.__ala__.res={}),dC.isEmpty(this.__ala__.res[r])){let n=i2(e);this.__ala__.res[r]=n}return this.__ala__.res[r].evaluate(t)}a(o2,"searchJSON")});var mC=T((Yle,hC)=>{"use strict";var dt=require("moment"),kp="YYYY-MM-DDTHH:mm:ss.SSSZZ";dt.suppressDeprecationWarnings=!0;hC.exports={current_date:()=>dt().utc().format("YYYY-MM-DD"),current_time:()=>dt().utc().format("HH:mm:ss.SSS"),extract:(e,t)=>{switch(t.toLowerCase()){case"year":return dt(e).utc().format("YYYY");case"month":return dt(e).utc().format("MM");case"day":return dt(e).utc().format("DD");case"hour":return dt(e).utc().format("HH");case"minute":return dt(e).utc().format("mm");case"second":return dt(e).utc().format("ss");case"millisecond":return dt(e).utc().format("SSS");default:break}},date:e=>dt(e).utc().format(kp),date_format:(e,t)=>dt(e).utc().format(t),date_add:(e,t,r)=>dt(e).utc().add(t,r).valueOf(),date_sub:(e,t,r)=>dt(e).utc().subtract(t,r).valueOf(),date_diff:(e,t,r)=>{let n=dt(e).utc(),s=dt(t).utc();return r?n.diff(s,r,!0):n.diff(s)},now:()=>dt().utc().valueOf(),get_server_time:()=>dt().format(kp),offset_utc:(e,t)=>dt(e).utc().utcOffset(t).format(kp)}});var gC=T((Kle,TC)=>{"use strict";var a2=require("@turf/area"),c2=require("@turf/length"),u2=require("@turf/circle"),l2=require("@turf/difference"),_2=require("@turf/distance"),d2=require("@turf/boolean-contains"),f2=require("@turf/boolean-equal"),E2=require("@turf/boolean-disjoint"),h2=require("@turf/helpers"),pC=U(),ge=J(),As=K();TC.exports={geoArea:m2,geoLength:p2,geoCircle:S2,geoDifference:T2,geoDistance:SC,geoNear:g2,geoContains:R2,geoEqual:A2,geoCrosses:O2,geoConvert:b2};function m2(e){if(ge.isEmpty(e))return NaN;typeof e=="string"&&(e=ge.autoCastJSON(e));try{return a2.default(e)}catch(t){return As.trace(t,e),NaN}}a(m2,"geoArea");function p2(e,t){if(ge.isEmpty(e))return NaN;typeof e=="string"&&(e=ge.autoCastJSON(e));try{return c2.default(e,{units:t||"kilometers"})}catch(r){return As.trace(r,e),NaN}}a(p2,"geoLength");function S2(e,t,r){if(ge.isEmpty(e))return NaN;if(ge.isEmpty(t))return NaN;typeof e=="string"&&(e=ge.autoCastJSON(e));try{return u2.default(e,t,{units:r||"kilometers"})}catch(n){return As.trace(n,e,t),NaN}}a(S2,"geoCircle");function T2(e,t){if(ge.isEmpty(e))return NaN;if(ge.isEmpty(t))return NaN;typeof e=="string"&&(e=ge.autoCastJSON(e)),typeof t=="string"&&(t=ge.autoCastJSON(t));try{return l2(e,t)}catch(r){return As.trace(r,e,t),NaN}}a(T2,"geoDifference");function SC(e,t,r){if(ge.isEmpty(e))return NaN;if(ge.isEmpty(t))return NaN;typeof e=="string"&&(e=ge.autoCastJSON(e)),typeof t=="string"&&(t=ge.autoCastJSON(t));try{return _2.default(e,t,{units:r||"kilometers"})}catch(n){return As.trace(n,e,t),NaN}}a(SC,"geoDistance");function g2(e,t,r,n){if(ge.isEmpty(e)||ge.isEmpty(t))return!1;if(ge.isEmpty(r))throw new Error("distance is required");if(typeof e=="string"&&(e=ge.autoCastJSON(e)),typeof t=="string"&&(t=ge.autoCastJSON(t)),isNaN(r))throw new Error("distance must be a number");try{return SC(e,t,n)<=r}catch(s){return As.trace(s,e,t),!1}}a(g2,"geoNear");function R2(e,t){if(ge.isEmpty(e)||ge.isEmpty(t)||e.coordinates&&e.coordinates.includes?.(null)||t.coordinates&&t.coordinates.includes?.(null))return!1;typeof e=="string"&&(e=ge.autoCastJSON(e)),typeof t=="string"&&(t=ge.autoCastJSON(t));try{return d2.default(e,t)}catch(r){return As.trace(r,e,t),!1}}a(R2,"geoContains");function A2(e,t){if(ge.isEmpty(e)||ge.isEmpty(t)||e.coordinates&&e.coordinates.includes?.(null)||t.coordinates&&t.coordinates.includes?.(null))return!1;typeof e=="string"&&(e=ge.autoCastJSON(e)),typeof t=="string"&&(t=ge.autoCastJSON(t));try{return f2.default(e,t)}catch(r){return As.trace(r,e,t),!1}}a(A2,"geoEqual");function O2(e,t){if(ge.isEmpty(e)||ge.isEmpty(t)||e.coordinates&&e.coordinates.includes?.(null)||t.coordinates&&t.coordinates.includes?.(null))return!1;typeof e=="string"&&(e=ge.autoCastJSON(e)),typeof t=="string"&&(t=ge.autoCastJSON(t));try{return!E2.default(e,t)}catch(r){return As.trace(r,e,t),!1}}a(O2,"geoCrosses");function b2(e,t,r){if(ge.isEmptyOrZeroLength(e))throw new Error("coordinates is required");if(ge.isEmpty(t))throw new Error("geo_type is required");if(ge.isEmpty(pC.GEO_CONVERSION_ENUM[t]))throw new Error(`geo_type of ${t} is invalid please use one of the following types: ${Object.keys(pC.GEO_CONVERSION_ENUM).join(",")}`);return typeof e=="string"&&(e=ge.autoCastJSON(e)),h2[t](e,r)}a(b2,"geoConvert")});var W_=T((Qle,RC)=>{var Ji=EC(),Br=mC(),jn=gC();RC.exports=e=>{e.aggr.mad=e.aggr.MAD=Ji.mad,e.aggr.mean=e.aggr.MEAN=Ji.mean,e.aggr.mode=e.aggr.MODE=Ji.mode,e.aggr.prod=e.aggr.PROD=Ji.prod,e.aggr.median=e.aggr.MEDIAN=Ji.median,e.fn.distinct_array=e.fn.DISTINCT_ARRAY=Ji.distinct_array,e.fn.search_json=e.fn.SEARCH_JSON=Ji.searchJSON,e.fn.__ala__=e,e.fn.current_date=e.fn.CURRENT_DATE=Br.current_date,e.fn.current_time=e.fn.CURRENT_TIME=Br.current_time,e.fn.extract=e.fn.EXTRACT=Br.extract,e.fn.date=e.fn.DATE=Br.date,e.fn.date_format=e.fn.DATE_FORMAT=Br.date_format,e.fn.date_add=e.fn.DATE_ADD=Br.date_add,e.fn.date_sub=e.fn.DATE_SUB=Br.date_sub,e.fn.date_diff=e.fn.DATE_DIFF=e.fn.datediff=e.fn.DATEDIFF=Br.date_diff,e.fn.now=e.fn.NOW=Br.now,e.fn.offset_utc=e.fn.OFFSET_UTC=Br.offset_utc,e.fn.get_server_time=e.fn.GET_SERVER_TIME=Br.get_server_time,e.fn.getdate=e.fn.GETDATE=Br.now,e.fn.current_timestamp=e.fn.CURRENT_TIMESTAMP=Br.now,e.fn.geoarea=e.fn.GEOAREA=e.fn.geoArea=jn.geoArea,e.fn.geocircle=e.fn.GEOCIRCLE=e.fn.geoCircle=jn.geoCircle,e.fn.geocontains=e.fn.GEOCONTAINS=e.fn.geoContains=jn.geoContains,e.fn.geoconvert=e.fn.GEOCONVERT=e.fn.geoConvert=jn.geoConvert,e.fn.geocrosses=e.fn.GEOCROSSES=e.fn.geoCrosses=jn.geoCrosses,e.fn.geodifference=e.fn.GEODIFFERENCE=e.fn.geoDifference=jn.geoDifference,e.fn.geodistance=e.fn.GEODISTANCE=e.fn.geoDistance=jn.geoDistance,e.fn.geoequal=e.fn.GEOEQUAL=e.fn.geoEqual=jn.geoEqual,e.fn.geolength=e.fn.GEOLENGTH=e.fn.geoLength=jn.geoLength,e.fn.geonear=e.fn.GEONEAR=e.fn.geoNear=jn.geoNear}});var yC=T((zle,bC)=>{"use strict";var jc=require("lodash"),nr=require("alasql");nr.options.cache=!1;var y2=W_(),AC=require("clone"),Q_=require("recursive-iterator"),Ee=K(),Ce=J(),ea=yn(),N2=U(),{hdb_errors:w2}=ee(),{getDatabases:OC}=(be(),te(qe)),I2="IS NULL",Dn="There was a problem performing this search. Please check the logs and try again.";y2(nr);var Vp=class{static{a(this,"SQLSearch")}constructor(t,r){if(Ce.isEmpty(t))throw Ee.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(),Ce.backtickASTSchemaItems(this.statement)}async search(){let t;try{let n=await this._checkEmptySQL();if(!Ce.isEmptyOrZeroLength(n))return Ee.trace("No results returned from checkEmptySQL SQLSearch method."),n}catch(n){throw Ee.error("Error thrown from checkEmptySQL in SQLSearch class method search."),Ee.error(n),new Error(Dn)}try{let n=await this._getFetchAttributeValues();if(n)return n}catch(n){throw Ee.error("Error thrown from getFetchAttributeValues in SQLSearch class method search."),Ee.error(n),new Error(Dn)}if(Object.keys(this.data).length===0)return Ee.trace('SQLSearch class field: "data" is empty.'),[];let r;try{r=await this._processJoins()}catch(n){throw Ee.error("Error thrown from processJoins in SQLSearch class method search."),Ee.error(n),new Error(Dn)}try{await this._getFinalAttributeData(r.existing_attributes,r.joined_length)}catch(n){throw Ee.error("Error thrown from getFinalAttributeData in SQLSearch class method search."),Ee.error(n),new Error(Dn)}try{return t=await this._finalSQL(),t}catch(n){throw Ee.error("Error thrown from finalSQL in SQLSearch class method search."),Ee.error(n),new Error(Dn)}}_getColumns(){let t=new Q_(this.statement);for(let{node:r,path:n}of t)r&&r.columnid&&(this.columns[n[0]]||(this.columns[n[0]]=[]),this.columns[n[0]].push(AC(r)))}_getTables(){let t=[];this.all_table_attributes.forEach(r=>{t.push(r.table)}),this.tables=jc.uniqBy(t,r=>[r.databaseid,r.tableid,r.as].join()),this.tables.forEach(r=>{let n=`${r.databaseid}_${r.as?r.as:r.tableid}`;this.data[n]={},this.data[n].__hash_name=OC()[r.databaseid][r.tableid].primaryKey,this.data[n].__merged_data={},this.data[n].__merged_attributes=[],this.data[n].__merged_attr_map={}})}_conditionsToFetchAttributeValues(){if(Ce.isEmpty(this.statement.where)){Ee.trace('AST "where" statement is empty.');return}let t=!1;for(let{node:r}of new Q_(this.statement.where))if(r&&r.op&&r.op==="OR"&&(t=!0),!Ce.isEmpty(r)&&r.right)if(Ce.isNotEmptyAndHasValue(r.right.value)){let n=Ce.autoCast(r.right.value);[!0,!1].indexOf(n)>=0&&(r.right=new nr.yy.LogicValue({value:n}))}else Array.isArray(r.right)&&r.right.forEach((n,s)=>{let i=Ce.autoCast(n.value);[!0,!1].indexOf(i)>=0?r.right[s]=new nr.yy.LogicValue({value:i}):n instanceof nr.yy.StringValue&&Ce.autoCasterIsNumberCheck(i.toString())&&(r.right[s]=new nr.yy.NumValue({value:i}))});if(t){Ee.trace('Where clause contains "OR", exact match search not performed on attributes.');return}for(let{node:r}of new Q_(this.statement.where))if(r&&r.left&&r.right&&(r.left.columnid||r.right.value)&&r.op){let n=new Set,s=r.left.columnid?r.left:r.right,i=this._findColumn(s);if(!i)continue;let o=[i.table.databaseid,i.table.tableid,i.attribute].join("/");if(!Ce.isEmpty(N2.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[r.op])){if(Ce.isEmpty(this.comparator_search_values[o])&&(this.comparator_search_values[o]={ignore:!1,comparators:[]}),!this.comparator_search_values[o].ignore){if(Ce.isEmptyOrZeroLength(r.left.columnid)||Ce.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(Ce.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"=":!Ce.isEmpty(r.right.value)||!Ce.isEmpty(r.left.value)?n.add(Ce.isEmpty(r.right.value)?r.left.value:r.right.value):c=!0;break;case"IN":let u=Array.isArray(r.right)?r.right:r.left;for(let _=0;_<u.length;_++)if(u[_].value)n.add(u[_].value);else{c=!0;break}break;default:c=!0;break}this.exact_search_values[o].ignore=c,c?this.exact_search_values[o].values=new Set:this.exact_search_values[o].values=new Set([...this.exact_search_values[o].values,...n])}}}_setAliasesForColumns(){if(Ce.isEmptyOrZeroLength(this.all_table_attributes)&&Ce.isEmptyOrZeroLength(this.statement.from)&&Ce.isEmptyOrZeroLength(this.columns.columns))return;let t=[],r={};this.statement.columns.forEach((n,s)=>{if(n.columnid==="*"){t.push(s);return}if(n.aggregatorid&&(this.has_aggregator=!0),!n.aggregatorid&&!n.funcid)if(n.as_orig=n.as?n.as:n.columnid,this.statement.joins)if(r[n.as_orig]>=0){let i=r[n.as_orig]+1;n.as=`[${n.as_orig+i}]`,r[n.as_orig]=i}else n.as=`[${n.as_orig}]`,r[n.as_orig]=0;else n.as=`[${n.as_orig}]`;!n.aggregatorid&&n.funcid&&n.args&&(n.as_orig=n.as?n.as:n.toString().replace(/'/g,'"'),n.as=`[${n.as_orig}]`),n.aggregatorid&&n.expression.columnid!=="*"&&(n.as_orig=n.as?n.as:n.expression.tableid?`${n.aggregatorid}(${n.expression.tableid}.${n.expression.columnid})`:`${n.aggregatorid}(${n.expression.columnid})`,n.as=`[${n.as_orig}]`)}),this.statement.columns.length>1&&t.length>0&&jc.pullAt(this.statement.columns,t)}_findColumn(t){let r=this.all_table_attributes.filter(n=>{if(t.columnid_orig&&t.tableid_orig)return(n.table.as===t.tableid_orig||n.table.tableid===t.tableid_orig)&&n.attribute===t.columnid_orig;if(t.tableid)return(n.table.as===t.tableid||n.table.tableid===t.tableid)&&n.attribute===t.columnid;let s=t.columnid_orig?t.columnid_orig:t.columnid;return n.attribute===s});if(Ce.isEmptyOrZeroLength(r)){let n=this.columns.columns.filter(s=>s.as?t.columnid===s.as:!1);Ce.isEmptyOrZeroLength(n)||(r=this.all_table_attributes.filter(s=>s.attribute===n[0].columnid&&n[0].tableid&&n[0].tableid===(s.table.as?s.table.as:s.table.tableid)))}return r[0]}async _checkEmptySQL(){let t=[];if(Ce.isEmptyOrZeroLength(this.all_table_attributes)&&!Ce.isEmptyOrZeroLength(this.columns.columns))return t;if(Ce.isEmptyOrZeroLength(this.all_table_attributes)&&Ce.isEmptyOrZeroLength(this.statement.from))try{let r=this._buildSQL(!1);t=await nr.promise(r)}catch(r){throw Ee.error("Error thrown from AlaSQL in SQLSearch class method checkEmptySQL."),Ee.error(r),new Error("There was a problem with the SQL statement")}return t}_addFetchColumns(t){t&&t.length>0&&t.forEach(r=>{let n=this._findColumn(r);n&&this.fetch_attributes.push(AC(n))})}_addColumnToMergedAttributes(t,r){this.data[t].__merged_attributes.push(r),this.data[t].__merged_attr_map[r]=this.data[t].__merged_attributes.length-1}_setMergedHashAttribute(t,r){this.data[t].__merged_data[r].splice(0,1,r)}_updateMergedAttribute(t,r,n,s){let i=this.data[t].__merged_attr_map[n];this.data[t].__merged_data[r].splice(i,1,s)}async _getFetchAttributeValues(){if(Ce.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(I2)>-1&&this.tables.forEach(s=>{let i={columnid:OC()[s.databaseid][s.tableid].primaryKey,tableid:s.tableid};this._addFetchColumns([i])}),this.statement.order&&(this._updateOrderByToAliases(),this._addNonAggregatorsToFetchColumns()),this.fetch_attributes=jc.uniqBy(this.fetch_attributes,s=>[s.table.databaseid,s.table.as?s.table.as:s.table.tableid,s.attribute].join()),r)return await this._simpleSQLQuery();let n=this.fetch_attributes.reduce((s,i)=>{let o=`${i.table.databaseid}_${i.table.as?i.table.as:i.table.tableid}`,c=this.data[o].__hash_name;return s[o]||(s[o]=[],s[o].push(null),this._addColumnToMergedAttributes(o,c)),i.attribute!==c&&(s[o].push(null),this._addColumnToMergedAttributes(o,i.attribute)),s},{});for(let s of this.fetch_attributes){let i=`${s.table.databaseid}_${s.table.as?s.table.as:s.table.tableid}`,o=this.data[i].__hash_name,c={schema:s.table.databaseid,table:s.table.tableid,get_attributes:[s.attribute]},u=!1,_=[s.table.databaseid,s.table.tableid,s.attribute].join("/");if(s.attribute===o&&(u=!0),!Ce.isEmpty(this.exact_search_values[_])&&!this.exact_search_values[_].ignore&&!Ce.isEmptyOrZeroLength(this.exact_search_values[_].values))if(u)try{c.hash_values=Array.from(this.exact_search_values[_].values);let l=await ea.getDataByHash(c);for(let d of c.hash_values)l.get(d)&&!this.data[i].__merged_data[d]&&(this.data[i].__merged_data[d]=[...n[i]],this._setMergedHashAttribute(i,d))}catch(l){throw Ee.error("Error thrown from getDataByHash function in SQLSearch class method getFetchAttributeValues exact match."),Ee.error(l),new Error(Dn)}else try{c.search_attribute=s.attribute,await Promise.all(Array.from(this.exact_search_values[_].values).map(async l=>{let d=Object.assign({},c);d.search_value=l;let f=await ea.getDataByValue(d);for(let[E,h]of f)this.data[i].__merged_data[E]?this._updateMergedAttribute(i,E,s.attribute,h[s.attribute]):(this.data[i].__merged_data[E]=[...n[i]],this._updateMergedAttribute(i,E,s.attribute,h[s.attribute]),this._setMergedHashAttribute(i,E))}))}catch(l){throw Ee.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues exact match."),Ee.error(l),new Error(Dn)}else if(!Ce.isEmpty(this.comparator_search_values[_])&&!this.comparator_search_values[_].ignore&&!Ce.isEmptyOrZeroLength(this.comparator_search_values[_].comparators))try{let l=this.comparator_search_values[_].comparators;for(let d=0,f=l.length;d<f;d++){let E=l[d];c.search_attribute=E.attribute,c.search_value=E.search_value;let h=await ea.getDataByValue(c,E.operation);if(u)for(let[p]of h)this.data[i].__merged_data[p]||(this.data[i].__merged_data[p]=[...n[i]],this._setMergedHashAttribute(i,p));else for(let[p,S]of h)this.data[i].__merged_data[p]?this._updateMergedAttribute(i,p,s.attribute,S[s.attribute]):(this.data[i].__merged_data[p]=[...n[i]],this._updateMergedAttribute(i,p,s.attribute,S[s.attribute]),this._setMergedHashAttribute(i,p))}}catch(l){throw Ee.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues comparator search values."),Ee.error(l),new Error(Dn)}else try{c.search_attribute=s.attribute,c.search_value="*";let l=await ea.getDataByValue(c);if(u)for(let[d]of l)this.data[i].__merged_data[d]||(this.data[i].__merged_data[d]=[...n[i]],this._setMergedHashAttribute(i,d));else for(let[d,f]of l)this.data[i].__merged_data[d]?this._updateMergedAttribute(i,d,s.attribute,f[s.attribute]):(this.data[i].__merged_data[d]=[...n[i]],this._updateMergedAttribute(i,d,s.attribute,f[s.attribute]),this._setMergedHashAttribute(i,d))}catch(l){throw Ee.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues no comparator search values."),Ee.error(l),new Error(Dn)}}}_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 nr.yy.Column||(t=!1)}),t)}_updateOrderByToAliases(){this.statement.order.forEach(t=>{if(t.expression.aggregatorid){t.is_aggregator=!0;return}if(t.expression.value){t.is_ordinal=!0,this.has_ordinal=!0;return}else t.is_ordinal=!1;let r=this.statement.columns.filter(s=>{let i=s.aggregatorid?s.expression:s,o=s.aggregatorid?s.as_orig:i.as_orig;return t.expression.tableid?i.columnid_orig===t.expression.columnid_orig&&i.tableid_orig===t.expression.tableid_orig:i.columnid_orig===t.expression.columnid_orig||t.expression.columnid_orig===o});r[0]||r.push(this._findColumn(t.expression));let n=r[0];if(t.is_func=!!n.funcid,t.is_aggregator=!!n.aggregatorid,n.as)if(n.as&&!t.expression.tableid)t.expression.columnid=n.as,t.expression.columnid_orig=n.as_orig;else{let s=new nr.yy.Column;s.columnid=n.as,s.columnid_orig=n.as_orig,t.expression=s}else{t.initial_select_column=Object.assign(new nr.yy.Column,t.expression),t.initial_select_column.as=`[${t.expression.columnid_orig}]`,t.expression.columnid=t.initial_select_column.as;return}if(!t.is_aggregator){let s=t.is_func?new nr.yy.FuncValue:new nr.yy.Column;t.initial_select_column=Object.assign(s,n)}})}_addNonAggregatorsToFetchColumns(){let r=this.statement.order.filter(n=>!n.is_aggregator&&!n.is_ordinal).map(n=>n.is_func?{columnid:n.initial_select_column.args.filter(i=>!!i.columnid_orig)[0].columnid_orig}:{columnid:n.expression.columnid_orig});this._addFetchColumns(r)}async _processJoins(){let t=[],r=[],n=this.statement.from[0],s=[n],i=["? "+(n.as?" AS "+n.as:n.tableid)];t.push(Object.values(this.data[`${n.databaseid_orig}_${n.as?n.as_orig:n.tableid_orig}`].__merged_data)),this.statement.joins&&this.statement.joins.forEach(E=>{E.joinmode&&E.joinmode!=="INNER"&&(this.has_outer_join=!0),s.push(E.table);let h=E.joinmode+" JOIN ? AS "+(E.as?E.as:E.table.tableid);E.on&&(h+=" ON "+E.on.toString()),i.push(h),t.push(Object.values(this.data[`${E.table.databaseid_orig}_${E.table.as?E.table.as_orig:E.table.tableid_orig}`].__merged_data))});let o=[],c={};s.forEach(E=>{let h=this.data[`${E.databaseid_orig}_${E.as?E.as_orig:E.tableid_orig}`].__hash_name,p=E.as?E.as_orig:E.tableid_orig;o.push({key:`'${p}.${h}'`,schema:E.databaseid_orig,table:E.as?E.as_orig:E.tableid_orig,keys:new Set}),r.push(`${E.as?E.as:E.tableid}.\`${h}\` AS "${p}.${h}"`),c[E.as?E.as_orig:E.tableid_orig]=this.data[`${E.databaseid_orig}_${E.as?E.as_orig:E.tableid_orig}`].__merged_attributes});let u=this.statement.where?"WHERE "+this.statement.where:"";u=u.replace(/NOT\(NULL\)/g,"NOT NULL");let _="";this.statement.order&&!this.has_ordinal&&!this.has_aggregator&&!this.statement.group&&this.statement.limit&&(_="ORDER BY "+this.statement.order.toString(),this.statement.order.forEach(E=>{E.is_func?r.push(E.initial_select_column.toString()):E.initial_select_column.tableid?r.push(`${E.initial_select_column.tableid}.${E.initial_select_column.columnid} AS ${E.expression.columnid}`):r.push(`${E.initial_select_column.columnid} AS ${E.expression.columnid}`)}));let l="",d="";!this.has_aggregator&&!this.statement.group&&!this.has_ordinal&&!this.statement.joins&&(l=this.statement.limit?"LIMIT "+this.statement.limit:"",d=this.statement.offset?"OFFSET "+this.statement.offset:"");let f=[];try{let E=`SELECT ${r.join(", ")} FROM ${i.join(" ")} ${u} ${_} ${l} ${d}`,h=this._convertColumnsToIndexes(E,s);f=await nr.promise(h,t),t=null}catch(E){throw Ee.error("Error thrown from AlaSQL in SQLSearch class method processJoins."),Ee.error(E),new Error("There was a problem processing the data.")}if(f&&f.length>0){for(let E=0,h=f.length;E<h;E++){let p=f[E];o.forEach(S=>{p[S.key]!==null&&p[S.key]!==void 0&&S.keys.add(p[S.key])})}o.forEach(E=>{let h=Object.keys(this.data[`${E.schema}_${E.table}`].__merged_data),p=jc.difference(h,[...E.keys].map(S=>S.toString()));for(let S=0,O=p.length;S<O;S++){let g=p[S];delete this.data[`${E.schema}_${E.table}`].__merged_data[g]}})}return{existing_attributes:c,joined_length:f?f.length:0}}async _getFinalAttributeData(t,r){if(r===0)return;let n=[],s=new Q_(this.columns);for(let{node:i}of s)if(i&&i.columnid){let o=this._findColumn(i);if(o){let c=o.table.as?o.table.as:o.table.tableid;(!t[c]||t[c].indexOf(o.attribute)<0)&&n.push(o)}}n=jc.uniqBy(n,i=>[i.table.databaseid,i.table.as?i.table.as:i.table.tableid,i.attribute].join());try{await this._getData(n)}catch(i){throw Ee.error("Error thrown from getData in SQLSearch class method getFinalAttributeData."),Ee.error(i),new Error(Dn)}}async _getData(t){try{let r=t.reduce((n,s)=>{let i=`${s.table.databaseid}_${s.table.as?s.table.as:s.table.tableid}`;return n[i]?n[i].columns.push(s.attribute):n[i]={schema:s.table.databaseid,table:s.table.tableid,columns:[s.attribute]},n},{});for(let n in r){let s=r[n],i=this.data[n].__merged_data,o=[];for(let l in i)o.push(i[l][0]);this.data[n].__merged_attributes.push(...s.columns);let c={schema:s.schema,table:s.table,hash_values:o,get_attributes:s.columns},u=await ea.getDataByHash(c),_=s.columns.length;for(let l=0,d=o.length;l<d;l++){let f=o[l],E=u.get(f);for(let h=0;h<_;h++){let p=s.columns[h],S=E[p]===void 0?null:E[p];this.data[n].__merged_data[f].push(S)}}}}catch(r){throw Ee.error("Error thrown from getDataByHash function in SQLSearch class method getData."),Ee.error(r),r}}async _finalSQL(){let t=[],r=this.statement.from[0];t.push(Object.values(this.data[`${r.databaseid_orig}_${r.as?r.as_orig:r.tableid_orig}`].__merged_data)),r.as=r.as?r.as:r.tableid,r.databaseid="",r.tableid="?",this.statement.joins&&this.statement.joins.forEach(s=>{s.as=s.as?s.as:s.table.tableid,t.push(Object.values(this.data[`${s.table.databaseid_orig}_${s.table.as?s.table.as_orig:s.table.tableid_orig}`].__merged_data)),s.table.databaseid="",s.table.tableid="?"}),this.statement.order&&this.statement.order.forEach(s=>{if(s.is_ordinal)return;this.statement.columns.filter(o=>{let c=o.aggregatorid?o.expression:o,u=o.aggregatorid?o.as_orig:c.as_orig;return s.expression.tableid?c.columnid_orig===s.expression.columnid_orig&&c.tableid_orig===s.expression.tableid_orig:c.columnid_orig===s.expression.columnid_orig||s.expression.columnid_orig===u}).length===0&&(s.expression.columnid=s.initial_select_column.columnid)}),!this.has_aggregator&&!this.statement.group&&!this.has_ordinal&&this.statement.limit&&!this.statement.joins&&(delete this.statement.limit,delete this.statement.offset);let n;try{let s=this._buildSQL();Ee.trace(`Final SQL: ${s}`),n=await nr.promise(s,t),this.has_outer_join&&(n=this._translateUndefinedValues(n)),Ee.trace(`Final AlaSQL results data included ${n.length} rows`)}catch(s){throw Ee.error("Error thrown from AlaSQL in SQLSearch class method finalSQL."),Ee.error(s),new Error("There was a problem running the generated sql.")}return n}_translateUndefinedValues(t){try{let r=[];for(let n of t){let s=Object.create(null);Object.keys(n).forEach(i=>{n[i]===void 0?s[i]=null:s[i]=n[i]}),r.push(s)}return r}catch(r){return Ee.error(w2.HDB_ERROR_MSGS.OUTER_JOIN_TRANSLATION_ERROR),Ee.trace(r.stack),t}}_buildSQL(t=!0){let r=this.statement.toString();return r=r.replace(/NOT\(NULL\)/g,"NOT NULL"),this.statement.columns.forEach(n=>{if(n.funcid&&n.as){let s=n.toString().replace(" AS "+n.as,"");r=r.replace(n.toString(),s)}}),t===!0?this._convertColumnsToIndexes(r,this.tables):r}_convertColumnsToIndexes(t,r){let n=t,s={};r.forEach(i=>{i.databaseid_orig?s[`${i.databaseid_orig}_${i.as?i.as_orig:i.tableid_orig}`]=i.as?i.as:i.tableid:s[`${i.databaseid}_${i.as?i.as:i.tableid}`]=`\`${i.as?i.as:i.tableid}\``});for(let i in this.data)this.data[i].__merged_attributes.forEach((o,c)=>{let u=s[i],_=new RegExp(`${u}.\`${o}\``,"g"),l=`${u}.[${c}]`;n=n.replace(_,l)});for(let i in this.data)this.data[i].__merged_attributes.forEach((o,c)=>{let u=new RegExp(`\`${o}\``,"g"),_=`[${c}]`;n=n.replace(u,_)});return n}async _simpleSQLQuery(){let t=this.statement.columns.reduce((n,s)=>(s.as_orig&&s.as_orig!=s.columnid_orig?n[s.columnid_orig]=s.as_orig:n[s.columnid_orig]||(n[s.columnid_orig]=s.columnid_orig),n),{}),r=this.fetch_attributes.reduce((n,s)=>{let i=`${s.table.databaseid}_${s.table.as?s.table.as:s.table.tableid}`;return n[i]||(n[i]={}),n[i][t[s.attribute]]=null,n},{});for(let n of this.fetch_attributes){let s=`${n.table.databaseid}_${n.table.as?n.table.as:n.table.tableid}`,i={schema:n.table.databaseid,table:n.table.tableid,get_attributes:[n.attribute]};try{i.search_attribute=n.attribute,i.search_value="*";let o=await ea.getDataByValue(i);for(let[c,u]of o)this.data[s].__merged_data[c]||(u[n.attribute]===void 0&&(u[n.attribute]=null),this.data[s].__merged_data[c]=Object.assign({},r[s])),this.data[s].__merged_data[c][t[n.attribute]]=u[n.attribute]??null}catch(o){throw Ee.error("There was an error when processing this SQL operation. Check your logs"),Ee.error(o),new Error(Dn)}}return Object.values(Object.values(this.data)[0].__merged_data)}};bC.exports=Vp});var Zr=T((jle,NC)=>{"use strict";var C2=Nb();NC.exports={searchByConditions:L2,searchByHash:M2,searchByValue:U2,search:P2};var $p=yn(),{transformReq:Yp}=J(),D2=yC();async function L2(e){return Yp(e),$p.searchByConditions(e)}a(L2,"searchByConditions");async function M2(e){Yp(e),e.ids&&(e.hash_values=e.ids);let t=[];for await(let r of $p.searchByHash(e))r&&t.push(r);return t}a(M2,"searchByHash");async function U2(e){Yp(e),e.hasOwnProperty("desc")===!0&&(e.reverse=e.desc);let t=[];for await(let r of $p.searchByValue(e))t.push(r);return t}a(U2,"searchByValue");function P2(e,t){try{let r=new C2(e);r.validate(),new D2(r.statement,r.attributes).search().then(s=>{t(null,s)}).catch(s=>{t(s,null)})}catch(r){return t(r)}}a(P2,"search")});var z_=T((Zle,wC)=>{"use strict";var v2=yn();wC.exports={writeTransaction:B2};function B2(e,t,r){return v2.writeTransaction(e,t,r)}a(B2,"writeTransaction")});var LC=T((r_e,DC)=>{"use strict";var H2=Zr(),x2=Ss(),IC=K(),q2=en(),t_e=z_(),F2=require("clone"),Wp=require("alasql"),G2=W_(),CC=require("util"),k2=CC.promisify(x2.getTableSchema),V2=CC.promisify(H2.search),$2=U(),Kp=J();G2(Wp);DC.exports={update:K2};var Y2="There was a problem performing this update. Please check the logs and try again.";async function K2({statement:e,hdb_user:t}){let r=await k2(e.table.databaseid,e.table.tableid),n=W2(e.columns);Kp.backtickASTSchemaItems(e);let{table:s,where:i}=e,o=F2(s),c=Kp.isEmpty(i)?"":` WHERE ${i.toString()}`,u=`SELECT ${r.hash_attribute} FROM ${s.toString()} ${c}`,_=Wp.parse(u).statements[0],l=await V2(_),d=Q2(n,l);return z2(o,d,t)}a(K2,"update");function W2(e){try{let t={};return e.forEach(r=>{"value"in r.expression?t[r.column.columnid]=r.expression.value??null:t[r.column.columnid]=Wp.compile(`SELECT ${r.expression.toString()} AS [${$2.FUNC_VAL}] FROM ?`)}),t}catch(t){throw IC.error(t),new Error(Y2)}}a(W2,"createUpdateRecord");function Q2(e,t){return Kp.isEmptyOrZeroLength(t)?[]:t.map(r=>Object.assign(r,e))}a(Q2,"buildUpdateRecords");async function z2(e,t,r){let n={operation:"update",schema:e.databaseid_orig,table:e.tableid_orig,records:t,hdb_user:r},s=await q2.update(n);try{delete s.new_attributes,delete s.txn_time}catch(i){IC.error(`Error delete new_attributes from update response: ${i}`)}return s}a(z2,"updateRecords")});var UC=T((o_e,MC)=>{var J2=require("alasql"),j2=Zr(),X2=K(),Z2=yn(),zp=require("util"),Qp=J(),e4=U(),t4=Ss(),s_e=z_(),i_e=en(),r4="record",n4="successfully deleted",s4=zp.callbackify(c4),i4=zp.promisify(j2.search),o4=zp.promisify(t4.getTableSchema);MC.exports={convertDelete:s4};function a4(e){return`${e.deleted_hashes.length} ${r4}${e.deleted_hashes.length===1?"":"s"} ${n4}`}a(a4,"generateReturnMessage");async function c4({statement:e,hdb_user:t}){let r=await o4(e.table.databaseid,e.table.tableid);Qp.backtickASTSchemaItems(e);let{table:n,where:s}=e,i=Qp.isEmpty(s)?"":` WHERE ${s.toString()}`,o=`SELECT ${r.hash_attribute} FROM ${n.toString()} ${i}`,c=J2.parse(o).statements[0],u={operation:e4.OPERATIONS_ENUM.DELETE,schema:n.databaseid_orig,table:n.tableid_orig,hdb_user:t};try{u.records=await i4(c);let _=await Z2.deleteRecords(u);return Qp.isEmptyOrZeroLength(_.message)&&(_.message=a4(_)),delete _.txn_time,_}catch(_){throw X2.error(_),_.hdb_code?_.message:_}}a(c4,"convertDelete")});var xC=T((c_e,HC)=>{"use strict";var u4=Hi(),{hdb_errors:PC}=ee(),{getDatabases:vC}=(be(),te(qe));HC.exports={checkSchemaExists:BC,checkSchemaTableExists:l4,schema_describe:u4};async function BC(e){if(!vC()[e])return PC.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}a(BC,"checkSchemaExists");async function l4(e,t){let r=await BC(e);if(r)return r;if(!vC()[e][t])return PC.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(l4,"checkSchemaTableExists")});var Xc=T((l_e,_4)=>{_4.exports={name:"harperdb",version:"4.3.0-beta.4",description:"HarperDB is a distributed SQL & NoSQL data platform focused on speed, flexibility, and ease of use.",keywords:["database","sql","nosql","api","distributed","cloud","enterprise","Fastify","NATS"],main:"harperdb.js",bin:{harperdb:"./bin/harperdb.js"},engines:{"minimum-node":"16.0.0","go-lang":"1.21.1","nats-server":"2.10.1"},exports:{".":"./index.js"},homepage:"https://www.harperdb.io/",bugs:"support@harperdb.io",author:{name:"HarperDB",email:"support@harperdb.io"},license:"SEE LICENSE IN LICENSE",scripts:{submodules:"git submodule update --init --recursive",build:"eslint -c ./.eslintbuild bin/ dataLayer/ security/ server/ sqlTranslator/ upgrade/ utility/ validation/",pretty:"eslint --fix bin/ dataLayer/ security/ server/ sqlTranslator/ upgrade/ utility/ validation/","cover:test":"pm2 kill && rimraf ./.nyc_output/* && node utility/devops/register.js --reset_license && nyc --no-clean --reporter=lcovonly npm run test:apitests && nyc --no-clean --reporter=lcovonly npm run test:resources && nyc --no-clean --reporter=lcovonly npm run test:logging && nyc --no-clean --reporter=lcovonly npm run test:upgrade && nyc --no-clean --reporter=lcovonly npm run test:nats && nyc --no-clean --reporter=lcovonly npm run test:cfserver && nyc --no-clean --reporter=lcovonly npm run test:hdbserver && nyc --no-clean --reporter=lcovonly npm run test:bin && nyc --no-clean --reporter=lcovonly npm run test:main && nyc merge .nyc_output coverage.json && node ./utility/devops/register.js --reset_license",test:"pm2 kill && rimraf ./.nyc_output/* && node utility/devops/register.js --reset_license && npm run test:apitests && npm run test:resources && npm run test:logging && npm run test:upgrade && npm run test:nats && npm run test:cfserver && npm run test:hdbserver && npm run test:bin && npm run test:main && nyc merge .nyc_output coverage.json && node ./utility/devops/register.js --reset_license","test:resources":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/resources/**/*.js' --config '../unitTests/.mocharc.json'","test:bin":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/bin/**/*.js' --config '../unitTests/.mocharc.json'","test:main":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/**/*.js' --config '../unitTests/.mocharc-main.json'","test:lmdbbridge":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/dataLayer/harperBridge/lmdbBridge/**/*.js' --config '../unitTests/.mocharc.json'","test:lmdbutility":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/utility/lmdb/**/*.js' --config '../unitTests/.mocharc.json'","test:hdbserver":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/server/harperdb/hdbServer-test.js' --config '../unitTests/.mocharc.json'","test:cfserver":"npm run submodules && cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/server/fastifyRoutes/customFunctionsServer-test.js' --config '../unitTests/.mocharc.json'","test:nats":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/server/nats/**/*.js' --config '../unitTests/.mocharc.json'","test:upgrade":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/upgrade/**/*.js' --config '../unitTests/.mocharc.json'","test:apitests":"pm2 kill && cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/apiTests/**/*-test.mjs' --config '../unitTests/.mocharc.json'","test:logging":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/utility/logging/*.js' --config '../unitTests/.mocharc.json'","test:ci":" cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/**/*.js' --retries 3 --config '../unitTests/.mocharc-main.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/dataLayer/harperBridge/lmdbBridge/**/*.js' --parallel --retries 3 --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/utility/lmdb/**/*.js' --parallel --retries 3 --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/server/harperdb/hdbServer-test.js' --parallel --retries 3 --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/server/customFunctions/customFunctionsServer-test.js' --parallel --retries 3 --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/upgrade/**/*.js' --parallel --retries 3 --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/server/nats/**/*.js' --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter","hdb-check":"./utility/devops/hdb-check.sh","download-prebuilds":"node ./utility/devops/build/download-prebuilds.js",prebuild:"date",postinstall:"node ./launchServiceScripts/launchInstallNATSServer.js",build_nats_dependency:"node ./utility/devops/nats/builder.js",coverage:"nyc --reporter=lcov npm test"},dependencies:{"@aws-sdk/abort-controller":"3.374.0","@aws-sdk/client-s3":"3.477.0","@aws-sdk/lib-storage":"3.477.0","@endo/static-module-record":"^1.0.0","@fastify/autoload":"5.7.1","@fastify/compress":"~6.5.0","@fastify/cors":"~8.5.0","@fastify/static":"~6.11.2","@turf/area":"6.5.0","@turf/boolean-contains":"6.5.0","@turf/boolean-disjoint":"6.5.0","@turf/boolean-equal":"6.5.0","@turf/circle":"6.5.0","@turf/difference":"6.5.0","@turf/distance":"6.5.0","@turf/helpers":"6.5.0","@turf/length":"6.5.0",alasql:"4.1.10","cbor-x":"1.5.4",chalk:"4.1.2","cli-progress":"3.12.0",clone:"2.1.2","fast-glob":"3.3.1",fastify:"~4.25.1","fastify-plugin":"~4.5.1","fs-extra":"11.2.0",graphql:"^16.8.1","human-readable-ids":"1.0.4",inquirer:"8.2.6","is-number":"7.0.0",joi:"17.11.0","json-bigint-fixes":"1.1.0",json2csv:"5.0.7",jsonata:"1.8.6",jsonwebtoken:"9.0.2",lmdb:"2.10.0-beta.1",lodash:"4.17.21",mathjs:"11.11.2",minimist:"1.2.8",mkcert:"1.5.1",moment:"2.29.4","mqtt-packet":"~8.2.1",msgpackr:"1.10.1",nats:"2.17.0",needle:"3.2.0","node-stream-zip":"1.15.0","node-unix-socket":"0.2.5","normalize-path":"^3.0.0",ora:"5.4.1","ordered-binary":"1.5.1",papaparse:"5.4.1",passport:"0.6.0","passport-http":"0.3.0","passport-local":"1.0.0",pino:"8.16.0",pm2:"5.3.1",prompt:"1.3.0","properties-reader":"2.3.0","recursive-iterator":"3.3.0",semver:"7.5.4",send:"^0.18.0","serve-static":"1.15.0",ses:"1.0.0","stream-chain":"2.2.5","stream-json":"1.8.0",systeminformation:"5.21.20","tar-fs":"2.1.1",ulidx:"0.5.0",uuid:"9.0.1","validate.js":"0.13.1",ws:"8.15.1",yaml:"2.3.4"},devDependencies:{"@tsconfig/node16":"^1.0.3","@types/node":"latest","@typescript-eslint/eslint-plugin":"^5.55.0","@typescript-eslint/parser":"^5.55.0",axios:"1.6.2",chai:"4.3.7","chai-integer":"0.1.0",esbuild:"^0.19.1",eslint:"8.22.0","eslint-config-prettier":"8.3.0","eslint-plugin-prettier":"3.4.1","eslint-plugin-radar":"0.2.1",eventsource:"^2.0.2","hook-std":"3.0.0","intercept-stdout":"0.1.2",mocha:"^10.2.0","mocha-teamcity-reporter":"3.0.0","mock-require":"3.0.3","mock-stdin":"1.0.0",mqtt:"~4.3.7",newman:"5.3.2","newman-reporter-html":"1.0.5","newman-reporter-htmlextra":"^1.22.11","newman-reporter-teamcity":"^0.1.12","node-fetch":"2.6.7",nyc:"15.1.0",prettier:"2.8.4",rewire:"5.0.0",rimraf:"3.0.2",sinon:"10.0.0","sinon-chai":"3.7.0","source-map-support":"^0.5.21",typescript:"^5.3.3","why-is-node-still-running":"^1.0.0"},overrides:{"eslint-plugin-radar":{eslint:"8.22.0"},"newman-reporter-html":{newman:"5.3.2"},alasql:{xlsx:"0.18.5"}},optionalDependencies:{bufferutil:"^4.0.7","utf-8-validate":"^5.0.10"}}});var ru={};ke(ru,{addAnalyticsListener:()=>tu,recordAction:()=>Hr,recordActionBinary:()=>tn,setAnalyticsEnabled:()=>d4});function d4(e){QC=e}function Hr(e,t,r,n,s){if(!QC)return;let i=t+(r?"-"+r:"");n!==void 0&&(i+="-"+n),s!==void 0&&(i+="-"+s);let o=X_.get(i);if(o)if(typeof e=="number"){let c=o.values,u=c.index++;if(u>=c.length){let _=c;o.values=c=new Float32Array(u*2),c.set(_),c.index=u+1}c[u]=e,o.total+=e}else if(typeof e=="boolean")e&&o.total++,o.count++;else if(typeof e=="function")o.count++;else throw new TypeError("Invalid metric value type "+typeof e);else{if(typeof e=="number")o={total:e,values:new Float32Array(4)},o.values.index=1,o.values[0]=e,o.total=e;else if(typeof e=="boolean")o={},o.total=e?1:0,o.count=1;else if(typeof e=="function")o={},o.count=1,o.callback=e;else throw new TypeError("Invalid metric value type "+typeof e);o.description={metric:t,path:r,method:n,type:s},X_.set(i,o)}J_||f4()}function tn(e,t,r,n,s){Hr(!!e,t,r,n,s)}function tu(e){jC.push(e)}function f4(){J_=performance.now(),setTimeout(async()=>{let e=performance.now()-J_;J_=0;let t=[],r={time:Date.now(),period:e,threadId:ji.threadId,metrics:t};for(let[s,i]of X_){if(i.values){let o=i.values.subarray(0,i.values.index);o.sort();let c=o.length,u=0,_=[],l;for(let d of XC){let f=Math.floor(c*d),E=o[f-1];if(f>u){let h=f-u;if(E===l){let p=_[_.length-1];typeof p=="number"?_[_.length-1]={value:p,count:1+h}:p.count+=h}else _.push(h>1?{value:E,count:h}:E),l=E;u=f}}t.push(Object.assign(i.description,{mean:i.total/c,distribution:_,count:c}))}else i.callback?t.push(Object.assign(i.description,i.callback(i))):t.push(Object.assign(i.description,{total:i.total,count:i.count}));await ZC()}let n=process.memoryUsage();t.push({metric:"memory",threadId:ji.threadId,byThread:!0,...n});for(let s of jC)s(t);X_=new Map,ji.parentPort?ji.parentPort.postMessage({type:JC,report:r}):rD({report:r})},zC).unref()}async function E4(e,t=6e4){let r=Xp(),n=eD(),s;for(let h of n.primaryStore.getRange({start:1/0,end:!1,reverse:!0}))if(h.value?.time){s=h.value.time;break}if(Date.now()-t<s)return;let i,o=new Map,c=new Map,u=[],_;for(let{key:h,value:p}of r.primaryStore.getRange({start:s||!1,exclusiveStart:!0,end:1/0})){if(!p)continue;if(i){if(h>i+t)break}else i=h;_=h;let{metrics:S,threadId:O}=p;for(let g of S||[]){let{path:R,method:B,type:H,metric:v,count:M,total:$,distribution:W,threads:z,...se}=g;M||(M=1);let Te=v+(R?"-"+R:"");B!==void 0&&(Te+="-"+B),H!==void 0&&(Te+="-"+H);let oe=o.get(Te);if(oe){if(oe.threads){let de=oe.threads[O];if(de)oe=de;else{oe.threads[O]=Object.assign({},se);continue}}oe.count||(oe.count=1);let xe=oe.count;for(let de in se){let It=se[de];typeof It=="number"&&(oe[de]=(oe[de]*xe+It*M)/(xe+M))}oe.count+=M,$>=0&&(oe.total+=$,oe.ratio=oe.total/oe.count)}else oe=Object.assign({period:t},g),delete oe.distribution,o.set(Te,oe),oe.byThread&&(oe.threads=[],oe.threads[O]=Object.assign({},se),u.push(oe));if(W){W=W.map(de=>typeof de=="number"?{value:de,count:1}:de);let xe=c.get(Te);xe?xe.push(...W):c.set(Te,W)}}await ZC()}for(let h of u){let{path:p,method:S,type:O,metric:g,count:R,total:B,distribution:H,threads:v,...M}=h;v=v.filter($=>$);for(let $ in M){if(typeof h[$]!="number")continue;let W=0;for(let z of v){let se=z[$];typeof se=="number"&&(W+=se)}h[$]=W}h.count=v.length,delete h.threads,delete h.byThread}for(let[h,p]of c){let S=o.get(h);p.sort((de,It)=>de.value>It.value?1:-1);let O=S.count-1,g=[],R=0,B=0,H;for(let de of XC){let It=O*de;for(;R<It;)H=p[B++],R+=H.count,B===1&&R--;let Nl=p[B>1?B-2:0];H||(H=p[0]),g.push(H.value-(H.value-Nl.value)*(R-It)/H.count)}let[v,M,$,W,z,se,Te,oe,xe]=g;Object.assign(S,{p1:v,p10:M,p25:$,median:W,p75:z,p90:se,p95:Te,p99:oe,p999:xe})}let l;for(let[h,p]of o)p.id=(0,j_.getNextMonotonicTime)(),p.time=_,n.primaryStore.put(p.id,p,{append:!0}).then(S=>{S||n.primaryStore.put(p.id,p)}),l=!0;let d=Date.now(),{idle:f,active:E}=performance.eventLoopUtilization();if(l||E*10>f){let h=(0,j_.getNextMonotonicTime)(),p={id:h,metric:"main-thread-utilization",idle:f-qC,active:E-FC,time:d,...process.memoryUsage()};n.primaryStore.put(h,p,{append:!0}).then(S=>{S||n.primaryStore.put(h,p)})}qC=f,FC=E}async function GC(e,t){let r=Date.now()-t;for(let n of e.primaryStore.getKeys({start:!1,end:r}))e.primaryStore.remove(n)}function Xp(){return kC||(kC=ot({table:"hdb_raw_analytics",database:"system",audit:!1,trackDeletes:!1,attributes:[{name:"id",isPrimaryKey:!0},{name:"action"},{name:"metrics"}]}))}function eD(){return VC||(VC=ot({table:"hdb_analytics",database:"system",audit:!1,trackDeletes:!1,attributes:[{name:"id",isPrimaryKey:!0},{name:"metric"},{name:"path"},{name:"method"},{name:"type"}]}))}function p4(){tD=!0;let e=(0,eu.get)(jp.CONFIG_PARAMS.ANALYTICS_AGGREGATEPERIOD)*1e3;e&&setInterval(async()=>{await E4(zC,e),await GC(Xp(),h4),await GC(eD(),m4)},Math.min(e/2,2147483647)).unref()}function rD(e,t){let r=e.report;r.threadId=t?.threadId||ji.threadId;for(let n of r.metrics)n.metric==="bytes-sent"&&($C+=n.mean*n.count);r.totalBytesProcessed=$C,t&&(r.metrics.push({metric:"utilization",...t.performance.eventLoopUtilization(YC.get(t))}),YC.set(t,t.performance.eventLoopUtilization())),r.id=(0,j_.getNextMonotonicTime)(),Xp().primaryStore.put(r.id,r),tD||p4(),S4&&(nD=g4(r))}async function g4(e){if(await nD,!ri){let r=(0,Zc.dirname)((0,WC.getLogFilePath)());try{ri=await(0,Jp.open)((0,Zc.join)(r,"analytics.log"),"r+")}catch{ri=await(0,Jp.open)((0,Zc.join)(r,"analytics.log"),"w+")}}let t=(await ri.stat()).size;if(t>T4){let r=Buffer.alloc(t);await ri.read(r,{position:0}),r=r.subarray(r.indexOf(10,r.length/2)+1),await ri.write(r,{position:0}),await ri.truncate(r.length),t=r.length}await ri.write(JSON.stringify(e)+`
|
|
8
|
+
`,t)}var ji,KC,WC,Zc,Jp,j_,eu,jp,X_,QC,J_,zC,JC,jC,XC,qC,FC,ZC,h4,m4,kC,VC,tD,$C,YC,S4,nD,ri,T4,Os=Oe(()=>{ji=require("worker_threads"),KC=x(Ze());be();WC=x(K()),Zc=require("path"),Jp=require("fs/promises"),j_=x(Cr()),eu=x(Z()),jp=x(U());Xt();(0,eu.initSync)();X_=new Map,QC=(0,eu.get)(jp.CONFIG_PARAMS.ANALYTICS_AGGREGATEPERIOD)>-1;a(d4,"setAnalyticsEnabled");a(Hr,"recordAction");Xe.recordAnalytics=Hr;a(tn,"recordActionBinary");J_=0,zC=1e3,JC="analytics-report",jC=[];a(tu,"addAnalyticsListener");XC=[.01,.1,.25,.5,.75,.9,.95,.99,.999,1];a(f4,"sendAnalytics");a(E4,"aggregation");qC=0,FC=0,ZC=a(()=>new Promise(setImmediate),"rest");a(GC,"cleanup");h4=36e5,m4=31536e6;a(Xp,"getRawAnalyticsTable");a(eD,"getAnalyticsTable");(0,KC.setChildListenerByType)(JC,rD);a(p4,"startScheduledTasks");$C=0,YC=new Map,S4=!1;a(rD,"recordAnalytics");T4=1e6;a(g4,"logAnalytics")});var ft=T((b_e,OD)=>{"use strict";var Ht=Z();Ht.initSync();var R4=require("fs-extra"),A4=require("semver"),iu=require("path"),{monotonicFactory:O4}=require("ulidx"),iD=O4(),b4=require("util"),oD=require("child_process"),y4=b4.promisify(oD.exec),N4=oD.spawn,Ne=tt(),Pe=U(),rS=J(),xr=K(),Z_=ps(),w4=z_(),nu=Ir(),{onMessageByType:I4}=Ze(),{isMainThread:C4}=require("worker_threads"),{Encoder:D4,decode:nS}=require("msgpackr"),aD=new D4,{isEmpty:to}=rS,cD=Ur(),L4=48*36e11,M4=5e9;C4&&I4(Pe.ITC_EVENT_TYPES.RESTART,()=>{rn=void 0,eo=void 0});var{connect:U4,StorageType:uD,RetentionPolicy:lD,AckPolicy:ed,DeliverPolicy:td,DiscardPolicy:P4,NatsConnection:g_e,JetStreamManager:R_e,JetStreamClient:A_e,StringCodec:O_e,JSONCodec:v4,createInbox:sS,headers:B4,ErrorCode:sD}=require("nats"),{PACKAGE_ROOT:H4}=U(),x4=Xc(),{recordAction:q4}=(Os(),te(ru)),_D=v4(),F4="clustering",G4=x4.engines[Ne.NATS_SERVER_NAME],k4=iu.join(H4,"dependencies"),tS=iu.join(k4,`${process.platform}-${process.arch}`,Ne.NATS_BINARY_NAME),Zp,eS,su,Xi,Zi;OD.exports={runCommand:dD,checkNATSServerInstalled:V4,createConnection:iS,getConnection:rd,getJetStreamManager:ou,getJetStream:ED,getNATSReferences:sr,getServerList:Y4,createLocalStream:oS,listStreams:hD,deleteLocalStream:K4,getServerConfig:au,listRemoteStreams:W4,viewStream:Q4,viewStreamIterator:z4,publishToStream:J4,createWorkQueueStream:j4,addSourceToWorkStream:pD,request:Z4,removeSourceFromWorkStream:TD,reloadNATS:aS,reloadNATSHub:e3,reloadNATSLeaf:t3,extractServerName:SD,requestErrorHandler:r3,updateWorkStream:n3,createLocalTableStream:RD,createTableStreams:s3,purgeTableStream:AD,purgeSchemaTableStreams:i3,getStreamInfo:o3,updateLocalStreams:c3,closeConnection:$4,getJsmServerName:cu,addNatsMsgHeader:mD,updateIngestStreamConsumer:X4,clearClientCache:fD};async function dD(e,t=void 0){let{stdout:r,stderr:n}=await y4(e,{cwd:t});if(n)throw new Error(n.replace(`
|
|
9
9
|
`,""));return r.replace(`
|
|
10
|
-
`,"")}a(uD,"runCommand");async function F4(){try{await S4.access(tS)}catch{return!1}let e=await uD(`${tS} --version`,void 0),t=e.substring(e.lastIndexOf("v")+1,e.length);return T4.eq(t,x4)}a(F4,"checkNATSServerInstalled");async function iS(e,t,r,n=!0,s="127.0.0.1"){if(!t&&!r){let o=await iD.getClusterUser();if(Zi(o))throw new Error("Unable to get nats connection. Cluster user is undefined.");t=o.username,r=o.decrypt_hash}Hr.trace("create nats connection called");let i=await D4({name:s,port:e,user:t,pass:r,maxReconnectAttempts:-1,waitOnFirstConnect:n,timeout:2e5,tls:{keyFile:xt.get(Pe.CONFIG_PARAMS.CLUSTERING_TLS_PRIVATEKEY),certFile:xt.get(Pe.CONFIG_PARAMS.CLUSTERING_TLS_CERTIFICATE),caFile:xt.get(Pe.CONFIG_PARAMS.CLUSTERING_TLS_CERT_AUTH),rejectUnauthorized:!1}});return i.protocol.transport.socket.unref(),Hr.trace("create connection established a nats client connection with id",i?.info?.client_id),i.closed().then(o=>{o&&Hr.error("Error with Nats client connection, connection closed",o),lD()}),i}a(iS,"createConnection");function lD(){tn=void 0,Ji=void 0,ji=void 0,Xi=void 0}a(lD,"clearClientCache");async function G4(){tn&&(await tn.drain(),tn=void 0,Ji=void 0,ji=void 0,Xi=void 0)}a(G4,"closeConnection");var tn,Xi;async function rd(){return Xi||(Xi=iS(xt.get(Pe.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),void 0,void 0),tn=await Xi),tn||Xi}a(rd,"getConnection");async function nu(){if(Ji)return Ji;Zi(tn)&&await rd();let{domain:e}=su(Pe.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);if(Zi(e))throw new Error("Error getting JetStream domain. Unable to get JetStream manager.");return Ji=await tn.jetstreamManager({domain:e,timeout:6e4}),Ji}a(nu,"getJetStreamManager");async function _D(){if(ji)return ji;Zi(tn)&&await rd();let{domain:e}=su(Pe.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);if(Zi(e))throw new Error("Error getting JetStream domain. Unable to get JetStream manager.");return ji=tn.jetstream({domain:e,timeout:6e4}),ji}a(_D,"getJetStream");async function ir(){let e=tn||await rd(),t=Ji||await nu(),r=ji||await _D();return{connection:e,jsm:t,js:r}}a(ir,"getNATSReferences");async function k4(e){let t=xt.get(Pe.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),{sys_name:r,decrypt_hash:n}=await iD.getClusterUser(),s=await iS(t,r,n),i=sS(),o=s.subscribe(i),c=[],u,_=(async()=>{for await(let l of o){let d=cD.decode(l.data);d.response_time=Date.now()-u,c.push(d)}})();return u=Date.now(),await s.publish("$SYS.REQ.SERVER.PING.VARZ",void 0,{reply:i}),await s.publish("$SYS.REQ.SERVER.PING",void 0,{reply:i}),await s.flush(),await rS.async_set_timeout(e),await o.drain(),await s.close(),await _,c}a(k4,"getServerList");async function oS(e,t){let{jsm:r}=await ir(),n=xt.get(Pe.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE);n=n===null?0:n*1e9;let s=xt.get(Pe.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS);s=s===null?-1:s;let i=xt.get(Pe.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES);i=i===null?-1:i,await r.streams.add({name:e,storage:oD.File,retention:aD.Limits,subjects:t,discard:L4.Old,max_msgs:s,max_bytes:i,max_age:n})}a(oS,"createLocalStream");async function dD(){let{jsm:e}=await ir(),t=await e.streams.list().next(),r=[];return t.forEach(n=>{r.push(n)}),r}a(dD,"listStreams");async function V4(e){let{jsm:t}=await ir();await t.streams.delete(e)}a(V4,"deleteLocalStream");async function $4(e){let{connection:t}=await ir(),r=[],n=sS(),s=t.subscribe(n),i=(async()=>{for await(let o of s)r.push(cD.decode(o.data))})();return await t.publish(`$JS.${e}.API.STREAM.LIST`,void 0,{reply:n}),await t.flush(),await s.drain(),await i,r}a($4,"listRemoteStreams");async function Y4(e,t=void 0,r=void 0){let{jsm:n,js:s}=await ir(),i=rD(),o={durable_name:i,ack_policy:ed.Explicit};t&&(o.deliver_policy=td.StartTime,o.opt_start_time=new Date(t).toISOString()),await n.consumers.add(e,o);let c=await s.consumers.get(e,i),u=r?await c.fetch({max_messages:r,expires:2e3}):await c.consume();if(c._info.num_pending===0)return[];let _=[];for await(let l of u){let d=nS(l.data),f={nats_timestamp:l.info.timestampNanos,nats_sequence:l.info.streamSequence,entry:d};if(l.headers&&(f.origin=l.headers.get(ye.MSG_HEADERS.ORIGIN)),_.push(f),l.ack(),l.info.pending===0)break}return await c.delete(),_}a(Y4,"viewStream");async function*K4(e,t=void 0,r=void 0){let{jsm:n,js:s}=await ir(),i=rD(),o={durable_name:i,ack_policy:ed.Explicit};t&&(o.deliver_policy=td.StartTime,o.opt_start_time=new Date(t).toISOString()),await n.consumers.add(e,o);let c=await s.consumers.get(e,i),u=r?await c.fetch({max_messages:r,expires:2e3}):await c.consume();if(c._info.num_pending===0)return[];for await(let _ of u){let l=nS(_.data);l[0]||(l=[l]);for(let d of l){let f={nats_timestamp:_.info.timestampNanos,nats_sequence:_.info.streamSequence,entry:d};_.headers&&(f.origin=_.headers.get(ye.MSG_HEADERS.ORIGIN)),yield f}if(_.ack(),_.info.pending===0)break}await c.delete()}a(K4,"viewStreamIterator");async function W4(e,t,r,n){Hr.trace(`publishToStream called with subject: ${e}, stream: ${t}, entries:`,n.operation),r=fD(n,r);let{js:s}=await ir(),i=await iu(),o=`${e}.${i}`,c=n instanceof Uint8Array?n:sD.encode(n);try{Hr.trace(`publishToStream publishing to subject: ${o}`),B4(c.length,"bytes-sent",e,n.operation,"replication"),await s.publish(o,c,{headers:r})}catch(u){if(u.code&&u.code.toString()==="503")return pD(async()=>{try{await s.publish(o,c,{headers:r})}catch{if(u.code&&u.code.toString()==="503"){Hr.trace(`publishToStream creating stream: ${t}`);let l=o.split(".");l[2]="*",await oS(t,[o]),await s.publish(o,c,{headers:r})}else throw u}});throw u}}a(W4,"publishToStream");function fD(e,t){t===void 0&&(t=U4());let r=xt.get(Pe.CONFIG_PARAMS.CLUSTERING_NODENAME);return!t.has(ye.MSG_HEADERS.ORIGIN)&&r&&t.append(ye.MSG_HEADERS.ORIGIN,r),t}a(fD,"addNatsMsgHeader");function su(e){e=e.toLowerCase();let t=ru.join(xt.get(Pe.CONFIG_PARAMS.ROOTPATH),H4);if(e===Pe.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase())return Zi(eS)&&(eS={port:eu.getConfigFromFile(Pe.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),server_name:eu.getConfigFromFile(Pe.CONFIG_PARAMS.CLUSTERING_NODENAME)+ye.SERVER_SUFFIX.HUB,config_file:ye.NATS_CONFIG_FILES.HUB_SERVER,pid_file_path:ru.join(t,ye.PID_FILES.HUB),hdb_nats_path:t}),eS;if(e===Pe.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())return Zi(Zp)&&(Zp={port:eu.getConfigFromFile(Pe.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),server_name:eu.getConfigFromFile(Pe.CONFIG_PARAMS.CLUSTERING_NODENAME)+ye.SERVER_SUFFIX.LEAF,config_file:ye.NATS_CONFIG_FILES.LEAF_SERVER,domain:eu.getConfigFromFile(Pe.CONFIG_PARAMS.CLUSTERING_NODENAME)+ye.SERVER_SUFFIX.LEAF,pid_file_path:ru.join(t,ye.PID_FILES.LEAF),hdb_nats_path:t}),Zp;Hr.error(`Unable to get Nats server config. Unrecognized process: ${e}`)}a(su,"getServerConfig");async function Q4(e){let{jsm:t}=await ir(),r=await iu();try{await t.streams.add({name:e.stream_name,storage:oD.File,retention:aD.Limits,max_age:I4,max_bytes:C4,subjects:[`${ye.SUBJECT_PREFIXES.TXN}.${e.stream_name}.${r}`]})}catch(n){if(n.code!=="400")throw n}try{await t.consumers.info(e.stream_name,e.durable_name)}catch(n){if(n.code.toString()==="404")await t.consumers.add(e.stream_name,{ack_policy:ed.Explicit,durable_name:e.durable_name,deliver_policy:td.All,max_ack_pending:1e4});else throw n}}a(Q4,"createWorkQueueStream");async function z4(){let{jsm:e}=await ir();(await e.consumers.info(ye.WORK_QUEUE_CONSUMER_NAMES.stream_name,ye.WORK_QUEUE_CONSUMER_NAMES.durable_name)).config.deliver_subject&&(Hr.info("Removing old nats push consumer from ingest stream"),await e.consumers.delete(ye.WORK_QUEUE_CONSUMER_NAMES.stream_name,ye.WORK_QUEUE_CONSUMER_NAMES.durable_name),Hr.info("Adding pull consumer to ingest stream"),await e.consumers.add(ye.WORK_QUEUE_CONSUMER_NAMES.stream_name,{ack_policy:ed.Explicit,durable_name:ye.WORK_QUEUE_CONSUMER_NAMES.durable_name,deliver_policy:td.All,max_ack_pending:1e4}))}a(z4,"updateIngestStreamConsumer");async function ED(e,t,r){let{jsm:n}=await ir(),s=await n.streams.info(t),i=hD(n.prefix),o=r.start_time?r.start_time:new Date(Date.now()).toISOString(),{schema:c,table:u}=r,_=Z_.createNatsTableStreamName(c,u),l=i===e,d,f,E=!1;if(!Array.isArray(s.config.sources)||s.config.sources.length===0)s.config.sources=[];else for(let p=0,S=s.config.sources.length;p<S;p++)if(d=s.config.sources[p],f=p,l&&d.name===_||!l&&d.name===_&&d.external&&d.external.api===`$JS.${e}.API`){E=!0;break}if(E===!0){if(d.opt_start_time===o)return;let p=`txn.${c}.${u}.${e}`;await n.streams.purge(t,{filter:p}),s.config.sources.splice(f,1),await n.streams.update(t,s.config)}let h={name:_,opt_start_time:o,filter_subject:`${ye.SUBJECT_PREFIXES.TXN}.>`};l||(h.external={api:`$JS.${e}.API`,deliver:""}),s.config.sources.push(h),await n.streams.update(t,s.config)}a(ED,"addSourceToWorkStream");function hD(e){return e.split(".")[1]}a(hD,"extractServerName");async function mD(e,t,r){let{jsm:n}=await ir(),{schema:s,table:i}=r,o=`txn.${s}.${i}.${e}`;await n.streams.purge(t,{filter:o});let c=Z_.createNatsTableStreamName(s,i),u=await n.streams.info(t);if(!Array.isArray(u.config.sources)||u.config.sources.length===0)return;let _=u.config.sources.length,l;for(;_--;)if(l=u.config.sources[_],l.name===c&&l.external.api===`$JS.${e}.API`){u.config.sources.splice(_,1);break}await n.streams.update(t,u.config)}a(mD,"removeSourceFromWorkStream");async function J4(e,t,r=6e4,n=sS()){if(!rS.isObject(t))throw new Error("data param must be an object");let s=sD.encode(t),{connection:i}=await ir(),o={timeout:r};n&&(o.reply=n,o.noMux=!0);let c=await i.request(e,s,o);return nS(c.data)}a(J4,"request");function aS(e){return new Promise(async(t,r)=>{let n=O4(tS,["--signal",`reload=${e}`],{cwd:__dirname}),s,i;n.on("error",o=>{r(o)}),n.stdout.on("data",o=>{i+=o.toString()}),n.stderr.on("data",o=>{s+=o.toString()}),n.stderr.on("close",o=>{s&&r(s),t(i)})})}a(aS,"reloadNATS");async function j4(){let{pid_file_path:e}=su(Pe.PROCESS_DESCRIPTORS.CLUSTERING_HUB);await aS(e)}a(j4,"reloadNATSHub");async function X4(){let{pid_file_path:e}=su(Pe.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);await aS(e)}a(X4,"reloadNATSLeaf");function Z4(e,t,r){let n;switch(e.code){case tD.NoResponders:n=`Unable to ${t}, node '${r}' is not listening.`;break;case tD.Timeout:n=`Unable to ${t}, node '${r}' is listening but did not respond.`;break;default:n=e.message;break}return n}a(Z4,"requestErrorHandler");async function e3(e,t){let r=t+ye.SERVER_SUFFIX.LEAF;await pD(async()=>{e.subscribe===!0?await ED(r,ye.WORK_QUEUE_CONSUMER_NAMES.stream_name,e):await mD(r,ye.WORK_QUEUE_CONSUMER_NAMES.stream_name,e)})}a(e3,"updateWorkStream");function pD(e){return b4.writeTransaction(Pe.SYSTEM_SCHEMA_NAME,Pe.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,e)}a(pD,"exclusiveLock");async function SD(e,t){let r=Z_.createNatsTableStreamName(e,t),n=await iu(),s=s3(e,t,n);await oS(r,[s])}a(SD,"createLocalTableStream");async function t3(e){for(let t=0,r=e.length;t<r;t++){let n=e[t].schema,s=e[t].table;await SD(n,s)}}a(t3,"createTableStreams");async function TD(e,t,r=!1){if(xt.get(Pe.CONFIG_PARAMS.CLUSTERING_ENABLED))try{let n=Z_.createNatsTableStreamName(e,t),{jsm:s}=await ir();r?await s.streams.purge(ye.WORK_QUEUE_CONSUMER_NAMES.stream_name):await s.streams.purge(n)}catch(n){if(n.message==="stream not found")Hr.warn(n);else throw n}}a(TD,"purgeTableStream");async function r3(e,t){if(xt.get(Pe.CONFIG_PARAMS.CLUSTERING_ENABLED))for(let r=0,n=t.length;r<n;r++)await TD(e,t[r])}a(r3,"purgeSchemaTableStreams");async function n3(e){return(await nu()).streams.info(e)}a(n3,"getStreamInfo");function s3(e,t,r){return`${ye.SUBJECT_PREFIXES.TXN}.${e}${t?"."+t:""}.${r}`}a(s3,"createSubjectName");async function iu(){if(tu)return tu;if(tu=(await nu())?.nc?.info?.server_name,tu===void 0)throw new Error("Unable to get jetstream manager server name");return tu}a(iu,"getJsmServerName");async function i3(){let e=await nu(),t=await iu(),r=await dD();for(let n of r){let s=n.config,i=s.subjects[0];if(!i)continue;let o=o3(n),c=i.split(".");if(!(c[c.length-1]===t&&!o)){if(s.name===ye.SCHEMA_QUEUE_CONSUMER_NAMES.stream_name){let _=`${ye.SCHEMA_QUEUE_CONSUMER_NAMES.deliver_subject}.${t}`;Hr.trace(`Updating stream subject name from: ${i} to: ${_}`),s.subjects[0]=_}else if(s.name===ye.WORK_QUEUE_CONSUMER_NAMES.stream_name){let _=`${ye.WORK_QUEUE_CONSUMER_NAMES.stream_name}.${t}`;Hr.trace(`Updating stream subject name from: ${i} to: ${_}`),s.subjects[0]=_}else{let _=i.split(".");_[_.length-1]=t;let l=_.join(".");Hr.trace(`Updating stream subject name from: ${i} to: ${l}`),s.subjects[0]=l}await e.streams.update(s.name,s)}}}a(i3,"updateLocalStreams");function o3(e){let{config:t}=e,r=!1;if(t.name===ye.SCHEMA_QUEUE_CONSUMER_NAMES.stream_name||t.name===ye.WORK_QUEUE_CONSUMER_NAMES.stream_name)return r;let n=xt.get(Pe.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE);n=n===null?0:n*1e9;let s=xt.get(Pe.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES);s=s===null?-1:s;let i=xt.get(Pe.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS);return i=i===null?-1:i,n!==t.max_age&&(t.max_age=n,r=!0),s!==t.max_bytes&&(t.max_bytes=s,r=!0),i!==t.max_msgs&&(t.max_msgs=i,r=!0),r}a(o3,"updateStreamLimits")});var od=g((w_e,bD)=>{"use strict";var Zo=d_(),ea=vC(),a3=Y(),c3=require("uuid").v4,y_e=require("clone"),sd=ps(),ta=M(),u3=require("util"),ti=On(),{handleHDBError:or,hdb_errors:l3}=ee(),{HDB_ERROR_MSGS:nd,HTTP_STATUS_CODES:ar}=l3,{SchemaEventMsg:id}=bn(),RD=ft(),{getDatabases:_3}=(be(),te(qe)),{transformReq:ra}=J();bD.exports={createSchema:d3,createSchemaStructure:AD,createTable:f3,createTableStructure:OD,createAttribute:S3,dropSchema:E3,dropTable:h3,dropAttribute:m3,getBackup:T3};async function d3(e){let t=await AD(e);return sd.signalSchemaChange(new id(process.pid,e.operation,e.schema)),t}a(d3,"createSchema");async function AD(e){let t=Zo.schema_object(e);if(t)throw or(t,t.message,ar.BAD_REQUEST,void 0,void 0,!0);if(ra(e),!await ea.checkSchemaExists(e.schema))throw or(new Error,nd.SCHEMA_EXISTS_ERR(e.schema),ar.BAD_REQUEST,ta.LOG_LEVELS.ERROR,nd.SCHEMA_EXISTS_ERR(e.schema),!0);return await ti.createSchema(e),`database '${e.schema}' successfully created`}a(AD,"createSchemaStructure");async function f3(e){return ra(e),e.hash_attribute=e.primary_key??e.hash_attribute,await OD(e)}a(f3,"createTable");async function OD(e){let t=Zo.create_table_object(e);if(t)throw or(t,t.message,ar.BAD_REQUEST,void 0,void 0,!0);if(Zo.validateTableResidence(e.residence),!await ea.checkSchemaTableExists(e.schema,e.table))throw or(new Error,nd.TABLE_EXISTS_ERR(e.schema,e.table),ar.BAD_REQUEST,ta.LOG_LEVELS.ERROR,nd.TABLE_EXISTS_ERR(e.schema,e.table),!0);let n={name:e.table,schema:e.schema,id:c3(),hash_attribute:e.hash_attribute};try{if(e.residence)if(global.clustering_on)n.residence=e.residence,await ti.createTable(n,e);else throw or(new Error,"Clustering does not appear to be enabled. Cannot insert table with property 'residence'.",ar.BAD_REQUEST);else await ti.createTable(n,e);return`table '${e.schema}.${e.table}' successfully created.`}catch(s){throw s}}a(OD,"createTableStructure");async function E3(e){let t=!e.schema&&!e.database?new Error("database is required"):void 0,r=Zo.schema_object(e),n=t??r;if(n)throw or(n,n.message,ar.BAD_REQUEST,void 0,void 0,!0);ra(e);let s=await ea.checkSchemaExists(e.schema);if(s)throw or(new Error,s,ar.NOT_FOUND,ta.LOG_LEVELS.ERROR,s,!0);let i=await ea.schema_describe.describeSchema({schema:e.schema}),o=Object.keys(global.hdb_schema[e.schema]);return await ti.dropSchema(e),sd.signalSchemaChange(new id(process.pid,e.operation,e.schema)),await RD.purgeSchemaTableStreams(e.schema,o),`successfully deleted '${e.schema}'`}a(E3,"dropSchema");async function h3(e){let t=Zo.table_object(e);if(t)throw or(t,t.message,ar.BAD_REQUEST,void 0,void 0,!0);ra(e);let r=await ea.checkSchemaTableExists(e.schema,e.table);if(r)throw or(new Error,r,ar.NOT_FOUND,ta.LOG_LEVELS.ERROR,r,!0);return await ti.dropTable(e),await RD.purgeTableStream(e.schema,e.table),`successfully deleted table '${e.schema}.${e.table}'`}a(h3,"dropTable");async function m3(e){let t=Zo.attribute_object(e);if(t)throw or(t,t.message,ar.BAD_REQUEST,void 0,void 0,!0);ra(e);let r=await ea.checkSchemaTableExists(e.schema,e.table);if(r)throw or(new Error,r,ar.NOT_FOUND,ta.LOG_LEVELS.ERROR,r,!0);if(e.attribute===global.hdb_schema[e.schema][e.table].hash_attribute)throw or(new Error,"You cannot drop a hash attribute",ar.BAD_REQUEST,void 0,void 0,!0);if(ta.TIME_STAMP_NAMES.indexOf(e.attribute)>=0)throw or(new Error,`cannot drop internal timestamp attribute: ${e.attribute}`,ar.BAD_REQUEST,void 0,void 0,!0);try{return await ti.dropAttribute(e),p3(e),sd.signalSchemaChange(new id(process.pid,e.operation,e.schema,e.table,e.attribute)),`successfully deleted attribute '${e.attribute}'`}catch(n){throw a3.error(`Got an error deleting attribute ${u3.inspect(e)}.`),n}}a(m3,"dropAttribute");function p3(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(p3,"dropAttributeFromGlobal");async function S3(e){ra(e);let t=_3()[e.schema][e.table].attributes;for(let{name:r}of t)if(r===e.attribute)throw or(new Error,`attribute '${e.attribute}' already exists in ${e.schema}.${e.table}`,ar.BAD_REQUEST,void 0,void 0,!0);return await ti.createAttribute(e),sd.signalSchemaChange(new id(process.pid,e.operation,e.schema,e.table,e.attribute)),`attribute '${e.schema}.${e.table}.${e.attribute}' successfully created.`}a(S3,"createAttribute");function T3(e){return ti.getBackup(e)}a(T3,"getBackup")});var yD=g((C_e,ND)=>{"use strict";var{OPERATIONS_ENUM:g3}=M(),cS=class{static{a(this,"ReadAuditLogObject")}constructor(t,r,n=void 0,s=void 0){this.operation=g3.READ_AUDIT_LOG,this.schema=t,this.table=r,this.search_type=n,this.search_values=s}};ND.exports=cS});var uS=g((M_e,LD)=>{"use strict";var R3=On(),L_e=yD(),ad=J(),cd=M(),A3=Z(),{handleHDBError:wD,hdb_errors:O3}=ee(),{HDB_ERROR_MSGS:ID,HTTP_STATUS_CODES:CD}=O3,b3=Object.values(cd.READ_AUDIT_LOG_SEARCH_TYPES_ENUM),DD="To use this operation audit log must be enabled in harperdb-config.yaml";LD.exports=N3;async function N3(e){if(ad.isEmpty(e.schema))throw new Error(ID.SCHEMA_REQUIRED_ERR);if(ad.isEmpty(e.table))throw new Error(ID.TABLE_REQUIRED_ERR);if(!A3.get(cd.CONFIG_PARAMS.LOGGING_AUDITLOG))throw wD(new Error,DD,CD.BAD_REQUEST,cd.LOG_LEVELS.ERROR,DD,!0);let t=ad.checkSchemaTableExist(e.schema,e.table);if(t)throw wD(new Error,t,CD.NOT_FOUND,cd.LOG_LEVELS.ERROR,t,!0);if(!ad.isEmpty(e.search_type)&&b3.indexOf(e.search_type)<0)throw new Error(`Invalid search_type '${e.search_type}'`);return await R3.readAuditLog(e)}a(N3,"readAuditLog")});var UD=g((P_e,MD)=>{"use strict";var{OPERATIONS_ENUM:y3}=M(),lS=class{static{a(this,"GetBackupObject")}constructor(t,r,n=void 0,s=void 0){this.operation=y3.GET_BACKUP,this.schema=t,this.table=r}};MD.exports=lS});var BD=g((x_e,vD)=>{"use strict";var w3=On(),B_e=UD(),_S=J(),I3=M(),H_e=Z(),{handleHDBError:C3,hdb_errors:D3}=ee(),{HDB_ERROR_MSGS:PD,HTTP_STATUS_CODES:L3}=D3;vD.exports=M3;async function M3(e){if(_S.isEmpty(e.schema))throw new Error(PD.SCHEMA_REQUIRED_ERR);if(_S.isEmpty(e.table))throw new Error(PD.TABLE_REQUIRED_ERR);let t=_S.checkSchemaTableExist(e.schema,e.table);if(t)throw C3(new Error,t,L3.NOT_FOUND,I3.LOG_LEVELS.ERROR,t,!0);return await w3.getBackup(read_audit_log_object)}a(M3,"getBackup")});var kD=g((F_e,GD)=>{var ri=require("validate.js"),xD=je(),na=M(),{handleHDBError:U3,hdb_errors:P3}=ee(),{HDB_ERROR_MSGS:ct,HTTP_STATUS_CODES:v3}=P3,dS=a(()=>({role:{presence:!0,format:"[\\w\\-\\_]+"},id:{presence:!0,format:"[\\w\\-\\_]+"},permission:{presence:!0}}),"constraintsTemplate"),B3={STRUCTURE_USER:"structure_user"},HD=Object.values(na.ROLE_TYPES_ENUM),H3="attribute_permissions",x3="attribute_name",{PERMS_CRUD_ENUM:sa}=na,q3=[H3,...Object.values(sa)],qD=[sa.READ,sa.INSERT,sa.UPDATE],F3=[x3,...qD];function G3(e){let t=dS();return t.role.presence=!0,t.id.presence=!1,t.permission.presence=!0,FD(e,t)}a(G3,"addRoleValidation");function k3(e){let t=dS();return t.role.presence=!1,t.id.presence=!0,t.permission.presence=!0,FD(e,t)}a(k3,"alterRoleValidation");function V3(e){let t=dS();return t.role.presence=!1,t.id.presence=!0,t.permission.presence=!1,xD.validateObject(e,t)}a(V3,"dropRoleValidation");var $3=["operation","role","id","permission","hdb_user","hdb_auth_header"];function FD(e,t){let r={main_permissions:[],schema_permissions:{}},n=Object.keys(e),s=[];for(let o=0,c=n.length;o<c;o++)$3.includes(n[o])||s.push(n[o]);s.length>0&&Et(ct.INVALID_ROLE_JSON_KEYS(s),r);let i=xD.validateObject(e,t);if(i&&i.message.split(",").forEach(o=>{Et(o,r)}),e.permission){let o=Y3(e);o&&Et(o,r),HD.forEach(c=>{e.permission[c]&&!ri.isBoolean(e.permission[c])&&Et(ct.SU_CU_ROLE_BOOLEAN_ERROR(c),r)})}for(let o in e.permission)if(HD.indexOf(o)<0){if(o===B3.STRUCTURE_USER){let u=e.permission[o];if(typeof u=="boolean")continue;if(Array.isArray(u)){for(let _=0,l=u.length;_<l;_++){let d=u[_];global.hdb_schema[d]||Et(ct.SCHEMA_NOT_FOUND(d),r)}continue}Et(ct.STRUCTURE_USER_ROLE_TYPE_ERROR(o),r);continue}let c=e.permission[o];if(!o||!global.hdb_schema[o]){Et(ct.SCHEMA_NOT_FOUND(o),r);continue}if(c.tables)for(let u in c.tables){let _=c.tables[u];if(!u||!global.hdb_schema[o][u]){Et(ct.TABLE_NOT_FOUND(o,u),r);continue}if(Object.keys(_).forEach(l=>{q3.includes(l)||Et(ct.INVALID_PERM_KEY(l),r,o,u)}),Object.values(sa).forEach(l=>{ri.isDefined(_[l])?ri.isBoolean(_[l])||Et(ct.TABLE_PERM_NOT_BOOLEAN(l),r,o,u):Et(ct.TABLE_PERM_MISSING(l),r,o,u)}),ri.isDefined(_.attribute_permissions)){if(!ri.isArray(_.attribute_permissions)){Et(ct.ATTR_PERMS_NOT_ARRAY,r,o,u);continue}}else{Et(ct.ATTR_PERMS_ARRAY_MISSING,r,o,u);continue}if(_.attribute_permissions){let l=global.hdb_schema[o][u].attributes.map(({attribute:f})=>f),d={read:!1,insert:!1,update:!1};for(let f in _.attribute_permissions){let E=_.attribute_permissions[f];if(Object.keys(E).forEach(p=>{!F3.includes(p)&&p!==sa.DELETE&&Et(ct.INVALID_ATTR_PERM_KEY(p),r,o,u)}),!ri.isDefined(E.attribute_name)){Et(ct.ATTR_PERM_MISSING_NAME,r,o,u);continue}let h=E.attribute_name;if(!l.includes(h)){Et(ct.INVALID_ATTRIBUTE_IN_PERMS(h),r,o,u);continue}qD.forEach(p=>{ri.isDefined(E[p])?ri.isBoolean(E[p])||Et(ct.ATTR_PERM_NOT_BOOLEAN(p,h),r,o,u):Et(ct.ATTR_PERM_MISSING(p,h),r,o,u)}),!d.read&&E.read===!0&&(d.read=!0),!d.insert&&E.insert===!0&&(d.insert=!0),!d.update&&E.update===!0&&(d.update=!0)}if(_.read===!1&&d.read===!0||_.insert===!1&&d.insert===!0||_.update===!1&&d.update===!0){let f=`${o}.${u}`;Et(ct.MISMATCHED_TABLE_ATTR_PERMS(f),r,o,u)}}}}return K3(r)}a(FD,"customValidate");GD.exports={addRoleValidation:G3,alterRoleValidation:k3,dropRoleValidation:V3};function Y3(e){let{operation:t,permission:r}=e;if(t===na.OPERATIONS_ENUM.ADD_ROLE||t===na.OPERATIONS_ENUM.ALTER_ROLE){let n=r.super_user===!0,s=r.cluster_user===!0;if(Object.keys(r).length>1&&(n||s)){if(s&&n)return ct.SU_CU_ROLE_COMBINED_ERROR;{let o=r.super_user?na.ROLE_TYPES_ENUM.SUPER_USER:na.ROLE_TYPES_ENUM.CLUSTER_USER;return ct.SU_CU_ROLE_NO_PERMS_ALLOWED(o)}}}return null}a(Y3,"validateNoSUPerms");function K3(e){let{main_permissions:t,schema_permissions:r}=e;if(t.length>0||Object.keys(r).length>0){let n={error:ct.ROLE_PERMS_ERROR,...e};return U3(new Error,n,v3.BAD_REQUEST)}else return null}a(K3,"generateRolePermResponse");function Et(e,t,r,n){if(!r)t.main_permissions.push(e);else{let s=n?r+"_"+n:r;t.schema_permissions[s]?t.schema_permissions[s].push(e):t.schema_permissions[s]=[e]}}a(Et,"addPermError")});var SS=g((k_e,KD)=>{"use strict";var VD=Zr(),$D=Xr(),W3=Fi(),ES=kD(),hS=ps(),Q3=require("uuid").v4,z3=require("util"),ud=M(),J3=J(),mS=$D.searchByValue,j3=$D.searchByHash,X3=z3.promisify(W3.delete),Z3=Kn(),ej=Jo(),{hdb_errors:tj,handleHDBError:eo}=ee(),{HDB_ERROR_MSGS:YD,HTTP_STATUS_CODES:ou}=tj,{UserEventMsg:pS}=bn();KD.exports={addRole:rj,alterRole:nj,dropRole:sj,listRoles:ij};function fS(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(fS,"scrubRoleDetails");async function rj(e){let t=ES.addRoleValidation(e);if(t)throw t;e=fS(e);let r={schema:"system",table:"hdb_role",search_attribute:"role",search_value:e.role,hash_attribute:"id",get_attributes:["*"]},n;try{n=Array.from(await mS(r)||[])}catch(i){throw eo(i)}if(n&&n.length>0)throw eo(new Error,YD.ROLE_ALREADY_EXISTS(e.role),ou.CONFLICT,void 0,void 0,!0);e.id||(e.id=Q3());let s={operation:"insert",schema:"system",table:"hdb_role",hash_attribute:"id",records:[e]};return await VD.insert(s),hS.signalUserChange(new pS(process.pid)),e=fS(e),e}a(rj,"addRole");async function nj(e){let t=ES.alterRoleValidation(e);if(t)throw t;e=fS(e);let r={operation:"update",schema:"system",table:"hdb_role",records:[e]},n;try{n=await VD.update(r)}catch(s){throw eo(s)}if(n&&n?.message==="updated 0 of 1 records")throw eo(new Error,"Invalid role id",ou.BAD_REQUEST,void 0,void 0,!0);return await hS.signalUserChange(new pS(process.pid)),e}a(nj,"alterRole");async function sj(e){let t=ES.dropRoleValidation(e);if(t)throw eo(new Error,t,ou.BAD_REQUEST,void 0,void 0,!0);let r=new ej(ud.SYSTEM_SCHEMA_NAME,ud.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME,[e.id],["role"]),n=Array.from(await j3(r));if(n.length===0)throw eo(new Error,YD.ROLE_NOT_FOUND,ou.NOT_FOUND,void 0,void 0,!0);let s=new Z3(ud.SYSTEM_SCHEMA_NAME,ud.SYSTEM_TABLE_NAMES.USER_TABLE_NAME,"role",e.id,void 0,["username","active"]),i=Array.from(await mS(s)),o=!1;if(J3.isEmptyOrZeroLength(i)===!1){for(let u=0;u<i.length;u++)if(i[u].active===!0){o=!0;break}}if(o===!0)throw eo(new Error,`Cannot drop role ${n[0].role} as it has active user(s) tied to this role`,ou.CONFLICT,void 0,void 0,!0);let c={table:"hdb_role",schema:"system",hash_values:[e.id]};return await X3(c),hS.signalUserChange(new pS(process.pid)),`${n[0].role} successfully deleted`}a(sj,"dropRole");async function ij(){return mS({table:"hdb_role",schema:"system",hash_attribute:"id",search_attribute:"id",search_value:"*",get_attributes:["*"]})}a(ij,"listRoles")});var JD=g(($_e,zD)=>{"use strict";var oj=Z(),ni=require("joi"),aj=je(),WD=require("moment"),cj=require("fs-extra"),TS=require("path"),uj=require("lodash"),au=M(),{LOG_LEVELS:to}=M(),lj="YYYY-MM-DD hh:mm:ss",_j=TS.resolve(__dirname,"../logs");zD.exports=function(e){return aj.validateBySchema(e,dj)};var dj=ni.object({from:ni.custom(QD),until:ni.custom(QD),level:ni.valid(to.NOTIFY,to.FATAL,to.ERROR,to.WARN,to.INFO,to.DEBUG,to.TRACE),order:ni.valid("asc","desc"),limit:ni.number().min(1),start:ni.number().min(0),log_name:ni.custom(fj)});function QD(e,t){if(WD(e,WD.ISO_8601).format(lj)==="Invalid date")return t.message(`'${t.state.path[0]}' date '${e}' is invalid.`)}a(QD,"validateDatetime");function fj(e,t){if(uj.invert(au.LOG_NAMES)[e]===void 0)return t.message(`'log_name' '${e}' is invalid.`);let n=oj.get(au.HDB_SETTINGS_NAMES.LOG_PATH_KEY),s=e===void 0?au.LOG_NAMES.HDB:e,i=s===au.LOG_NAMES.INSTALL?TS.join(_j,au.LOG_NAMES.INSTALL):TS.join(n,s);return cj.existsSync(i)?null:t.message(`'log_name' '${e}' does not exist.`)}a(fj,"validateReadLogPath")});var RS=g((K_e,XD)=>{"use strict";var ld=M(),Ej=Y(),hj=Z(),mj=JD(),gS=require("path"),jD=require("fs-extra"),{once:pj}=require("events"),{handleHDBError:Sj,hdb_errors:Tj}=ee(),{PACKAGE_ROOT:gj}=M(),Rj=gS.join(gj,"logs"),Aj=1e3,Oj=200;XD.exports=bj;async function bj(e){let t=mj(e);if(t)throw Sj(t,t.message,Tj.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0);let r=hj.get(ld.HDB_SETTINGS_NAMES.LOG_PATH_KEY),n=e.log_name===void 0?ld.LOG_NAMES.HDB:e.log_name,s=n===ld.LOG_NAMES.INSTALL?gS.join(Rj,ld.LOG_NAMES.INSTALL):gS.join(r,n),i=e.level!==void 0,o=i?e.level:void 0,c=e.from!==void 0,u=c?new Date(e.from):void 0,_=e.until!==void 0,l=_?new Date(e.until):void 0,d=e.limit===void 0?Aj:e.limit,f=e.order===void 0?void 0:e.order,E=e.start===void 0?0:e.start,h=E+d,p=0;f==="desc"&&!u&&!l&&(p=Math.max(jD.statSync(s).size-(h+5)*Oj,0));let S=jD.createReadStream(s,{start:p});S.on("error",v=>{Ej.error(v)});let T=0,A=[],b="",H;S.on("data",v=>{let P=/(?:^|\n)(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:[\d\.]+Z) \[(.+?)]: /g;v=b+v;let z=0,W;for(;(W=P.exec(v))&&!S.destroyed;){H&&(H.message=v.slice(z,W.index),q(H));let[Q,se,pe]=W,oe=pe.split("] ["),xe=oe[0],le=oe[1];oe.splice(0,2),H={timestamp:se,thread:xe,level:le,tags:oe,message:""},z=W.index+Q.length}b=v.slice(z)}),S.on("end",v=>{S.destroyed||H&&(H.message=b.trim(),q(H))}),S.resume();function q(v){let P,z,W;switch(!0){case(i&&c&&_):P=new Date(v.timestamp),z=new Date(u),W=new Date(l),v.level===o&&P>=z&&P<=W&&T<E?T++:v.level===o&&P>=z&&P<=W&&(si(v,f,A),T++,T===h&&S.destroy());break;case(i&&c):P=new Date(v.timestamp),z=new Date(u),v.level===o&&P>=z&&T<E?T++:v.level===o&&P>=z&&(si(v,f,A),T++,T===h&&S.destroy());break;case(i&&_):P=new Date(v.timestamp),W=new Date(l),v.level===o&&P<=W&&T<E?T++:v.level===o&&P<=W&&(si(v,f,A),T++,T===h&&S.destroy());break;case(c&&_):P=new Date(v.timestamp),z=new Date(u),W=new Date(l),P>=z&&P<=W&&T<E?T++:P>=z&&P<=W&&(si(v,f,A),T++,T===h&&S.destroy());break;case i:v.level===o&&T<E?T++:v.level===o&&(si(v,f,A),T++,T===h&&S.destroy());break;case c:P=new Date(v.timestamp),z=new Date(u),P>=z&&T<E?T++:P>=z&&T>=E&&(si(v,f,A),T++,T===h&&S.destroy());break;case _:P=new Date(v.timestamp),W=new Date(l),P<=W&&T<E?T++:P<=W&&T>=E&&(si(v,f,A),T++,T===h&&S.destroy());break;default:T<E?T++:(si(v,f,A),T++,T===h&&S.destroy())}}return a(q,"onLogMessage"),await pj(S,"close"),A}a(bj,"readLog");function si(e,t,r){t==="desc"?Nj(e,r):t==="asc"?yj(e,r):r.push(e)}a(si,"pushLineToResult");function Nj(e,t){let r=new Date(e.timestamp),n=0,s=t.length;for(;n<s;){let i=n+s>>>1;new Date(t[i].timestamp)>r?n=i+1:s=i}t.splice(n,0,e)}a(Nj,"insertDescending");function yj(e,t){let r=new Date(e.timestamp),n=0,s=t.length;for(;n<s;){let i=n+s>>>1;new Date(t[i].timestamp)<r?n=i+1:s=i}t.splice(n,0,e)}a(yj,"insertAscending")});var _d=g((j_e,rL)=>{"use strict";var AS=require("joi"),{string:cu,boolean:ZD,date:wj}=AS.types(),Ij=je(),{validateSchemaExists:Q_e,validateTableExists:z_e,validateSchemaName:J_e}=kn(),Cj=M(),Dj=tt(),eL=Z();eL.initSync();var Lj=cu.invalid(eL.get(Cj.CONFIG_PARAMS.CLUSTERING_NODENAME)).pattern(Dj.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(),tL={operation:cu.valid("add_node","update_node","set_node_replication"),node_name:Lj,subscriptions:AS.array().items({table:cu.optional(),schema:cu.optional(),database:cu.optional(),subscribe:ZD.required(),publish:ZD.required().custom(Uj),start_time:wj.iso()}).min(1).required()};function Mj(e){return Ij.validateBySchema(e,AS.object(tL))}a(Mj,"addUpdateNodeValidator");function Uj(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(Uj,"checkForFalsy");rL.exports={addUpdateNodeValidator:Mj,validation_schema:tL}});var sL=g((Z_e,nL)=>{var Pj=je(),vj={user:{presence:!0},schema:{presence:!0},table:{presence:!0},operation:{presence:!0}};nL.exports=function(e){return Pj.validateObject(e,vj)}});var bS=g((ede,iL)=>{"use strict";var Bj=M().OPERATIONS_ENUM,OS=class{static{a(this,"UpdateObject")}constructor(t,r,n,s=void 0){this.operation=Bj.UPDATE,this.schema=t,this.table=r,this.records=n,this.__origin=s}};iL.exports=OS});var aL=g((rde,oL)=>{"use strict";var Hj={OPERATION:"operation",REFRESH:"refresh"},NS=class{static{a(this,"JWTTokens")}constructor(t,r){this.operation_token=t,this.refresh_token=r}},yS=class{static{a(this,"JWTRSAKeys")}constructor(t,r,n){this.public_key=t,this.private_key=r,this.passphrase=n}};oL.exports={JWTTokens:NS,TOKEN_TYPE_ENUM:Hj,JWTRSAKeys:yS}});var _u=g((sde,_L)=>{"use strict";var lu=require("jsonwebtoken"),wS=require("fs-extra"),IS=J(),rn=M(),{handleHDBError:cr,hdb_errors:xj}=ee(),{HTTP_STATUS_CODES:ur,AUTHENTICATION_ERROR_MSGS:lr}=xj,uu=Y(),cL=N_(),LS=Mr(),qj=Zr().update,Fj=bS(),Gj=ps(),{UserEventMsg:kj}=bn(),ii=Z();ii.initSync();var CS=require("path"),{JWTTokens:Vj,JWTRSAKeys:$j,TOKEN_TYPE_ENUM:dd}=aL(),Yj=ii.get(rn.HDB_SETTINGS_NAMES.OPERATION_TOKEN_TIMEOUT_KEY)?ii.get(rn.HDB_SETTINGS_NAMES.OPERATION_TOKEN_TIMEOUT_KEY):"1d",Kj=ii.get(rn.HDB_SETTINGS_NAMES.REFRESH_TOKEN_TIMEOUT_KEY)?ii.get(rn.HDB_SETTINGS_NAMES.REFRESH_TOKEN_TIMEOUT_KEY):"30d",fd="RS256",DS;_L.exports={createTokens:Wj,validateOperationToken:zj,refreshOperationToken:Qj,validateRefreshToken:lL};async function Wj(e){if(IS.isEmpty(e)||typeof e!="object")throw cr(new Error,lr.INVALID_AUTH_OBJECT,ur.BAD_REQUEST,void 0,void 0,!0);if(IS.isEmpty(e.username))throw cr(new Error,lr.USERNAME_REQUIRED,ur.BAD_REQUEST,void 0,void 0,!0);if(IS.isEmpty(e.password))throw cr(new Error,lr.PASSWORD_REQUIRED,ur.BAD_REQUEST,void 0,void 0,!0);let t;try{if(t=await LS.findAndValidateUser(e.username,e.password),!t)throw cr(new Error,lr.INVALID_CREDENTIALS,ur.UNAUTHORIZED,void 0,void 0,!0)}catch(f){throw uu.error(f),cr(new Error,lr.INVALID_CREDENTIALS,ur.UNAUTHORIZED,void 0,void 0,!0)}let r=await Ed(),n=!1,s=!1;t.role&&t.role.permission&&(n=t.role.permission.super_user===!0,s=t.role.permission.cluster_user===!0);let i={username:e.username,super_user:n,cluster_user:s},o=await uL(i,r.private_key,r.passphrase),c=await lu.sign(i,{key:r.private_key,passphrase:r.passphrase},{expiresIn:Kj,algorithm:fd,subject:dd.REFRESH}),u=cL.hash(c),_=new Fj(rn.SYSTEM_SCHEMA_NAME,rn.SYSTEM_TABLE_NAMES.USER_TABLE_NAME,[{username:e.username,refresh_token:u}]),l,d;try{l=await qj(_)}catch(f){uu.error(f),d=f}if(d!==void 0||l.skipped_hashes.length>0)throw cr(new Error,lr.REFRESH_TOKEN_SAVE_FAILED,ur.INTERNAL_SERVER_ERROR);return Gj.signalUserChange(new kj(process.pid)),new Vj(o,c)}a(Wj,"createTokens");async function uL(e,t,r){return await lu.sign(e,{key:t,passphrase:r},{expiresIn:Yj,algorithm:fd,subject:dd.OPERATION})}a(uL,"signOperationToken");async function Ed(){if(DS===void 0)try{let e=CS.join(ii.getHdbBasePath(),rn.LICENSE_KEY_DIR_NAME,rn.JWT_ENUM.JWT_PASSPHRASE_NAME),t=CS.join(ii.getHdbBasePath(),rn.LICENSE_KEY_DIR_NAME,rn.JWT_ENUM.JWT_PRIVATE_KEY_NAME),r=CS.join(ii.getHdbBasePath(),rn.LICENSE_KEY_DIR_NAME,rn.JWT_ENUM.JWT_PUBLIC_KEY_NAME),n=(await wS.readFile(e)).toString(),s=(await wS.readFile(t)).toString(),i=(await wS.readFile(r)).toString();DS=new $j(i,s,n)}catch(e){throw uu.error(e),cr(new Error,lr.NO_ENCRYPTION_KEYS,ur.INTERNAL_SERVER_ERROR)}return DS}a(Ed,"getJWTRSAKeys");async function Qj(e){if(!e)throw cr(new Error,lr.INVALID_BODY,ur.BAD_REQUEST,void 0,void 0,!0);if(!e.refresh_token)throw cr(new Error,lr.REFRESH_TOKEN_REQUIRED,ur.BAD_REQUEST,void 0,void 0,!0);await lL(e.refresh_token);let t=await Ed(),r=await lu.decode(e.refresh_token);return{operation_token:await uL({username:r.username,super_user:r.super_user,cluster_user:r.cluster_user},t.private_key,t.passphrase)}}a(Qj,"refreshOperationToken");async function zj(e){try{let t=await Ed(),r=await lu.verify(e,t.public_key,{algorithms:fd,subject:dd.OPERATION});return await LS.findAndValidateUser(r.username,void 0,!1)}catch(t){throw uu.warn(t),t.name&&t.name==="TokenExpiredError"?cr(new Error,lr.TOKEN_EXPIRED,ur.FORBIDDEN):cr(new Error,lr.INVALID_TOKEN,ur.UNAUTHORIZED)}}a(zj,"validateOperationToken");async function lL(e){let t;try{let r=await Ed(),n=await lu.verify(e,r.public_key,{algorithms:fd,subject:dd.REFRESH});t=await LS.findAndValidateUser(n.username,void 0,!1)}catch(r){throw uu.warn(r),r.name&&r.name==="TokenExpiredError"?cr(new Error,lr.TOKEN_EXPIRED,ur.FORBIDDEN):cr(new Error,lr.INVALID_TOKEN,ur.UNAUTHORIZED)}if(!cL.validate(t.refresh_token,e))throw cr(new Error,lr.INVALID_TOKEN,ur.UNAUTHORIZED);return t}a(lL,"validateRefreshToken")});var MS=g((ade,EL)=>{"use strict";var Jj=sL(),ia=require("passport"),jj=require("passport-local").Strategy,Xj=require("passport-http").BasicStrategy,Zj=require("util"),eX=Mr(),fL=Zj.callbackify(eX.findAndValidateUser),ode=Or(),tX=M(),dL=_u();ia.use(new jj(function(e,t,r){fL(e,t,r)}));ia.use(new Xj(function(e,t,r){fL(e,t,r)}));ia.serializeUser(function(e,t){t(null,e)});ia.deserializeUser(function(e,t){t(null,e)});function rX(e,t,r){if(e.raw?.user!==void 0)return r(null,e.raw.user);let n,s;if(e.headers?.authorization){let o=e.headers.authorization.split(" ");n=o[0],s=o[1]}function i(o,c){return o?r(o):c?r(null,c):r("Must login")}switch(a(i,"handleResponse"),n){case"Basic":ia.authenticate("basic",{session:!1},(o,c)=>{i(o,c)})(e,t,r);break;case"Bearer":e.body?.operation&&e.body.operation===tX.OPERATIONS_ENUM.REFRESH_OPERATION_TOKEN?dL.validateRefreshToken(s).then(o=>{e.body.refresh_token=s,r(null,o)}).catch(o=>{r(o)}):dL.validateOperationToken(s).then(o=>{r(null,o)}).catch(o=>{r(o)});break;default:ia.authenticate("local",{session:!1},function(o,c){i(o,c)})(e,t,r);break}}a(rX,"authorize");function nX(e,t){let r=Jj(e);if(r){t(r);return}let n={authorized:!0,messages:[]},s=e.user.role;if(!s?.permission)return t("Invalid role");let i=JSON.parse(s.permission);if(i.super_user)return t(null,n);if(!i[e.schema])return n.authorized=!1,n.messages.push(`Not authorized to access ${e.schema} schema`),t(null,n);if(!i[e.schema].tables[e.table])return n.authorized=!1,n.messages.push(`Not authorized to access ${e.table} table`),t(null,n);if(!i[e.schema].tables[e.table][e.operation])return n.authorized=!1,n.messages.push(`Not authorized to access ${e.operation} on ${e.table} table`),t(null,n);if(i[e.schema].tables[e.table].attribute_permissions&&!e.attributes)return n.authorized=!1,n.messages.push(`${e.schema}.${e.table} has attribute permissions. Missing attributes to validate`),t(null,n);if(i[e.schema].tables[e.table].attribute_permissions&&e.attributes){let o=i[e.schema].tables[e.table].attribute_permissions;for(let c in o)e.attributes.indexOf(o[c].attribute_name)>-1&&!o[c][e.operation]&&(n.authorized=!1,n.messages.push(`Not authorized to ${e.operation} ${o[c].attribute_name} `))}return t(null,n)}a(nX,"checkPermissions");EL.exports={authorize:rX,checkPermissions:nX}});var oa=g((ude,hL)=>{"use strict";var US=class{static{a(this,"Node")}constructor(t,r,n){this.name=t,this.subscriptions=r,this.system_info=n}},PS=class{static{a(this,"NodeSubscription")}constructor(t,r,n,s){this.schema=t,this.table=r,this.publish=n,this.subscribe=s}};hL.exports={Node:US,NodeSubscription:PS}});var pL=g((_de,mL)=>{"use strict";var sX=M().OPERATIONS_ENUM,vS=class{static{a(this,"UpsertObject")}constructor(t,r,n,s=void 0){this.operation=sX.UPSERT,this.schema=t,this.table=r,this.records=n,this.__origin=s}};mL.exports=vS});var du=g((fde,SL)=>{"use strict";var BS=class{static{a(this,"RemotePayloadObject")}constructor(t,r,n,s){this.operation=t,this.node_name=r,this.subscriptions=n,this.system_info=s}},HS=class{static{a(this,"RemotePayloadSubscription")}constructor(t,r,n,s,i,o,c){this.schema=t,this.table=r,this.hash_attribute=n,this.publish=s,this.subscribe=i,this.start_time=o,c!==void 0&&(this.attributes=c)}};SL.exports={RemotePayloadObject:BS,RemotePayloadSubscription:HS}});var gL=g((hde,TL)=>{"use strict";var xS=class{static{a(this,"TableSizeObject")}constructor(t,r,n=0,s=0,i=0,o=0){this.schema=t,this.table=r,this.table_size=n,this.record_count=s,this.transaction_log_size=i,this.transaction_log_record_count=o}};TL.exports=xS});var OL=g((gde,AL)=>{"use strict";var iX=gL(),pde=lt(),RL=$e(),oX=Y(),{getSchemaPath:Sde,getTransactionAuditStorePath:Tde}=Ke(),{getDatabases:aX}=(be(),te(qe));AL.exports=cX;async function cX(e){let t=new iX;try{let r=aX()[e.schema]?.[e.name],n=r.primaryStore.getStats(),s=r.auditStore?.getStats(),i=await RL.environmentDataSize(schema_path,e.name),o=await RL.environmentDataSize(txn_path,e.name);t.schema=e.schema,t.table=e.name,t.table_size=i,t.record_count=n.entryCount,t.transaction_log_size=o,t.transaction_log_record_count=s.entryCount}catch(r){oX.warn(`unable to stat table dbi due to ${r}`)}return t}a(cX,"lmdbGetTableSize")});var NL=g((Ade,bL)=>{"use strict";var qS=class{static{a(this,"SystemInformationObject")}constructor(t,r,n,s,i,o,c){this.system=t,this.time=r,this.cpu=n,this.memory=s,this.disk=i,this.network=o,this.harperdb_processes=c}};bL.exports=qS});var aa=g((yde,CL)=>{"use strict";var uX=require("fs-extra"),lX=require("path"),Wt=require("systeminformation"),oi=Y(),_X=ft(),FS=tt(),md=M(),dX=OL(),IL=vi(),{getThreadInfo:yL}=Ze(),JS=Z();JS.initSync();var fX=NL(),{openEnvironment:bde}=$e(),{getSchemaPath:Nde}=Ke(),{database:EX}=(be(),te(qe)),hd;CL.exports={getHDBProcessInfo:$S,getNetworkInfo:KS,getDiskInfo:YS,getMemoryInfo:VS,getCPUInfo:kS,getTimeInfo:GS,getSystemInformation:WS,systemInformation:hX,getTableSize:QS,getMetrics:zS};function GS(){return Wt.time()}a(GS,"getTimeInfo");async function kS(){try{let{family:e,model:t,stepping:r,revision:n,voltage:s,speedmin:i,speedmax:o,governor:c,socket:u,cache:_,...l}=await Wt.cpu();l.cpu_speed=await Wt.cpuCurrentSpeed();let{raw_currentload:d,raw_currentload_idle:f,raw_currentload_irq:E,raw_currentload_nice:h,raw_currentload_system:p,raw_currentload_user:S,cpus:T,...A}=await Wt.currentLoad();return A.cpus=[],T.forEach(b=>{let{raw_load:H,raw_load_idle:q,raw_load_irq:v,raw_load_nice:P,raw_load_system:z,raw_load_user:W,...Q}=b;A.cpus.push(Q)}),l.current_load=A,l}catch(e){return oi.error(`error in getCPUInfo: ${e}`),{}}}a(kS,"getCPUInfo");async function VS(){try{let{buffers:e,cached:t,slab:r,buffcache:n,...s}=await Wt.mem();return Object.assign(s,process.memoryUsage())}catch(e){return oi.error(`error in getMemoryInfo: ${e}`),{}}}a(VS,"getMemoryInfo");async function $S(){let e={core:[],clustering:[]};try{let t=await Wt.processes(),r;try{r=Number.parseInt(await uX.readFile(lX.join(JS.get(md.CONFIG_PARAMS.ROOTPATH),md.HDB_PID_FILE),"utf8"))}catch(n){if(n.code===md.NODE_ERROR_CODES.ENOENT)oi.error("Unable to locate 'hdb.pid' file, try stopping and starting HarperDB");else throw n}t.list.forEach(n=>{n.pid===r?e.core.push(n):n.name==="nats-server"&&e.clustering.push(n)});for(let n of e.core)for(let s of t.list)s.pid===n.parentPid&&(s.name==="PM2"||s.command==="PM2")&&(n.parent="PM2");return e}catch(t){return oi.error(`error in getHDBProcessInfo: ${t}`),e}}a($S,"getHDBProcessInfo");async function YS(){let e={};try{let{rIO_sec:t,wIO_sec:r,tIO_sec:n,ms:s,...i}=await Wt.disksIO();e.io=i;let{rx_sec:o,tx_sec:c,wx_sec:u,..._}=await Wt.fsStats();return e.read_write=_,e.size=await Wt.fsSize(),e}catch(t){return oi.error(`error in getDiskInfo: ${t}`),e}}a(YS,"getDiskInfo");async function KS(){let e={default_interface:null,latency:{},interfaces:[],stats:[],connections:[]};try{return e.default_interface=await Wt.networkInterfaceDefault(),e.latency=await Wt.inetChecksite("google.com"),(await Wt.networkInterfaces()).forEach(n=>{let{internal:s,virtual:i,mtu:o,dhcp:c,dnsSuffix:u,ieee8021xAuth:_,ieee8021xState:l,carrier_changes:d,...f}=n;e.interfaces.push(f)}),(await Wt.networkStats()).forEach(n=>{let{rx_sec:s,tx_sec:i,ms:o,...c}=n;e.stats.push(c)}),e}catch(t){return oi.error(`error in getNetworkInfo: ${t}`),e}}a(KS,"getNetworkInfo");async function WS(){if(hd!==void 0)return hd;let e={};try{let{codepage:t,logofile:r,serial:n,build:s,servicepack:i,uefi:o,...c}=await Wt.osInfo();e=c;let u=await Wt.versions("node, npm");return e.node_version=u.node,e.npm_version=u.npm,hd=e,hd}catch(t){return oi.error(`error in getSystemInformation: ${t}`),e}}a(WS,"getSystemInformation");async function QS(){let e=[],t=await IL.describeAll();for(let r of Object.values(t))for(let n of Object.values(r))e.push(await dX(n));return e}a(QS,"getTableSize");async function zS(){let e=await IL.describeAll(),t={};for(let r in e){let n=t[r]={};for(let s in e[r])try{let i=EX({database:r,table:s}),o=i.getStats();o.readers=i.readerList().split(/\n\s+/).slice(1).map(c=>{let[u,_,l]=c.trim().split(" ");return{pid:u,thread:_,txnid:l}}),n[s]=o}catch(i){oi.notify(`Error getting stats for table ${s}: ${i}`)}}return t}a(zS,"getMetrics");async function wL(){if(JS.get(md.CONFIG_PARAMS.CLUSTERING_ENABLED)){let{js:e,jsm:t}=await _X.getNATSReferences(),r=await t.streams.info(FS.WORK_QUEUE_CONSUMER_NAMES.stream_name),n=await e.consumers.get(FS.WORK_QUEUE_CONSUMER_NAMES.stream_name,FS.WORK_QUEUE_CONSUMER_NAMES.durable_name),s={ingest:{stream:{...r.state},consumer:{num_ack_pending:n._info.num_ack_pending,num_redelivered:n._info.num_redelivered,num_waiting:n._info.num_waiting,num_pending:n._info.num_pending}}};return r.sources&&(s.ingest.stream.sources=r.sources),s}}a(wL,"getNatsStreamInfo");async function hX(e){let t=new fX;if(!Array.isArray(e.attributes)||e.attributes.length===0)return t.system=await WS(),t.time=GS(),t.cpu=await kS(),t.memory=await VS(),t.disk=await YS(),t.network=await KS(),t.harperdb_processes=await $S(),t.table_size=await QS(),t.metrics=await zS(),t.threads=await yL(),t.replication=await wL(),t;for(let r=0;r<e.attributes.length;r++)switch(e.attributes[r]){case"system":t.system=await WS();break;case"time":t.time=GS();break;case"cpu":t.cpu=await kS();break;case"memory":t.memory=await VS();break;case"disk":t.disk=await YS();break;case"network":t.network=await KS();break;case"harperdb_processes":t.harperdb_processes=await $S();break;case"table_size":t.table_size=await QS();break;case"database_metrics":case"metrics":t.metrics=await zS();break;case"threads":t.threads=await yL();break;case"replication":t.replication=await wL();break;default:break}return t}a(hX,"systemInformation")});var Sd=g((Ide,DL)=>{"use strict";DL.exports={version:mX,printVersion:pX};var pd=zc();function mX(){if(pd)return pd.version}a(mX,"version");function pX(){pd&&console.log(`HarperDB Version ${pd.version}`)}a(pX,"printVersion")});var As=g((Mde,PL)=>{"use strict";var SX=Zr(),jS=J(),TX=require("util"),ro=M(),LL=Z();LL.initSync();var gX=MS(),ML=Xr(),{Node:Dde,NodeSubscription:Lde}=oa(),RX=Jo(),AX=pL(),{RemotePayloadObject:OX,RemotePayloadSubscription:bX}=du(),{handleHDBError:NX,hdb_errors:yX}=ee(),{HTTP_STATUS_CODES:wX,HDB_ERROR_MSGS:IX}=yX,CX=Kn(),DX=aa(),LX=Sd(),{getDatabases:MX}=(be(),te(qe)),UX=TX.promisify(gX.authorize),PX=ML.searchByHash,vX=ML.searchByValue;PL.exports={authHeaderToUser:BX,isEmpty:HX,getNodeRecord:xX,upsertNodeRecord:qX,buildNodePayloads:FX,checkClusteringEnabled:GX,getAllNodeRecords:kX,getSystemInfo:VX,reverseSubscription:UL};async function BX(e){let t={headers:{authorization:e.hdb_auth_header}};return e.hdb_user=await UX(t,null),e}a(BX,"authHeaderToUser");function HX(e){return e==null}a(HX,"isEmpty");async function xX(e){let t=new RX(ro.SYSTEM_SCHEMA_NAME,ro.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[e],["*"]);return PX(t)}a(xX,"getNodeRecord");async function qX(e){let t=new AX(ro.SYSTEM_SCHEMA_NAME,ro.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[e]);return SX.upsert(t)}a(qX,"upsertNodeRecord");function UL(e){if(jS.isEmpty(e.subscribe)||jS.isEmpty(e.publish))throw new Error("Received invalid subscription object");let{schema:t,table:r,hash_attribute:n}=e,s={schema:t,table:r,hash_attribute:n};return e.subscribe===!0&&e.publish===!1?(s.subscribe=!1,s.publish=!0):e.subscribe===!1&&e.publish===!0?(s.subscribe=!0,s.publish=!1):(s.subscribe=e.subscribe,s.publish=e.publish),s}a(UL,"reverseSubscription");function FX(e,t,r,n){let s=[];for(let i=0,o=e.length;i<o;i++){let c=e[i],{schema:u,table:_}=c,l=jS.getTableHashAttribute(u,_),{subscribe:d,publish:f}=UL(c),E=MX()[u]?.[_],h=new bX(u,_,l,f,d,c.start_time,E.schemaDefined?E.attributes:void 0);s.push(h)}return new OX(r,t,s,n)}a(FX,"buildNodePayloads");function GX(){if(!LL.get(ro.CONFIG_PARAMS.CLUSTERING_ENABLED))throw NX(new Error,IX.CLUSTERING_NOT_ENABLED,wX.BAD_REQUEST,void 0,void 0,!0)}a(GX,"checkClusteringEnabled");async function kX(){let e=new CX(ro.SYSTEM_SCHEMA_NAME,ro.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,"name","*",void 0,["*"]);return Array.from(await vX(e))}a(kX,"getAllNodeRecords");async function VX(){let e=await DX.getSystemInformation();return{hdb_version:LX.version(),node_version:e.node_version,platform:e.platform}}a(VX,"getSystemInfo")});var XS=g((Pde,kL)=>{"use strict";var Td=ft(),vL=J(),BL=tt(),HL=M(),gd=Y(),xL=od(),$X=Sp(),{RemotePayloadObject:YX}=du(),{handleHDBError:qL,hdb_errors:KX}=ee(),{HTTP_STATUS_CODES:FL}=KX,{NodeSubscription:GL}=oa();kL.exports=WX;async function WX(e,t){let r;try{r=await Td.request(`${t}.${BL.REQUEST_SUFFIX}`,new YX(HL.OPERATIONS_ENUM.DESCRIBE_ALL,t,void 0,void 0)),gd.trace("Response from remote describe all request:",r)}catch(o){gd.error(`addNode received error from describe all request to remote node: ${o}`);let c=Td.requestErrorHandler(o,"add_node",t);throw qL(new Error,c,FL.INTERNAL_SERVER_ERROR,"error",c)}if(r.status===BL.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let o=`Error returned from remote node ${t}: ${r.message}`;throw qL(new Error,o,FL.INTERNAL_SERVER_ERROR,"error",o)}let n=r.message,s=[],i=[];for(let o of e){let{table:c}=o,u=o.database??o.schema??"data";if(u===HL.SYSTEM_SCHEMA_NAME){await Td.createLocalTableStream(u,c);let h=new GL(u,c,o.publish,o.subscribe);h.start_time=o.start_time,i.push(h);continue}let _=vL.doesSchemaExist(u),l=n[u]!==void 0,d=c?vL.doesTableExist(u,c):!0,f=c?n?.[u]?.[c]!==void 0:!0;if(!_&&!l||!d&&!f){s.push(o);continue}if(!_&&l&&(gd.trace(`addNode creating schema: ${u}`),await xL.createSchema({operation:"create_schema",schema:u})),!d&&f){gd.trace(`addNode creating table: ${c} in schema: ${u} with attributes ${JSON.stringify(n[u][c].attributes)}`);let h=new $X(u,c,n[u][c].hash_attribute);n[u][c].attributes&&(h.attributes=n[u][c].attributes),await xL.createTable(h)}await Td.createLocalTableStream(u,c);let E=new GL(u,c,o.publish,o.subscribe);E.start_time=o.start_time,i.push(E)}return{added:i,skipped:s}}a(WX,"reviewSubscriptions")});var Od=g((Bde,YL)=>{"use strict";var{handleHDBError:Rd,hdb_errors:QX}=ee(),{HTTP_STATUS_CODES:Ad}=QX,{addUpdateNodeValidator:zX}=_d(),fu=Y(),$L=M(),VL=tt(),JX=J(),ZS=ft(),Eu=As(),jX=Z(),XX=XS(),{Node:ZX,NodeSubscription:eZ}=oa(),{broadcast:tZ}=Ze(),rZ="Unable to create subscriptions due to schema and/or tables not existing on the local or remote node",nZ="Some subscriptions were unsuccessful due to schema and/or tables not existing on the local or remote node",sZ=jX.get($L.CONFIG_PARAMS.CLUSTERING_NODENAME);YL.exports=iZ;async function iZ(e,t=!1){fu.trace("addNode called with:",e),Eu.checkClusteringEnabled();let r=zX(e);if(r)throw Rd(r,r.message,Ad.BAD_REQUEST,void 0,void 0,!0);let n=e.node_name;if(!t){let d=await Eu.getNodeRecord(n);if(!JX.isEmptyOrZeroLength(d))throw Rd(new Error,`Node '${n}' has already been added, perform update_node to proceed.`,Ad.BAD_REQUEST,void 0,void 0,!0)}let{added:s,skipped:i}=await XX(e.subscriptions,n),o={message:void 0,added:s,skipped:i};if(s.length===0)return o.message=rZ,o;let c=Eu.buildNodePayloads(s,sZ,$L.OPERATIONS_ENUM.ADD_NODE,await Eu.getSystemInfo());fu.trace("addNode sending remote payload:",c);let u;try{u=await ZS.request(`${n}.${VL.REQUEST_SUFFIX}`,c)}catch(d){fu.error(`addNode received error from request: ${d}`);let f=ZS.requestErrorHandler(d,"add_node",n);throw Rd(new Error,f,Ad.INTERNAL_SERVER_ERROR,"error",f)}if(u.status===VL.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let d=`Error returned from remote node ${n}: ${u.message}`;throw Rd(new Error,d,Ad.INTERNAL_SERVER_ERROR,"error",d)}fu.trace(u);let _=[];for(let d=0,f=s.length;d<f;d++){let E=s[d];fu.trace("Add node updating work stream for node:",n,"subscriptions:",E),await ZS.updateWorkStream(E,n),s[d].start_time===void 0&&delete s[d].start_time,_.push(new eZ(E.schema,E.table,E.publish,E.subscribe))}let l=new ZX(n,_,u.system_info);return await Eu.upsertNodeRecord(l),tZ({type:"nats_update"}),i.length>0?o.message=nZ:o.message=`Successfully added '${n}' to manifest`,o}a(iZ,"addNode")});var nT=g((qde,QL)=>{"use strict";var{handleHDBError:eT,hdb_errors:oZ}=ee(),{HTTP_STATUS_CODES:tT}=oZ,{addUpdateNodeValidator:aZ}=_d(),hu=Y(),WL=M(),KL=tt(),xde=J(),rT=ft(),mu=As(),cZ=Z(),{cloneDeep:uZ}=require("lodash"),lZ=XS(),{Node:_Z,NodeSubscription:dZ}=oa(),{broadcast:fZ}=Ze(),EZ="Unable to update subscriptions due to schema and/or tables not existing on the local or remote node",hZ="Some subscriptions were unsuccessful due to schema and/or tables not existing on the local or remote node",mZ=cZ.get(WL.CONFIG_PARAMS.CLUSTERING_NODENAME);QL.exports=pZ;async function pZ(e){hu.trace("updateNode called with:",e),mu.checkClusteringEnabled();let t=aZ(e);if(t)throw eT(t,t.message,tT.BAD_REQUEST,void 0,void 0,!0);let r=e.node_name,n,s=await mu.getNodeRecord(r);s.length>0&&(n=uZ(s));let{added:i,skipped:o}=await lZ(e.subscriptions,r),c={message:void 0,updated:i,skipped:o};if(i.length===0)return c.message=EZ,c;let u=mu.buildNodePayloads(i,mZ,WL.OPERATIONS_ENUM.UPDATE_NODE,await mu.getSystemInfo());hu.trace("updateNode sending remote payload:",u);let _;try{_=await rT.request(`${r}.${KL.REQUEST_SUFFIX}`,u)}catch(l){hu.error(`updateNode received error from request: ${l}`);let d=rT.requestErrorHandler(l,"update_node",r);throw eT(new Error,d,tT.INTERNAL_SERVER_ERROR,"error",d)}if(_.status===KL.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let l=`Error returned from remote node ${r}: ${_.message}`;throw eT(new Error,l,tT.INTERNAL_SERVER_ERROR,"error",l)}hu.trace(_);for(let l=0,d=i.length;l<d;l++){let f=i[l];hu.trace(`updateNode updating work stream for node: ${r} subscription:`,f),await rT.updateWorkStream(f,r),i[l].start_time===void 0&&delete i[l].start_time}return n||(n=[new _Z(r,[],_.system_info)]),await SZ(n[0],i,_.system_info),o.length>0?c.message=hZ:c.message=`Successfully updated '${r}'`,c}a(pZ,"updateNode");async function SZ(e,t,r){let n=e;for(let s=0,i=t.length;s<i;s++){let o=t[s],c=!1;for(let u=0,_=e.subscriptions.length;u<_;u++){let l=n.subscriptions[u];if(l.schema===o.schema&&l.table===o.table){l.publish=o.publish,l.subscribe=o.subscribe,c=!0;break}}c||n.subscriptions.push(new dZ(o.schema,o.table,o.publish,o.subscribe))}n.system_info=r,await mu.upsertNodeRecord(n),fZ({type:"nats_update"})}a(SZ,"updateNodeTable")});var ZL=g((Gde,XL)=>{"use strict";var jL=require("joi"),{string:zL}=jL.types(),TZ=je(),JL=M(),gZ=Z(),RZ=tt();XL.exports=AZ;function AZ(e){let t=zL.invalid(gZ.get(JL.CONFIG_PARAMS.CLUSTERING_NODENAME)).pattern(RZ.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=jL.object({operation:zL.valid(JL.OPERATIONS_ENUM.REMOVE_NODE).required(),node_name:t});return TZ.validateBySchema(e,r)}a(AZ,"removeNodeValidator")});var Nd=g((Vde,iM)=>{"use strict";var{handleHDBError:eM,hdb_errors:OZ}=ee(),{HTTP_STATUS_CODES:tM}=OZ,bZ=ZL(),pu=Y(),rM=As(),NZ=J(),bd=M(),nM=tt(),sM=ft(),yZ=Z(),{RemotePayloadObject:wZ}=du(),{NodeSubscription:IZ}=oa(),CZ=Gc(),DZ=Fi(),{broadcast:LZ}=Ze(),MZ=yZ.get(bd.CONFIG_PARAMS.CLUSTERING_NODENAME);iM.exports=UZ;async function UZ(e){pu.trace("removeNode called with:",e),rM.checkClusteringEnabled();let t=bZ(e);if(t)throw eM(t,t.message,tM.BAD_REQUEST,void 0,void 0,!0);let r=e.node_name,n=await rM.getNodeRecord(r);if(NZ.isEmptyOrZeroLength(n))throw eM(new Error,`Node '${r}' was not found.`,tM.BAD_REQUEST,void 0,void 0,!0);n=n[0];let s=new wZ(bd.OPERATIONS_ENUM.REMOVE_NODE,MZ,[]),i,o=!1;try{i=await sM.request(`${r}.${nM.REQUEST_SUFFIX}`,s),pu.trace("Remove node reply from remote node:",r,i)}catch(u){pu.error("removeNode received error from request:",u),o=!0}for(let u=0,_=n.subscriptions.length;u<_;u++){let l=n.subscriptions[u];pu.trace(`Remove node removing subscription: ${l.schema}.${l.table} for node: ${r}`);let d=new IZ(l.schema,l.table,!1,!1);await sM.updateWorkStream(d,r)}let c=new CZ(bd.SYSTEM_SCHEMA_NAME,bd.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[r]);return await DZ.deleteRecord(c),LZ({type:"nats_update"}),i?.status===nM.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR||o?(pu.error("Error returned from remote node:",r,i?.message),`Successfully removed '${r}' from local manifest, however there was an error reaching remote node. Check the logs for more details.`):`Successfully removed '${r}' from manifest`}a(UZ,"removeNode")});var cM=g((Yde,aM)=>{"use strict";var oM=require("joi"),{string:PZ,array:vZ}=oM.types(),BZ=je(),HZ=_d();aM.exports=xZ;function xZ(e){let t=oM.object({operation:PZ.valid("configure_cluster").required(),connections:vZ.items(HZ.validation_schema).required()});return BZ.validateBySchema(e,t)}a(xZ,"configureClusterValidator")});var sT=g((Wde,fM)=>{"use strict";var qZ=M(),yd=Y(),FZ=J(),GZ=Nd(),kZ=Od(),uM=As(),VZ=cM(),{handleHDBError:lM,hdb_errors:$Z}=ee(),{HTTP_STATUS_CODES:_M}=$Z,YZ="Configure cluster complete.",KZ="Failed to configure the cluster. Check the logs for more details.",WZ="Configure cluster was partially successful. Errors occurred when attempting to configure the following nodes. Check the logs for more details.";fM.exports=QZ;async function QZ(e){yd.trace("configure cluster called with:",e),uM.checkClusteringEnabled();let t=VZ(e);if(t)throw lM(t,t.message,_M.BAD_REQUEST,void 0,void 0,!0);let r=await uM.getAllNodeRecords(),n=[];for(let f=0,E=r.length;f<E;f++)n.push(dM(GZ,{operation:qZ.OPERATIONS_ENUM.REMOVE_NODE,node_name:r[f].name},r[f].name));let s=await Promise.allSettled(n);yd.trace("All results from configure_cluster remove node:",s);let i=[],o=e.connections.length;for(let f=0;f<o;f++){let E=e.connections[f];i.push(dM(kZ,E,E.node_name))}let c=await Promise.allSettled(i);yd.trace("All results from configure_cluster add node:",c);let u=[],_=[],l=!1,d=s.concat(c);for(let f=0,E=d.length;f<E;f++){let h=d[f];h.status==="rejected"&&(yd.error(h.reason),u.includes(h.reason.node_name)||u.push(h.reason.node_name)),h.status==="fulfilled"&&(l=!0);let p=h?.value?.result;typeof p=="string"&&p.includes("Successfully removed")||h.status==="rejected"||_.push({node_name:h?.value?.node_name,subscriptions:h?.value?.result})}if(FZ.isEmptyOrZeroLength(u))return{message:YZ,connections:_};if(l)return{message:WZ,failed_nodes:u,connections:_};throw lM(new Error,KZ,_M.INTERNAL_SERVER_ERROR,void 0,void 0,!0)}a(QZ,"configureCluster");async function dM(e,t,r){try{return{node_name:r,result:await e(t)}}catch(n){throw{node_name:r,error:n}}}a(dM,"functionWrapper")});var hM=g((zde,EM)=>{"use strict";var wd=require("joi"),zZ=je(),{validateSchemaExists:JZ,validateTableExists:jZ,validateSchemaName:XZ}=kn(),ZZ=wd.object({operation:wd.string().valid("purge_stream"),schema:wd.string().custom(JZ).custom(XZ).required(),table:wd.string().custom(jZ).required()});function e5(e){return zZ.validateBySchema(e,ZZ)}a(e5,"purgeStreamValidator");EM.exports=e5});var iT=g((jde,mM)=>{"use strict";var{handleHDBError:t5,hdb_errors:r5}=ee(),{HTTP_STATUS_CODES:n5}=r5,s5=hM(),i5=ft(),o5=As();mM.exports=a5;async function a5(e){if(e.purge_ingest!==!0){let s=s5(e);if(s)throw t5(s,s.message,n5.BAD_REQUEST,void 0,void 0,!0)}o5.checkClusteringEnabled();let{schema:t,table:r,purge_ingest:n}=e;return await i5.purgeTableStream(t,r,n),n?"Successfully purged ingest":`Successfully purged table '${t}.${r}'`}a(a5,"purgeStream")});var cT=g((Zde,AM)=>{"use strict";var aT=As(),c5=ft(),TM=Z(),Id=M(),no=tt(),u5=J(),oT=Y(),{RemotePayloadObject:l5}=du(),{ErrorCode:pM}=require("nats"),SM=TM.get(Id.CONFIG_PARAMS.CLUSTERING_ENABLED),gM=TM.get(Id.CONFIG_PARAMS.CLUSTERING_NODENAME);AM.exports={clusterStatus:_5,buildNodeStatus:RM};async function _5(){let e={node_name:gM,is_enabled:SM,connections:[]};if(!SM)return e;let t=await aT.getAllNodeRecords();if(u5.isEmptyOrZeroLength(t))return e;let r=[];for(let n=0,s=t.length;n<s;n++)r.push(RM(t[n],e.connections));return await Promise.allSettled(r),e}a(_5,"clusterStatus");async function RM(e,t){let r=e.name,n=new l5(Id.OPERATIONS_ENUM.CLUSTER_STATUS,gM,void 0,await aT.getSystemInfo()),s,i,o=no.CLUSTER_STATUS_STATUSES.OPEN;try{let u=Date.now();s=await c5.request(no.REQUEST_SUBJECT(r),n),i=Date.now()-u,s.status===no.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR&&(o=no.CLUSTER_STATUS_STATUSES.CLOSED,oT.error(`Error getting node status from ${r} `,s))}catch(u){oT.warn(`Error getting node status from ${r}`,u),u.code===pM.NoResponders?o=no.CLUSTER_STATUS_STATUSES.NO_RESPONDERS:u.code===pM.Timeout?o=no.CLUSTER_STATUS_STATUSES.TIMEOUT:o=no.CLUSTER_STATUS_STATUSES.CLOSED}let c=new d5(r,o,s?.message?.ports?.clustering,s?.message?.ports?.operations_api,i,s?.message?.uptime,e.subscriptions,s?.message?.system_info);try{let u={name:r,system_info:s?.message?.system_info};e.system_info?.hdb_version!==Id.PRE_4_0_0_VERSION&&await aT.upsertNodeRecord(u)}catch(u){oT.error("Cluster status encountered an error updating system info for node:",r,u)}t.push(c)}a(RM,"buildNodeStatus");function d5(e,t,r,n,s,i,o,c){this.node_name=e,this.status=t,this.ports={clustering:r,operations_api:n},this.latency_ms=s,this.uptime=i,this.subscriptions=o,this.system_info=c}a(d5,"NodeStatusObject")});var lT=g((tfe,OM)=>{"use strict";var{handleHDBError:f5,hdb_errors:E5}=ee(),{HTTP_STATUS_CODES:h5}=E5,m5=ft(),p5=As(),uT=J(),Cd=require("joi"),S5=je(),T5=2e3,g5=Cd.object({timeout:Cd.number().min(1),connected_nodes:Cd.boolean(),routes:Cd.boolean()});OM.exports=R5;async function R5(e){p5.checkClusteringEnabled();let t=S5.validateBySchema(e,g5);if(t)throw f5(t,t.message,h5.BAD_REQUEST,void 0,void 0,!0);let{timeout:r,connected_nodes:n,routes:s}=e,i=n===void 0||uT.autoCastBoolean(n),o=s===void 0||uT.autoCastBoolean(s),c={nodes:[]},u=await m5.getServerList(r??T5),_={};if(i)for(let l=0,d=u.length;l<d;l++){let f=u[l].statsz;f&&(_[u[l].server.name]=f.routes)}for(let l=0,d=u.length;l<d;l++){if(u[l].statsz)continue;let f=u[l].server,E=u[l].data;if(f.name.endsWith("-hub")){let h={name:f.name.slice(0,-4),response_time:u[l].response_time};i&&(h.connected_nodes=[],_[f.name]&&_[f.name].forEach(p=>{h.connected_nodes.includes(p.name.slice(0,-4))||h.connected_nodes.push(p.name.slice(0,-4))})),o&&(h.routes=E.cluster?.urls?E.cluster?.urls.map(p=>({host:p.split(":")[0],port:uT.autoCast(p.split(":")[1])})):[]),c.nodes.push(h)}}return c}a(R5,"clusterNetwork")});var wM=g((nfe,yM)=>{"use strict";var _T=require("joi"),bM=je(),{route_constraints:NM}=Eh();yM.exports={setRoutesValidator:A5,deleteRoutesValidator:O5};function A5(e){let t=_T.object({server:_T.valid("hub","leaf").required(),routes:NM.required()});return bM.validateBySchema(e,t)}a(A5,"setRoutesValidator");function O5(e){let t=_T.object({routes:NM.required()});return bM.validateBySchema(e,t)}a(O5,"deleteRoutesValidator")});var fT=g((ife,LM)=>{"use strict";var so=wr(),dT=J(),Dd=M(),IM=wM(),{handleHDBError:CM,hdb_errors:b5}=ee(),{HTTP_STATUS_CODES:DM}=b5,N5="cluster routes successfully set",y5="cluster routes successfully deleted";LM.exports={setRoutes:w5,getRoutes:I5,deleteRoutes:C5};function w5(e){let t=IM.setRoutesValidator(e);if(t)throw CM(t,t.message,DM.BAD_REQUEST,void 0,void 0,!0);let r=so.getClusteringRoutes(),n=e.server==="hub"?r.hub_routes:r.leaf_routes,s=e.server==="hub"?r.leaf_routes:r.hub_routes,i=[],o=[];for(let c=0,u=e.routes.length;c<u;c++){let _=e.routes[c];_.port=dT.autoCast(_.port);let l=n.some(f=>f.host===_.host&&f.port===_.port),d=s.some(f=>f.host===_.host&&f.port===_.port);l||d?i.push(_):(n.push(_),o.push(_))}return e.server==="hub"?so.updateConfigValue(Dd.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,n):so.updateConfigValue(Dd.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,n),{message:N5,set:o,skipped:i}}a(w5,"setRoutes");function I5(){let e=so.getClusteringRoutes();return{hub:e.hub_routes,leaf:e.leaf_routes}}a(I5,"getRoutes");function C5(e){let t=IM.deleteRoutesValidator(e);if(t)throw CM(t,t.message,DM.BAD_REQUEST,void 0,void 0,!0);let r=so.getClusteringRoutes(),n=r.hub_routes,s=r.leaf_routes,i=[],o=[],c=!1,u=!1;for(let _=0,l=e.routes.length;_<l;_++){let d=e.routes[_],f=!1;for(let E=0,h=n.length;E<h;E++){let p=n[E];if(d.host===p.host&&d.port===p.port){n.splice(E,1),f=!0,c=!0,i.push(d);break}}if(!f){let E=!0;for(let h=0,p=s.length;h<p;h++){let S=s[h];if(d.host===S.host&&d.port===S.port){s.splice(h,1),u=!0,E=!1,i.push(d);break}}E&&o.push(d)}}return c&&(n=dT.isEmptyOrZeroLength(n)?null:n,so.updateConfigValue(Dd.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,n)),u&&(s=dT.isEmptyOrZeroLength(s)?null:s,so.updateConfigValue(Dd.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,s)),{message:y5,deleted:i,skipped:o}}a(C5,"deleteRoutes")});var UM=g((afe,MM)=>{"use strict";var Su=require("alasql"),io=require("recursive-iterator"),Cn=Y(),D5=J(),Tu=M(),ET=class{static{a(this,"sql_statement_bucket")}constructor(t){this.ast=t,this.affected_attributes=new Map,this.table_lookup=new Map,this.schema_lookup=new Map,this.table_to_schema_lookup=new Map,M5(this.ast,this.affected_attributes,this.table_lookup,this.schema_lookup,this.table_to_schema_lookup)}getAttributesBySchemaTableName(t,r){if(!t||!r||!this.affected_attributes)return[];if(this.affected_attributes.has(t))return!this.affected_attributes.get(t).has(r)&&(r=this.table_lookup.get(r),!r)?[]:this.affected_attributes.get(t).get(r)}getAllTables(){let t=[];if(!this.affected_attributes)return t;for(let r of this.affected_attributes.keys())t.push(Array.from(this.affected_attributes.get(r).keys()));return t}getTablesBySchemaName(t){return!t||!this.affected_attributes?[]:Array.from(this.affected_attributes.get(t).keys())}getSchemas(){return this.affected_attributes?Array.from(this.affected_attributes.keys()):[]}getAst(){return this.ast}updateAttributeWildcardsForRolePerms(t){let r=this.ast.columns.filter(s=>Tu.SEARCH_WILDCARDS.includes(s.columnid));if(r.length===0)return this.ast;let n=this.ast.from[0].databaseid;return this.ast.columns=this.ast.columns.filter(s=>!Tu.SEARCH_WILDCARDS.includes(s.columnid)),r.forEach(s=>{let i=this.table_to_schema_lookup.has(s.tableid)?this.table_to_schema_lookup.get(s.tableid):n,o=this.table_lookup.has(s.tableid)?this.table_lookup.get(s.tableid):this.ast.from[0].tableid;if(t[i]&&t[i].tables[o]&&t[i].tables[o][Tu.PERMS_CRUD_ENUM.READ]){let c;t[i].tables[o].attribute_permissions.length>0?c=L5(t[i].tables[o].attribute_permissions):c=global.hdb_schema[i][o].attributes.map(_=>({attribute_name:_.attribute}));let u=this.affected_attributes.get(i).get(o).filter(_=>!Tu.SEARCH_WILDCARDS.includes(_));c.forEach(({attribute_name:_})=>{let l=new Su.yy.Column({columnid:_});s.tableid&&(l.tableid=s.tableid),this.ast.columns.push(l),u.includes(_)||u.push(_)}),this.affected_attributes.get(i).set(o,u)}}),this.ast}};function L5(e){return e.filter(t=>t[Tu.PERMS_CRUD_ENUM.READ])}a(L5,"filterReadRestrictedAttrs");function M5(e,t,r,n,s){U5(e,t,r,n,s)}a(M5,"interpretAST");function gu(e,t,r,n,s){if(!(!e||!e.databaseid)&&(t.has(e.databaseid)||t.set(e.databaseid,new Map),t.get(e.databaseid).has(e.tableid)||t.get(e.databaseid).set(e.tableid,[]),e.as&&(r.has(e.as)||r.set(e.as,e.tableid),n&&!n.has(e.as)&&n.set(e.as,e.databaseid)),s)){let i=e.databaseid,o=e.tableid;e.as&&(o=e.as),s.set(o,i)}}a(gu,"addSchemaTableToMap");function U5(e,t,r,n,s){if(!e){Cn.info("getRecordAttributesAST: invalid SQL syntax tree");return}e instanceof Su.yy.Insert?H5(e,t,r):e instanceof Su.yy.Select?P5(e,t,r,n,s):e instanceof Su.yy.Update?v5(e,t,r):e instanceof Su.yy.Delete?B5(e,t,r):Cn.error("AST in getRecordAttributesAST() is not a valid SQL type.")}a(U5,"getRecordAttributesAST");function P5(e,t,r,n,s){if(!e){Cn.info("getSelectAttributes: invalid SQL syntax tree");return}if(!e.from||e.from[0]===void 0)return;let i=e.from[0].databaseid;if(D5.isEmptyOrZeroLength(i)){Cn.error("No schema specified");return}e.from.forEach(c=>{gu(c,t,r,n,s)}),e.joins&&e.joins.forEach(c=>{c.as&&(c.table.as=c.as),gu(c.table,t,r,n,s)});let o=new io(e.columns);for(let{node:c}of o)if(c&&c.columnid){let u=c.tableid,_=n.has(u)?n.get(u):i;if(u||(u=e.from[0].tableid),!t.get(_).has(u))if(r.has(u))u=r.get(u);else{Cn.info(`table specified as ${u} not found.`);return}t.get(_).get(u).indexOf(c.columnid)<0&&t.get(_).get(u).push(c.columnid)}if(e.where){let c=new io(e.where),u=e.from[0].tableid;for(let{node:_}of c)if(_&&_.columnid){let l=_.tableid?_.tableid:u;if(!t.get(i).has(l))if(r.has(l))l=r.get(l);else{Cn.info(`table specified as ${l} not found.`);continue}t.get(i).get(l).indexOf(_.columnid)<0&&t.get(i).get(l).push(_.columnid)}}if(e.joins&&e.joins.forEach(c=>{let u=new io(c.on);for(let{node:_}of u)if(_&&_.columnid){let l=_.tableid,d=s.get(l);if(!t.get(d).has(l))if(r.has(l))l=r.get(l);else{Cn.info(`table specified as ${l} not found.`);continue}t.get(d).get(l).indexOf(_.columnid)<0&&t.get(d).get(l).push(_.columnid)}}),e.order){let c=new io(e.order);for(let{node:u}of c)if(u&&u.columnid){let _=u.tableid,l=n.has(_)?n.get(_):i;if(_||(_=e.from[0].tableid),!t.get(l).has(_))if(r.has(_))_=r.get(_);else{Cn.info(`table specified as ${_} not found.`);return}t.get(l).get(_).indexOf(u.columnid)<0&&t.get(l).get(_).push(u.columnid)}}}a(P5,"getSelectAttributes");function v5(e,t,r){if(!e){Cn.info("getUpdateAttributes: invalid SQL syntax tree");return}let n=new io(e.columns),s=e.table.databaseid;gu(e.table,t,r);for(let{node:i}of n)i&&i.columnid&&hT(e.table.tableid,s,i.columnid,t,r)}a(v5,"getUpdateAttributes");function B5(e,t,r){if(!e){Cn.info("getDeleteAttributes: invalid SQL syntax tree");return}let n=new io(e.where),s=e.table.databaseid;gu(e.table,t,r);for(let{node:i}of n)i&&i.columnid&&hT(e.table.tableid,s,i.columnid,t,r)}a(B5,"getDeleteAttributes");function H5(e,t,r){if(!e){Cn.info("getInsertAttributes: invalid SQL syntax tree");return}let n=new io(e.columns),s=e.into.databaseid;gu(e.into,t,r);for(let{node:i}of n)i&&i.columnid&&hT(e.into.tableid,s,i.columnid,t,r)}a(H5,"getInsertAttributes");function hT(e,t,r,n,s){if(!n.get(t))return;let i=e;n.get(t).has(i)||(i=s.get(i)),n.get(t).get(i).push(r)}a(hT,"pushAttribute");MM.exports=ET});var ST=g((ufe,HM)=>{var Ld=Gi(),PM=require("chalk"),xr=Y(),vM=require("prompt"),{promisify:x5}=require("util"),mT=M(),q5=require("fs-extra"),F5=require("path"),G5=J(),k5=Sd(),BM=Z();BM.initSync();var V5=require("moment"),$5=x5(vM.get),Y5=F5.join(BM.getHdbBasePath(),mT.LICENSE_KEY_DIR_NAME,mT.LICENSE_FILE_NAME,mT.LICENSE_FILE_NAME);HM.exports={getFingerprint:W5,setLicense:K5,parseLicense:pT,register:Q5,getRegistrationInfo:J5};async function K5(e){if(e&&e.key&&e.company){try{xr.info(`parsing license key: ${e.key} and `);let t=e.company.toString();await pT(e.key.trim(),t.trim())}catch(t){let r="There was an error parsing the license key.";throw xr.error(r),xr.error(t),new Error(r)}return"Wrote license key file. Registration successful."}throw new Error("Invalid key or company specified for license file.")}a(K5,"setLicense");async function W5(){let e={};try{e=await Ld.generateFingerPrint()}catch(t){let r="Error generating fingerprint.";throw xr.error(r),xr.error(t),new Error(r)}return e}a(W5,"getFingerprint");async function pT(e,t){if(!e||!t)throw new Error("Invalid entries for License Key and Customer Company");xr.info("Validating license input...");let r=Ld.validateLicense(e,t);if(xr.info("checking for valid license..."),!r.valid_license)throw new Error("Invalid license found.");if(xr.info("checking valid license date..."),!r.valid_date)throw new Error("This License has expired.");if(xr.info(`checking for valid machine license ${r.valid_machine}`),!r.valid_machine)throw new Error("This license is in use on another machine.");try{xr.info("writing license to disk"),await q5.writeFile(Y5,JSON.stringify({license_key:e,company:t}))}catch(n){throw xr.error("Failed to write License"),n}return"Registration successful."}a(pT,"parseLicense");async function Q5(){let e=await z5();return pT(e.HDB_LICENSE,e.CUSTOMER_COMPANY)}a(Q5,"register");async function z5(){let e=await Ld.generateFingerPrint(),t={properties:{CUSTOMER_COMPANY:{description:PM.magenta("[COMPANY] Please enter your company name"),required:!0},HDB_LICENSE:{description:PM.magenta(`[HDB_LICENSE] Your fingerprint is ${e} Please enter your license key`),required:!0}}};try{vM.start()}catch(n){xr.error(n)}let r;try{r=await $5(t)}catch(n){throw console.error("There was a problem prompting for registration input. Exiting."),n}return r}a(z5,"promptForRegistration");async function J5(){let e={registered:!1,version:null,ram_allocation:null,license_expiration_date:null},t;try{t=await Ld.getLicense()}catch(r){throw xr.error(`There was an error when searching licenses due to: ${r.message}`),r}if(G5.isEmptyOrZeroLength(t))throw new Error("There were no licenses found.");if(e.registered=t.enterprise,e.version=k5.version(),e.ram_allocation=t.ram_allocation,isNaN(t.exp_date))e.license_expiration_date=t.enterprise?t.exp_date:null;else{let r=V5.utc(t.exp_date).format("YYYY-MM-DD");e.license_expiration_date=t.enterprise?r:null}return e}a(J5,"getRegistrationInfo")});var qM=g((_fe,xM)=>{"use strict";var j5=tt(),TT=class{static{a(this,"HubConfigObject")}constructor(t,r,n,s,i,o,c,u,_,l,d,f,E,h){this.port=t,o===null&&(o=void 0),this.server_name=r+j5.SERVER_SUFFIX.HUB,this.pid_file=n,this.max_payload=67108864,this.jetstream={enabled:!1},this.tls={cert_file:s,key_file:i,ca_file:o,insecure:c,verify:u},this.leafnodes={port:_,tls:{cert_file:s,key_file:i,ca_file:o,insecure:c}},this.cluster={name:l,port:d,routes:f,tls:{cert_file:s,key_file:i,ca_file:o,insecure:c,verify:u}},this.accounts={SYS:{users:E},HDB:{users:h}},this.system_account="SYS"}};xM.exports=TT});var kM=g((ffe,GM)=>{"use strict";var FM=tt(),gT=class{static{a(this,"LeafConfigObject")}constructor(t,r,n,s,i,o,c,u,_,l,d){this.port=t,d===null&&(d=void 0),this.server_name=r+FM.SERVER_SUFFIX.LEAF,this.pid_file=n,this.max_payload=67108864,this.jetstream={enabled:!0,store_dir:s,domain:r+FM.SERVER_SUFFIX.LEAF},this.tls={cert_file:_,key_file:l,ca_file:d,insecure:!0},this.leafnodes={remotes:[{tls:{ca_file:d,insecure:!0},urls:i,account:"SYS"},{tls:{ca_file:d,insecure:!0},urls:o,account:"HDB"}]},this.accounts={SYS:{users:c},HDB:{users:u,jetstream:"enabled"}},this.system_account="SYS"}};GM.exports=gT});var $M=g((hfe,VM)=>{"use strict";var RT=class{static{a(this,"HdbUserObject")}constructor(t,r){this.user=t,this.password=r}};VM.exports=RT});var KM=g((pfe,YM)=>{"use strict";var X5=tt(),AT=class{static{a(this,"SysUserObject")}constructor(t,r){this.user=t+X5.SERVER_SUFFIX.ADMIN,this.password=r}};YM.exports=AT});var NT=g((Tfe,zM)=>{"use strict";var ca=require("path"),Pd=require("fs-extra"),Z5=qM(),e8=kM(),t8=$M(),r8=KM(),OT=Mr(),la=J(),_r=wr(),Ud=M(),Ru=tt(),{CONFIG_PARAMS:ut}=Ud,Au=Y(),Ou=Z(),WM=hs(),bT=ft(),ua="clustering",n8=1e4,QM=5;zM.exports={generateNatsConfig:i8,removeNatsConfig:o8,getHubConfigPath:s8};function s8(){let e=Ou.get(ut.ROOTPATH);return ca.join(e,ua,Ru.NATS_CONFIG_FILES.HUB_SERVER)}a(s8,"getHubConfigPath");async function i8(e=!1,t=void 0){Ou.initSync();let r=Ou.get(ut.ROOTPATH),n=ca.join(r,ua,Ru.PID_FILES.HUB),s=ca.join(r,ua,Ru.PID_FILES.LEAF),i=_r.getConfigFromFile(ut.CLUSTERING_LEAFSERVER_STREAMS_PATH),o=ca.join(r,ua,Ru.NATS_CONFIG_FILES.HUB_SERVER),c=ca.join(r,ua,Ru.NATS_CONFIG_FILES.LEAF_SERVER),u=_r.getConfigFromFile(ut.CLUSTERING_TLS_CERTIFICATE),_=_r.getConfigFromFile(ut.CLUSTERING_TLS_PRIVATEKEY),l=_r.getConfigFromFile(ut.CLUSTERING_TLS_CERT_AUTH),d=_r.getConfigFromFile(ut.CLUSTERING_TLS_INSECURE),f=_r.getConfigFromFile(ut.CLUSTERING_TLS_VERIFY),E=_r.getConfigFromFile(ut.CLUSTERING_NODENAME),h=_r.getConfigFromFile(ut.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT);await bT.checkNATSServerInstalled()||vd("nats-server dependency is either missing or the wrong version. Run 'npm install' to fix");let p=await OT.listUsers(),S=_r.getConfigFromFile(ut.CLUSTERING_USER),T=await OT.getClusterUser();(la.isEmpty(T)||T.active!==!0)&&vd(`Invalid cluster user '${S}'. A valid user with the role 'cluster_user' must be defined under clustering.user in harperdb-config.yaml`),e||(await Md(ut.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),await Md(ut.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT),await Md(ut.CLUSTERING_HUBSERVER_NETWORK_PORT),await Md(ut.CLUSTERING_LEAFSERVER_NETWORK_PORT));let A=[],b=[];for(let[Q,se]of p.entries())se.role.role===Ud.ROLE_TYPES_ENUM.CLUSTER_USER&&se.active&&(A.push(new r8(se.username,WM.decrypt(se.hash))),b.push(new t8(se.username,WM.decrypt(se.hash))));let H=[],{hub_routes:q}=_r.getClusteringRoutes();if(!la.isEmptyOrZeroLength(q))for(let Q of q)H.push(`tls://${T.sys_name_encoded}:${T.uri_encoded_d_hash}@${Q.host}:${Q.port}`);let v=new Z5(_r.getConfigFromFile(ut.CLUSTERING_HUBSERVER_NETWORK_PORT),E,n,u,_,l,d,f,h,_r.getConfigFromFile(ut.CLUSTERING_HUBSERVER_CLUSTER_NAME),_r.getConfigFromFile(ut.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),H,A,b);l==null&&(delete v.tls.ca_file,delete v.leafnodes.tls.ca_file),t=la.isEmpty(t)?void 0:t.toLowerCase(),(t===void 0||t===Ud.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase())&&(await Pd.writeJson(o,v),Au.trace(`Hub server config written to ${o}`));let P=`tls://${T.sys_name_encoded}:${T.uri_encoded_d_hash}@0.0.0.0:${h}`,z=`tls://${T.uri_encoded_name}:${T.uri_encoded_d_hash}@0.0.0.0:${h}`,W=new e8(_r.getConfigFromFile(ut.CLUSTERING_LEAFSERVER_NETWORK_PORT),E,s,i,[P],[z],A,b,u,_,l,d);l==null&&delete W.tls.ca_file,(t===void 0||t===Ud.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())&&(await Pd.writeJson(c,W),Au.trace(`Leaf server config written to ${c}`))}a(i8,"generateNatsConfig");async function Md(e){let t=Ou.get(e);return la.isEmpty(t)&&vd(`port undefined for '${e}'`),await la.isPortTaken(t)&&vd(`'${e}' port '${t}' is is in use by another process, check to see if HarperDB is already running or another process is using this port.`),!0}a(Md,"isPortAvailable");function vd(e){let t=`Error generating clustering config: ${e}`;Au.error(t),console.error(t),process.exit(1)}a(vd,"generateNatsConfigError");async function o8(e){let{port:t,config_file:r}=bT.getServerConfig(e),{username:n,decrypt_hash:s}=await OT.getClusterUser(),i=0,o=2e3;for(;i<QM;){try{let _=await bT.createConnection(t,n,s,!1);if(_.protocol.connected===!0){_.close();break}}catch(_){Au.trace(`removeNatsConfig waiting for ${e}. Caught and swallowed error ${_}`)}if(i++,i>=QM)throw new Error(`Operations API timed out attempting to connect to ${e}. This is commonly caused by incorrect clustering config. Check hdb.log for further details.`);await la.async_set_timeout(o*(i*2))}let c="0".repeat(n8),u=ca.join(Ou.get(ut.ROOTPATH),ua,r);await Pd.writeFile(u,c),await Pd.remove(u),Au.notify(e,"started.")}a(o8,"removeNatsConfig")});var tU=g((Rfe,eU)=>{"use strict";var qr=Z(),a8=Gi(),me=M(),bu=tt(),Os=require("path"),{PACKAGE_ROOT:Hd}=M(),JM=Z(),Bd=J(),_a="/dev/null",c8=Os.join(Hd,"launchServiceScripts"),jM=Os.join(Hd,"utility/scripts"),u8=Os.join(jM,me.HDB_RESTART_SCRIPT),XM=Os.resolve(Hd,"dependencies",`${process.platform}-${process.arch}`,bu.NATS_BINARY_NAME);function ZM(){let t=a8.licenseSearch().ram_allocation||me.RAM_ALLOCATION_ENUM.DEFAULT,r=me.MEM_SETTING_KEY+t,n={[me.PROCESS_NAME_ENV_PROP]:me.PROCESS_DESCRIPTORS.HDB,IS_SCRIPTED_SERVICE:!0};return Bd.noBootFile()&&(n[me.CONFIG_PARAMS.ROOTPATH.toUpperCase()]=Bd.getEnvCliRootPath()),{name:me.PROCESS_DESCRIPTORS.HDB,script:me.LAUNCH_SERVICE_SCRIPTS.MAIN,exec_mode:"fork",env:n,node_args:r,cwd:Hd}}a(ZM,"generateMainServerConfig");var l8=9930;function _8(){qr.initSync(!0);let e=qr.get(me.CONFIG_PARAMS.ROOTPATH),t=Os.join(e,"clustering",bu.NATS_CONFIG_FILES.HUB_SERVER),r=Os.join(qr.get(me.HDB_SETTINGS_NAMES.LOG_PATH_KEY),me.LOG_NAMES.HDB),n=JM.get(me.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),s=bu.LOG_LEVEL_FLAGS[qr.get(me.CONFIG_PARAMS.CLUSTERING_LOGLEVEL)]??void 0,i={name:me.PROCESS_DESCRIPTORS.CLUSTERING_HUB+(n!==l8?"-"+n:""),script:XM,args:s?`${s} -c ${t}`:`-c ${t}`,exec_mode:"fork",env:{[me.PROCESS_NAME_ENV_PROP]:me.PROCESS_DESCRIPTORS.CLUSTERING_HUB},merge_logs:!0,out_file:r,error_file:r,instances:1};return qr.get(me.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(i.out_file=_a,i.error_file=_a),i}a(_8,"generateNatsHubServerConfig");var d8=9940;function f8(){qr.initSync(!0);let e=qr.get(me.CONFIG_PARAMS.ROOTPATH),t=Os.join(e,"clustering",bu.NATS_CONFIG_FILES.LEAF_SERVER),r=Os.join(qr.get(me.HDB_SETTINGS_NAMES.LOG_PATH_KEY),me.LOG_NAMES.HDB),n=JM.get(me.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),s=bu.LOG_LEVEL_FLAGS[qr.get(me.CONFIG_PARAMS.CLUSTERING_LOGLEVEL)]??void 0,i={name:me.PROCESS_DESCRIPTORS.CLUSTERING_LEAF+(n!==d8?"-"+n:""),script:XM,args:s?`${s} -c ${t}`:`-c ${t}`,exec_mode:"fork",env:{[me.PROCESS_NAME_ENV_PROP]:me.PROCESS_DESCRIPTORS.CLUSTERING_LEAF},merge_logs:!0,out_file:r,error_file:r,instances:1};return qr.get(me.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(i.out_file=_a,i.error_file=_a),i}a(f8,"generateNatsLeafServerConfig");function E8(){qr.initSync();let e=Os.join(qr.get(me.CONFIG_PARAMS.LOGGING_ROOT),me.LOG_NAMES.HDB),t={name:me.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0,script:me.LAUNCH_SERVICE_SCRIPTS.NODES_UPGRADE_4_0_0,exec_mode:"fork",env:{[me.PROCESS_NAME_ENV_PROP]:me.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0},merge_logs:!0,out_file:e,error_file:e,instances:1,cwd:c8,autorestart:!1};return qr.get(me.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(t.out_file=_a,t.error_file=_a),t}a(E8,"generateClusteringUpgradeV4ServiceConfig");function h8(){let e={[me.PROCESS_NAME_ENV_PROP]:me.PROCESS_DESCRIPTORS.RESTART_HDB};return Bd.noBootFile()&&(e[me.CONFIG_PARAMS.ROOTPATH.toUpperCase()]=Bd.getEnvCliRootPath()),{...{name:me.PROCESS_DESCRIPTORS.RESTART_HDB,exec_mode:"fork",env:e,instances:1,autorestart:!1,cwd:jM},script:u8}}a(h8,"generateRestart");function m8(){return{apps:[ZM()]}}a(m8,"generateAllServiceConfigs");eU.exports={generateAllServiceConfigs:m8,generateMainServerConfig:ZM,generateRestart:h8,generateNatsHubServerConfig:_8,generateNatsLeafServerConfig:f8,generateClusteringUpgradeV4ServiceConfig:E8}});var hU=g((bfe,EU)=>{"use strict";var Me=M(),p8=J(),bs=NT(),Nu=ft(),Jn=tt(),ai=tU(),xd=Z(),ci=Y(),S8=As(),{startWorker:rU,onMessageFromWorkers:T8}=Ze(),g8=aa(),Ofe=require("util"),R8=require("child_process"),A8=require("fs"),{execFile:O8}=R8,we;EU.exports={enterPM2Mode:b8,start:ui,stop:yT,reload:sU,restart:iU,list:wT,describe:aU,connect:Ns,kill:C8,startAllServices:D8,startService:IT,getUniqueServicesList:cU,restartAllServices:L8,isServiceRegistered:uU,reloadStopStart:lU,restartHdb:oU,deleteProcess:w8,startClusteringProcesses:dU,startClusteringThreads:fU,isHdbRestartRunning:I8,isClusteringRunning:U8,stopClustering:M8,reloadClustering:P8};var yu=!1;T8(e=>{e.type==="restart"&&xd.initSync(!0)});function b8(){yu=!0}a(b8,"enterPM2Mode");function Ns(){return we||(we=require("pm2")),new Promise((e,t)=>{we.connect((r,n)=>{ci.setupConsoleLogging(),r&&t(r),e(n)})})}a(Ns,"connect");var dr,N8=10,nU;function ui(e,t=!1){if(yu)return y8(e);let r=O8(e.script,e.args.split(" "),e);r.name=e.name,r.on("exit",async i=>{let o=dr.indexOf(r);o>-1&&dr.splice(o,1),!nU&&i!==0&&(e.restarts=(e.restarts||0)+1,e.restarts<N8&&(A8.existsSync(bs.getHubConfigPath())?ui(e):(await bs.generateNatsConfig(!0),ui(e),await new Promise(c=>setTimeout(c,3e3)),await bs.removeNatsConfig(Me.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await bs.removeNatsConfig(Me.PROCESS_DESCRIPTORS.CLUSTERING_LEAF))))});let n={serviceName:e.name.replace(/ /g,"-")};function s(i){let o=xd.get(Me.CONFIG_PARAMS.CLUSTERING_LOGLEVEL),c=/\[\d+][^\[]+\[(\w+)]/g,u,_=0,l;for(;u=c.exec(i);){if(u.index&&Jn.LOG_LEVEL_HIERARCHY[o]>=Jn.LOG_LEVEL_HIERARCHY[l||"info"]){let E=l===Jn.LOG_LEVELS.ERR||l===Jn.LOG_LEVELS.WRN?ci.OUTPUTS.STDERR:ci.OUTPUTS.STDOUT;ci.logCustomLevel(l||"info",E,n,i.slice(_,u.index).trim())}let[d,f]=u;_=u.index+d.length,l=Jn.LOG_LEVELS[f]}if(Jn.LOG_LEVEL_HIERARCHY[o]>=Jn.LOG_LEVEL_HIERARCHY[l||"info"]){let d=l===Jn.LOG_LEVELS.ERR||l===Jn.LOG_LEVELS.WRN?ci.OUTPUTS.STDERR:ci.OUTPUTS.STDOUT;ci.logCustomLevel(l||"info",d,n,i.slice(_).trim())}}if(a(s,"extractMessages"),r.stdout.on("data",s),r.stderr.on("data",s),r.unref(),dr=[],!dr&&!t){let i=a(()=>{nU=!0,dr&&(dr.map(o=>o.kill()),process.exit(0))},"kill_children");process.on("exit",i),process.on("SIGINT",i),process.on("SIGQUIT",i),process.on("SIGTERM",i)}dr.push(r)}a(ui,"start");function y8(e){return new Promise(async(t,r)=>{try{await Ns()}catch(n){r(n)}we.start(e,(n,s)=>{n&&(we.disconnect(),r(n)),we.disconnect(),t(s)})})}a(y8,"startWithPM2");function yT(e){if(!yu){for(let t of dr||[])t.name===e&&(dr.splice(dr.indexOf(t),1),t.kill());return}return new Promise(async(t,r)=>{try{await Ns()}catch(n){r(n)}we.stop(e,async(n,s)=>{n&&(we.disconnect(),r(n)),we.delete(e,(i,o)=>{i&&(we.disconnect(),r(n)),we.disconnect(),t(o)})})})}a(yT,"stop");function sU(e){return new Promise(async(t,r)=>{try{await Ns()}catch(n){r(n)}we.reload(e,(n,s)=>{n&&(we.disconnect(),r(n)),we.disconnect(),t(s)})})}a(sU,"reload");function iU(e){if(!yu)for(let t of dr||[])t.name===e&&t.kill();return new Promise(async(t,r)=>{try{await Ns()}catch(n){r(n)}we.restart(e,(n,s)=>{we.disconnect(),t(s)})})}a(iU,"restart");function w8(e){return new Promise(async(t,r)=>{try{await Ns()}catch(n){r(n)}we.delete(e,(n,s)=>{n&&(we.disconnect(),r(n)),we.disconnect(),t(s)})})}a(w8,"deleteProcess");async function oU(){await ui(ai.generateRestart())}a(oU,"restartHdb");async function I8(){let e=await wT();for(let t in e)if(e[t].name===Me.PROCESS_DESCRIPTORS.RESTART_HDB)return!0;return!1}a(I8,"isHdbRestartRunning");function wT(){return new Promise(async(e,t)=>{try{await Ns()}catch(r){t(r)}we.list((r,n)=>{r&&(we.disconnect(),t(r)),we.disconnect(),e(n)})})}a(wT,"list");function aU(e){return new Promise(async(t,r)=>{try{await Ns()}catch(n){r(n)}we.describe(e,(n,s)=>{n&&(we.disconnect(),r(n)),we.disconnect(),t(s)})})}a(aU,"describe");function C8(){if(!yu){for(let e of dr||[])e.kill();dr=[];return}return new Promise(async(e,t)=>{try{await Ns()}catch(r){t(r)}we.killDaemon((r,n)=>{r&&(we.disconnect(),t(r)),we.disconnect(),e(n)})})}a(C8,"kill");async function D8(){try{await dU(),await fU(),await ui(ai.generateAllServiceConfigs())}catch(e){throw we?.disconnect(),e}}a(D8,"startAllServices");async function IT(e,t=!1){try{let r;switch(e=e.toLowerCase(),e){case Me.PROCESS_DESCRIPTORS.HDB.toLowerCase():r=ai.generateMainServerConfig();break;case Me.PROCESS_DESCRIPTORS.CLUSTERING_INGEST_SERVICE.toLowerCase():r=ai.generateNatsIngestServiceConfig();break;case Me.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE.toLowerCase():r=ai.generateNatsReplyServiceConfig();break;case Me.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase():r=ai.generateNatsHubServerConfig(),await ui(r,t),await bs.removeNatsConfig(e);return;case Me.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase():r=ai.generateNatsLeafServerConfig(),await ui(r,t),await bs.removeNatsConfig(e);return;case Me.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0.toLowerCase():r=ai.generateClusteringUpgradeV4ServiceConfig();break;default:throw new Error(`Start service called with unknown service config: ${e}`)}await ui(r)}catch(r){throw we?.disconnect(),r}}a(IT,"startService");async function cU(){try{let e=await wT(),t={};for(let r=0,n=e.length;r<n;r++){let s=e[r];t[s.name]===void 0&&(t[s.name]={name:s.name,exec_mode:s.pm2_env.exec_mode})}return t}catch(e){throw we?.disconnect(),e}}a(cU,"getUniqueServicesList");async function L8(e=[]){try{let t=!1,r=await cU();for(let n=0,s=Object.values(r).length;n<s;n++){let o=Object.values(r)[n].name;e.includes(o)||(o===Me.PROCESS_DESCRIPTORS.HDB?t=!0:await iU(o))}t&&await lU(Me.PROCESS_DESCRIPTORS.HDB)}catch(t){throw we?.disconnect(),t}}a(L8,"restartAllServices");async function uU(e){if(dr?.find(r=>r.name===e))return!0;let t=await g8.getHDBProcessInfo();return t.core.length&&t.core[0]?.parent==="PM2"}a(uU,"isServiceRegistered");async function lU(e){let t=e===Me.PROCESS_DESCRIPTORS.HDB?xd.get(Me.HDB_SETTINGS_NAMES.MAX_HDB_PROCESSES):xd.get(Me.HDB_SETTINGS_NAMES.MAX_CUSTOM_FUNCTION_PROCESSES),r=await aU(e),n=p8.isEmptyOrZeroLength(r)?0:r.length;t!==n?(await yT(e),await IT(e)):e===Me.PROCESS_DESCRIPTORS.HDB?await oU():await sU(e)}a(lU,"reloadStopStart");var _U;async function dU(e=!1){for(let t in Me.CLUSTERING_PROCESSES){let r=Me.CLUSTERING_PROCESSES[t];await IT(r,e)}}a(dU,"startClusteringProcesses");async function fU(){_U=rU(Me.LAUNCH_SERVICE_SCRIPTS.NATS_REPLY_SERVICE,{name:Me.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE}),await Nu.createWorkQueueStream(Jn.WORK_QUEUE_CONSUMER_NAMES),await Nu.updateIngestStreamConsumer(),await Nu.updateLocalStreams();let e=await S8.getAllNodeRecords();for(let t=0,r=e.length;t<r;t++)if(e[t].system_info?.hdb_version===Me.PRE_4_0_0_VERSION){ci.info("Starting clustering upgrade 4.0.0 process"),rU(Me.LAUNCH_SERVICE_SCRIPTS.NODES_UPGRADE_4_0_0,{name:"Upgrade-4-0-0"});break}}a(fU,"startClusteringThreads");async function M8(){for(let e in Me.CLUSTERING_PROCESSES)if(e!==Me.CLUSTERING_PROCESSES.CLUSTERING_INGEST_PROC_DESCRIPTOR)if(e===Me.CLUSTERING_PROCESSES.CLUSTERING_REPLY_SERVICE_DESCRIPTOR)await _U.terminate();else{let t=Me.CLUSTERING_PROCESSES[e];await yT(t)}}a(M8,"stopClustering");async function U8(){for(let e in Me.CLUSTERING_PROCESSES){let t=Me.CLUSTERING_PROCESSES[e];if(await uU(t)===!1)return!1}return!0}a(U8,"isClusteringRunning");async function P8(){await bs.generateNatsConfig(!0),await Nu.reloadNATSHub(),await Nu.reloadNATSLeaf(),await bs.removeNatsConfig(Me.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase()),await bs.removeNatsConfig(Me.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())}a(P8,"reloadClustering")});var kd=g((yfe,AU)=>{"use strict";var v8=require("minimist"),{isMainThread:LT,parentPort:SU}=require("worker_threads"),rt=M(),{PROCESS_DESCRIPTORS_VALIDATE:wu}=rt,jn=Y(),MT=J(),qd=NT(),da=ft(),CT=tt(),TU=wr(),Xn=hU(),mU=aa(),B8=nh(),{restartWorkers:Fd,onMessageByType:H8}=Ze(),{handleHDBError:x8,hdb_errors:q8}=ee(),{HTTP_STATUS_CODES:F8}=q8,Gd=Z();Gd.initSync();var Iu=`Restarting HarperDB. This may take up to ${rt.RESTART_TIMEOUT_MS/1e3} seconds.`,G8="Restart is not available from the CLI when running in non-pm2 mode. Either call restart from the API or stop and start HarperDB.",pU="Clustering is not enabled so cannot be restarted",k8="Invalid service",fa,nn;AU.exports={restart:gU,restartService:UT};LT&&H8(rt.ITC_EVENT_TYPES.RESTART,e=>{e.workerType?UT({service:e.workerType}):gU({operation:"restart"})});async function gU(e){nn=Object.keys(e).length===0,fa=await Xn.isServiceRegistered(rt.HDB_PROC_DESCRIPTOR);let t=v8(process.argv);if(t.service){await UT(t);return}if(nn&&!fa){console.error(G8);return}if(nn&&console.log(Iu),fa){Xn.enterPM2Mode(),jn.notify(Iu);let r=B8(Object.keys(rt.CONFIG_PARAM_MAP),!0);return MT.isEmptyOrZeroLength(Object.keys(r))||TU.updateConfigValue(void 0,void 0,r,!0,!0),$8(),Iu}return LT?(jn.notify(Iu),setTimeout(()=>{Fd()},50)):SU.postMessage({type:rt.ITC_EVENT_TYPES.RESTART}),Iu}a(gU,"restart");async function UT(e){let{service:t}=e;if(rt.PROCESS_DESCRIPTORS_VALIDATE[t]===void 0)throw x8(new Error,k8,F8.BAD_REQUEST,void 0,void 0,!0);if(fa=await Xn.isServiceRegistered(rt.HDB_PROC_DESCRIPTOR),!LT)return SU.postMessage({type:rt.ITC_EVENT_TYPES.RESTART,workerType:t}),t==="custom_functions"&&(t="Custom Functions"),`Restarting ${t}`;let r;switch(t){case wu.clustering:if(!Gd.get(rt.CONFIG_PARAMS.CLUSTERING_ENABLED)){r=pU;break}nn&&console.log("Restarting clustering"),jn.notify("Restarting clustering"),await RU();break;case wu.clustering_config:case wu["clustering config"]:if(!Gd.get(rt.CONFIG_PARAMS.CLUSTERING_ENABLED)){r=pU;break}nn&&console.log("Restarting clustering_config"),jn.notify("Restarting clustering_config"),await Xn.reloadClustering();break;case"custom_functions":case"custom functions":case wu.harperdb:case wu.http_workers:if(nn&&!fa){r=`Restart ${t} is not available from the CLI when running in non-pm2 mode. Either call restart ${t} from the API or stop and start HarperDB.`;break}nn&&console.log("Restarting http_workers"),jn.notify("Restarting http_workers"),nn?await Xn.restart(rt.HDB_PROC_DESCRIPTOR):setTimeout(()=>{Fd("http")},200);break;default:r=`Unrecognized service: ${t}`;break}return r?(jn.error(r),nn&&console.error(r),r):(t==="custom_functions"&&(t="Custom Functions"),`Restarting ${t}`)}a(UT,"restartService");async function V8(){await da.publishToStream(`${CT.SUBJECT_PREFIXES.TXN}.${CT.WORK_QUEUE_CONSUMER_NAMES.stream_name}`,CT.WORK_QUEUE_CONSUMER_NAMES.stream_name,da.addNatsMsgHeader({operation:"dummy_msg"},void 0),{operation:"dummy_msg"})}a(V8,"postDummyNatsMsg");async function $8(){await RU(),await Xn.restart(rt.HDB_PROC_DESCRIPTOR),await MT.async_set_timeout(2e3),Gd.get(rt.CONFIG_PARAMS.CLUSTERING_ENABLED)&&await DT(),nn&&(await da.closeConnection(),process.exit(0))}a($8,"restartPM2Mode");async function RU(){if(!TU.getConfigFromFile(rt.CONFIG_PARAMS.CLUSTERING_ENABLED))return;if((await mU.getHDBProcessInfo()).clustering.length===0)jn.trace("Clustering not running, restart will start clustering services"),await qd.generateNatsConfig(!0),await Xn.startClusteringProcesses(),await Xn.startClusteringThreads(),await DT(),nn&&await da.closeConnection();else{await V8(),await qd.generateNatsConfig(!0),fa?(jn.trace("Restart clustering restarting PM2 managed Hub and Leaf servers"),await Xn.restart(rt.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await Xn.restart(rt.PROCESS_DESCRIPTORS.CLUSTERING_LEAF)):(await mU.getHDBProcessInfo()).clustering.forEach(s=>{jn.trace("Restart clustering killing process pid",s.pid),process.kill(s.pid)}),await MT.async_set_timeout(3e3),await DT(),await da.updateLocalStreams(),nn&&await da.closeConnection(),jn.trace("Restart clustering restarting ingest and reply service threads");let t=Fd(rt.LAUNCH_SERVICE_SCRIPTS.NATS_INGEST_SERVICE),r=Fd(rt.LAUNCH_SERVICE_SCRIPTS.NATS_REPLY_SERVICE);await t,await r}}a(RU,"restartClustering");async function DT(){await qd.removeNatsConfig(rt.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await qd.removeNatsConfig(rt.PROCESS_DESCRIPTORS.CLUSTERING_LEAF)}a(DT,"removeNatsConfig")});var UU=g((Cfe,MU)=>{"use strict";var Ife=require("lodash"),fr=M(),{handleHDBError:OU,hdb_errors:Y8}=ee(),{HDB_ERROR_MSGS:K8,HTTP_STATUS_CODES:W8}=Y8,PT=Y();MU.exports={getRolePermissions:z8};var oo=Object.create(null),Q8=a(e=>({key:e,perms:{}}),"perms_template_obj"),wU=a((e=!1)=>({describe:e,tables:{}}),"schema_perms_template"),IU=a((e=!1,t=!1,r=!1,n=!1)=>({[fr.PERMS_CRUD_ENUM.READ]:e,[fr.PERMS_CRUD_ENUM.INSERT]:t,[fr.PERMS_CRUD_ENUM.UPDATE]:r,[fr.PERMS_CRUD_ENUM.DELETE]:n}),"permissions_template"),vT=a((e=!1,t=!1,r=!1,n=!1,s=!1)=>({attribute_permissions:[],describe:e,...IU(t,r,n,s)}),"table_perms_template"),bU=a((e,t=IU())=>({attribute_name:e,describe:LU(t),[Cu]:t[Cu],[BT]:t[BT],[HT]:t[HT]}),"attr_perms_template"),NU=a((e,t=!1)=>({attribute_name:e,describe:t,[Cu]:t}),"timestamp_attr_perms_template"),{READ:Cu,INSERT:BT,UPDATE:HT}=fr.PERMS_CRUD_ENUM,CU=Object.values(fr.PERMS_CRUD_ENUM),DU=[Cu,BT,HT];function z8(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[fr.SYSTEM_SCHEMA_NAME],t=e.role;let n=JSON.stringify([e.__updatedtime__,r]);if(oo[t]&&oo[t].key===n)return oo[t].perms;let s=J8(e,r);return oo[t]?oo[t].key=n:oo[t]=Q8(n),oo[t].perms=s,s}catch(r){if(!e[fr.TIME_STAMP_NAMES_ENUM.UPDATED_TIME]||e[fr.TIME_STAMP_NAMES_ENUM.UPDATED_TIME]<fr.PERMS_UPDATE_RELEASE_TIMESTAMP){let n=`Role permissions for role '${t}' must be updated to align with new structure from the 2.2.0 release.`;throw PT.error(n),PT.debug(r),OU(new Error,K8.OUTDATED_PERMS_TRANSLATION_ERROR,W8.BAD_REQUEST)}else{let n=`There was an error while translating role permissions for role: ${t}.
|
|
11
|
-
${r.stack}`;throw PT.error(n),OU(new Error)}}}a(z8,"getRolePermissions");function J8(e,t){let r=Object.create(null);r.super_user=!1;let n=e.permission;r[fr.SYSTEM_SCHEMA_NAME]=n[fr.SYSTEM_SCHEMA_NAME],r.structure_user=n.structure_user;let s=Array.isArray(e.permission.structure_user)||e.permission.structure_user===!0?e.permission.structure_user:[];return Object.keys(t).forEach(i=>{if(s===!0||s.indexOf(i)>-1){r[i]=j8(t[i]);return}r[i]=wU(),n[i]?(n[i].describe&&(r[i].describe=!0),Object.keys(t[i]).forEach(o=>{if(n[i].tables[o]){let c=n[i].tables[o],u=t[i][o],_=X8(c,u);r[i].describe||CU.forEach(l=>{_[l]&&(r[i].describe=!0)}),r[i].tables[o]=_}else r[i].tables[o]=vT()})):Object.keys(t[i]).forEach(o=>{r[i].tables[o]=vT()})}),r}a(J8,"translateRolePermissions");function j8(e){let t=wU(!0);return Object.keys(e).forEach(r=>{t.tables[r]=vT(!0,!0,!0,!0,!0)}),t}a(j8,"createStructureUserPermissions");function X8(e,t){let{attribute_permissions:r}=e;if(r.length>0){let s=Object.assign({},e);s.attribute_permissions=[];let i=r.reduce((_,l)=>{let{attribute_name:d}=l,f=l;return fr.TIME_STAMP_NAMES.includes(d)&&(f=NU(d,l[Cu])),_[d]=f,_},{}),o=t.primaryKey||t.hash_attribute,c=!!i[o],u=bU(o);return t.attributes.forEach(({attribute:_})=>{if(i[_]){let l=i[_];l.describe=LU(l),s.attribute_permissions.push(l),c||Z8(l,u)}else if(_!==o){let l;fr.TIME_STAMP_NAMES.includes(_)?l=NU(_):l=bU(_),s.attribute_permissions.push(l)}}),c||s.attribute_permissions.push(u),s.describe=yU(s),s}else return e.describe=yU(e),e}a(X8,"getTableAttrPerms");function yU(e){return CU.filter(t=>e[t]).length>0}a(yU,"getSchemaTableDescribePerm");function LU(e){return DU.filter(t=>e[t]).length>0}a(LU,"getAttributeDescribePerm");function Z8(e,t){DU.forEach(r=>{e[r]&&!t[r]&&(t[r]=!0,t.describe=!0)})}a(Z8,"checkForHashPerms")});var PU={};Ve(PU,{Resources:()=>Vd,keyArrayToString:()=>Ea,resetResources:()=>e6,resources:()=>li});function e6(){return li=new Vd}function Ea(e){return Array.isArray(e)?e[e.length-1]===null?e.slice(0,-1).join("/")+"/":e.join("/"):e}var Vd,li,Du=Oe(()=>{Wi();Vd=class extends Map{static{a(this,"Resources")}isWorker=!0;loginPath;set(t,r,n,s){if(!r)throw new Error("Must provide a resource");t.startsWith("/")&&(t=t.replace(/^\/+/,""));let i={Resource:r,path:t,type:n,hasSubPaths:!1,relativeURL:""},o=super.get(t);if(o&&(o.Resource.databaseName!==r.databaseName||o.Resource.tableName!==r.tableName)&&!s)throw new Error(`Conflicting paths for ${t}`);super.set(t,i);for(let[c,u]of this){let _=2;for(;(_=c.indexOf("/",_))>-1;){let l=this.get(c.slice(0,_));l&&(l.hasSubPaths=!0),_+=2}}}getMatch(t,r){let n=2,s;for(;(n=t.indexOf("/",n))>-1;){let c=t.slice(0,n),u=this.get(c);if(u){if(u.relativeURL=t.slice(n),!u.hasSubPaths)return u;s=u}n+=2}if(s)return s;let i=t.indexOf("?"),o=i>-1?t.slice(0,i):t;return s=this.get(o),s?s.relativeURL=i>-1?t.slice(i):"":s||(s=this.get(""),s&&(t[0]!=="/"&&(t="/"+t),s.relativeURL=t)),s}getResource(t,r){let n=this.getMatch(t);if(n)return t=n.relativeURL,n.Resource.getResource(this.pathToId(t,n.Resource),r)}call(t,r,n){return We(r,async()=>{let s=this.getMatch(t);if(s)return t=s.relativeURL,n(s.Resource,s.path,t)})}setRepresentation(t,r,n){}};a(e6,"resetResources");a(Ea,"keyArrayToString")});var vU={};Ve(vU,{Headers:()=>_i});var _i,$d=Oe(()=>{_i=class extends Map{static{a(this,"Headers")}set(t,r){return typeof t!="string"&&(t=""+t),typeof r!="string"&&(r=""+r),super.set(t.toLowerCase(),[t,r])}get(t){return typeof t!="string"&&(t=""+t),super.get(t.toLowerCase())?.[1]}has(t){return typeof t!="string"&&(t=""+t),super.has(t.toLowerCase())}setIfNone(t,r){typeof t!="string"&&(t=""+t),typeof r!="string"&&(r=""+r);let n=t.toLowerCase();if(!super.has(n))return super.set(n,[t,r])}append(t,r,n){typeof t!="string"&&(t=""+t),typeof r!="string"&&(r=""+r);let s=t.toLowerCase(),i=super.get(s);if(i){let o=i[1];n?r=(typeof o=="string"?o:o.join(", "))+", "+r:typeof o=="string"?r=[o,r]:o.push(r)}return super.set(s,[t,r])}[Symbol.iterator](){return super.values()[Symbol.iterator]()}}});var Lu={};Ve(Lu,{authentication:()=>VU,bypassAuth:()=>a6,login:()=>u6,logout:()=>l6,start:()=>c6});function a6(){kU=!0}async function VU(e,t){let r=e.headers.asObject,n=r.authorization,s=r.cookie,i=r.origin,o=[];try{if(i){let E=e.isOperationsServer?s6?n6:[]:r6?t6:[];if(E.includes(i)||E.includes("*")){if(e.method==="OPTIONS"){let h=new _i([["Access-Control-Allow-Methods","POST, GET, PUT, DELETE, PATCH, OPTIONS"],["Access-Control-Allow-Headers","Accept, Content-Type, Authorization"],["Access-Control-Allow-Origin",i]]);return Yd&&h.set("Access-Control-Allow-Credentials","true"),{status:200,headers:h}}o.push("Access-Control-Allow-Origin",i),Yd&&o.push("Access-Control-Allow-Credentials","true")}}let u,_;if(Yd){let E=(i?i.replace(/^https?:\/\//,"").replace(/\W/,"_")+"-":"")+"hdb-session=",h=s?.indexOf(E);if(h>=0){let p=s.indexOf(";",h),S=s.indexOf("=",h);u=s.slice(S+1,p===-1?s.length:p),_=await HU.get(u)}e.session=_||(_={})}e.user=null;let l=a((E,h,p)=>{let S=new Wd.AuthAuditLog(E,h,qt.AUTH_AUDIT_TYPES.AUTHENTICATION,r["x-forwarded-for"]??e.ip,e.method,e.pathname);S.auth_strategy=p,u&&(S.session_id=u),r.referer&&(S.referer=r.referer),r.origin&&(S.origin=r.origin),h===qt.AUTH_AUDIT_STATUS.SUCCESS?BU.notify(S):BU.error(S)},"authAuditLog");if(e.mtlsConfig&&e.authorized){let E=e.mtlsConfig.user;E!==null&&((E===void 0||E==="Common Name"||E==="CN")&&(E=e.peerCertificate.subject.CN),e.user=await Xe.getUser(E,null,null))}let d;if(!e.user)if(n){if(d=ao.get(n),!d){let[E,h]=n.split(" "),p,S;try{switch(E){case"Basic":[p,S]=atob(h).split(":"),d=p||S?await Xe.getUser(p,S,e):null;break;case"Bearer":try{d=await(0,Kd.validateOperationToken)(h)}catch(T){if(T.message==="invalid token")try{return await(0,Kd.validateRefreshToken)(h),c({status:-1})}catch{throw T}}break}}catch(T){return o6&&(ao.get(h)||(ao.set(h,h),l(p,qt.AUTH_AUDIT_STATUS.FAILURE,E))),c({status:401,body:di({error:T.message},e)})}ao.set(n,d),i6&&l(d.username,qt.AUTH_AUDIT_STATUS.SUCCESS,E)}e.user=d}else _?.user?e.user=await Xe.getUser(_.user,null,e):(kU&&(e.ip?.includes("127.0.0.1")||e.ip=="::1")||e?._nodeRequest?.socket?.server?._pipeName&&e.ip===void 0)&&(e.user=await(0,qU.getSuperUser)());Yd&&(e.session.update=function(E){if(!u){u=(0,FU.v4)();let p=`${(i?i.replace(/^https?:\/\//,"").replace(/\W/,"_")+"-":"")+"hdb-session="}${u}; Path=/; Expires=Tue, 01 Oct 8307 19:33:20 GMT; HttpOnly${e.protocol==="https"?"; SameSite=None; Secure":""}`;o?o.push("Set-Cookie",p):f?.headers?.set&&f.headers.set("Set-Cookie",p)}return e.protocol==="https"&&(o?(i&&o.push("Access-Control-Expose-Headers","X-Hdb-Session"),o.push("X-Hdb-Session","Secure")):f?.headers?.set&&(i&&f.headers.set("Access-Control-Expose-Headers","X-Hdb-Session"),f.headers.set("X-Hdb-Session","Secure"))),E.id=u,HU.put(E)},e.login=async function(E,h){e.user=await Xe.getUser(E,h,e),e.session.update({user:e.user.username})},(d&&!_||_?.user?.username!==d?.username)&&r["user-agent"]?.startsWith("Mozilla")&&e.session.update({user:e.user.username}));let f=await t(e);return f&&(f.status===401&&(r["user-agent"]?.startsWith("Mozilla")&&r.accept?.startsWith("text/html")&&li.loginPath?(f.status=302,f.headers.set("Location",li.loginPath(e))):f.headers.set("WWW-Authenticate","Basic")),c(f))}catch(u){throw c(u)}function c(u){let _=o.length;if(_>0){let l=u.headers;l||(u.headers=l=new _i);for(let d=0;d<_;){let f=o[d++];l.set(f,o[d++])}}return o=null,u}a(c,"applyResponseHeaders")}function c6({server:e,port:t}){e.request(VU,{port:t||"all"}),xU||(xU=!0,setInterval(()=>{ao=new Map},sn.get(qt.CONFIG_PARAMS.AUTHENTICATION_CACHETTL)).unref(),GU.user.addListener(()=>{ao=new Map}))}async function u6(e){if(!e.baseRequest?.login)throw new Error("No session for login");return e.baseResponse.headers.set=(t,r)=>{e.fastifyResponse.header(t,r)},await e.baseRequest.login(e.username,e.password),"Login successful"}async function l6(e){if(!e.baseRequest.session)throw new Error("No session for logout");return await e.baseRequest.session.update({user:null}),"Logout successful"}var qU,Kd,FU,sn,qt,Wd,GU,BU,t6,r6,n6,s6,HU,Yd,kU,i6,o6,ao,xU,Qd=Oe(()=>{qU=B(Mr());Zt();Du();Kd=B(_u());be();FU=require("uuid"),sn=B(Z()),qt=B(M()),Wd=B(Y()),GU=B(Mc());$d();ha();BU=(0,Wd.loggerWithTag)("auth-event");sn.initSync();t6=sn.get(qt.CONFIG_PARAMS.HTTP_CORSACCESSLIST),r6=sn.get(qt.CONFIG_PARAMS.HTTP_CORS),n6=sn.get(qt.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_CORSACCESSLIST),s6=sn.get(qt.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_CORS),HU=ot({table:"hdb_session",database:"system",attributes:[{name:"id",isPrimaryKey:!0},{name:"user"}]}),Yd=sn.get(qt.CONFIG_PARAMS.AUTHENTICATION_ENABLESESSIONS)??!0,kU=sn.get(qt.CONFIG_PARAMS.AUTHENTICATION_AUTHORIZELOCAL)??process.env.DEV_MODE,i6=sn.get(qt.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)??!1,o6=sn.get(qt.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGFAILED)??!1,ao=new Map;Xe.onInvalidatedUser(()=>{ao=new Map});a(a6,"bypassAuth");a(VU,"authentication");a(c6,"start");a(u6,"login");a(l6,"logout")});var JU=g((Ffe,zU)=>{"use strict";var Ie=require("joi"),$U=require("fs-extra"),YU=require("path"),ws=je(),KU=Z(),WU=M(),QU=Y(),{hdb_errors:_6}=ee(),{HDB_ERROR_MSGS:Qt}=_6,ys=/^[a-zA-Z0-9-_]+$/;zU.exports={getDropCustomFunctionValidator:f6,setCustomFunctionValidator:E6,addComponentValidator:S6,dropCustomFunctionProjectValidator:T6,packageComponentValidator:g6,deployComponentValidator:R6,setComponentFileValidator:h6,getComponentFileValidator:p6,dropComponentFileValidator:m6};function zd(e,t,r){try{let n=KU.get(WU.CONFIG_PARAMS.COMPONENTSROOT),s=YU.join(n,t);return $U.existsSync(s)?e?t:r.message(Qt.PROJECT_EXISTS):e?r.message(Qt.NO_PROJECT):t}catch(n){return QU.error(n),r.message(Qt.VALIDATION_ERR)}}a(zd,"checkProjectExists");function Mu(e,t){return e.includes("..")?t.message("Invalid file path"):e}a(Mu,"checkFilePath");function d6(e,t,r,n){try{let s=KU.get(WU.CONFIG_PARAMS.COMPONENTSROOT),i=YU.join(s,e,t,r+".js");return $U.existsSync(i)?r:n.message(Qt.NO_FILE)}catch(s){return QU.error(s),n.message(Qt.VALIDATION_ERR)}}a(d6,"checkFileExists");function f6(e){let t=Ie.object({project:Ie.string().pattern(ys).custom(zd.bind(null,!0)).required().messages({"string.pattern.base":Qt.BAD_PROJECT_NAME}),type:Ie.string().valid("helpers","routes").required(),file:Ie.string().pattern(ys).custom(d6.bind(null,e.project,e.type)).custom(Mu).required().messages({"string.pattern.base":Qt.BAD_FILE_NAME})});return ws.validateBySchema(e,t)}a(f6,"getDropCustomFunctionValidator");function E6(e){let t=Ie.object({project:Ie.string().pattern(ys).custom(zd.bind(null,!0)).required().messages({"string.pattern.base":Qt.BAD_PROJECT_NAME}),type:Ie.string().valid("helpers","routes").required(),file:Ie.string().custom(Mu).required(),function_content:Ie.string().required()});return ws.validateBySchema(e,t)}a(E6,"setCustomFunctionValidator");function h6(e){let t=Ie.object({project:Ie.string().pattern(ys).required().messages({"string.pattern.base":Qt.BAD_PROJECT_NAME}),file:Ie.string().custom(Mu).required(),payload:Ie.string().allow("").optional(),encoding:Ie.string().valid("utf8","ASCII","binary","hex","base64","utf16le","latin1","ucs2").optional()});return ws.validateBySchema(e,t)}a(h6,"setComponentFileValidator");function m6(e){let t=Ie.object({project:Ie.string().pattern(ys).required().messages({"string.pattern.base":Qt.BAD_PROJECT_NAME}),file:Ie.string().custom(Mu).optional()});return ws.validateBySchema(e,t)}a(m6,"dropComponentFileValidator");function p6(e){let t=Ie.object({project:Ie.string().required(),file:Ie.string().custom(Mu).required(),encoding:Ie.string().valid("utf8","ASCII","binary","hex","base64","utf16le","latin1","ucs2").optional()});return ws.validateBySchema(e,t)}a(p6,"getComponentFileValidator");function S6(e){let t=Ie.object({project:Ie.string().pattern(ys).custom(zd.bind(null,!1)).required().messages({"string.pattern.base":Qt.BAD_PROJECT_NAME})});return ws.validateBySchema(e,t)}a(S6,"addComponentValidator");function T6(e){let t=Ie.object({project:Ie.string().pattern(ys).custom(zd.bind(null,!0)).required().messages({"string.pattern.base":Qt.BAD_PROJECT_NAME})});return ws.validateBySchema(e,t)}a(T6,"dropCustomFunctionProjectValidator");function g6(e){let t=Ie.object({project:Ie.string().pattern(ys).required().messages({"string.pattern.base":Qt.BAD_PROJECT_NAME}),skip_node_modules:Ie.boolean()});return ws.validateBySchema(e,t)}a(g6,"packageComponentValidator");function R6(e){let t=Ie.object({project:Ie.string().pattern(ys).required().messages({"string.pattern.base":Qt.BAD_PROJECT_NAME}),payload:Ie.string().optional().messages({"string.pattern.base":Qt.BAD_PACKAGE}),package:Ie.string().optional()});return ws.validateBySchema(e,t)}a(R6,"deployComponentValidator")});var Zd=g((kfe,nP)=>{"use strict";var Jd=require("joi"),jd=require("path"),jU=require("fs-extra"),{exec:A6}=require("child_process"),O6=require("util"),XU=O6.promisify(A6),Uu=M(),{handleHDBError:ma,hdb_errors:b6}=ee(),{HTTP_STATUS_CODES:pa}=b6,Pu=Z(),N6=je(),Sa=Y();Pu.initSync();var xT=Pu.get(Uu.CONFIG_PARAMS.COMPONENTSROOT),ZU="npm install --omit=dev --json",y6=`${ZU} --dry-run`;nP.exports={installModules:D6,auditModules:L6,installAllRootModules:w6,uninstallRootModule:I6,linkHarperdb:C6};async function w6(e=!1){await Xd(),await vu(e?"npm install --ignore-scripts":"npm install",Pu.get(Uu.CONFIG_PARAMS.ROOTPATH))}a(w6,"installAllRootModules");async function I6(e){await vu(`npm uninstall ${e}`,Pu.get(Uu.CONFIG_PARAMS.ROOTPATH))}a(I6,"uninstallRootModule");async function C6(){await Xd(),await vu(`npm link ${Uu.PACKAGE_ROOT}`,Pu.get(Uu.CONFIG_PARAMS.ROOTPATH))}a(C6,"linkHarperdb");async function vu(e,t=void 0){let r,n;try{({stdout:r,stderr:n}=await XU(e,{cwd:t}))}catch(s){throw new Error(s.stderr.replace(`
|
|
12
|
-
`,""))}return n&&!n.includes("Debugger listening")&&
|
|
13
|
-
`,"")}a(
|
|
10
|
+
`,"")}a(dD,"runCommand");async function V4(){try{await R4.access(tS)}catch{return!1}let e=await dD(`${tS} --version`,void 0),t=e.substring(e.lastIndexOf("v")+1,e.length);return A4.eq(t,G4)}a(V4,"checkNATSServerInstalled");async function iS(e,t,r,n=!0,s="127.0.0.1"){if(!t&&!r){let o=await cD.getClusterUser();if(to(o))throw new Error("Unable to get nats connection. Cluster user is undefined.");t=o.username,r=o.decrypt_hash}xr.trace("create nats connection called");let i=await U4({name:s,port:e,user:t,pass:r,maxReconnectAttempts:-1,waitOnFirstConnect:n,timeout:2e5,tls:{keyFile:Ht.get(Pe.CONFIG_PARAMS.CLUSTERING_TLS_PRIVATEKEY),certFile:Ht.get(Pe.CONFIG_PARAMS.CLUSTERING_TLS_CERTIFICATE),caFile:Ht.get(Pe.CONFIG_PARAMS.CLUSTERING_TLS_CERT_AUTH),rejectUnauthorized:!1}});return i.protocol.transport.socket.unref(),xr.trace("create connection established a nats client connection with id",i?.info?.client_id),i.closed().then(o=>{o&&xr.error("Error with Nats client connection, connection closed",o),fD()}),i}a(iS,"createConnection");function fD(){rn=void 0,Xi=void 0,Zi=void 0,eo=void 0}a(fD,"clearClientCache");async function $4(){rn&&(await rn.drain(),rn=void 0,Xi=void 0,Zi=void 0,eo=void 0)}a($4,"closeConnection");var rn,eo;async function rd(){return eo||(eo=iS(Ht.get(Pe.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),void 0,void 0),rn=await eo),rn||eo}a(rd,"getConnection");async function ou(){if(Xi)return Xi;to(rn)&&await rd();let{domain:e}=au(Pe.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);if(to(e))throw new Error("Error getting JetStream domain. Unable to get JetStream manager.");return Xi=await rn.jetstreamManager({domain:e,timeout:6e4}),Xi}a(ou,"getJetStreamManager");async function ED(){if(Zi)return Zi;to(rn)&&await rd();let{domain:e}=au(Pe.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);if(to(e))throw new Error("Error getting JetStream domain. Unable to get JetStream manager.");return Zi=rn.jetstream({domain:e,timeout:6e4}),Zi}a(ED,"getJetStream");async function sr(){let e=rn||await rd(),t=Xi||await ou(),r=Zi||await ED();return{connection:e,jsm:t,js:r}}a(sr,"getNATSReferences");async function Y4(e){let t=Ht.get(Pe.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),{sys_name:r,decrypt_hash:n}=await cD.getClusterUser(),s=await iS(t,r,n),i=sS(),o=s.subscribe(i),c=[],u,_=(async()=>{for await(let l of o){let d=_D.decode(l.data);d.response_time=Date.now()-u,c.push(d)}})();return u=Date.now(),await s.publish("$SYS.REQ.SERVER.PING.VARZ",void 0,{reply:i}),await s.publish("$SYS.REQ.SERVER.PING",void 0,{reply:i}),await s.flush(),await rS.async_set_timeout(e),await o.drain(),await s.close(),await _,c}a(Y4,"getServerList");async function oS(e,t){let{jsm:r}=await sr(),n=Ht.get(Pe.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE);n=n===null?0:n*1e9;let s=Ht.get(Pe.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS);s=s===null?-1:s;let i=Ht.get(Pe.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES);i=i===null?-1:i,await r.streams.add({name:e,storage:uD.File,retention:lD.Limits,subjects:t,discard:P4.Old,max_msgs:s,max_bytes:i,max_age:n})}a(oS,"createLocalStream");async function hD(){let{jsm:e}=await sr(),t=await e.streams.list().next(),r=[];return t.forEach(n=>{r.push(n)}),r}a(hD,"listStreams");async function K4(e){let{jsm:t}=await sr();await t.streams.delete(e)}a(K4,"deleteLocalStream");async function W4(e){let{connection:t}=await sr(),r=[],n=sS(),s=t.subscribe(n),i=(async()=>{for await(let o of s)r.push(_D.decode(o.data))})();return await t.publish(`$JS.${e}.API.STREAM.LIST`,void 0,{reply:n}),await t.flush(),await s.drain(),await i,r}a(W4,"listRemoteStreams");async function Q4(e,t=void 0,r=void 0){let{jsm:n,js:s}=await sr(),i=iD(),o={durable_name:i,ack_policy:ed.Explicit};t&&(o.deliver_policy=td.StartTime,o.opt_start_time=new Date(t).toISOString()),await n.consumers.add(e,o);let c=await s.consumers.get(e,i),u=r?await c.fetch({max_messages:r,expires:2e3}):await c.consume();if(c._info.num_pending===0)return[];let _=[];for await(let l of u){let d=nS(l.data),f={nats_timestamp:l.info.timestampNanos,nats_sequence:l.info.streamSequence,entry:d};if(l.headers&&(f.origin=l.headers.get(Ne.MSG_HEADERS.ORIGIN)),_.push(f),l.ack(),l.info.pending===0)break}return await c.delete(),_}a(Q4,"viewStream");async function*z4(e,t=void 0,r=void 0){let{jsm:n,js:s}=await sr(),i=iD(),o={durable_name:i,ack_policy:ed.Explicit};t&&(o.deliver_policy=td.StartTime,o.opt_start_time=new Date(t).toISOString()),await n.consumers.add(e,o);let c=await s.consumers.get(e,i),u=r?await c.fetch({max_messages:r,expires:2e3}):await c.consume();if(c._info.num_pending===0)return[];for await(let _ of u){let l=nS(_.data);l[0]||(l=[l]);for(let d of l){let f={nats_timestamp:_.info.timestampNanos,nats_sequence:_.info.streamSequence,entry:d};_.headers&&(f.origin=_.headers.get(Ne.MSG_HEADERS.ORIGIN)),yield f}if(_.ack(),_.info.pending===0)break}await c.delete()}a(z4,"viewStreamIterator");async function J4(e,t,r,n){xr.trace(`publishToStream called with subject: ${e}, stream: ${t}, entries:`,n.operation),r=mD(n,r);let{js:s}=await sr(),i=await cu(),o=`${e}.${i}`,c=n instanceof Uint8Array?n:aD.encode(n);try{xr.trace(`publishToStream publishing to subject: ${o}`),q4(c.length,"bytes-sent",e,n.operation,"replication"),await s.publish(o,c,{headers:r})}catch(u){if(u.code&&u.code.toString()==="503")return gD(async()=>{try{await s.publish(o,c,{headers:r})}catch{if(u.code&&u.code.toString()==="503"){xr.trace(`publishToStream creating stream: ${t}`);let l=o.split(".");l[2]="*",await oS(t,[o]),await s.publish(o,c,{headers:r})}else throw u}});throw u}}a(J4,"publishToStream");function mD(e,t){t===void 0&&(t=B4());let r=Ht.get(Pe.CONFIG_PARAMS.CLUSTERING_NODENAME);return!t.has(Ne.MSG_HEADERS.ORIGIN)&&r&&t.append(Ne.MSG_HEADERS.ORIGIN,r),t}a(mD,"addNatsMsgHeader");function au(e){e=e.toLowerCase();let t=iu.join(Ht.get(Pe.CONFIG_PARAMS.ROOTPATH),F4);if(e===Pe.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase())return to(eS)&&(eS={port:nu.getConfigFromFile(Pe.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),server_name:nu.getConfigFromFile(Pe.CONFIG_PARAMS.CLUSTERING_NODENAME)+Ne.SERVER_SUFFIX.HUB,config_file:Ne.NATS_CONFIG_FILES.HUB_SERVER,pid_file_path:iu.join(t,Ne.PID_FILES.HUB),hdb_nats_path:t}),eS;if(e===Pe.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())return to(Zp)&&(Zp={port:nu.getConfigFromFile(Pe.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),server_name:nu.getConfigFromFile(Pe.CONFIG_PARAMS.CLUSTERING_NODENAME)+Ne.SERVER_SUFFIX.LEAF,config_file:Ne.NATS_CONFIG_FILES.LEAF_SERVER,domain:nu.getConfigFromFile(Pe.CONFIG_PARAMS.CLUSTERING_NODENAME)+Ne.SERVER_SUFFIX.LEAF,pid_file_path:iu.join(t,Ne.PID_FILES.LEAF),hdb_nats_path:t}),Zp;xr.error(`Unable to get Nats server config. Unrecognized process: ${e}`)}a(au,"getServerConfig");async function j4(e){let{jsm:t}=await sr(),r=await cu();try{await t.streams.add({name:e.stream_name,storage:uD.File,retention:lD.Limits,max_age:L4,max_bytes:M4,subjects:[`${Ne.SUBJECT_PREFIXES.TXN}.${e.stream_name}.${r}`]})}catch(n){if(n.code!=="400")throw n}try{await t.consumers.info(e.stream_name,e.durable_name)}catch(n){if(n.code.toString()==="404")await t.consumers.add(e.stream_name,{ack_policy:ed.Explicit,durable_name:e.durable_name,deliver_policy:td.All,max_ack_pending:1e4});else throw n}}a(j4,"createWorkQueueStream");async function X4(){let{jsm:e}=await sr();(await e.consumers.info(Ne.WORK_QUEUE_CONSUMER_NAMES.stream_name,Ne.WORK_QUEUE_CONSUMER_NAMES.durable_name)).config.deliver_subject&&(xr.info("Removing old nats push consumer from ingest stream"),await e.consumers.delete(Ne.WORK_QUEUE_CONSUMER_NAMES.stream_name,Ne.WORK_QUEUE_CONSUMER_NAMES.durable_name),xr.info("Adding pull consumer to ingest stream"),await e.consumers.add(Ne.WORK_QUEUE_CONSUMER_NAMES.stream_name,{ack_policy:ed.Explicit,durable_name:Ne.WORK_QUEUE_CONSUMER_NAMES.durable_name,deliver_policy:td.All,max_ack_pending:1e4}))}a(X4,"updateIngestStreamConsumer");async function pD(e,t,r){let{jsm:n}=await sr(),s=await n.streams.info(t),i=SD(n.prefix),o=r.start_time?r.start_time:new Date(Date.now()).toISOString(),{schema:c,table:u}=r,_=Z_.createNatsTableStreamName(c,u),l=i===e,d,f,E=!1;if(!Array.isArray(s.config.sources)||s.config.sources.length===0)s.config.sources=[];else for(let p=0,S=s.config.sources.length;p<S;p++)if(d=s.config.sources[p],f=p,l&&d.name===_||!l&&d.name===_&&d.external&&d.external.api===`$JS.${e}.API`){E=!0;break}if(E===!0){if(d.opt_start_time===o)return;let p=`txn.${c}.${u}.${e}`;await n.streams.purge(t,{filter:p}),s.config.sources.splice(f,1),await n.streams.update(t,s.config)}let h={name:_,opt_start_time:o,filter_subject:`${Ne.SUBJECT_PREFIXES.TXN}.>`};l||(h.external={api:`$JS.${e}.API`,deliver:""}),s.config.sources.push(h),await n.streams.update(t,s.config)}a(pD,"addSourceToWorkStream");function SD(e){return e.split(".")[1]}a(SD,"extractServerName");async function TD(e,t,r){let{jsm:n}=await sr(),{schema:s,table:i}=r,o=`txn.${s}.${i}.${e}`;await n.streams.purge(t,{filter:o});let c=Z_.createNatsTableStreamName(s,i),u=await n.streams.info(t);if(!Array.isArray(u.config.sources)||u.config.sources.length===0)return;let _=u.config.sources.length,l;for(;_--;)if(l=u.config.sources[_],l.name===c&&l.external.api===`$JS.${e}.API`){u.config.sources.splice(_,1);break}await n.streams.update(t,u.config)}a(TD,"removeSourceFromWorkStream");async function Z4(e,t,r=6e4,n=sS()){if(!rS.isObject(t))throw new Error("data param must be an object");let s=aD.encode(t),{connection:i}=await sr(),o={timeout:r};n&&(o.reply=n,o.noMux=!0);let c=await i.request(e,s,o);return nS(c.data)}a(Z4,"request");function aS(e){return new Promise(async(t,r)=>{let n=N4(tS,["--signal",`reload=${e}`],{cwd:__dirname}),s,i;n.on("error",o=>{r(o)}),n.stdout.on("data",o=>{i+=o.toString()}),n.stderr.on("data",o=>{s+=o.toString()}),n.stderr.on("close",o=>{s&&r(s),t(i)})})}a(aS,"reloadNATS");async function e3(){let{pid_file_path:e}=au(Pe.PROCESS_DESCRIPTORS.CLUSTERING_HUB);await aS(e)}a(e3,"reloadNATSHub");async function t3(){let{pid_file_path:e}=au(Pe.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);await aS(e)}a(t3,"reloadNATSLeaf");function r3(e,t,r){let n;switch(e.code){case sD.NoResponders:n=`Unable to ${t}, node '${r}' is not listening.`;break;case sD.Timeout:n=`Unable to ${t}, node '${r}' is listening but did not respond.`;break;default:n=e.message;break}return n}a(r3,"requestErrorHandler");async function n3(e,t){let r=t+Ne.SERVER_SUFFIX.LEAF;await gD(async()=>{e.subscribe===!0?await pD(r,Ne.WORK_QUEUE_CONSUMER_NAMES.stream_name,e):await TD(r,Ne.WORK_QUEUE_CONSUMER_NAMES.stream_name,e)})}a(n3,"updateWorkStream");function gD(e){return w4.writeTransaction(Pe.SYSTEM_SCHEMA_NAME,Pe.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,e)}a(gD,"exclusiveLock");async function RD(e,t){let r=Z_.createNatsTableStreamName(e,t),n=await cu(),s=a3(e,t,n);await oS(r,[s])}a(RD,"createLocalTableStream");async function s3(e){for(let t=0,r=e.length;t<r;t++){let n=e[t].schema,s=e[t].table;await RD(n,s)}}a(s3,"createTableStreams");async function AD(e,t,r=!1){if(Ht.get(Pe.CONFIG_PARAMS.CLUSTERING_ENABLED))try{let n=Z_.createNatsTableStreamName(e,t),{jsm:s}=await sr();r?await s.streams.purge(Ne.WORK_QUEUE_CONSUMER_NAMES.stream_name):await s.streams.purge(n)}catch(n){if(n.message==="stream not found")xr.warn(n);else throw n}}a(AD,"purgeTableStream");async function i3(e,t){if(Ht.get(Pe.CONFIG_PARAMS.CLUSTERING_ENABLED))for(let r=0,n=t.length;r<n;r++)await AD(e,t[r])}a(i3,"purgeSchemaTableStreams");async function o3(e){return(await ou()).streams.info(e)}a(o3,"getStreamInfo");function a3(e,t,r){return`${Ne.SUBJECT_PREFIXES.TXN}.${e}${t?"."+t:""}.${r}`}a(a3,"createSubjectName");async function cu(){if(su)return su;if(su=(await ou())?.nc?.info?.server_name,su===void 0)throw new Error("Unable to get jetstream manager server name");return su}a(cu,"getJsmServerName");async function c3(){let e=await ou(),t=await cu(),r=await hD();for(let n of r){let s=n.config,i=s.subjects[0];if(!i)continue;let o=u3(n),c=i.split(".");if(!(c[c.length-1]===t&&!o)){if(s.name===Ne.SCHEMA_QUEUE_CONSUMER_NAMES.stream_name){let _=`${Ne.SCHEMA_QUEUE_CONSUMER_NAMES.deliver_subject}.${t}`;xr.trace(`Updating stream subject name from: ${i} to: ${_}`),s.subjects[0]=_}else if(s.name===Ne.WORK_QUEUE_CONSUMER_NAMES.stream_name){let _=`${Ne.WORK_QUEUE_CONSUMER_NAMES.stream_name}.${t}`;xr.trace(`Updating stream subject name from: ${i} to: ${_}`),s.subjects[0]=_}else{let _=i.split(".");_[_.length-1]=t;let l=_.join(".");xr.trace(`Updating stream subject name from: ${i} to: ${l}`),s.subjects[0]=l}await e.streams.update(s.name,s)}}}a(c3,"updateLocalStreams");function u3(e){let{config:t}=e,r=!1;if(t.name===Ne.SCHEMA_QUEUE_CONSUMER_NAMES.stream_name||t.name===Ne.WORK_QUEUE_CONSUMER_NAMES.stream_name)return r;let n=Ht.get(Pe.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE);n=n===null?0:n*1e9;let s=Ht.get(Pe.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES);s=s===null?-1:s;let i=Ht.get(Pe.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS);return i=i===null?-1:i,n!==t.max_age&&(t.max_age=n,r=!0),s!==t.max_bytes&&(t.max_bytes=s,r=!0),i!==t.max_msgs&&(t.max_msgs=i,r=!0),r}a(u3,"updateStreamLimits")});var od=T((w_e,wD)=>{"use strict";var ta=d_(),ra=xC(),l3=K(),_3=require("uuid").v4,N_e=require("clone"),sd=Ts(),na=U(),d3=require("util"),ni=yn(),{handleHDBError:ir,hdb_errors:f3}=ee(),{HDB_ERROR_MSGS:nd,HTTP_STATUS_CODES:or}=f3,{SchemaEventMsg:id}=Nn(),bD=ft(),{getDatabases:E3}=(be(),te(qe)),{transformReq:sa}=J();wD.exports={createSchema:h3,createSchemaStructure:yD,createTable:m3,createTableStructure:ND,createAttribute:R3,dropSchema:p3,dropTable:S3,dropAttribute:T3,getBackup:A3};async function h3(e){let t=await yD(e);return sd.signalSchemaChange(new id(process.pid,e.operation,e.schema)),t}a(h3,"createSchema");async function yD(e){let t=ta.schema_object(e);if(t)throw ir(t,t.message,or.BAD_REQUEST,void 0,void 0,!0);if(sa(e),!await ra.checkSchemaExists(e.schema))throw ir(new Error,nd.SCHEMA_EXISTS_ERR(e.schema),or.BAD_REQUEST,na.LOG_LEVELS.ERROR,nd.SCHEMA_EXISTS_ERR(e.schema),!0);return await ni.createSchema(e),`database '${e.schema}' successfully created`}a(yD,"createSchemaStructure");async function m3(e){return sa(e),e.hash_attribute=e.primary_key??e.hash_attribute,await ND(e)}a(m3,"createTable");async function ND(e){let t=ta.create_table_object(e);if(t)throw ir(t,t.message,or.BAD_REQUEST,void 0,void 0,!0);if(ta.validateTableResidence(e.residence),!await ra.checkSchemaTableExists(e.schema,e.table))throw ir(new Error,nd.TABLE_EXISTS_ERR(e.schema,e.table),or.BAD_REQUEST,na.LOG_LEVELS.ERROR,nd.TABLE_EXISTS_ERR(e.schema,e.table),!0);let n={name:e.table,schema:e.schema,id:_3(),hash_attribute:e.hash_attribute};try{if(e.residence)if(global.clustering_on)n.residence=e.residence,await ni.createTable(n,e);else throw ir(new Error,"Clustering does not appear to be enabled. Cannot insert table with property 'residence'.",or.BAD_REQUEST);else await ni.createTable(n,e);return`table '${e.schema}.${e.table}' successfully created.`}catch(s){throw s}}a(ND,"createTableStructure");async function p3(e){let t=!e.schema&&!e.database?new Error("database is required"):void 0,r=ta.schema_object(e),n=t??r;if(n)throw ir(n,n.message,or.BAD_REQUEST,void 0,void 0,!0);sa(e);let s=await ra.checkSchemaExists(e.schema);if(s)throw ir(new Error,s,or.NOT_FOUND,na.LOG_LEVELS.ERROR,s,!0);let i=await ra.schema_describe.describeSchema({schema:e.schema}),o=Object.keys(global.hdb_schema[e.schema]);return await ni.dropSchema(e),sd.signalSchemaChange(new id(process.pid,e.operation,e.schema)),await bD.purgeSchemaTableStreams(e.schema,o),`successfully deleted '${e.schema}'`}a(p3,"dropSchema");async function S3(e){let t=ta.table_object(e);if(t)throw ir(t,t.message,or.BAD_REQUEST,void 0,void 0,!0);sa(e);let r=await ra.checkSchemaTableExists(e.schema,e.table);if(r)throw ir(new Error,r,or.NOT_FOUND,na.LOG_LEVELS.ERROR,r,!0);return await ni.dropTable(e),await bD.purgeTableStream(e.schema,e.table),`successfully deleted table '${e.schema}.${e.table}'`}a(S3,"dropTable");async function T3(e){let t=ta.attribute_object(e);if(t)throw ir(t,t.message,or.BAD_REQUEST,void 0,void 0,!0);sa(e);let r=await ra.checkSchemaTableExists(e.schema,e.table);if(r)throw ir(new Error,r,or.NOT_FOUND,na.LOG_LEVELS.ERROR,r,!0);if(e.attribute===global.hdb_schema[e.schema][e.table].hash_attribute)throw ir(new Error,"You cannot drop a hash attribute",or.BAD_REQUEST,void 0,void 0,!0);if(na.TIME_STAMP_NAMES.indexOf(e.attribute)>=0)throw ir(new Error,`cannot drop internal timestamp attribute: ${e.attribute}`,or.BAD_REQUEST,void 0,void 0,!0);try{return await ni.dropAttribute(e),g3(e),sd.signalSchemaChange(new id(process.pid,e.operation,e.schema,e.table,e.attribute)),`successfully deleted attribute '${e.attribute}'`}catch(n){throw l3.error(`Got an error deleting attribute ${d3.inspect(e)}.`),n}}a(T3,"dropAttribute");function g3(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(g3,"dropAttributeFromGlobal");async function R3(e){sa(e);let t=E3()[e.schema][e.table].attributes;for(let{name:r}of t)if(r===e.attribute)throw ir(new Error,`attribute '${e.attribute}' already exists in ${e.schema}.${e.table}`,or.BAD_REQUEST,void 0,void 0,!0);return await ni.createAttribute(e),sd.signalSchemaChange(new id(process.pid,e.operation,e.schema,e.table,e.attribute)),`attribute '${e.schema}.${e.table}.${e.attribute}' successfully created.`}a(R3,"createAttribute");function A3(e){return ni.getBackup(e)}a(A3,"getBackup")});var CD=T((C_e,ID)=>{"use strict";var{OPERATIONS_ENUM:O3}=U(),cS=class{static{a(this,"ReadAuditLogObject")}constructor(t,r,n=void 0,s=void 0){this.operation=O3.READ_AUDIT_LOG,this.schema=t,this.table=r,this.search_type=n,this.search_values=s}};ID.exports=cS});var uS=T((M_e,PD)=>{"use strict";var b3=yn(),L_e=CD(),ad=J(),cd=U(),y3=Z(),{handleHDBError:DD,hdb_errors:N3}=ee(),{HDB_ERROR_MSGS:LD,HTTP_STATUS_CODES:MD}=N3,w3=Object.values(cd.READ_AUDIT_LOG_SEARCH_TYPES_ENUM),UD="To use this operation audit log must be enabled in harperdb-config.yaml";PD.exports=I3;async function I3(e){if(ad.isEmpty(e.schema))throw new Error(LD.SCHEMA_REQUIRED_ERR);if(ad.isEmpty(e.table))throw new Error(LD.TABLE_REQUIRED_ERR);if(!y3.get(cd.CONFIG_PARAMS.LOGGING_AUDITLOG))throw DD(new Error,UD,MD.BAD_REQUEST,cd.LOG_LEVELS.ERROR,UD,!0);let t=ad.checkSchemaTableExist(e.schema,e.table);if(t)throw DD(new Error,t,MD.NOT_FOUND,cd.LOG_LEVELS.ERROR,t,!0);if(!ad.isEmpty(e.search_type)&&w3.indexOf(e.search_type)<0)throw new Error(`Invalid search_type '${e.search_type}'`);return await b3.readAuditLog(e)}a(I3,"readAuditLog")});var BD=T((P_e,vD)=>{"use strict";var{OPERATIONS_ENUM:C3}=U(),lS=class{static{a(this,"GetBackupObject")}constructor(t,r,n=void 0,s=void 0){this.operation=C3.GET_BACKUP,this.schema=t,this.table=r}};vD.exports=lS});var qD=T((x_e,xD)=>{"use strict";var D3=yn(),B_e=BD(),_S=J(),L3=U(),H_e=Z(),{handleHDBError:M3,hdb_errors:U3}=ee(),{HDB_ERROR_MSGS:HD,HTTP_STATUS_CODES:P3}=U3;xD.exports=v3;async function v3(e){if(_S.isEmpty(e.schema))throw new Error(HD.SCHEMA_REQUIRED_ERR);if(_S.isEmpty(e.table))throw new Error(HD.TABLE_REQUIRED_ERR);let t=_S.checkSchemaTableExist(e.schema,e.table);if(t)throw M3(new Error,t,P3.NOT_FOUND,L3.LOG_LEVELS.ERROR,t,!0);return await D3.getBackup(read_audit_log_object)}a(v3,"getBackup")});var YD=T((F_e,$D)=>{var si=require("validate.js"),GD=je(),ia=U(),{handleHDBError:B3,hdb_errors:H3}=ee(),{HDB_ERROR_MSGS:ct,HTTP_STATUS_CODES:x3}=H3,dS=a(()=>({role:{presence:!0,format:"[\\w\\-\\_]+"},id:{presence:!0,format:"[\\w\\-\\_]+"},permission:{presence:!0}}),"constraintsTemplate"),q3={STRUCTURE_USER:"structure_user"},FD=Object.values(ia.ROLE_TYPES_ENUM),F3="attribute_permissions",G3="attribute_name",{PERMS_CRUD_ENUM:oa}=ia,k3=[F3,...Object.values(oa)],kD=[oa.READ,oa.INSERT,oa.UPDATE],V3=[G3,...kD];function $3(e){let t=dS();return t.role.presence=!0,t.id.presence=!1,t.permission.presence=!0,VD(e,t)}a($3,"addRoleValidation");function Y3(e){let t=dS();return t.role.presence=!1,t.id.presence=!0,t.permission.presence=!0,VD(e,t)}a(Y3,"alterRoleValidation");function K3(e){let t=dS();return t.role.presence=!1,t.id.presence=!0,t.permission.presence=!1,GD.validateObject(e,t)}a(K3,"dropRoleValidation");var W3=["operation","role","id","permission","hdb_user","hdb_auth_header"];function VD(e,t){let r={main_permissions:[],schema_permissions:{}},n=Object.keys(e),s=[];for(let o=0,c=n.length;o<c;o++)W3.includes(n[o])||s.push(n[o]);s.length>0&&Et(ct.INVALID_ROLE_JSON_KEYS(s),r);let i=GD.validateObject(e,t);if(i&&i.message.split(",").forEach(o=>{Et(o,r)}),e.permission){let o=Q3(e);o&&Et(o,r),FD.forEach(c=>{e.permission[c]&&!si.isBoolean(e.permission[c])&&Et(ct.SU_CU_ROLE_BOOLEAN_ERROR(c),r)})}for(let o in e.permission)if(FD.indexOf(o)<0){if(o===q3.STRUCTURE_USER){let u=e.permission[o];if(typeof u=="boolean")continue;if(Array.isArray(u)){for(let _=0,l=u.length;_<l;_++){let d=u[_];global.hdb_schema[d]||Et(ct.SCHEMA_NOT_FOUND(d),r)}continue}Et(ct.STRUCTURE_USER_ROLE_TYPE_ERROR(o),r);continue}let c=e.permission[o];if(!o||!global.hdb_schema[o]){Et(ct.SCHEMA_NOT_FOUND(o),r);continue}if(c.tables)for(let u in c.tables){let _=c.tables[u];if(!u||!global.hdb_schema[o][u]){Et(ct.TABLE_NOT_FOUND(o,u),r);continue}if(Object.keys(_).forEach(l=>{k3.includes(l)||Et(ct.INVALID_PERM_KEY(l),r,o,u)}),Object.values(oa).forEach(l=>{si.isDefined(_[l])?si.isBoolean(_[l])||Et(ct.TABLE_PERM_NOT_BOOLEAN(l),r,o,u):Et(ct.TABLE_PERM_MISSING(l),r,o,u)}),si.isDefined(_.attribute_permissions)){if(!si.isArray(_.attribute_permissions)){Et(ct.ATTR_PERMS_NOT_ARRAY,r,o,u);continue}}else{Et(ct.ATTR_PERMS_ARRAY_MISSING,r,o,u);continue}if(_.attribute_permissions){let l=global.hdb_schema[o][u].attributes.map(({attribute:f})=>f),d={read:!1,insert:!1,update:!1};for(let f in _.attribute_permissions){let E=_.attribute_permissions[f];if(Object.keys(E).forEach(p=>{!V3.includes(p)&&p!==oa.DELETE&&Et(ct.INVALID_ATTR_PERM_KEY(p),r,o,u)}),!si.isDefined(E.attribute_name)){Et(ct.ATTR_PERM_MISSING_NAME,r,o,u);continue}let h=E.attribute_name;if(!l.includes(h)){Et(ct.INVALID_ATTRIBUTE_IN_PERMS(h),r,o,u);continue}kD.forEach(p=>{si.isDefined(E[p])?si.isBoolean(E[p])||Et(ct.ATTR_PERM_NOT_BOOLEAN(p,h),r,o,u):Et(ct.ATTR_PERM_MISSING(p,h),r,o,u)}),!d.read&&E.read===!0&&(d.read=!0),!d.insert&&E.insert===!0&&(d.insert=!0),!d.update&&E.update===!0&&(d.update=!0)}if(_.read===!1&&d.read===!0||_.insert===!1&&d.insert===!0||_.update===!1&&d.update===!0){let f=`${o}.${u}`;Et(ct.MISMATCHED_TABLE_ATTR_PERMS(f),r,o,u)}}}}return z3(r)}a(VD,"customValidate");$D.exports={addRoleValidation:$3,alterRoleValidation:Y3,dropRoleValidation:K3};function Q3(e){let{operation:t,permission:r}=e;if(t===ia.OPERATIONS_ENUM.ADD_ROLE||t===ia.OPERATIONS_ENUM.ALTER_ROLE){let n=r.super_user===!0,s=r.cluster_user===!0;if(Object.keys(r).length>1&&(n||s)){if(s&&n)return ct.SU_CU_ROLE_COMBINED_ERROR;{let o=r.super_user?ia.ROLE_TYPES_ENUM.SUPER_USER:ia.ROLE_TYPES_ENUM.CLUSTER_USER;return ct.SU_CU_ROLE_NO_PERMS_ALLOWED(o)}}}return null}a(Q3,"validateNoSUPerms");function z3(e){let{main_permissions:t,schema_permissions:r}=e;if(t.length>0||Object.keys(r).length>0){let n={error:ct.ROLE_PERMS_ERROR,...e};return B3(new Error,n,x3.BAD_REQUEST)}else return null}a(z3,"generateRolePermResponse");function Et(e,t,r,n){if(!r)t.main_permissions.push(e);else{let s=n?r+"_"+n:r;t.schema_permissions[s]?t.schema_permissions[s].push(e):t.schema_permissions[s]=[e]}}a(Et,"addPermError")});var SS=T((k_e,zD)=>{"use strict";var KD=en(),WD=Zr(),J3=ki(),ES=YD(),hS=Ts(),j3=require("uuid").v4,X3=require("util"),ud=U(),Z3=J(),mS=WD.searchByValue,ej=WD.searchByHash,tj=X3.promisify(J3.delete),rj=Qn(),nj=Xo(),{hdb_errors:sj,handleHDBError:ro}=ee(),{HDB_ERROR_MSGS:QD,HTTP_STATUS_CODES:uu}=sj,{UserEventMsg:pS}=Nn();zD.exports={addRole:ij,alterRole:oj,dropRole:aj,listRoles:cj};function fS(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(fS,"scrubRoleDetails");async function ij(e){let t=ES.addRoleValidation(e);if(t)throw t;e=fS(e);let r={schema:"system",table:"hdb_role",search_attribute:"role",search_value:e.role,hash_attribute:"id",get_attributes:["*"]},n;try{n=Array.from(await mS(r)||[])}catch(i){throw ro(i)}if(n&&n.length>0)throw ro(new Error,QD.ROLE_ALREADY_EXISTS(e.role),uu.CONFLICT,void 0,void 0,!0);e.id||(e.id=j3());let s={operation:"insert",schema:"system",table:"hdb_role",hash_attribute:"id",records:[e]};return await KD.insert(s),hS.signalUserChange(new pS(process.pid)),e=fS(e),e}a(ij,"addRole");async function oj(e){let t=ES.alterRoleValidation(e);if(t)throw t;e=fS(e);let r={operation:"update",schema:"system",table:"hdb_role",records:[e]},n;try{n=await KD.update(r)}catch(s){throw ro(s)}if(n&&n?.message==="updated 0 of 1 records")throw ro(new Error,"Invalid role id",uu.BAD_REQUEST,void 0,void 0,!0);return await hS.signalUserChange(new pS(process.pid)),e}a(oj,"alterRole");async function aj(e){let t=ES.dropRoleValidation(e);if(t)throw ro(new Error,t,uu.BAD_REQUEST,void 0,void 0,!0);let r=new nj(ud.SYSTEM_SCHEMA_NAME,ud.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME,[e.id],["role"]),n=Array.from(await ej(r));if(n.length===0)throw ro(new Error,QD.ROLE_NOT_FOUND,uu.NOT_FOUND,void 0,void 0,!0);let s=new rj(ud.SYSTEM_SCHEMA_NAME,ud.SYSTEM_TABLE_NAMES.USER_TABLE_NAME,"role",e.id,void 0,["username","active"]),i=Array.from(await mS(s)),o=!1;if(Z3.isEmptyOrZeroLength(i)===!1){for(let u=0;u<i.length;u++)if(i[u].active===!0){o=!0;break}}if(o===!0)throw ro(new Error,`Cannot drop role ${n[0].role} as it has active user(s) tied to this role`,uu.CONFLICT,void 0,void 0,!0);let c={table:"hdb_role",schema:"system",hash_values:[e.id]};return await tj(c),hS.signalUserChange(new pS(process.pid)),`${n[0].role} successfully deleted`}a(aj,"dropRole");async function cj(){return mS({table:"hdb_role",schema:"system",hash_attribute:"id",search_attribute:"id",search_value:"*",get_attributes:["*"]})}a(cj,"listRoles")});var ZD=T(($_e,XD)=>{"use strict";var uj=Z(),ii=require("joi"),lj=je(),JD=require("moment"),_j=require("fs-extra"),TS=require("path"),dj=require("lodash"),lu=U(),{LOG_LEVELS:no}=U(),fj="YYYY-MM-DD hh:mm:ss",Ej=TS.resolve(__dirname,"../logs");XD.exports=function(e){return lj.validateBySchema(e,hj)};var hj=ii.object({from:ii.custom(jD),until:ii.custom(jD),level:ii.valid(no.NOTIFY,no.FATAL,no.ERROR,no.WARN,no.INFO,no.DEBUG,no.TRACE),order:ii.valid("asc","desc"),limit:ii.number().min(1),start:ii.number().min(0),log_name:ii.custom(mj)});function jD(e,t){if(JD(e,JD.ISO_8601).format(fj)==="Invalid date")return t.message(`'${t.state.path[0]}' date '${e}' is invalid.`)}a(jD,"validateDatetime");function mj(e,t){if(dj.invert(lu.LOG_NAMES)[e]===void 0)return t.message(`'log_name' '${e}' is invalid.`);let n=uj.get(lu.HDB_SETTINGS_NAMES.LOG_PATH_KEY),s=e===void 0?lu.LOG_NAMES.HDB:e,i=s===lu.LOG_NAMES.INSTALL?TS.join(Ej,lu.LOG_NAMES.INSTALL):TS.join(n,s);return _j.existsSync(i)?null:t.message(`'log_name' '${e}' does not exist.`)}a(mj,"validateReadLogPath")});var RS=T((K_e,tL)=>{"use strict";var ld=U(),pj=K(),Sj=Z(),Tj=ZD(),gS=require("path"),eL=require("fs-extra"),{once:gj}=require("events"),{handleHDBError:Rj,hdb_errors:Aj}=ee(),{PACKAGE_ROOT:Oj}=U(),bj=gS.join(Oj,"logs"),yj=1e3,Nj=200;tL.exports=wj;async function wj(e){let t=Tj(e);if(t)throw Rj(t,t.message,Aj.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0);let r=Sj.get(ld.HDB_SETTINGS_NAMES.LOG_PATH_KEY),n=e.log_name===void 0?ld.LOG_NAMES.HDB:e.log_name,s=n===ld.LOG_NAMES.INSTALL?gS.join(bj,ld.LOG_NAMES.INSTALL):gS.join(r,n),i=e.level!==void 0,o=i?e.level:void 0,c=e.from!==void 0,u=c?new Date(e.from):void 0,_=e.until!==void 0,l=_?new Date(e.until):void 0,d=e.limit===void 0?yj:e.limit,f=e.order===void 0?void 0:e.order,E=e.start===void 0?0:e.start,h=E+d,p=0;f==="desc"&&!u&&!l&&(p=Math.max(eL.statSync(s).size-(h+5)*Nj,0));let S=eL.createReadStream(s,{start:p});S.on("error",v=>{pj.error(v)});let O=0,g=[],R="",B;S.on("data",v=>{let M=/(?:^|\n)(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:[\d\.]+Z) \[(.+?)]: /g;v=R+v;let $=0,W;for(;(W=M.exec(v))&&!S.destroyed;){B&&(B.message=v.slice($,W.index),H(B));let[z,se,Te]=W,oe=Te.split("] ["),xe=oe[0],de=oe[1];oe.splice(0,2),B={timestamp:se,thread:xe,level:de,tags:oe,message:""},$=W.index+z.length}R=v.slice($)}),S.on("end",v=>{S.destroyed||B&&(B.message=R.trim(),H(B))}),S.resume();function H(v){let M,$,W;switch(!0){case(i&&c&&_):M=new Date(v.timestamp),$=new Date(u),W=new Date(l),v.level===o&&M>=$&&M<=W&&O<E?O++:v.level===o&&M>=$&&M<=W&&(oi(v,f,g),O++,O===h&&S.destroy());break;case(i&&c):M=new Date(v.timestamp),$=new Date(u),v.level===o&&M>=$&&O<E?O++:v.level===o&&M>=$&&(oi(v,f,g),O++,O===h&&S.destroy());break;case(i&&_):M=new Date(v.timestamp),W=new Date(l),v.level===o&&M<=W&&O<E?O++:v.level===o&&M<=W&&(oi(v,f,g),O++,O===h&&S.destroy());break;case(c&&_):M=new Date(v.timestamp),$=new Date(u),W=new Date(l),M>=$&&M<=W&&O<E?O++:M>=$&&M<=W&&(oi(v,f,g),O++,O===h&&S.destroy());break;case i:v.level===o&&O<E?O++:v.level===o&&(oi(v,f,g),O++,O===h&&S.destroy());break;case c:M=new Date(v.timestamp),$=new Date(u),M>=$&&O<E?O++:M>=$&&O>=E&&(oi(v,f,g),O++,O===h&&S.destroy());break;case _:M=new Date(v.timestamp),W=new Date(l),M<=W&&O<E?O++:M<=W&&O>=E&&(oi(v,f,g),O++,O===h&&S.destroy());break;default:O<E?O++:(oi(v,f,g),O++,O===h&&S.destroy())}}return a(H,"onLogMessage"),await gj(S,"close"),g}a(wj,"readLog");function oi(e,t,r){t==="desc"?Ij(e,r):t==="asc"?Cj(e,r):r.push(e)}a(oi,"pushLineToResult");function Ij(e,t){let r=new Date(e.timestamp),n=0,s=t.length;for(;n<s;){let i=n+s>>>1;new Date(t[i].timestamp)>r?n=i+1:s=i}t.splice(n,0,e)}a(Ij,"insertDescending");function Cj(e,t){let r=new Date(e.timestamp),n=0,s=t.length;for(;n<s;){let i=n+s>>>1;new Date(t[i].timestamp)<r?n=i+1:s=i}t.splice(n,0,e)}a(Cj,"insertAscending")});var _d=T((j_e,iL)=>{"use strict";var AS=require("joi"),{string:_u,boolean:rL,date:Dj}=AS.types(),Lj=je(),{validateSchemaExists:Q_e,validateTableExists:z_e,validateSchemaName:J_e}=$n(),Mj=U(),Uj=tt(),nL=Z();nL.initSync();var Pj=_u.invalid(nL.get(Mj.CONFIG_PARAMS.CLUSTERING_NODENAME)).pattern(Uj.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(),sL={operation:_u.valid("add_node","update_node","set_node_replication"),node_name:Pj,subscriptions:AS.array().items({table:_u.optional(),schema:_u.optional(),database:_u.optional(),subscribe:rL.required(),publish:rL.required().custom(Bj),start_time:Dj.iso()}).min(1).required()};function vj(e){return Lj.validateBySchema(e,AS.object(sL))}a(vj,"addUpdateNodeValidator");function Bj(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(Bj,"checkForFalsy");iL.exports={addUpdateNodeValidator:vj,validation_schema:sL}});var aL=T((Z_e,oL)=>{var Hj=je(),xj={user:{presence:!0},schema:{presence:!0},table:{presence:!0},operation:{presence:!0}};oL.exports=function(e){return Hj.validateObject(e,xj)}});var bS=T((ede,cL)=>{"use strict";var qj=U().OPERATIONS_ENUM,OS=class{static{a(this,"UpdateObject")}constructor(t,r,n,s=void 0){this.operation=qj.UPDATE,this.schema=t,this.table=r,this.records=n,this.__origin=s}};cL.exports=OS});var lL=T((rde,uL)=>{"use strict";var Fj={OPERATION:"operation",REFRESH:"refresh"},yS=class{static{a(this,"JWTTokens")}constructor(t,r){this.operation_token=t,this.refresh_token=r}},NS=class{static{a(this,"JWTRSAKeys")}constructor(t,r,n){this.public_key=t,this.private_key=r,this.passphrase=n}};uL.exports={JWTTokens:yS,TOKEN_TYPE_ENUM:Fj,JWTRSAKeys:NS}});var Eu=T((sde,EL)=>{"use strict";var fu=require("jsonwebtoken"),wS=require("fs-extra"),IS=J(),nn=U(),{handleHDBError:ar,hdb_errors:Gj}=ee(),{HTTP_STATUS_CODES:cr,AUTHENTICATION_ERROR_MSGS:ur}=Gj,du=K(),_L=y_(),LS=Ur(),kj=en().update,Vj=bS(),$j=Ts(),{UserEventMsg:Yj}=Nn(),ai=Z();ai.initSync();var CS=require("path"),{JWTTokens:Kj,JWTRSAKeys:Wj,TOKEN_TYPE_ENUM:dd}=lL(),Qj=ai.get(nn.HDB_SETTINGS_NAMES.OPERATION_TOKEN_TIMEOUT_KEY)?ai.get(nn.HDB_SETTINGS_NAMES.OPERATION_TOKEN_TIMEOUT_KEY):"1d",zj=ai.get(nn.HDB_SETTINGS_NAMES.REFRESH_TOKEN_TIMEOUT_KEY)?ai.get(nn.HDB_SETTINGS_NAMES.REFRESH_TOKEN_TIMEOUT_KEY):"30d",fd="RS256",DS;EL.exports={createTokens:Jj,validateOperationToken:Xj,refreshOperationToken:jj,validateRefreshToken:fL};async function Jj(e){if(IS.isEmpty(e)||typeof e!="object")throw ar(new Error,ur.INVALID_AUTH_OBJECT,cr.BAD_REQUEST,void 0,void 0,!0);if(IS.isEmpty(e.username))throw ar(new Error,ur.USERNAME_REQUIRED,cr.BAD_REQUEST,void 0,void 0,!0);if(IS.isEmpty(e.password))throw ar(new Error,ur.PASSWORD_REQUIRED,cr.BAD_REQUEST,void 0,void 0,!0);let t;try{if(t=await LS.findAndValidateUser(e.username,e.password),!t)throw ar(new Error,ur.INVALID_CREDENTIALS,cr.UNAUTHORIZED,void 0,void 0,!0)}catch(f){throw du.error(f),ar(new Error,ur.INVALID_CREDENTIALS,cr.UNAUTHORIZED,void 0,void 0,!0)}let r=await Ed(),n=!1,s=!1;t.role&&t.role.permission&&(n=t.role.permission.super_user===!0,s=t.role.permission.cluster_user===!0);let i={username:e.username,super_user:n,cluster_user:s},o=await dL(i,r.private_key,r.passphrase),c=await fu.sign(i,{key:r.private_key,passphrase:r.passphrase},{expiresIn:zj,algorithm:fd,subject:dd.REFRESH}),u=_L.hash(c),_=new Vj(nn.SYSTEM_SCHEMA_NAME,nn.SYSTEM_TABLE_NAMES.USER_TABLE_NAME,[{username:e.username,refresh_token:u}]),l,d;try{l=await kj(_)}catch(f){du.error(f),d=f}if(d!==void 0||l.skipped_hashes.length>0)throw ar(new Error,ur.REFRESH_TOKEN_SAVE_FAILED,cr.INTERNAL_SERVER_ERROR);return $j.signalUserChange(new Yj(process.pid)),new Kj(o,c)}a(Jj,"createTokens");async function dL(e,t,r){return await fu.sign(e,{key:t,passphrase:r},{expiresIn:Qj,algorithm:fd,subject:dd.OPERATION})}a(dL,"signOperationToken");async function Ed(){if(DS===void 0)try{let e=CS.join(ai.getHdbBasePath(),nn.LICENSE_KEY_DIR_NAME,nn.JWT_ENUM.JWT_PASSPHRASE_NAME),t=CS.join(ai.getHdbBasePath(),nn.LICENSE_KEY_DIR_NAME,nn.JWT_ENUM.JWT_PRIVATE_KEY_NAME),r=CS.join(ai.getHdbBasePath(),nn.LICENSE_KEY_DIR_NAME,nn.JWT_ENUM.JWT_PUBLIC_KEY_NAME),n=(await wS.readFile(e)).toString(),s=(await wS.readFile(t)).toString(),i=(await wS.readFile(r)).toString();DS=new Wj(i,s,n)}catch(e){throw du.error(e),ar(new Error,ur.NO_ENCRYPTION_KEYS,cr.INTERNAL_SERVER_ERROR)}return DS}a(Ed,"getJWTRSAKeys");async function jj(e){if(!e)throw ar(new Error,ur.INVALID_BODY,cr.BAD_REQUEST,void 0,void 0,!0);if(!e.refresh_token)throw ar(new Error,ur.REFRESH_TOKEN_REQUIRED,cr.BAD_REQUEST,void 0,void 0,!0);await fL(e.refresh_token);let t=await Ed(),r=await fu.decode(e.refresh_token);return{operation_token:await dL({username:r.username,super_user:r.super_user,cluster_user:r.cluster_user},t.private_key,t.passphrase)}}a(jj,"refreshOperationToken");async function Xj(e){try{let t=await Ed(),r=await fu.verify(e,t.public_key,{algorithms:fd,subject:dd.OPERATION});return await LS.findAndValidateUser(r.username,void 0,!1)}catch(t){throw du.warn(t),t.name&&t.name==="TokenExpiredError"?ar(new Error,ur.TOKEN_EXPIRED,cr.FORBIDDEN):ar(new Error,ur.INVALID_TOKEN,cr.UNAUTHORIZED)}}a(Xj,"validateOperationToken");async function fL(e){let t;try{let r=await Ed(),n=await fu.verify(e,r.public_key,{algorithms:fd,subject:dd.REFRESH});t=await LS.findAndValidateUser(n.username,void 0,!1)}catch(r){throw du.warn(r),r.name&&r.name==="TokenExpiredError"?ar(new Error,ur.TOKEN_EXPIRED,cr.FORBIDDEN):ar(new Error,ur.INVALID_TOKEN,cr.UNAUTHORIZED)}if(!_L.validate(t.refresh_token,e))throw ar(new Error,ur.INVALID_TOKEN,cr.UNAUTHORIZED);return t}a(fL,"validateRefreshToken")});var MS=T((ade,pL)=>{"use strict";var Zj=aL(),aa=require("passport"),eX=require("passport-local").Strategy,tX=require("passport-http").BasicStrategy,rX=require("util"),nX=Ur(),mL=rX.callbackify(nX.findAndValidateUser),ode=br(),sX=U(),hL=Eu();aa.use(new eX(function(e,t,r){mL(e,t,r)}));aa.use(new tX(function(e,t,r){mL(e,t,r)}));aa.serializeUser(function(e,t){t(null,e)});aa.deserializeUser(function(e,t){t(null,e)});function iX(e,t,r){if(e.raw?.user!==void 0)return r(null,e.raw.user);let n,s;if(e.headers?.authorization){let o=e.headers.authorization.split(" ");n=o[0],s=o[1]}function i(o,c){return o?r(o):c?r(null,c):r("Must login")}switch(a(i,"handleResponse"),n){case"Basic":aa.authenticate("basic",{session:!1},(o,c)=>{i(o,c)})(e,t,r);break;case"Bearer":e.body?.operation&&e.body.operation===sX.OPERATIONS_ENUM.REFRESH_OPERATION_TOKEN?hL.validateRefreshToken(s).then(o=>{e.body.refresh_token=s,r(null,o)}).catch(o=>{r(o)}):hL.validateOperationToken(s).then(o=>{r(null,o)}).catch(o=>{r(o)});break;default:aa.authenticate("local",{session:!1},function(o,c){i(o,c)})(e,t,r);break}}a(iX,"authorize");function oX(e,t){let r=Zj(e);if(r){t(r);return}let n={authorized:!0,messages:[]},s=e.user.role;if(!s?.permission)return t("Invalid role");let i=JSON.parse(s.permission);if(i.super_user)return t(null,n);if(!i[e.schema])return n.authorized=!1,n.messages.push(`Not authorized to access ${e.schema} schema`),t(null,n);if(!i[e.schema].tables[e.table])return n.authorized=!1,n.messages.push(`Not authorized to access ${e.table} table`),t(null,n);if(!i[e.schema].tables[e.table][e.operation])return n.authorized=!1,n.messages.push(`Not authorized to access ${e.operation} on ${e.table} table`),t(null,n);if(i[e.schema].tables[e.table].attribute_permissions&&!e.attributes)return n.authorized=!1,n.messages.push(`${e.schema}.${e.table} has attribute permissions. Missing attributes to validate`),t(null,n);if(i[e.schema].tables[e.table].attribute_permissions&&e.attributes){let o=i[e.schema].tables[e.table].attribute_permissions;for(let c in o)e.attributes.indexOf(o[c].attribute_name)>-1&&!o[c][e.operation]&&(n.authorized=!1,n.messages.push(`Not authorized to ${e.operation} ${o[c].attribute_name} `))}return t(null,n)}a(oX,"checkPermissions");pL.exports={authorize:iX,checkPermissions:oX}});var ca=T((ude,SL)=>{"use strict";var US=class{static{a(this,"Node")}constructor(t,r,n){this.name=t,this.subscriptions=r,this.system_info=n}},PS=class{static{a(this,"NodeSubscription")}constructor(t,r,n,s){this.schema=t,this.table=r,this.publish=n,this.subscribe=s}};SL.exports={Node:US,NodeSubscription:PS}});var gL=T((_de,TL)=>{"use strict";var aX=U().OPERATIONS_ENUM,vS=class{static{a(this,"UpsertObject")}constructor(t,r,n,s=void 0){this.operation=aX.UPSERT,this.schema=t,this.table=r,this.records=n,this.__origin=s}};TL.exports=vS});var hu=T((fde,RL)=>{"use strict";var BS=class{static{a(this,"RemotePayloadObject")}constructor(t,r,n,s){this.operation=t,this.node_name=r,this.subscriptions=n,this.system_info=s}},HS=class{static{a(this,"RemotePayloadSubscription")}constructor(t,r,n,s,i,o,c){this.schema=t,this.table=r,this.hash_attribute=n,this.publish=s,this.subscribe=i,this.start_time=o,c!==void 0&&(this.attributes=c)}};RL.exports={RemotePayloadObject:BS,RemotePayloadSubscription:HS}});var OL=T((hde,AL)=>{"use strict";var xS=class{static{a(this,"TableSizeObject")}constructor(t,r,n=0,s=0,i=0,o=0){this.schema=t,this.table=r,this.table_size=n,this.record_count=s,this.transaction_log_size=i,this.transaction_log_record_count=o}};AL.exports=xS});var NL=T((gde,yL)=>{"use strict";var cX=OL(),pde=lt(),bL=Ve(),uX=K(),{getSchemaPath:Sde,getTransactionAuditStorePath:Tde}=Ye(),{getDatabases:lX}=(be(),te(qe));yL.exports=_X;async function _X(e){let t=new cX;try{let r=lX()[e.schema]?.[e.name],n=r.primaryStore.getStats(),s=r.auditStore?.getStats(),i=await bL.environmentDataSize(schema_path,e.name),o=await bL.environmentDataSize(txn_path,e.name);t.schema=e.schema,t.table=e.name,t.table_size=i,t.record_count=n.entryCount,t.transaction_log_size=o,t.transaction_log_record_count=s.entryCount}catch(r){uX.warn(`unable to stat table dbi due to ${r}`)}return t}a(_X,"lmdbGetTableSize")});var IL=T((Ade,wL)=>{"use strict";var qS=class{static{a(this,"SystemInformationObject")}constructor(t,r,n,s,i,o,c){this.system=t,this.time=r,this.cpu=n,this.memory=s,this.disk=i,this.network=o,this.harperdb_processes=c}};wL.exports=qS});var ua=T((Nde,ML)=>{"use strict";var dX=require("fs-extra"),fX=require("path"),Kt=require("systeminformation"),ci=K(),EX=ft(),FS=tt(),md=U(),hX=NL(),LL=Hi(),{getThreadInfo:CL}=Ze(),JS=Z();JS.initSync();var mX=IL(),{openEnvironment:bde}=Ve(),{getSchemaPath:yde}=Ye(),{database:pX}=(be(),te(qe)),hd;ML.exports={getHDBProcessInfo:$S,getNetworkInfo:KS,getDiskInfo:YS,getMemoryInfo:VS,getCPUInfo:kS,getTimeInfo:GS,getSystemInformation:WS,systemInformation:SX,getTableSize:QS,getMetrics:zS};function GS(){return Kt.time()}a(GS,"getTimeInfo");async function kS(){try{let{family:e,model:t,stepping:r,revision:n,voltage:s,speedmin:i,speedmax:o,governor:c,socket:u,cache:_,...l}=await Kt.cpu();l.cpu_speed=await Kt.cpuCurrentSpeed();let{raw_currentload:d,raw_currentload_idle:f,raw_currentload_irq:E,raw_currentload_nice:h,raw_currentload_system:p,raw_currentload_user:S,cpus:O,...g}=await Kt.currentLoad();return g.cpus=[],O.forEach(R=>{let{raw_load:B,raw_load_idle:H,raw_load_irq:v,raw_load_nice:M,raw_load_system:$,raw_load_user:W,...z}=R;g.cpus.push(z)}),l.current_load=g,l}catch(e){return ci.error(`error in getCPUInfo: ${e}`),{}}}a(kS,"getCPUInfo");async function VS(){try{let{buffers:e,cached:t,slab:r,buffcache:n,...s}=await Kt.mem();return Object.assign(s,process.memoryUsage())}catch(e){return ci.error(`error in getMemoryInfo: ${e}`),{}}}a(VS,"getMemoryInfo");async function $S(){let e={core:[],clustering:[]};try{let t=await Kt.processes(),r;try{r=Number.parseInt(await dX.readFile(fX.join(JS.get(md.CONFIG_PARAMS.ROOTPATH),md.HDB_PID_FILE),"utf8"))}catch(n){if(n.code===md.NODE_ERROR_CODES.ENOENT)ci.error("Unable to locate 'hdb.pid' file, try stopping and starting HarperDB");else throw n}t.list.forEach(n=>{n.pid===r?e.core.push(n):n.name==="nats-server"&&e.clustering.push(n)});for(let n of e.core)for(let s of t.list)s.pid===n.parentPid&&(s.name==="PM2"||s.command==="PM2")&&(n.parent="PM2");return e}catch(t){return ci.error(`error in getHDBProcessInfo: ${t}`),e}}a($S,"getHDBProcessInfo");async function YS(){let e={};try{let{rIO_sec:t,wIO_sec:r,tIO_sec:n,ms:s,...i}=await Kt.disksIO();e.io=i;let{rx_sec:o,tx_sec:c,wx_sec:u,..._}=await Kt.fsStats();return e.read_write=_,e.size=await Kt.fsSize(),e}catch(t){return ci.error(`error in getDiskInfo: ${t}`),e}}a(YS,"getDiskInfo");async function KS(){let e={default_interface:null,latency:{},interfaces:[],stats:[],connections:[]};try{return e.default_interface=await Kt.networkInterfaceDefault(),e.latency=await Kt.inetChecksite("google.com"),(await Kt.networkInterfaces()).forEach(n=>{let{internal:s,virtual:i,mtu:o,dhcp:c,dnsSuffix:u,ieee8021xAuth:_,ieee8021xState:l,carrier_changes:d,...f}=n;e.interfaces.push(f)}),(await Kt.networkStats()).forEach(n=>{let{rx_sec:s,tx_sec:i,ms:o,...c}=n;e.stats.push(c)}),e}catch(t){return ci.error(`error in getNetworkInfo: ${t}`),e}}a(KS,"getNetworkInfo");async function WS(){if(hd!==void 0)return hd;let e={};try{let{codepage:t,logofile:r,serial:n,build:s,servicepack:i,uefi:o,...c}=await Kt.osInfo();e=c;let u=await Kt.versions("node, npm");return e.node_version=u.node,e.npm_version=u.npm,hd=e,hd}catch(t){return ci.error(`error in getSystemInformation: ${t}`),e}}a(WS,"getSystemInformation");async function QS(){let e=[],t=await LL.describeAll();for(let r of Object.values(t))for(let n of Object.values(r))e.push(await hX(n));return e}a(QS,"getTableSize");async function zS(){let e=await LL.describeAll(),t={};for(let r in e){let n=t[r]={};for(let s in e[r])try{let i=pX({database:r,table:s}),o=i.getStats();o.readers=i.readerList().split(/\n\s+/).slice(1).map(c=>{let[u,_,l]=c.trim().split(" ");return{pid:u,thread:_,txnid:l}}),n[s]=o}catch(i){ci.notify(`Error getting stats for table ${s}: ${i}`)}}return t}a(zS,"getMetrics");async function DL(){if(JS.get(md.CONFIG_PARAMS.CLUSTERING_ENABLED)){let{js:e,jsm:t}=await EX.getNATSReferences(),r=await t.streams.info(FS.WORK_QUEUE_CONSUMER_NAMES.stream_name),n=await e.consumers.get(FS.WORK_QUEUE_CONSUMER_NAMES.stream_name,FS.WORK_QUEUE_CONSUMER_NAMES.durable_name),s={ingest:{stream:{...r.state},consumer:{num_ack_pending:n._info.num_ack_pending,num_redelivered:n._info.num_redelivered,num_waiting:n._info.num_waiting,num_pending:n._info.num_pending}}};return r.sources&&(s.ingest.stream.sources=r.sources),s}}a(DL,"getNatsStreamInfo");async function SX(e){let t=new mX;if(!Array.isArray(e.attributes)||e.attributes.length===0)return t.system=await WS(),t.time=GS(),t.cpu=await kS(),t.memory=await VS(),t.disk=await YS(),t.network=await KS(),t.harperdb_processes=await $S(),t.table_size=await QS(),t.metrics=await zS(),t.threads=await CL(),t.replication=await DL(),t;for(let r=0;r<e.attributes.length;r++)switch(e.attributes[r]){case"system":t.system=await WS();break;case"time":t.time=GS();break;case"cpu":t.cpu=await kS();break;case"memory":t.memory=await VS();break;case"disk":t.disk=await YS();break;case"network":t.network=await KS();break;case"harperdb_processes":t.harperdb_processes=await $S();break;case"table_size":t.table_size=await QS();break;case"database_metrics":case"metrics":t.metrics=await zS();break;case"threads":t.threads=await CL();break;case"replication":t.replication=await DL();break;default:break}return t}a(SX,"systemInformation")});var Sd=T((Ide,UL)=>{"use strict";UL.exports={version:TX,printVersion:gX};var pd=Xc();function TX(){if(pd)return pd.version}a(TX,"version");function gX(){pd&&console.log(`HarperDB Version ${pd.version}`)}a(gX,"printVersion")});var bs=T((Mde,HL)=>{"use strict";var RX=en(),jS=J(),AX=require("util"),so=U(),PL=Z();PL.initSync();var OX=MS(),vL=Zr(),{Node:Dde,NodeSubscription:Lde}=ca(),bX=Xo(),yX=gL(),{RemotePayloadObject:NX,RemotePayloadSubscription:wX}=hu(),{handleHDBError:IX,hdb_errors:CX}=ee(),{HTTP_STATUS_CODES:DX,HDB_ERROR_MSGS:LX}=CX,MX=Qn(),UX=ua(),PX=Sd(),{getDatabases:vX}=(be(),te(qe)),BX=AX.promisify(OX.authorize),HX=vL.searchByHash,xX=vL.searchByValue;HL.exports={authHeaderToUser:qX,isEmpty:FX,getNodeRecord:GX,upsertNodeRecord:kX,buildNodePayloads:VX,checkClusteringEnabled:$X,getAllNodeRecords:YX,getSystemInfo:KX,reverseSubscription:BL};async function qX(e){let t={headers:{authorization:e.hdb_auth_header}};return e.hdb_user=await BX(t,null),e}a(qX,"authHeaderToUser");function FX(e){return e==null}a(FX,"isEmpty");async function GX(e){let t=new bX(so.SYSTEM_SCHEMA_NAME,so.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[e],["*"]);return HX(t)}a(GX,"getNodeRecord");async function kX(e){let t=new yX(so.SYSTEM_SCHEMA_NAME,so.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[e]);return RX.upsert(t)}a(kX,"upsertNodeRecord");function BL(e){if(jS.isEmpty(e.subscribe)||jS.isEmpty(e.publish))throw new Error("Received invalid subscription object");let{schema:t,table:r,hash_attribute:n}=e,s={schema:t,table:r,hash_attribute:n};return e.subscribe===!0&&e.publish===!1?(s.subscribe=!1,s.publish=!0):e.subscribe===!1&&e.publish===!0?(s.subscribe=!0,s.publish=!1):(s.subscribe=e.subscribe,s.publish=e.publish),s}a(BL,"reverseSubscription");function VX(e,t,r,n){let s=[];for(let i=0,o=e.length;i<o;i++){let c=e[i],{schema:u,table:_}=c,l=jS.getTableHashAttribute(u,_),{subscribe:d,publish:f}=BL(c),E=vX()[u]?.[_],h=new wX(u,_,l,f,d,c.start_time,E.schemaDefined?E.attributes:void 0);s.push(h)}return new NX(r,t,s,n)}a(VX,"buildNodePayloads");function $X(){if(!PL.get(so.CONFIG_PARAMS.CLUSTERING_ENABLED))throw IX(new Error,LX.CLUSTERING_NOT_ENABLED,DX.BAD_REQUEST,void 0,void 0,!0)}a($X,"checkClusteringEnabled");async function YX(){let e=new MX(so.SYSTEM_SCHEMA_NAME,so.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,"name","*",void 0,["*"]);return Array.from(await xX(e))}a(YX,"getAllNodeRecords");async function KX(){let e=await UX.getSystemInformation();return{hdb_version:PX.version(),node_version:e.node_version,platform:e.platform}}a(KX,"getSystemInfo")});var XS=T((Pde,YL)=>{"use strict";var Td=ft(),xL=J(),qL=tt(),FL=U(),gd=K(),GL=od(),WX=Sp(),{RemotePayloadObject:QX}=hu(),{handleHDBError:kL,hdb_errors:zX}=ee(),{HTTP_STATUS_CODES:VL}=zX,{NodeSubscription:$L}=ca();YL.exports=JX;async function JX(e,t){let r;try{r=await Td.request(`${t}.${qL.REQUEST_SUFFIX}`,new QX(FL.OPERATIONS_ENUM.DESCRIBE_ALL,t,void 0,void 0)),gd.trace("Response from remote describe all request:",r)}catch(o){gd.error(`addNode received error from describe all request to remote node: ${o}`);let c=Td.requestErrorHandler(o,"add_node",t);throw kL(new Error,c,VL.INTERNAL_SERVER_ERROR,"error",c)}if(r.status===qL.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let o=`Error returned from remote node ${t}: ${r.message}`;throw kL(new Error,o,VL.INTERNAL_SERVER_ERROR,"error",o)}let n=r.message,s=[],i=[];for(let o of e){let{table:c}=o,u=o.database??o.schema??"data";if(u===FL.SYSTEM_SCHEMA_NAME){await Td.createLocalTableStream(u,c);let h=new $L(u,c,o.publish,o.subscribe);h.start_time=o.start_time,i.push(h);continue}let _=xL.doesSchemaExist(u),l=n[u]!==void 0,d=c?xL.doesTableExist(u,c):!0,f=c?n?.[u]?.[c]!==void 0:!0;if(!_&&!l||!d&&!f){s.push(o);continue}if(!_&&l&&(gd.trace(`addNode creating schema: ${u}`),await GL.createSchema({operation:"create_schema",schema:u})),!d&&f){gd.trace(`addNode creating table: ${c} in schema: ${u} with attributes ${JSON.stringify(n[u][c].attributes)}`);let h=new WX(u,c,n[u][c].hash_attribute);n[u][c].attributes&&(h.attributes=n[u][c].attributes),await GL.createTable(h)}await Td.createLocalTableStream(u,c);let E=new $L(u,c,o.publish,o.subscribe);E.start_time=o.start_time,i.push(E)}return{added:i,skipped:s}}a(JX,"reviewSubscriptions")});var Od=T((Bde,QL)=>{"use strict";var{handleHDBError:Rd,hdb_errors:jX}=ee(),{HTTP_STATUS_CODES:Ad}=jX,{addUpdateNodeValidator:XX}=_d(),mu=K(),WL=U(),KL=tt(),ZX=J(),ZS=ft(),pu=bs(),eZ=Z(),tZ=XS(),{Node:rZ,NodeSubscription:nZ}=ca(),{broadcast:sZ}=Ze(),iZ="Unable to create subscriptions due to schema and/or tables not existing on the local or remote node",oZ="Some subscriptions were unsuccessful due to schema and/or tables not existing on the local or remote node",aZ=eZ.get(WL.CONFIG_PARAMS.CLUSTERING_NODENAME);QL.exports=cZ;async function cZ(e,t=!1){mu.trace("addNode called with:",e),pu.checkClusteringEnabled();let r=XX(e);if(r)throw Rd(r,r.message,Ad.BAD_REQUEST,void 0,void 0,!0);let n=e.node_name;if(!t){let d=await pu.getNodeRecord(n);if(!ZX.isEmptyOrZeroLength(d))throw Rd(new Error,`Node '${n}' has already been added, perform update_node to proceed.`,Ad.BAD_REQUEST,void 0,void 0,!0)}let{added:s,skipped:i}=await tZ(e.subscriptions,n),o={message:void 0,added:s,skipped:i};if(s.length===0)return o.message=iZ,o;let c=pu.buildNodePayloads(s,aZ,WL.OPERATIONS_ENUM.ADD_NODE,await pu.getSystemInfo());mu.trace("addNode sending remote payload:",c);let u;try{u=await ZS.request(`${n}.${KL.REQUEST_SUFFIX}`,c)}catch(d){mu.error(`addNode received error from request: ${d}`);let f=ZS.requestErrorHandler(d,"add_node",n);throw Rd(new Error,f,Ad.INTERNAL_SERVER_ERROR,"error",f)}if(u.status===KL.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let d=`Error returned from remote node ${n}: ${u.message}`;throw Rd(new Error,d,Ad.INTERNAL_SERVER_ERROR,"error",d)}mu.trace(u);let _=[];for(let d=0,f=s.length;d<f;d++){let E=s[d];mu.trace("Add node updating work stream for node:",n,"subscriptions:",E),await ZS.updateWorkStream(E,n),s[d].start_time===void 0&&delete s[d].start_time,_.push(new nZ(E.schema,E.table,E.publish,E.subscribe))}let l=new rZ(n,_,u.system_info);return await pu.upsertNodeRecord(l),sZ({type:"nats_update"}),i.length>0?o.message=oZ:o.message=`Successfully added '${n}' to manifest`,o}a(cZ,"addNode")});var nT=T((qde,jL)=>{"use strict";var{handleHDBError:eT,hdb_errors:uZ}=ee(),{HTTP_STATUS_CODES:tT}=uZ,{addUpdateNodeValidator:lZ}=_d(),Su=K(),JL=U(),zL=tt(),xde=J(),rT=ft(),Tu=bs(),_Z=Z(),{cloneDeep:dZ}=require("lodash"),fZ=XS(),{Node:EZ,NodeSubscription:hZ}=ca(),{broadcast:mZ}=Ze(),pZ="Unable to update subscriptions due to schema and/or tables not existing on the local or remote node",SZ="Some subscriptions were unsuccessful due to schema and/or tables not existing on the local or remote node",TZ=_Z.get(JL.CONFIG_PARAMS.CLUSTERING_NODENAME);jL.exports=gZ;async function gZ(e){Su.trace("updateNode called with:",e),Tu.checkClusteringEnabled();let t=lZ(e);if(t)throw eT(t,t.message,tT.BAD_REQUEST,void 0,void 0,!0);let r=e.node_name,n,s=await Tu.getNodeRecord(r);s.length>0&&(n=dZ(s));let{added:i,skipped:o}=await fZ(e.subscriptions,r),c={message:void 0,updated:i,skipped:o};if(i.length===0)return c.message=pZ,c;let u=Tu.buildNodePayloads(i,TZ,JL.OPERATIONS_ENUM.UPDATE_NODE,await Tu.getSystemInfo());Su.trace("updateNode sending remote payload:",u);let _;try{_=await rT.request(`${r}.${zL.REQUEST_SUFFIX}`,u)}catch(l){Su.error(`updateNode received error from request: ${l}`);let d=rT.requestErrorHandler(l,"update_node",r);throw eT(new Error,d,tT.INTERNAL_SERVER_ERROR,"error",d)}if(_.status===zL.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let l=`Error returned from remote node ${r}: ${_.message}`;throw eT(new Error,l,tT.INTERNAL_SERVER_ERROR,"error",l)}Su.trace(_);for(let l=0,d=i.length;l<d;l++){let f=i[l];Su.trace(`updateNode updating work stream for node: ${r} subscription:`,f),await rT.updateWorkStream(f,r),i[l].start_time===void 0&&delete i[l].start_time}return n||(n=[new EZ(r,[],_.system_info)]),await RZ(n[0],i,_.system_info),o.length>0?c.message=SZ:c.message=`Successfully updated '${r}'`,c}a(gZ,"updateNode");async function RZ(e,t,r){let n=e;for(let s=0,i=t.length;s<i;s++){let o=t[s],c=!1;for(let u=0,_=e.subscriptions.length;u<_;u++){let l=n.subscriptions[u];if(l.schema===o.schema&&l.table===o.table){l.publish=o.publish,l.subscribe=o.subscribe,c=!0;break}}c||n.subscriptions.push(new hZ(o.schema,o.table,o.publish,o.subscribe))}n.system_info=r,await Tu.upsertNodeRecord(n),mZ({type:"nats_update"})}a(RZ,"updateNodeTable")});var rM=T((Gde,tM)=>{"use strict";var eM=require("joi"),{string:XL}=eM.types(),AZ=je(),ZL=U(),OZ=Z(),bZ=tt();tM.exports=yZ;function yZ(e){let t=XL.invalid(OZ.get(ZL.CONFIG_PARAMS.CLUSTERING_NODENAME)).pattern(bZ.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=eM.object({operation:XL.valid(ZL.OPERATIONS_ENUM.REMOVE_NODE).required(),node_name:t});return AZ.validateBySchema(e,r)}a(yZ,"removeNodeValidator")});var yd=T((Vde,cM)=>{"use strict";var{handleHDBError:nM,hdb_errors:NZ}=ee(),{HTTP_STATUS_CODES:sM}=NZ,wZ=rM(),gu=K(),iM=bs(),IZ=J(),bd=U(),oM=tt(),aM=ft(),CZ=Z(),{RemotePayloadObject:DZ}=hu(),{NodeSubscription:LZ}=ca(),MZ=$c(),UZ=ki(),{broadcast:PZ}=Ze(),vZ=CZ.get(bd.CONFIG_PARAMS.CLUSTERING_NODENAME);cM.exports=BZ;async function BZ(e){gu.trace("removeNode called with:",e),iM.checkClusteringEnabled();let t=wZ(e);if(t)throw nM(t,t.message,sM.BAD_REQUEST,void 0,void 0,!0);let r=e.node_name,n=await iM.getNodeRecord(r);if(IZ.isEmptyOrZeroLength(n))throw nM(new Error,`Node '${r}' was not found.`,sM.BAD_REQUEST,void 0,void 0,!0);n=n[0];let s=new DZ(bd.OPERATIONS_ENUM.REMOVE_NODE,vZ,[]),i,o=!1;try{i=await aM.request(`${r}.${oM.REQUEST_SUFFIX}`,s),gu.trace("Remove node reply from remote node:",r,i)}catch(u){gu.error("removeNode received error from request:",u),o=!0}for(let u=0,_=n.subscriptions.length;u<_;u++){let l=n.subscriptions[u];gu.trace(`Remove node removing subscription: ${l.schema}.${l.table} for node: ${r}`);let d=new LZ(l.schema,l.table,!1,!1);await aM.updateWorkStream(d,r)}let c=new MZ(bd.SYSTEM_SCHEMA_NAME,bd.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[r]);return await UZ.deleteRecord(c),PZ({type:"nats_update"}),i?.status===oM.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR||o?(gu.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(BZ,"removeNode")});var _M=T((Yde,lM)=>{"use strict";var uM=require("joi"),{string:HZ,array:xZ}=uM.types(),qZ=je(),FZ=_d();lM.exports=GZ;function GZ(e){let t=uM.object({operation:HZ.valid("configure_cluster").required(),connections:xZ.items(FZ.validation_schema).required()});return qZ.validateBySchema(e,t)}a(GZ,"configureClusterValidator")});var sT=T((Wde,mM)=>{"use strict";var kZ=U(),Nd=K(),VZ=J(),$Z=yd(),YZ=Od(),dM=bs(),KZ=_M(),{handleHDBError:fM,hdb_errors:WZ}=ee(),{HTTP_STATUS_CODES:EM}=WZ,QZ="Configure cluster complete.",zZ="Failed to configure the cluster. Check the logs for more details.",JZ="Configure cluster was partially successful. Errors occurred when attempting to configure the following nodes. Check the logs for more details.";mM.exports=jZ;async function jZ(e){Nd.trace("configure cluster called with:",e),dM.checkClusteringEnabled();let t=KZ(e);if(t)throw fM(t,t.message,EM.BAD_REQUEST,void 0,void 0,!0);let r=await dM.getAllNodeRecords(),n=[];for(let f=0,E=r.length;f<E;f++)n.push(hM($Z,{operation:kZ.OPERATIONS_ENUM.REMOVE_NODE,node_name:r[f].name},r[f].name));let s=await Promise.allSettled(n);Nd.trace("All results from configure_cluster remove node:",s);let i=[],o=e.connections.length;for(let f=0;f<o;f++){let E=e.connections[f];i.push(hM(YZ,E,E.node_name))}let c=await Promise.allSettled(i);Nd.trace("All results from configure_cluster add node:",c);let u=[],_=[],l=!1,d=s.concat(c);for(let f=0,E=d.length;f<E;f++){let h=d[f];h.status==="rejected"&&(Nd.error(h.reason),u.includes(h.reason.node_name)||u.push(h.reason.node_name)),h.status==="fulfilled"&&(l=!0);let p=h?.value?.result;typeof p=="string"&&p.includes("Successfully removed")||h.status==="rejected"||_.push({node_name:h?.value?.node_name,subscriptions:h?.value?.result})}if(VZ.isEmptyOrZeroLength(u))return{message:QZ,connections:_};if(l)return{message:JZ,failed_nodes:u,connections:_};throw fM(new Error,zZ,EM.INTERNAL_SERVER_ERROR,void 0,void 0,!0)}a(jZ,"configureCluster");async function hM(e,t,r){try{return{node_name:r,result:await e(t)}}catch(n){throw{node_name:r,error:n}}}a(hM,"functionWrapper")});var SM=T((zde,pM)=>{"use strict";var wd=require("joi"),XZ=je(),{validateSchemaExists:ZZ,validateTableExists:e5,validateSchemaName:t5}=$n(),r5=wd.object({operation:wd.string().valid("purge_stream"),schema:wd.string().custom(ZZ).custom(t5).required(),table:wd.string().custom(e5).required()});function n5(e){return XZ.validateBySchema(e,r5)}a(n5,"purgeStreamValidator");pM.exports=n5});var iT=T((jde,TM)=>{"use strict";var{handleHDBError:s5,hdb_errors:i5}=ee(),{HTTP_STATUS_CODES:o5}=i5,a5=SM(),c5=ft(),u5=bs();TM.exports=l5;async function l5(e){if(e.purge_ingest!==!0){let s=a5(e);if(s)throw s5(s,s.message,o5.BAD_REQUEST,void 0,void 0,!0)}u5.checkClusteringEnabled();let{schema:t,table:r,purge_ingest:n}=e;return await c5.purgeTableStream(t,r,n),n?"Successfully purged ingest":`Successfully purged table '${t}.${r}'`}a(l5,"purgeStream")});var cT=T((Zde,yM)=>{"use strict";var aT=bs(),_5=ft(),AM=Z(),Id=U(),io=tt(),d5=J(),oT=K(),{RemotePayloadObject:f5}=hu(),{ErrorCode:gM}=require("nats"),RM=AM.get(Id.CONFIG_PARAMS.CLUSTERING_ENABLED),OM=AM.get(Id.CONFIG_PARAMS.CLUSTERING_NODENAME);yM.exports={clusterStatus:E5,buildNodeStatus:bM};async function E5(){let e={node_name:OM,is_enabled:RM,connections:[]};if(!RM)return e;let t=await aT.getAllNodeRecords();if(d5.isEmptyOrZeroLength(t))return e;let r=[];for(let n=0,s=t.length;n<s;n++)r.push(bM(t[n],e.connections));return await Promise.allSettled(r),e}a(E5,"clusterStatus");async function bM(e,t){let r=e.name,n=new f5(Id.OPERATIONS_ENUM.CLUSTER_STATUS,OM,void 0,await aT.getSystemInfo()),s,i,o=io.CLUSTER_STATUS_STATUSES.OPEN;try{let u=Date.now();s=await _5.request(io.REQUEST_SUBJECT(r),n),i=Date.now()-u,s.status===io.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR&&(o=io.CLUSTER_STATUS_STATUSES.CLOSED,oT.error(`Error getting node status from ${r} `,s))}catch(u){oT.warn(`Error getting node status from ${r}`,u),u.code===gM.NoResponders?o=io.CLUSTER_STATUS_STATUSES.NO_RESPONDERS:u.code===gM.Timeout?o=io.CLUSTER_STATUS_STATUSES.TIMEOUT:o=io.CLUSTER_STATUS_STATUSES.CLOSED}let c=new h5(r,o,s?.message?.ports?.clustering,s?.message?.ports?.operations_api,i,s?.message?.uptime,e.subscriptions,s?.message?.system_info);try{let u={name:r,system_info:s?.message?.system_info};e.system_info?.hdb_version!==Id.PRE_4_0_0_VERSION&&await aT.upsertNodeRecord(u)}catch(u){oT.error("Cluster status encountered an error updating system info for node:",r,u)}t.push(c)}a(bM,"buildNodeStatus");function h5(e,t,r,n,s,i,o,c){this.node_name=e,this.status=t,this.ports={clustering:r,operations_api:n},this.latency_ms=s,this.uptime=i,this.subscriptions=o,this.system_info=c}a(h5,"NodeStatusObject")});var lT=T((tfe,NM)=>{"use strict";var{handleHDBError:m5,hdb_errors:p5}=ee(),{HTTP_STATUS_CODES:S5}=p5,T5=ft(),g5=bs(),uT=J(),Cd=require("joi"),R5=je(),A5=2e3,O5=Cd.object({timeout:Cd.number().min(1),connected_nodes:Cd.boolean(),routes:Cd.boolean()});NM.exports=b5;async function b5(e){g5.checkClusteringEnabled();let t=R5.validateBySchema(e,O5);if(t)throw m5(t,t.message,S5.BAD_REQUEST,void 0,void 0,!0);let{timeout:r,connected_nodes:n,routes:s}=e,i=n===void 0||uT.autoCastBoolean(n),o=s===void 0||uT.autoCastBoolean(s),c={nodes:[]},u=await T5.getServerList(r??A5),_={};if(i)for(let l=0,d=u.length;l<d;l++){let f=u[l].statsz;f&&(_[u[l].server.name]=f.routes)}for(let l=0,d=u.length;l<d;l++){if(u[l].statsz)continue;let f=u[l].server,E=u[l].data;if(f.name.endsWith("-hub")){let h={name:f.name.slice(0,-4),response_time:u[l].response_time};i&&(h.connected_nodes=[],_[f.name]&&_[f.name].forEach(p=>{h.connected_nodes.includes(p.name.slice(0,-4))||h.connected_nodes.push(p.name.slice(0,-4))})),o&&(h.routes=E.cluster?.urls?E.cluster?.urls.map(p=>({host:p.split(":")[0],port:uT.autoCast(p.split(":")[1])})):[]),c.nodes.push(h)}}return c}a(b5,"clusterNetwork")});var DM=T((nfe,CM)=>{"use strict";var _T=require("joi"),wM=je(),{route_constraints:IM}=fh();CM.exports={setRoutesValidator:y5,deleteRoutesValidator:N5};function y5(e){let t=_T.object({server:_T.valid("hub","leaf").required(),routes:IM.required()});return wM.validateBySchema(e,t)}a(y5,"setRoutesValidator");function N5(e){let t=_T.object({routes:IM.required()});return wM.validateBySchema(e,t)}a(N5,"deleteRoutesValidator")});var fT=T((ife,PM)=>{"use strict";var oo=Ir(),dT=J(),Dd=U(),LM=DM(),{handleHDBError:MM,hdb_errors:w5}=ee(),{HTTP_STATUS_CODES:UM}=w5,I5="cluster routes successfully set",C5="cluster routes successfully deleted";PM.exports={setRoutes:D5,getRoutes:L5,deleteRoutes:M5};function D5(e){let t=LM.setRoutesValidator(e);if(t)throw MM(t,t.message,UM.BAD_REQUEST,void 0,void 0,!0);let r=oo.getClusteringRoutes(),n=e.server==="hub"?r.hub_routes:r.leaf_routes,s=e.server==="hub"?r.leaf_routes:r.hub_routes,i=[],o=[];for(let c=0,u=e.routes.length;c<u;c++){let _=e.routes[c];_.port=dT.autoCast(_.port);let l=n.some(f=>f.host===_.host&&f.port===_.port),d=s.some(f=>f.host===_.host&&f.port===_.port);l||d?i.push(_):(n.push(_),o.push(_))}return e.server==="hub"?oo.updateConfigValue(Dd.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,n):oo.updateConfigValue(Dd.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,n),{message:I5,set:o,skipped:i}}a(D5,"setRoutes");function L5(){let e=oo.getClusteringRoutes();return{hub:e.hub_routes,leaf:e.leaf_routes}}a(L5,"getRoutes");function M5(e){let t=LM.deleteRoutesValidator(e);if(t)throw MM(t,t.message,UM.BAD_REQUEST,void 0,void 0,!0);let r=oo.getClusteringRoutes(),n=r.hub_routes,s=r.leaf_routes,i=[],o=[],c=!1,u=!1;for(let _=0,l=e.routes.length;_<l;_++){let d=e.routes[_],f=!1;for(let E=0,h=n.length;E<h;E++){let p=n[E];if(d.host===p.host&&d.port===p.port){n.splice(E,1),f=!0,c=!0,i.push(d);break}}if(!f){let E=!0;for(let h=0,p=s.length;h<p;h++){let S=s[h];if(d.host===S.host&&d.port===S.port){s.splice(h,1),u=!0,E=!1,i.push(d);break}}E&&o.push(d)}}return c&&(n=dT.isEmptyOrZeroLength(n)?null:n,oo.updateConfigValue(Dd.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,n)),u&&(s=dT.isEmptyOrZeroLength(s)?null:s,oo.updateConfigValue(Dd.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,s)),{message:C5,deleted:i,skipped:o}}a(M5,"deleteRoutes")});var BM=T((afe,vM)=>{"use strict";var Ru=require("alasql"),ao=require("recursive-iterator"),Ln=K(),U5=J(),Au=U(),ET=class{static{a(this,"sql_statement_bucket")}constructor(t){this.ast=t,this.affected_attributes=new Map,this.table_lookup=new Map,this.schema_lookup=new Map,this.table_to_schema_lookup=new Map,v5(this.ast,this.affected_attributes,this.table_lookup,this.schema_lookup,this.table_to_schema_lookup)}getAttributesBySchemaTableName(t,r){if(!t||!r||!this.affected_attributes)return[];if(this.affected_attributes.has(t))return!this.affected_attributes.get(t).has(r)&&(r=this.table_lookup.get(r),!r)?[]:this.affected_attributes.get(t).get(r)}getAllTables(){let t=[];if(!this.affected_attributes)return t;for(let r of this.affected_attributes.keys())t.push(Array.from(this.affected_attributes.get(r).keys()));return t}getTablesBySchemaName(t){return!t||!this.affected_attributes?[]:Array.from(this.affected_attributes.get(t).keys())}getSchemas(){return this.affected_attributes?Array.from(this.affected_attributes.keys()):[]}getAst(){return this.ast}updateAttributeWildcardsForRolePerms(t){let r=this.ast.columns.filter(s=>Au.SEARCH_WILDCARDS.includes(s.columnid));if(r.length===0)return this.ast;let n=this.ast.from[0].databaseid;return this.ast.columns=this.ast.columns.filter(s=>!Au.SEARCH_WILDCARDS.includes(s.columnid)),r.forEach(s=>{let i=this.table_to_schema_lookup.has(s.tableid)?this.table_to_schema_lookup.get(s.tableid):n,o=this.table_lookup.has(s.tableid)?this.table_lookup.get(s.tableid):this.ast.from[0].tableid;if(t[i]&&t[i].tables[o]&&t[i].tables[o][Au.PERMS_CRUD_ENUM.READ]){let c;t[i].tables[o].attribute_permissions.length>0?c=P5(t[i].tables[o].attribute_permissions):c=global.hdb_schema[i][o].attributes.map(_=>({attribute_name:_.attribute}));let u=this.affected_attributes.get(i).get(o).filter(_=>!Au.SEARCH_WILDCARDS.includes(_));c.forEach(({attribute_name:_})=>{let l=new Ru.yy.Column({columnid:_});s.tableid&&(l.tableid=s.tableid),this.ast.columns.push(l),u.includes(_)||u.push(_)}),this.affected_attributes.get(i).set(o,u)}}),this.ast}};function P5(e){return e.filter(t=>t[Au.PERMS_CRUD_ENUM.READ])}a(P5,"filterReadRestrictedAttrs");function v5(e,t,r,n,s){B5(e,t,r,n,s)}a(v5,"interpretAST");function Ou(e,t,r,n,s){if(!(!e||!e.databaseid)&&(t.has(e.databaseid)||t.set(e.databaseid,new Map),t.get(e.databaseid).has(e.tableid)||t.get(e.databaseid).set(e.tableid,[]),e.as&&(r.has(e.as)||r.set(e.as,e.tableid),n&&!n.has(e.as)&&n.set(e.as,e.databaseid)),s)){let i=e.databaseid,o=e.tableid;e.as&&(o=e.as),s.set(o,i)}}a(Ou,"addSchemaTableToMap");function B5(e,t,r,n,s){if(!e){Ln.info("getRecordAttributesAST: invalid SQL syntax tree");return}e instanceof Ru.yy.Insert?F5(e,t,r):e instanceof Ru.yy.Select?H5(e,t,r,n,s):e instanceof Ru.yy.Update?x5(e,t,r):e instanceof Ru.yy.Delete?q5(e,t,r):Ln.error("AST in getRecordAttributesAST() is not a valid SQL type.")}a(B5,"getRecordAttributesAST");function H5(e,t,r,n,s){if(!e){Ln.info("getSelectAttributes: invalid SQL syntax tree");return}if(!e.from||e.from[0]===void 0)return;let i=e.from[0].databaseid;if(U5.isEmptyOrZeroLength(i)){Ln.error("No schema specified");return}e.from.forEach(c=>{Ou(c,t,r,n,s)}),e.joins&&e.joins.forEach(c=>{c.as&&(c.table.as=c.as),Ou(c.table,t,r,n,s)});let o=new ao(e.columns);for(let{node:c}of o)if(c&&c.columnid){let u=c.tableid,_=n.has(u)?n.get(u):i;if(u||(u=e.from[0].tableid),!t.get(_).has(u))if(r.has(u))u=r.get(u);else{Ln.info(`table specified as ${u} not found.`);return}t.get(_).get(u).indexOf(c.columnid)<0&&t.get(_).get(u).push(c.columnid)}if(e.where){let c=new ao(e.where),u=e.from[0].tableid;for(let{node:_}of c)if(_&&_.columnid){let l=_.tableid?_.tableid:u;if(!t.get(i).has(l))if(r.has(l))l=r.get(l);else{Ln.info(`table specified as ${l} not found.`);continue}t.get(i).get(l).indexOf(_.columnid)<0&&t.get(i).get(l).push(_.columnid)}}if(e.joins&&e.joins.forEach(c=>{let u=new ao(c.on);for(let{node:_}of u)if(_&&_.columnid){let l=_.tableid,d=s.get(l);if(!t.get(d).has(l))if(r.has(l))l=r.get(l);else{Ln.info(`table specified as ${l} not found.`);continue}t.get(d).get(l).indexOf(_.columnid)<0&&t.get(d).get(l).push(_.columnid)}}),e.order){let c=new ao(e.order);for(let{node:u}of c)if(u&&u.columnid){let _=u.tableid,l=n.has(_)?n.get(_):i;if(_||(_=e.from[0].tableid),!t.get(l).has(_))if(r.has(_))_=r.get(_);else{Ln.info(`table specified as ${_} not found.`);return}t.get(l).get(_).indexOf(u.columnid)<0&&t.get(l).get(_).push(u.columnid)}}}a(H5,"getSelectAttributes");function x5(e,t,r){if(!e){Ln.info("getUpdateAttributes: invalid SQL syntax tree");return}let n=new ao(e.columns),s=e.table.databaseid;Ou(e.table,t,r);for(let{node:i}of n)i&&i.columnid&&hT(e.table.tableid,s,i.columnid,t,r)}a(x5,"getUpdateAttributes");function q5(e,t,r){if(!e){Ln.info("getDeleteAttributes: invalid SQL syntax tree");return}let n=new ao(e.where),s=e.table.databaseid;Ou(e.table,t,r);for(let{node:i}of n)i&&i.columnid&&hT(e.table.tableid,s,i.columnid,t,r)}a(q5,"getDeleteAttributes");function F5(e,t,r){if(!e){Ln.info("getInsertAttributes: invalid SQL syntax tree");return}let n=new ao(e.columns),s=e.into.databaseid;Ou(e.into,t,r);for(let{node:i}of n)i&&i.columnid&&hT(e.into.tableid,s,i.columnid,t,r)}a(F5,"getInsertAttributes");function hT(e,t,r,n,s){if(!n.get(t))return;let i=e;n.get(t).has(i)||(i=s.get(i)),n.get(t).get(i).push(r)}a(hT,"pushAttribute");vM.exports=ET});var ST=T((ufe,FM)=>{var Ld=Vi(),HM=require("chalk"),qr=K(),xM=require("prompt"),{promisify:G5}=require("util"),mT=U(),k5=require("fs-extra"),V5=require("path"),$5=J(),Y5=Sd(),qM=Z();qM.initSync();var K5=require("moment"),W5=G5(xM.get),Q5=V5.join(qM.getHdbBasePath(),mT.LICENSE_KEY_DIR_NAME,mT.LICENSE_FILE_NAME,mT.LICENSE_FILE_NAME);FM.exports={getFingerprint:J5,setLicense:z5,parseLicense:pT,register:j5,getRegistrationInfo:Z5};async function z5(e){if(e&&e.key&&e.company){try{qr.info(`parsing license key: ${e.key} and `);let t=e.company.toString();await pT(e.key.trim(),t.trim())}catch(t){let r="There was an error parsing the license key.";throw qr.error(r),qr.error(t),new Error(r)}return"Wrote license key file. Registration successful."}throw new Error("Invalid key or company specified for license file.")}a(z5,"setLicense");async function J5(){let e={};try{e=await Ld.generateFingerPrint()}catch(t){let r="Error generating fingerprint.";throw qr.error(r),qr.error(t),new Error(r)}return e}a(J5,"getFingerprint");async function pT(e,t){if(!e||!t)throw new Error("Invalid entries for License Key and Customer Company");qr.info("Validating license input...");let r=Ld.validateLicense(e,t);if(qr.info("checking for valid license..."),!r.valid_license)throw new Error("Invalid license found.");if(qr.info("checking valid license date..."),!r.valid_date)throw new Error("This License has expired.");if(qr.info(`checking for valid machine license ${r.valid_machine}`),!r.valid_machine)throw new Error("This license is in use on another machine.");try{qr.info("writing license to disk"),await k5.writeFile(Q5,JSON.stringify({license_key:e,company:t}))}catch(n){throw qr.error("Failed to write License"),n}return"Registration successful."}a(pT,"parseLicense");async function j5(){let e=await X5();return pT(e.HDB_LICENSE,e.CUSTOMER_COMPANY)}a(j5,"register");async function X5(){let e=await Ld.generateFingerPrint(),t={properties:{CUSTOMER_COMPANY:{description:HM.magenta("[COMPANY] Please enter your company name"),required:!0},HDB_LICENSE:{description:HM.magenta(`[HDB_LICENSE] Your fingerprint is ${e} Please enter your license key`),required:!0}}};try{xM.start()}catch(n){qr.error(n)}let r;try{r=await W5(t)}catch(n){throw console.error("There was a problem prompting for registration input. Exiting."),n}return r}a(X5,"promptForRegistration");async function Z5(){let e={registered:!1,version:null,ram_allocation:null,license_expiration_date:null},t;try{t=await Ld.getLicense()}catch(r){throw qr.error(`There was an error when searching licenses due to: ${r.message}`),r}if($5.isEmptyOrZeroLength(t))throw new Error("There were no licenses found.");if(e.registered=t.enterprise,e.version=Y5.version(),e.ram_allocation=t.ram_allocation,isNaN(t.exp_date))e.license_expiration_date=t.enterprise?t.exp_date:null;else{let r=K5.utc(t.exp_date).format("YYYY-MM-DD");e.license_expiration_date=t.enterprise?r:null}return e}a(Z5,"getRegistrationInfo")});var kM=T((_fe,GM)=>{"use strict";var e8=tt(),TT=class{static{a(this,"HubConfigObject")}constructor(t,r,n,s,i,o,c,u,_,l,d,f,E,h){this.port=t,o===null&&(o=void 0),this.server_name=r+e8.SERVER_SUFFIX.HUB,this.pid_file=n,this.max_payload=67108864,this.jetstream={enabled:!1},this.tls={cert_file:s,key_file:i,ca_file:o,insecure:c,verify:u},this.leafnodes={port:_,tls:{cert_file:s,key_file:i,ca_file:o,insecure:c}},this.cluster={name:l,port:d,routes:f,tls:{cert_file:s,key_file:i,ca_file:o,insecure:c,verify:u}},this.accounts={SYS:{users:E},HDB:{users:h}},this.system_account="SYS"}};GM.exports=TT});var YM=T((ffe,$M)=>{"use strict";var VM=tt(),gT=class{static{a(this,"LeafConfigObject")}constructor(t,r,n,s,i,o,c,u,_,l,d){this.port=t,d===null&&(d=void 0),this.server_name=r+VM.SERVER_SUFFIX.LEAF,this.pid_file=n,this.max_payload=67108864,this.jetstream={enabled:!0,store_dir:s,domain:r+VM.SERVER_SUFFIX.LEAF},this.tls={cert_file:_,key_file:l,ca_file:d,insecure:!0},this.leafnodes={remotes:[{tls:{ca_file:d,insecure:!0},urls:i,account:"SYS"},{tls:{ca_file:d,insecure:!0},urls:o,account:"HDB"}]},this.accounts={SYS:{users:c},HDB:{users:u,jetstream:"enabled"}},this.system_account="SYS"}};$M.exports=gT});var WM=T((hfe,KM)=>{"use strict";var RT=class{static{a(this,"HdbUserObject")}constructor(t,r){this.user=t,this.password=r}};KM.exports=RT});var zM=T((pfe,QM)=>{"use strict";var t8=tt(),AT=class{static{a(this,"SysUserObject")}constructor(t,r){this.user=t+t8.SERVER_SUFFIX.ADMIN,this.password=r}};QM.exports=AT});var yT=T((Tfe,XM)=>{"use strict";var la=require("path"),Pd=require("fs-extra"),r8=kM(),n8=YM(),s8=WM(),i8=zM(),OT=Ur(),da=J(),lr=Ir(),Ud=U(),bu=tt(),{CONFIG_PARAMS:ut}=Ud,yu=K(),Nu=Z(),JM=ps(),bT=ft(),_a="clustering",o8=1e4,jM=5;XM.exports={generateNatsConfig:c8,removeNatsConfig:u8,getHubConfigPath:a8};function a8(){let e=Nu.get(ut.ROOTPATH);return la.join(e,_a,bu.NATS_CONFIG_FILES.HUB_SERVER)}a(a8,"getHubConfigPath");async function c8(e=!1,t=void 0){Nu.initSync();let r=Nu.get(ut.ROOTPATH),n=la.join(r,_a,bu.PID_FILES.HUB),s=la.join(r,_a,bu.PID_FILES.LEAF),i=lr.getConfigFromFile(ut.CLUSTERING_LEAFSERVER_STREAMS_PATH),o=la.join(r,_a,bu.NATS_CONFIG_FILES.HUB_SERVER),c=la.join(r,_a,bu.NATS_CONFIG_FILES.LEAF_SERVER),u=lr.getConfigFromFile(ut.CLUSTERING_TLS_CERTIFICATE),_=lr.getConfigFromFile(ut.CLUSTERING_TLS_PRIVATEKEY),l=lr.getConfigFromFile(ut.CLUSTERING_TLS_CERT_AUTH),d=lr.getConfigFromFile(ut.CLUSTERING_TLS_INSECURE),f=lr.getConfigFromFile(ut.CLUSTERING_TLS_VERIFY),E=lr.getConfigFromFile(ut.CLUSTERING_NODENAME),h=lr.getConfigFromFile(ut.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT);await bT.checkNATSServerInstalled()||vd("nats-server dependency is either missing or the wrong version. Run 'npm install' to fix");let p=await OT.listUsers(),S=lr.getConfigFromFile(ut.CLUSTERING_USER),O=await OT.getClusterUser();(da.isEmpty(O)||O.active!==!0)&&vd(`Invalid cluster user '${S}'. A valid user with the role 'cluster_user' must be defined under clustering.user in harperdb-config.yaml`),e||(await Md(ut.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),await Md(ut.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT),await Md(ut.CLUSTERING_HUBSERVER_NETWORK_PORT),await Md(ut.CLUSTERING_LEAFSERVER_NETWORK_PORT));let g=[],R=[];for(let[z,se]of p.entries())se.role.role===Ud.ROLE_TYPES_ENUM.CLUSTER_USER&&se.active&&(g.push(new i8(se.username,JM.decrypt(se.hash))),R.push(new s8(se.username,JM.decrypt(se.hash))));let B=[],{hub_routes:H}=lr.getClusteringRoutes();if(!da.isEmptyOrZeroLength(H))for(let z of H)B.push(`tls://${O.sys_name_encoded}:${O.uri_encoded_d_hash}@${z.host}:${z.port}`);let v=new r8(lr.getConfigFromFile(ut.CLUSTERING_HUBSERVER_NETWORK_PORT),E,n,u,_,l,d,f,h,lr.getConfigFromFile(ut.CLUSTERING_HUBSERVER_CLUSTER_NAME),lr.getConfigFromFile(ut.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),B,g,R);l==null&&(delete v.tls.ca_file,delete v.leafnodes.tls.ca_file),t=da.isEmpty(t)?void 0:t.toLowerCase(),(t===void 0||t===Ud.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase())&&(await Pd.writeJson(o,v),yu.trace(`Hub server config written to ${o}`));let M=`tls://${O.sys_name_encoded}:${O.uri_encoded_d_hash}@0.0.0.0:${h}`,$=`tls://${O.uri_encoded_name}:${O.uri_encoded_d_hash}@0.0.0.0:${h}`,W=new n8(lr.getConfigFromFile(ut.CLUSTERING_LEAFSERVER_NETWORK_PORT),E,s,i,[M],[$],g,R,u,_,l,d);l==null&&delete W.tls.ca_file,(t===void 0||t===Ud.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())&&(await Pd.writeJson(c,W),yu.trace(`Leaf server config written to ${c}`))}a(c8,"generateNatsConfig");async function Md(e){let t=Nu.get(e);return da.isEmpty(t)&&vd(`port undefined for '${e}'`),await da.isPortTaken(t)&&vd(`'${e}' port '${t}' is is in use by another process, check to see if HarperDB is already running or another process is using this port.`),!0}a(Md,"isPortAvailable");function vd(e){let t=`Error generating clustering config: ${e}`;yu.error(t),console.error(t),process.exit(1)}a(vd,"generateNatsConfigError");async function u8(e){let{port:t,config_file:r}=bT.getServerConfig(e),{username:n,decrypt_hash:s}=await OT.getClusterUser(),i=0,o=2e3;for(;i<jM;){try{let _=await bT.createConnection(t,n,s,!1);if(_.protocol.connected===!0){_.close();break}}catch(_){yu.trace(`removeNatsConfig waiting for ${e}. Caught and swallowed error ${_}`)}if(i++,i>=jM)throw new Error(`Operations API timed out attempting to connect to ${e}. This is commonly caused by incorrect clustering config. Check hdb.log for further details.`);await da.async_set_timeout(o*(i*2))}let c="0".repeat(o8),u=la.join(Nu.get(ut.ROOTPATH),_a,r);await Pd.writeFile(u,c),await Pd.remove(u),yu.notify(e,"started.")}a(u8,"removeNatsConfig")});var sU=T((Rfe,nU)=>{"use strict";var Fr=Z(),l8=Vi(),Se=U(),wu=tt(),ys=require("path"),{PACKAGE_ROOT:Hd}=U(),ZM=Z(),Bd=J(),fa="/dev/null",_8=ys.join(Hd,"launchServiceScripts"),eU=ys.join(Hd,"utility/scripts"),d8=ys.join(eU,Se.HDB_RESTART_SCRIPT),tU=ys.resolve(Hd,"dependencies",`${process.platform}-${process.arch}`,wu.NATS_BINARY_NAME);function rU(){let t=l8.licenseSearch().ram_allocation||Se.RAM_ALLOCATION_ENUM.DEFAULT,r=Se.MEM_SETTING_KEY+t,n={[Se.PROCESS_NAME_ENV_PROP]:Se.PROCESS_DESCRIPTORS.HDB,IS_SCRIPTED_SERVICE:!0};return Bd.noBootFile()&&(n[Se.CONFIG_PARAMS.ROOTPATH.toUpperCase()]=Bd.getEnvCliRootPath()),{name:Se.PROCESS_DESCRIPTORS.HDB,script:Se.LAUNCH_SERVICE_SCRIPTS.MAIN,exec_mode:"fork",env:n,node_args:r,cwd:Hd}}a(rU,"generateMainServerConfig");var f8=9930;function E8(){Fr.initSync(!0);let e=Fr.get(Se.CONFIG_PARAMS.ROOTPATH),t=ys.join(e,"clustering",wu.NATS_CONFIG_FILES.HUB_SERVER),r=ys.join(Fr.get(Se.HDB_SETTINGS_NAMES.LOG_PATH_KEY),Se.LOG_NAMES.HDB),n=ZM.get(Se.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),s=wu.LOG_LEVEL_FLAGS[Fr.get(Se.CONFIG_PARAMS.CLUSTERING_LOGLEVEL)]??void 0,i={name:Se.PROCESS_DESCRIPTORS.CLUSTERING_HUB+(n!==f8?"-"+n:""),script:tU,args:s?`${s} -c ${t}`:`-c ${t}`,exec_mode:"fork",env:{[Se.PROCESS_NAME_ENV_PROP]:Se.PROCESS_DESCRIPTORS.CLUSTERING_HUB},merge_logs:!0,out_file:r,error_file:r,instances:1};return Fr.get(Se.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(i.out_file=fa,i.error_file=fa),i}a(E8,"generateNatsHubServerConfig");var h8=9940;function m8(){Fr.initSync(!0);let e=Fr.get(Se.CONFIG_PARAMS.ROOTPATH),t=ys.join(e,"clustering",wu.NATS_CONFIG_FILES.LEAF_SERVER),r=ys.join(Fr.get(Se.HDB_SETTINGS_NAMES.LOG_PATH_KEY),Se.LOG_NAMES.HDB),n=ZM.get(Se.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),s=wu.LOG_LEVEL_FLAGS[Fr.get(Se.CONFIG_PARAMS.CLUSTERING_LOGLEVEL)]??void 0,i={name:Se.PROCESS_DESCRIPTORS.CLUSTERING_LEAF+(n!==h8?"-"+n:""),script:tU,args:s?`${s} -c ${t}`:`-c ${t}`,exec_mode:"fork",env:{[Se.PROCESS_NAME_ENV_PROP]:Se.PROCESS_DESCRIPTORS.CLUSTERING_LEAF},merge_logs:!0,out_file:r,error_file:r,instances:1};return Fr.get(Se.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(i.out_file=fa,i.error_file=fa),i}a(m8,"generateNatsLeafServerConfig");function p8(){Fr.initSync();let e=ys.join(Fr.get(Se.CONFIG_PARAMS.LOGGING_ROOT),Se.LOG_NAMES.HDB),t={name:Se.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0,script:Se.LAUNCH_SERVICE_SCRIPTS.NODES_UPGRADE_4_0_0,exec_mode:"fork",env:{[Se.PROCESS_NAME_ENV_PROP]:Se.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0},merge_logs:!0,out_file:e,error_file:e,instances:1,cwd:_8,autorestart:!1};return Fr.get(Se.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(t.out_file=fa,t.error_file=fa),t}a(p8,"generateClusteringUpgradeV4ServiceConfig");function S8(){let e={[Se.PROCESS_NAME_ENV_PROP]:Se.PROCESS_DESCRIPTORS.RESTART_HDB};return Bd.noBootFile()&&(e[Se.CONFIG_PARAMS.ROOTPATH.toUpperCase()]=Bd.getEnvCliRootPath()),{...{name:Se.PROCESS_DESCRIPTORS.RESTART_HDB,exec_mode:"fork",env:e,instances:1,autorestart:!1,cwd:eU},script:d8}}a(S8,"generateRestart");function T8(){return{apps:[rU()]}}a(T8,"generateAllServiceConfigs");nU.exports={generateAllServiceConfigs:T8,generateMainServerConfig:rU,generateRestart:S8,generateNatsHubServerConfig:E8,generateNatsLeafServerConfig:m8,generateClusteringUpgradeV4ServiceConfig:p8}});var SU=T((bfe,pU)=>{"use strict";var Me=U(),g8=J(),Ns=yT(),Iu=ft(),Xn=tt(),ui=sU(),xd=Z(),li=K(),R8=bs(),{startWorker:iU,onMessageFromWorkers:A8}=Ze(),O8=ua(),Ofe=require("util"),b8=require("child_process"),y8=require("fs"),{execFile:N8}=b8,we;pU.exports={enterPM2Mode:w8,start:_i,stop:NT,reload:aU,restart:cU,list:wT,describe:lU,connect:ws,kill:M8,startAllServices:U8,startService:IT,getUniqueServicesList:_U,restartAllServices:P8,isServiceRegistered:dU,reloadStopStart:fU,restartHdb:uU,deleteProcess:D8,startClusteringProcesses:hU,startClusteringThreads:mU,isHdbRestartRunning:L8,isClusteringRunning:B8,stopClustering:v8,reloadClustering:H8};var Cu=!1;A8(e=>{e.type==="restart"&&xd.initSync(!0)});function w8(){Cu=!0}a(w8,"enterPM2Mode");function ws(){return we||(we=require("pm2")),new Promise((e,t)=>{we.connect((r,n)=>{li.setupConsoleLogging(),r&&t(r),e(n)})})}a(ws,"connect");var _r,I8=10,oU;function _i(e,t=!1){if(Cu)return C8(e);let r=N8(e.script,e.args.split(" "),e);r.name=e.name,r.on("exit",async i=>{let o=_r.indexOf(r);o>-1&&_r.splice(o,1),!oU&&i!==0&&(e.restarts=(e.restarts||0)+1,e.restarts<I8&&(y8.existsSync(Ns.getHubConfigPath())?_i(e):(await Ns.generateNatsConfig(!0),_i(e),await new Promise(c=>setTimeout(c,3e3)),await Ns.removeNatsConfig(Me.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await Ns.removeNatsConfig(Me.PROCESS_DESCRIPTORS.CLUSTERING_LEAF))))});let n={serviceName:e.name.replace(/ /g,"-")};function s(i){let o=xd.get(Me.CONFIG_PARAMS.CLUSTERING_LOGLEVEL),c=/\[\d+][^\[]+\[(\w+)]/g,u,_=0,l;for(;u=c.exec(i);){if(u.index&&Xn.LOG_LEVEL_HIERARCHY[o]>=Xn.LOG_LEVEL_HIERARCHY[l||"info"]){let E=l===Xn.LOG_LEVELS.ERR||l===Xn.LOG_LEVELS.WRN?li.OUTPUTS.STDERR:li.OUTPUTS.STDOUT;li.logCustomLevel(l||"info",E,n,i.slice(_,u.index).trim())}let[d,f]=u;_=u.index+d.length,l=Xn.LOG_LEVELS[f]}if(Xn.LOG_LEVEL_HIERARCHY[o]>=Xn.LOG_LEVEL_HIERARCHY[l||"info"]){let d=l===Xn.LOG_LEVELS.ERR||l===Xn.LOG_LEVELS.WRN?li.OUTPUTS.STDERR:li.OUTPUTS.STDOUT;li.logCustomLevel(l||"info",d,n,i.slice(_).trim())}}if(a(s,"extractMessages"),r.stdout.on("data",s),r.stderr.on("data",s),r.unref(),_r=[],!_r&&!t){let i=a(()=>{oU=!0,_r&&(_r.map(o=>o.kill()),process.exit(0))},"kill_children");process.on("exit",i),process.on("SIGINT",i),process.on("SIGQUIT",i),process.on("SIGTERM",i)}_r.push(r)}a(_i,"start");function C8(e){return new Promise(async(t,r)=>{try{await ws()}catch(n){r(n)}we.start(e,(n,s)=>{n&&(we.disconnect(),r(n)),we.disconnect(),t(s)})})}a(C8,"startWithPM2");function NT(e){if(!Cu){for(let t of _r||[])t.name===e&&(_r.splice(_r.indexOf(t),1),t.kill());return}return new Promise(async(t,r)=>{try{await ws()}catch(n){r(n)}we.stop(e,async(n,s)=>{n&&(we.disconnect(),r(n)),we.delete(e,(i,o)=>{i&&(we.disconnect(),r(n)),we.disconnect(),t(o)})})})}a(NT,"stop");function aU(e){return new Promise(async(t,r)=>{try{await ws()}catch(n){r(n)}we.reload(e,(n,s)=>{n&&(we.disconnect(),r(n)),we.disconnect(),t(s)})})}a(aU,"reload");function cU(e){if(!Cu)for(let t of _r||[])t.name===e&&t.kill();return new Promise(async(t,r)=>{try{await ws()}catch(n){r(n)}we.restart(e,(n,s)=>{we.disconnect(),t(s)})})}a(cU,"restart");function D8(e){return new Promise(async(t,r)=>{try{await ws()}catch(n){r(n)}we.delete(e,(n,s)=>{n&&(we.disconnect(),r(n)),we.disconnect(),t(s)})})}a(D8,"deleteProcess");async function uU(){await _i(ui.generateRestart())}a(uU,"restartHdb");async function L8(){let e=await wT();for(let t in e)if(e[t].name===Me.PROCESS_DESCRIPTORS.RESTART_HDB)return!0;return!1}a(L8,"isHdbRestartRunning");function wT(){return new Promise(async(e,t)=>{try{await ws()}catch(r){t(r)}we.list((r,n)=>{r&&(we.disconnect(),t(r)),we.disconnect(),e(n)})})}a(wT,"list");function lU(e){return new Promise(async(t,r)=>{try{await ws()}catch(n){r(n)}we.describe(e,(n,s)=>{n&&(we.disconnect(),r(n)),we.disconnect(),t(s)})})}a(lU,"describe");function M8(){if(!Cu){for(let e of _r||[])e.kill();_r=[];return}return new Promise(async(e,t)=>{try{await ws()}catch(r){t(r)}we.killDaemon((r,n)=>{r&&(we.disconnect(),t(r)),we.disconnect(),e(n)})})}a(M8,"kill");async function U8(){try{await hU(),await mU(),await _i(ui.generateAllServiceConfigs())}catch(e){throw we?.disconnect(),e}}a(U8,"startAllServices");async function IT(e,t=!1){try{let r;switch(e=e.toLowerCase(),e){case Me.PROCESS_DESCRIPTORS.HDB.toLowerCase():r=ui.generateMainServerConfig();break;case Me.PROCESS_DESCRIPTORS.CLUSTERING_INGEST_SERVICE.toLowerCase():r=ui.generateNatsIngestServiceConfig();break;case Me.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE.toLowerCase():r=ui.generateNatsReplyServiceConfig();break;case Me.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase():r=ui.generateNatsHubServerConfig(),await _i(r,t),await Ns.removeNatsConfig(e);return;case Me.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase():r=ui.generateNatsLeafServerConfig(),await _i(r,t),await Ns.removeNatsConfig(e);return;case Me.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0.toLowerCase():r=ui.generateClusteringUpgradeV4ServiceConfig();break;default:throw new Error(`Start service called with unknown service config: ${e}`)}await _i(r)}catch(r){throw we?.disconnect(),r}}a(IT,"startService");async function _U(){try{let e=await wT(),t={};for(let r=0,n=e.length;r<n;r++){let s=e[r];t[s.name]===void 0&&(t[s.name]={name:s.name,exec_mode:s.pm2_env.exec_mode})}return t}catch(e){throw we?.disconnect(),e}}a(_U,"getUniqueServicesList");async function P8(e=[]){try{let t=!1,r=await _U();for(let n=0,s=Object.values(r).length;n<s;n++){let o=Object.values(r)[n].name;e.includes(o)||(o===Me.PROCESS_DESCRIPTORS.HDB?t=!0:await cU(o))}t&&await fU(Me.PROCESS_DESCRIPTORS.HDB)}catch(t){throw we?.disconnect(),t}}a(P8,"restartAllServices");async function dU(e){if(_r?.find(r=>r.name===e))return!0;let t=await O8.getHDBProcessInfo();return t.core.length&&t.core[0]?.parent==="PM2"}a(dU,"isServiceRegistered");async function fU(e){let t=e===Me.PROCESS_DESCRIPTORS.HDB?xd.get(Me.HDB_SETTINGS_NAMES.MAX_HDB_PROCESSES):xd.get(Me.HDB_SETTINGS_NAMES.MAX_CUSTOM_FUNCTION_PROCESSES),r=await lU(e),n=g8.isEmptyOrZeroLength(r)?0:r.length;t!==n?(await NT(e),await IT(e)):e===Me.PROCESS_DESCRIPTORS.HDB?await uU():await aU(e)}a(fU,"reloadStopStart");var EU;async function hU(e=!1){for(let t in Me.CLUSTERING_PROCESSES){let r=Me.CLUSTERING_PROCESSES[t];await IT(r,e)}}a(hU,"startClusteringProcesses");async function mU(){EU=iU(Me.LAUNCH_SERVICE_SCRIPTS.NATS_REPLY_SERVICE,{name:Me.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE}),await Iu.createWorkQueueStream(Xn.WORK_QUEUE_CONSUMER_NAMES),await Iu.updateIngestStreamConsumer(),await Iu.updateLocalStreams();let e=await R8.getAllNodeRecords();for(let t=0,r=e.length;t<r;t++)if(e[t].system_info?.hdb_version===Me.PRE_4_0_0_VERSION){li.info("Starting clustering upgrade 4.0.0 process"),iU(Me.LAUNCH_SERVICE_SCRIPTS.NODES_UPGRADE_4_0_0,{name:"Upgrade-4-0-0"});break}}a(mU,"startClusteringThreads");async function v8(){for(let e in Me.CLUSTERING_PROCESSES)if(e!==Me.CLUSTERING_PROCESSES.CLUSTERING_INGEST_PROC_DESCRIPTOR)if(e===Me.CLUSTERING_PROCESSES.CLUSTERING_REPLY_SERVICE_DESCRIPTOR)await EU.terminate();else{let t=Me.CLUSTERING_PROCESSES[e];await NT(t)}}a(v8,"stopClustering");async function B8(){for(let e in Me.CLUSTERING_PROCESSES){let t=Me.CLUSTERING_PROCESSES[e];if(await dU(t)===!1)return!1}return!0}a(B8,"isClusteringRunning");async function H8(){await Ns.generateNatsConfig(!0),await Iu.reloadNATSHub(),await Iu.reloadNATSLeaf(),await Ns.removeNatsConfig(Me.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase()),await Ns.removeNatsConfig(Me.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())}a(H8,"reloadClustering")});var kd=T((Nfe,yU)=>{"use strict";var x8=require("minimist"),{isMainThread:LT,parentPort:RU}=require("worker_threads"),rt=U(),{PROCESS_DESCRIPTORS_VALIDATE:Du}=rt,Zn=K(),MT=J(),qd=yT(),Ea=ft(),CT=tt(),AU=Ir(),es=SU(),TU=ua(),q8=rh(),{restartWorkers:Fd,onMessageByType:F8}=Ze(),{handleHDBError:G8,hdb_errors:k8}=ee(),{HTTP_STATUS_CODES:V8}=k8,Gd=Z();Gd.initSync();var Lu=`Restarting HarperDB. This may take up to ${rt.RESTART_TIMEOUT_MS/1e3} seconds.`,$8="Restart is not available from the CLI when running in non-pm2 mode. Either call restart from the API or stop and start HarperDB.",gU="Clustering is not enabled so cannot be restarted",Y8="Invalid service",ha,sn;yU.exports={restart:OU,restartService:UT};LT&&F8(rt.ITC_EVENT_TYPES.RESTART,e=>{e.workerType?UT({service:e.workerType}):OU({operation:"restart"})});async function OU(e){sn=Object.keys(e).length===0,ha=await es.isServiceRegistered(rt.HDB_PROC_DESCRIPTOR);let t=x8(process.argv);if(t.service){await UT(t);return}if(sn&&!ha){console.error($8);return}if(sn&&console.log(Lu),ha){es.enterPM2Mode(),Zn.notify(Lu);let r=q8(Object.keys(rt.CONFIG_PARAM_MAP),!0);return MT.isEmptyOrZeroLength(Object.keys(r))||AU.updateConfigValue(void 0,void 0,r,!0,!0),W8(),Lu}return LT?(Zn.notify(Lu),setTimeout(()=>{Fd()},50)):RU.postMessage({type:rt.ITC_EVENT_TYPES.RESTART}),Lu}a(OU,"restart");async function UT(e){let{service:t}=e;if(rt.PROCESS_DESCRIPTORS_VALIDATE[t]===void 0)throw G8(new Error,Y8,V8.BAD_REQUEST,void 0,void 0,!0);if(ha=await es.isServiceRegistered(rt.HDB_PROC_DESCRIPTOR),!LT)return RU.postMessage({type:rt.ITC_EVENT_TYPES.RESTART,workerType:t}),t==="custom_functions"&&(t="Custom Functions"),`Restarting ${t}`;let r;switch(t){case Du.clustering:if(!Gd.get(rt.CONFIG_PARAMS.CLUSTERING_ENABLED)){r=gU;break}sn&&console.log("Restarting clustering"),Zn.notify("Restarting clustering"),await bU();break;case Du.clustering_config:case Du["clustering config"]:if(!Gd.get(rt.CONFIG_PARAMS.CLUSTERING_ENABLED)){r=gU;break}sn&&console.log("Restarting clustering_config"),Zn.notify("Restarting clustering_config"),await es.reloadClustering();break;case"custom_functions":case"custom functions":case Du.harperdb:case Du.http_workers:if(sn&&!ha){r=`Restart ${t} is not available from the CLI when running in non-pm2 mode. Either call restart ${t} from the API or stop and start HarperDB.`;break}sn&&console.log("Restarting http_workers"),Zn.notify("Restarting http_workers"),sn?await es.restart(rt.HDB_PROC_DESCRIPTOR):setTimeout(()=>{Fd("http")},200);break;default:r=`Unrecognized service: ${t}`;break}return r?(Zn.error(r),sn&&console.error(r),r):(t==="custom_functions"&&(t="Custom Functions"),`Restarting ${t}`)}a(UT,"restartService");async function K8(){await Ea.publishToStream(`${CT.SUBJECT_PREFIXES.TXN}.${CT.WORK_QUEUE_CONSUMER_NAMES.stream_name}`,CT.WORK_QUEUE_CONSUMER_NAMES.stream_name,Ea.addNatsMsgHeader({operation:"dummy_msg"},void 0),{operation:"dummy_msg"})}a(K8,"postDummyNatsMsg");async function W8(){await bU(),await es.restart(rt.HDB_PROC_DESCRIPTOR),await MT.async_set_timeout(2e3),Gd.get(rt.CONFIG_PARAMS.CLUSTERING_ENABLED)&&await DT(),sn&&(await Ea.closeConnection(),process.exit(0))}a(W8,"restartPM2Mode");async function bU(){if(!AU.getConfigFromFile(rt.CONFIG_PARAMS.CLUSTERING_ENABLED))return;if((await TU.getHDBProcessInfo()).clustering.length===0)Zn.trace("Clustering not running, restart will start clustering services"),await qd.generateNatsConfig(!0),await es.startClusteringProcesses(),await es.startClusteringThreads(),await DT(),sn&&await Ea.closeConnection();else{await K8(),await qd.generateNatsConfig(!0),ha?(Zn.trace("Restart clustering restarting PM2 managed Hub and Leaf servers"),await es.restart(rt.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await es.restart(rt.PROCESS_DESCRIPTORS.CLUSTERING_LEAF)):(await TU.getHDBProcessInfo()).clustering.forEach(s=>{Zn.trace("Restart clustering killing process pid",s.pid),process.kill(s.pid)}),await MT.async_set_timeout(3e3),await DT(),await Ea.updateLocalStreams(),sn&&await Ea.closeConnection(),Zn.trace("Restart clustering restarting ingest and reply service threads");let t=Fd(rt.LAUNCH_SERVICE_SCRIPTS.NATS_INGEST_SERVICE),r=Fd(rt.LAUNCH_SERVICE_SCRIPTS.NATS_REPLY_SERVICE);await t,await r}}a(bU,"restartClustering");async function DT(){await qd.removeNatsConfig(rt.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await qd.removeNatsConfig(rt.PROCESS_DESCRIPTORS.CLUSTERING_LEAF)}a(DT,"removeNatsConfig")});var BU=T((Cfe,vU)=>{"use strict";var Ife=require("lodash"),dr=U(),{handleHDBError:NU,hdb_errors:Q8}=ee(),{HDB_ERROR_MSGS:z8,HTTP_STATUS_CODES:J8}=Q8,PT=K();vU.exports={getRolePermissions:X8};var co=Object.create(null),j8=a(e=>({key:e,perms:{}}),"perms_template_obj"),DU=a((e=!1)=>({describe:e,tables:{}}),"schema_perms_template"),LU=a((e=!1,t=!1,r=!1,n=!1)=>({[dr.PERMS_CRUD_ENUM.READ]:e,[dr.PERMS_CRUD_ENUM.INSERT]:t,[dr.PERMS_CRUD_ENUM.UPDATE]:r,[dr.PERMS_CRUD_ENUM.DELETE]:n}),"permissions_template"),vT=a((e=!1,t=!1,r=!1,n=!1,s=!1)=>({attribute_permissions:[],describe:e,...LU(t,r,n,s)}),"table_perms_template"),wU=a((e,t=LU())=>({attribute_name:e,describe:PU(t),[Mu]:t[Mu],[BT]:t[BT],[HT]:t[HT]}),"attr_perms_template"),IU=a((e,t=!1)=>({attribute_name:e,describe:t,[Mu]:t}),"timestamp_attr_perms_template"),{READ:Mu,INSERT:BT,UPDATE:HT}=dr.PERMS_CRUD_ENUM,MU=Object.values(dr.PERMS_CRUD_ENUM),UU=[Mu,BT,HT];function X8(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[dr.SYSTEM_SCHEMA_NAME],t=e.role;let n=JSON.stringify([e.__updatedtime__,r]);if(co[t]&&co[t].key===n)return co[t].perms;let s=Z8(e,r);return co[t]?co[t].key=n:co[t]=j8(n),co[t].perms=s,s}catch(r){if(!e[dr.TIME_STAMP_NAMES_ENUM.UPDATED_TIME]||e[dr.TIME_STAMP_NAMES_ENUM.UPDATED_TIME]<dr.PERMS_UPDATE_RELEASE_TIMESTAMP){let n=`Role permissions for role '${t}' must be updated to align with new structure from the 2.2.0 release.`;throw PT.error(n),PT.debug(r),NU(new Error,z8.OUTDATED_PERMS_TRANSLATION_ERROR,J8.BAD_REQUEST)}else{let n=`There was an error while translating role permissions for role: ${t}.
|
|
11
|
+
${r.stack}`;throw PT.error(n),NU(new Error)}}}a(X8,"getRolePermissions");function Z8(e,t){let r=Object.create(null);r.super_user=!1;let n=e.permission;r[dr.SYSTEM_SCHEMA_NAME]=n[dr.SYSTEM_SCHEMA_NAME],r.structure_user=n.structure_user;let s=Array.isArray(e.permission.structure_user)||e.permission.structure_user===!0?e.permission.structure_user:[];return Object.keys(t).forEach(i=>{if(s===!0||s.indexOf(i)>-1){r[i]=e6(t[i]);return}r[i]=DU(),n[i]?(n[i].describe&&(r[i].describe=!0),Object.keys(t[i]).forEach(o=>{if(n[i].tables[o]){let c=n[i].tables[o],u=t[i][o],_=t6(c,u);r[i].describe||MU.forEach(l=>{_[l]&&(r[i].describe=!0)}),r[i].tables[o]=_}else r[i].tables[o]=vT()})):Object.keys(t[i]).forEach(o=>{r[i].tables[o]=vT()})}),r}a(Z8,"translateRolePermissions");function e6(e){let t=DU(!0);return Object.keys(e).forEach(r=>{t.tables[r]=vT(!0,!0,!0,!0,!0)}),t}a(e6,"createStructureUserPermissions");function t6(e,t){let{attribute_permissions:r}=e;if(r.length>0){let s=Object.assign({},e);s.attribute_permissions=[];let i=r.reduce((_,l)=>{let{attribute_name:d}=l,f=l;return dr.TIME_STAMP_NAMES.includes(d)&&(f=IU(d,l[Mu])),_[d]=f,_},{}),o=t.primaryKey||t.hash_attribute,c=!!i[o],u=wU(o);return t.attributes.forEach(({attribute:_})=>{if(i[_]){let l=i[_];l.describe=PU(l),s.attribute_permissions.push(l),c||r6(l,u)}else if(_!==o){let l;dr.TIME_STAMP_NAMES.includes(_)?l=IU(_):l=wU(_),s.attribute_permissions.push(l)}}),c||s.attribute_permissions.push(u),s.describe=CU(s),s}else return e.describe=CU(e),e}a(t6,"getTableAttrPerms");function CU(e){return MU.filter(t=>e[t]).length>0}a(CU,"getSchemaTableDescribePerm");function PU(e){return UU.filter(t=>e[t]).length>0}a(PU,"getAttributeDescribePerm");function r6(e,t){UU.forEach(r=>{e[r]&&!t[r]&&(t[r]=!0,t.describe=!0)})}a(r6,"checkForHashPerms")});var HU={};ke(HU,{Resources:()=>Vd,keyArrayToString:()=>ma,resetResources:()=>n6,resources:()=>di});function n6(){return di=new Vd}function ma(e){return Array.isArray(e)?e[e.length-1]===null?e.slice(0,-1).join("/")+"/":e.join("/"):e}var Vd,di,Uu=Oe(()=>{zi();Vd=class extends Map{static{a(this,"Resources")}isWorker=!0;loginPath;set(t,r,n,s){if(!r)throw new Error("Must provide a resource");t.startsWith("/")&&(t=t.replace(/^\/+/,""));let i={Resource:r,path:t,type:n,hasSubPaths:!1,relativeURL:""},o=super.get(t);if(o&&(o.Resource.databaseName!==r.databaseName||o.Resource.tableName!==r.tableName)&&!s)throw new Error(`Conflicting paths for ${t}`);super.set(t,i);for(let[c,u]of this){let _=2;for(;(_=c.indexOf("/",_))>-1;){let l=this.get(c.slice(0,_));l&&(l.hasSubPaths=!0),_+=2}}}getMatch(t,r){let n=2,s;for(;(n=t.indexOf("/",n))>-1;){let c=t.slice(0,n),u=this.get(c);if(u){if(u.relativeURL=t.slice(n),!u.hasSubPaths)return u;s=u}n+=2}if(s)return s;let i=t.indexOf("?"),o=i>-1?t.slice(0,i):t;return s=this.get(o),s?s.relativeURL=i>-1?t.slice(i):"":s||(s=this.get(""),s&&(t[0]!=="/"&&(t="/"+t),s.relativeURL=t)),s}getResource(t,r){let n=this.getMatch(t);if(n)return t=n.relativeURL,n.Resource.getResource(this.pathToId(t,n.Resource),r)}call(t,r,n){return Ke(r,async()=>{let s=this.getMatch(t);if(s)return t=s.relativeURL,n(s.Resource,s.path,t)})}setRepresentation(t,r,n){}};a(n6,"resetResources");a(ma,"keyArrayToString")});var xU={};ke(xU,{Headers:()=>fi});var fi,$d=Oe(()=>{fi=class extends Map{static{a(this,"Headers")}set(t,r){return typeof t!="string"&&(t=""+t),typeof r!="string"&&(r=""+r),super.set(t.toLowerCase(),[t,r])}get(t){return typeof t!="string"&&(t=""+t),super.get(t.toLowerCase())?.[1]}has(t){return typeof t!="string"&&(t=""+t),super.has(t.toLowerCase())}setIfNone(t,r){typeof t!="string"&&(t=""+t),typeof r!="string"&&(r=""+r);let n=t.toLowerCase();if(!super.has(n))return super.set(n,[t,r])}append(t,r,n){typeof t!="string"&&(t=""+t),typeof r!="string"&&(r=""+r);let s=t.toLowerCase(),i=super.get(s);if(i){let o=i[1];n?r=(typeof o=="string"?o:o.join(", "))+", "+r:typeof o=="string"?r=[o,r]:o.push(r)}return super.set(s,[t,r])}[Symbol.iterator](){return super.values()[Symbol.iterator]()}}});var Pu={};ke(Pu,{authentication:()=>KU,bypassAuth:()=>l6,login:()=>d6,logout:()=>f6,start:()=>_6});function l6(){YU=!0}async function KU(e,t){let r=e.headers.asObject,n=r.authorization,s=r.cookie,i=r.origin,o=[];try{if(i){let E=e.isOperationsServer?a6?o6:[]:i6?s6:[];if(E.includes(i)||E.includes("*")){if(e.method==="OPTIONS"){let h=new fi([["Access-Control-Allow-Methods","POST, GET, PUT, DELETE, PATCH, OPTIONS"],["Access-Control-Allow-Headers","Accept, Content-Type, Authorization"],["Access-Control-Allow-Origin",i]]);return Yd&&h.set("Access-Control-Allow-Credentials","true"),{status:200,headers:h}}o.push("Access-Control-Allow-Origin",i),Yd&&o.push("Access-Control-Allow-Credentials","true")}}let u,_;if(Yd){let E=(i?i.replace(/^https?:\/\//,"").replace(/\W/,"_")+"-":"")+"hdb-session=",h=s?.indexOf(E);if(h>=0){let p=s.indexOf(";",h),S=s.indexOf("=",h);u=s.slice(S+1,p===-1?s.length:p),_=await FU.get(u)}e.session=_||(_={})}e.user=null;let l=a((E,h,p)=>{let S=new Wd.AuthAuditLog(E,h,xt.AUTH_AUDIT_TYPES.AUTHENTICATION,r["x-forwarded-for"]??e.ip,e.method,e.pathname);S.auth_strategy=p,u&&(S.session_id=u),r.referer&&(S.referer=r.referer),r.origin&&(S.origin=r.origin),h===xt.AUTH_AUDIT_STATUS.SUCCESS?qU.notify(S):qU.error(S)},"authAuditLog");if(e.mtlsConfig&&e.authorized){let E=e.mtlsConfig.user;E!==null&&((E===void 0||E==="Common Name"||E==="CN")&&(E=e.peerCertificate.subject.CN),e.user=await Xe.getUser(E,null,null))}let d;if(!e.user)if(n){if(d=uo.get(n),!d){let[E,h]=n.split(" "),p,S;try{switch(E){case"Basic":[p,S]=atob(h).split(":"),d=p||S?await Xe.getUser(p,S,e):null;break;case"Bearer":try{d=await(0,Kd.validateOperationToken)(h)}catch(O){if(O.message==="invalid token")try{return await(0,Kd.validateRefreshToken)(h),c({status:-1})}catch{throw O}}break}}catch(O){return u6&&(uo.get(h)||(uo.set(h,h),l(p,xt.AUTH_AUDIT_STATUS.FAILURE,E))),c({status:401,body:Ei({error:O.message},e)})}uo.set(n,d),c6&&l(d.username,xt.AUTH_AUDIT_STATUS.SUCCESS,E)}e.user=d}else _?.user?e.user=await Xe.getUser(_.user,null,e):(YU&&(e.ip?.includes("127.0.0.1")||e.ip=="::1")||e?._nodeRequest?.socket?.server?._pipeName&&e.ip===void 0)&&(e.user=await(0,kU.getSuperUser)());Yd&&(e.session.update=function(E){if(!u){u=(0,VU.v4)();let p=`${(i?i.replace(/^https?:\/\//,"").replace(/\W/,"_")+"-":"")+"hdb-session="}${u}; Path=/; Expires=Tue, 01 Oct 8307 19:33:20 GMT; HttpOnly${e.protocol==="https"?"; SameSite=None; Secure":""}`;o?o.push("Set-Cookie",p):f?.headers?.set&&f.headers.set("Set-Cookie",p)}return e.protocol==="https"&&(o?(i&&o.push("Access-Control-Expose-Headers","X-Hdb-Session"),o.push("X-Hdb-Session","Secure")):f?.headers?.set&&(i&&f.headers.set("Access-Control-Expose-Headers","X-Hdb-Session"),f.headers.set("X-Hdb-Session","Secure"))),E.id=u,FU.put(E)},e.login=async function(E,h){e.user=await Xe.getUser(E,h,e),e.session.update({user:e.user.username})},(d&&!_||_?.user?.username!==d?.username)&&r["user-agent"]?.startsWith("Mozilla")&&e.session.update({user:e.user.username}));let f=await t(e);return f&&(f.status===401&&(r["user-agent"]?.startsWith("Mozilla")&&r.accept?.startsWith("text/html")&&di.loginPath?(f.status=302,f.headers.set("Location",di.loginPath(e))):f.headers.set("WWW-Authenticate","Basic")),c(f))}catch(u){throw c(u)}function c(u){let _=o.length;if(_>0){let l=u.headers;l||(u.headers=l=new fi);for(let d=0;d<_;){let f=o[d++];l.set(f,o[d++])}}return o=null,u}a(c,"applyResponseHeaders")}function _6({server:e,port:t}){e.request(KU,{port:t||"all"}),GU||(GU=!0,setInterval(()=>{uo=new Map},on.get(xt.CONFIG_PARAMS.AUTHENTICATION_CACHETTL)).unref(),$U.user.addListener(()=>{uo=new Map}))}async function d6(e){if(!e.baseRequest?.login)throw new Error("No session for login");return e.baseResponse.headers.set=(t,r)=>{e.fastifyResponse.header(t,r)},await e.baseRequest.login(e.username,e.password),"Login successful"}async function f6(e){if(!e.baseRequest.session)throw new Error("No session for logout");return await e.baseRequest.session.update({user:null}),"Logout successful"}var kU,Kd,VU,on,xt,Wd,$U,qU,s6,i6,o6,a6,FU,Yd,YU,c6,u6,uo,GU,Qd=Oe(()=>{kU=x(Ur());Xt();Uu();Kd=x(Eu());be();VU=require("uuid"),on=x(Z()),xt=x(U()),Wd=x(K()),$U=x(vc());$d();pa();qU=(0,Wd.loggerWithTag)("auth-event");on.initSync();s6=on.get(xt.CONFIG_PARAMS.HTTP_CORSACCESSLIST),i6=on.get(xt.CONFIG_PARAMS.HTTP_CORS),o6=on.get(xt.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_CORSACCESSLIST),a6=on.get(xt.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_CORS),FU=ot({table:"hdb_session",database:"system",attributes:[{name:"id",isPrimaryKey:!0},{name:"user"}]}),Yd=on.get(xt.CONFIG_PARAMS.AUTHENTICATION_ENABLESESSIONS)??!0,YU=on.get(xt.CONFIG_PARAMS.AUTHENTICATION_AUTHORIZELOCAL)??process.env.DEV_MODE,c6=on.get(xt.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)??!1,u6=on.get(xt.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGFAILED)??!1,uo=new Map;Xe.onInvalidatedUser(()=>{uo=new Map});a(l6,"bypassAuth");a(KU,"authentication");a(_6,"start");a(d6,"login");a(f6,"logout")});var ZU=T((Ffe,XU)=>{"use strict";var Ie=require("joi"),WU=require("fs-extra"),QU=require("path"),Cs=je(),zU=Z(),JU=U(),jU=K(),{hdb_errors:E6}=ee(),{HDB_ERROR_MSGS:Wt}=E6,Is=/^[a-zA-Z0-9-_]+$/;XU.exports={getDropCustomFunctionValidator:m6,setCustomFunctionValidator:p6,addComponentValidator:R6,dropCustomFunctionProjectValidator:A6,packageComponentValidator:O6,deployComponentValidator:b6,setComponentFileValidator:S6,getComponentFileValidator:g6,dropComponentFileValidator:T6};function zd(e,t,r){try{let n=zU.get(JU.CONFIG_PARAMS.COMPONENTSROOT),s=QU.join(n,t);return WU.existsSync(s)?e?t:r.message(Wt.PROJECT_EXISTS):e?r.message(Wt.NO_PROJECT):t}catch(n){return jU.error(n),r.message(Wt.VALIDATION_ERR)}}a(zd,"checkProjectExists");function vu(e,t){return e.includes("..")?t.message("Invalid file path"):e}a(vu,"checkFilePath");function h6(e,t,r,n){try{let s=zU.get(JU.CONFIG_PARAMS.COMPONENTSROOT),i=QU.join(s,e,t,r+".js");return WU.existsSync(i)?r:n.message(Wt.NO_FILE)}catch(s){return jU.error(s),n.message(Wt.VALIDATION_ERR)}}a(h6,"checkFileExists");function m6(e){let t=Ie.object({project:Ie.string().pattern(Is).custom(zd.bind(null,!0)).required().messages({"string.pattern.base":Wt.BAD_PROJECT_NAME}),type:Ie.string().valid("helpers","routes").required(),file:Ie.string().pattern(Is).custom(h6.bind(null,e.project,e.type)).custom(vu).required().messages({"string.pattern.base":Wt.BAD_FILE_NAME})});return Cs.validateBySchema(e,t)}a(m6,"getDropCustomFunctionValidator");function p6(e){let t=Ie.object({project:Ie.string().pattern(Is).custom(zd.bind(null,!0)).required().messages({"string.pattern.base":Wt.BAD_PROJECT_NAME}),type:Ie.string().valid("helpers","routes").required(),file:Ie.string().custom(vu).required(),function_content:Ie.string().required()});return Cs.validateBySchema(e,t)}a(p6,"setCustomFunctionValidator");function S6(e){let t=Ie.object({project:Ie.string().pattern(Is).required().messages({"string.pattern.base":Wt.BAD_PROJECT_NAME}),file:Ie.string().custom(vu).required(),payload:Ie.string().allow("").optional(),encoding:Ie.string().valid("utf8","ASCII","binary","hex","base64","utf16le","latin1","ucs2").optional()});return Cs.validateBySchema(e,t)}a(S6,"setComponentFileValidator");function T6(e){let t=Ie.object({project:Ie.string().pattern(Is).required().messages({"string.pattern.base":Wt.BAD_PROJECT_NAME}),file:Ie.string().custom(vu).optional()});return Cs.validateBySchema(e,t)}a(T6,"dropComponentFileValidator");function g6(e){let t=Ie.object({project:Ie.string().required(),file:Ie.string().custom(vu).required(),encoding:Ie.string().valid("utf8","ASCII","binary","hex","base64","utf16le","latin1","ucs2").optional()});return Cs.validateBySchema(e,t)}a(g6,"getComponentFileValidator");function R6(e){let t=Ie.object({project:Ie.string().pattern(Is).custom(zd.bind(null,!1)).required().messages({"string.pattern.base":Wt.BAD_PROJECT_NAME})});return Cs.validateBySchema(e,t)}a(R6,"addComponentValidator");function A6(e){let t=Ie.object({project:Ie.string().pattern(Is).custom(zd.bind(null,!0)).required().messages({"string.pattern.base":Wt.BAD_PROJECT_NAME})});return Cs.validateBySchema(e,t)}a(A6,"dropCustomFunctionProjectValidator");function O6(e){let t=Ie.object({project:Ie.string().pattern(Is).required().messages({"string.pattern.base":Wt.BAD_PROJECT_NAME}),skip_node_modules:Ie.boolean()});return Cs.validateBySchema(e,t)}a(O6,"packageComponentValidator");function b6(e){let t=Ie.object({project:Ie.string().pattern(Is).required().messages({"string.pattern.base":Wt.BAD_PROJECT_NAME}),payload:Ie.string().optional().messages({"string.pattern.base":Wt.BAD_PACKAGE}),package:Ie.string().optional()});return Cs.validateBySchema(e,t)}a(b6,"deployComponentValidator")});var Zd=T((kfe,oP)=>{"use strict";var Jd=require("joi"),jd=require("path"),eP=require("fs-extra"),{exec:y6}=require("child_process"),N6=require("util"),tP=N6.promisify(y6),Bu=U(),{handleHDBError:Sa,hdb_errors:w6}=ee(),{HTTP_STATUS_CODES:Ta}=w6,Hu=Z(),I6=je(),ga=K();Hu.initSync();var xT=Hu.get(Bu.CONFIG_PARAMS.COMPONENTSROOT),rP="npm install --omit=dev --json",C6=`${rP} --dry-run`;oP.exports={installModules:U6,auditModules:P6,installAllRootModules:D6,uninstallRootModule:L6,linkHarperdb:M6};async function D6(e=!1){await Xd(),await xu(e?"npm install --ignore-scripts":"npm install",Hu.get(Bu.CONFIG_PARAMS.ROOTPATH))}a(D6,"installAllRootModules");async function L6(e){await xu(`npm uninstall ${e}`,Hu.get(Bu.CONFIG_PARAMS.ROOTPATH))}a(L6,"uninstallRootModule");async function M6(){await Xd(),await xu(`npm link ${Bu.PACKAGE_ROOT}`,Hu.get(Bu.CONFIG_PARAMS.ROOTPATH))}a(M6,"linkHarperdb");async function xu(e,t=void 0){let r,n;try{({stdout:r,stderr:n}=await tP(e,{cwd:t}))}catch(s){throw new Error(s.stderr.replace(`
|
|
12
|
+
`,""))}return n&&!n.includes("Debugger listening")&&ga.error("Error running NPM command:",e,n),ga.trace(r,n),r?.replace(`
|
|
13
|
+
`,"")}a(xu,"runCommand");async function U6(e){ga.info(`starting installModules for request: ${e}`);let t=iP(e);if(t)throw Sa(t,t.message,Ta.BAD_REQUEST);let{projects:r,dry_run:n}=e,s=n===!0?C6:rP;await Xd(),await sP(r);let i={};for(let o=0,c=r.length;o<c;o++){let u=r[o];i[u]={npm_output:null,npm_error:null};let _=jd.join(xT,u),l,d=null;try{let{stdout:f,stderr:E}=await tP(s,{cwd:_});l=f?f.replace(`
|
|
14
14
|
`,""):null,d=E?E.replace(`
|
|
15
|
-
`,""):null}catch(f){f.stderr?i[u].npm_error=
|
|
16
|
-
`);return r>-1&&n>-1?JSON.parse(e.substring(r+t.length-1,n+1)):e}a(eP,"parseNPMStdErr");async function L6(e){Sa.info(`starting auditModules for request: ${e}`);let t=rP(e);if(t)throw ma(t,t.message,pa.BAD_REQUEST);let{projects:r}=e;await Xd(),await tP(r);let n={};for(let s=0,i=r.length;s<i;s++){let o=r[s],c=jd.join(xT,o);n[o]={npm_output:null,npm_error:null};try{let u=await vu("npm audit --json",c);n[o].npm_output=JSON.parse(u)}catch(u){n[o].npm_error=eP(u.stderr)}}return Sa.info(`finished auditModules with response ${n}`),n}a(L6,"auditModules");async function Xd(){try{return await vu("npm -v"),!0}catch{throw ma(new Error,"Unable to install project dependencies: npm is not installed on this instance of HarperDB.",pa.BAD_REQUEST,void 0,void 0,!0)}}a(Xd,"checkNPMInstalled");async function tP(e){if(!Array.isArray(e)||e.length===0)throw ma(new Error,"projects argument must be an array with at least 1 element",pa.BAD_REQUEST,void 0,void 0,!0);let t=[],r=[];for(let n=0,s=e.length;n<s;n++){let i=e[n],o=jd.join(xT,i.toString());if(!await jU.pathExists(o)){t.push(i);continue}let u=jd.join(o,"package.json");await jU.pathExists(u)||r.push(i)}if(t.length>0)throw ma(new Error,`Unable to install project dependencies: custom function projects '${t.join(",")}' does not exist.`,pa.BAD_REQUEST,void 0,void 0,!0);if(r.length>0)throw ma(new Error,`Unable to install project dependencies: custom function projects '${r.join(",")}' do not have a package.json file.`,pa.BAD_REQUEST,void 0,void 0,!0)}a(tP,"checkProjectPaths");function rP(e){let t=Jd.object({projects:Jd.array().min(1).items(Jd.string()).required(),dry_run:Jd.boolean().default(!1)});return N6.validateBySchema(e,t)}a(rP,"modulesValidator")});var FT=g(($fe,cP)=>{"use strict";var Ta=require("fs-extra"),qT=require("path"),ef=Y(),sP=J(),tf=M(),aP=Z(),M6=wr();cP.exports=U6;async function U6(){let e=P6(),t=aP.get(tf.CONFIG_PARAMS.ROOTPATH),r=qT.join(t,"package.json"),n={dependencies:{harperdb:"file:"+tf.PACKAGE_ROOT}},s=qT.join(t,"node_modules");await Ta.ensureDir(s);let i,o=!0,c=!1;try{i=await Ta.readJson(r)}catch(u){if(sP.isEmptyOrZeroLength(e))return;if(u.code!==tf.NODE_ERROR_CODES.ENOENT)throw u;o=!1}if(!sP.isEmptyOrZeroLength(e)){for(let{name:u,package:_}of e){let l=await iP(_);n.dependencies[u]=l+_}if(!o){ef.notify("Installing components"),await oP(r,n,null);return}for(let{name:u,package:_}of e){let l=i.dependencies[u],d=await iP(_);if(l===void 0||l!==d+_){c=!0;break}}}for(let u in i.dependencies)n.dependencies[u]===void 0&&(ef.notify("Removing component",u),c=!0);c&&(ef.notify("Updating components."),await oP(r,n,i))}a(U6,"installComponents");function P6(){let e=M6.getConfiguration(),t=[];for(let r in e)e[r]?.package&&t.push(Object.assign(e[r],{name:r}));return t}a(P6,"getComponentsConfig");async function iP(e){return e.includes(":")?"":e.startsWith("@")||!e.startsWith("@")&&!e.includes("/")?"npm:":qT.extname(e)||await Ta.pathExists(e)?"file:":"github:"}a(iP,"getPkgPrefix");async function oP(e,t,r){ef.trace("npm installing components package.json",t),await Ta.writeFile(e,JSON.stringify(t,null," "));try{await Zd().installAllRootModules(aP.get(tf.CONFIG_PARAMS.IGNORE_SCRIPTS)===!0)}catch(n){throw r?await Ta.writeFile(e,JSON.stringify(r,null," ")):await Ta.unlink(e),n}}a(oP,"installPackages")});var VT=g((Wfe,dP)=>{"use strict";var Fe=require("fs-extra"),GT=require("fast-glob"),ge=require("path"),lP=require("tar-fs"),Kfe=require("uuid").v4,kT=require("normalize-path"),Zn=JU(),At=Y(),Ye=M(),ht=Z(),Bu=wr(),v6=J(),{PACKAGE_ROOT:B6}=M(),{handleHDBError:Lt,hdb_errors:H6}=ee(),{basename:x6}=require("path"),q6=FT(),_P=Z(),F6=M(),{Readable:G6}=require("stream"),{isMainThread:k6}=require("worker_threads"),{HDB_ERROR_MSGS:co,HTTP_STATUS_CODES:Mt}=H6,V6=ge.join(B6,"application-template"),uP=ge.join(ht.get(Ye.HDB_SETTINGS_NAMES.HDB_ROOT_KEY),"tmp");function $6(){At.trace("getting custom api status");let e={};try{e={port:ht.get(Ye.CONFIG_PARAMS.HTTP_PORT),directory:ht.get(Ye.CONFIG_PARAMS.COMPONENTSROOT),is_enabled:!0}}catch(t){throw Lt(new Error,co.FUNCTION_STATUS,Mt.INTERNAL_SERVER_ERROR,At.ERR,t)}return e}a($6,"customFunctionsStatus");function Y6(){At.trace("getting custom api endpoints");let e={},t=ht.get(Ye.CONFIG_PARAMS.COMPONENTSROOT);try{GT.sync(kT(`${t}/*`),{onlyDirectories:!0}).forEach(n=>{let s=n.split("/").pop();e[s]={routes:GT.sync(kT(`${n}/routes/*.js`)).map(i=>i.split("/").pop().split(".js")[0]),helpers:GT.sync(kT(`${n}/helpers/*.js`)).map(i=>i.split("/").pop().split(".js")[0])}})}catch(r){throw Lt(new Error,co.GET_FUNCTIONS,Mt.INTERNAL_SERVER_ERROR,At.ERR,r)}return e}a(Y6,"getCustomFunctions");function K6(e){e.project&&(e.project=ge.parse(e.project).name),e.file&&(e.file=ge.parse(e.file).name);let t=Zn.getDropCustomFunctionValidator(e);if(t)throw Lt(t,t.message,Mt.BAD_REQUEST);At.trace("getting custom api endpoint file content");let r=ht.get(Ye.CONFIG_PARAMS.COMPONENTSROOT),{project:n,type:s,file:i}=e,o=ge.join(r,n,s,i+".js");try{return Fe.readFileSync(o,{encoding:"utf8"})}catch(c){throw Lt(new Error,co.GET_FUNCTION,Mt.INTERNAL_SERVER_ERROR,At.ERR,c)}}a(K6,"getCustomFunction");function W6(e){e.project&&(e.project=ge.parse(e.project).name),e.file&&(e.file=ge.parse(e.file).name);let t=Zn.setCustomFunctionValidator(e);if(t)throw Lt(t,t.message,Mt.BAD_REQUEST);At.trace("setting custom function file content");let r=ht.get(Ye.CONFIG_PARAMS.COMPONENTSROOT),{project:n,type:s,file:i,function_content:o}=e;try{return Fe.outputFileSync(ge.join(r,n,s,i+".js"),o),`Successfully updated custom function: ${i}.js`}catch(c){throw Lt(new Error,co.SET_FUNCTION,Mt.INTERNAL_SERVER_ERROR,At.ERR,c)}}a(W6,"setCustomFunction");function Q6(e){e.project&&(e.project=ge.parse(e.project).name),e.file&&(e.file=ge.parse(e.file).name);let t=Zn.getDropCustomFunctionValidator(e);if(t)throw Lt(t,t.message,Mt.BAD_REQUEST);At.trace("dropping custom function file");let r=ht.get(Ye.CONFIG_PARAMS.COMPONENTSROOT),{project:n,type:s,file:i}=e;try{return Fe.unlinkSync(ge.join(r,n,s,i+".js")),`Successfully deleted custom function: ${i}.js`}catch(o){throw Lt(new Error,co.DROP_FUNCTION,Mt.INTERNAL_SERVER_ERROR,At.ERR,o)}}a(Q6,"dropCustomFunction");function z6(e){e.project&&(e.project=ge.parse(e.project).name);let t=Zn.addComponentValidator(e);if(t)throw Lt(t,t.message,Mt.BAD_REQUEST);At.trace("adding component");let r=ht.get(Ye.CONFIG_PARAMS.COMPONENTSROOT),{project:n}=e;try{let s=ge.join(r,n);return Fe.mkdirSync(s,{recursive:!0}),Fe.copySync(V6,s),`Successfully added project: ${n}`}catch(s){throw Lt(new Error,co.ADD_FUNCTION,Mt.INTERNAL_SERVER_ERROR,At.ERR,s)}}a(z6,"addComponent");function J6(e){e.project&&(e.project=ge.parse(e.project).name);let t=Zn.dropCustomFunctionProjectValidator(e);if(t)throw Lt(t,t.message,Mt.BAD_REQUEST);At.trace("dropping custom function project");let r=ht.get(Ye.CONFIG_PARAMS.COMPONENTSROOT),{project:n}=e,s=ht.get(Ye.CONFIG_PARAMS.APPS);if(!v6.isEmptyOrZeroLength(s)){let i=!1;for(let[o,c]of s.entries())if(c.name===n){s.splice(o,1),i=!0;break}if(i)return Bu.updateConfigValue(Ye.CONFIG_PARAMS.APPS,s),`Successfully deleted project: ${n}`}try{let i=ge.join(r,n);return Fe.rmSync(i,{recursive:!0}),`Successfully deleted project: ${n}`}catch(i){throw Lt(new Error,co.DROP_FUNCTION_PROJECT,Mt.INTERNAL_SERVER_ERROR,At.ERR,i)}}a(J6,"dropCustomFunctionProject");async function j6(e){e.project&&(e.project=ge.parse(e.project).name);let t=Zn.packageComponentValidator(e);if(t)throw Lt(t,t.message,Mt.BAD_REQUEST);let r=ht.get(Ye.CONFIG_PARAMS.COMPONENTSROOT),{project:n}=e;At.trace("packaging component",n);let s;try{s=await Fe.realpath(ge.join(r,n))}catch(u){if(u.code!==Ye.NODE_ERROR_CODES.ENOENT)throw u;try{s=await Fe.realpath(ge.join(ht.get(Ye.CONFIG_PARAMS.ROOTPATH),"node_modules",n))}catch(_){if(_.code===Ye.NODE_ERROR_CODES.ENOENT)throw new Error(`Unable to locate project '${n}'`)}}await Fe.ensureDir(uP);let i=ge.join(uP,`${n}.tar`),o={};(e.skip_node_modules===!0||e.skip_node_modules==="true")&&(o={ignore:u=>u.includes(ge.join(s,"node_modules"))}),lP.pack(s,o).pipe(Fe.createWriteStream(i,{overwrite:!0})),await new Promise(u=>setTimeout(u,2e3));let c=Fe.readFileSync(i,{encoding:"base64"});return await Fe.remove(i),{project:n,payload:c}}a(j6,"packageComponent");async function X6(e){e.project&&(e.project=ge.parse(e.project).name);let t=Zn.deployComponentValidator(e);if(t)throw Lt(t,t.message,Mt.BAD_REQUEST);let r=ht.get(Ye.CONFIG_PARAMS.COMPONENTSROOT),{project:n,payload:s,package:i}=e;if(At.trace("deploying component",n),!s&&!i)throw new Error("'payload' or 'package' must be provided");let o;if(s){o=ge.join(r,n),i="file:"+o,await Fe.ensureDir(o);let f=G6.from(Buffer.from(s,"base64"));await new Promise((h,p)=>{f.pipe(lP.extract(o,{finish:h})).on("error",p)});let E=await Fe.readdir(o);E.length===1&&E[0]==="package"&&(await Fe.copy(ge.join(o,"package"),o),await Fe.remove(ge.join(o,"package")))}if(await Bu.addConfig(n,{package:i}),!s){await q6();let f=_P.get(F6.CONFIG_PARAMS.ROOTPATH);o=ge.join(f,"node_modules",n)}if(k6)return;let c=new Map;c.isWorker=!0;let u=(nf(),te(rf)),_;u.setErrorReporter(f=>_=f);let l=x6(o),d=u.component_errors.get(l);try{await u.loadComponent(o,c)}finally{u.component_errors.set(l,d)}if(_)throw _;return At.info("Installed component"),`Successfully deployed: ${n}`}a(X6,"deployComponent");async function Z6(){let e=Bu.getConfiguration(),t=[];for(let o in e)if(e[o]?.package){if(e[o].package.startsWith("file:"))continue;t.push(Object.assign({},e[o],{name:o}))}let r=a(async(o,c)=>{try{let u=await Fe.readdir(o,{withFileTypes:!0});for(let _ of u){let l=_.name;if(l.startsWith(".")||l==="node_modules")continue;let d=ge.join(o,l);if(_.isDirectory()||_.isSymbolicLink()){let f={name:l,entries:[]};c.entries.push(f),await r(d,f)}else{let f=await Fe.stat(d),E={name:ge.basename(l),mtime:f.mtime,size:f.size};c.entries.push(E)}}return c}catch(u){return At.warn("Error loading package",u),{error:u.toString(),entries:[]}}},"walk_dir"),n=await r(ht.get(Ye.CONFIG_PARAMS.COMPONENTSROOT),{name:ht.get(Ye.CONFIG_PARAMS.COMPONENTSROOT).split(ge.sep).slice(-1).pop(),entries:t});for(let o of n.entries)if(o.package){let c=await r(ge.join(ht.get(Ye.CONFIG_PARAMS.ROOTPATH),"node_modules",o.name),{name:o.name,entries:[]});Object.assign(o,c)}let i=(nf(),te(rf)).component_errors;for(let o of t){let c=i.get(o.name);c?o.error=i.get(o.name):c===void 0&&(o.error="The component has not been loaded yet (may need a restart)")}return n}a(Z6,"getComponents");async function e9(e){let t=Zn.getComponentFileValidator(e);if(t)throw Lt(t,t.message,Mt.BAD_REQUEST);let n=Bu.getConfigObj()[e.project]||e.project==="harperdb"?ge.join(_P.get(Ye.CONFIG_PARAMS.ROOTPATH),"node_modules"):ht.get(Ye.CONFIG_PARAMS.COMPONENTSROOT),s=e.encoding?{encoding:e.encoding}:{encoding:"utf8"};try{let i=await Fe.stat(ge.join(n,e.project,e.file));return{message:await Fe.readFile(ge.join(n,e.project,e.file),s),size:i.size,birthtime:i.birthtime,mtime:i.mtime}}catch(i){throw i.code===Ye.NODE_ERROR_CODES.ENOENT?new Error(`Component file not found '${ge.join(e.project,e.file)}'`):i}}a(e9,"getComponentFile");async function t9(e){let t=Zn.setComponentFileValidator(e);if(t)throw Lt(t,t.message,Mt.BAD_REQUEST);let r=e.encoding?{encoding:e.encoding}:{encoding:"utf8"},n=ge.join(ht.get(Ye.CONFIG_PARAMS.COMPONENTSROOT),e.project,e.file);return e.payload!==void 0?(await Fe.ensureFile(n),await Fe.outputFile(n,e.payload,r)):await Fe.ensureDir(n),"Successfully set component: "+e.file}a(t9,"setComponentFile");async function r9(e){let t=Zn.dropComponentFileValidator(e);if(t)throw Lt(t,t.message,Mt.BAD_REQUEST);let r=e.file?ge.join(e.project,e.file):e.project,n=ge.join(ht.get(Ye.CONFIG_PARAMS.COMPONENTSROOT),r);return await Fe.pathExists(n)&&await Fe.remove(n),Bu.deleteConfigFromFile([e.project]),"Successfully dropped: "+r}a(r9,"dropComponent");dP.exports={customFunctionsStatus:$6,getCustomFunctions:Y6,getCustomFunction:K6,setCustomFunction:W6,dropCustomFunction:Q6,addComponent:z6,dropCustomFunctionProject:J6,packageComponent:j6,deployComponent:X6,getComponents:Z6,getComponentFile:e9,setComponentFile:t9,dropComponent:r9}});var $T=g((zfe,EP)=>{"use strict";var es=require("joi"),fP=je();EP.exports={readTransactionLogValidator:n9,deleteTransactionLogsBeforeValidator:s9};function n9(e){let t=es.object({schema:es.string().required(),table:es.string().required(),from:es.date().timestamp(),to:es.date().timestamp(),limit:es.number().min(1)});return fP.validateBySchema(e,t)}a(n9,"readTransactionLogValidator");function s9(e){let t=es.object({schema:es.string().required(),table:es.string().required(),timestamp:es.date().timestamp().required()});return fP.validateBySchema(e,t)}a(s9,"deleteTransactionLogsBeforeValidator")});var of=g((jfe,TP)=>{"use strict";var YT=M(),sf=ft(),hP=J(),mP=Z(),pP=hs(),{handleHDBError:ga,hdb_errors:i9}=ee(),{HTTP_STATUS_CODES:Ra}=i9,{readTransactionLogValidator:o9,deleteTransactionLogsBeforeValidator:a9}=$T(),SP="This operation relies on clustering and cannot run with it disable.",c9="Logs successfully deleted from transaction log.",u9="All logs successfully deleted from transaction log.";TP.exports={readTransactionLog:l9,deleteTransactionLogsBefore:_9};async function*l9(e){let t=o9(e);if(t)throw ga(t,t.message,Ra.BAD_REQUEST,void 0,void 0,!0);if(!mP.get(YT.CONFIG_PARAMS.CLUSTERING_ENABLED))throw ga(new Error,SP,Ra.NOT_FOUND,void 0,void 0,!0);let{schema:r,table:n}=e,s=hP.checkSchemaTableExist(r,n);if(s)throw ga(new Error,s,Ra.NOT_FOUND,void 0,void 0,!0);let i=pP.createNatsTableStreamName(r,n),o=await sf.viewStreamIterator(i,parseInt(e.from),e.limit);for await(let c of o){let u=Math.floor(c?.nats_timestamp/1e6);if(e.to&&u>e.to)break;let _={operation:c?.entry?.operation,user:c?.entry?.__origin?.user,timestamp:u,records:c?.entry?.records,attributes:c?.entry?.attributes};c?.entry?.operation===YT.OPERATIONS_ENUM.DELETE&&(_.hash_values=c?.entry?.hash_values),yield _}}a(l9,"readTransactionLog");async function _9(e){let t=a9(e);if(t)throw ga(t,t.message,Ra.BAD_REQUEST,void 0,void 0,!0);if(!mP.get(YT.CONFIG_PARAMS.CLUSTERING_ENABLED))throw ga(new Error,SP,Ra.NOT_FOUND,void 0,void 0,!0);let{schema:r,table:n,timestamp:s}=e,i=hP.checkSchemaTableExist(r,n);if(i)throw ga(new Error,i,Ra.NOT_FOUND,void 0,void 0,!0);let o=pP.createNatsTableStreamName(r,n),{jsm:c}=await sf.getNATSReferences(),u=await sf.getStreamInfo(o),_=new Date(u.state.first_ts).getTime();if(s<=_)return`No transactions exist before: ${s}`;let l=c9,d,f=new Date(u.state.last_ts).getTime();return s>f?(d=u.state.last_seq+1,l=u9):d=(await sf.viewStream(o,parseInt(s),1))[0].nats_sequence,await c.streams.purge(o,{seq:d}),l}a(_9,"deleteTransactionLogsBefore")});var RP=g((Zfe,gP)=>{"use strict";var KT=class{static{a(this,"PermissionTableResponseObject")}constructor(t,r,n=[],s=[]){this.schema=t,this.table=r,this.required_table_permissions=n,this.required_attribute_permissions=s}};gP.exports=KT});var OP=g((tEe,AP)=>{"use strict";var WT=class{static{a(this,"PermissionAttributeResponseObject")}constructor(t,r=[]){this.attribute_name=t,this.required_permissions=r}};AP.exports=WT});var zT=g((nEe,NP)=>{"use strict";var bP=RP(),d9=OP(),{HDB_ERROR_MSGS:f9}=Or(),QT=class{static{a(this,"PermissionResponseObject")}constructor(){this.error=f9.OP_AUTH_PERMS_ERROR,this.unauthorized_access={},this.invalid_schema_items=[]}handleUnauthorizedItem(t){return this.invalid_schema_items=[],this.unauthorized_access=[t],this}handleInvalidItem(t){return this.invalid_schema_items=[t],this.unauthorized_access=[],this}addInvalidItem(t,r,n){if(r&&n){let s=`${r}_${n}`;if(this.unauthorized_access[s])return}this.invalid_schema_items.push(t)}addUnauthorizedTable(t,r,n){let s=new bP(t,r,n),i=`${t}_${r}`;this.unauthorized_access[i]=s}addUnauthorizedAttributes(t,r,n,s){let i=[];t.forEach(c=>{let u=new d9(c,s[c]);i.push(u)});let o=`${r}_${n}`;if(this.unauthorized_access[o])this.unauthorized_access[o].required_attribute_permissions=i;else{let c=new bP(r,n,[],i);this.unauthorized_access[o]=c}}getPermsResponse(){let t=Object.values(this.unauthorized_access);return t.length>0||this.invalid_schema_items.length>0?(this.unauthorized_access=t,this):null}};NP.exports=QT});var lf=g((iEe,GP)=>{"use strict";var JT=Zr(),af=Xr(),an=od(),qu=vi(),jT=Fi(),E9=uS(),h9=BD(),Fu=Mr(),cf=SS(),Ot=Y(),m9=RS(),p9=Od(),S9=nT(),T9=Nd(),g9=sT(),R9=iT(),A9=cT(),O9=lT(),XT=fT(),Is=J(),b9=UM(),ZT=ST(),IP=kd(),on=M(),CP=UU(),N9=aa(),DP=_u(),LP=(Qd(),te(Lu)),MP=wr(),Fr=VT(),y9=require("alasql"),UP=of(),PP=Zd(),vP=zT(),{handleHDBError:Er,hdb_errors:BP}=ee(),{HDB_ERROR_MSGS:Ft,HTTP_STATUS_CODES:Hu}=BP,G=new Map,HP="delete",fi="insert",Cs="read",uo="update",xu="describe",yP=qu.describeSchema.name,wP=qu.describeTable.name,xP={delete:!0,deleteRecord:!0,update:!0,updateData:!0,dropAttribute:!0,dropTable:!0,dropSchema:!0,upsert:!0,upsertData:!0},w9="catchup",I9="handleGetJob",C9="handleGetJobsByStartDate",uf={CSV_DATA_LOAD:"csvDataLoad",CSV_URL_LOAD:"csvURLLoad",CSV_FILE_LOAD:"csvFileLoad",IMPORT_FROM_S3:"importFromS3"},D9=[an.createTable.name,an.createAttribute.name,an.dropTable.name,an.dropAttribute.name],qP={EXPORT_TO_S3:"export_to_s3",EXPORT_LOCAL:"export_local"},K=class{static{a(this,"permission")}constructor(t,r){this.requires_su=t,this.perms=r}};G.set(JT.insert.name,new K(!1,[fi]));G.set(JT.update.name,new K(!1,[uo]));G.set(JT.upsert.name,new K(!1,[fi,uo]));G.set(af.searchByConditions.name,new K(!1,[Cs]));G.set(af.searchByHash.name,new K(!1,[Cs]));G.set(af.searchByValue.name,new K(!1,[Cs]));G.set(af.search.name,new K(!1,[Cs]));G.set(an.createSchema.name,new K(!0,[]));G.set(an.createTable.name,new K(!0,[]));G.set(an.createAttribute.name,new K(!1,[fi]));G.set(an.dropSchema.name,new K(!0,[]));G.set(an.dropTable.name,new K(!0,[]));G.set(an.dropAttribute.name,new K(!0,[]));G.set(qu.describeSchema.name,new K(!1,[Cs]));G.set(qu.describeTable.name,new K(!1,[Cs]));G.set(jT.deleteRecord.name,new K(!1,[HP]));G.set(Fu.addUser.name,new K(!0,[]));G.set(Fu.alterUser.name,new K(!0,[]));G.set(Fu.dropUser.name,new K(!0,[]));G.set(Fu.listUsersExternal.name,new K(!0,[]));G.set(cf.listRoles.name,new K(!0,[]));G.set(cf.addRole.name,new K(!0,[]));G.set(cf.alterRole.name,new K(!0,[]));G.set(cf.dropRole.name,new K(!0,[]));G.set(m9.name,new K(!0,[]));G.set(p9.name,new K(!0,[]));G.set(S9.name,new K(!0,[]));G.set(T9.name,new K(!0,[]));G.set(g9.name,new K(!0,[]));G.set(R9.name,new K(!0,[]));G.set(XT.setRoutes.name,new K(!0,[]));G.set(XT.getRoutes.name,new K(!0,[]));G.set(XT.deleteRoutes.name,new K(!0,[]));G.set(MP.setConfiguration.name,new K(!0,[]));G.set(A9.clusterStatus.name,new K(!0,[]));G.set(O9.name,new K(!0,[]));G.set(ZT.getFingerprint.name,new K(!0,[]));G.set(ZT.setLicense.name,new K(!0,[]));G.set(jT.deleteFilesBefore.name,new K(!0,[]));G.set(jT.deleteAuditLogsBefore.name,new K(!0,[]));G.set(IP.restart.name,new K(!0,[]));G.set(IP.restartService.name,new K(!0,[]));G.set(E9.name,new K(!0,[]));G.set(h9.name,new K(!0,[Cs]));G.set(N9.systemInformation.name,new K(!0,[]));G.set(MP.getConfiguration.name,new K(!0,[]));G.set(UP.readTransactionLog.name,new K(!0,[]));G.set(UP.deleteTransactionLogsBefore.name,new K(!0,[]));G.set(PP.installModules.name,new K(!0,[]));G.set(PP.auditModules.name,new K(!0,[]));G.set(DP.createTokens.name,new K(!1,[]));G.set(DP.refreshOperationToken.name,new K(!1,[]));G.set(LP.login.name,new K(!1,[]));G.set(LP.logout.name,new K(!1,[]));G.set(Fr.customFunctionsStatus.name,new K(!0,[]));G.set(Fr.getCustomFunctions.name,new K(!0,[]));G.set(Fr.getComponents.name,new K(!0,[]));G.set(Fr.getComponentFile.name,new K(!0,[]));G.set(Fr.setComponentFile.name,new K(!0,[]));G.set(Fr.dropComponent.name,new K(!0,[]));G.set(Fr.getCustomFunction.name,new K(!0,[]));G.set(Fr.setCustomFunction.name,new K(!0,[]));G.set(Fr.dropCustomFunction.name,new K(!0,[]));G.set(Fr.addComponent.name,new K(!0,[]));G.set(Fr.dropCustomFunctionProject.name,new K(!0,[]));G.set(Fr.packageComponent.name,new K(!0,[]));G.set(Fr.deployComponent.name,new K(!0,[]));G.set(ZT.getRegistrationInfo.name,new K(!1,[]));G.set(Fu.userInfo.name,new K(!1,[]));G.set(qu.describeAll.name,new K(!1,[]));G.set(I9,new K(!1,[]));G.set(C9,new K(!0,[]));G.set(w9,new K(!0,[]));G.set(uf.CSV_DATA_LOAD,new K(!1,[fi,uo]));G.set(uf.CSV_URL_LOAD,new K(!1,[fi,uo]));G.set(uf.CSV_FILE_LOAD,new K(!1,[fi,uo]));G.set(uf.IMPORT_FROM_S3,new K(!1,[fi,uo]));G.set(qP.EXPORT_TO_S3,new K(!0,[]));G.set(qP.EXPORT_LOCAL,new K(!0,[]));G.set(on.VALID_SQL_OPS_ENUM.DELETE,new K(!1,[HP]));G.set(on.VALID_SQL_OPS_ENUM.SELECT,new K(!1,[Cs]));G.set(on.VALID_SQL_OPS_ENUM.INSERT,new K(!1,[fi]));G.set(on.VALID_SQL_OPS_ENUM.UPDATE,new K(!1,[uo]));GP.exports={verifyPerms:M9,verifyPermsAst:L9,verifyBulkLoadAttributePerms:P9};function L9(e,t,r){if(Is.isEmptyOrZeroLength(e))throw Ot.info("verify_perms_ast has an empty user parameter"),Er(new Error);if(Is.isEmptyOrZeroLength(t))throw Ot.info("verify_perms_ast has an empty user parameter"),Er(new Error);if(Is.isEmptyOrZeroLength(r))throw Ot.info("verify_perms_ast has a null operation parameter"),Er(new Error);try{let n=new vP,s=new b9(e),i=s.getSchemas(),o=new Map;if((!i||i.length===0)&&s.affected_attributes&&s.affected_attributes.size>0)throw Ot.info("No schemas defined in verifyPermsAst(), will not continue."),Er(new Error);let c=!!t.role.permission.super_user,u=i.includes("system");if(u&&xP[r])throw Er(new Error,Ft.DROP_SYSTEM,Hu.FORBIDDEN);if(c&&!u)return null;let _=CP.getRolePermissions(t.role);t.role.permission=_,!c&&e instanceof y9.yy.Select&&(e=s.updateAttributeWildcardsForRolePerms(_));for(let d=0;d<i.length;d++){let f=s.getTablesBySchemaName(i[d]);f&&o.set(i[d],f)}let l=FP(t,r,o,n);return l||(o.forEach((d,f)=>{for(let E=0;E<d.length;E++){let h=s.getAttributesBySchemaTableName(f,d[E]),p=tg(t.role.permission,f,d[E]);eg(h,p,r,d[E],f,n)}}),n.getPermsResponse())}catch(n){throw Er(n)}}a(L9,"verifyPermsAst");function M9(e,t){if(e===null||t===null||e.hdb_user===void 0||e.hdb_user===null)throw Ot.info("null required parameter in verifyPerms"),Er(new Error,Ft.DEFAULT_INVALID_REQUEST,Hu.BAD_REQUEST);let r;t instanceof Function?r=t.name:r=t;let n=e.action,s=e.schema??e.database,i=e.table,o=new Map;s&&i&&o.set(s,[i]);let c=new vP;if(Is.isEmptyOrZeroLength(e.hdb_user.role)||Is.isEmptyOrZeroLength(e.hdb_user.role.permission))return Ot.info(`User ${e.hdb_user.username} has no role or permissions. Please assign the user a valid role.`),c.handleUnauthorizedItem(Ft.USER_HAS_NO_PERMS(e.hdb_user.username));let u=!!e.hdb_user.role.permission.super_user,_=e.hdb_user.role.permission.structure_user,l=o.has(on.SYSTEM_SCHEMA_NAME)||s===on.SYSTEM_SCHEMA_NAME;if(l&&xP[r])throw Er(new Error,Ft.DROP_SYSTEM,Hu.FORBIDDEN);if(u&&!l||_===!0&&(r===an.createSchema.name||r===an.dropSchema.name))return null;if(D9.indexOf(r)>=0&&(_===!0||Array.isArray(_)))return _===!0||_.indexOf(s)>=0?null:c.handleUnauthorizedItem(`User does not have access to perform '${e.operation}' against schema '${s}'`);let d=CP.getRolePermissions(e.hdb_user.role);if(e.hdb_user.role.permission=d,r===yP||r===wP){if(s===on.SYSTEM_SCHEMA_NAME)return c.handleUnauthorizedItem(Ft.SCHEMA_PERM_ERROR(s));if(!d.super_user){if(r===yP&&(!d[s]||!d[s][xu]))return c.handleInvalidItem(Ft.SCHEMA_NOT_FOUND(s));if(r===wP&&(!d[s]||!d[s].tables[i]||!d[s].tables[i][xu]))return c.handleInvalidItem(Ft.TABLE_NOT_FOUND(s,i))}}let f=FP(e.hdb_user,r,o,c,n);if(f)return f;if(G.get(r)&&G.get(r).perms.length===0)return null;if(!u&&e.get_attributes&&on.SEARCH_WILDCARDS.includes(e.get_attributes[0])){let p=[],S=d[s].tables[i];S[on.PERMS_CRUD_ENUM.READ]&&(S.attribute_permissions.length>0?S.attribute_permissions.filter(A=>A[on.PERMS_CRUD_ENUM.READ]).forEach(A=>{p.push(A.attribute_name)}):p=global.hdb_schema[s][i].attributes.map(T=>T.attribute),e.get_attributes=p)}let E=U9(e),h=tg(e.hdb_user.role.permission,s,i);return eg(E,h,r,i,s,c,n),c.getPermsResponse()}a(M9,"verifyPerms");function FP(e,t,r,n,s){if(Is.arrayHasEmptyValues([e,t,r]))throw Ot.info("hasPermissions has an invalid parameter"),Er(new Error);let i=r.has("system"),o=e.role.permission;if(o.super_user&&(!i||G.get(t).requires_su))return null;if(!G.get(t))throw Ot.info(`operation ${t} not found.`),Er(new Error,Ft.OP_NOT_FOUND(t),Hu.BAD_REQUEST);if(G.get(t)&&G.get(t).requires_su)return Ot.info(`operation ${t} requires SU permissions.`),n.handleUnauthorizedItem(Ft.OP_IS_SU_ONLY(t));let c=r.keys();for(let u of c){try{if(u&&!o[u]||o[u][xu]===!1){n.addInvalidItem(Ft.SCHEMA_NOT_FOUND(u));continue}}catch{n.addInvalidItem(Ft.SCHEMA_NOT_FOUND(u));continue}let _=r.get(u);for(let l of _){let d=o[u].tables[l];if(!d||d[xu]===!1)n.addInvalidItem(Ft.TABLE_NOT_FOUND(u,l));else try{let f=[],E=G.get(t).perms;!Is.isEmpty(s)&&E.includes(s)&&(E=[s]);for(let h=0;h<E.length;h++){let p=E[h],S=d[p];(S==null||S===!1)&&(Ot.info(`Required ${p} permission not found for ${t} ${s?`${s} `:""}operation in role ${e.role.id}`),f.push(p))}f.length>0&&n.addUnauthorizedTable(u,l,f)}catch(f){let E=Ft.UNKNOWN_OP_AUTH_ERROR(t,u,l);throw Ot.error(E),Ot.error(f),Er(BP.CHECK_LOGS_WRAPPER(E))}}}return r.size<2?n.getPermsResponse():null}a(FP,"hasPermissions");function eg(e,t,r,n,s,i,o){if(!e||!t)throw Ot.info("no attributes specified in checkAttributePerms."),Er(new Error);let c=G.get(r).perms;if(!c||c==="")throw Ot.info(`no permissions found for ${r} in checkAttributePerms().`),Er(new Error);if(Is.isEmptyOrZeroLength(t))return Ot.info("No role permissions set (this is OK)."),null;o&&c.includes(o)&&(c=[o]);let u={};for(let l of e){let d=t.get(l);if(d){if(d[xu]===!1){i.addInvalidItem(Ft.ATTR_NOT_FOUND(s,n,l),s,n);continue}if(c)for(let f of c){if(on.TIME_STAMP_NAMES.includes(d.attribute_name)&&f!==Cs)throw Er(new Error,Ft.SYSTEM_TIMESTAMP_PERMS_ERR,Hu.FORBIDDEN);d[f]===!1&&(u[d.attribute_name]?u[d.attribute_name].push(f):u[d.attribute_name]=[f])}}else i.addInvalidItem(Ft.ATTR_NOT_FOUND(s,n,l),s,n)}let _=Object.keys(u);_.length>0&&i.addUnauthorizedAttributes(_,s,n,u)}a(eg,"checkAttributePerms");function U9(e){let t=new Set;try{if(e.action)return t;if(e.operation===on.OPERATIONS_ENUM.SEARCH_BY_CONDITIONS&&e.conditions.forEach(r=>{t.add(r.search_attribute)}),e&&e.search_attribute&&t.add(e.search_attribute),!e.records||e.records.length===0){if(!e.get_attributes||!e.get_attributes.length===0)return t;for(let r=0;r<e.get_attributes.length;r++)t.add(e.get_attributes[r])}else for(let r=0;r<e.records.length;r++){let n=Object.keys(e.records[r]);for(let s=0;s<n.length;s++)t.add(n[s])}}catch(r){Ot.info(r)}return t}a(U9,"getRecordAttributes");function tg(e,t,r){let n=new Map;if(Is.isEmpty(e))return Ot.info("no hdb_user specified in getAttributePermissions"),n;if(e.super_user||!t||!r)return n;try{e[t].tables[r].attribute_permissions.forEach(s=>{n.has(s.attribute_name)||n.set(s.attribute_name,s)})}catch{Ot.info(`No attribute permissions found for schema ${t} and table ${r}.`)}return n}a(tg,"getAttributePermissions");function P9(e,t,r,n,s,i,o){let c=new Set(i),u=tg(e,n,s);eg(c,u,t,s,n,o,r)}a(P9,"verifyBulkLoadAttributePerms")});var df=g((aEe,KP)=>{"use strict";KP.exports={evaluateSQL:W9,processAST:YP,convertSQLToAST:$P,checkASTPermissions:VP};var v9=Zr(),kP=require("util"),B9=kP.callbackify(v9.insert),H9=Xr().search,x9=IC().update,q9=kP.callbackify(x9),F9=DC().convertDelete,Ei=require("alasql"),G9=lf(),_f=Y(),k9=W_(),V9=J(),Gu=M(),{hdb_errors:$9,handleHDBError:rg}=ee(),{HTTP_STATUS_CODES:ng}=$9;k9(Ei);var Y9=403,K9="There was a problem performing this insert. Please check the logs and try again.",sg=class{static{a(this,"ParsedSQLObject")}constructor(){this.ast=void 0,this.variant=void 0,this.permissions_checked=!1}};function W9(e,t){let r=e.parsed_sql_object;if(!r){r=$P(e.sql);let n,s=r.ast.statements[0];if(s instanceof Ei.yy.Insert?n=s.into.databaseid:s instanceof Ei.yy.Select?n=s.from?s.from[0].databaseid:null:s instanceof Ei.yy.Update||s instanceof Ei.yy.Delete?n=s.table.databaseid:_f.error("AST in evaluateSQL is not a valid SQL type."),!(s instanceof Ei.yy.Select)&&V9.isEmptyOrZeroLength(n))return t("No schema specified",null)}YP(e,r,(n,s)=>{if(n)return t(n);t(null,s)})}a(W9,"evaluateSQL");function VP(e,t){let r;try{r=G9.verifyPermsAst(t.ast.statements[0],e.hdb_user,t.variant),t.permissions_checked=!0}catch(n){throw n}return r||null}a(VP,"checkASTPermissions");function $P(e){let t=new sg;if(!e)throw rg(new Error,"The 'sql' parameter is missing from the request body",ng.BAD_REQUEST);try{let r=e.trim(),n=Ei.parse(r),s=r.split(" ")[0].toLowerCase();t.ast=n,t.variant=s}catch(r){let n=r.message.split(`
|
|
17
|
-
`);throw n[1]?rg(r,`Invalid SQL at: ${n[1]}. Please ensure your SQL is valid. Try adding backticks to reserved words and schema table references.`,ng.BAD_REQUEST):rg(r,"We had trouble parsing your request. Please ensure your SQL is valid. Try adding backticks to reserved words and schema table references.",ng.BAD_REQUEST)}return t}a($P,"convertSQLToAST");function YP(e,t,r){try{let n=Q9;if(!e.bypass_auth&&!t.permissions_checked){let i=VP(e,t);if(i&&i.length>0)return r(Y9,i)}let s={statement:t.ast.statements[0],hdb_user:e.hdb_user};switch(t.variant){case Gu.VALID_SQL_OPS_ENUM.SELECT:n=H9,s=t.ast.statements[0];break;case Gu.VALID_SQL_OPS_ENUM.INSERT:n=z9;break;case Gu.VALID_SQL_OPS_ENUM.UPDATE:n=q9;break;case Gu.VALID_SQL_OPS_ENUM.DELETE:n=F9;break;default:throw new Error(`unsupported SQL type ${t.variant} in SQL: ${e}`)}n(s,(i,o)=>{if(i){r(i);return}r(null,o)})}catch(n){return r(n)}}a(YP,"processAST");function Q9(e,t){_f.info(e),t("unknown sql statement")}a(Q9,"nullFunction");function z9({statement:e,hdb_user:t},r){let n=e.into,s={schema:n.databaseid,table:n.tableid,operation:"insert",hdb_user:t},i=e.columns.map(o=>o.columnid);try{s.records=J9(i,e.values)}catch(o){return r(o)}B9(s,(o,c)=>{if(o)return r(o);try{delete c.new_attributes,delete c.txn_time}catch(u){_f.error(`Error delete new_attributes from insert response: ${u}`)}r(null,c)})}a(z9,"convertInsert");function J9(e,t){try{return t.map(r=>{if(e.length!==r.length)throw"number of values do not match number of columns in insert";let n={};return r.forEach((s,i)=>{if(s.columnid)throw"cannot use a column in insert value";"value"in s?n[e[i]]=s.value:n[e[i]]=Ei.compile(`SELECT ${s.toString()} AS [${Gu.FUNC_VAL}] FROM ?`)}),n})}catch(r){throw _f.error(r),new Error(K9)}}a(J9,"createDataObjects")});var ig=g((uEe,QP)=>{"use strict";var{S3:j9,GetObjectCommand:X9}=require("@aws-sdk/client-s3");QP.exports={getFileStreamFromS3:Z9,getS3AuthObj:WP};async function Z9(e){let{s3:t}=e,r={Bucket:t.bucket,Key:t.key};return(await WP(t.aws_access_key_id,t.aws_secret_access_key,t.region).send(new X9(r))).Body}a(Z9,"getFileStreamFromS3");function WP(e,t,r){return new j9({credentials:{accessKeyId:e,secretAccessKey:t},region:r})}a(WP,"getS3AuthObj")});var ff=g((_Ee,nv)=>{"use strict";var ag=Xr(),e7=df(),t7=ig(),{AsyncParser:r7,Transform:n7}=require("json2csv"),Vu=require("stream"),Gr=J(),og=require("fs-extra"),s7=require("path"),cn=Y(),{promisify:jP}=require("util"),ku=J(),{handleHDBError:mt,hdb_errors:i7}=ee(),{HDB_ERROR_MSGS:hr,HTTP_STATUS_CODES:pt}=i7,{streamAsJSON:o7}=(Dh(),te(lb)),{Upload:a7}=require("@aws-sdk/lib-storage"),zP=["search_by_value","search_by_hash","sql","search_by_conditions"],JP=["json","csv"],XP="json",ZP="csv",c7="Successfully exported JSON locally.",u7="Successfully exported CSV locally.",l7=1e3,_7=ag.searchByHash,d7=ag.searchByValue,f7=jP(e7.evaluateSQL),E7=jP(Vu.finished);nv.exports={export_to_s3:S7,export_local:h7,toCsvStream:ev};async function h7(e){cn.trace(`export_local request to path: ${e.path}, filename: ${e.filename}, format: ${e.format}`);let t=tv(e);if(!Gr.isEmpty(t))throw cn.error(t),mt(new Error,t,pt.BAD_REQUEST,void 0,void 0,!0);if(Gr.isEmpty(e.path))throw cn.error(hr.MISSING_VALUE("path")),mt(new Error,hr.MISSING_VALUE("path"),pt.BAD_REQUEST,void 0,void 0,!0);let r=(Gr.isEmpty(e.filename)?new Date().getTime():e.filename)+"."+e.format;e.path.endsWith(s7.sep)&&(e.path=e.path.substring(0,e.path.length-1));let n=Gr.buildFolderPath(e.path,r);await m7(e.path);let s=await rv(e);return await p7(n,e.format,s)}a(h7,"export_local");async function m7(e){if(cn.trace("in confirmPath"),Gr.isEmptyOrZeroLength(e))throw mt(new Error,`Invalid path: ${e}`,pt.BAD_REQUEST,void 0,void 0,!0);let t;try{t=await og.stat(e)}catch(r){let n;throw r.code==="ENOENT"?n=`path '${e}' does not exist`:r.code==="EACCES"?n=`access to path '${e}' is denied`:n=r.message,cn.error(n),mt(new Error,n,pt.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 cn.error(r),mt(new Error,r,pt.BAD_REQUEST,void 0,void 0,!0)}return!0}a(m7,"confirmPath");async function p7(e,t,r){if(cn.trace("in saveToLocal"),ku.isEmptyOrZeroLength(e))throw mt(new Error,hr.INVALID_VALUE("file_path"),pt.BAD_REQUEST,void 0,void 0,!0);if(ku.isEmptyOrZeroLength(t))throw mt(new Error,hr.INVALID_VALUE("Source format"),pt.BAD_REQUEST,void 0,void 0,!0);if(ku.isEmpty(r))throw mt(new Error,hr.NOT_FOUND("Data"),pt.BAD_REQUEST,void 0,void 0,!0);if(t===XP){let n=og.createWriteStream(e);return o7(r).pipe(n),await E7(n),{message:c7,path:e}}else if(t===ZP){let n=og.createWriteStream(e),s=Vu.Readable.from(r),i={},o=r.getColumns?.();o&&(i.fields=o.map(l=>({label:l,value:l})));let c={objectMode:!0};return await new r7(i,c).fromInput(s).toOutput(n).promise(!1),{message:u7,path:e}}throw mt(new Error,hr.INVALID_VALUE("format"),pt.BAD_REQUEST)}a(p7,"saveToLocal");async function S7(e){if(!e.s3||Object.keys(e.s3).length===0)throw mt(new Error,hr.MISSING_VALUE("S3 object"),pt.BAD_REQUEST);if(Gr.isEmptyOrZeroLength(e.s3.aws_access_key_id))throw mt(new Error,hr.MISSING_VALUE("aws_access_key_id"),pt.BAD_REQUEST);if(Gr.isEmptyOrZeroLength(e.s3.aws_secret_access_key))throw mt(new Error,hr.MISSING_VALUE("aws_secret_access_key"),pt.BAD_REQUEST);if(Gr.isEmptyOrZeroLength(e.s3.bucket))throw mt(new Error,hr.MISSING_VALUE("bucket"),pt.BAD_REQUEST);if(Gr.isEmptyOrZeroLength(e.s3.key))throw mt(new Error,hr.MISSING_VALUE("key"),pt.BAD_REQUEST);if(Gr.isEmptyOrZeroLength(e.s3.region))throw mt(new Error,hr.MISSING_VALUE("region"),pt.BAD_REQUEST);let t=tv(e);if(!Gr.isEmpty(t))throw mt(new Error,t,pt.BAD_REQUEST);cn.trace(`called export_to_s3 to bucket: ${e.s3.bucket} and query ${e.search_operation.sql}`);let r;try{r=await rv(e)}catch(u){throw cn.error(u),u}let n,s=await t7.getS3AuthObj(e.s3.aws_access_key_id,e.s3.aws_secret_access_key,e.s3.region),i,o=new Vu.PassThrough;if(e.format===ZP){i=e.s3.key+".csv";let u=ev(r,r.getColumns?.());u.on("error",_=>{throw _}),u.pipe(o)}else if(e.format===XP){i=e.s3.key+".json";let u=new Vu.Readable;u.pipe(o),u.on("error",d=>{throw d}),u.push("[");let _=r.length,l="";for(let[d,f]of r.entries()){let E=d===_-1?JSON.stringify(f):JSON.stringify(f)+",";l+=E,d!==0&&d%l7===0&&(u.push(l),l="")}l.length!==0&&u.push(l),u.push("]"),u.push(null)}else throw mt(new Error,hr.INVALID_VALUE("format"),pt.BAD_REQUEST);return new a7({client:s,params:{Bucket:e.s3.bucket,Key:i,Body:o}}).done()}a(S7,"export_to_s3");function ev(e,t){let r=Vu.Readable.from(e?.[Symbol.iterator]||e?.[Symbol.asyncIterator]?e:[e]),n={};t&&(n.fields=t.map(o=>({label:o,value:o})));let s={objectMode:!0},i=new n7(n,s);return r.pipe(i)}a(ev,"toCsvStream");function tv(e){if(cn.trace("in exportCoreValidation"),Gr.isEmpty(e.format))return"format missing";if(JP.indexOf(e.format)<0)return`format invalid. must be one of the following values: ${JP.join(", ")}`;let t=e.search_operation.operation;if(Gr.isEmpty(t))return"search_operation.operation missing";if(zP.indexOf(t)<0)return`search_operation.operation must be one of the following values: ${zP.join(", ")}`}a(tv,"exportCoreValidation");async function rv(e){cn.trace("in getRecords");let t,r;if(ku.isEmpty(e.search_operation)||ku.isEmptyOrZeroLength(e.search_operation.operation))throw mt(new Error,hr.INVALID_VALUE("Search operation"),pt.BAD_REQUEST);switch(e.search_operation.operation){case"search_by_value":t=d7;break;case"search_by_hash":t=_7;break;case"search_by_conditions":t=ag.searchByConditions;break;case"sql":t=f7;break;default:throw r=`Operation ${e.search_operation.operation} is not support by export.`,cn.error(r),mt(new Error,r,pt.BAD_REQUEST)}return e.search_operation.hdb_user=e.hdb_user,t(e.search_operation)}a(rv,"getRecords")});var _v={};Ve(_v,{contentTypes:()=>dg,findBestSerializer:()=>hf,getDeserializer:()=>_o,registerContentHandlers:()=>fg,serialize:()=>mf,serializeMessage:()=>di});function T7(e){try{return e?.[0]===123?_g(e):e}catch{return e}}function fg(e){e.register(R7,{serializers:[{regex:/^application\/json$/,serializer:fc},{regex:/^application\/cbor$/,serializer:function(t){return new lo.EncoderStream(Yu).end(t)}},{regex:/^application\/(x-)?msgpack$/,serializer:function(t){return(t?.[Symbol.iterator]||t?.[Symbol.asyncIterator])&&!Array.isArray(t)?Ef.Readable.from((0,ts.encodeIter)(t,Yu)):(0,ts.pack)(t)}},{regex:/^text\/csv$/,serializer:function(t){return this.header("Content-Disposition",'attachment; filename="data.csv"'),(0,cg.toCsvStream)(t)}}]}),e.addContentTypeParser("application/x-msgpack",{parseAs:"buffer"},(t,r,n)=>{try{n(null,(0,ts.unpack)(r))}catch(s){s.statusCode=400,n(s)}}),e.addContentTypeParser("application/cbor",{parseAs:"buffer"},(t,r,n)=>{try{n(null,(0,lo.decode)(r))}catch(s){s.statusCode=400,n(s)}})}function hf(e){let r=(e.headers.asObject||e.headers).accept,n,s=0,i,o,c=r?r.toLowerCase().split(/\s*,\s*/):[];for(let u of c){let[_,...l]=u.split(/\s*;\s*/),d=1,f={q:1};for(let h of l){let p=h.indexOf("=");f[h.substring(0,p)]=h.substring(p+1)}d=+f.q;let E=Ut.get(_);if(E){let h=(E.q||1)*d;h>s&&(n=E,i=E.type||_,s=h,o=f)}}if(!n){if(r)return{serializer(){this.code(406).send("No supported content types found in Accept header, supported types include: "+Array.from(Ut.keys()).join(", "))}};n=Ut.get("application/json"),i="application/json"}return{serializer:n,type:i,parameters:o}}function mf(e,t,r){let n=iv&&t.headers.asObject?.["accept-encoding"]?.includes("br"),s;if(e?.contentType!=null&&e.data!=null)r.headers.set("Content-Type",e.contentType),r.headers.set("Vary","Accept-Encoding"),s=e.data;else if(e instanceof Uint8Array)r.headers.set("Content-Type","application/octet-stream"),r.headers.set("Vary","Accept-Encoding"),s=e;else{let i=hf(t);if(i.serializer.compressible===!1&&(n=!1),r.headers.set("Vary","Accept, Accept-Encoding"),r.headers.set("Content-Type",i.type),typeof e=="object"&&(e[Symbol.iterator]||e[Symbol.asyncIterator])&&i.serializer.serializeStream){let o=i.serializer.serializeStream(e,r);return n&&(r.headers.set("Content-Encoding","br"),o=o.pipe((0,Ds.createBrotliCompress)({params:{[Ds.constants.BROTLI_PARAM_MODE]:i.type.includes("json")||i.type.includes("text")?Ds.constants.BROTLI_MODE_TEXT:Ds.constants.BROTLI_MODE_GENERIC,[Ds.constants.BROTLI_PARAM_QUALITY]:2}}))),o}s=i.serializer.serialize(e,r)}return n&&s?.length>iv?(r.headers.set("Content-Encoding","br"),new Promise((i,o)=>(0,Ds.brotliCompress)(s,(c,u)=>{c?o(c):i(u)}))):s}function di(e,t){if(e?.contentType!=null&&e.data!=null)return e.data;if(!t)return $u(e);let r=t.serialize;if(r)return r(e);let n=hf(t);return r=t.serialize=n.serializer.serialize,r(e)}function A7(e){return new Promise((t,r)=>{let n=[];e.on("data",s=>n.push(s)),e.on("end",()=>t(Buffer.concat(n))),e.on("error",r)})}function _o(e,t){e||(e="");let r=e.indexOf(";"),n;r>-1&&(n=e.slice(r+1),e=e.slice(0,r));let s=Ut.get(e);if(t){if(s?.deserializeStream)return s.deserializeStream;let i=Ut.get(e)?.deserialize||ov(e,n);return o=>A7(o).then(i)}return e&&Ut.get(e)?.deserialize||ov(e,n)}function ov(e,t){if(e.startsWith("text/")){let r=t?.match(/charset=(.+)/)?.[1]||"utf-8";return n=>({contentType:e,data:n.toString(r)})}else return e==="application/octet-stream"?r=>r:r=>{if(!e)try{if(r?.[0]===123)return _g(r)}catch{}return{contentType:e||"application/octet-stream",data:r}}}function O7(e,t){return{[Symbol.asyncIterator](){let r=e[Symbol.asyncIterator]?e[Symbol.asyncIterator]():e[Symbol.iterator]();return{next(){let n=r.next();return n.then?n.then(s=>({value:t(s.value),done:s.done})):{value:t(n.value),done:n.done}},return(n){return r.return(n)},throw(n){return r.throw(n)}}}}}var cg,ts,lo,Ds,Ef,av,ug,lg,cv,uv,$u,_g,Yu,Ut,dg,sv,lv,g7,R7,iv,ha=Oe(()=>{Dh();cg=B(ff()),ts=require("msgpackr"),lo=require("cbor-x"),Ds=require("zlib"),Ef=require("stream");Zt();av=require("../../index"),ug=B(Z()),lg=B(M()),cv=B(require("yaml")),uv=ug.default.get(lg.CONFIG_PARAMS.SERIALIZATION_BIGINT)!==!1,$u=uv?Ci:JSON.stringify,_g=uv?Ch:JSON.parse,Yu={useRecords:!1,useToJSON:!0},Ut=new Map,dg=Ut;Xe.contentTypes=dg;(0,av._assignPackageExport)("contentTypes",dg);Ut.set("application/json",{serializeStream:fc,serialize:$u,deserialize:_g,q:.8});sv=new lo.Encoder(Yu);Ut.set("application/cbor",{serializeStream(e){return e[Symbol.asyncIterator]&&(e[Symbol.iterator]=null),new lo.EncoderStream(Yu).end(e)},serialize:sv.encode,deserialize:sv.decode,q:1});Ut.set("application/x-msgpack",{serializeStream(e){return(e?.[Symbol.iterator]||e?.[Symbol.asyncIterator])&&!Array.isArray(e)?Ef.Readable.from((0,ts.encodeIter)(e,Yu)):(0,ts.pack)(e)},serialize:ts.pack,deserialize:ts.unpack,q:.9});Ut.set("text/csv",{serializeStream(e,t){return t.headers.set("Content-Disposition",'attachment; filename="data.csv"'),(0,cg.toCsvStream)(e,e?.getColumns?.())},q:.1});Ut.set("text/plain",{serialize(e){return e.toString()},deserialize(e){return e.toString()},q:.01});Ut.set("text/yaml",{serialize(e){return cv.stringify(e,{aliasDuplicateObjects:!1})},q:.7});Ut.set("text/event-stream",{serializeStream:function(e){return Ef.Readable.from(O7(e,this.serialize))},serialize:function(e){if(e.acknowledge&&e.acknowledge(),typeof e=="object"&&"value"in e&&e.timestamp&&(e={data:e.value,event:e.type,id:e.timestamp}),e.data||e.event){let t="";if(e.event&&(t+="event: "+e.event+`
|
|
18
|
-
`),e.data){let r=e.data;typeof r=="object"&&(r
|
|
15
|
+
`,""):null}catch(f){f.stderr?i[u].npm_error=nP(f.stderr):i[u].npm_error=f.message;continue}try{i[u].npm_output=JSON.parse(l)}catch{i[u].npm_output=l}try{i[u].npm_error=JSON.parse(d)}catch{i[u].npm_error=d}}return ga.info(`finished installModules with response ${i}`),i}a(U6,"installModules");function nP(e){let t='"error": {',r=e.indexOf('"error": {'),n=e.indexOf(`}
|
|
16
|
+
`);return r>-1&&n>-1?JSON.parse(e.substring(r+t.length-1,n+1)):e}a(nP,"parseNPMStdErr");async function P6(e){ga.info(`starting auditModules for request: ${e}`);let t=iP(e);if(t)throw Sa(t,t.message,Ta.BAD_REQUEST);let{projects:r}=e;await Xd(),await sP(r);let n={};for(let s=0,i=r.length;s<i;s++){let o=r[s],c=jd.join(xT,o);n[o]={npm_output:null,npm_error:null};try{let u=await xu("npm audit --json",c);n[o].npm_output=JSON.parse(u)}catch(u){n[o].npm_error=nP(u.stderr)}}return ga.info(`finished auditModules with response ${n}`),n}a(P6,"auditModules");async function Xd(){try{return await xu("npm -v"),!0}catch{throw Sa(new Error,"Unable to install project dependencies: npm is not installed on this instance of HarperDB.",Ta.BAD_REQUEST,void 0,void 0,!0)}}a(Xd,"checkNPMInstalled");async function sP(e){if(!Array.isArray(e)||e.length===0)throw Sa(new Error,"projects argument must be an array with at least 1 element",Ta.BAD_REQUEST,void 0,void 0,!0);let t=[],r=[];for(let n=0,s=e.length;n<s;n++){let i=e[n],o=jd.join(xT,i.toString());if(!await eP.pathExists(o)){t.push(i);continue}let u=jd.join(o,"package.json");await eP.pathExists(u)||r.push(i)}if(t.length>0)throw Sa(new Error,`Unable to install project dependencies: custom function projects '${t.join(",")}' does not exist.`,Ta.BAD_REQUEST,void 0,void 0,!0);if(r.length>0)throw Sa(new Error,`Unable to install project dependencies: custom function projects '${r.join(",")}' do not have a package.json file.`,Ta.BAD_REQUEST,void 0,void 0,!0)}a(sP,"checkProjectPaths");function iP(e){let t=Jd.object({projects:Jd.array().min(1).items(Jd.string()).required(),dry_run:Jd.boolean().default(!1)});return I6.validateBySchema(e,t)}a(iP,"modulesValidator")});var FT=T(($fe,_P)=>{"use strict";var Ra=require("fs-extra"),qT=require("path"),ef=K(),aP=J(),tf=U(),lP=Z(),v6=Ir();_P.exports=B6;async function B6(){let e=H6(),t=lP.get(tf.CONFIG_PARAMS.ROOTPATH),r=qT.join(t,"package.json"),n={dependencies:{harperdb:"file:"+tf.PACKAGE_ROOT}},s=qT.join(t,"node_modules");await Ra.ensureDir(s);let i,o=!0,c=!1;try{i=await Ra.readJson(r)}catch(u){if(aP.isEmptyOrZeroLength(e))return;if(u.code!==tf.NODE_ERROR_CODES.ENOENT)throw u;o=!1}if(!aP.isEmptyOrZeroLength(e)){for(let{name:u,package:_}of e){let l=await cP(_);n.dependencies[u]=l+_}if(!o){ef.notify("Installing components"),await uP(r,n,null);return}for(let{name:u,package:_}of e){let l=i.dependencies[u],d=await cP(_);if(l===void 0||l!==d+_){c=!0;break}}}for(let u in i.dependencies)n.dependencies[u]===void 0&&(ef.notify("Removing component",u),c=!0);c&&(ef.notify("Updating components."),await uP(r,n,i))}a(B6,"installComponents");function H6(){let e=v6.getConfiguration(),t=[];for(let r in e)e[r]?.package&&t.push(Object.assign(e[r],{name:r}));return t}a(H6,"getComponentsConfig");async function cP(e){return e.includes(":")?"":e.startsWith("@")||!e.startsWith("@")&&!e.includes("/")?"npm:":qT.extname(e)||await Ra.pathExists(e)?"file:":"github:"}a(cP,"getPkgPrefix");async function uP(e,t,r){ef.trace("npm installing components package.json",t),await Ra.writeFile(e,JSON.stringify(t,null," "));try{await Zd().installAllRootModules(lP.get(tf.CONFIG_PARAMS.IGNORE_SCRIPTS)===!0)}catch(n){throw r?await Ra.writeFile(e,JSON.stringify(r,null," ")):await Ra.unlink(e),n}}a(uP,"installPackages")});var VT=T((Wfe,hP)=>{"use strict";var Fe=require("fs-extra"),GT=require("fast-glob"),Re=require("path"),fP=require("tar-fs"),Kfe=require("uuid").v4,kT=require("normalize-path"),ts=ZU(),Ot=K(),$e=U(),ht=Z(),qu=Ir(),x6=J(),{PACKAGE_ROOT:q6}=U(),{handleHDBError:Mt,hdb_errors:F6}=ee(),{basename:G6}=require("path"),k6=FT(),EP=Z(),V6=U(),{Readable:$6}=require("stream"),{isMainThread:Y6}=require("worker_threads"),{HDB_ERROR_MSGS:lo,HTTP_STATUS_CODES:Ut}=F6,K6=Re.join(q6,"application-template"),dP=Re.join(ht.get($e.HDB_SETTINGS_NAMES.HDB_ROOT_KEY),"tmp");function W6(){Ot.trace("getting custom api status");let e={};try{e={port:ht.get($e.CONFIG_PARAMS.HTTP_PORT),directory:ht.get($e.CONFIG_PARAMS.COMPONENTSROOT),is_enabled:!0}}catch(t){throw Mt(new Error,lo.FUNCTION_STATUS,Ut.INTERNAL_SERVER_ERROR,Ot.ERR,t)}return e}a(W6,"customFunctionsStatus");function Q6(){Ot.trace("getting custom api endpoints");let e={},t=ht.get($e.CONFIG_PARAMS.COMPONENTSROOT);try{GT.sync(kT(`${t}/*`),{onlyDirectories:!0}).forEach(n=>{let s=n.split("/").pop();e[s]={routes:GT.sync(kT(`${n}/routes/*.js`)).map(i=>i.split("/").pop().split(".js")[0]),helpers:GT.sync(kT(`${n}/helpers/*.js`)).map(i=>i.split("/").pop().split(".js")[0])}})}catch(r){throw Mt(new Error,lo.GET_FUNCTIONS,Ut.INTERNAL_SERVER_ERROR,Ot.ERR,r)}return e}a(Q6,"getCustomFunctions");function z6(e){e.project&&(e.project=Re.parse(e.project).name),e.file&&(e.file=Re.parse(e.file).name);let t=ts.getDropCustomFunctionValidator(e);if(t)throw Mt(t,t.message,Ut.BAD_REQUEST);Ot.trace("getting custom api endpoint file content");let r=ht.get($e.CONFIG_PARAMS.COMPONENTSROOT),{project:n,type:s,file:i}=e,o=Re.join(r,n,s,i+".js");try{return Fe.readFileSync(o,{encoding:"utf8"})}catch(c){throw Mt(new Error,lo.GET_FUNCTION,Ut.INTERNAL_SERVER_ERROR,Ot.ERR,c)}}a(z6,"getCustomFunction");function J6(e){e.project&&(e.project=Re.parse(e.project).name),e.file&&(e.file=Re.parse(e.file).name);let t=ts.setCustomFunctionValidator(e);if(t)throw Mt(t,t.message,Ut.BAD_REQUEST);Ot.trace("setting custom function file content");let r=ht.get($e.CONFIG_PARAMS.COMPONENTSROOT),{project:n,type:s,file:i,function_content:o}=e;try{return Fe.outputFileSync(Re.join(r,n,s,i+".js"),o),`Successfully updated custom function: ${i}.js`}catch(c){throw Mt(new Error,lo.SET_FUNCTION,Ut.INTERNAL_SERVER_ERROR,Ot.ERR,c)}}a(J6,"setCustomFunction");function j6(e){e.project&&(e.project=Re.parse(e.project).name),e.file&&(e.file=Re.parse(e.file).name);let t=ts.getDropCustomFunctionValidator(e);if(t)throw Mt(t,t.message,Ut.BAD_REQUEST);Ot.trace("dropping custom function file");let r=ht.get($e.CONFIG_PARAMS.COMPONENTSROOT),{project:n,type:s,file:i}=e;try{return Fe.unlinkSync(Re.join(r,n,s,i+".js")),`Successfully deleted custom function: ${i}.js`}catch(o){throw Mt(new Error,lo.DROP_FUNCTION,Ut.INTERNAL_SERVER_ERROR,Ot.ERR,o)}}a(j6,"dropCustomFunction");function X6(e){e.project&&(e.project=Re.parse(e.project).name);let t=ts.addComponentValidator(e);if(t)throw Mt(t,t.message,Ut.BAD_REQUEST);Ot.trace("adding component");let r=ht.get($e.CONFIG_PARAMS.COMPONENTSROOT),{project:n}=e;try{let s=Re.join(r,n);return Fe.mkdirSync(s,{recursive:!0}),Fe.copySync(K6,s),`Successfully added project: ${n}`}catch(s){throw Mt(new Error,lo.ADD_FUNCTION,Ut.INTERNAL_SERVER_ERROR,Ot.ERR,s)}}a(X6,"addComponent");function Z6(e){e.project&&(e.project=Re.parse(e.project).name);let t=ts.dropCustomFunctionProjectValidator(e);if(t)throw Mt(t,t.message,Ut.BAD_REQUEST);Ot.trace("dropping custom function project");let r=ht.get($e.CONFIG_PARAMS.COMPONENTSROOT),{project:n}=e,s=ht.get($e.CONFIG_PARAMS.APPS);if(!x6.isEmptyOrZeroLength(s)){let i=!1;for(let[o,c]of s.entries())if(c.name===n){s.splice(o,1),i=!0;break}if(i)return qu.updateConfigValue($e.CONFIG_PARAMS.APPS,s),`Successfully deleted project: ${n}`}try{let i=Re.join(r,n);return Fe.rmSync(i,{recursive:!0}),`Successfully deleted project: ${n}`}catch(i){throw Mt(new Error,lo.DROP_FUNCTION_PROJECT,Ut.INTERNAL_SERVER_ERROR,Ot.ERR,i)}}a(Z6,"dropCustomFunctionProject");async function e9(e){e.project&&(e.project=Re.parse(e.project).name);let t=ts.packageComponentValidator(e);if(t)throw Mt(t,t.message,Ut.BAD_REQUEST);let r=ht.get($e.CONFIG_PARAMS.COMPONENTSROOT),{project:n}=e;Ot.trace("packaging component",n);let s;try{s=await Fe.realpath(Re.join(r,n))}catch(u){if(u.code!==$e.NODE_ERROR_CODES.ENOENT)throw u;try{s=await Fe.realpath(Re.join(ht.get($e.CONFIG_PARAMS.ROOTPATH),"node_modules",n))}catch(_){if(_.code===$e.NODE_ERROR_CODES.ENOENT)throw new Error(`Unable to locate project '${n}'`)}}await Fe.ensureDir(dP);let i=Re.join(dP,`${n}.tar`),o={};(e.skip_node_modules===!0||e.skip_node_modules==="true")&&(o={ignore:u=>u.includes(Re.join(s,"node_modules"))}),fP.pack(s,o).pipe(Fe.createWriteStream(i,{overwrite:!0})),await new Promise(u=>setTimeout(u,2e3));let c=Fe.readFileSync(i,{encoding:"base64"});return await Fe.remove(i),{project:n,payload:c}}a(e9,"packageComponent");async function t9(e){e.project&&(e.project=Re.parse(e.project).name);let t=ts.deployComponentValidator(e);if(t)throw Mt(t,t.message,Ut.BAD_REQUEST);let r=ht.get($e.CONFIG_PARAMS.COMPONENTSROOT),{project:n,payload:s,package:i}=e;if(Ot.trace("deploying component",n),!s&&!i)throw new Error("'payload' or 'package' must be provided");let o;if(s){o=Re.join(r,n),i="file:"+o,await Fe.ensureDir(o);let f=$6.from(Buffer.from(s,"base64"));await new Promise((h,p)=>{f.pipe(fP.extract(o,{finish:h})).on("error",p)});let E=await Fe.readdir(o);E.length===1&&E[0]==="package"&&(await Fe.copy(Re.join(o,"package"),o),await Fe.remove(Re.join(o,"package")))}if(await qu.addConfig(n,{package:i}),!s){await k6();let f=EP.get(V6.CONFIG_PARAMS.ROOTPATH);o=Re.join(f,"node_modules",n)}if(Y6)return;let c=new Map;c.isWorker=!0;let u=(nf(),te(rf)),_;u.setErrorReporter(f=>_=f);let l=G6(o),d=u.component_errors.get(l);try{await u.loadComponent(o,c)}finally{u.component_errors.set(l,d)}if(_)throw _;return Ot.info("Installed component"),`Successfully deployed: ${n}`}a(t9,"deployComponent");async function r9(){let e=qu.getConfiguration(),t=[];for(let o in e)if(e[o]?.package){if(e[o].package.startsWith("file:"))continue;t.push(Object.assign({},e[o],{name:o}))}let r=a(async(o,c)=>{try{let u=await Fe.readdir(o,{withFileTypes:!0});for(let _ of u){let l=_.name;if(l.startsWith(".")||l==="node_modules")continue;let d=Re.join(o,l);if(_.isDirectory()||_.isSymbolicLink()){let f={name:l,entries:[]};c.entries.push(f),await r(d,f)}else{let f=await Fe.stat(d),E={name:Re.basename(l),mtime:f.mtime,size:f.size};c.entries.push(E)}}return c}catch(u){return Ot.warn("Error loading package",u),{error:u.toString(),entries:[]}}},"walk_dir"),n=await r(ht.get($e.CONFIG_PARAMS.COMPONENTSROOT),{name:ht.get($e.CONFIG_PARAMS.COMPONENTSROOT).split(Re.sep).slice(-1).pop(),entries:t});for(let o of n.entries)if(o.package){let c=await r(Re.join(ht.get($e.CONFIG_PARAMS.ROOTPATH),"node_modules",o.name),{name:o.name,entries:[]});Object.assign(o,c)}let i=(nf(),te(rf)).component_errors;for(let o of t){let c=i.get(o.name);c?o.error=i.get(o.name):c===void 0&&(o.error="The component has not been loaded yet (may need a restart)")}return n}a(r9,"getComponents");async function n9(e){let t=ts.getComponentFileValidator(e);if(t)throw Mt(t,t.message,Ut.BAD_REQUEST);let n=qu.getConfigObj()[e.project]||e.project==="harperdb"?Re.join(EP.get($e.CONFIG_PARAMS.ROOTPATH),"node_modules"):ht.get($e.CONFIG_PARAMS.COMPONENTSROOT),s=e.encoding?{encoding:e.encoding}:{encoding:"utf8"};try{let i=await Fe.stat(Re.join(n,e.project,e.file));return{message:await Fe.readFile(Re.join(n,e.project,e.file),s),size:i.size,birthtime:i.birthtime,mtime:i.mtime}}catch(i){throw i.code===$e.NODE_ERROR_CODES.ENOENT?new Error(`Component file not found '${Re.join(e.project,e.file)}'`):i}}a(n9,"getComponentFile");async function s9(e){let t=ts.setComponentFileValidator(e);if(t)throw Mt(t,t.message,Ut.BAD_REQUEST);let r=e.encoding?{encoding:e.encoding}:{encoding:"utf8"},n=Re.join(ht.get($e.CONFIG_PARAMS.COMPONENTSROOT),e.project,e.file);return e.payload!==void 0?(await Fe.ensureFile(n),await Fe.outputFile(n,e.payload,r)):await Fe.ensureDir(n),"Successfully set component: "+e.file}a(s9,"setComponentFile");async function i9(e){let t=ts.dropComponentFileValidator(e);if(t)throw Mt(t,t.message,Ut.BAD_REQUEST);let r=e.file?Re.join(e.project,e.file):e.project,n=Re.join(ht.get($e.CONFIG_PARAMS.COMPONENTSROOT),r);return await Fe.pathExists(n)&&await Fe.remove(n),qu.deleteConfigFromFile([e.project]),"Successfully dropped: "+r}a(i9,"dropComponent");hP.exports={customFunctionsStatus:W6,getCustomFunctions:Q6,getCustomFunction:z6,setCustomFunction:J6,dropCustomFunction:j6,addComponent:X6,dropCustomFunctionProject:Z6,packageComponent:e9,deployComponent:t9,getComponents:r9,getComponentFile:n9,setComponentFile:s9,dropComponent:i9}});var $T=T((zfe,pP)=>{"use strict";var rs=require("joi"),mP=je();pP.exports={readTransactionLogValidator:o9,deleteTransactionLogsBeforeValidator:a9};function o9(e){let t=rs.object({schema:rs.string().required(),table:rs.string().required(),from:rs.date().timestamp(),to:rs.date().timestamp(),limit:rs.number().min(1)});return mP.validateBySchema(e,t)}a(o9,"readTransactionLogValidator");function a9(e){let t=rs.object({schema:rs.string().required(),table:rs.string().required(),timestamp:rs.date().timestamp().required()});return mP.validateBySchema(e,t)}a(a9,"deleteTransactionLogsBeforeValidator")});var of=T((jfe,AP)=>{"use strict";var YT=U(),sf=ft(),SP=J(),TP=Z(),gP=ps(),{handleHDBError:Aa,hdb_errors:c9}=ee(),{HTTP_STATUS_CODES:Oa}=c9,{readTransactionLogValidator:u9,deleteTransactionLogsBeforeValidator:l9}=$T(),RP="This operation relies on clustering and cannot run with it disable.",_9="Logs successfully deleted from transaction log.",d9="All logs successfully deleted from transaction log.";AP.exports={readTransactionLog:f9,deleteTransactionLogsBefore:E9};async function*f9(e){let t=u9(e);if(t)throw Aa(t,t.message,Oa.BAD_REQUEST,void 0,void 0,!0);if(!TP.get(YT.CONFIG_PARAMS.CLUSTERING_ENABLED))throw Aa(new Error,RP,Oa.NOT_FOUND,void 0,void 0,!0);let{schema:r,table:n}=e,s=SP.checkSchemaTableExist(r,n);if(s)throw Aa(new Error,s,Oa.NOT_FOUND,void 0,void 0,!0);let i=gP.createNatsTableStreamName(r,n),o=await sf.viewStreamIterator(i,parseInt(e.from),e.limit);for await(let c of o){let u=Math.floor(c?.nats_timestamp/1e6);if(e.to&&u>e.to)break;let _={operation:c?.entry?.operation,user:c?.entry?.__origin?.user,timestamp:u,records:c?.entry?.records,attributes:c?.entry?.attributes};c?.entry?.operation===YT.OPERATIONS_ENUM.DELETE&&(_.hash_values=c?.entry?.hash_values),yield _}}a(f9,"readTransactionLog");async function E9(e){let t=l9(e);if(t)throw Aa(t,t.message,Oa.BAD_REQUEST,void 0,void 0,!0);if(!TP.get(YT.CONFIG_PARAMS.CLUSTERING_ENABLED))throw Aa(new Error,RP,Oa.NOT_FOUND,void 0,void 0,!0);let{schema:r,table:n,timestamp:s}=e,i=SP.checkSchemaTableExist(r,n);if(i)throw Aa(new Error,i,Oa.NOT_FOUND,void 0,void 0,!0);let o=gP.createNatsTableStreamName(r,n),{jsm:c}=await sf.getNATSReferences(),u=await sf.getStreamInfo(o),_=new Date(u.state.first_ts).getTime();if(s<=_)return`No transactions exist before: ${s}`;let l=_9,d,f=new Date(u.state.last_ts).getTime();return s>f?(d=u.state.last_seq+1,l=d9):d=(await sf.viewStream(o,parseInt(s),1))[0].nats_sequence,await c.streams.purge(o,{seq:d}),l}a(E9,"deleteTransactionLogsBefore")});var bP=T((Zfe,OP)=>{"use strict";var KT=class{static{a(this,"PermissionTableResponseObject")}constructor(t,r,n=[],s=[]){this.schema=t,this.table=r,this.required_table_permissions=n,this.required_attribute_permissions=s}};OP.exports=KT});var NP=T((tEe,yP)=>{"use strict";var WT=class{static{a(this,"PermissionAttributeResponseObject")}constructor(t,r=[]){this.attribute_name=t,this.required_permissions=r}};yP.exports=WT});var zT=T((nEe,IP)=>{"use strict";var wP=bP(),h9=NP(),{HDB_ERROR_MSGS:m9}=br(),QT=class{static{a(this,"PermissionResponseObject")}constructor(){this.error=m9.OP_AUTH_PERMS_ERROR,this.unauthorized_access={},this.invalid_schema_items=[]}handleUnauthorizedItem(t){return this.invalid_schema_items=[],this.unauthorized_access=[t],this}handleInvalidItem(t){return this.invalid_schema_items=[t],this.unauthorized_access=[],this}addInvalidItem(t,r,n){if(r&&n){let s=`${r}_${n}`;if(this.unauthorized_access[s])return}this.invalid_schema_items.push(t)}addUnauthorizedTable(t,r,n){let s=new wP(t,r,n),i=`${t}_${r}`;this.unauthorized_access[i]=s}addUnauthorizedAttributes(t,r,n,s){let i=[];t.forEach(c=>{let u=new h9(c,s[c]);i.push(u)});let o=`${r}_${n}`;if(this.unauthorized_access[o])this.unauthorized_access[o].required_attribute_permissions=i;else{let c=new wP(r,n,[],i);this.unauthorized_access[o]=c}}getPermsResponse(){let t=Object.values(this.unauthorized_access);return t.length>0||this.invalid_schema_items.length>0?(this.unauthorized_access=t,this):null}};IP.exports=QT});var lf=T((iEe,$P)=>{"use strict";var JT=en(),af=Zr(),cn=od(),ku=Hi(),jT=ki(),p9=uS(),S9=qD(),Vu=Ur(),cf=SS(),bt=K(),T9=RS(),g9=Od(),R9=nT(),A9=yd(),O9=sT(),b9=iT(),y9=cT(),N9=lT(),XT=fT(),Ds=J(),w9=BM(),ZT=ST(),LP=kd(),an=U(),MP=BU(),I9=ua(),UP=Eu(),PP=(Qd(),te(Pu)),vP=Ir(),Gr=VT(),C9=require("alasql"),BP=of(),HP=Zd(),xP=zT(),{handleHDBError:fr,hdb_errors:qP}=ee(),{HDB_ERROR_MSGS:qt,HTTP_STATUS_CODES:Fu}=qP,k=new Map,FP="delete",hi="insert",Ls="read",_o="update",Gu="describe",CP=ku.describeSchema.name,DP=ku.describeTable.name,GP={delete:!0,deleteRecord:!0,update:!0,updateData:!0,dropAttribute:!0,dropTable:!0,dropSchema:!0,upsert:!0,upsertData:!0},D9="catchup",L9="handleGetJob",M9="handleGetJobsByStartDate",uf={CSV_DATA_LOAD:"csvDataLoad",CSV_URL_LOAD:"csvURLLoad",CSV_FILE_LOAD:"csvFileLoad",IMPORT_FROM_S3:"importFromS3"},U9=[cn.createTable.name,cn.createAttribute.name,cn.dropTable.name,cn.dropAttribute.name],kP={EXPORT_TO_S3:"export_to_s3",EXPORT_LOCAL:"export_local"},Q=class{static{a(this,"permission")}constructor(t,r){this.requires_su=t,this.perms=r}};k.set(JT.insert.name,new Q(!1,[hi]));k.set(JT.update.name,new Q(!1,[_o]));k.set(JT.upsert.name,new Q(!1,[hi,_o]));k.set(af.searchByConditions.name,new Q(!1,[Ls]));k.set(af.searchByHash.name,new Q(!1,[Ls]));k.set(af.searchByValue.name,new Q(!1,[Ls]));k.set(af.search.name,new Q(!1,[Ls]));k.set(cn.createSchema.name,new Q(!0,[]));k.set(cn.createTable.name,new Q(!0,[]));k.set(cn.createAttribute.name,new Q(!1,[hi]));k.set(cn.dropSchema.name,new Q(!0,[]));k.set(cn.dropTable.name,new Q(!0,[]));k.set(cn.dropAttribute.name,new Q(!0,[]));k.set(ku.describeSchema.name,new Q(!1,[Ls]));k.set(ku.describeTable.name,new Q(!1,[Ls]));k.set(jT.deleteRecord.name,new Q(!1,[FP]));k.set(Vu.addUser.name,new Q(!0,[]));k.set(Vu.alterUser.name,new Q(!0,[]));k.set(Vu.dropUser.name,new Q(!0,[]));k.set(Vu.listUsersExternal.name,new Q(!0,[]));k.set(cf.listRoles.name,new Q(!0,[]));k.set(cf.addRole.name,new Q(!0,[]));k.set(cf.alterRole.name,new Q(!0,[]));k.set(cf.dropRole.name,new Q(!0,[]));k.set(T9.name,new Q(!0,[]));k.set(g9.name,new Q(!0,[]));k.set(R9.name,new Q(!0,[]));k.set(A9.name,new Q(!0,[]));k.set(O9.name,new Q(!0,[]));k.set(b9.name,new Q(!0,[]));k.set(XT.setRoutes.name,new Q(!0,[]));k.set(XT.getRoutes.name,new Q(!0,[]));k.set(XT.deleteRoutes.name,new Q(!0,[]));k.set(vP.setConfiguration.name,new Q(!0,[]));k.set(y9.clusterStatus.name,new Q(!0,[]));k.set(N9.name,new Q(!0,[]));k.set(ZT.getFingerprint.name,new Q(!0,[]));k.set(ZT.setLicense.name,new Q(!0,[]));k.set(jT.deleteFilesBefore.name,new Q(!0,[]));k.set(jT.deleteAuditLogsBefore.name,new Q(!0,[]));k.set(LP.restart.name,new Q(!0,[]));k.set(LP.restartService.name,new Q(!0,[]));k.set(p9.name,new Q(!0,[]));k.set(S9.name,new Q(!0,[Ls]));k.set(I9.systemInformation.name,new Q(!0,[]));k.set(vP.getConfiguration.name,new Q(!0,[]));k.set(BP.readTransactionLog.name,new Q(!0,[]));k.set(BP.deleteTransactionLogsBefore.name,new Q(!0,[]));k.set(HP.installModules.name,new Q(!0,[]));k.set(HP.auditModules.name,new Q(!0,[]));k.set(UP.createTokens.name,new Q(!1,[]));k.set(UP.refreshOperationToken.name,new Q(!1,[]));k.set(PP.login.name,new Q(!1,[]));k.set(PP.logout.name,new Q(!1,[]));k.set(Gr.customFunctionsStatus.name,new Q(!0,[]));k.set(Gr.getCustomFunctions.name,new Q(!0,[]));k.set(Gr.getComponents.name,new Q(!0,[]));k.set(Gr.getComponentFile.name,new Q(!0,[]));k.set(Gr.setComponentFile.name,new Q(!0,[]));k.set(Gr.dropComponent.name,new Q(!0,[]));k.set(Gr.getCustomFunction.name,new Q(!0,[]));k.set(Gr.setCustomFunction.name,new Q(!0,[]));k.set(Gr.dropCustomFunction.name,new Q(!0,[]));k.set(Gr.addComponent.name,new Q(!0,[]));k.set(Gr.dropCustomFunctionProject.name,new Q(!0,[]));k.set(Gr.packageComponent.name,new Q(!0,[]));k.set(Gr.deployComponent.name,new Q(!0,[]));k.set(ZT.getRegistrationInfo.name,new Q(!1,[]));k.set(Vu.userInfo.name,new Q(!1,[]));k.set(ku.describeAll.name,new Q(!1,[]));k.set(L9,new Q(!1,[]));k.set(M9,new Q(!0,[]));k.set(D9,new Q(!0,[]));k.set(uf.CSV_DATA_LOAD,new Q(!1,[hi,_o]));k.set(uf.CSV_URL_LOAD,new Q(!1,[hi,_o]));k.set(uf.CSV_FILE_LOAD,new Q(!1,[hi,_o]));k.set(uf.IMPORT_FROM_S3,new Q(!1,[hi,_o]));k.set(kP.EXPORT_TO_S3,new Q(!0,[]));k.set(kP.EXPORT_LOCAL,new Q(!0,[]));k.set(an.VALID_SQL_OPS_ENUM.DELETE,new Q(!1,[FP]));k.set(an.VALID_SQL_OPS_ENUM.SELECT,new Q(!1,[Ls]));k.set(an.VALID_SQL_OPS_ENUM.INSERT,new Q(!1,[hi]));k.set(an.VALID_SQL_OPS_ENUM.UPDATE,new Q(!1,[_o]));$P.exports={verifyPerms:v9,verifyPermsAst:P9,verifyBulkLoadAttributePerms:H9};function P9(e,t,r){if(Ds.isEmptyOrZeroLength(e))throw bt.info("verify_perms_ast has an empty user parameter"),fr(new Error);if(Ds.isEmptyOrZeroLength(t))throw bt.info("verify_perms_ast has an empty user parameter"),fr(new Error);if(Ds.isEmptyOrZeroLength(r))throw bt.info("verify_perms_ast has a null operation parameter"),fr(new Error);try{let n=new xP,s=new w9(e),i=s.getSchemas(),o=new Map;if((!i||i.length===0)&&s.affected_attributes&&s.affected_attributes.size>0)throw bt.info("No schemas defined in verifyPermsAst(), will not continue."),fr(new Error);let c=!!t.role.permission.super_user,u=i.includes("system");if(u&&GP[r])throw fr(new Error,qt.DROP_SYSTEM,Fu.FORBIDDEN);if(c&&!u)return null;let _=MP.getRolePermissions(t.role);t.role.permission=_,!c&&e instanceof C9.yy.Select&&(e=s.updateAttributeWildcardsForRolePerms(_));for(let d=0;d<i.length;d++){let f=s.getTablesBySchemaName(i[d]);f&&o.set(i[d],f)}let l=VP(t,r,o,n);return l||(o.forEach((d,f)=>{for(let E=0;E<d.length;E++){let h=s.getAttributesBySchemaTableName(f,d[E]),p=tg(t.role.permission,f,d[E]);eg(h,p,r,d[E],f,n)}}),n.getPermsResponse())}catch(n){throw fr(n)}}a(P9,"verifyPermsAst");function v9(e,t){if(e===null||t===null||e.hdb_user===void 0||e.hdb_user===null)throw bt.info("null required parameter in verifyPerms"),fr(new Error,qt.DEFAULT_INVALID_REQUEST,Fu.BAD_REQUEST);let r;t instanceof Function?r=t.name:r=t;let n=e.action,s=e.schema??e.database,i=e.table,o=new Map;s&&i&&o.set(s,[i]);let c=new xP;if(Ds.isEmptyOrZeroLength(e.hdb_user.role)||Ds.isEmptyOrZeroLength(e.hdb_user.role.permission))return bt.info(`User ${e.hdb_user.username} has no role or permissions. Please assign the user a valid role.`),c.handleUnauthorizedItem(qt.USER_HAS_NO_PERMS(e.hdb_user.username));let u=!!e.hdb_user.role.permission.super_user,_=e.hdb_user.role.permission.structure_user,l=o.has(an.SYSTEM_SCHEMA_NAME)||s===an.SYSTEM_SCHEMA_NAME;if(l&&GP[r])throw fr(new Error,qt.DROP_SYSTEM,Fu.FORBIDDEN);if(u&&!l||_===!0&&(r===cn.createSchema.name||r===cn.dropSchema.name))return null;if(U9.indexOf(r)>=0&&(_===!0||Array.isArray(_)))return _===!0||_.indexOf(s)>=0?null:c.handleUnauthorizedItem(`User does not have access to perform '${e.operation}' against schema '${s}'`);let d=MP.getRolePermissions(e.hdb_user.role);if(e.hdb_user.role.permission=d,r===CP||r===DP){if(s===an.SYSTEM_SCHEMA_NAME)return c.handleUnauthorizedItem(qt.SCHEMA_PERM_ERROR(s));if(!d.super_user){if(r===CP&&(!d[s]||!d[s][Gu]))return c.handleInvalidItem(qt.SCHEMA_NOT_FOUND(s));if(r===DP&&(!d[s]||!d[s].tables[i]||!d[s].tables[i][Gu]))return c.handleInvalidItem(qt.TABLE_NOT_FOUND(s,i))}}let f=VP(e.hdb_user,r,o,c,n);if(f)return f;if(k.get(r)&&k.get(r).perms.length===0)return null;if(!u&&e.get_attributes&&an.SEARCH_WILDCARDS.includes(e.get_attributes[0])){let p=[],S=d[s].tables[i];S[an.PERMS_CRUD_ENUM.READ]&&(S.attribute_permissions.length>0?S.attribute_permissions.filter(g=>g[an.PERMS_CRUD_ENUM.READ]).forEach(g=>{p.push(g.attribute_name)}):p=global.hdb_schema[s][i].attributes.map(O=>O.attribute),e.get_attributes=p)}let E=B9(e),h=tg(e.hdb_user.role.permission,s,i);return eg(E,h,r,i,s,c,n),c.getPermsResponse()}a(v9,"verifyPerms");function VP(e,t,r,n,s){if(Ds.arrayHasEmptyValues([e,t,r]))throw bt.info("hasPermissions has an invalid parameter"),fr(new Error);let i=r.has("system"),o=e.role.permission;if(o.super_user&&(!i||k.get(t).requires_su))return null;if(!k.get(t))throw bt.info(`operation ${t} not found.`),fr(new Error,qt.OP_NOT_FOUND(t),Fu.BAD_REQUEST);if(k.get(t)&&k.get(t).requires_su)return bt.info(`operation ${t} requires SU permissions.`),n.handleUnauthorizedItem(qt.OP_IS_SU_ONLY(t));let c=r.keys();for(let u of c){try{if(u&&!o[u]||o[u][Gu]===!1){n.addInvalidItem(qt.SCHEMA_NOT_FOUND(u));continue}}catch{n.addInvalidItem(qt.SCHEMA_NOT_FOUND(u));continue}let _=r.get(u);for(let l of _){let d=o[u].tables[l];if(!d||d[Gu]===!1)n.addInvalidItem(qt.TABLE_NOT_FOUND(u,l));else try{let f=[],E=k.get(t).perms;!Ds.isEmpty(s)&&E.includes(s)&&(E=[s]);for(let h=0;h<E.length;h++){let p=E[h],S=d[p];(S==null||S===!1)&&(bt.info(`Required ${p} permission not found for ${t} ${s?`${s} `:""}operation in role ${e.role.id}`),f.push(p))}f.length>0&&n.addUnauthorizedTable(u,l,f)}catch(f){let E=qt.UNKNOWN_OP_AUTH_ERROR(t,u,l);throw bt.error(E),bt.error(f),fr(qP.CHECK_LOGS_WRAPPER(E))}}}return r.size<2?n.getPermsResponse():null}a(VP,"hasPermissions");function eg(e,t,r,n,s,i,o){if(!e||!t)throw bt.info("no attributes specified in checkAttributePerms."),fr(new Error);let c=k.get(r).perms;if(!c||c==="")throw bt.info(`no permissions found for ${r} in checkAttributePerms().`),fr(new Error);if(Ds.isEmptyOrZeroLength(t))return bt.info("No role permissions set (this is OK)."),null;o&&c.includes(o)&&(c=[o]);let u={};for(let l of e){let d=t.get(l);if(d){if(d[Gu]===!1){i.addInvalidItem(qt.ATTR_NOT_FOUND(s,n,l),s,n);continue}if(c)for(let f of c){if(an.TIME_STAMP_NAMES.includes(d.attribute_name)&&f!==Ls)throw fr(new Error,qt.SYSTEM_TIMESTAMP_PERMS_ERR,Fu.FORBIDDEN);d[f]===!1&&(u[d.attribute_name]?u[d.attribute_name].push(f):u[d.attribute_name]=[f])}}else i.addInvalidItem(qt.ATTR_NOT_FOUND(s,n,l),s,n)}let _=Object.keys(u);_.length>0&&i.addUnauthorizedAttributes(_,s,n,u)}a(eg,"checkAttributePerms");function B9(e){let t=new Set;try{if(e.action)return t;if(e.operation===an.OPERATIONS_ENUM.SEARCH_BY_CONDITIONS&&e.conditions.forEach(r=>{t.add(r.search_attribute)}),e&&e.search_attribute&&t.add(e.search_attribute),!e.records||e.records.length===0){if(!e.get_attributes||!e.get_attributes.length===0)return t;for(let r=0;r<e.get_attributes.length;r++)t.add(e.get_attributes[r])}else for(let r=0;r<e.records.length;r++){let n=Object.keys(e.records[r]);for(let s=0;s<n.length;s++)t.add(n[s])}}catch(r){bt.info(r)}return t}a(B9,"getRecordAttributes");function tg(e,t,r){let n=new Map;if(Ds.isEmpty(e))return bt.info("no hdb_user specified in getAttributePermissions"),n;if(e.super_user||!t||!r)return n;try{e[t].tables[r].attribute_permissions.forEach(s=>{n.has(s.attribute_name)||n.set(s.attribute_name,s)})}catch{bt.info(`No attribute permissions found for schema ${t} and table ${r}.`)}return n}a(tg,"getAttributePermissions");function H9(e,t,r,n,s,i,o){let c=new Set(i),u=tg(e,n,s);eg(c,u,t,s,n,o,r)}a(H9,"verifyBulkLoadAttributePerms")});var df=T((aEe,zP)=>{"use strict";zP.exports={evaluateSQL:J9,processAST:QP,convertSQLToAST:WP,checkASTPermissions:KP};var x9=en(),YP=require("util"),q9=YP.callbackify(x9.insert),F9=Zr().search,G9=LC().update,k9=YP.callbackify(G9),V9=UC().convertDelete,mi=require("alasql"),$9=lf(),_f=K(),Y9=W_(),K9=J(),$u=U(),{hdb_errors:W9,handleHDBError:rg}=ee(),{HTTP_STATUS_CODES:ng}=W9;Y9(mi);var Q9=403,z9="There was a problem performing this insert. Please check the logs and try again.",sg=class{static{a(this,"ParsedSQLObject")}constructor(){this.ast=void 0,this.variant=void 0,this.permissions_checked=!1}};function J9(e,t){let r=e.parsed_sql_object;if(!r){r=WP(e.sql);let n,s=r.ast.statements[0];if(s instanceof mi.yy.Insert?n=s.into.databaseid:s instanceof mi.yy.Select?n=s.from?s.from[0].databaseid:null:s instanceof mi.yy.Update||s instanceof mi.yy.Delete?n=s.table.databaseid:_f.error("AST in evaluateSQL is not a valid SQL type."),!(s instanceof mi.yy.Select)&&K9.isEmptyOrZeroLength(n))return t("No schema specified",null)}QP(e,r,(n,s)=>{if(n)return t(n);t(null,s)})}a(J9,"evaluateSQL");function KP(e,t){let r;try{r=$9.verifyPermsAst(t.ast.statements[0],e.hdb_user,t.variant),t.permissions_checked=!0}catch(n){throw n}return r||null}a(KP,"checkASTPermissions");function WP(e){let t=new sg;if(!e)throw rg(new Error,"The 'sql' parameter is missing from the request body",ng.BAD_REQUEST);try{let r=e.trim(),n=mi.parse(r),s=r.split(" ")[0].toLowerCase();t.ast=n,t.variant=s}catch(r){let n=r.message.split(`
|
|
17
|
+
`);throw n[1]?rg(r,`Invalid SQL at: ${n[1]}. Please ensure your SQL is valid. Try adding backticks to reserved words and schema table references.`,ng.BAD_REQUEST):rg(r,"We had trouble parsing your request. Please ensure your SQL is valid. Try adding backticks to reserved words and schema table references.",ng.BAD_REQUEST)}return t}a(WP,"convertSQLToAST");function QP(e,t,r){try{let n=j9;if(!e.bypass_auth&&!t.permissions_checked){let i=KP(e,t);if(i&&i.length>0)return r(Q9,i)}let s={statement:t.ast.statements[0],hdb_user:e.hdb_user};switch(t.variant){case $u.VALID_SQL_OPS_ENUM.SELECT:n=F9,s=t.ast.statements[0];break;case $u.VALID_SQL_OPS_ENUM.INSERT:n=X9;break;case $u.VALID_SQL_OPS_ENUM.UPDATE:n=k9;break;case $u.VALID_SQL_OPS_ENUM.DELETE:n=V9;break;default:throw new Error(`unsupported SQL type ${t.variant} in SQL: ${e}`)}n(s,(i,o)=>{if(i){r(i);return}r(null,o)})}catch(n){return r(n)}}a(QP,"processAST");function j9(e,t){_f.info(e),t("unknown sql statement")}a(j9,"nullFunction");function X9({statement:e,hdb_user:t},r){let n=e.into,s={schema:n.databaseid,table:n.tableid,operation:"insert",hdb_user:t},i=e.columns.map(o=>o.columnid);try{s.records=Z9(i,e.values)}catch(o){return r(o)}q9(s,(o,c)=>{if(o)return r(o);try{delete c.new_attributes,delete c.txn_time}catch(u){_f.error(`Error delete new_attributes from insert response: ${u}`)}r(null,c)})}a(X9,"convertInsert");function Z9(e,t){try{return t.map(r=>{if(e.length!==r.length)throw"number of values do not match number of columns in insert";let n={};return r.forEach((s,i)=>{if(s.columnid)throw"cannot use a column in insert value";"value"in s?n[e[i]]=s.value:n[e[i]]=mi.compile(`SELECT ${s.toString()} AS [${$u.FUNC_VAL}] FROM ?`)}),n})}catch(r){throw _f.error(r),new Error(z9)}}a(Z9,"createDataObjects")});var ig=T((uEe,jP)=>{"use strict";var{S3:e7,GetObjectCommand:t7}=require("@aws-sdk/client-s3");jP.exports={getFileStreamFromS3:r7,getS3AuthObj:JP};async function r7(e){let{s3:t}=e,r={Bucket:t.bucket,Key:t.key};return(await JP(t.aws_access_key_id,t.aws_secret_access_key,t.region).send(new t7(r))).Body}a(r7,"getFileStreamFromS3");function JP(e,t,r){return new e7({credentials:{accessKeyId:e,secretAccessKey:t},region:r})}a(JP,"getS3AuthObj")});var ff=T((_Ee,ov)=>{"use strict";var ag=Zr(),n7=df(),s7=ig(),{AsyncParser:i7,Transform:o7}=require("json2csv"),Ku=require("stream"),kr=J(),og=require("fs-extra"),a7=require("path"),un=K(),{promisify:ev}=require("util"),Yu=J(),{handleHDBError:mt,hdb_errors:c7}=ee(),{HDB_ERROR_MSGS:Er,HTTP_STATUS_CODES:pt}=c7,{streamAsJSON:u7}=(Dh(),te(fb)),{Upload:l7}=require("@aws-sdk/lib-storage"),XP=["search_by_value","search_by_hash","sql","search_by_conditions"],ZP=["json","csv"],tv="json",rv="csv",_7="Successfully exported JSON locally.",d7="Successfully exported CSV locally.",f7=1e3,E7=ag.searchByHash,h7=ag.searchByValue,m7=ev(n7.evaluateSQL),p7=ev(Ku.finished);ov.exports={export_to_s3:R7,export_local:S7,toCsvStream:nv};async function S7(e){un.trace(`export_local request to path: ${e.path}, filename: ${e.filename}, format: ${e.format}`);let t=sv(e);if(!kr.isEmpty(t))throw un.error(t),mt(new Error,t,pt.BAD_REQUEST,void 0,void 0,!0);if(kr.isEmpty(e.path))throw un.error(Er.MISSING_VALUE("path")),mt(new Error,Er.MISSING_VALUE("path"),pt.BAD_REQUEST,void 0,void 0,!0);let r=(kr.isEmpty(e.filename)?new Date().getTime():e.filename)+"."+e.format;e.path.endsWith(a7.sep)&&(e.path=e.path.substring(0,e.path.length-1));let n=kr.buildFolderPath(e.path,r);await T7(e.path);let s=await iv(e);return await g7(n,e.format,s)}a(S7,"export_local");async function T7(e){if(un.trace("in confirmPath"),kr.isEmptyOrZeroLength(e))throw mt(new Error,`Invalid path: ${e}`,pt.BAD_REQUEST,void 0,void 0,!0);let t;try{t=await og.stat(e)}catch(r){let n;throw r.code==="ENOENT"?n=`path '${e}' does not exist`:r.code==="EACCES"?n=`access to path '${e}' is denied`:n=r.message,un.error(n),mt(new Error,n,pt.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 un.error(r),mt(new Error,r,pt.BAD_REQUEST,void 0,void 0,!0)}return!0}a(T7,"confirmPath");async function g7(e,t,r){if(un.trace("in saveToLocal"),Yu.isEmptyOrZeroLength(e))throw mt(new Error,Er.INVALID_VALUE("file_path"),pt.BAD_REQUEST,void 0,void 0,!0);if(Yu.isEmptyOrZeroLength(t))throw mt(new Error,Er.INVALID_VALUE("Source format"),pt.BAD_REQUEST,void 0,void 0,!0);if(Yu.isEmpty(r))throw mt(new Error,Er.NOT_FOUND("Data"),pt.BAD_REQUEST,void 0,void 0,!0);if(t===tv){let n=og.createWriteStream(e);return u7(r).pipe(n),await p7(n),{message:_7,path:e}}else if(t===rv){let n=og.createWriteStream(e),s=Ku.Readable.from(r),i={},o=r.getColumns?.();o&&(i.fields=o.map(l=>({label:l,value:l})));let c={objectMode:!0};return await new i7(i,c).fromInput(s).toOutput(n).promise(!1),{message:d7,path:e}}throw mt(new Error,Er.INVALID_VALUE("format"),pt.BAD_REQUEST)}a(g7,"saveToLocal");async function R7(e){if(!e.s3||Object.keys(e.s3).length===0)throw mt(new Error,Er.MISSING_VALUE("S3 object"),pt.BAD_REQUEST);if(kr.isEmptyOrZeroLength(e.s3.aws_access_key_id))throw mt(new Error,Er.MISSING_VALUE("aws_access_key_id"),pt.BAD_REQUEST);if(kr.isEmptyOrZeroLength(e.s3.aws_secret_access_key))throw mt(new Error,Er.MISSING_VALUE("aws_secret_access_key"),pt.BAD_REQUEST);if(kr.isEmptyOrZeroLength(e.s3.bucket))throw mt(new Error,Er.MISSING_VALUE("bucket"),pt.BAD_REQUEST);if(kr.isEmptyOrZeroLength(e.s3.key))throw mt(new Error,Er.MISSING_VALUE("key"),pt.BAD_REQUEST);if(kr.isEmptyOrZeroLength(e.s3.region))throw mt(new Error,Er.MISSING_VALUE("region"),pt.BAD_REQUEST);let t=sv(e);if(!kr.isEmpty(t))throw mt(new Error,t,pt.BAD_REQUEST);un.trace(`called export_to_s3 to bucket: ${e.s3.bucket} and query ${e.search_operation.sql}`);let r;try{r=await iv(e)}catch(u){throw un.error(u),u}let n,s=await s7.getS3AuthObj(e.s3.aws_access_key_id,e.s3.aws_secret_access_key,e.s3.region),i,o=new Ku.PassThrough;if(e.format===rv){i=e.s3.key+".csv";let u=nv(r,r.getColumns?.());u.on("error",_=>{throw _}),u.pipe(o)}else if(e.format===tv){i=e.s3.key+".json";let u=new Ku.Readable;u.pipe(o),u.on("error",d=>{throw d}),u.push("[");let _=r.length,l="";for(let[d,f]of r.entries()){let E=d===_-1?JSON.stringify(f):JSON.stringify(f)+",";l+=E,d!==0&&d%f7===0&&(u.push(l),l="")}l.length!==0&&u.push(l),u.push("]"),u.push(null)}else throw mt(new Error,Er.INVALID_VALUE("format"),pt.BAD_REQUEST);return new l7({client:s,params:{Bucket:e.s3.bucket,Key:i,Body:o}}).done()}a(R7,"export_to_s3");function nv(e,t){let r=Ku.Readable.from(e?.[Symbol.iterator]||e?.[Symbol.asyncIterator]?e:[e]),n={};t&&(n.fields=t.map(o=>({label:o,value:o})));let s={objectMode:!0},i=new o7(n,s);return r.pipe(i)}a(nv,"toCsvStream");function sv(e){if(un.trace("in exportCoreValidation"),kr.isEmpty(e.format))return"format missing";if(ZP.indexOf(e.format)<0)return`format invalid. must be one of the following values: ${ZP.join(", ")}`;let t=e.search_operation.operation;if(kr.isEmpty(t))return"search_operation.operation missing";if(XP.indexOf(t)<0)return`search_operation.operation must be one of the following values: ${XP.join(", ")}`}a(sv,"exportCoreValidation");async function iv(e){un.trace("in getRecords");let t,r;if(Yu.isEmpty(e.search_operation)||Yu.isEmptyOrZeroLength(e.search_operation.operation))throw mt(new Error,Er.INVALID_VALUE("Search operation"),pt.BAD_REQUEST);switch(e.search_operation.operation){case"search_by_value":t=h7;break;case"search_by_hash":t=E7;break;case"search_by_conditions":t=ag.searchByConditions;break;case"sql":t=m7;break;default:throw r=`Operation ${e.search_operation.operation} is not support by export.`,un.error(r),mt(new Error,r,pt.BAD_REQUEST)}return e.search_operation.hdb_user=e.hdb_user,t(e.search_operation)}a(iv,"getRecords")});var Ev={};ke(Ev,{contentTypes:()=>dg,findBestSerializer:()=>hf,getDeserializer:()=>Eo,registerContentHandlers:()=>fg,serialize:()=>mf,serializeMessage:()=>Ei});function A7(e){try{return e?.[0]===123?_g(e):e}catch{return e}}function fg(e){e.register(b7,{serializers:[{regex:/^application\/json$/,serializer:mc},{regex:/^application\/cbor$/,serializer:function(t){return new fo.EncoderStream(Qu).end(t)}},{regex:/^application\/(x-)?msgpack$/,serializer:function(t){return(t?.[Symbol.iterator]||t?.[Symbol.asyncIterator])&&!Array.isArray(t)?Ef.Readable.from((0,ns.encodeIter)(t,Qu)):(0,ns.pack)(t)}},{regex:/^text\/csv$/,serializer:function(t){return this.header("Content-Disposition",'attachment; filename="data.csv"'),(0,cg.toCsvStream)(t)}}]}),e.addContentTypeParser("application/x-msgpack",{parseAs:"buffer"},(t,r,n)=>{try{n(null,(0,ns.unpack)(r))}catch(s){s.statusCode=400,n(s)}}),e.addContentTypeParser("application/cbor",{parseAs:"buffer"},(t,r,n)=>{try{n(null,(0,fo.decode)(r))}catch(s){s.statusCode=400,n(s)}})}function hf(e){let r=(e.headers.asObject||e.headers).accept,n,s=0,i,o,c=r?r.toLowerCase().split(/\s*,\s*/):[];for(let u of c){let[_,...l]=u.split(/\s*;\s*/),d=1,f={q:1};for(let h of l){let p=h.indexOf("=");f[h.substring(0,p)]=h.substring(p+1)}d=+f.q;let E=Pt.get(_);if(E){let h=(E.q||1)*d;h>s&&(n=E,i=E.type||_,s=h,o=f)}}if(!n){if(r)return{serializer(){this.code(406).send("No supported content types found in Accept header, supported types include: "+Array.from(Pt.keys()).join(", "))}};n=Pt.get("application/json"),i="application/json"}return{serializer:n,type:i,parameters:o}}function mf(e,t,r){let n=cv&&t.headers.asObject?.["accept-encoding"]?.includes("br"),s;if(e?.contentType!=null&&e.data!=null)r.headers.set("Content-Type",e.contentType),r.headers.set("Vary","Accept-Encoding"),s=e.data;else if(e instanceof Uint8Array)r.headers.set("Content-Type","application/octet-stream"),r.headers.set("Vary","Accept-Encoding"),s=e;else{let i=hf(t);if(i.serializer.compressible===!1&&(n=!1),r.headers.set("Vary","Accept, Accept-Encoding"),r.headers.set("Content-Type",i.type),typeof e=="object"&&(e[Symbol.iterator]||e[Symbol.asyncIterator])&&i.serializer.serializeStream){let o=i.serializer.serializeStream(e,r);return n&&(r.headers.set("Content-Encoding","br"),o=o.pipe((0,Ms.createBrotliCompress)({params:{[Ms.constants.BROTLI_PARAM_MODE]:i.type.includes("json")||i.type.includes("text")?Ms.constants.BROTLI_MODE_TEXT:Ms.constants.BROTLI_MODE_GENERIC,[Ms.constants.BROTLI_PARAM_QUALITY]:2}}))),o}s=i.serializer.serialize(e,r)}return n&&s?.length>cv?(r.headers.set("Content-Encoding","br"),new Promise((i,o)=>(0,Ms.brotliCompress)(s,(c,u)=>{c?o(c):i(u)}))):s}function Ei(e,t){if(e?.contentType!=null&&e.data!=null)return e.data;if(!t)return Wu(e);let r=t.serialize;if(r)return r(e);let n=hf(t);return r=t.serialize=n.serializer.serialize,r(e)}function y7(e){return new Promise((t,r)=>{let n=[];e.on("data",s=>n.push(s)),e.on("end",()=>t(Buffer.concat(n))),e.on("error",r)})}function Eo(e,t){e||(e="");let r=e.indexOf(";"),n;r>-1&&(n=e.slice(r+1),e=e.slice(0,r));let s=Pt.get(e);if(t){if(s?.deserializeStream)return s.deserializeStream;let i=Pt.get(e)?.deserialize||uv(e,n);return o=>y7(o).then(i)}return e&&Pt.get(e)?.deserialize||uv(e,n)}function uv(e,t){if(e.startsWith("text/")){let r=t?.match(/charset=(.+)/)?.[1]||"utf-8";return n=>({contentType:e,data:n.toString(r)})}else return e==="application/octet-stream"?r=>r:r=>{if(!e)try{if(r?.[0]===123)return _g(r)}catch{}return{contentType:e||"application/octet-stream",data:r}}}function N7(e,t){return{[Symbol.asyncIterator](){let r=e[Symbol.asyncIterator]?e[Symbol.asyncIterator]():e[Symbol.iterator]();return{next(){let n=r.next();return n.then?n.then(s=>({value:t(s.value),done:s.done})):{value:t(n.value),done:n.done}},return(n){return r.return(n)},throw(n){return r.throw(n)}}}}}var cg,ns,fo,Ms,Ef,lv,ug,lg,_v,dv,Wu,_g,Qu,Pt,dg,av,fv,O7,b7,cv,pa=Oe(()=>{Dh();cg=x(ff()),ns=require("msgpackr"),fo=require("cbor-x"),Ms=require("zlib"),Ef=require("stream");Xt();lv=require("../../index"),ug=x(Z()),lg=x(U()),_v=x(require("yaml")),dv=ug.default.get(lg.CONFIG_PARAMS.SERIALIZATION_BIGINT)!==!1,Wu=dv?Li:JSON.stringify,_g=dv?Ch:JSON.parse,Qu={useRecords:!1,useToJSON:!0},Pt=new Map,dg=Pt;Xe.contentTypes=dg;(0,lv._assignPackageExport)("contentTypes",dg);Pt.set("application/json",{serializeStream:mc,serialize:Wu,deserialize:_g,q:.8});av=new fo.Encoder(Qu);Pt.set("application/cbor",{serializeStream(e){return e[Symbol.asyncIterator]&&(e[Symbol.iterator]=null),new fo.EncoderStream(Qu).end(e)},serialize:av.encode,deserialize:av.decode,q:1});Pt.set("application/x-msgpack",{serializeStream(e){return(e?.[Symbol.iterator]||e?.[Symbol.asyncIterator])&&!Array.isArray(e)?Ef.Readable.from((0,ns.encodeIter)(e,Qu)):(0,ns.pack)(e)},serialize:ns.pack,deserialize:ns.unpack,q:.9});Pt.set("text/csv",{serializeStream(e,t){return t.headers.set("Content-Disposition",'attachment; filename="data.csv"'),(0,cg.toCsvStream)(e,e?.getColumns?.())},q:.1});Pt.set("text/plain",{serialize(e){return e.toString()},deserialize(e){return e.toString()},q:.01});Pt.set("text/yaml",{serialize(e){return _v.stringify(e,{aliasDuplicateObjects:!1})},q:.7});Pt.set("text/event-stream",{serializeStream:function(e){return Ef.Readable.from(N7(e,this.serialize))},serialize:function(e){if(e.acknowledge&&e.acknowledge(),typeof e=="object"&&"value"in e&&e.timestamp&&(e={data:e.value,event:e.type,id:e.timestamp}),e.data||e.event){let t="";if(e.event&&(t+="event: "+e.event+`
|
|
18
|
+
`),e.data){let r=e.data;typeof r=="object"&&(r=Wu(r)),t+="data: "+r+`
|
|
19
19
|
`}return e.id&&(t+="id: "+e.id+`
|
|
20
20
|
`),e.retry&&(t+="retry: "+e.retry+`
|
|
21
21
|
`),t+`
|
|
22
|
-
`}else return typeof e=="object"?`data: ${
|
|
22
|
+
`}else return typeof e=="object"?`data: ${Wu(e)}
|
|
23
23
|
|
|
24
24
|
`:`data: ${e}
|
|
25
25
|
|
|
26
|
-
`},compressible:!1,q:.8});Ut.set("application/x-www-form-urlencoded",{deserialize(e){let t={};for(let[r,n]of new URLSearchParams(e))if(t.hasOwnProperty(r)){let s=t[r];Array.isArray(s)?s.push(n):t.key=[s,n]}else t[r]=n},serialize(e){let t=new URLSearchParams;for(let r in e)t.set(r,e);return t.toString()}});lv={type:"application/json",serializeStream:fc,serialize:$u,deserialize:T7,q:.8};Ut.set("*/*",lv);Ut.set("",lv);a(T7,"tryJSONParse");a(fg,"registerContentHandlers");g7=require("fastify-plugin"),R7=g7(function(e,t,r){e.addHook("preSerialization",async(n,s)=>{if(s.raw.getHeader("content-type"))return;let{serializer:o,type:c}=hf(n.raw);s.type(c),s.serializer(function(u){return(o.serializeStream||o.serialize)(u,{headers:{set:(_,l)=>{s.header(_,l)}}})})}),r()},{name:"content-type-negotiation"});a(hf,"findBestSerializer");iv=ug.default.get(lg.CONFIG_PARAMS.HTTP_COMPRESSIONTHRESHOLD);a(mf,"serialize");a(di,"serializeMessage");a(A7,"streamToBuffer");a(_o,"getDeserializer");a(ov,"deserializerUnknownType");a(O7,"transformIterable")});function pg(e,t,r,n,s,i,o,c){let u=e[0];if(t==="or"){let d=_(u);for(let E=1;E<e.length;E++){let h=e[E],p=_(h);d=d.concat(p)}let f=new Set;return d.filter(E=>{let h=E.key??E;return f.has(h)?!1:(f.add(h),!0)})}else{let d=_(u),f=l(e.slice(1),!0,u.estimated_count);return f.length>0?o(d,f):d}function _(d){return d.conditions?pg(d.conditions,d.operator,r,n,s,i,o,c):ba(d,n,d.descending||s.reverse===!0,r,s.allowFullScan,c)}a(_,"executeCondition");function l(d,f,E){return d.map((h,p)=>{if(h.conditions){let A=h.operator==="or",b=l(h.conditions,!A,E);return A?H=>b.some(q=>q(H)):H=>b.every(q=>q(H))}let S=(h.attribute||h[0])===r.primaryKey,T=Tg(h,r,i,c,S,E);return f&&p<d.length-1&&E&&(E=M7(r.primaryStore,h.estimated_count,E)),T}).filter(Boolean)}a(l,"mapConditionsToFilters")}function ba(e,t,r,n,s,i){let o=e[0]??e.attribute,c=e[1]??e.value,u=e.comparator;if(Array.isArray(o)){let T=o[0],A=Ms(n.attributes,T);if(A.relationship){if(o.length<2)throw new Ls.ClientError("Can not directly query a relational attribute, must query an attribute within the target table");let b=A.definition?.tableClass||A.elements?.definition?.tableClass,H=new Map,q=ba({attribute:o.length>2?o.slice(1):o[1],value:c,comparator:u},t,r,b,s,H);if(A.relationship.to){i[o[0]]=H;let v=!!Ms(b.attributes,A.relationship.to)?.elements;q=I7(q,A,b.primaryStore,v,H)}if(A.relationship.from){let v=a(P=>ba({attribute:A.relationship.from,value:P},t,r,n,s,H),"searchEntry");A.elements?(i[o[0]]=H,q=C7(q,A,b.primaryStore,H,v)):q=q.flatMap(v)}return q}else if(o.length===1)o=o[0];else throw new Ls.ClientError("Unable to query by attribute "+JSON.stringify(o))}let _,l,d,f;c instanceof Date&&(c=c.getTime());let E;switch(Sg[u]||u){case"lt":_=!0,l=c;break;case"le":_=!0,l=c,d=!0;break;case"gt":_=c,f=!0;break;case"ge":_=c;break;case"prefix":Array.isArray(c)?c[c.length-1]!=null&&(c=c.concat(null)):c=[c,null],_=c,l=c.slice(0),l[l.length-1]=rs.MAXIMUM_KEY;break;case"starts_with":_=c.toString(),l=c+"\uFFFF";break;case"between":_=c[0],_ instanceof Date&&(_=_.getTime()),l=c[1],l instanceof Date&&(l=l.getTime()),d=!0;break;case"equals":case void 0:_=c,l=c,d=!0;break;case"ne":if(c===null){_=c,f=!0;break}case"contains":case"ends_with":E=!0;break;default:throw new Ls.ClientError(`Unknown query comparator "${u}"`)}if(r){let T=_;_=l,l=T,T=!f,f=!d,d=T}let h=o===n.primaryKey||o==null,p=h?n.primaryStore:n.indices[o];if(!p||p.isIndexing||E||c===null&&!p.indexNulls){if(!s)throw new Ls.ClientError(`"${o}" is not indexed${c===null&&!p.indexNulls?" for nulls, index needs to be rebuilt to search for nulls":p?.isIndexing?" yet":""}, can not search for this attribute`,404);let T=Tg(e);if(!T)throw new Ls.ClientError(`Unknown search operator ${e.comparator}`);return n.primaryStore.getRange({start:!0,transaction:t,reverse:r}).map(({key:A,value:b})=>new Promise((H,q)=>setImmediate(()=>{try{H(b&&T(b)?A:Eg.SKIP)}catch(v){q(v)}})))}let S={start:_,end:l,inclusiveEnd:d,exclusiveStart:f,values:!0,versions:h,transaction:t,reverse:r};if(h){let T=p.getRange(S).map(A=>A.value==null?Eg.SKIP:A);return T.hasEntries=!0,T}else return p.getRange(S).map(({value:T})=>T)}function Ms(e,t){if(Array.isArray(t))if(t.length>1){let r=Ms(e,t[0]),n=(r?.definition?.tableClass||r?.elements.definition?.tableClass)?.attributes;return n?Ms(n,t.slice(1)):void 0}else t=t.toString();else typeof t!="string"&&(t=t.toString());return e.find(r=>r.name===t)}function I7(e,t,r,n,s){return new e.constructor({[Symbol.iterator](){let i;s.hasMappings=!0;let o;return{next(){if(!i){let u=t.relationship.to;return(async()=>{let _=a((d,f)=>{let E=d;Array.isArray(d)&&(E=Dn(d),o=!0);let h=s.get(E);h?h.push(f):s.set(E,h=[f]),d!==E&&(h.key=d)},"add_entry"),l=0;for await(let d of e){let f=d.value??r.get(d.key??d),E=f?.[u];if(E!=null&&!s.filters?.some(h=>!h(f))){if(n)for(let h=0;h<E.length;h++)_(E[h],d);else _(E,d);l++>100&&(await new Promise(setImmediate),l=0)}}return i=(o?s:s.keys())[Symbol.iterator](),this.next()})()}let c=i.next();return c.done?c:{value:o?c.value[1].key||c.value[0]:c.value}}}}})}function C7(e,t,r,n,s){return new e.constructor({[Symbol.iterator](){let i,o,c=new Set;return{next(){let u;if(o)for(;u=o.next(),!u.done;){let _=Dn(u.value);if(!c.has(_))return c.add(_),u}if(!i)return(async()=>{let _=new Map;n.fromRecord=d=>d[t.relationship.from]?.filter?.(f=>_.has(Dn(f)));let l=0;for await(let d of e){if(n.filters){let f=r.get(d);if(n.filters.some(E=>!E(f)))continue}_.set(Dn(d),d),l++>100&&(await new Promise(setImmediate),l=0)}return i=_.values()[Symbol.iterator](),this.next()})();do{let _=i.next();return _.done?_:(o=s(_.value)[Symbol.iterator](),this.next())}while(!0)},return(){return o?.return?.()},throw(){return o?.throw?.()}}}})}function Tg(e,t,r,n,s,i){let o=e.comparator,c=e[0]??e.attribute,u=e[1]??e.value;if(Array.isArray(c)){if(c.length===0)return()=>!0;if(c.length===1)c=c[0];else if(c.length>1){let l=c[0],d=Ms(t.attributes,l),f=d.definition?.tableClass||d.elements.definition?.tableClass,E=n?.[l],h=Tg({attribute:c.length>2?c.slice(1):c[1],value:u,comparator:o},f,r,E?.[l]?.joined,c[1]===f.primaryKey,i);if(!h)return;if(E){E.filters||(E.filters=[]),E.filters.push(h);return}let p=t.propertyResolvers?.[l],S,T=a((A,b)=>{let H,q;if(p){if(p.from&&h.idFilter){if(!S)if(h.idFilter.idSet?.size===1){for(let P of h.idFilter.idSet)e={attribute:p.from,value:P};S=_(p.from,h.idFilter,!0)}else S=_(p.from,h.idFilter,!1);let v=S(A);return S.idFilter&&(T.idFilter=S.idFilter),v}q=p(A,r,b),H=q?.value}else H=A[l];return H?Array.isArray(H)?H.some(h):h(H,q):!1},"recordFilter");return T}}switch(u instanceof Date&&(u=u.getTime()),Sg[o]||o){case hg.SEARCH_TYPES.EQUALS:case void 0:return _(c,l=>l===u,!0);case"contains":return _(c,l=>l?.toString().includes(u));case"ends_with":return _(c,l=>l?.toString().endsWith(u));case"starts_with":return _(c,l=>typeof l=="string"&&l.startsWith(u),!0);case"prefix":return Array.isArray(u)?u[u.length-1]==null&&(u=u.slice(0,-1)):u=[u],_(c,l=>{if(!Array.isArray(l))return!1;for(let d=0,f=u.length;d<f;d++)if(l[d]!==u[d])return!1;return!0},!0);case"between":return u[0]instanceof Date&&(u[0]=u[0].getTime()),u[1]instanceof Date&&(u[1]=u[1].getTime()),_(c,l=>(0,rs.compareKeys)(l,u[0])>=0&&(0,rs.compareKeys)(l,u[1])<=0,!0);case"gt":return _(c,l=>(0,rs.compareKeys)(l,u)>0);case"ge":return _(c,l=>(0,rs.compareKeys)(l,u)>=0);case"lt":return _(c,l=>(0,rs.compareKeys)(l,u)<0);case"le":return _(c,l=>(0,rs.compareKeys)(l,u)<=0);case"ne":return _(c,l=>(0,rs.compareKeys)(l,u)!==0);default:throw new Ls.ClientError(`Unknown query comparator "${o}"`)}function _(l,d,f){let E;f=f&&!s&&t?.indices[l]&&i>3,f&&(e.estimated_count==null&&Sf(t)(e),E=e.estimated_count>>4,(isNaN(E)||E>=i)&&(f=!1));let h=0,p=3;function S(T){let A=T[l],b;if(typeof A!="object"||!A?b=d(A):Array.isArray(A)?b=A.some(d):A instanceof Date&&(b=d(A.getTime())),f&&(p++,!b&&!S.idFilter&&++h/p*(i-p)>E)){let H=ba(e,r.transaction.getReadTxn(),!1,t).map(Dn),q=new Set(H);S.idFilter=v=>q.has(Dn(v)),S.idFilter.idSet=q}return b}return a(S,"recordFilter"),s&&(S.idFilter=d),S}a(_,"attributeComparator")}function Sf(e){function t(r){if(r.estimated_count===void 0){if(r.conditions){let s;if(r.operator==="or"){s=0;for(let i of r.conditions)t(i),s+=i.estimated_count}else{s=1/0;for(let i of r.conditions)t(i),s=isFinite(s)?s*i.estimated_count/hi(e.primaryStore):i.estimated_count}return r.estimated_count=s,r.estimated_count}let n=r.comparator||r.search_type;if(n=Sg[n]||n,n===hg.SEARCH_TYPES.EQUALS||!n){let s=r[0]??r.attribute;if(s==null||s===e.primaryKey)r.estimated_count=1;else if(Array.isArray(s)&&s.length>1){let i=Ms(e.attributes,s[0]),o=i.definition?.tableClass||i.elements.definition?.tableClass,c=Sf(o)({value:r.value,attribute:s.length>2?s.slice(1):s[1],comparator:"equals"});r.estimated_count=c*hi(e.indices[i.relationship.from]||e.primaryStore)/(hi(o.primaryStore)||1)}else{let i=e.indices[s];r.estimated_count=i?i.getValuesCount(r[1]??r.value):1/0}}else if(n==="contains"||n==="ends_with"||n==="ne"){let s=r[0]??r.attribute,i=e.indices[s];r.value===null&&n==="ne"?r.estimated_count=hi(e.primaryStore)-(i?i.getValuesCount(null):0):r.estimated_count=1/0}else n==="starts_with"||n==="prefix"?r.estimated_count=y7*hi(e.primaryStore)+1:n==="between"?r.estimated_count=N7*hi(e.primaryStore)+1:r.estimated_count=b7*hi(e.primaryStore)+1;typeof r.descending=="boolean"&&(r.estimated_count/=4)}return r.estimated_count}return a(t,"estimateConditionForTable"),t}function Tf(e){if(e)if(mi=e,Aa.lastIndex=0,D7.test(e))try{let t=Ku(new Oa,"");if(mr!==mi.length)throw new SyntaxError("Unable to parse query, unexpected end of query");return t}catch(t){throw t.statusCode=400,t.message=`Unable to parse query, ${t.message} at position ${mr} in '${mi}'`,t}else{let t=new URLSearchParams(e);return t.conditions=t,t}}function Ku(e,t){let r=Aa,n,s,i,o,c,u=decodeURIComponent,_;for(;n=r.exec(mi);){mr=r.lastIndex;let[,l,d]=n;if(o){if(l)throw new SyntaxError(`expected operator, but encountered '${l}'`);o=!1,c=!1}else c=!0;let f;switch(d){case"=":if(s){if(l.length<=2)i=l;else throw new SyntaxError(`invalid FIQL operator ${l}`);u=dv}else{if(u=decodeURIComponent,i="equals",!l)throw new SyntaxError("attribute must be specified before equality comparator");s=Wu(l)}break;case"==":case"!=":case"<":case"<=":case">":case">=":case"===":case"!==":if(i=w7[d],u=mg[i]?dv:decodeURIComponent,!l)throw new SyntaxError(`attribute must be specified before comparator ${d}`);s=Wu(l);break;case"|":case"&":case"":case void 0:if(s==null){if(s===void 0)throw t?new SyntaxError(`expected '${t}', but encountered ${d[0]?"'"+d[0]+"'":"end of string"}}`):new SyntaxError(`no comparison specified before ${d?"'"+d+"'":"end of string"}`)}else{if(!e.conditions)throw new SyntaxError("conditions/comparisons are not allowed in a property list");let h={comparator:i,attribute:s,value:u(l)};i==="eq"&&fv(h,l),pf(e,_),e.conditions.push(h)}d==="&"&&(_="and"),d==="|"&&(_="or"),s=void 0;break;case",":if(e.conditions)throw new SyntaxError("conditions/comparisons are not allowed in a property list");e.push(Wu(l)),s=void 0;break;case"(":Aa.lastIndex=mr;let E=Ku(l?[]:new Oa,")");switch(l){case"":pf(e,_),e.conditions.push(E);break;case"limit":switch(E.length){case 1:e.limit=+E[0];break;case 2:e.offset=+E[0],e.limit=E[1]-e.offset;break;default:throw new SyntaxError("limit must have 1 or 2 arguments")}break;case"select":Array.isArray(E[0])&&E.length===1&&!E[0].name?(e.select=E[0],e.select.asArray=!0):E.length===1?e.select=E[0]:E.length===2&&E[1]===""?e.select=E.slice(0,1):e.select=E;break;case"group-by":throw new SyntaxError("group by is not implemented yet");case"sort":e.sort=Ev(E);break;default:throw new SyntaxError(`unknown query function call ${l}`)}mi[mr]===","?r.lastIndex=++mr:o=!0,s=null;break;case"{":if(e.conditions)throw new SyntaxError("property sets are not allowed in a queries");if(!l)throw new SyntaxError("property sets must have a defined parent property name");Aa.lastIndex=mr,f=Ku([],"}"),f.name=l,e.push(f),mi[mr]===","?r.lastIndex=++mr:o=!0;break;case"[":Aa.lastIndex=mr,l?(f=Ku(new Oa,"]"),f.name=l):f=Ku(e.conditions?new Oa:[],"]"),e.conditions?(pf(e,_),e.conditions.push(f),s=null):e.push(f),mi[mr]===","?r.lastIndex=++mr:o=!0;break;case")":case"]":case"}":if(t===d[0]){if(e.conditions){if(s){let h={comparator:i||"equals",attribute:s,value:u(l)};i==="eq"&&fv(h,l),pf(e,_),e.conditions.push(h)}else if(l)throw new SyntaxError("no attribute or comparison specified")}else(l||e.length>0&&c)&&e.push(Wu(l));return e}else throw t?new SyntaxError(`expected '${t}', but encountered '${d[0]}'`):new SyntaxError(`unexpected token '${d[0]}'`);default:throw new SyntaxError(`unexpected operator '${d}'`)}if(t!==")"&&(r=s?L7:Aa,r.lastIndex=mr),mr===mi.length)return e}if(t)throw new SyntaxError(`expected '${t}', but encountered end of string`)}function pf(e,t){if(e.conditions.length>0)if(e.operator){if(e.operator!==t)throw new SyntaxError("Can not mix operators within a condition grouping")}else e.operator=t}function Wu(e){return e.indexOf(".")>-1?e.split(".").map(Wu):decodeURIComponent(e)}function dv(e){if(e==="null")return null;if(e.indexOf(":")>-1){let[t,r]=e.split(":");if(t==="number")return+r;if(t==="boolean")return r==="true";if(t==="date")return new Date(decodeURIComponent(r));if(t==="string")return decodeURIComponent(r);throw new Ls.ClientError(`Unknown type ${t}`)}return decodeURIComponent(e)}function fv(e,t){if(t.indexOf("*")>-1)if(t.endsWith("*"))e.comparator="starts_with",e.value=decodeURIComponent(t.slice(0,-1));else throw new Ls.ClientError("wildcard can only be used at the end of a string")}function Ev(e){let t=hv(e[0]);return e.length>1&&(t.next=Ev(e.slice(1))),t}function hv(e){if(Array.isArray(e)){let t=hv(e[0]);return e[0]=t.attribute,t.attribute=e,t}if(typeof e=="string")switch(e[0]){case"-":return{attribute:e.slice(1),descending:!0};case"+":return{attribute:e.slice(1),descending:!1};default:return{attribute:e,descending:!1}}throw new SyntaxError(`Unknown sort type ${e}`)}function Dn(e){return Array.isArray(e)?e.join("\0"):e}function hi(e){let t=Date.now();return(e.estimatedEntryCountExpires||0)<t&&(e.estimatedEntryCount=e.getStats().entryCount,e.estimatedEntryCountExpires=t+1e4),e.estimatedEntryCount}function M7(e,t,r){return t*r/hi(e)}var Ls,hg,rs,Eg,b7,N7,y7,w7,mg,Sg,D7,Aa,L7,mr,mi,Oa,gf=Oe(()=>{Ls=B(ee()),hg=B(lt()),rs=require("ordered-binary"),Eg=require("lmdb"),b7=.3,N7=.1,y7=.05,w7={"<":"lt","<=":"le",">":"gt",">=":"ge","!=":"ne","==":"eq","===":"equals","!==":"not_equal"},mg={lt:!0,le:!0,gt:!0,ge:!0,ne:!0,eq:!0};a(pg,"executeConditions");a(ba,"searchByIndex");a(Ms,"findAttribute");a(I7,"joinTo");a(C7,"joinFrom");Sg={eq:"equals",greater_than:"gt",greaterThan:"gt",greater_than_equal:"ge",greaterThanEqual:"ge",less_than:"lt",lessThan:"lt",less_than_equal:"le",lessThanEqual:"le",not_equal:"ne",notEqual:"ne",equal:"equals",sw:"starts_with",startsWith:"starts_with",ew:"ends_with",endsWith:"ends_with",ct:"contains",">":"gt",">=":"ge","<":"lt","<=":"le","...":"between"};a(Tg,"filterByType");a(Sf,"estimateCondition");D7=/[()[\]|!<>.]|(=\w*=)/,Aa=/([^?&|=<>!([{}\]),]*)([([{}\])|,&]|[=<>!]*)/g,L7=/([^&|=[\]{}]+)([[\]{}]|[&|=]*)/g;a(Tf,"parseQuery");a(Ku,"parseBlock");a(pf,"assignOperator");a(Wu,"decodeProperty");a(dv,"typedDecoding");a(fv,"wildcardDecoding");a(Ev,"toSortObject");a(hv,"toSortEntry");Oa=class{static{a(this,"Query")}constructor(){this.conditions=[]}[Symbol.iterator](){return this.conditions[Symbol.iterator]()}get(t){for(let r=0;r<this.conditions.length;r++){let n=this.conditions[r];if(n.attribute===t)return n.value}}};a(Dn,"flattenKey");a(hi,"estimatedEntryCount");a(M7,"intersectionEstimate")});function Rv(e){let t={openapi:U7,info:{title:"HarperDB HTTP REST interface",version:(0,gv.version)()},paths:{},components:{schemas:{},securitySchemes:{basicAuth:{type:"http",scheme:"basic"},bearerAuth:{type:"http",scheme:"bearer",bearerFormat:"JWT"}}}},r=[{basicAuth:[],bearerAuth:[]}];for(let[,n]of e){if(!n.path)continue;let{path:s}=n,{attributes:i,primaryKey:o,prototype:c}=n.Resource;if(o=o??"id",!o)continue;let u={},_=[];if(i)for(let{type:A,name:b}of i)u[b]=new Tv(mv[A],A),_.push(new Ag(b,"query",u[b]));let l=Object.keys(u),d=new Ag(o,"path",new Tv(mv.ID,"ID"));d.required=!0,d.description="primary key of record";let f=new Ag("property","path",{enum:l});f.required=!0,t.components.schemas[s]=new B7(u);let E=c.post!==Resource.prototype.post||c.update,h=c.hasOwnProperty("put"),p=c.hasOwnProperty("get"),S=c.hasOwnProperty("delete"),T="/"+s+"/";E&&(t.paths[T]={},t.paths[T].post=new P7(s,r,"create a new record auto-assigning a primary key")),p&&(t.paths[T]||(t.paths[T]={}),t.paths[T].get=new gg(_,r,{200:new Rg({$ref:Rf+s})},"search for records by the specified property name and value")),S&&(t.paths[T]||(t.paths[T]={}),t.paths[T].delete=new Sv(_,r,"delete all the records that match the provided query",{204:new pv})),T="/"+s+"/{"+o+"}",p&&(t.paths[T]={},t.paths[T].get=new gg([d],r,{200:new Rg({$ref:Rf+s})},"retrieve a record by its primary key")),h&&(t.paths[T]||(t.paths[T]={}),t.paths[T].put=new v7([d],r,s,"create or update the record with the URL path that maps to the record's primary key")),S&&(t.paths[T]||(t.paths[T]={}),t.paths[T].delete=new Sv([d],r,"delete a record with the given primary key",{204:new pv})),p&&f.schema.enum.length>0&&(T="/"+s+"/{"+o+"}.{property}",t.paths[T]={},t.paths[T].get=new gg([d,f],r,{200:new Rg({enum:l})},"used to retrieve the specified property of the specified record"))}return t}function P7(e,t,r){this.description=r,this.requestBody={content:{"application/json":{schema:{$ref:Rf+e}}}},this.security=t,this.responses={200:{description:Og,headers:{Location:{description:"primary key of new record",schema:{type:"string",format:"ID"}}},content:{"application/json":{schema:{type:"string",format:"ID"}}}}}}function gg(e,t,r,n){this.description=n,this.parameters=e,this.security=t,this.responses=r}function Rg(e){this.description=Og,this.content={"application/json":{schema:e}}}function pv(){this.description="successfully processed request, no content returned to client"}function v7(e,t,r,n){this.description=n,this.parameters=e,this.security=t,this.requestBody={content:{"application/json":{schema:{$ref:Rf+r}}}},this.responses={200:{description:Og}}}function Sv(e,t,r,n){this.description=r,this.parameters=e,this.security=t,this.responses=n}function B7(e){this.type="object",this.properties=e}function Tv(e,t){this.type=e,this.format=t}function Ag(e,t,r){this.name=e,this.in=t,this.schema=r}var gv,U7,mv,Rf,Og,Av=Oe(()=>{gv=B(Sd()),U7="3.0.3",mv={ID:"string",Int:"integer",Float:"number",Long:"integer",String:"string",Boolean:"boolean",Date:"string",Bytes:"string",Any:"string",BigInt:"integer"},Rf="#/components/schemas/",Og="successful operation";a(Rv,"generateJsonApi");a(P7,"Post");a(gg,"Get");a(Rg,"Response200");a(pv,"Response204");a(v7,"Put");a(Sv,"Delete");a(B7,"ResourceSchema");a(Tv,"Type");a(Ag,"Parameter")});var Of={};Ve(Of,{start:()=>q7});async function x7(e,t){let r=e.headers.asObject,n=r.accept==="text/event-stream"?"CONNECT":e.method;e.search&&Tf(e);let s=new _i;try{e.responseHeaders=s;let i=e.url.slice(1),o,c;if(i!==Ov){let h=Af.getMatch(i);if(!h)return t(e);e.handlerPath=h.path,o={url:h.relativeURL,async:!0},c=h.Resource}let u=r["cache-control"];if(u){u=u.toLowerCase();let h=u.match(/max-age=(\d+)/)?.[1];h&&(e.expiresAt=h*1e3+Date.now()),u.includes("only-if-cached")&&(e.onlyIfCached=!0),u.includes("no-cache")&&(e.noCache=!0),u.includes("no-store")&&(e.noCacheStore=!0),u.includes("stale-if-error")&&(e.staleIfError=!0),u.includes("must-revalidate")&&(e.mustRevalidate=!0)}let _=await We(e,()=>{if(n==="POST"||n==="PUT"||n==="PATCH"||n==="QUERY")try{e.data=_o(r["content-type"],!0)(e.body)}catch(h){throw new zu.ClientError(h,400)}if(e.authorize=!0,i===Ov&&n==="GET")return Rv(Af);switch(n){case"GET":case"HEAD":return c.get(o,e);case"POST":return c.post(o,e.data,e);case"PUT":return c.put(o,e.data,e);case"DELETE":return c.delete(o,e);case"PATCH":return c.patch(o,e.data,e);case"OPTIONS":s.setIfNone("Allow","GET, HEAD, POST, PUT, DELETE, PATCH, OPTIONS, TRACE, QUERY, COPY, MOVE");return;case"CONNECT":return c.connect(o,null,e);case"TRACE":return"HarperDB is the terminating server";case"QUERY":return c.query(o,e.data,e);case"COPY":return c.copy(o,r.destination,e);case"MOVE":return c.move(o,r.destination,e);case"BREW":throw new zu.ClientError("HarperDB is short and stout and can't brew coffee",418);default:throw new zu.ServerError(`Method ${n} is not recognized`,501)}}),l=200,d;if(_==null)l=n==="GET"||n==="HEAD"?404:204,bg.lastModified&&e.lastModified&&s.setIfNone("Last-Modified",new Date(e.lastModified).toUTCString());else if(d=e.lastModified){H7[0]=d;let h=String.fromCharCode(34,(Gt[0]&63)+62,(Gt[0]>>6)+(Gt[1]<<2&63)+62,(Gt[1]>>4)+(Gt[2]<<4&63)+62,(Gt[2]>>2)+62,(Gt[3]&63)+62,(Gt[3]>>6)+(Gt[4]<<2&63)+62,(Gt[4]>>4)+(Gt[5]<<4&63)+62,(Gt[5]>>2)+62,(Gt[6]&63)+62,(Gt[6]>>6)+(Gt[7]<<2&63)+62,34),p=r["if-none-match"];p&&h==p?(_?.onDone&&_.onDone(),l=304,_=void 0):s.setIfNone("ETag",h),bg.lastModified&&s.setIfNone("Last-Modified",new Date(d).toUTCString())}e.createdResource&&(l=201),e.newLocation&&s.setIfNone("Location",e.newLocation);let f={status:l,headers:s,body:void 0},E=_?.wasLoadedFromSource?.();return E!==void 0&&(f.wasCacheMiss=E,!E&&d&&s.setIfNone("Age",Math.round((Date.now()-(e.lastRefreshed||d))/1e3))),_!==void 0&&(f.body=mf(_,e,f),n==="HEAD"&&(f.body=void 0)),f}catch(i){i.statusCode?i.statusCode===500?fo.warn(i):fo.info(i):fo.error(i),i.statusCode===405&&(i.method&&(i.message+=` to handle HTTP method ${i.method.toUpperCase()||""}`),i.allow&&(i.allow.push("trace","head","options"),s.setIfNone("Allow",i.allow.map(c=>c.toUpperCase()).join(", "))));let o={status:i.statusCode||500,headers:s,body:void 0};return o.body=mf(i.contentType?i:i.toString(),e,o),o}}function q7(e){bg=e,!bv&&(bv=!0,Af=e.resources,e.server.http(async(t,r)=>{if(!t.isWebSocket)return x7(t,r)}),e.server.ws(async(t,r,n)=>{Qu++;let s=new Tn;Nv||(Nv=!0,Xc(l=>{Qu>0&&l.push({metric:"ws-connections",connections:Qu,byThread:!0})}));let i;t.on("error",l=>{i=!0,fo.warn(l)});let o;t.on("message",a(function(d){o||(o=_o(r.headers.asObject["content-type"]));let f=o(d);s.push(f)},"message"));let c;t.on("close",()=>{Qu--,en(!i,"connection","ws","disconnect"),s.emit("close"),c&&c.return()}),await n;let u=r.url.slice(1),_=Af.getMatch(u);if(en(!!_,"connection","ws","connect"),!_)t.send(di(`No resource was found to handle ${r.pathname}`,r));else{r.handlerPath=_.path,Br(h=>({count:h.count,total:Qu}),"connections",r.handlerPath,"connect","ws");let l={url:_.relativeURL,async:!0},d=_.Resource;c=(await We(r,()=>d.connect(l,s,r)))[Symbol.asyncIterator]();let E;for(;!(E=await c.next()).done;){let h=di(E.value,r);t.send(h),Br(h.length,"bytes-sent",r.handlerPath,"message","ws")}}t.close()}))}var fo,zu,Gt,H7,bg,Ov,bv,Af,Nv,Qu,yv=Oe(()=>{ha();Rs();fo=B(Y()),zu=B(ee());gf();_c();Wi();$d();Av();Gt=new Uint8Array(8),H7=new Float64Array(Gt.buffer,0,1),bg={},Ov="openapi";a(x7,"http");Qu=0;a(q7,"start")});var Ng=g((CEe,wv)=>{var{recordAction:bf,recordActionBinary:F7}=(Rs(),te(Zc)),G7=require("fastify-plugin"),k7=200;wv.exports=G7(function(e,t,r){e.addHook("onResponse",async(n,s)=>{s.getResponseTime()}),e.addHook("onSend",async(n,s,i)=>{let o=s.getResponseTime(),c=performance.now(),u=s.request.routeOptions,_,l,d;u.config?.isOperation?(_=n.body?.operation,l="operation"):(_=u.url,l="fastify-route",d=u.method),bf(o,"duration",_,d,l),F7(s.raw.statusCode<400,"success",_,d,l);let f=k7;i?.pipe?(i.on("data",h=>{f+=h.length}),i.on("end",()=>{bf(performance.now()-c,"transfer",_,d,l),bf(f,"bytes-sent",_,d,l)})):(f+=i?.length||0,bf(f,"bytes-sent",_,d,l));let E=o.toFixed(3);s.header("Server-Timing",`db;dur=${E}`)}),r()},{name:"hdb-request-time"})});var Cg=g((DEe,Mv)=>{var Cf=require("clone"),Df=je(),V7=J(),wf=M(),$7=Y(),Nf=require("fs"),yg=require("joi"),{string:If}=yg.types(),{hdb_errors:Y7,handleHDBError:Ju}=ee(),{HDB_ERROR_MSGS:K7,HTTP_STATUS_CODES:yf}=Y7,{common_validators:Na}=kn(),Iv=1e9,Cv=" is required",W7=["insert","update","upsert"],wg={database:{presence:!1,format:Na.schema_format,length:Na.schema_length},schema:{presence:!1,format:Na.schema_format,length:Na.schema_length},table:{presence:!0,format:Na.schema_format,length:Na.schema_length},action:{inclusion:{within:W7,message:"is required and must be either insert, update, or upsert"}},file_path:{},csv_url:{url:{allowLocal:!0}},data:{},passthrough_headers:{}},Q7={schema:If.required(),table:If.required(),action:If.valid("insert","update","upsert")},{AWS_ACCESS_KEY:z7,AWS_SECRET:J7,AWS_BUCKET:j7,AWS_FILE_KEY:X7,REGION:Z7}=wf.S3_BUCKET_AUTH_KEYS,eee={s3:{presence:!0},[`s3.${z7}`]:{presence:!0,type:"String"},[`s3.${J7}`]:{presence:!0,type:"String"},[`s3.${j7}`]:{presence:!0,type:"String"},[`s3.${X7}`]:{presence:!0,type:"String",hasValidFileExt:[".csv",".json"]},[`s3.${Z7}`]:{presence:!0,type:"String"}},Dv=Cf(wg);Dv.data.presence={message:Cv};var Lv=Cf(wg);Lv.file_path.presence={message:Cv};var tee=Object.assign(Cf(wg),eee),Ig=Cf(Q7);Ig.csv_url=If.uri().messages({"string.uri":"'csv_url' must be a valid url"}).required();Ig.passthrough_headers=yg.object();function ree(e){let t=Df.validateObject(e,Dv);return Lf(e,t)}a(ree,"dataObject");function nee(e){let t=Df.validateBySchema(e,yg.object(Ig));return Lf(e,t)}a(nee,"urlObject");function see(e){let t=Df.validateObject(e,Lv);return Lf(e,t)}a(see,"fileObject");function iee(e){let t=Df.validateObject(e,tee);return Lf(e,t)}a(iee,"s3FileObject");function Lf(e,t){if(!t){let r=V7.checkGlobalSchemaTable(e.schema,e.table);if(r)return Ju(new Error,r,yf.BAD_REQUEST);if(e.operation===wf.OPERATIONS_ENUM.CSV_FILE_LOAD){try{Nf.accessSync(e.file_path,Nf.constants.R_OK|Nf.constants.F_OK)}catch(n){return n.code===wf.NODE_ERROR_CODES.ENOENT?Ju(n,`No such file or directory ${n.path}`,yf.BAD_REQUEST):n.code===wf.NODE_ERROR_CODES.EACCES?Ju(n,`Permission denied ${n.path}`,yf.BAD_REQUEST):Ju(n)}try{let n=Nf.statSync(e.file_path).size;if(n>Iv)return Ju(new Error,K7.MAX_FILE_SIZE_ERR(n,Iv),yf.BAD_REQUEST)}catch(n){$7.error(n),console.error(n)}}}return t}a(Lf,"postValidateChecks");Mv.exports={dataObject:ree,urlObject:nee,fileObject:see,s3FileObject:iee}});var Dg=g((MEe,Uv)=>{"use strict";var ju=Y(),Mf=M();async function oee(e,t,r,n=void 0){if(!e||typeof e!="function")throw new Error("Invalid function parameter");let s;try{return s=await e(t),r&&await r(t,s,n),t.operation===Mf.OPERATIONS_ENUM.INSERT||t.operation===Mf.OPERATIONS_ENUM.UPDATE||t.operation===Mf.OPERATIONS_ENUM.UPSERT?(delete s.new_attributes,delete s.txn_time):t.operation===Mf.OPERATIONS_ENUM.DELETE&&delete s.txn_time,s}catch(i){throw i.message&&typeof i.message=="string"&&i.message.includes("already exists")?(ju.info(i.message),i):i.http_resp_msg?(ju.error(`Error calling operation: ${e.name}`),ju.error(i.http_resp_msg),i):(ju.error(`Error calling operation: ${e.name}`),ju.error(i),i)}}a(oee,"callOperationFunctionAsAwait");Uv.exports={callOperationFunctionAsAwait:oee}});var vv=g((PEe,Pv)=>{"use strict";var Lg=class{static{a(this,"BulkLoadFileObject")}constructor(t,r,n,s,i,o,c=null){this.op=t,this.action=r,this.schema=n,this.table=s,this.file_path=i,this.file_type=o,this.role_perms=c}},Mg=class{static{a(this,"BulkLoadDataObject")}constructor(t,r,n,s){this.action=t,this.schema=r,this.table=n,this.data=s}};Pv.exports={BulkLoadFileObject:Lg,BulkLoadDataObject:Mg}});var Hv=g((BEe,Bv)=>{"use strict";var Ug=class{static{a(this,"ClusteringOriginObject")}constructor(t,r,n){this.timestamp=t,this.user=r,this.node_name=n}};Bv.exports=Ug});var qg=g((kEe,e0)=>{"use strict";var Uf=Zr(),vf=Cg(),aee=require("needle"),Ln=M(),xEe=tt(),ya=J(),{handleHDBError:nt,hdb_errors:Kv}=ee(),{HTTP_STATUS_CODES:kt,HDB_ERROR_MSGS:bt,CHECK_LOGS_WRAPPER:ho}=Kv,wa=Y(),Pg=require("papaparse");ya.promisifyPapaParse();var Mn=require("fs-extra"),cee=require("path"),{chain:xv}=require("stream-chain"),qv=require("stream-json/streamers/StreamArray"),Fv=require("stream-json/utils/Batch"),Gv=require("stream-chain/utils/comp"),{finished:kv}=require("stream"),uee=Z(),Wv=Dg(),lee=ig(),{BulkLoadFileObject:Bg,BulkLoadDataObject:_ee}=vv(),Hg=zT(),{verifyBulkLoadAttributePerms:Qv}=lf(),qEe=Hv(),FEe=ft(),GEe=hs(),{databases:dee}=(be(),te(qe)),{coerceType:fee}=(Bf(),te(Fg)),Vv="No records parsed from csv file.",Eo=`${uee.get("HDB_ROOT")}/tmp`,{schema_regex:Eee}=kn(),$v=1024*1024*2,Yv=5e3,hee={"text/csv":!0,"application/octet-stream":!0,"text/plain":!0,"application/vnd.ms-excel":!0};e0.exports={csvDataLoad:mee,csvURLLoad:pee,csvFileLoad:See,importFromS3:Tee};async function mee(e,t){let r=vf.dataObject(e);if(r)throw nt(r,r.message,kt.BAD_REQUEST,void 0,void 0,!0);let n={};try{let s=jv(e.schema,e.table),i=Pg.parse(e.data,{header:!0,skipEmptyLines:!0,transform:vg.bind(null,s),dynamicTyping:!1}),o=new Hg;e.hdb_user&&e.hdb_user.role&&e.hdb_user.role.permission&&e.hdb_user.role.permission.super_user!==!0&&Qv(e.hdb_user.role.permission,this.job_operation_function.name,e.action,e.schema,e.table,i.meta.fields,o);let c=o.getPermsResponse();if(c)throw nt(new Error,c,kt.BAD_REQUEST,void 0,void 0,!0);let u=new _ee(e.action,e.schema,e.table,i.data);return n=await Wv.callOperationFunctionAsAwait(Xv,u,null),n.message===Vv?Vv:Zv(n.records,n.number_written)}catch(s){throw mo(s)}}a(mee,"csvDataLoad");async function pee(e){let t=vf.urlObject(e);if(t)throw nt(t,t.message,kt.BAD_REQUEST,void 0,void 0,!0);let r=`${Date.now()}.csv`,n=`${Eo}/${r}`;try{await gee(e,r)}catch(s){throw wa.error(bt.DOWNLOAD_FILE_ERR(r)+" - "+s),nt(s,ho(bt.DOWNLOAD_FILE_ERR(r)))}try{let s=new Bg(this.job_operation_function.name,e.action,e.schema,e.table,n,Ln.VALID_S3_FILE_TYPES.CSV,e.hdb_user.role.permission),i=await xg(s);return await Pf(n),i}catch(s){throw await Pf(n),mo(s)}}a(pee,"csvURLLoad");async function See(e){let t=vf.fileObject(e);if(t)throw nt(t,t.message,kt.BAD_REQUEST,void 0,void 0,!0);let r=new Bg(this.job_operation_function.name,e.action,e.schema,e.table,e.file_path,Ln.VALID_S3_FILE_TYPES.CSV,e.hdb_user.role.permission);try{return await xg(r)}catch(n){throw mo(n)}}a(See,"csvFileLoad");async function Tee(e){let t=vf.s3FileObject(e);if(t)throw nt(t,t.message,kt.BAD_REQUEST,void 0,void 0,!0);let r;try{let n=cee.extname(e.s3.key),s=`${Date.now()}${n}`;r=`${Eo}/${s}`;let i=new Bg(this.job_operation_function.name,e.action,e.schema,e.table,r,n,e.hdb_user.role.permission);await Ree(s,e);let o=await xg(i);return await Pf(r),o}catch(n){throw await Pf(r),mo(n)}}a(Tee,"importFromS3");async function gee(e,t){let r;try{let n=e.passthrough_headers?{headers:e.passthrough_headers}:void 0;r=await aee("get",e.csv_url,n)}catch(n){let s=`Error downloading CSV file from ${e.csv_url}, status code: ${n.statusCode}. Check the log for more information.`;throw nt(n,s,n.statusCode,Ln.LOG_LEVELS.ERROR,"Error downloading CSV file - "+n)}Oee(r,e.csv_url),await Aee(t,r.raw)}a(gee,"downloadCSVFile");async function Ree(e,t){try{let r=`${Eo}/${e}`;await Mn.mkdirp(Eo),await Mn.writeFile(`${Eo}/${e}`,"",{flag:"a+"});let n=await Mn.createWriteStream(r),s=await lee.getFileStreamFromS3(t);await new Promise((i,o)=>{s.on("error",function(c){o(c)}),s.pipe(n).on("error",function(c){o(c)}).on("close",function(){wa.info(`${t.s3.key} successfully downloaded to ${r}`),i()})})}catch(r){throw wa.error(bt.S3_DOWNLOAD_ERR+" - "+r),nt(r,ho(bt.S3_DOWNLOAD_ERR))}}a(Ree,"downloadFileFromS3");async function Aee(e,t){try{await Mn.mkdirp(Eo),await Mn.writeFile(`${Eo}/${e}`,t)}catch(r){throw wa.error(bt.WRITE_TEMP_FILE_ERR),nt(r,ho(bt.DEFAULT_BULK_LOAD_ERR))}}a(Aee,"writeFileToTempFolder");async function Pf(e){if(e)try{await Mn.access(e),await Mn.unlink(e)}catch{wa.warn(`could not delete temp csv file at ${e}, file does not exist`)}}a(Pf,"deleteTempFile");function Oee(e,t){if(e.statusCode!==Kv.HTTP_STATUS_CODES.OK)throw nt(new Error,`CSV Load failed from URL: ${t}, status code: ${e.statusCode}, message: ${e.statusMessage}`,kt.BAD_REQUEST);if(!hee[e.headers["content-type"]])throw nt(new Error,`CSV Load failed from URL: ${t}, unsupported content type: ${e.headers["content-type"]}`,kt.BAD_REQUEST);if(!e.raw)throw nt(new Error,`CSV Load failed from URL: ${t}, no csv found at url`,kt.BAD_REQUEST)}a(Oee,"validateURLResponse");async function xg(e){try{let t;switch(e.file_type){case Ln.VALID_S3_FILE_TYPES.CSV:t=await bee(e);break;case Ln.VALID_S3_FILE_TYPES.JSON:t=await Nee(e);break;default:throw nt(new Error,bt.DEFAULT_BULK_LOAD_ERR,kt.BAD_REQUEST,Ln.LOG_LEVELS.ERROR,bt.INVALID_FILE_EXT_ERR(e))}return Zv(t.records,t.number_written)}catch(t){throw mo(t)}}a(xg,"fileLoad");async function zv(e,t,r,n,s){let i=n.data?n.data:n;if(i.length===0)return;s&&s.pause();let o={operation:e.action,schema:e.schema,table:e.table,records:i};try{let{attributes:c}=await Uf.validation(o);e.role_perms&&e.role_perms.super_user!==!0&&Qv(e.role_perms,e.op,e.action,e.schema,e.table,c,t),s&&s.resume()}catch(c){let u=nt(c);r(u)}}a(zv,"validateChunk");async function Jv(e,t,r,n,s){let i=n.data?n.data:n;if(i.length===0)return;ya.autoCastJSONDeep(i),s&&s.pause();let o=n.meta?n.meta.fields:null;if(o)i.forEach(c=>{!ya.isEmpty(c)&&!ya.isEmpty(c.__parsed_extra)&&delete c.__parsed_extra});else{let c=new Set;i.forEach(u=>{Object.keys(u).forEach(_=>c.add(_))}),o=[...c]}try{let c={schema:e.schema,table:e.table,action:e.action,data:i},u=await Wv.callOperationFunctionAsAwait(Xv,c,null);t.records+=u.records,t.number_written+=u.number_written,s&&s.resume()}catch(c){let u=nt(c,ho(bt.INSERT_CSV_ERR),kt.INTERNAL_SERVER_ERROR,Ln.LOG_LEVELS.ERROR,bt.INSERT_CSV_ERR+" - "+c);r(u)}}a(Jv,"insertChunk");async function bee(e){let t={records:0,number_written:0},r=jv(e.schema,e.table);try{let n=new Hg,s=Mn.createReadStream(e.file_path,{highWaterMark:$v});s.setEncoding("utf8"),await Pg.parsePromise(s,zv.bind(null,e,n),vg.bind(null,r));let i=n.getPermsResponse();if(i)throw nt(new Error,i,kt.BAD_REQUEST);return s=Mn.createReadStream(e.file_path,{highWaterMark:$v}),s.setEncoding("utf8"),await Pg.parsePromise(s,Jv.bind(null,e,t),vg.bind(null,r)),s.destroy(),t}catch(n){throw nt(n,ho(bt.PAPA_PARSE_ERR),kt.INTERNAL_SERVER_ERROR,Ln.LOG_LEVELS.ERROR,bt.PAPA_PARSE_ERR+n)}}a(bee,"callPapaParse");function jv(e,t){let r=dee[e][t].attributes,n=new Map;for(let s of r)s.type&&n.set(s.name,i=>fee(i,s));return n}a(jv,"createTransformMap");function vg(e,t,r){let n=e.get(r);return n?n(t):ya.autoCast(t)}a(vg,"typeFunction");async function Nee(e){let t={records:0,number_written:0},r=a(n=>{throw n},"throwErr");try{let n=new Hg,s=xv([Mn.createReadStream(e.file_path,{encoding:"utf-8"}),qv.withParser(),c=>c.value,new Fv({batchSize:Yv}),Gv(async c=>{await zv(e,n,r,c)})]);await new Promise((c,u)=>{kv(s,_=>{_?u(_):c()}),s.resume()});let i=n.getPermsResponse();if(i)throw nt(new Error,i,kt.BAD_REQUEST);let o=xv([Mn.createReadStream(e.file_path,{encoding:"utf-8"}),qv.withParser(),c=>c.value,new Fv({batchSize:Yv}),Gv(async c=>{await Jv(e,t,r,c)})]);return await new Promise((c,u)=>{kv(o,_=>{_?u(_):c()}),o.resume()}),t}catch(n){throw nt(n,ho(bt.INSERT_JSON_ERR),kt.INTERNAL_SERVER_ERROR,Ln.LOG_LEVELS.ERROR,bt.INSERT_JSON_ERR+n)}}a(Nee,"insertJson");async function Xv(e){let t={};try{e.data&&e.data.length>0&&yee(e.data[0])?t=await wee(e.data,e.schema,e.table,e.action):(t.message="No records parsed from csv file.",wa.info(t.message))}catch(r){throw mo(r)}return t}a(Xv,"callBulkFileLoad");function yee(e){let t=Object.keys(e);for(let r of t)if(!Eee.test(r))throw new Error(`Invalid column name '${r}', cancelling load operation`);return!0}a(yee,"validateColumnNames");async function wee(e,t,r,n){n||(n="insert");let s={operation:n,schema:t,table:r,records:e},i;switch(n){case"insert":i=Uf.insert;break;case"update":i=Uf.update;break;case"upsert":i=Uf.upsert;break;default:throw nt(new Error,bt.INVALID_ACTION_PARAM_ERR(n),kt.BAD_REQUEST,Ln.LOG_LEVELS.ERROR,bt.INVALID_ACTION_PARAM_ERR(n))}try{let o=await i(s),c;switch(n){case"insert":c=o.inserted_hashes;break;case"update":c=o.update_hashes;break;case"upsert":c=o.upserted_hashes;break;default:break}if(Array.isArray(o.skipped_hashes)&&o.skipped_hashes.length>0){let l=global.hdb_schema[t][r].hash_attribute,d=e.length;for(;d--;)o.skipped_hashes.indexOf(e[d][l])>=0&&e.splice(d,1)}let u=ya.isEmptyOrZeroLength(c)?0:c.length;return{records:e.length,number_written:u,new_attributes:o.new_attributes}}catch(o){throw mo(o)}}a(wee,"bulkFileLoad");function Zv(e,t){return`successfully loaded ${t} of ${e} records`}a(Zv,"buildResponseMsg");function mo(e){return nt(e,ho(bt.DEFAULT_BULK_LOAD_ERR),kt.INTERNAL_SERVER_ERROR,Ln.LOG_LEVELS.ERROR,bt.DEFAULT_BULK_LOAD_ERR+" - "+e)}a(mo,"buildTopLevelErrMsg")});var r0=g(($Ee,t0)=>{"use strict";var Gg=class{static{a(this,"SqlSearchObject")}constructor(t,r){this.operation="sql",this.sql=t,this.hdb_user=r}};t0.exports=Gg});var i0=g((KEe,s0)=>{"use strict";var Iee=M(),n0=require("moment"),Cee=require("uuid").v4,kg=class{static{a(this,"JobObject")}constructor(){this.id=Cee(),this.type=void 0,this.start_datetime=n0().valueOf(),this.created_datetime=n0().valueOf(),this.end_datetime=void 0,this.status=Iee.JOB_STATUS_ENUM.CREATED,this.message=void 0,this.user=void 0,this.request=void 0}};s0.exports=kg});var xf=g((QEe,_0)=>{"use strict";var Dee=require("uuid").v4,c0=Zr(),u0=Xr(),Lee=Kn(),Mee=Jo(),Uee=r0(),st=M(),Pee=i0(),vee=bS(),un=Y(),Bee=Nc(),Ia=J(),{promisify:Hee}=require("util"),po=require("moment"),xee=df(),Hf=Cg(),o0=Nm(),{deleteTransactionLogsBeforeValidator:qee}=$T(),{handleHDBError:Fee,hdb_errors:Gee}=ee(),{HTTP_STATUS_CODES:kee}=Gee,a0=u0.searchByValue,Vee=u0.searchByHash,$ee=c0.insert,Yee=Hee(xee.evaluateSQL),Kee=c0.update;_0.exports={addJob:zee,updateJob:jee,handleGetJob:Wee,handleGetJobsByStartDate:Qee,getJobById:l0};async function Wee(e){try{let t=await l0(e.id);return Ia.isEmptyOrZeroLength(t)||(t[0]={...t[0]},t[0].request!==void 0&&delete t[0].request,delete t[0].__createdtime__,delete t[0].__updatedtime__),t}catch(t){let r=`There was an error getting job: ${t}`;throw un.error("There was an error getting job",t),new Error(r)}}a(Wee,"handleGetJob");async function Qee(e){try{let t=await Jee(e);if(un.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=po(r.start_datetime)),r.end_datetime&&(r.end_datetime_converted=po(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 un.error(r),new Error(r)}}a(Qee,"handleGetJobsByStartDate");async function zee(e){let t={message:"",error:"",success:!1,createdJob:void 0};if(!e||Object.keys(e).length===0||Ia.isEmptyOrZeroLength(e.operation)){let l="job parameter is invalid";return un.info(l),t.error=l,t}if(!st.JOB_TYPE_ENUM[e.operation])return un.info(`invalid job type specified: ${e.operation}.`),t;let r=e.operation,n;switch(r){case st.OPERATIONS_ENUM.CSV_FILE_LOAD:n=Hf.fileObject(e);break;case st.OPERATIONS_ENUM.CSV_URL_LOAD:n=Hf.urlObject(e);break;case st.OPERATIONS_ENUM.CSV_DATA_LOAD:n=Hf.dataObject(e);break;case st.OPERATIONS_ENUM.IMPORT_FROM_S3:n=Hf.s3FileObject(e);break;case st.OPERATIONS_ENUM.DELETE_FILES_BEFORE:case st.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE:n=o0(e,"date");break;case st.OPERATIONS_ENUM.DELETE_AUDIT_LOGS_BEFORE:n=o0(e,"timestamp");break;case st.OPERATIONS_ENUM.DELETE_TRANSACTION_LOGS_BEFORE:n=qee(e);break;default:break}if(n)throw Fee(n,n.message,kee.BAD_REQUEST,void 0,void 0,!0);let s=new Pee;s.type=e.operation===st.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE?st.OPERATIONS_ENUM.DELETE_FILES_BEFORE:e.operation,s.type=e.operation,s.user=e.hdb_user.username;let i=new Lee(st.SYSTEM_SCHEMA_NAME,st.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,"id",s.id,"id",["id"]),o;try{o=Array.from(await a0(i))}catch(l){let d=`There was an error inserting a new job: ${l}`;return un.error(d),t}let c=Array.isArray(o)?o:Object.keys(o);if(c&&c.length>0){s.id=Dee();try{o=await a0(i)}catch(l){let d=`There was an error inserting a new job: ${l}`;return un.error(d),t}if(c=Array.isArray(o)?o:Object.keys(o),c&&c.length>0)return un.error("Error creating a job, could not find a unique job id."),t}s.request=e;let u=new Bee(st.SYSTEM_SCHEMA_NAME,st.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,"id",[s]),_;try{_=await $ee(u)}catch(l){return un.error(`There was an error inserting a job for job type: ${e.operation} -- ${l}`),t.success=!1,t}if(_.inserted_hashes.length===0)t.message=`Had a problem creating a job with type ${s.operation} and id ${s.id}`;else{let l=`Created a job with type ${s.type} and id ${s.id}`;t.message=l,t.createdJob=s,t.success=!0,un.trace(l)}return t}a(zee,"addJob");async function Jee(e){let t=po(e.from_date,po.ISO_8601),r=po(e.to_date,po.ISO_8601);if(!t.isValid())throw new Error("Invalid 'from' date, must be in ISO-8601 format (YYYY-MM-DD).");if(!r.isValid())throw new Error("Invalid 'to' date, must be in ISO-8601 format (YYYY-MM-DD)");let n=`select * from system.hdb_job where start_datetime > '${t.valueOf()}' and start_datetime < '${r.valueOf()}'`,s=new Uee(n,e.hdb_user);try{return await Yee(s)}catch(i){throw un.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(Jee,"getJobsInDateRange");async function l0(e){if(Ia.isEmptyOrZeroLength(e))return Ia.errorizeMessage("Invalid job ID specified.");let t=new Mee(st.SYSTEM_SCHEMA_NAME,st.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,[e],["*"]);try{return await Vee(t)}catch(r){let n=`There was an error searching for a job by id: ${e} ${r}`;return un.error(n),Ia.errorizeMessage("there was an error searching for jobs. Please check the log for details.")}}a(l0,"getJobById");async function jee(e){if(Object.keys(e).length===0)throw new Error("invalid job object passed to updateJob");if(Ia.isEmptyOrZeroLength(e.id))throw new Error("invalid ID passed to updateJob");(e.status===st.JOB_STATUS_ENUM.COMPLETE||e.status===st.JOB_STATUS_ENUM.ERROR)&&(e.end_datetime=po().valueOf());let t=new vee(st.SYSTEM_SCHEMA_NAME,st.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,[e]),r;return r=await Kee(t),r}a(jee,"updateJob")});var p0=g((JEe,m0)=>{"use strict";var d0=J(),pr=M(),Xee=require("moment"),qf=qg(),Ff=Y(),f0=xf(),E0=ff(),h0=Fi(),Zee=Ze(),ete=of(),Vg=class{static{a(this,"RunnerMessage")}constructor(t,r){this.job=t,this.json=r}};async function tte(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(d0.isEmptyOrZeroLength(e.json.operation))throw new Error("Invalid operation");if(d0.isEmptyOrZeroLength(e.job.id))throw new Error("Empty job id specified");switch(e.json.operation){case pr.JOB_TYPE_ENUM.csv_file_load:await Us(e,qf.csvFileLoad);break;case pr.JOB_TYPE_ENUM.csv_url_load:await Us(e,qf.csvURLLoad);break;case pr.JOB_TYPE_ENUM.csv_data_load:await Us(e,qf.csvDataLoad);break;case pr.JOB_TYPE_ENUM.import_from_s3:await Us(e,qf.importFromS3);break;case pr.JOB_TYPE_ENUM.empty_trash:break;case pr.JOB_TYPE_ENUM.export_local:await Us(e,E0.export_local);break;case pr.JOB_TYPE_ENUM.export_to_s3:await Us(e,E0.export_to_s3);break;case pr.JOB_TYPE_ENUM.delete_files_before:case pr.JOB_TYPE_ENUM.delete_records_before:await Us(e,h0.deleteFilesBefore);break;case pr.JOB_TYPE_ENUM.delete_audit_logs_before:await Us(e,h0.deleteAuditLogsBefore);break;case pr.JOB_TYPE_ENUM.delete_transaction_logs_before:await Us(e,ete.deleteTransactionLogsBefore);break;default:return`Invalid operation ${e.json.operation} specified`}}a(tte,"parseMessage");async function Us(e,t){try{e.job.status=pr.JOB_STATUS_ENUM.IN_PROGRESS,e.job.start_datetime=Xee().valueOf(),await f0.updateJob(e.job),await rte(e.job.id)}catch(r){let n=r.message!==void 0?r.message:r;typeof n=="string"?(n=`There was an error running ${t.name} job with id ${e.job.id} - ${n}`,r.message=n):Ff.error(`There was an error running ${t.name} job with id ${e.job.id}`),Ff.error(n),e.job.message=n,e.job.status=pr.JOB_STATUS_ENUM.ERROR;try{await f0.updateJob(e.job)}catch(s){throw Ff.error(`Unable to update job with id ${e.job.id}`),s}throw r}}a(Us,"runJob");async function rte(e){Ff.trace("launching job thread:",e),Zee.startWorker("server/jobs/jobProcess.js",{autoRestart:!1,name:"job",env:Object.assign({},process.env,{[pr.PROCESS_NAME_ENV_PROP]:`JOB-${e}`})})}a(rte,"launchJobThread");m0.exports={parseMessage:tte,RunnerMessage:Vg}});var T0=g((XEe,S0)=>{"use strict";var $g=class{static{a(this,"OperationFunctionObject")}constructor(t,r=void 0){this.operation_function=t,this.job_operation_function=r}};S0.exports=$g});var jg=g((ehe,Jg)=>{"use strict";var $f=Xr(),Wg=df(),Gf=qg(),Ps=od(),kf=vi(),Zu=Fi(),nte=uS(),Xu=Mr(),Vf=SS(),Vt=VT(),Nt=Y(),ste=RS(),ite=Od(),g0=nT(),ote=Nd(),ate=sT(),cte=iT(),ute=cT(),lte=lT(),Yg=fT(),R0=ff(),_te=lf(),Qg=xf(),F=M(),{hdb_errors:tl,handleHDBError:el}=ee(),{HTTP_STATUS_CODES:A0}=tl,Kg=ST(),O0=kd(),M0=require("util"),Ca=Zr(),dte=ms(),fte=aa(),b0=p0(),N0=_u(),y0=(Qd(),te(Lu)),w0=wr(),I0=of(),C0=Zd(),{setServerUtilities:Ete}=(Bf(),te(Fg)),{CONTEXT:hte}=(gn(),te(Ep)),{_assignPackageExport:mte}=require("../../index"),{transformReq:pte}=J(),{server:Ste}=(Zt(),te(yi)),Tte=Dg(),D0=$f.searchByHash,gte=$f.searchByValue,Rte=M0.promisify($f.search),Ate=M0.promisify(Wg.evaluateSQL),Ote={[F.OPERATIONS_ENUM.CREATE_ATTRIBUTE]:!0,[F.OPERATIONS_ENUM.CREATE_TABLE]:!0,[F.OPERATIONS_ENUM.CREATE_SCHEMA]:!0,[F.OPERATIONS_ENUM.DROP_ATTRIBUTE]:!0,[F.OPERATIONS_ENUM.DROP_TABLE]:!0,[F.OPERATIONS_ENUM.DROP_SCHEMA]:!0},V=T0();async function U0(e,t){try{if(e.body.operation!=="read_log"&&(Nt.log_level===F.LOG_LEVELS.INFO||Nt.log_level===F.LOG_LEVELS.DEBUG||Nt.log_level===F.LOG_LEVELS.TRACE)){let{hdb_user:n,hdb_auth_header:s,password:i,...o}=e.body;Nt.info(o)}}catch(n){Nt.error(n)}let r=await Tte.callOperationFunctionAsAwait(t,e.body,null);if(typeof r!="object"&&(r={message:r}),r instanceof Error)throw r;return Ote[e.body.operation]&&dte.setSchemaDataToGlobal(n=>{n&&Nt.error(n)}),r}a(U0,"processLocalTransaction");var L0=Nte();Jg.exports={chooseOperation:P0,getOperationFunction:v0,operation:zg,processLocalTransaction:U0};Ete(Jg.exports);Ste.operation=zg;function P0(e){let t;try{t=v0(e)}catch(s){throw Nt.error(`Error when selecting operation function - ${s}`),s}let{operation_function:r,job_operation_function:n}=t;try{if(e.operation==="sql"||e.search_operation&&e.search_operation.operation==="sql"){let s=e.operation==="sql"?e.sql:e.search_operation.sql,i=Wg.convertSQLToAST(s);if(e.parsed_sql_object=i,!e.bypass_auth){let o=Wg.checkASTPermissions(e,i);if(o)throw Nt.error(`${A0.FORBIDDEN} from operation ${e.operation}`),Nt.warn(`User '${e.hdb_user.username}' is not permitted to ${e.operation}`),el(new Error,o,tl.HTTP_STATUS_CODES.FORBIDDEN,void 0,void 0,!0)}}else if(!e.bypass_auth&&e.operation!==F.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS&&e.operation!==F.OPERATIONS_ENUM.LOGIN&&e.operation!==F.OPERATIONS_ENUM.LOGOUT){let s=n===void 0?r:n,i=e.search_operation?e.search_operation:e;i.hdb_user||(i.hdb_user=e.hdb_user);let o=_te.verifyPerms(i,s);if(o)throw Nt.error(`${A0.FORBIDDEN} from operation ${e.operation}`),Nt.warn(`User '${i.hdb_user.username}' is not permitted to ${i.operation}`),el(new Error,o,tl.HTTP_STATUS_CODES.FORBIDDEN,void 0,!1,!0)}}catch(s){throw el(s,"There was an error when trying to choose an operation path")}return r}a(P0,"chooseOperation");function v0(e){if(Nt.trace(`getOperationFunction with operation: ${e.operation}`),L0.has(e.operation))return L0.get(e.operation);throw el(new Error,tl.HDB_ERROR_MSGS.OP_NOT_FOUND(e.operation),tl.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0)}a(v0,"getOperationFunction");mte("operation",zg);function zg(e,t){e.hdb_user=this[hte]?.user,e.bypass_auth=!t;let r=P0(e);return U0({body:e},r)}a(zg,"operation");async function bte(e){Nt.trace("In serverUtils.catchup");let t=e.transaction,r=t.channel.split(":"),n=r[0],s=r[1];for(let i of t.transactions)try{i.schema=n,i.table=s,i[F.CLUSTERING_FLAG]=!0;let o;switch(i.operation){case F.OPERATIONS_ENUM.INSERT:o=await Ca.insert(i);break;case F.OPERATIONS_ENUM.UPDATE:o=await Ca.update(i);break;case F.OPERATIONS_ENUM.UPSERT:o=await Ca.upsert(i);break;case F.OPERATIONS_ENUM.DELETE:o=await Zu.deleteRecord(i);break;default:Nt.warn("invalid operation in catchup");break}await transact_to_clustering_utils.postOperationHandler(i,o,e)}catch(o){Nt.info("Invalid operation in transaction"),Nt.error(o)}}a(bte,"catchup");async function ns(e){pte(e);let t,r;try{r=await Qg.addJob(e),t=r.createdJob,Nt.info("addJob result",r);let n=new b0.RunnerMessage(t,e);return await b0.parseMessage(n),{message:`Starting job with id ${t.id}`,job_id:t.id}}catch(n){let s=`There was an error executing job: ${n.http_resp_msg?n.http_resp_msg:n}`;throw Nt.error(s),el(n,s)}}a(ns,"executeJob");function Nte(){let e=new Map;return e.set(F.OPERATIONS_ENUM.INSERT,new V(Ca.insert)),e.set(F.OPERATIONS_ENUM.UPDATE,new V(Ca.update)),e.set(F.OPERATIONS_ENUM.UPSERT,new V(Ca.upsert)),e.set(F.OPERATIONS_ENUM.SEARCH_BY_CONDITIONS,new V($f.searchByConditions)),e.set(F.OPERATIONS_ENUM.SEARCH_BY_HASH,new V(D0)),e.set(F.OPERATIONS_ENUM.SEARCH_BY_ID,new V(D0)),e.set(F.OPERATIONS_ENUM.SEARCH_BY_VALUE,new V(gte)),e.set(F.OPERATIONS_ENUM.SEARCH,new V(Rte)),e.set(F.OPERATIONS_ENUM.SQL,new V(Ate)),e.set(F.OPERATIONS_ENUM.CSV_DATA_LOAD,new V(ns,Gf.csvDataLoad)),e.set(F.OPERATIONS_ENUM.CSV_FILE_LOAD,new V(ns,Gf.csvFileLoad)),e.set(F.OPERATIONS_ENUM.CSV_URL_LOAD,new V(ns,Gf.csvURLLoad)),e.set(F.OPERATIONS_ENUM.IMPORT_FROM_S3,new V(ns,Gf.importFromS3)),e.set(F.OPERATIONS_ENUM.CREATE_SCHEMA,new V(Ps.createSchema)),e.set(F.OPERATIONS_ENUM.CREATE_DATABASE,new V(Ps.createSchema)),e.set(F.OPERATIONS_ENUM.CREATE_TABLE,new V(Ps.createTable)),e.set(F.OPERATIONS_ENUM.CREATE_ATTRIBUTE,new V(Ps.createAttribute)),e.set(F.OPERATIONS_ENUM.DROP_SCHEMA,new V(Ps.dropSchema)),e.set(F.OPERATIONS_ENUM.DROP_DATABASE,new V(Ps.dropSchema)),e.set(F.OPERATIONS_ENUM.DROP_TABLE,new V(Ps.dropTable)),e.set(F.OPERATIONS_ENUM.DROP_ATTRIBUTE,new V(Ps.dropAttribute)),e.set(F.OPERATIONS_ENUM.DESCRIBE_SCHEMA,new V(kf.describeSchema)),e.set(F.OPERATIONS_ENUM.DESCRIBE_DATABASE,new V(kf.describeSchema)),e.set(F.OPERATIONS_ENUM.DESCRIBE_TABLE,new V(kf.describeTable)),e.set(F.OPERATIONS_ENUM.DESCRIBE_ALL,new V(kf.describeAll)),e.set(F.OPERATIONS_ENUM.DELETE,new V(Zu.deleteRecord)),e.set(F.OPERATIONS_ENUM.ADD_USER,new V(Xu.addUser)),e.set(F.OPERATIONS_ENUM.ALTER_USER,new V(Xu.alterUser)),e.set(F.OPERATIONS_ENUM.DROP_USER,new V(Xu.dropUser)),e.set(F.OPERATIONS_ENUM.LIST_USERS,new V(Xu.listUsersExternal)),e.set(F.OPERATIONS_ENUM.LIST_ROLES,new V(Vf.listRoles)),e.set(F.OPERATIONS_ENUM.ADD_ROLE,new V(Vf.addRole)),e.set(F.OPERATIONS_ENUM.ALTER_ROLE,new V(Vf.alterRole)),e.set(F.OPERATIONS_ENUM.DROP_ROLE,new V(Vf.dropRole)),e.set(F.OPERATIONS_ENUM.USER_INFO,new V(Xu.userInfo)),e.set(F.OPERATIONS_ENUM.READ_LOG,new V(ste)),e.set(F.OPERATIONS_ENUM.ADD_NODE,new V(ite)),e.set(F.OPERATIONS_ENUM.UPDATE_NODE,new V(g0)),e.set(F.OPERATIONS_ENUM.SET_NODE_REPLICATION,new V(g0)),e.set(F.OPERATIONS_ENUM.REMOVE_NODE,new V(ote)),e.set(F.OPERATIONS_ENUM.CONFIGURE_CLUSTER,new V(ate)),e.set(F.OPERATIONS_ENUM.PURGE_STREAM,new V(cte)),e.set(F.OPERATIONS_ENUM.SET_CONFIGURATION,new V(w0.setConfiguration)),e.set(F.OPERATIONS_ENUM.CLUSTER_STATUS,new V(ute.clusterStatus)),e.set(F.OPERATIONS_ENUM.CLUSTER_NETWORK,new V(lte)),e.set(F.OPERATIONS_ENUM.CLUSTER_SET_ROUTES,new V(Yg.setRoutes)),e.set(F.OPERATIONS_ENUM.CLUSTER_GET_ROUTES,new V(Yg.getRoutes)),e.set(F.OPERATIONS_ENUM.CLUSTER_DELETE_ROUTES,new V(Yg.deleteRoutes)),e.set(F.OPERATIONS_ENUM.EXPORT_TO_S3,new V(ns,R0.export_to_s3)),e.set(F.OPERATIONS_ENUM.DELETE_FILES_BEFORE,new V(ns,Zu.deleteFilesBefore)),e.set(F.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE,new V(ns,Zu.deleteFilesBefore)),e.set(F.OPERATIONS_ENUM.EXPORT_LOCAL,new V(ns,R0.export_local)),e.set(F.OPERATIONS_ENUM.SEARCH_JOBS_BY_START_DATE,new V(Qg.handleGetJobsByStartDate)),e.set(F.OPERATIONS_ENUM.GET_JOB,new V(Qg.handleGetJob)),e.set(F.OPERATIONS_ENUM.GET_FINGERPRINT,new V(Kg.getFingerprint)),e.set(F.OPERATIONS_ENUM.SET_LICENSE,new V(Kg.setLicense)),e.set(F.OPERATIONS_ENUM.GET_REGISTRATION_INFO,new V(Kg.getRegistrationInfo)),e.set(F.OPERATIONS_ENUM.RESTART,new V(O0.restart)),e.set(F.OPERATIONS_ENUM.RESTART_SERVICE,new V(O0.restartService)),e.set(F.OPERATIONS_ENUM.CATCHUP,new V(bte)),e.set(F.OPERATIONS_ENUM.SYSTEM_INFORMATION,new V(fte.systemInformation)),e.set(F.OPERATIONS_ENUM.DELETE_AUDIT_LOGS_BEFORE,new V(ns,Zu.deleteAuditLogsBefore)),e.set(F.OPERATIONS_ENUM.READ_AUDIT_LOG,new V(nte)),e.set(F.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS,new V(N0.createTokens)),e.set(F.OPERATIONS_ENUM.REFRESH_OPERATION_TOKEN,new V(N0.refreshOperationToken)),e.set(F.OPERATIONS_ENUM.LOGIN,new V(y0.login)),e.set(F.OPERATIONS_ENUM.LOGOUT,new V(y0.logout)),e.set(F.OPERATIONS_ENUM.GET_CONFIGURATION,new V(w0.getConfiguration)),e.set(F.OPERATIONS_ENUM.CUSTOM_FUNCTIONS_STATUS,new V(Vt.customFunctionsStatus)),e.set(F.OPERATIONS_ENUM.GET_CUSTOM_FUNCTIONS,new V(Vt.getCustomFunctions)),e.set(F.OPERATIONS_ENUM.GET_COMPONENT_FILE,new V(Vt.getComponentFile)),e.set(F.OPERATIONS_ENUM.GET_COMPONENTS,new V(Vt.getComponents)),e.set(F.OPERATIONS_ENUM.SET_COMPONENT_FILE,new V(Vt.setComponentFile)),e.set(F.OPERATIONS_ENUM.DROP_COMPONENT,new V(Vt.dropComponent)),e.set(F.OPERATIONS_ENUM.GET_CUSTOM_FUNCTION,new V(Vt.getCustomFunction)),e.set(F.OPERATIONS_ENUM.SET_CUSTOM_FUNCTION,new V(Vt.setCustomFunction)),e.set(F.OPERATIONS_ENUM.DROP_CUSTOM_FUNCTION,new V(Vt.dropCustomFunction)),e.set(F.OPERATIONS_ENUM.ADD_CUSTOM_FUNCTION_PROJECT,new V(Vt.addComponent)),e.set(F.OPERATIONS_ENUM.ADD_COMPONENT,new V(Vt.addComponent)),e.set(F.OPERATIONS_ENUM.DROP_CUSTOM_FUNCTION_PROJECT,new V(Vt.dropCustomFunctionProject)),e.set(F.OPERATIONS_ENUM.PACKAGE_CUSTOM_FUNCTION_PROJECT,new V(Vt.packageComponent)),e.set(F.OPERATIONS_ENUM.PACKAGE_COMPONENT,new V(Vt.packageComponent)),e.set(F.OPERATIONS_ENUM.DEPLOY_CUSTOM_FUNCTION_PROJECT,new V(Vt.deployComponent)),e.set(F.OPERATIONS_ENUM.DEPLOY_COMPONENT,new V(Vt.deployComponent)),e.set(F.OPERATIONS_ENUM.READ_TRANSACTION_LOG,new V(I0.readTransactionLog)),e.set(F.OPERATIONS_ENUM.DELETE_TRANSACTION_LOGS_BEFORE,new V(ns,I0.deleteTransactionLogsBefore)),e.set(F.OPERATIONS_ENUM.INSTALL_NODE_MODULES,new V(C0.installModules)),e.set(F.OPERATIONS_ENUM.AUDIT_NODE_MODULES,new V(C0.auditModules)),e.set(F.OPERATIONS_ENUM.GET_BACKUP,new V(Ps.getBackup)),e}a(Nte,"initializeOperationFunctionMap")});var Kf=g((rhe,x0)=>{"use strict";var Xg=M(),yte=J(),rl=Y(),{handleHDBError:Zg,hdb_errors:Yf}=ee(),{isMainThread:wte}=require("worker_threads"),{Readable:Ite}=require("stream"),B0=require("os"),Cte=require("util"),Dte=MS(),Lte=Cte.promisify(Dte.authorize),H0=jg(),{createGzip:Mte,constants:Ute}=require("zlib");function Pte(e){let t=`Found an uncaught exception with message: ${e.message}. ${B0.EOL}Stack: ${e.stack} ${B0.EOL}Terminating ${wte?"HDB":"thread"}.`;console.error(t),rl.fatal(t),process.exit(1)}a(Pte,"handleServerUncaughtException");function vte(e,t,r){if(rl[e.logLevel||"error"](e),e.statusCode)return typeof e.http_resp_msg!="object"?r.code(e.statusCode).send({error:e.http_resp_msg||e.message}):r.code(e.statusCode).send(e.http_resp_msg);let n=e.statusCode?e.statusCode:Yf.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR;return typeof e=="string"?r.code(n).send({error:e}):r.code(n).send(e.message?{error:e.message}:e)}a(vte,"serverErrorHandler");function Bte(e,t,r){if(!e.body||Object.keys(e.body).length===0||typeof e.body!="object"){let n=Zg(new Error,"Invalid JSON.",Yf.HTTP_STATUS_CODES.BAD_REQUEST);r(n,null)}if(yte.isEmpty(e.body.operation)){let n=Zg(new Error,"Request body must include an 'operation' property.",Yf.HTTP_STATUS_CODES.BAD_REQUEST);r(n,null)}r()}a(Bte,"reqBodyValidationHandler");function Hte(e,t,r){let n;e.body.operation!==Xg.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS&&e.body.operation!==Xg.OPERATIONS_ENUM.LOGIN&&e.body.operation!==Xg.OPERATIONS_ENUM.LOGOUT?Lte(e,t).then(s=>{n=s,e.body.hdb_user=n,e.body.hdb_auth_header=e.headers.authorization,r()}).catch(s=>{rl.warn(s),rl.warn(`{"ip":"${e.socket.remoteAddress}", "error":"${s.stack}"`);let i=typeof s=="string"?{error:s}:{error:s.message};r(Zg(s,i,Yf.HTTP_STATUS_CODES.UNAUTHORIZED),null)}):(e.body.hdb_user=null,e.body.hdb_auth_header=e.headers.authorization,e.body.baseRequest=e.raw?.baseRequest,e.body.baseResponse=t.raw?.baseResponse,e.body.fastifyResponse=t,r())}a(Hte,"authHandler");async function xte(e,t,r=!1){let n;try{r&&(e.body.operation!=="configure_cluster"||e.body.operation!=="set_configuration")&&(e.body.bypass_auth=r),n=H0.chooseOperation(e.body);let s=await H0.processLocalTransaction(e,n);if(s instanceof Ite&&s.headers){for(let[i,o]of s.headers)t.header(i,o);e.headers["accept-encoding"]?.includes("gzip")&&(t.header("content-encoding","gzip"),s=s.pipe(Mte({level:Ute.Z_BEST_SPEED})))}return s}catch(s){throw rl.error(s),s}}a(xte,"handlePostRequest");x0.exports={authHandler:Hte,handlePostRequest:xte,handleServerUncaughtException:Pte,serverErrorHandler:vte,reqBodyValidationHandler:Bte}});var k0=g((she,G0)=>{"use strict";var qte=require("fastify-plugin"),{handlePostRequest:q0,authHandler:Fte,reqBodyValidationHandler:Gte}=Kf();async function kte(e){e.decorate("hdbCore",{preValidation:[Gte,Fte],request:t=>F0(q0(t,response)),requestWithoutAuthentication:(t,r)=>F0(q0(t,r,!0))})}a(kte,"hdbCore");async function F0(e){if(e=await e,e?.[Symbol.asyncIterator]&&!e[Symbol.iterator]){let t=[];for await(let r of e)t.push(r);return t}return e}a(F0,"convertAsyncIterators");G0.exports=qte(kte)});var Y0=g((ahe,$0)=>{"use strict";var ohe=require("fs"),eR=Z();eR.initSync();var{CONFIG_PARAMS:V0}=M(),Vte=1024*1024*1024;function $te(e){let t=eR.get(V0.HTTP_TIMEOUT),r=eR.get(V0.HTTP_KEEPALIVETIMEOUT);return{bodyLimit:Vte,connectionTimeout:t,keepAliveTimeout:r,return503OnClosing:!1,forceCloseConnections:!0,ignoreTrailingSlash:!0,https:e}}a($te,"getServerOptions");$0.exports=$te});var Q0=g((uhe,W0)=>{"use strict";var tR=Z();tR.initSync();var{CONFIG_PARAMS:K0}=M();function Yte(){let e=tR.get(K0.HTTP_CORSACCESSLIST),t=tR.get(K0.HTTP_CORS),r;return t&&(r={origin:!0,allowedHeaders:["Content-Type","Authorization","Accept"],credentials:!1},e&&e.length>0&&e[0]!==null&&e[0]!=="*"&&(r.origin=(n,s)=>s(null,e.indexOf(n)!==-1))),r}a(Yte,"getCORSOptions");W0.exports=Yte});var j0=g((_he,J0)=>{"use strict";var z0=Z();z0.initSync();var Kte=M();function Wte(){return z0.get(Kte.CONFIG_PARAMS.HTTP_HEADERSTIMEOUT)??6e4}a(Wte,"getHeaderTimeoutConfig");J0.exports=Wte});var nR={};Ve(nR,{customFunctionsServer:()=>Jte,ready:()=>dB,start:()=>zte});function zte(e){let t=e.securePort>0;return{async handleFile(r,n,s,i){vs||(vs=_B(t),Xe.http((await vs).server));let o=await vs,c=(0,rR.dirname)(s),u=(0,rR.dirname)(n);if(u.startsWith("/")&&(u=u.slice(1)),!X0.has(c)){X0.add(c);try{o.register(Xte(c,u))}catch(_){if(_.message==="Root plugin has already booted")Ge.warn(`Could not load root fastify route for ${s}, this may require a restart to install properly`);else throw _}}},ready:dB}}async function Jte(){try{Ge.info("In Custom Functions Fastify server"+process.cwd()),Ge.info(`Custom Functions Running with NODE_ENV set as: ${process.env.NODE_ENV}`),Ge.debug(`Custom Functions server process ${process.pid} starting up.`),await jte();let e=sB.get(iB.CONFIG_PARAMS.HTTP_SECUREPORT)>0,t;try{t=vs=await _B(e)}catch(r){throw Ge.error(`Custom Functions buildServer error: ${r}`),r}try{await t.ready()}catch(r){throw Ge.error(`Custom Functions server.ready() error: ${r}`),r}t.server.cantCleanupProperly=!0}catch(e){Ge.error(`Custom Functions ${process.pid} Error: ${e}`),Ge.error(e),process.exit(1)}}async function jte(){try{Ge.info("Custom Functions starting configuration."),await oB.setUsersToGlobal(),Ge.info("Custom Functions completed configuration.")}catch(e){Ge.error(e)}}function Xte(e,t){return async function(r){try{Ge.info("Custom Functions starting buildRoutes"),Ge.trace("Loading fastify routes folder "+e),(0,Z0.existsSync)(e)&&r.register(nB.default,s=>({dir:e,dirNameRoutePrefix:!1,options:{hdbCore:s.hdbCore,logger:Ge.loggerWithTag("custom-function"),prefix:`/${t}`}})).after((s,i,o)=>{s?.message?Ge.error(s.message):s&&Ge.error(s),o()})}catch(n){Ge.error(`Custom Functions errored buildRoutes: ${n}`)}}}async function _B(e){Ge.info("Custom Functions starting buildServer.");let t=(0,aB.default)(e),r=(0,eB.default)(t);r.server.headersTimeout=(0,uB.default)(),r.setErrorHandler(lB.serverErrorHandler);let n=(0,cB.default)();return n&&r.register(tB.default,n),r.register(function(s,i,o){s.setNotFoundHandler(function(c,u){r.server.emit("unhandled",c.raw,u.raw)}),o()}),r.register(rB.default),await r.register(Qte),await r.after(),fg(r),Ge.info("Custom Functions completed buildServer."),r}function dB(){if(vs)return vs.then?vs.then(e=>e.ready()):vs.ready()}var rR,Z0,eB,tB,rB,nB,sB,iB,Ge,Qte,oB,aB,cB,uB,lB,vs,X0,fB=Oe(()=>{rR=require("path"),Z0=require("fs"),eB=B(require("fastify")),tB=B(require("@fastify/cors")),rB=B(Ng()),nB=B(require("@fastify/autoload")),sB=B(Z()),iB=B(M()),Ge=B(Y()),Qte=B(k0()),oB=B(Mr()),aB=B(Y0()),cB=B(Q0()),uB=B(j0()),lB=B(Kf());ha();Zt();X0=new Set;a(zte,"start");a(Jte,"customFunctionsServer");a(jte,"setUp");a(Xte,"buildRouteFolder");a(_B,"buildServer");a(dB,"ready")});var sR={};Ve(sR,{start:()=>Zte});function Zte(e){return{handleDirectory(t,r){if(t==="/"){let n=(0,SB.default)(r,e);return e.server.http(async(s,i)=>{if(!s.isWebSocket)return new Promise(o=>n(s._nodeRequest,s._nodeResponse,()=>{o(i(s))}))}),!0}},handleFile(t,r,n){hB||(hB=!0,e.server.http(async(s,i)=>{if(!s.isWebSocket){let o=EB.get(s.pathname);if(o)return{handlesHeaders:!0,body:(0,mB.default)(s,(0,pB.realpathSync)(o))}}return i(s)},{runFirst:!0})),EB.set(r,n)}}}var mB,pB,SB,EB,hB,TB=Oe(()=>{mB=B(require("send")),pB=require("fs"),SB=B(require("serve-static")),EB=new Map;a(Zte,"start")});function rre(e,t=1,r){if(iR++,(0,So.startWorker)("server/threads/threadServer.js",{name:zf.THREAD_TYPES.HTTP,workerIndex:e,threadCount:t,async onStarted(n){let s=new Promise((o,c)=>{function u(_){_.type===zf.CLUSTER_MESSAGE_TYPE_ENUM.CHILD_STARTED&&(n.removeListener("message",u),o(n))}a(u,"onMessage"),n.on("message",u),n.on("error",c)});tre.push(s),await s,Da.push(n),n.expectedIdle=1,n.lastIdle=0,n.requests=1,n.on("message",o=>{if(o.requestId){let c=Qf.get(o.requestId);c&&c(o)}}),n.on("exit",i),n.on("shutdown",i);function i(){let o=Da.indexOf(n);o>-1&&Da.splice(o,1)}if(a(i,"removeWorker"),La){let o=La;La=[];for(let c of o)OB[c.localPort](null,c)}}}),r){let n=setInterval(()=>{oR?oR=!1:(clearInterval(n),console.log("shut down dynamic thread due to inactivity"),(0,So.shutdownWorkers)(),iR=0,setTimeout(()=>{global.gc?.()},5e3))},1e4)}}function bB(e=0,t){if(typeof e=="string")try{(0,Jf.existsSync)(e)&&(0,Jf.unlinkSync)(e)}catch{}let r;t?t==="ip"?r=nre:r=sre(t):r=cR;let n=(0,Ma.createServer)({allowHalfOpen:!0,pauseOnConnect:!r.readsData}).listen(e);if(n._handle){n._handle.onconnection=OB[e]=function(i,o){r.readsData||(o.reading=!1,o.readStop()),oR=!0,r(o,(c,u)=>{if(!c){if(gB){let l=o._socket||new Ma.Socket({handle:o,writable:!0,readable:!0});gB.deliverSocket(l,e,u),l.resume()}else iR>0?(La.length===0&&setTimeout(()=>{La.length>0&&console.warn("Incoming sockets/requests have been queued for workers to start, and no workers have handled them. Check to make sure an error is not preventing workers from starting")},1e4).unref(),o.localPort=e,La.push(o)):(console.log("start up a dynamic thread to handle request"),rre(0));Br(!1,"socket-routed");return}c.requests++;let _=o.fd;if(_>=0)c.postMessage({port:e,fd:_,data:u});else{let l=o._socket||new Ma.Socket({handle:o,writable:!0,readable:!0});cre(l,c,e)}Br(!0,"socket-routed")})};let s=zc();aR.info(`HarperDB ${s.version} Server running on port ${e}`)}return n.on("error",s=>{console.error("Error in socket server",s)}),process.env._UNREF_SERVER&&n.unref(),n}function cR(e,t){let r,n=0;for(let s of Da){if(s.threadId===-1)continue;let i=s.expectedIdle/s.requests;if(i>n)r=s;else if(n>=Wf)return Wf=i,t(r);n=i}Wf=0,t(r)}function nre(e,t){let r={};e.getpeername(r);let n=r.address,s=Ua.get(n),i=Date.now();if(s&&s.worker.threadId!==-1)return s.lastUsed=i,t(s.worker);cR(e,o=>{Ua.set(n,{worker:o,lastUsed:i}),t(o)})}function sre(e){let t=new RegExp(`${e}:\\s*(.+)`,"i");return r.readsData=!0,r;function r(n,s){let i=new Ma.Socket({handle:n,readable:!0,writable:!0});n._socket=i,i.on("data",o=>{n.readStop();let u=o.toString("latin1").match(t)?.[1],_=Ua.get(u),l=Date.now();if(_&&_.worker.threadId!==-1)return _.lastUsed=l,s(_.worker);cR(n,d=>{Ua.set(u,{worker:d,lastUsed:l}),s(d,o)})})}a(r,"findByHeaderAffinity")}function ore(){Wf=0;for(let e of Da)e.expectedIdle=e.recentELU.idle+ire,e.requests=1;Da.sort((e,t)=>e.expectedIdle>t.expectedIdle?-1:1)}function cre(e,t,r){let n=are++;t.postMessage({port:r,requestId:n,event:"connection"}),e.on("data",s=>{let i=s.toString("latin1");t.postMessage({port:r,requestId:n,data:i,event:"data"})}).on("close",s=>{t.postMessage({port:r,requestId:n,event:"close",hadError:s})}).on("error",s=>{t.postMessage({port:r,requestId:n,event:"error",error:s})}).on("drain",s=>{t.postMessage({port:r,requestId:n,event:"drain",error:s})}).on("end",()=>{t.postMessage({port:r,requestId:n,event:"end"})}).resume(),Qf.set(n,s=>{s.event=="data"&&e.write(Buffer.from(s.data,"latin1")),s.event=="end"&&(e.end(s.data&&Buffer.from(s.data,"latin1")),Qf.delete(n)),s.event=="destroy"&&(e.destroy(),Qf.delete(n))})}var So,Ma,zf,aR,Jf,AB,ere,Da,La,OB,gB,iR,tre,oR,Wf,RB,Ua,ire,Qf,are,NB=Oe(()=>{So=B(Ze()),Ma=require("net"),zf=B(M()),aR=B(Y()),Jf=require("fs");Rs();AB=require("worker_threads"),ere=B(Gi()),Da=[],La=[],OB=[],iR=0,tre=[];AB.isMainThread&&process.on("uncaughtException",e=>{e.code!=="ECONNRESET"&&e.message!=="write EIO"&&console.error("uncaughtException",e)});a(rre,"startHTTPWorker");a(bB,"startSocketServer");Wf=0;a(cR,"findMostIdleWorker");RB=36e5,Ua=new Map;a(nre,"findByRemoteAddressAffinity");a(sre,"makeFindByHeaderAffinity");setInterval(()=>{let e=Date.now();for(let[t,r]of Ua)r.lastUsed+RB<e&&Ua.delete(t)},RB).unref();ire=1e3;a(ore,"updateWorkerIdleness");(0,So.setMonitorListener)(ore);Qf=new Map,are=1;a(cre,"proxySocket")});var dR={};Ve(dR,{Request:()=>uR,createReuseportFd:()=>jf});var yB,uR,lR,_R,jf,Xf=Oe(()=>{yB=require("os"),uR=class{static{a(this,"Request")}#e;constructor(t,r){this.method=t.method;let n=t.url;this._nodeRequest=t,this._nodeResponse=r,this.url=n,this.headers=new _R(t.headers)}get absoluteURL(){return this.protocol+"://"+this.host+this.url}get pathname(){let t=this.url.indexOf("?");return t>-1?this.url.slice(0,t):this.url}set pathname(t){let r=this.url.indexOf("?");r>-1?this.url=t+this.url.slice(r):this.url=t}get protocol(){return this._nodeRequest.socket.encrypted?"https":"http"}get ip(){return this._nodeRequest.socket.remoteAddress}get authorized(){return this._nodeRequest.socket.authorized}get peerCertificate(){return this._nodeRequest.socket.getPeerCertificate()}get mtlsConfig(){return this._nodeRequest.socket.server.mtlsConfig}get body(){return this.#e||(this.#e=new lR(this._nodeRequest))}get host(){return this._nodeRequest.authority||this._nodeRequest.headers.host}get isAborted(){return!1}},lR=class{static{a(this,"RequestBody")}#e;constructor(t){this.#e=t}on(t,r){return this.#e.on(t,r),this}},_R=class{constructor(t){this.asObject=t}static{a(this,"Headers")}set(t,r){this.asObject[t.toLowerCase()]=r}get(t){return this.asObject[t.toLowerCase()]}has(t){return this.asObject.hasOwnProperty(t.toLowerCase())}[Symbol.iterator](){return Object.entries(this.asObject)[Symbol.iterator]()}keys(){return Object.keys(this.asObject)}values(){return Object.values(this.asObject)}forEach(t){for(let[r,n]of this)t(n,r,this)}};(0,yB.platform)()!="win32"&&(jf=require("node-unix-socket").createReuseportFd)});var DB=g((yhe,CB)=>{"use strict";var ure=require("cluster"),To=Z();To.initSync();var IB=M(),Rhe=require("util"),Bs=Y(),Ahe=require("fs"),lre=require("fastify"),Ohe=zc(),_re=require("@fastify/cors"),dre=require("@fastify/compress"),fre=require("@fastify/static"),Ere=Ng(),hre=require("path"),{PACKAGE_ROOT:mre}=M(),pre=ms(),Sre=J(),Tre=Mr(),gre=Gi(),{server:Rre}=(Zt(),te(yi)),{node_request_key:bhe}=(Xf(),te(dR)),{authHandler:Are,handlePostRequest:Ore,serverErrorHandler:bre,reqBodyValidationHandler:Nre}=Kf(),Nhe=require("net"),{registerContentHandlers:yre}=(ha(),te(_v)),wre=6e4,Ire=1024*1024*1024,Cre="TRUE",{CONFIG_PARAMS:nl}=IB,Pa;CB.exports={hdbServer:wB,start:wB};async function wB(e){try{Bs.info("In Fastify server"+process.cwd()),Bs.info(`Running with NODE_ENV set as: ${process.env.NODE_ENV}`),Bs.debug(`HarperDB server process ${process.pid} starting up.`),global.clustering_on=!1,global.isMaster=ure.isMaster,await Dre();let t=e.securePort>0;Pa=Lre(t),await Pa.ready(),e||(e={}),e.isOperationsServer=!0;try{Rre.http(Pa.server,e),Pa.server.closeIdleConnections||await Pa.listen({port:0,host:"::"})}catch(r){throw Pa.close(),Bs.error(r),Bs.error("Error configuring operations server"),r}}catch(t){console.error(`Failed to build server on ${process.pid}`,t),Bs.fatal(t),process.exit(1)}}a(wB,"operationsServer");async function Dre(){Bs.trace("Configuring HarperDB process."),pre.setSchemaDataToGlobal(),await Tre.setUsersToGlobal(),await gre.getLicense()}a(Dre,"setUp");function Lre(e){Bs.debug(`HarperDB process starting to build ${e?"HTTPS":"HTTP"} server.`);let t=Mre(e),r=lre(t);r.server.headersTimeout=Pre(),r.setErrorHandler(bre);let n=Ure();n&&r.register(_re,n),r.register(function(i,o,c){i.setNotFoundHandler(function(u,_){r.server.emit("unhandled",u.raw,_.raw)}),c()}),r.register(Ere),r.register(dre),r.register(fre,{root:hre.join(mre,"studio/build-local")}),yre(r);let s=To.get(IB.HDB_SETTINGS_NAMES.LOCAL_STUDIO_ON);return r.get("/",function(i,o){return!Sre.isEmpty(s)&&s.toString().toLowerCase()==="true"?o.sendFile("index.html"):o.sendFile("running.html")}),r.post("/",{preValidation:[Nre,Are],config:{isOperation:!0}},async function(i,o){return i.body?.operation?.startsWith("restart")&&o.header("Connection","close"),Ore(i,o)}),r.get("/health",()=>"HarperDB is running."),Bs.debug(`HarperDB process starting up ${e?"HTTPS":"HTTP"} server listener.`),r}a(Lre,"buildServer");function Mre(e){let t=To.get(nl.OPERATIONSAPI_NETWORK_TIMEOUT),r=To.get(nl.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT);return{bodyLimit:Ire,connectionTimeout:t,keepAliveTimeout:r,forceCloseConnections:!0,return503OnClosing:!1,https:e}}a(Mre,"getServerOptions");function Ure(){let e=To.get(nl.OPERATIONSAPI_NETWORK_CORS),t=To.get(nl.OPERATIONSAPI_NETWORK_CORSACCESSLIST),r;return e&&(e===!0||e.toUpperCase()===Cre)&&(r={origin:!0,allowedHeaders:["Content-Type","Authorization","Accept"],credentials:!1},t&&t.length>0&&t[0]!==null&&t[0]!=="*"&&(r.origin=(n,s)=>s(null,t.indexOf(n)!==-1))),r}a(Ure,"getCORSOpts");function Pre(){return To.get(nl.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT)??wre}a(Pre,"getHeaderTimeoutConfig")});var FB=g((Lhe,qB)=>{"use strict";var{decode:vre}=require("msgpackr"),{isMainThread:Ihe,parentPort:Bre,threadId:Che}=require("worker_threads"),ER=ft(),Hs=tt(),Hre=M(),pi=Y(),LB=Z(),UB=M();Ze();var xre=hs(),{recordAction:qre,recordActionBinary:Fre}=(Rs(),te(Zc)),{publishToStream:Gre}=ER,{ConsumerEvents:kre}=require("nats"),Dhe={durable:Hs.WORK_QUEUE_CONSUMER_NAMES.durable_name,queue:Hs.WORK_QUEUE_CONSUMER_NAMES.deliver_group},Vre,$re,Yre,PB,vB;qB.exports={initialize:hR,workQueueListener:xB,setSubscription:Kre,setIgnoreOrigin:Qre,getDatabaseSubscriptions:Wre};async function hR(){vB=!0,pi.notify("Starting clustering ingest service.");let{connection:e,jsm:t,js:r}=await ER.getNATSReferences();Vre=e,$re=e.info.server_name,Yre=t,PB=r}a(hR,"initialize");var eE=new Map;function Kre(e,t,r){let n=eE.get(e);n||eE.set(e,n=new Map),n.set(t,r),vB||hR().then(xB)}a(Kre,"setSubscription");function Wre(){return eE}a(Wre,"getDatabaseSubscriptions");var BB;function Qre(e){BB=e}a(Qre,"setIgnoreOrigin");var HB=100,MB=new Array(HB),Zf=0;async function xB(){let e=await PB.consumers.get(Hs.WORK_QUEUE_CONSUMER_NAMES.stream_name,Hs.WORK_QUEUE_CONSUMER_NAMES.durable_name),t=!1,r;for(Bre?.on("message",async n=>{let{type:s}=n;s===UB.ITC_EVENT_TYPES.SHUTDOWN&&(t=!0,r&&r.close?.()&&r.close())});!t;){r=await e.consume(),(async()=>{for await(let n of await r.status())if(n.type===kre.HeartbeatsMissed){let s=n.data;pi.trace(`${s} clustering ingest consumer heartbeats missed`),s===2&&(pi.warn("Restarting clustering ingest consumer due to missed heartbeat threshold being met"),r.stop())}})();try{for await(let n of r)await MB[Zf],MB[Zf]=zre(n).catch(s=>{pi.error(s)}),++Zf>=HB&&(Zf=0)}catch(n){pi.error("Error consuming clustering ingest, restarting consumer",n)}ER.clearClientCache(),await hR()}}a(xB,"workQueueListener");async function zre(e){let t=vre(e.data);qre(e.data.length,"bytes-received",e.subject,t.operation,"ingest");let r=e.headers,n=!1,s=LB.get(Hre.CONFIG_PARAMS.CLUSTERING_NODENAME);r.has(Hs.MSG_HEADERS.TRANSACTED_NODES)&&r.values(Hs.MSG_HEADERS.TRANSACTED_NODES).indexOf(s)>-1&&(n=!0);let i=r.get(Hs.MSG_HEADERS.ORIGIN);if(n||(n=i===s&&!BB),Fre(n,"echo",e.subject,t.operation,"ingest"),n){e.ack();return}r.append(Hs.MSG_HEADERS.TRANSACTED_NODES,s);try{let{operation:o,schema:c,next:u,table:_,records:l,hash_values:d,__origin:f,expiresAt:E}=t;pi.trace("processing message:",o,c,_,(l?"records: "+l.map(b=>b?.id):"")+(d?"ids: "+d:""),"with sequence:",e.seq),pi.trace(`messageProcessor nats msg id: ${e.headers.get(Hs.MSG_HEADERS.NATS_MSG_ID)}`);let h;l||(l=d);let{timestamp:p,user:S,node_name:T}=f||{},A=eE.get(c)?.get(_);if(!A)throw new Error("Missing table for replication message",_);if(o==="define_schema")t.type=o,A.send(t);else if(l.length===1&&!u)A.send({type:fR(o),value:l[0],id:d?.[0],expiresAt:E,timestamp:p,table:_,onCommit:h,user:S,nodeName:T});else{let b=l.map((H,q)=>({type:fR(o),value:H,expiresAt:E,id:d?.[q],table:_}));for(;u;)b.push({type:fR(u.operation),value:u.record,expiresAt:u.expiresAt,id:u.id,table:u.table}),u=u.next;A.send({type:"transaction",writes:b,table:_,timestamp:p,onCommit:h,user:S,nodeName:T})}LB.get(UB.CONFIG_PARAMS.CLUSTERING_REPUBLISHMESSAGES)!==!1&&Gre(e.subject.split(".").slice(0,-1).join("."),xre.createNatsTableStreamName(c,_),e.headers,e.data)}catch(o){pi.error(o)}e.ack()}a(zre,"messageProcessor");function fR(e){switch(e){case"insert":case"upsert":case"update":return"put"}return e}a(fR,"convertOperation")});var oE={};Ve(oE,{disableNATS:()=>jre,publishToStream:()=>iE,setNATSReplicator:()=>mR,setPublishToStream:()=>Xre,setSubscription:()=>gR,start:()=>Jre});function Jre(){rE.default.get(nE.default.CONFIG_PARAMS.CLUSTERING_ENABLED)&&ene()}function jre(e=!0){YB=e}function Xre(e,t){iE=e,gR=t}function ene(){if(YB||process.env._DISABLE_NATS)return;let e=yn(),t=Object.keys(e);t.push("system");for(let r of t){let n=e[r];for(let s in n){let i=n[s];mR(s,r,i)}}AR((r,n)=>{mR(r.tableName,r.databaseName,r),n&&WB(r)}),!GB&&(GB=!0)}function mR(e,t,r){if(!r)return console.error(`Attempt to replicate non-existent table ${e} from database ${t}`);if(r.sources.some(s=>s?.isNATSReplicator))return;r.sourcedFrom(class extends Bt{static{a(this,"NATSReplicator")}put(i){return n(this.getContext()).addWrite(t,{operation:"put",table:e,id:this[Ue],record:i})}delete(){return n(this.getContext()).addWrite(t,{operation:"delete",table:e,id:this[Ue]})}publish(i){return n(this.getContext()).addWrite(t,{operation:"publish",table:e,id:this[Ue],record:i})}patch(i){return n(this.getContext()).addWrite(t,{operation:"patch",table:e,id:this[Ue],record:i})}invalidate(){n(this.getContext()).addWrite(t,{operation:"invalidate",table:e,id:this[Ue]})}static defineSchema(i){WB(i)}static subscribe(){let i=new Tn;return gR(t,e,i),i}static subscribeOnThisThread(i){return i<Zre}static isEqual(i){return i.isNATSReplicator}static isNATSReplicator=!0;static shouldReceiveInvalidations=!0},{intermediateSource:!0});function n(s){let i=s?.transaction?.nats;if(!i)if(s?.transaction){s.transaction.nats=i=new tE(s.transaction,s);let o=s.transaction;for(;o.next;)o=o.next;o.next=s.transaction.nats,i.user=s.user,i.context=s}else i=KB;return i}a(n,"getNATSTransaction")}function WB(e){let t=rE.default.get(nE.default.CONFIG_PARAMS.CLUSTERING_NODENAME);iE(`${SR.SUBJECT_PREFIXES.TXN}.${e.databaseName}.${e.tableName}`,(0,TR.createNatsTableStreamName)(e.databaseName,e.tableName),void 0,{operation:"define_schema",schema:e.databaseName,table:e.tableName,attributes:e.attributes,__origin:{timestamp:Date.now(),node_name:t}})}var kB,SR,TR,VB,$B,rE,nE,sE,YB,iE,gR,Zre,KB,GB,tE,pR,RR=Oe(()=>{be();gn();kB=B(ft()),SR=B(tt()),TR=B(hs());_c();VB=B(FB()),$B=B(Ir()),rE=B(Z()),nE=B(M()),sE=B(Y());a(Jre,"start");a(jre,"disableNATS");iE=kB.publishToStream,gR=VB.setSubscription;a(Xre,"setPublishToStream");Zre=2;a(ene,"assignReplicationSource");a(mR,"setNATSReplicator");a(WB,"publishSchema");tE=class{constructor(t,r){this.transaction=t;this.options=r}static{a(this,"NATSTransaction")}user;writes_by_db=new Map;addWrite(t,r){r.expiresAt=this.context?.expiresAt;let n=this.writes_by_db.get(t);n||this.writes_by_db.set(t,n=[]),n.push(r)}commit({timestamp:t}){let r=rE.default.get(nE.default.CONFIG_PARAMS.CLUSTERING_NODENAME),n=[];for(let[s,i]of this.writes_by_db){let o=[],c=[],u,_;for(let l of i){let d=l.table,f=l.operation=="put"?"upsert":l.operation;u||(sE.trace(`Sending transaction event ${f}`),_=u={operation:f,schema:s,table:d,__origin:{user:this.user?.username,timestamp:t,node_name:r}},u.hash_values=c,f!=="delete"&&f!=="invalidate"&&(u.records=o)),u.table===d&&u.operation===f?(o.push(l.record),c.push(l.id)):_=_.next={operation:f,table:d,id:l.id,record:l.record},l.expiresAt&&(_.expiresAt=l.expiresAt)}u&&n.push(iE(`${SR.SUBJECT_PREFIXES.TXN}.${s}.${u.table}`,(0,TR.createNatsTableStreamName)(s,u.table),void 0,u)?.catch(l=>{throw sE.error("An error has occurred trying to replicate transaction",u,l),l.statusCode=504,l}))}return Promise.all(n)}},pR=class extends tE{static{a(this,"ImmmediateNATSTransaction")}constructor(){super({get timestamp(){return(0,$B.getNextMonotonicTime)()}})}addWrite(t,r){super.addWrite(t,r),this.commit({})}};KB=new pR});var aH=g(go=>{"use strict";var{isMainThread:tne,parentPort:ol,threadId:sl}=require("worker_threads"),{Socket:rne,createServer:nne}=require("net"),{createServer:sne,IncomingMessage:ine}=require("http"),{createServer:one}=require("https"),{readFileSync:va,unlinkSync:QB,existsSync:ane}=require("fs"),Un=Y(),He=Z(),Sr=M(),{server:uE}=(Zt(),te(yi)),{WebSocketServer:cne}=require("ws"),{createServer:une}=require("tls"),{getTicketKeys:lne,restartNumber:_ne,getWorkerIndex:zB}=Ze(),{Headers:eH}=($d(),te(vU)),{recordAction:il,recordActionBinary:dne}=(Rs(),te(Zc)),{Request:tH,createReuseportFd:JB}=(Xf(),te(dR)),{checkMemoryLimit:fne}=Gi(),rH=require("tls"),jB=rH.createSecureContext;rH.createSecureContext=function(e){if(!e.cert||!e.key)return jB(e);let t={...e};delete t.key,delete t.cert;let r=jB(t);return r.context.setCert(e.cert),r.context.setKey(e.key,void 0),r};if(process.env.DEV_MODE)try{require("inspector").open(9229)}catch(e){_ne<=1&&Un.trace("Could not start debugging on port 9229, you may already be debugging:",e.message)}process.on("uncaughtException",e=>{e.code!=="ECONNRESET"&&e.message!=="write EIO"&&console.error("uncaughtException",e)});var{HDB_SETTINGS_NAMES:xhe,CONFIG_PARAMS:Ene}=Sr;He.initSync();var hne=He.get(Ene.HTTP_SESSIONAFFINITY),ss={};go.registerServer=wR;go.httpServer=IR;go.deliverSocket=yR;go.startServers=nH;go.when_components_loaded=null;uE.http=IR;uE.request=Tne;uE.socket=gne;uE.ws=Rne;var OR={},aE={},mne,Si={},cE={},pne=[],bR=[];function nH(){return go.when_components_loaded=CR().loadRootComponents(!0).then(()=>{ol?.on("message",t=>{let{port:r,fd:n,data:s}=t;if(n)yR(n,r,s);else if(t.requestId)Sne(t);else if(t.type===Sr.ITC_EVENT_TYPES.SHUTDOWN){Un.trace("received shutdown request",sl);for(let i in ss){let o=ss[i],c;o.closeIdleConnections&&(setInterval(()=>{o.closeIdleConnections()},25).unref(),setTimeout(()=>{o.closeAllConnections(),Un.info("Closed all http connections",i,sl)},4e3).unref()),o.close?.(()=>{if(He.get(Sr.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET)&&zB()==0)try{QB(He.get(Sr.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET))}catch{}clearInterval(c),setTimeout(()=>{console.log("forced close server",i,sl),o.cantCleanupProperly||Un.warn("Had to forcefully exit the thread",sl),process.exit(0)},5e3).unref()})}if(process.env.DEV_MODE)try{require("inspector").close()}catch(i){console.error("Could not close debugger",i)}}}).ref();let e=[];if(JB&&!hne)for(let t in ss){let r=ss[t];if(isNaN(t)&&zB()==0){ane(t)&&QB(t),e.push(new Promise((s,i)=>{r.listen({path:t},()=>{s(),Un.info("Domain socket listening on "+t)}).on("error",i)}));continue}let n;try{n=JB(+t,"::")}catch(s){console.error(`Unable to bind to port ${t}`,s);continue}e.push(new Promise((s,i)=>{r.listen({fd:n},()=>{s(),Un.trace("Listening on port "+t,sl)}).on("error",i)}))}Promise.all(e).then(()=>{ol?.postMessage({type:Sr.ITC_EVENT_TYPES.CHILD_STARTED})})})}a(nH,"startServers");tne||nH();function yR(e,t,r){let n=e?.read?e:new rne({fd:e,readable:!0,writable:!0,allowHalfOpen:!0}),s=ss[t];if(s.isSecure&&(n.startTime=performance.now()),s)typeof s=="function"?s(n):s.emit("connection",n),r&&n.emit("data",r);else{let i=a(o=>{setTimeout(()=>{let c=ss[t];c?(typeof c=="function"?c(n):c.emit("connection",n),r&&n.emit("data",r)):o<5?i(o+1):(Un.error(`Server on port ${t} was not registered`),n.destroy())},1e3)},"retry");i(1)}return n}a(yR,"deliverSocket");var XB=new Map;function Sne(e){let{port:t,event:r,data:n,requestId:s}=e,i;switch(i=XB.get(s),r){case"connection":i=yR(void 0,t),XB.set(s,i),i.write=(c,u,_)=>(ol.postMessage({requestId:s,event:"data",data:c.toString("latin1")}),_&&_(),!0),i.end=(c,u,_)=>(ol.postMessage({requestId:s,event:"end",data:c?.toString("latin1")}),_&&_(),!0);let o=i.destroy;i.destroy=()=>{o.call(i),ol.postMessage({requestId:s,event:"destroy"})};break;case"data":i._readableState.destroyed||i.emit("data",Buffer.from(n,"latin1"));break;case"drain":i._readableState.destroyed||i.emit("drain",{});break;case"end":i._readableState.destroyed||i.emit("end",{});break;case"error":i._readableState.destroyed||i.emit("error",{});break}}a(Sne,"proxyRequest");function wR(e,t,r=!0){!+t&&t!==He.get(Sr.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET)&&(t=parseInt(He.get(Sr.CONFIG_PARAMS.HTTP_PORT),10));let n=ss[t];if(n){let s=n.lastServer||n;if(s===e)throw new Error(`Can not register the same server twice for the same port ${t}`);if(r&&!!s.sessionIdContext!=!!e.sessionIdContext&&+t)throw new Error(`Can not mix secure HTTPS and insecure HTTP on the same port ${t}`);s.off("unhandled",ZB),s.on("unhandled",(i,o)=>{e.cantCleanupProperly&&(n.cantCleanupProperly=!0),e.emit("request",i,o)}),n.lastServer=e}else ss[t]=e;e.on("unhandled",ZB)}a(wR,"registerServer");function sH(e){let t=[],r=parseInt(e?.securePort);return r&&t.push({port:r,secure:!0}),r=parseInt(e?.port),r&&t.push({port:r,secure:!1}),t.length===0&&(t=[],He.get(Sr.CONFIG_PARAMS.HTTP_PORT)!=null&&t.push({port:He.get(Sr.CONFIG_PARAMS.HTTP_PORT),secure:He.get(Sr.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HTTPS)}),He.get(Sr.CONFIG_PARAMS.HTTP_SECUREPORT)!=null&&t.push({port:He.get(Sr.CONFIG_PARAMS.HTTP_SECUREPORT),secure:!0})),e?.isOperationsServer&&He.get(Sr.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET)&&t.push({port:He.get(Sr.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET),secure:!1}),t}a(sH,"getPorts");function IR(e,t){for(let{port:r,secure:n}of sH(t))iH(r,n,t?.isOperationsServer),typeof e=="function"?bR[t?.runFirst?"unshift":"push"]({listener:e,port:t?.port||r}):(e.isSecure=n,wR(e,r,!1)),cE[r]=NR(bR,r),mne=NR(pne,r)}a(IR,"httpServer");function iH(e,t,r){if(!Si[e]){let n=r?"operationsApi_network":"http",s={keepAliveTimeout:He.get(n+"_keepAliveTimeout"),headersTimeout:He.get(n+"_headersTimeout"),requestTimeout:He.get(n+"_timeout")},i=He.get(n+"_mtls"),o=He.get(n+"_mtls_required");if(t){n=r?"operationsApi_":"";let u=He.get(n+"tls_privateKey"),_=He.get(n+"tls_certificate"),l=He.get(n+"tls_certificateAuthority");Object.assign(s,{allowHTTP1:!0,key:va(u),ciphers:He.get("tls_ciphers"),cert:va(_),ca:l&&va(l),rejectUnauthorized:!!o,requestCert:!!i,ticketKeys:lne()})}let c=fne();Si[e]=(t?one:sne)(s,async(u,_)=>{try{let d=performance.now(),f=new tH(u,_);r&&(f.isOperationsServer=!0);let E=await cE[e](f);if(!E){if(f._nodeResponse.statusCode)return;E=oH(f)}if(c?E.headers?.set?.("Server","Unlicensed HarperDB, this should only be used for educational and development purposes"):E.headers?.set?.("Server","HarperDB"),E.status===-1){for(let q of E.headers||[])_.setHeader(q[0],q[1]);return u.baseRequest=f,_.baseResponse=E,Si[e].emit("unhandled",u,_)}let h=E.status||200,p=performance.now(),S=p-d,T=E.body,A;if(!E.handlesHeaders){let q=E.headers||new eH;if(T?T.length>=0&&(typeof T=="string"?q.set("Content-Length",Buffer.byteLength(T)):q.set("Content-Length",T.length),A=!0):(q.set("Content-Length","0"),A=!0),q.append){let v=`hdb;dur=${S.toFixed(2)}`;E.wasCacheMiss&&(v+=", miss"),q.append("Server-Timing",v,!0)}_.writeHead(h,q&&(q[Symbol.iterator]?Array.from(q):q)),A&&_.end(T)}let b=f.handlerPath,H=f.method;if(il(S,"duration",b,H,E.wasCacheMiss==null?void 0:E.wasCacheMiss?"cache-miss":"cache-hit"),dne(h<400,"success",b,H),!A)if(T?.pipe){T.pipe(_),T.destroy&&_.on("close",()=>{T.destroy()});let q=0;T.on("data",v=>{q+=v.length}),T.on("end",()=>{il(performance.now()-p,"transfer",b,H),il(q,"bytes-sent",b,H)})}else T?.then?T.then(q=>{_.end(q)},l):_.end(T)}catch(d){l(d)}function l(d){let f=d.headers;_.writeHead(d.statusCode||500,f&&(f[Symbol.iterator]?Array.from(f):f)),_.end(d.toString()),d.statusCode?d.statusCode===500?Un.warn(d):Un.info(d):Un.error(d)}a(l,"onError")}),i&&(Si[e].mtlsConfig=i),t&&(Si[e].on("secureConnection",u=>{u._parent.startTime&&il(performance.now()-u._parent.startTime,"tls-handshake",e),il(u.isSessionReused(),"tls-reused",e)}),Si[e].isSecure=!0),wR(Si[e],e)}return Si[e]}a(iH,"getHTTPServer");function NR(e,t){let r=oH;for(let n=e.length;n>0;){let{listener:s,port:i}=e[--n];if(i===t||i==="all"){let o=r;r=a(c=>s(c,o),"next_callback")}}return r}a(NR,"makeCallbackChain");function oH(e){return e.user&&(e._nodeRequest.user=e.user),{status:-1,body:"Not found",headers:new eH}}a(oH,"unhandled");function Tne(e,t){IR(e,{requestOnly:!0,...t})}a(Tne,"onRequest");function gne(e,t){let r;if(t.securePort){let n=He.get("tls_privateKey"),s=He.get("tls_certificate"),i=t.mtls?.certificateAuthority||He.get("tls_certificateAuthority");r=une({ciphers:He.get("tls_ciphers"),key:va(n),cert:va(s),ca:i&&va(i),rejectUnauthorized:!!t.mtls?.required,requestCert:!!t.mtls},e),ss[t.securePort]=r}return t.port&&(r=nne(e),ss[t.port]=r),r}a(gne,"onSocket");Object.defineProperty(ine.prototype,"upgrade",{get(){return"connection"in this.headers&&"upgrade"in this.headers&&this.headers.connection.startsWith("Upgrade")&&this.headers.upgrade.toLowerCase()=="websocket"},set(e){}});function Rne(e,t){let r;for(let{port:n,secure:s}of sH(t)){aE[n]||(aE[n]=new cne({server:r=iH(n,s)}),aE[n].on("connection",async(c,u)=>{try{let _=new tH(u);_.isWebSocket=!0;let l=cE[n](_),d=u.headers["sec-websocket-protocol"]||"",f=OR[n];if(d){let E;for(let h=0;h<f.length;h++){let p=f[h];p.protocol===d&&(E=!0,p.listener(c,_,l))}if(E)return}for(let E=0;E<f.length;E++){let h=f[E];h.protocol||h.listener(c,_,l)}}catch(_){Un.warn("Error handling WebSocket connection",_)}}),aE[n].on("error",c=>{console.log("Error in setting up WebSocket server",c)}));let i=t?.subProtocol||"",o=OR[n];o||(o=OR[n]=[]),o.push({listener:e,protocol:i}),cE[n]=NR(bR,n)}return r}a(Rne,"onWebSocket");function ZB(e,t){t.writeHead(404),t.end(`Not found
|
|
27
|
-
`)}a(ZB,"defaultNotFound")});async function _H({clientId:e,user:t,clean:r,will:n}){let s;if(e&&!r){let i=await DR.getResource(e,{});s=new UR(e,t,i),i&&(s.sessionWasPresent=!0)}else{if(e){let i=await DR.get(e);i&&i.delete()}s=new _E(e,t)}return n&&(n.id=e,n.user={username:t?.username},al.put(n)),s}function LR(){return lE++,lE>65500&&(lE=1),lE}function MR(e,t,r=e){let{topic:n,retain:s}=e;e.data=t,e.async=!0,e.authorize=!0;let i=li.getMatch(n);if(!i)throw new Error(`Can not publish to topic ${n} as it does not exist, no resource has been defined to handle this topic`);e.url=i.relativeURL;let o=i.Resource;return We(r,()=>s?t===void 0?o.delete(e,r):o.put(e,e.data,r):o.publish(e,e.data,r))}var cH,Ro,uH,lH,DR,al,lE,_E,UR,dH=Oe(()=>{be();Du();cH=B(Ir()),Ro=B(Y());Wi();uH=B(Ze()),lH=B(aH());Zt();DR=ot({database:"system",table:"hdb_durable_session",attributes:[{name:"id",isPrimaryKey:!0},{name:"subscriptions",type:"array",elements:{attributes:[{name:"topic"},{name:"qos"},{name:"startTime"},{name:"acks"}]}}]}),al=ot({database:"system",table:"hdb_session_will",attributes:[{name:"id",isPrimaryKey:!0},{name:"topic",type:"string"},{name:"data"},{name:"qos",type:"number"},{name:"retain",type:"boolean"},{name:"user",type:"any"}]});(0,uH.getWorkerIndex)()===0&&(async()=>{await lH.when_components_loaded,await new Promise(e=>setTimeout(e,2e3));for await(let e of al.search({})){let t=e.data,r=Object.assign({},e);r.user?.username&&(r.user=await Xe.getUser(r.user.username)),We(r,()=>{try{MR(r,t)}finally{al.delete(e.id,r)}})}})();a(_H,"getSession");lE=1;a(LR,"getNextMessageId");_E=class{static{a(this,"SubscriptionsSession")}listener;sessionId;user;subscriptions=[];awaitingAcks;sessionWasPresent;constructor(t,r){this.sessionId=t,this.user=r}async addSubscription(t,r,n){let{topic:s,rh:i,startTime:o}=t,c=s.indexOf("?"),u,_;if(c>-1?(u=s.slice(c),_=s.slice(0,c)):_=s,!_)throw new Error("No topic provided");if(_.indexOf(".")>-1)throw new Error("Dots are not allowed in topic names");let l=this.subscriptions.find(T=>T.topic===s),d;l?(d=i>0,l.end(),this.subscriptions.splice(this.subscriptions.indexOf(l),1)):d=i===2;let f={search:u,async:!0,authorize:!0,user:this.user,startTime:o,omitCurrent:d,url:""};o&&(0,Ro.trace)("Resuming subscription from",s,"from",o);let E=li.getMatch(_);if(!E){let T=new Error(`The topic ${s} does not exist, no resource has been defined to handle this topic`);throw T.statusCode=404,T}if(f.url=E.relativeURL,f.url.indexOf("+")>-1||f.url.indexOf("#")>-1){let T=f.url.slice(1);if(T.indexOf("#")>-1&&T.indexOf("#")!==T.length-1)throw new Error("Multi-level wildcards can only be used at the end of a topic");if(f.isCollection=!0,T.indexOf("+")===T.length-1)f.onlyChildren=!0,f.url="/"+T.slice(0,T.length-1);else{let A=T.split("/"),b;for(let v=0;v<A.length;v++)if(A[v].indexOf("+")>-1)if(A[v]==="+")b=!0;else throw new Error("Single-level wildcards can only be used as a topic level (between or after slashes)");if(n&&b)throw new Error("Filters can not be combined");let H=!0;A[A.length-1]==="#"&&(A.length--,H=!1),b&&(n=a(v=>{let P=v.id;if(!Array.isArray(P)||H&&P.length!==A.length)return!1;for(let z=0;z<A.length;z++)if(A[z]!=="+"&&A[z]!==P[z])return!1;return!0},"filter"));let q=A.indexOf("+");f.url="/"+(q>-1?A.slice(0,q):A).concat("").join("/")}}let h=E.path,p=E.Resource,S=await We(f,async()=>{let T=await p.subscribe(f);if(!T)throw new Error(`No subscription was returned from subscribe for topic ${s}`);if(!T[Symbol.asyncIterator])throw new Error(`Subscription is not (async) iterable for topic ${s}`);return(async()=>{for await(let A of T)try{let b;if(A.type&&A.type!=="put"&&A.type!=="delete"&&A.type!=="message"&&A.type!=="patch"||n&&!n(A))continue;r?(A.topic=s,b=this.needsAcknowledge(A)):(A.acknowledge?.(),b=LR());let H=A.id;Array.isArray(H)&&(H=Ea(H)),H==null&&(H=""),this.listener(h+"/"+H,A.value,b,t)}catch(b){(0,Ro.warn)(b)}})(),T});return S.topic=s,S.qos=t.qos,this.subscriptions.push(S),S}resume(){}needsAcknowledge(t){let r=LR();return t.acknowledge&&(this.awaitingAcks||(this.awaitingAcks=new Map),this.awaitingAcks.set(r,t.acknowledge)),r}acknowledge(t){let r=this.awaitingAcks?.get(t);r&&(this.awaitingAcks.delete(t),r())}async removeSubscription(t){let r=this.subscriptions.find(n=>n.topic===t);if(r)return r.end(),!0}async publish(t,r){return t.user=this.user,MR(t,r)}setListener(t){this.listener=t}disconnect(t){let r={};We(r,async()=>{if(!t){let n=await al.get(this.sessionId,r);n?.doesExist()&&await MR(n,n.data,r)}await al.delete(this.sessionId,r)}).catch(n=>{(0,Ro.warn)(`Error publishing MQTT will for ${this.sessionId}`,n)});for(let n of this.subscriptions)n.end();this.subscriptions=[]}};a(MR,"publish");UR=class extends _E{static{a(this,"DurableSubscriptionsSession")}sessionRecord;constructor(t,r,n){super(t,r),this.sessionRecord=n||{id:t,subscriptions:[]}}async resume(){for(let t of this.sessionRecord.subscriptions||[])await this.resumeSubscription({omitCurrent:!0,topic:t.topic,qos:t.qos,startTime:t.startTime},!0,t.acks?r=>!t.acks.includes(r.timestamp):null)}resumeSubscription(t,r,n){return super.addSubscription(t,r,n)}needsAcknowledge(t){this.awaitingAcks||(this.awaitingAcks=new Map);let r=LR(),n={topic:t.topic,timestamp:t.timestamp};return t.acknowledge&&(n.acknowledge=t.acknowledge),this.awaitingAcks.set(r,n),r}acknowledge(t){let r=this.awaitingAcks.get(t);this.awaitingAcks.delete(t),r.acknowledge?.();let n=r.topic;for(let[,s]of this.awaitingAcks)if(s.topic===n&&s.timestamp<r.timestamp){for(let i of this.sessionRecord.subscriptions)if(i.topic===n){i.acks||(i.acks=[]),i.acks.push(r.timestamp),(0,Ro.trace)("Received ack",n,r.timestamp),this.sessionRecord.update();return}}for(let s of this.sessionRecord.subscriptions)s.topic===n&&(s.startTime=r.timestamp);this.sessionRecord.update()}async addSubscription(t,r){await this.resumeSubscription(t,r);let{qos:n,startTime:s}=t;return n>0&&!s&&(this.sessionRecord.subscriptions=this.subscriptions.map(i=>{let o=i.startTime;return o||(o=i.startTime=(0,cH.getNextMonotonicTime)()),(0,Ro.trace)("Added durable subscription",i.topic,o),{qos:i.qos,topic:i.topic,startTime:o}}),DR.put(this.sessionRecord)),t.qos}}});var PR={};Ve(PR,{bypassAuth:()=>Ane,start:()=>One});function Ane(){pH=!0}function One({server:e,port:t,network:r,webSocket:n,securePort:s,requireAuthentication:i}){let o=e.mqtt={requireAuthentication:i,sessions:new Set},c,u=r?.mtls;return n&&(c=e.ws((_,l,d)=>{if(_.protocol==="mqtt"){let{onMessage:f,onClose:E}=hH(_,(h,p)=>{if(_.send(h),p&&_._socket.writableNeedDrain)return new Promise(S=>this._socket.once("drain",S))},l,Promise.resolve(d).then(()=>l?.user),o);_.on("message",f),_.on("close",E),_.on("error",h=>{(0,Tr.info)("WebSocket error",h)})}},Object.assign({subProtocol:"mqtt"},n))),(t||s)&&(c=e.socket(async _=>{let l;if(u){if(_.authorized)try{let E=u.user;E!==null&&((E===void 0||E==="Common Name"||E==="CN")&&(E=_.getPeerCertificate().subject.CN),l=await e.getUser(E,null,null))}catch(E){(0,Tr.error)(E)}else if(u.required)return(0,Tr.info)(`Unauthorized connection attempt, no authorized client certificate provided, error: ${_.authorizationError}`),_.end()}!l&&pH&&_.remoteAddress.includes("127.0.0.1")&&(l=await(0,mH.getSuperUser)());let{onMessage:d,onClose:f}=hH(_,E=>_.write(E),null,l,o);_.on("data",d),_.on("close",f),_.on("error",E=>{(0,Tr.info)("Socket error",E)})},{port:t,securePort:s,mtls:u})),c}function hH(e,t,r,n,s){EH||(EH=!0,Xc(d=>{dE>0&&d.push({metric:"mqtt-connections",connections:dE,byThread:!0})}));let i;dE++;let o,c={protocolVersion:4},u=(0,EE.parser)({protocolVersion:5});function _(d){u.parse(d)}a(_,"onMessage");function l(){dE--,i||(i=!0,o?.disconnect(),s.sessions.delete(o),en(!1,"connection","mqtt","disconnect"))}return a(l,"onClose"),u.on("packet",async d=>{n?.then&&(n=await n),o?.then&&await o;try{switch(d.cmd){case"connect":if(c.protocolVersion=d.protocolVersion,d.username)try{n=await Xe.getUser(d.username,d.password.toString(),r),(0,fE.get)(is.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)&&fH.notify({username:n.username,status:is.AUTH_AUDIT_STATUS.SUCCESS,type:is.AUTH_AUDIT_TYPES.AUTHENTICATION,auth_strategy:"MQTT",remote_address:e.remoteAddress})}catch{return(0,fE.get)(is.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGFAILED)&&fH.error({username:n.username,status:is.AUTH_AUDIT_STATUS.FAILURE,type:is.AUTH_AUDIT_TYPES.AUTHENTICATION,auth_strategy:"mqtt",remote_address:e.remoteAddress}),f({cmd:"connack",reasonCode:4,returnCode:134})}if(!n&&s.requireAuthentication)return en(!1,"connection","mqtt","connect"),f({cmd:"connack",reasonCode:4,returnCode:134});try{if(s.authorizeClient?.(d,n),d.will){let b=e.deserialize||(e.deserialize=_o(r?.headers.get?.("content-type")));d.will.data=d.will.payload?.length>0?b(d.will.payload):void 0,delete d.will.payload}o=_H({user:n,...d}),o=await o,s.sessions.add(o)}catch(b){return(0,Tr.error)(b),en(!1,"connection","mqtt","connect"),f({cmd:"connack",reasonCode:b.code||5,returnCode:b.code||128})}en(!0,"connection","mqtt","connect"),f({cmd:"connack",sessionPresent:o.sessionWasPresent,reasonCode:0,returnCode:0}),o.setListener((b,H,q,v)=>{try{let P=b.indexOf("/",1),z=P>0?b.slice(0,P):b;f({cmd:"publish",topic:b,payload:E(H),messageId:q||Math.floor(Math.random()*1e8),qos:v.qos},z)}catch(P){(0,Tr.error)(P),o?.disconnect(),s.sessions.delete(o)}}),o.sessionWasPresent&&await o.resume();break;case"subscribe":let h=[];for(let b of d.subscriptions){let H;try{H=(await o.addSubscription(b,b.qos>=1)).qos||0}catch(q){(0,Tr.error)(q),H=c.protocolVersion<5?128:q.statusCode===403?135:q.statusCode===404?143:128}h.push(H)}await o.committed,f({cmd:"suback",granted:h,messageId:d.messageId});break;case"unsubscribe":{let b=[];for(let H of d.unsubscriptions)b.push(o.removeSubscription(H)?0:17);f({cmd:"unsuback",granted:b,messageId:d.messageId});break}case"pubrel":f({cmd:"pubcomp",messageId:d.messageId,reasonCode:0});return;case"publish":let p=d.qos===2?"pubrec":"puback",S=e.deserialize||(e.deserialize=_o(r?.headers.get?.("content-type"))),T=d.payload?.length>0?S(d.payload):void 0,A;try{A=await o.publish(d,T)}catch(b){(0,Tr.warn)(b),d.qos>0&&f({cmd:p,messageId:d.messageId,reasonCode:128},d.topic);break}d.qos>0&&f({cmd:p,messageId:d.messageId,reasonCode:A===!1?144:0},d.topic);break;case"pubrec":f({cmd:"pubrel",messageId:d.messageId,reasonCode:0});break;case"pubcomp":case"puback":o.acknowledge(d.messageId);break;case"pingreq":f({cmd:"pingresp"});break;case"disconnect":i=!0,o?.disconnect(!0),s.sessions.delete(o),en(!0,"connection","mqtt","disconnect"),e.close?e.close():e.end();break}}catch(h){(0,Tr.error)(h),f({cmd:"disconnect"})}function f(h,p){let S=(0,EE.generate)(h,c);t(S),Br(S.length,"bytes-sent",p,h.cmd,"mqtt")}a(f,"sendPacket");function E(h){return di(h,r)}a(E,"serialize")}),{onMessage:_,onClose:l}}var EE,mH,fE,is,Tr,fH,pH,EH,dE,SH=Oe(()=>{EE=require("mqtt-packet");dH();mH=B(Mr());ha();Rs();Zt();fE=B(Z()),is=B(M()),Tr=B(Y()),fH=(0,Tr.loggerWithTag)("auth-event"),pH=(0,fE.get)(is.CONFIG_PARAMS.AUTHENTICATION_AUTHORIZELOCAL)??process.env.DEV_MODE;a(Ane,"bypassAuth");a(One,"start");dE=0;a(hH,"onSocket")});var rf={};Ve(rf,{component_errors:()=>Ha,loadComponent:()=>hE,loadComponentDirectories:()=>wH,setErrorReporter:()=>wne});function wH(e,t){t&&(BR=t),e&&(HR=e);let r=[];if((0,Pn.existsSync)(vR)){let s=(0,Pn.readdirSync)(vR,{withFileTypes:!0});for(let i of s){if(!i.isDirectory()&&!i.isSymbolicLink())continue;let o=i.name,c=(0,St.join)(vR,o);r.push(hE(c,BR,"hdb",!1))}}let n=process.env.RUN_HDB_APP;return n&&r.push(hE(n,BR,n,!1,null,process.env.DEV_MODE)),Promise.all(r).then(()=>{yH=!0})}function wne(e){ul=e}async function hE(e,t,r,n,s,i){if(!gH.has(e)){gH.set(e,!0),s&&(HR=s);try{let o;n&&(Ha=new Map);let c=(0,St.join)(e,n?"harperdb-config.yaml":"config.yaml");(0,Pn.existsSync)(c)?o=n?(0,NH.getConfigObj)():(0,RH.parseDocument)((0,Pn.readFileSync)(c,"utf8"),{simpleKeys:!0}).toJSON():o=xR;let u=[],_=n;for(let l in o){let d=o[l];if(Ha.set(n?l:(0,St.basename)(e),!1),!d)continue;let f,E=d.package;try{if(E){let A=e,b;for(;!(0,Pn.existsSync)(b=(0,St.join)(A,"node_modules",l));)if(A=(0,St.dirname)(A),A.length<(0,bH.getHdbBasePath)().length){b=null;break}if(b)f=await hE(b,t,r,!1),_=!0;else throw new Error(`Unable to find package ${l}:${E}`)}else f=yne[l];if(!f)continue;u.push(f);let h=a(A=>(A.origin=r,ot(A)),"ensureTable"),p=d.network||(d.port||d.securePort)&&d,S=p?.securePort||p?.https&&p.port,T=!p?.https&&p?.port;if(Ba.isMainThread&&(f=await f.startOnMainThread?.({server:Xe,ensureTable:h,port:T,securePort:S,resources:t,...d})||f,n&&p))for(let A of[T,S])try{if(+A&&!TH.includes(A)){let b=qR.get(FR.CONFIG_PARAMS.HTTP_SESSIONAFFINITY);b&&cl.default.warn("Session affinity is not recommended and may cause memory leaks"),(b||!jf)&&(TH.push(A),bB(A,b))}}catch(b){console.error("Error listening on socket",A,b,l)}if(t.isWorker&&(f=await f.start?.({server:Xe,ensureTable:h,port:T,securePort:S,resources:t,...d})||f),HR.set(f,!0),(f.handleFile||f.handleDirectory)&&d.files){if(d.files.includes(".."))throw(0,OH.handleHDBError)("Can not reference parent directories");let A=(0,St.join)(e,d.files).replace(/\\/g,"/"),b=A.indexOf("/*");if(b>-1&&d.files!==xR[l]?.files&&!(0,Pn.existsSync)(A.slice(0,b)))throw new Error(`The path '${A.slice(0,b)}' does not exist and cannot be used as the base of the resolved 'files' path value '${d.files}'`);let H=(0,St.basename)(e),q=d.path||"/";q=q.startsWith("/")?q:q.startsWith("./")?"/"+H+q.slice(2):q==="."?"/"+H:"/"+H+"/"+q;let v,P,z;if(d.root){let Q=d.root;Q.startsWith("/")&&(Q=Q.slice(1)),Q.endsWith("/")&&(Q=Q.slice(0,-1)),Q+="/",P=(0,St.join)(e,Q)}else(z=A.indexOf("/*"))>-1&&(P=A.slice(0,z+1),v=(0,St.relative)(e,P));let W=!1;if(Ba.isMainThread&&f.setupDirectory&&(W=await f.setupDirectory?.(q,P,t)),t.isWorker&&f.handleDirectory&&(W=await f.handleDirectory?.(q,P,t)),W)continue;for(let Q of await(0,AH.default)(A,{onlyFiles:!1,objectMode:!0})){let{path:se,dirent:pe}=Q;_=!0;let oe=(0,St.relative)(e,se).replace(/\\/g,"/");if(v)if(oe.startsWith(v))oe=oe.slice(v.length+1);else throw new Error(`The root path '${d.root}' does not reference a valid part of the file path '${oe}'.The root path should be used to indicate the relative path/part of the file path for determining the exported web path.`);let xe=q+(q.endsWith("/")?"":"/")+oe;try{if(pe.isFile()){let le=await Nne(se);Ba.isMainThread&&await f.setupFile?.(le,xe,se,t),t.isWorker&&await f.handleFile?.(le,xe,se,t)}else Ba.isMainThread&&await f.setupDirectory?.(xe,se,t),t.isWorker&&await f.handleDirectory?.(xe,se,t)}catch(le){le.message=`Could not load ${pe.isFile()?"file":"directory"} '${se}'${d.module?" using '"+d.module+"'":""} for application '${e}' due to: ${le.message}`,ul?.(le),((0,xa.getWorkerIndex)()===0?console:cl.default).error(le),t.set(d.path||"/",new ll(le)),Ha.set(n?l:(0,St.basename)(e),le.message)}}}}catch(h){h.message=`Could not load component '${l}' for application '${(0,St.basename)(e)}' due to: ${h.message}`,ul?.(h),((0,xa.getWorkerIndex)()===0?console:cl.default).error(h),t.set(d.path||"/",new ll(h),null,!0),Ha.set(n?l:(0,St.basename)(e),h.message)}}if(Ba.isMainThread&&!yH&&i&&(0,xa.watchDir)(e,async()=>wH()),o.extensionModule)return await zl((0,St.join)(e,o.extensionModule));if(!_&&t.isWorker){let l=`${e} did not load any modules, resources, or files, is this a valid component?`;ul?.(new Error(l)),((0,xa.getWorkerIndex)()===0?console:cl.default).error(l),Ha.set((0,St.basename)(e),l)}}catch(o){console.error(`Could not load application directory ${e}`,o),o.message=`Could not load application due to ${o.message}`,ul?.(o),t.set("",new ll(o))}}}var Pn,St,Ba,RH,qR,FR,AH,xa,cl,OH,bH,bne,NH,Nne,vR,HR,yH,BR,Ha,yne,xR,TH,gH,ul,ll,nf=Oe(()=>{Pn=require("fs"),St=require("path"),Ba=require("worker_threads"),RH=require("yaml"),qR=B(Z()),FR=B(M());XO();rb();nb();yv();fB();TB();AH=B(require("fast-glob")),xa=B(Ze()),cl=B(Y());Oh();Zt();OH=B(ee());gn();be();NB();bH=B(Z()),bne=B(DB());Qd();RR();SH();NH=B(wr());Xf();({readFile:Nne}=Pn.promises),vR=qR.get(FR.CONFIG_PARAMS.COMPONENTSROOT),HR=new Map,Ha=new Map;a(wH,"loadComponentDirectories");yne={REST:Of,rest:Of,graphqlSchema:Ah,jsResource:Nh,fastifyRoutes:nR,login:wh,static:sR,operationsApi:bne,customFunctions:{},http:{},clustering:oE,authentication:Lu,mqtt:PR},xR={rest:!0,graphqlSchema:{files:"*.graphql"},jsResource:{files:"resources.js"},fastifyRoutes:{files:"routes/*.js",path:"."}};Object.defineProperty(xR,"static",{value:{files:"web/**"}});TH=[],gH=new Map;a(wne,"setErrorReporter");a(hE,"loadComponent");ll=class extends Bt{constructor(r){super();this.error=r}static{a(this,"ErrorResource")}get(){throw this.error}post(){throw this.error}put(){throw this.error}delete(){throw this.error}connect(){throw this.error}getResource(){return this}publish(){throw this.error}subscribe(){throw this.error}}});var CR=g((lme,CH)=>{var{isMainThread:IH}=require("worker_threads"),{getTables:Ine}=(be(),te(qe)),{loadComponentDirectories:Cne,loadComponent:Dne}=(nf(),te(rf)),{resetResources:Lne}=(Du(),te(PU)),Mne=FT(),Une=wr(),{dirname:Pne}=require("path"),{getConnection:vne}=ft(),Bne=Z(),Hne=M(),GR=new Map;async function xne(e=!1){!IH&&Bne.get(Hne.CONFIG_PARAMS.CLUSTERING_ENABLED)&&vne();try{IH&&await Mne()}catch(n){console.error(n)}let t=Lne();Ine(),t.isWorker=e,await Dne(Pne(Une.getConfigFilePath()),t,"hdb",!0,GR),await Cne(GR,t);let r=[];for(let[n]of GR)n.ready&&r.push(n.ready());r.length>0&&await Promise.all(r)}a(xne,"loadRootComponents");CH.exports.loadRootComponents=xne});var Ze=g((dme,gi)=>{"use strict";var{Worker:qne,MessageChannel:Fne,parentPort:os,isMainThread:KR,threadId:Gne,workerData:xs}=require("worker_threads"),{PACKAGE_ROOT:kne}=M(),{join:UH,isAbsolute:Vne,extname:$ne}=require("path"),{server:PH}=(Zt(),te(yi)),{watch:Yne,readdir:Kne}=require("fs/promises"),{totalmem:DH}=require("os"),_l=M(),vH=Z(),qs=Y(),{randomBytes:Wne}=require("crypto"),{_assignPackageExport:Qne}=require("../../index"),zne=M(),LH=1024*1024,Ti=[],ln=[],Jne=50,WR=1e4,jne="restart",BH="request_thread_info",HH="resource_report",xH="thread_info",qH="added-port",Xne="ack",kR;Qne("threads",ln);gi.exports={startWorker:VR,restartWorkers:zR,shutdownWorkers:nse,workers:Ti,setMonitorListener:_se,onMessageFromWorkers:sse,onMessageByType:YH,broadcast:ose,broadcastWithAcknowledgement:cse,setChildListenerByType:rse,getWorkerIndex:FH,getWorkerCount:GH,getTicketKeys:kH,setMainIsWorker:ese,setTerminateTimeout:Zne,restartNumber:xs?.restartNumber||1};ln.onMessageByType=YH;ln.sendToThread=function(e,t){if(!t?.type)throw new Error("A message with a type must be provided");let r=ln.find(n=>n.threadId===e);if(r)return r.postMessage(t),!0};var QR;function Zne(e){WR=e}a(Zne,"setTerminateTimeout");function FH(){return xs?xs.workerIndex:QR?0:void 0}a(FH,"getWorkerIndex");function GH(){return xs?xs.workerCount:QR?1:void 0}a(GH,"getWorkerCount");function ese(e){QR=e}a(ese,"setMainIsWorker");var mE;function kH(){return mE||(mE=KR?Wne(48):xs.ticketKeys,mE)}a(kH,"getTicketKeys");Object.defineProperty(PH,"workerIndex",{get(){return FH()}});Object.defineProperty(PH,"workerCount",{get(){return GH()}});var VH={[BH](e,t){use(t)},[HH](e,t){lse(t,e)}};function VR(e,t={}){let r=process.constrainedMemory?.()||DH();r=Math.min(r,DH(),2e4*LH);let n=vH.get(_l.CONFIG_PARAMS.MAXHEAPMEMORY)??Math.max(Math.floor(r/LH/(10+(t.threadCount||1)/4)),512),s=Math.min(Math.max(n>>6,16),64),i=[],o=[];for(let u of ln){let _=new Fne;_.existingPort=u,i.push(_),o.push(_.port2)}$ne(e)||(e+=".js");let c=new qne(Vne(e)?e:UH(kne,e),Object.assign({resourceLimits:{maxOldGenerationSizeMb:n,maxYoungGenerationSizeMb:s},execArgv:["--enable-source-maps"],argv:process.argv.slice(2),workerData:{addPorts:o,addThreadIds:i.map(u=>u.existingPort.threadId),workerIndex:t.workerIndex,workerCount:t.threadCount,name:t.name,restartNumber:gi.exports.restartNumber,ticketKeys:kH()},transferList:o},t));for(let{port1:u,existingPort:_}of i)_.postMessage({type:qH,port:u,threadId:c.threadId},[u]);return SE(c,!0),c.unexpectedRestarts=t.unexpectedRestarts||0,c.startCopy=()=>VR(e,t),c.on("error",u=>{console.error("Worker error:",u),qs.error("Worker error:",u)}),c.on("exit",u=>{Ti.splice(Ti.indexOf(c),1),!c.wasShutdown&&t.autoRestart!==!1&&(c.unexpectedRestarts<Jne?(t.unexpectedRestarts=c.unexpectedRestarts+1,VR(e,t)):qs.error(`Thread has been restarted ${c.restarts} times and will not be restarted`))}),c.on("message",u=>{VH[u.type]?.(u,c)}),Ti.push(c),fse(),t.onStarted&&t.onStarted(c),c.name=t.name,c}a(VR,"startWorker");var tse=[_l.THREAD_TYPES.HTTP];async function zR(e=null,t=2,r=!0){if(KR){if(r){let{loadRootComponents:o}=CR();await o()}gi.exports.restartNumber++,t<1&&(t=t*Ti.length);let n=[],s=[];for(let o of Ti.slice(0)){if(e&&o.name!==e||o.wasShutdown)continue;qs.trace("sending shutdown request to ",o.threadId),o.postMessage({restartNumber:gi.exports.restartNumber,type:_l.ITC_EVENT_TYPES.SHUTDOWN}),o.wasShutdown=!0,o.emit("shutdown",{});let c=tse.indexOf(o.name)>-1,u=new Promise(_=>{let l=setTimeout(()=>o.terminate(),WR*2).unref();o.on("exit",()=>{clearTimeout(l),n.splice(n.indexOf(u)),!c&&r&&o.startCopy(),_()})});if(n.push(u),c&&r){let _=o.startCopy(),l=new Promise(d=>{let f=a(E=>{E.type===zne.ITC_EVENT_TYPES.CHILD_STARTED&&(qs.trace("Worker has started",_.threadId),d(),s.splice(s.indexOf(l)),_.off("message",f))},"startListener");qs.trace("Waiting for worker to start",_.threadId),_.on("message",f)});s.push(l),n.length>=t&&await Promise.race(n),s.length>=t&&await Promise.race(s)}}await Promise.all(n),await Promise.all(s);let{restartService:i}=kd();r&&(e==="http"||!e)&&vH.get(_l.CONFIG_PARAMS.CLUSTERING_ENABLED)&&await i({service:"clustering"})}else os.postMessage({type:jne,workerType:e})}a(zR,"restartWorkers");function rse(e,t){VH[e]=t}a(rse,"setChildListenerByType");function nse(e){return zR(e,1/0,!1)}a(nse,"shutdownWorkers");var $H=[];function sse(e){$H.push(e)}a(sse,"onMessageFromWorkers");var $R=new Map;function YH(e,t){let r=$R.get(e);r||$R.set(e,r=[]),r.push(t)}a(YH,"onMessageByType");var ise=10;async function ose(e){let t=0;for(let r of ln)try{r.postMessage(e),t++>ise&&(t=0,await new Promise(setImmediate))}catch(n){qs.error("Unable to send message to worker",n)}}a(ose,"broadcast");var pE=new Map,ase=1;function cse(e){return new Promise(t=>{let r=0;for(let n of ln)try{let s=ase++,i=a(()=>{pE.delete(s),--r===0&&t(),n!==os&&--n.refCount===0&&n.unref()},"ack_handler");i.port=n,n.ref(),n.refCount=(n.refCount||0)+1,pE.set(e.requestId=s,i),n.hasAckCloseListener||(n.hasAckCloseListener=!0,n.on(n.close?"close":"exit",()=>{for(let[,o]of pE)o.port===n&&o()})),n.postMessage(e),r++}catch(s){qs.error("Unable to send message to worker",s)}r===0&&t()})}a(cse,"broadcastWithAcknowledgement");function use(e){e.postMessage({type:xH,workers:KH()})}a(use,"sendThreadInfo");function KH(){let e=Date.now();return Ti.map(t=>({threadId:t.threadId,name:t.name,heapTotal:t.resources?.heapTotal,heapUsed:t.resources?.heapUsed,externalMemory:t.resources?.external,arrayBuffers:t.resources?.arrayBuffers,sinceLastUpdate:e-t.resources?.updated,...t.recentELU}))}a(KH,"getChildWorkerInfo");function lse(e,t){e.resources=t,e.resources.updated=Date.now()}a(lse,"recordResourceReport");var YR;function _se(e){YR=e}a(_se,"setMonitorListener");var dse=1e3,MH=!1;function fse(){MH||(MH=!0,setInterval(()=>{for(let e of Ti){let t=e.performance.eventLoopUtilization(),r;e.lastTotalELU?r=e.performance.eventLoopUtilization(t,e.lastTotalELU):r=t,e.lastTotalELU=t,e.recentELU=r}YR&&YR()},dse).unref())}a(fse,"startMonitoring");var Ese=1e3;if(os){SE(os);for(let e=0,t=xs.addPorts.length;e<t;e++){let r=xs.addPorts[e];r.threadId=xs.addThreadIds[e],SE(r)}setInterval(()=>{let e=process.memoryUsage();os.postMessage({type:HH,heapTotal:e.heapTotal,heapUsed:e.heapUsed,external:e.external,arrayBuffers:e.arrayBuffers})},Ese).unref(),kR=a(()=>new Promise((e,t)=>{os.on("message",r),os.postMessage({type:BH});function r(n){n.type===xH&&(os.off("message",r),e(n.workers))}a(r,"receiveThreadInfo")}),"getThreadInfo")}else kR=KH;gi.exports.getThreadInfo=kR;function SE(e,t){ln.push(e),e.on("message",r=>{if(r.type===qH)r.port.threadId=r.threadId,SE(r.port);else if(r.type===Xne){let n=pE.get(r.id);n&&n()}else{for(let s of $H)s(r,e);let n=$R.get(r.type);if(n)for(let s of n)try{s(r,e)}catch(i){qs.error(i)}}}).on("close",()=>{ln.splice(ln.indexOf(e),1)}).on("exit",()=>{ln.splice(ln.indexOf(e),1)}),t?e.refCount=100:e.unref()}a(SE,"addPort");if(KR){let e,t,r=a(async(n,s)=>{s&&(e=s);for(let i of await Kne(n,{withFileTypes:!0}))i.isDirectory()&&i.name!=="node_modules"&&r(UH(n,i.name));try{for await(let{filename:i}of Yne(n,{persistent:!1}))t&&clearTimeout(t),t=setTimeout(async()=>{e&&await e(),await zR(),console.log("Reloaded HarperDB components")},100)}catch(i){console.warn("Error trying to watch component directory",n,i)}},"watch_dir");gi.exports.watchDir=r,process.env.WATCH_DIR&&r(process.env.WATCH_DIR)}else os.on("message",async e=>{let{type:t}=e;t===_l.ITC_EVENT_TYPES.SHUTDOWN&&(gi.exports.restartNumber=e.restartNumber,os.unref(),setTimeout(()=>{qs.warn("Thread did not voluntarily terminate",Gne),process.exit(0)},WR).unref())})});var YI={};Ve(YI,{AUDIT_STORE_OPTIONS:()=>rx,createAuditEntry:()=>e_,openAuditStore:()=>AE,readAuditEntry:()=>Dt,setAuditRetention:()=>mse,transactionKeyEncoder:()=>tx});function AE(e){let t=e.auditStore=e.openDB(XH.AUDIT_STORE_NAME,rx);t.rootStore=e;let r=[];t.addDeleteRemovalCallback=function(i,o){return r[i]=o,{remove(){delete r[i]}}};let n=null;function s(i=TE){clearTimeout(n),n=setTimeout(async()=>{if(t.rootStore.status==="closed")return;let o=0,c;try{for(let{key:u,value:_}of t.getRange({start:0,snapshot:!1,end:Date.now()-JR})){if((_[0]&15)===ZR){let l=Dt(_),d=l.tableId;r[d]?.(l.recordId)}if(c=t.remove(u),await new Promise(setImmediate),++o>=hse){i=10;break}}await c}finally{o===0&&(i=Math.min(i<<1,JR/10)),s(i)}},i).unref()}return a(s,"scheduleAuditCleanup"),t.scheduleAuditCleanup=s,(0,RE.getWorkerIndex)()===(0,RE.getWorkerCount)()-1&&s(TE),t}function mse(e,t=TE){JR=e,TE=t}function e_(e,t,r,n,s,i,o){let c=nx[i];if(!c)throw new Error(`Invalid audit entry type ${i}`);let u=1;n&&(n>1?qa.setFloat64(0,n):_n.set($h),u=9),f(0),f(t),d(r),qa.setFloat64(u,e),u+=8,s?d(s):_n[u++]=0,_n[n?8:0]=c;let l=_n.subarray(0,u);if(o)return Buffer.concat([l,o]);return l;function d(E){let h=u;u+=1,u=(0,Fa.writeKey)(E,_n,u);let p=u-h-1;p>127?p>16383?(tA.error("Key or username was too large for audit entry",E),u=h+1,_n[h]=0):(_n.copyWithin(h+2,h+1,u),qa.setUint16(h,p|32768),u++):_n[h]=p}function f(E){E<128?_n[u++]=E:E<16384?(qa.setUint16(u,E|32768),u+=2):E<1056964608?(qa.setUint32(u,E|3221225472),u+=4):(_n[u]=255,qa.setUint32(u+1,E),u+=5)}}function Dt(e){try{let t=e.dataView||(e.dataView=new eA(e.buffer,e.byteOffset,e.byteLength)),r;e[0]==66&&(r=t.readFloat64());let n=t.readInt(),s=t.readInt(),i=t.readInt(),o=t.readInt(),c=t.position,u=t.position+=o,_=t.readFloat64();o=t.readInt();let l=t.position,d=t.position+=o;return{type:nx[n&7],tableId:i,get recordId(){return jH(e,c,u)},version:_,previousLocalTime:r,get user(){return d>l?jH(e,l,d):void 0},getValue(f,E,h){if(n&jR||n&XR&&!E)return f.decoder.decode(e.subarray(t.position));if(n&XR&&h)return rA(f.getEntry(this.recordId),h,f)}}}catch{return tA.error("Reading audit entry error",e),{}}}function jH(e,t,r){let n=e.subarray(t,r);return(0,Fa.readKey)(n,0,r-t)}var Fa,gE,XH,ZH,RE,ex,tA,_n,qa,tx,rx,JR,hse,TE,jR,XR,WH,ZR,QH,zH,JH,nx,eA,Li=Oe(()=>{Fa=require("ordered-binary"),gE=B(Z()),XH=B(lt()),ZH=B(M()),RE=B(Ze()),ex=B(J());vo();tA=B(Y());OE();(0,gE.initSync)();_n=Buffer.alloc(1024),qa=new DataView(_n.buffer,_n.byteOffset,1024),tx={writeKey(e,t,r){return e===pc?(t.set(pc,r),r+8):typeof e=="number"?((t.dataView||(t.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength))).setFloat64(r,e),r+8):(0,Fa.writeKey)(e,t,r)},readKey(e,t,r){return e[t]===66?(e.dataView||(e.dataView=new DataView(e.buffer,e.byteOffset,e.byteLength))).getFloat64(t):(0,Fa.readKey)(e,t,r)}},rx={encoding:"binary",keyEncoder:tx},JR=(0,ex.convertToMS)((0,gE.get)(ZH.CONFIG_PARAMS.LOGGING_AUDITRETENTION))||86400*3,hse=1e3,TE=1e4;a(AE,"openAuditStore");a(mse,"setAuditRetention");jR=16,XR=32,WH=1,ZR=2,QH=3,zH=4,JH=5,nx={put:WH|jR,[WH]:"put",delete:ZR,[ZR]:"delete",message:QH|jR,[QH]:"message",invalidate:zH,[zH]:"invalidate",patch:JH|XR,[JH]:"patch"};a(e_,"createAuditEntry");a(Dt,"readAuditEntry");eA=class extends DataView{static{a(this,"Decoder")}position=0;readInt(){let t=this.getUint8(this.position++);return t>=128?t>=192?t===255?(t=this.getUint32(this.position),this.position+=4,t):(t=this.getUint32(this.position-1)&1073741823,this.position+=3,t):(t=this.getUint16(this.position-1)&32767,this.position++,t):t}readFloat64(){try{let t=this.getFloat64(this.position);return this.position+=8,t}catch{debugger}}};a(jH,"readKeySafely")});var nA={};Ve(nA,{add:()=>bE,applyReverse:()=>sx,getRecordAtTime:()=>rA,rebuildUpdateBefore:()=>NE});function bE(e,t,r){isNaN(e[t])?e[t]=r.value:e[t]+=r.value}function NE(e,t){let r=null;for(let n in e)if(n in t){let s=t[n];if(s?.__op__){let i=e[n];if(i?.__op__)if(i.__op__===s.__op__)r||(r={}),r[n]=i;else throw new Error("Can not merge updates with different operations");else r||(r={}),r[n]=i,bE(r,n,s)}}else r||(r={}),r[n]=e[n];return r}function sx(e,t){for(let r in t){let n=t[r];if(n?.__op__){let s=pse[n.__op__]?.reverse;if(s)s(e,r,{value:n.value});else throw new Error(`Unsupported operation ${n.__op__}`)}else e[r]=ix}}function rA(e,t,r){let n=r.rootStore.auditStore,s=Object.assign({},e.value),i=e.localTime;for(;i>t;){let u=n.get(i),_=Dt(u);switch(_.type){case"put":s=_.getValue(r);break;case"patch":sx(s,_.getValue(r));break;case"delete":s=null}i=_.previousLocalTime}let o={},c=0;for(let u in s)s[u]===ix&&(o[u]=!0,c++);for(;c>0&&i>0;){let u=n.get(i),_=Dt(u),l;switch(_.type){case"put":l=_.getValue(r);break;case"patch":l=_.getValue(r);break}for(let d in l)o[d]&&(s[d]=l[d],o[d]=!1,c--);i=_.previousLocalTime}if(c>0)for(let u in o)s[u]=null;return s}var pse,ix,OE=Oe(()=>{Li();a(bE,"add");bE.reverse=function(e,t,r){isNaN(e[t])||(e[t]-=r.value)};pse={add:bE};a(NE,"rebuildUpdateBefore");a(sx,"applyReverse");ix={};a(rA,"getRecordAtTime")});function kr(e){return e[yt]||(e[yt]=Object.create(null))}function DE(e,t){let r=e.prototype,n={},s=t.attributes||t.properties||[];for(let o of s){let c=o.name,u,_;if(o.resolve)_={get(){return o.resolve(this,this[Ne])},set(l){return o.set(this,l)},configurable:!0};else{switch(o.type){case"String":u=a(function(l){if(!(typeof l=="string"||l==null&&o.nullable!==!1))throw new dn.ClientError(`${c} must be a string, attempt to assign ${l}`);kr(this)[c]=l},"set");break;case"ID":u=a(function(l){if(!(typeof l=="string"||l?.length>0&&l.every?.(d=>typeof d=="string")||l==null&&o.nullable!==!1))throw new dn.ClientError(`${c} must be a string, attempt to assign ${l}`);kr(this)[c]=l},"set");break;case"Float":case"Number":u=a(function(l){if(!(typeof l=="number"||l==null&&o.nullable!==!1))throw new dn.ClientError(`${c} must be a number, attempt to assign ${l}`);kr(this)[c]=l},"set");break;case"Int":u=a(function(l){if(!(l>>0===l||l==null&&o.nullable!==!1))if(typeof l=="number"&&Math.abs((l>>0)-l)<=1)l=Math.round(l);else throw new dn.ClientError(`${c} must be an integer between -2147483648 and 2147483647, attempt to assign ${l}`);kr(this)[c]=l},"set");break;case"Long":u=a(function(l){if(!(Math.round(l)===l&&Math.abs(l)<=9007199254740992||l==null&&o.nullable!==!1))if(typeof l=="number"&&Math.abs(l)<=9007199254740992)l=Math.round(l);else throw new dn.ClientError(`${c} must be an integer between -9007199254740992 and 9007199254740992, attempt to assign ${l}`);kr(this)[c]=l},"set");break;case"BigInt":u=a(function(l){if(!(typeof l=="bigint"||l==null&&o.nullable!==!1))if(typeof l=="string"||typeof l=="number")l=BigInt(l);else throw new dn.ClientError(`${c} must be a number, attempt to assign ${l}`);kr(this)[c]=l},"set");break;case"Boolean":u=a(function(l){if(!(typeof l=="boolean"||l==null&&o.nullable!==!1))throw new dn.ClientError(`${c} must be a boolean, attempt to assign ${l}`);kr(this)[c]=l},"set");break;case"Date":u=a(function(l){if(!(l instanceof Date||l==null&&o.nullable!==!1))if(typeof l=="string"||typeof l=="number")l=new Date(l);else throw new dn.ClientError(`${c} must be a Date, attempt to assign ${l}`);kr(this)[c]=l},"set");break;case"Bytes":u=a(function(l){if(!(l instanceof Uint8Array||l==null&&o.nullable!==!1))throw new dn.ClientError(`${c} must be a Buffer or Uint8Array, attempt to assign ${l}`);kr(this)[c]=l},"set");break;case"Any":case void 0:u=a(function(l){kr(this)[c]=l},"set");break;default:u=a(function(l){if(!(typeof l=="object"||l==null&&o.nullable!==!1))throw new dn.ClientError(`${c} must be an object, attempt to assign ${l}`);kr(this)[c]=l},"set")}_={get(){let l=this[yt];if(l&&c in l){let f=l[c];if(f?.__op__){let E=this[Re]?.[c];return f.update(E)}return f}let d=this[Re]?.[c];if(d&&typeof d=="object"){let f=ox(d,o);if(f)return l||(l=this[yt]=Object.create(null)),l[c]=f}return d},set:u,enumerable:!0,configurable:!0}}_.get.isAttribute=!0,n[c]=_,(!(c in r)||Object.getOwnPropertyDescriptor(r,c)?.get?.isAttribute)&&Object.defineProperty(r,c,_)}i("getProperty",function(o){let c=n[o];if(c)return c.get.call(this);let u=this[yt];return u?.[o]!==void 0?u[o]:this[Re]?.[o]}),i("set",function(o,c){let u=n[o];if(u)return u.set.call(this,c);if(t.sealed)throw new dn.ClientError("Can not add a property to a sealed table schema");kr(this)[o]=c}),i("deleteProperty",function(o){kr(this)[o]=void 0}),i("toJSON",function(){let o=this[yt],c;for(let _ in o){c||(c=Object.assign({},this[Re]));let l=o[_];if(l?.__op__){let d=c[_];l=l.update(d)}c[_]=l}return Object.keys(this).length>0&&(c||(c=Object.assign({},this[Re])),Object.assign(c,this)),c||this[Re]}),r.get||i("get",r.getProperty),r.delete||i("delete",r.deleteProperty);function i(o,c){Object.defineProperty(r,o,{value:c,configurable:!0})}a(i,"setMethod")}function ox(e,t){let r;switch(e.constructor){case Object:return t?((r=t.TrackedObject)||(t.TrackedObject=r=class{static{a(this,"TrackedObject")}constructor(s){if(s?.[Re])throw new Error("Can not track an already tracked object, check for circular references");this[Re]=s}},DE(r,t)),new r(e)):new yE(e);case Array:let n=new IE(e.length);n[Re]=e;for(let s=0,i=e.length;s<i;s++){let o=e[s];o&&typeof o=="object"&&(o=ox(o,t?.elements)),n[s]=o}return n;default:return e}}function $_(e){let t=e[yt],r;for(let s in t){r||(r=Object.assign({},e[Re]));let i=t[s];if(i&&typeof i=="object")if(i.__op__){let o=r[s];i=i.update(o)}else i=$_(i);r[s]=i}return Object.keys(e).length>0&&(r||(r=Object.assign({},e[Re])),Object.assign(r,e)),r||e[Re]}function Oo(e,t=e[yt]){let r;if(e[Re]&&e.constructor===Array&&!Object.isFrozen(e)){r=e;for(let n=0,s=e.length;n<s;n++){let i=e[n];if(i&&typeof i=="object"){let o=Oo(i);o!==i&&r===e&&(r=e.slice(0)),i=o}r[n]=i}return Object.freeze(r)}for(let n in t){r||(r=Object.assign({},e[Re]));let s=t[n];if(s&&typeof s=="object")if(s.__op__){let i=nA[s?.__op__];if(i)i(r,n,s);else throw new Error("Invalid CRDT operation "+s.__op__);continue}else s=Oo(s);r[n]=s}return r?Object.freeze(r):e[Re]||e}function wE(e){let t=e[Re];if(t===void 0)return!0;if(e.constructor===Array){if(!t||e[Ao]||e.length!==t.length)return!0;for(let r=0,n=e.length;r<n;r++){let s=t[r],i=e[r];if(s&&i?.[Re]===s){if(wE(i))return!0}else return!0}}else{let r=e[yt];if(r&&!t)return!0;for(let n in r){let s=r[n];if(s&&typeof s=="object"){let i=t[n];if(i&&s[Re]===i){if(wE(s))return!0}else return!0}else return!0}}return!1}var dn,yt,yE,Ao,IE,CE,Y_=Oe(()=>{gn();dn=B(ee());OE();yt=Symbol("own-data");a(kr,"getChanges");a(DE,"assignTrackedAccessors");a(ox,"trackObject");yE=class{static{a(this,"GenericTrackedObject")}constructor(t){if(t?.[Re])throw new Error("Can not track an already tracked object, check for circular references");this[Re]=t}};DE(yE,{});a($_,"collapseData");a(Oo,"deepFreeze");a(wE,"hasChanges");Ao=Symbol.for("has-array-changes"),IE=class extends Array{static{a(this,"TrackedArray")}[Ao];constructor(t){super(t)}splice(...t){return this[Ao]=!0,super.splice(...t)}push(...t){return this[Ao]=!0,super.push(...t)}pop(){return this[Ao]=!0,super.pop()}unshift(...t){return this[Ao]=!0,super.unshift(...t)}shift(){return this[Ao]=!0,super.shift()}};IE.prototype.constructor=Array;CE=class{constructor(t){this.value=t}static{a(this,"Addition")}__op__="add";update(t){return(+t||0)+this.value}}});var Ep={};Ve(Ep,{CONTEXT:()=>Ne,ID_PROPERTY:()=>Ue,IS_COLLECTION:()=>fn,RECORD_PROPERTY:()=>Re,Resource:()=>Bt,snake_case:()=>Tse,transformForSelect:()=>ME});function Tse(e){return e[0].toLowerCase()+e.slice(1).replace(/[a-z][A-Z][a-z]/g,t=>t[0]+"_"+t.slice(1))}function ax(e,t){if(dl=!1,e==="")return null;if(e=e.slice(1),e.indexOf("/")===-1)return e===""?(dl=!0,null):(e.startsWith("$")&&(e=parseInt(e,36)),t.coerceId(decodeURIComponent(e)));let r=e.split("/"),n=new iA;for(let s=0;s<r.length;s++){let i=r[s];if(!i&&s===r.length-1){dl=!0;break}n[s]=t.coerceId(decodeURIComponent(i))}return n}function Vr(e,t){n.reliesOnPrototype=!0;let r=t.hasContent;return n;function n(s,i,o){let c,u,_,l;if(r?(o?(l=i,o=o[Ne]||o):i?typeof s=="object"&&s&&(!Array.isArray(s)||typeof s[0]=="object")?(l=s,c=l[this.primaryKey]??null,o=i[Ne]||i):l=i:(l=s,c=l[Ue]??l[this.primaryKey]??null),c==null&&(_=!0)):i?o=i[Ne]||i:s&&typeof s=="object"&&!Array.isArray(s)&&(o=s),c===void 0)if(typeof s=="string")c=s;else if(typeof s=="object"&&s)if(u=s,s[Symbol.iterator]){c=[],_=!0;for(let E of s){if(typeof E=="object"&&E)break;c.push(E)}c.length===0?c=null:(c.length===1&&(c=c[0]),u.slice&&(u=u.slice(c.length,u.length),u.length===0&&(u=null,_=!1)))}else{if(typeof(c=s.url)=="string"){let E=c.indexOf("?");if(E>-1){let p=this.parseQuery(c.slice(E+1));u?u=Object.assign(p,u):u=p,c=c.slice(0,E)}let h=this.parsePath(c,o,u);h?.id!==void 0?(h.query&&(u?u=Object.assign(h.query,u):u=h.query),_=h.isCollection,c=h.id):c=h}c===void 0&&(c=s.id??null,c==null&&(_=!0))}else c=s??null,c==null&&(_=!0);o||(o={});let d;if(u?.ensureLoaded!=null||u?.async||_?(d=Object.assign({},t),u?.ensureLoaded!=null&&(d.ensureLoaded=u.ensureLoaded),u?.async&&(d.async=u.async),_&&(d.isCollection=!0)):d=t,o.transaction){let E=this.getResource(c,o,d);return E.then?E.then(f):f(E)}else return d.resetTransaction=!0,We(o,()=>{let E=this.getResource(c,o,d);return E.then?E.then(f):f(E)},d);function f(E){if(o.authorize){o.authorize=!1;let h=t.type==="read"?E.allowRead(o.user,u,o):t.type==="update"?E.doesExist?.()===!1?E.allowCreate(o.user,l,o):E.allowUpdate(o.user,l,o):t.type==="create"?E.allowCreate(o.user,l,o):E.allowDelete(o.user,u,o);if(h?.then)return h.then(p=>{if(!p)throw new LE(o.user);return typeof l?.then=="function"?l.then(S=>e(E,u,o,S)):e(E,u,o,l)});if(!h)throw new LE(o.user)}return typeof l?.then=="function"?l.then(h=>e(E,u,o,h)):e(E,u,o,l)}a(f,"authorizeActionOnResource")}}function $r(e,t){let r=new lx.ClientError(`The ${e.constructor.name} does not have a ${t} method implemented`,405);r.allow=[],r.method=t;for(let n of["get","put","post","delete","query","move","copy"])typeof e[n]=="function"&&r.allow.push(n);throw r}function sA(e,t,r){let n=e[Re];if(n){let s=e[yt];return i=>{let o,c;return e.hasOwnProperty(i)&&typeof(o=e[i])!="function"?o:s&&i in s?s[i]:(c=t?.[i])?c(e,r):n[i]}}else return t?s=>{let i=t[s];return i?i(e,r):e[s]}:s=>e[s]}function ME(e,t){let r=t?.propertyResolvers,n=t[Ne],s;if(typeof e=="string")return a(function o(c){return c.then?c.then(o):Array.isArray(c)?c.map(o):sA(c,r,n)(e)},"transform");if(typeof e=="object"){if(e.asArray)return a(function c(u){if(u.then)return u.then(c);if(Array.isArray(u))return u.map(c);let _=[],l=i(sA(u,r,n));for(let d of e)_.push(l(d));return _},"transform");let o=e.forceNulls;return a(function c(u){if(u.then)return u.then(c);if(Array.isArray(u))return u.map(f=>f&&typeof f=="object"?c(f):f);let _={},l=i(sA(u,r,n)),d;for(let f of e){let E=l(f);E===void 0&&o&&(E=null),E?.then?(d||(d=[]),d.push(E.then(h=>_[f.name||f]=h))):_[f.name||f]=E}return d?Promise.all(d).then(()=>_):_},"transform")}else throw new Error("Invalid select argument type "+typeof e);function i(o){return c=>{if(typeof c=="string")return o(c);if(typeof c=="object")if(c.name){s||(s={});let u=s[c.name];if(!u){let l=r[c.name]?.definition?.tableClass;u=s[c.name]=ME(c.select||c,l)}let _=o(c.name);return u(_)}else return o(c);else return c}}a(i,"handleProperty")}var cx,ux,lx,Ne,Ue,fn,Re,Sse,Bt,LE,dl,iA,gn=Oe(()=>{cx=require("crypto");_c();ux=require("../../index"),lx=B(ee());Y_();Wi();gf();Ne=Symbol.for("context"),Ue=Symbol.for("primary-key"),fn=Symbol("is-collection"),Re=Symbol("stored-record"),Sse={json:"application/json",cbor:"application/cbor",msgpack:"application/x-msgpack",csv:"text/csv"},Bt=class{static{a(this,"Resource")}static transactions;constructor(t,r){this[Ue]=t;let n=r?.[Ne];this[Ne]=n!==void 0?n:r||null}static get=Vr(function(t,r,n,s){let i=t.get?.(r);if(i?.then)return i.then(o);return o(i);function o(c){let u;if((u=r?.select)&&c!=null&&!c.selectApplied){let _=ME(u,t.constructor);return typeof c?.map=="function"?c.map(_):_(c)}return c}},{type:"read",resetTransaction:!0,ensureLoaded:!0,async:!0});static put=Vr(function(t,r,n,s){if(Array.isArray(s)&&t[fn]){let i=[],o=n.authorize;for(let c of s){let u=t.constructor,_=u.getResource(c[u.primaryKey],n,{async:!0});_.then?i.push(_.then(l=>l.put(c,n))):i.push(_.put(c,n))}return Promise.all(i)}return t.put?t.put(s,r):$r(t,"put")},{hasContent:!0,type:"update"});static patch=Vr(function(t,r,n,s){return t.patch?t.patch(s,r):$r(t,"patch")},{hasContent:!0,type:"update"});static delete=Vr(function(t,r,n,s){return t.delete?t.delete(r):$r(t,"delete")},{hasContent:!1,type:"delete"});static getNewId(){return(0,cx.randomUUID)()}static create(t,r,n){let s;return t==null?s=this.getNewId():Array.isArray(t)&&typeof t[0]!="object"?s=[...t,this.getNewId()]:typeof t!="object"?s=[t,this.getNewId()]:(s=this.getNewId(),n=r,r=t),We(n,()=>{let i=new this(s,n),o=i.update?i.update(r):$r(i,"update");return n.newLocation=s,n.createdResource=!0,o?.then?o.then(()=>s):s})}static invalidate=Vr(function(t,r,n,s){return t.invalidate?t.invalidate(r):$r(t,"delete")},{hasContent:!1,type:"update"});static post=Vr(function(t,r,n,s){return t[Ue]!=null&&t.update?.(),t.post(s,r)},{hasContent:!0,type:"create"});static connect=Vr(function(t,r,n,s){return t.connect?t.connect(s,r):$r(t,"connect")},{hasContent:!0,type:"read"});static subscribe=Vr(function(t,r,n,s){return t.subscribe?t.subscribe(r):$r(t,"subscribe")},{type:"read"});static publish=Vr(function(t,r,n,s){return t[Ue]!=null&&t.update?.(),t.publish?t.publish(s,r):$r(t,"publish")},{hasContent:!0,type:"create"});static search=Vr(function(t,r,n,s){let i=t.search?t.search(r):$r(t,"search"),o=n.select;if(o&&n.hasOwnProperty("select")&&i!=null&&!i.selectApplied){let c=ME(o,t.constructor);return i.map(c)}return i},{type:"read"});static query=Vr(function(t,r,n,s){return t.search?t.search(s,r):$r(t,"search")},{hasContent:!0,type:"read"});static copy=Vr(function(t,r,n,s){return t.copy?t.copy(s,r):$r(t,"copy")},{type:"create"});static move=Vr(function(t,r,n,s){return t.move?t.move(s,r):$r(t,"move")},{type:"delete"});post(t){if(this[fn])return this.constructor.create(this[Ue],t,this[Ne]);$r(this,"post")}static isCollection(t){return t?.[fn]}static coerceId(t){return t}static parseQuery(t){return Tf(t)}static parsePath(t,r,n){let s=t.indexOf(".");if(s>-1){let o=t.slice(s+1);t=t.slice(0,s);let c=r?.headers&&Sse[o];if(c)r.headers.set("accept",c);else if(n)n.property=o;else return{query:{property:o},id:ax(t,this),isCollection:dl}}let i=ax(t,this);return dl?{id:i,isCollection:!0}:i}static getResource(t,r,n){let s,i=r[Ne],o;typeof r.isCollection=="boolean"&&r.hasOwnProperty("isCollection")?o=r.isCollection:o=n?.isCollection;let c=o&&this.Collection||this;if(i||(i=i===void 0?r:{}),i.transaction){let u;if(i.resourceCache?u=i.resourceCache:u=i.resourceCache=[],u.asMap){let _=u.asMap.get(t);if(s=_?.find(l=>l.constructor===c),s)return s;_||u.asMap.set(t,_=[]),_.push(s=new c(t,i))}else{if(s=u.find(_=>_[Ue]===t&&_.constructor===c),s)return s;if(u.push(s=new c(t,i)),u.length>10){let _=new Map;for(let l of u){let d=l[Ue],f=_.get(d);f?f.push(l):_.set(d,[l])}i.resourceCache.length=0,i.resourceCache.asMap=_}}}else s=new c(t,i);return o&&(s[fn]=!0),s}subscribe(t){return new Tn}connect(t){return t?.subscribe!==!1?this.subscribe?.(t):new Tn}allowRead(t){return t?.role.permission.super_user}allowUpdate(t){return t?.role.permission.super_user}allowCreate(t){return t?.role.permission.super_user}allowDelete(t){return t?.role.permission.super_user}getId(){return this[Ue]}getContext(){return this[Ne]}};Bt.prototype[Ne]=null;(0,ux._assignPackageExport)("Resource",Bt);a(Tse,"snake_case");LE=class extends Error{static{a(this,"AccessError")}constructor(t){t?(super("Unauthorized access to resource"),this.statusCode=403):(super("Must login"),this.statusCode=401)}};a(ax,"pathToId");iA=class extends Array{static{a(this,"MulitPartId")}toString(){return this.join("/")}};a(Vr,"transactional");a($r,"missingMethod");a(sA,"selectFromObject");a(ME,"transformForSelect")});function dx(e,t,r,n){let s=e.primaryStore.env.path,i=e.primaryStore.tableId;Ga||((0,UE.onMessageByType)(_x,l=>{fx(l.path)}),Ga=Object.create(null));let o=Ga[s]||(Ga[s]=[]);o.auditStore=e.auditStore,o.lastTxnTime==null&&(o.lastTxnTime=Date.now());let c=o[i];c||(c=o[i]=new Map,c.envs=o,c.tableId=i,c.store=e.primaryStore),t=Ea(t);let u=new aA(r);u.startTime=n;let _=c.get(t);return _?_.push(u):(c.set(t,_=[u]),_.tables=c,_.key=t),u.subscriptions=_,u}function fx(e,t){if(!Ga)return;let r=Ga[e];if(!r)return;try{r.auditStore.resetReadTxn()}catch(s){throw s.message+=" in "+e,s}let n;for(let{key:s,value:i}of r.auditStore.getRange({start:r.lastTxnTime,exclusiveStart:!0})){r.lastTxnTime=s;let o=Dt(i),c=r[o.tableId];if(!c)continue;let u=o.recordId,_,l=Ea(o.recordId),d=0;do{let f=c.get(l);if(f){for(let h of f)if(!(d>0&&!(h.includeDescendants&&!(h.onlyChildren&&d>1)))){if(h.startTime>=s){(0,oA.info)("omitting",u,h.startTime,s);continue}try{if(h.crossThreads===!1&&!t)continue;let p;h.supportsTransactions&&h.txnInProgress!==o.version&&(p=!0,h.txnInProgress||(n?n.push(h):n=[h]),h.txnInProgress=o.version),h.listener(u,o,s,p)}catch(p){console.error(p),(0,oA.info)(p)}}}if(l==null)break;let E=l.lastIndexOf?.("/",l.length-2);E>-1?l=l.slice(0,E):l=null,d++}while(!0)}if(n)for(let s of n)s.txnInProgress=null,s.listener(null,{type:"end_txn"},r.lastTxnTime,!0)}function Ex(e,t){let r=t||e,n=r.env;if(t&&!t.cache&&(t.cache=new Map),!n.hasBroadcastListener){n.hasBroadcastListener=!0;let s=n.path;r.on("aftercommit",()=>{(0,UE.broadcast)({type:_x,path:s}),fx(s,!0)})}}var oA,UE,_x,Ga,Pme,aA,hx=Oe(()=>{oA=B(Y()),UE=B(Ze());_c();Du();Li();_x="transaction",Pme=Buffer.alloc(4096);a(dx,"addSubscription");aA=class extends Tn{static{a(this,"Subscription")}listener;subscriptions;startTime;constructor(t){super(),this.listener=t,this.on("close",()=>this.end())}end(){if(this.subscriptions){if(this.subscriptions.splice(this.subscriptions.indexOf(this),1),this.subscriptions.length===0){let t=this.subscriptions.tables,r=this.subscriptions.key;if(t.delete(r),t.size===0){let n=t.envs,s=t.dbi;delete n[s]}}this.subscriptions=null}}toJSON(){return{name:"subscription"}}};a(fx,"notifyFromTransactionData");a(Ex,"listenToCommits")});var Fg={};Ve(Fg,{coerceType:()=>PE,makeTable:()=>HE,setServerUtilities:()=>Ise,updateResource:()=>vE});function HE(e){let{primaryKey:t,indices:r,tableId:n,tableName:s,primaryStore:i,databasePath:o,databaseName:c,auditStore:u,schemaDefined:_,dbisDB:l}=e,{expirationMS:d,evictionMS:f,audit:E,trackDeletes:h}=e,{attributes:p}=e;p||(p=[]),Ex(i,u);let S=Wh(i,n,u),T=0,A,b,H={},q=Promise.resolve(),v,P,z;for(let $ of p)($.assignCreatedTime||$.name==="__createdtime__")&&(v=$),($.assignUpdatedTime||$.name==="__updatedtime__")&&(P=$),$.expiresAt&&(z=$),$.isPrimaryKey&&(H=$);let W,Q=[],se=[],pe=1,oe=2,xe={},le={},wt=864e5,Nl,yl,Fs,TA=!1,WE,Kx=i.getRange({start:!1,end:!1}).constructor,Wx=10,Qx=6;E&&AA();class Qe extends Bt{static name=s;static primaryStore=i;static auditStore=u;static primaryKey=t;static tableName=s;static indices=r;static audit=E;static databasePath=o;static databaseName=c;static attributes=p;static expirationTimer;static createdTimeProperty=v;static updatedTimeProperty=P;static propertyResolvers;static sources=[];static get expirationMS(){return d}static dbisDB=l;static schemaDefined=_;static sourcedFrom(m,R){R&&(this.sourceOptions=R,(R.expiration||R.eviction||R.scanInterval)&&this.setTTLExpiration(R)),R?.intermediateSource?(m.intermediateSource=!0,this.sources.unshift(m)):this.sources.push(m),b=m.get&&(!m.get.reliesOnPrototype||m.prototype.get);let I=a(w=>{let y=this.sources.slice(0,-1);if(y=y.filter(U=>U[w]&&(!U[w].reliesOnPrototype||U.prototype[w])),y.length>0)if(y.length===1){let U=y[0];return(L,D,x)=>{if(L?.source!==U)return U[w](D,x,L)}}else return(U,L,D)=>{let x=[];for(let k of y){if(U?.source===k)break;x.push(k[w](L,D,U))}return Promise.all(x)}},"getApplyToIntermediateSource"),O=this.sources[this.sources.length-1],N=a(w=>{if(O[w]&&(!O[w].reliesOnPrototype||O.prototype[w]))return(y,U,L)=>{if(!y?.source)return O[w](U,L,y)}},"getApplyToCanonicalSource");return xe={put:N("put"),patch:N("patch"),delete:N("delete"),publish:N("publish")},le={put:I("put"),patch:I("patch"),delete:I("delete"),publish:I("publish"),invalidate:I("invalidate")},(async()=>{let w=!1,y=a(async(U,L)=>{let D=U.value,x=U.table?et[c][U.table]:Qe;if(c===vn.SYSTEM_SCHEMA_NAME&&(U.table===vn.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME||U.table===vn.SYSTEM_TABLE_NAMES.USER_TABLE_NAME)&&(w=!0),U.id===void 0&&(U.id=D[x.primaryKey],U.id===void 0))throw new Error("Replication message without an id "+JSON.stringify(U));U.source=m;let k=await x.getResource(U.id,L,ka);switch(U.type){case"put":return k._writeUpdate(D,!0,ka);case"patch":return k._writeUpdate(D,!1,ka);case"delete":return k._writeDelete(ka);case"publish":return k._writePublish(D,ka);case"invalidate":return k.invalidate(ka);default:ze.error("Unknown operation",U.type,U.id)}},"writeUpdate");try{let U=m.subscribe;U&&h==null&&(h=!0);let L=m.subscribeOnThisThread?m.subscribeOnThisThread((0,No.getWorkerIndex)()):(0,No.getWorkerIndex)()===0,D=U&&L&&await m.subscribe?.({crossThreads:!1,inTransactionUpdates:!0,supportsTransactions:!0,omitCurrent:!0});if(D){let x;for await(let k of D)try{if(!(k.type==="transaction"?k.writes[0]:k)){ze.error("Bad subscription event",k);continue}if(k.source=m,x)if(k.beginTxn)x.resolve();else{y(k,x);continue}if(k.type==="end_txn")continue;let _e=We(k,()=>{if(k.type==="transaction"){let re=[];for(let ae of k.writes)try{re.push(y(ae,k))}catch(ve){throw ve.message+=" writing "+JSON.stringify(ae)+" of event "+JSON.stringify(k),ve}return Promise.all(re)}else if(k.type==="define_schema"){let re=this.attributes.slice(0),ae;for(let ve of k.attributes)re.find(ne=>ne.name===ve.name)||(re.push(ve),ae=!0);ae&&(ot({table:s,database:c,attributes:re,origin:"cluster"}),Tl.signalSchemaChange(new gl.SchemaEventMsg(process.pid,vn.OPERATIONS_ENUM.CREATE_TABLE,c,s)))}else return k.beginTxn?(x=k,y(k,k),new Promise(re=>{x.resolve=re})):y(k,k)});w&&(await _e,Tl.signalUserChange(new gl.UserEventMsg(process.pid))),k.onCommit&&(_e?.then?_e.then(k.onCommit):k.onCommit())}catch(ie){ze.error("error in subscription handler",ie)}}}catch(U){ze.error(U)}})(),this}static getResource(m,R,I){let O=super.getResource(m,R,I);if(m!=null){Ka(m);try{if(O.hasOwnProperty(Re))return O;if(typeof m=="object"&&m&&!Array.isArray(m))throw new Error(`Invalid id ${JSON.stringify(m)}`);let N=!I?.async||i.cache?.get(m),w=Rr(R),y=w.getReadTxn();if(y?.isDone)throw new Error("You can not read from a transaction that has already been committed/aborted");return QE(m,R,{transaction:y},N,U=>{if(U?vE(O,U):O[Re]=null,R.onlyIfCached&&R.noCacheStore){if(!O.doesExist())throw new En.ServerError("Entry is not cached",504)}else if(I?.ensureLoaded){let L=zE(m,U,R,O);if(L)return w?.disregardReadTxn(),O[cA]=!0,lA(L,D=>(vE(O,D),O))}return O})}catch(N){throw N.message.includes("Unable to serialize object")&&(N.message+=": "+JSON.stringify(m)),N}}return O}ensureLoaded(){let m=zE(this[Ue],this[Yr],this[Ne]);if(m)return this[cA]=!0,lA(m,R=>{this[Yr]=R,this[Re]=R.value,this[pl]=R.version})}static setTTLExpiration(m){if(typeof m=="number")d=m*1e3,f||(f=0);else if(m&&typeof m=="object")d=m.expiration*1e3,f=(m.eviction||0)*1e3,wt=m.scanInterval*1e3;else throw new Error("Invalid expiration value type");if(d<0)throw new Error("Expiration can not be negative");wt=wt||(d+f)/4,jE()}static enableAuditing(m=!0){E=m,m&&AA(),Qe.audit=m}static coerceId(m){return m===""?null:PE(m,H)}static async dropTable(){if(delete et[c][s],c===o){for(let m of p)l.remove(Qe.tableName+"/"+m.name),r[m.name]?.drop();l.remove(Qe.tableName+"/"),i.drop(),await l.committed}else console.log("legacy dropTable"),await i.close(),await fs.remove(data_path),await fs.remove(data_path===standard_path?data_path+MDB_LOCK_FILE_SUFFIX:path.join(path.dirname(data_path),MDB_LEGACY_LOCK_FILE_NAME));Tl.signalSchemaChange(new gl.SchemaEventMsg(process.pid,vn.OPERATIONS_ENUM.DROP_TABLE,c,s))}get(m){if(typeof m=="string")return this.getProperty(m);if(this[fn])return this.search(m);if(this[Ue]===null){if(m?.conditions)return this.search(m);let R=Qe.getRecordCount();return{recordCount:R.recordCount,estimatedRecordRange:R.estimatedRange,records:"./",name:s,database:c,attributes:p}}if(m?.property)return this.getProperty(m.property);if(this.doesExist()||m?.ensureLoaded===!1||this[Ne]?.returnNonexistent)return this}allowRead(m,R){let I=Il(m);if(I?.read){if(I.isSuperUser)return!0;let O=I.attribute_permissions,N=R?.select;if(O?.length>0||TA&&N){if(R||(R={}),N){let w=O?.length>0&&uA(O,"read");R.select=N.map(y=>{let U=y.name||y;if(!w||w[U]){let L=Fs[U]?.definition?.tableClass;if(L){if(y.name||(y={name:y}),!L.prototype.allowRead.call(null,m,y))return!1;if(!y.select)return y.name}return y}}).filter(Boolean)}else R.select=O.filter(w=>w.read&&!Fs[w.attribute_name]).map(w=>w.attribute_name);return R}else return!0}}allowUpdate(m,R){let I=Il(m);if(I?.update){let O=I.attribute_permissions;if(O?.length>0){let N=uA(O,"update");for(let w in R)if(!N[w])return!1;for(let w of O){let y=w.attribute_name;!w.update&&!(y in R)&&(R[y]=this.getProperty(y))}}return!0}}allowCreate(m,R){if(this[fn]){let I=Il(m);if(I?.insert){let O=I.attribute_permissions;if(O?.length>0){let N=uA(O,"insert");for(let w in R)if(!N[w])return!1}else return!0}}else return this.allowUpdate(m,{})}allowDelete(m){return Il(m)?.delete}update(m,R){if(!Rr(this[Ne]))throw new Error("Can not update a table resource outside of a transaction");if(m===!1)return this;let O;return typeof m=="object"&&m&&(R?(Object.isFrozen(m)&&(m=Object.assign({},m)),this[Re]={},this[yt]=m):(O=this[yt],O&&(m=Object.assign(O,m)),this[yt]=O=m)),this._writeUpdate(this[yt],R),this}addTo(m,R){if(typeof R=="number")this[fl]===px?this.set(m,(+this.getProperty(m)||0)+R):(this[fl]||this.update(),this.set(m,new CE(R)));else throw new Error("Can not add a non-numeric value")}subtractFrom(m,R){if(typeof R=="number")return this.addTo(m,-R);throw new Error("Can not subtract a non-numeric value")}invalidate(m){let R=this[Ne],I=this[Ue];Ka(I),Rr(this[Ne]).addWrite({key:I,store:i,invalidated:!0,entry:this[Yr],nodeName:this[Ne]?.nodeName,before:xe.invalidate?.bind(this,R,I),beforeIntermediate:le.invalidate?.bind(this,R,I),commit:(N,w)=>{if(w?.version>N)return;let y=null;for(let U in r)y||(y={}),y[U]=this.getProperty(U);S(I,y,this[Yr],N,El,E,this[Ne],0,"invalidate")}})}static evict(m,R,I){let O=this.Source,N;if(!((b||E)&&(!R||(N=i.getEntry(m),!N||!R)||N.version!==I))){if(b){if(i.hasLock(m,N.version))return;let w;for(let y in r)w||(w={}),w[y]=R[y];if(w)return S(m,w,N,I,hl,null,null,0,null,!0)}return i.ifVersion(I,()=>{wl(m,R,null)}),E?S(m,null,N,I,hl,null,null,0,null,!0):i.remove(m,I)}}lock(){throw new Error("Not yet implemented")}static operation(m,R){return m.table||=s,m.schema||=c,Ox.operation(m,R)}put(m){this.update(m,!0)}patch(m){this.update(m,!1)}_writeUpdate(m,R,I){let O=this[Ne],N=Rr(O),w=this[Ue];Ka(w);let y=this[Yr];this[fl]=R?px:Nse;let U={key:w,store:i,entry:y,nodeName:O?.nodeName,validate:L=>{m||(m=this[yt]),R||m&&wE(m)?(this.validate(m,!R),O?.source||(P&&(m[P.name]=P.type==="Date"?new Date(L):P.type==="String"?new Date(L).toISOString():L),R&&(t&&m[t]!==w&&(m[t]=w),v&&(y?.value?m[v.name]=y?.value[v.name]:m[v.name]=v.type==="Date"?new Date(L):v.type==="String"?new Date(L).toISOString():L),m=Oo(m)))):N.removeWrite(U)},before:R?xe.put?()=>xe.put(O,w,m):null:xe.patch?()=>xe.patch(O,w,m):xe.put?()=>xe.put(O,w,Oo(this)):null,beforeIntermediate:R?le.put?()=>le.put(O,w,m):null:le.patch?()=>le.patch(O,w,m):le.put?()=>le.put(O,w,Oo(this)):null,commit:(L,D,x)=>{if(x){if(O&&D?.version>(O.lastModified||0)&&(O.lastModified=D.version),this[Yr]=D,D?.value?.[Re])throw new Error("Can not assign a record to a record, check for circular references");R||(this[Re]=D?.value??null)}this[yt]=m,this[pl]=L;let k=D?.value,ie=m;if(this[fl]=0,D?.version>L)if(E){let ve=D.localTime,ne=D.version;for(;ie&&(ve>L||ne>L&&ve>0);){let j=u.get(ve),de=Dt(j);if(ne=de.version,ne>L)if(de.type==="patch"){let Se=de.getValue(i);ie=NE(ie,Se)}else(de.type==="put"||de.type==="delete")&&(ie=null);ve=de.previousLocalTime}}else R?ie=null:ie=NE(ie,k);let _e=Oo(this,ie);if(_e?.[Re])throw new Error("Can not assign a record to a record, check for circular references");this[Re]=_e;let re;R||(re=m),wl(w,k,_e);let ae=R?"put":"patch";S(w,_e,D,L,0,E,O,O.expiresAt||(d?d+Date.now():0),ae,!1,re)}};N.addWrite(U)}async delete(m){if(typeof m=="string")return this.deleteProperty(m);if(this[fn]){for await(let R of this.search(m))(await Qe.getResource(R[t],this.getContext(),{ensureLoaded:!1}))._writeDelete(m);return}return this[Re]?this._writeDelete(m):!1}_writeDelete(m){let R=Rr(this[Ne]),I=this[Ue];Ka(I);let O=this[Ne];return R.addWrite({key:I,store:i,resource:this,nodeName:O?.nodeName,before:xe.delete?.bind(this,O,I),beforeIntermediate:le.delete?.bind(this,O,I),commit:(N,w,y)=>{let U=w?.value;y&&(O&&w?.version>(O.lastModified||0)&&(O.lastModified=w.version),vE(this,w)),!(w?.version>N)&&(wl(this[Ue],U),ze.trace("Write delete entry",I,N),E||h?(S(I,null,this[Yr],N,0,E,this[Ne],0,"delete"),E||jE()):i.remove(this[Ue]))}}),!0}search(m){let R=this[Ne],I=Rr(R);if(!m)throw new Error("No query provided");let O=m.conditions;O?O.length===void 0&&(O=O[Symbol.iterator]?Array.from(O):[O]):O=Array.isArray(m)?m:m[Symbol.iterator]?Array.from(m):[],this[Ue]&&(O=[{attribute:null,comparator:"prefix",value:this[Ue]}].concat(O));let N,w={};function y(j,de){let Se;switch(de){case"and":case void 0:if(j.length<1)throw new Error('An "and" operator requires at least one condition');Se=!0;break;case"or":if(j.length<2)throw new Error('An "or" operator requires at least two conditions');break;default:throw new Error("Invalid operator "+de)}let Bn=Se&&{},Gs;for(let ke of j){if(ke.conditions){ke.conditions=y(ke.conditions,ke.operator);continue}let Pt=ke[0]??ke.attribute,zr=Pt==null?H:Ms(p,Pt);if(zr){if(Se){let Hn=Dn(Pt),vt=Bn[Hn];vt?(vt.push(ke),Gs=!0):Bn[Hn]=[ke]}(zr.type||mg[ke.comparator])&&(ke[1]===void 0?ke.value=L(ke.value,zr):ke[1]=L(ke[1],zr))}else if(Pt!=null)throw(0,En.handleHDBError)(new Error,`${Pt} is not a defined attribute`,404)}if(m.enforceExecutionOrder)return j;if(Gs)for(let ke in Bn){let Pt=Bn[ke],zr=Pt.length;if(zr>1)for(let Hn=0;Hn<zr;Hn++){let vt=Pt[Hn];if(vt.comparator==="ge"||vt.comparator==="greater_than_equal")for(let ks=0;ks<zr;ks++){let Co=Pt[ks];(Co.comparator==="le"||Co.comparator==="less_than_equal")&&(vt.comparator="between",vt.value=[vt.value,Co.value],j.splice(j.indexOf(Co),1))}if(vt.comparator==="equals"||!vt.comparator){for(let ks=0;ks<zr;ks++)if(ks!==Hn){let Co=Pt[ks];j.splice(j.indexOf(Co),1)}break}}}return j}a(y,"prepareConditions");function U(j,de){if(m.enforceExecutionOrder)return j;for(let Se of j)Se.conditions&&(Se.conditions=U(Se.conditions,Se.operator));return j.length>1&&de!=="or"?(0,Ax.sortBy)(j,Sf(Qe)):j}a(U,"orderConditions");function L(j,de){return Array.isArray(j)?j.map(Se=>PE(Se,de)):PE(j,de)}a(L,"coerceTypedValues");let D=m.operator;(O.length>0||D)&&(O=y(O,D));let x=typeof m.sort=="object"&&m.sort,k;if(x&&D!=="or"){let j=x.attribute;if(N=O.find(de=>Dn(de.attribute)===Dn(j)),!N){if(!Ms(p,j))throw(0,En.handleHDBError)(new Error,`${Array.isArray(j)?j.join("."):j} is not a defined attribute`,404);N={attribute:j},O.push(N)}N.descending=!!x.descending}O=U(O,D),x&&(O[0]===N?x.next&&(k={dbOrderedAttribute:x.attribute,attribute:x.next.attribute,descending:x.next.descending,next:x.next.next}):(N&&O.splice(O.indexOf(N),1),k=x));let ie=m.select;if(O.length===0&&(O=[{attribute:t,comparator:"greater_than",value:!0}]),m.explain)return{conditions:O,operator:D,postOrdering:k,selectApplied:!!ie};let _e=I.useReadTxn(),re=pg(O,D,Qe,_e,m,R,(j,de)=>gA(j,ie,R,de),w);(m.offset||m.limit!==void 0)&&(re=re.slice(m.offset,m.limit!==void 0?(m.offset||0)+m.limit:void 0));let ae=m.ensureLoaded!==!1,ve=Qe.transformEntryForSelect(ie,R,w,ae,!0),ne=Qe.transformToOrderedSelect(re,ie,k,R,ve);return ne.onDone=()=>{ne.onDone=null,I.doneReadTxn()},ne.selectApplied=!0,ne.getColumns=()=>{if(ie){let j=[];for(let de of ie)de==="*"?j.push(...p.map(Se=>Se.name)):j.push(de.name||de);return j}return p.map(j=>j.name)},ne}static transformToOrderedSelect(m,R,I,O,N){let w=new Kx;if(I){m=gA(m,R,O,null);let y;w.iterate=function(){let L,D=m[Symbol.asyncIterator]?m[Symbol.asyncIterator]():m[Symbol.iterator](),x,k=I.dbOrderedAttribute,ie,_e,re=!0;function ae(ne){let j=ne.next&&ae(ne.next),de=ne.descending;return(Se,Bn)=>{let Gs=JE(Se,ne.attribute,O),ke=JE(Bn,ne.attribute,O),Pt=de?(0,yo.compareKeys)(ke,Gs):(0,yo.compareKeys)(Gs,ke);return Pt===0?j?.(Se,Bn)||0:Pt}}a(ae,"createComparator");let ve=ae(I);return{async next(){let ne;if(L)if(ne=L.next(),ne.done){if(x)return w.onDone&&w.onDone(),ne}else return{value:await N(ne.value)};y=[],ie&&y.push(ie);do if(ne=await D.next(),ne.done){if(x=!0,y.length)break;return w.onDone&&w.onDone(),ne}else{let j=ne.value;if(j?.then&&(j=await j),k){let de=JE(j,k,O);if(re)re=!1,_e=de;else if(de!==_e){_e=de,ie=j;break}}y.push(j)}while(!0);return I.isGrouped,y.sort(ve),L=y[Symbol.iterator](),ne=L.next(),ne.done?(w.onDone&&w.onDone(),ne):{value:await N(ne.value)}},return(){w.onDone&&w.onDone(),D.return()},throw(){w.onDone&&w.onDone(),D.throw()}}};let U=a(L=>{if(typeof R=="object"&&Array.isArray(L.attribute))for(let D=0;D<R.length;D++){let x=R[D],k;if(x.name===L.attribute[0]){for(k=x.sort||(x.sort={});k.next;)k=k.next;k.attribute=L.attribute.slice(1),k.descending=L.descending}else x===L.attribute[0]&&(R[D]=k={name:x,sort:{attribute:L.attribute.slice(1),descending:L.descending}})}L.next&&U(L.next)},"applySortingOnSelect");U(I)}else w.iterate=(m[Symbol.asyncIterator]||m[Symbol.iterator]).bind(m),w=w.map(N);return w}static transformEntryForSelect(m,R,I,O,N){if(m&&(m===t||m?.length===1&&m[0]===t)){let L=a(D=>D?.key??D,"transform");return m===t?L:m.asArray?D=>[L(D)]:D=>({[t]:L(D)})}let w;O&&b&&!m?.every(L=>{let D;return typeof L=="object"?D=L.name:D=L,r[D]||D===t})&&(w=!0);let y,U=a(L=>{let D;if(L){if(WE=L,D=L.value||L.deref?.(),!D&&(L.key===void 0||L.deref)){if(L=QE(L.key??L,R,{transaction:Rr(R).getReadTxn(),lazy:m?.length<4},!1,x=>x),L?.then)return L.then(U);D=L?.value}if(w&&(L.metadataFlags&(El|hl)||L.expiresAt&&L.expiresAt<Date.now())){let x=zE(L.key??L,L,R);if(x?.then)return x.then(U)}}if(D==null)return N?bo.SKIP:D;if(m&&!(m[0]==="*"&&m.length===1)){let x,k=a((_e,re)=>{let ae;typeof _e=="object"?ae=_e.name:ae=_e;let ve=Fs?.[ae],ne;if(ve){let j=I?.[ae];if(j)if(j.hasMappings){let Se=ve.from?D[ve.from]:Dn(L.key);ne=j.get(Se),ne||(ne=[])}else ne=j.fromRecord?.(D);else ne=ve(D,R,L);let de=a(Se=>{if(Se&&typeof Se=="object"){let Bn=ve.definition?.tableClass||Qe;y||(y={});let Gs=y[ae]||(y[ae]=Bn.transformEntryForSelect(ae===_e?null:_e.select||(Array.isArray(_e)?_e:null),R,j,O));if(Array.isArray(Se)){let ke=[],Pt=Bn.transformToOrderedSelect(Se,_e.select,typeof _e.sort=="object"&&_e.sort,R,Gs)[Symbol.asyncIterator](),zr=a(vt=>{for(;!vt.done;){if(vt?.then)return vt.then(zr);ke.push(vt.value),vt=Pt.next()}re(ke,ae)},"nextValue"),Hn=zr(Pt.next());Hn&&(x||(x=[]),x.push(Hn));return}else if(Se=Gs(Se),Se?.then){x||(x=[]),x.push(Se.then(ke=>re(ke,ae)));return}}re(Se,ae)},"handleResolvedValue");ne?.then?(x||(x=[]),x.push(ne.then(de))):de(ne);return}else ne=D[ae],ne&&typeof ne=="object"&&ae!==_e&&(ne=this.transformEntryForSelect(_e.select||_e,R,null)({value:ne}));re(ne,ae)},"selectAttribute"),ie;if(typeof m=="string")k(m,_e=>{ie=_e});else if(Array.isArray(m))if(m.asArray)ie=[],m.forEach((_e,re)=>{_e==="*"?m[re]=D:k(_e,ae=>ie[re]=ae)});else{ie={};let _e=m.forceNulls;for(let re of m)if(re==="*")for(let ae in D)ie[ae]=D[ae];else k(re,(ae,ve)=>{ae===void 0&&_e&&(ae=null),ie[ve]=ae})}else throw new En.ClientError("Invalid select"+m);return x?Promise.all(x).then(()=>ie):ie}return D},"transform");return U}async subscribe(m){if(!u)throw new Error("Can not subscribe to a table without an audit log");E||ot({table:s,database:c,schemaDefined:_,attributes:p,audit:!0}),m||(m={});let R=!m.rawEvents,I=dx(Qe,this[Ue]??null,function(y,U,L,D){try{let x=U.getValue?.(i,R);if(!x&&U.type==="patch"&&R){let k=i.getEntry(y);k?.version===U.version?x=k.value:x=U.getValue?.(i,!0,L),U.type="put"}this.send({id:y,timestamp:L,value:x,version:U.version,type:U.type,beginTxn:D})}catch(x){ze.error(x)}},m.startTime||0,this[fn]);this[fn]&&(I.includeDescendants=!0,m.onlyChildren&&(I.onlyChildren=!0)),m.crossThreads===!1&&(I.crossThreads=!1),m.supportsTransactions&&(I.supportsTransactions=!0);let O=this[Ue],N=m.previousCount;N>1e3&&(N=1e3);let w=m.startTime;if(this[fn]){if(w){if(N)throw new En.ClientError("startTime and previousCount can not be combined for a table level subscription");for(let{key:y,value:U}of u.getRange({start:w,exclusiveStart:!0})){let L=Dt(U);if(L.tableId!==n)continue;let D=L.recordId;(O==null||gx(O,D))&&I.send({id:D,timestamp:y,...L}),I.startTime=y}}else if(N){let y=[];for(let{key:U,value:L}of u.getRange({start:"z",end:!1,reverse:!0}))try{let D=Dt(L);if(D.tableId!==n)continue;let x=D.recordId;if(O==null||gx(O,x)){let k=D.getValue(i,R,U);if(y.push({id:x,timestamp:U,value:k,version:D.version,type:D.type}),--N<=0)break}}catch(D){ze.error("Error getting history entry",U,D)}for(let U=y.length;U>0;)I.send(y[--U]);y[0]&&(I.startTime=y[0].timestamp)}else if(!m.omitCurrent)for(let{key:y,value:U,version:L,localTime:D}of i.getRange({start:O??!1,end:O==null?void 0:[O,yo.MAXIMUM_KEY],versions:!0}))U&&I.send({id:y,version:L,timestamp:D,value:U})}else{N&&!w&&(w=0);let y=this[Yr]?.localTime;if(y===Kh&&(i.cache?.delete(O),this[Yr]=i.getEntry(O),ze.trace("re-retrieved record",y,this[Yr]?.localTime),y=this[Yr]?.localTime),ze.trace("Subscription from",w,"from",O,y),w<y){let U=[],L=y;do{let D=u.get(L);if(D){m.omitCurrent=!0;let x=Dt(D),k=x.getValue(i,R,L);R&&(x.type="put"),U.push({id:O,value:k,timestamp:L,...x}),L=x.previousLocalTime}else break;N&&N--}while(L>w&&N!==0);for(let D=U.length;D>0;)I.send(U[--D]);I.startTime=y}!m.omitCurrent&&this.doesExist()&&I.send({id:O,version:this[pl],timestamp:y,value:this})}return m.listener&&I.on("data",m.listener),I}doesExist(){return!!(this[Re]||this[fl])}publish(m,R){this._writePublish(m,R)}_writePublish(m,R){let I=Rr(this[Ne]),O=this[Ue]||null;Ka(O);let N=this[Ne];I.addWrite({key:O,store:i,entry:this[Yr],nodeName:N?.nodeName,validate:()=>{this.validate(m)},before:xe.publish?.bind(this,N,O,m),beforeIntermediate:le.publish?.bind(this,N,O,m),commit:(w,y,U)=>{y===void 0&&h&&!E&&jE(),S(O,y?.value??null,y,y?.version||w,0,!0,N,y?.expiresAt,"message",!1,m)}})}validate(m,R){let I,O=a((N,w,y)=>{if(w.type&&N!=null)if(R&&N.__op__&&(N=N.value),w.properties){typeof N!="object"&&(I||(I=[])).push(`Property ${y} must be an object${w.type?" ("+w.type+")":""}`);let U=w.properties;for(let L=0,D=U.length;L<D;L++){let x=U[L],k=O(N[x.name],x,y+"."+x.name);k&&(N[x.name]=k)}}else switch(w.type){case"Int":(typeof N!="number"||N>>0!==N)&&(I||(I=[])).push(`Property ${y} must be an integer (from -2147483648 to 2147483647)`);break;case"Long":(typeof N!="number"||!(Math.floor(N)===N&&Math.abs(N)<=9007199254740992))&&(I||(I=[])).push(`Property ${y} must be an integer (from -9007199254740992 to 9007199254740992)`);break;case"Float":typeof N!="number"&&(I||(I=[])).push(`Property ${y} must be a number`);break;case"ID":typeof N=="string"||N?.length>0&&N.every?.(U=>typeof U=="string")||(I||(I=[])).push(`Property ${y} must be a string, or an array of strings`);break;case"String":typeof N!="string"&&(I||(I=[])).push(`Property ${y} must be a string`);break;case"Boolean":typeof N!="boolean"&&(I||(I=[])).push(`Property ${y} must be a boolean`);break;case"Date":if(!(N instanceof Date)){if(typeof N=="string"||typeof N=="number")return new Date(N);(I||(I=[])).push(`Property ${y} must be a Date`)}break;case"BigInt":if(typeof N!="bigint"){if(typeof N=="string"||typeof N=="number")return BigInt(N);(I||(I=[])).push(`Property ${y} must be a bigint`)}break;case"Bytes":N instanceof Uint8Array||(I||(I=[])).push(`Property ${y} must be a Buffer or Uint8Array`);break;case"array":if(Array.isArray(N)){if(w.elements)for(let U=0,L=N.length;U<L;U++){let D=N[U],x=O(D,w.elements,y+"[*]");x&&(N[U]=x)}}else(I||(I=[])).push(`Property ${y} must be a Buffer or Uint8Array`);break}w.nullable===!1&&N==null&&(I||(I=[])).push(`Property ${y} is required (and not does not allow null values)`)},"validateValue");for(let N=0,w=p.length;N<w;N++){let y=p[N];if(!y.relationship&&(!R||y.name in m)){let U=O(m[y.name],y,y.name);U&&(m[y.name]=U)}}if(I)throw new En.ClientError(I.join(". "))}getUpdatedTime(){return this[pl]}wasLoadedFromSource(){return b?!!this[cA]:void 0}static async addAttributes(m){let R=p.slice(0);for(let I of m){if(!I.name)throw new En.ClientError("Attribute name is required");if(I.name.match(/[`/]/))throw new En.ClientError("Attribute names cannot include backticks or forward slashes");R.push(I)}return ot({table:s,database:c,schemaDefined:_,attributes:R}),Qe.indexingOperation}static async removeAttributes(m){let R=p.filter(I=>!m.includes(I.name));return ot({table:s,database:c,schemaDefined:_,attributes:R}),Qe.indexingOperation}static getRecordCount(m){let R=i.getStats().entryCount,I=5e3,O=1e3,N;R>I&&!m?.exactCount&&(N=O);let w=0;for(let{value:y}of i.getRange({start:!0,lazy:!0,limit:N}))y!=null&&w++;if(N){let y=w;w=0;for(let{value:ae}of i.getRange({start:"\uFFFF",reverse:!0,lazy:!0,limit:N}))ae!=null&&w++;let U=N*2,L=(w+y)/U,D=Math.pow((w-y+1)/N/2,2)+L*(1-L)/U,x=Math.max(Math.sqrt(D)*R,1),k=Math.round(L*R),ie=Math.max(k-1.96*x,0),_e=Math.min(k+1.96*x,R),re=Math.pow(10,Math.round(Math.log10(x)));return re>k&&(re=re/10),w=Math.round(k/re)*re,{recordCount:w,estimatedRange:[Math.round(ie),Math.round(_e)]}}return{recordCount:w}}static updatedAttributes(){Fs=this.propertyResolvers={$id:(m,R,I)=>({value:I.key}),$updatedtime:(m,R,I)=>I.version,$record:(m,R,I)=>I?{value:m}:m};for(let m of this.attributes){m.resolve=null;let R=m.relationship;if(R)if(TA=!0,R.to)m.elements?.definition?(Fs[m.name]=m.resolve=(I,O,N)=>{let w=I[R.from?R.from:t],y=m.elements.definition.tableClass;return N?ba({attribute:R.to,value:w},Rr(O).getReadTxn(),!1,y).asArray:y.search([{attribute:R.to,value:w}],O).asArray},m.set=()=>{throw new Error("Setting a one-to-many relationship property is not supported")},m.resolve.definition=m.elements.definition,R.from&&(m.resolve.from=R.from)):console.error(`The one-to-many/many-to-many relationship property "${m.name}" in table "${s}" must have an array type referencing a table as the elements`);else if(R.from){let I=m.definition||m.elements?.definition;I?(Fs[m.name]=m.resolve=(O,N,w)=>{let y=O[R.from];if(y!==void 0){if(m.elements){let U,L=y.map(D=>{let x=w?I.tableClass.primaryStore.getEntry(D,{transaction:Rr(N).getReadTxn()}):I.tableClass.get(D,N);return x?.then&&(U=!0),x});return R.filterMissing?U?Promise.all(L).then(D=>D.filter(Rx)):L.filter(Rx):U?Promise.all(L):L}return w?I.tableClass.primaryStore.getEntry(y,{transaction:Rr(N).getReadTxn()}):I.tableClass.get(y,N)}},m.set=(O,N)=>{if(Array.isArray(N)){let w=N.map(y=>y[Ue]||y[I.tableClass.primaryKey]);O[R.from]=w}else{let w=N[Ue]||N[I.tableClass.primaryKey];O[R.from]=w}},m.resolve.definition=m.definition||m.elements?.definition,m.resolve.from=R.from):console.error(`The relationship property "${m.name}" in table "${s}" must be a type that references a table`)}else console.error(`The relationship directive on "${m.name}" in table "${s}" must use either "from" or "to" arguments`)}DE(this,this)}static async deleteHistory(m=0){let R;for(let{key:I,value:O}of u.getRange({start:0,end:m}))await ml(),Dt(O).tableId===n&&(R=u.remove(I));await R}static async*getHistory(m=0,R=1/0){for(let{key:I,value:O}of u.getRange({start:m,end:R})){await ml();let N=Dt(O);N.tableId===n&&(yield{id:N.recordId,localTime:I,version:N.version,type:N.type,value:N.getValue(i,!0,I),user:N.user})}}static async getHistoryOfRecord(m){let R=[];if(m==null)throw new Error("An id is required");let I=i.getEntry(m);if(!I)return R;let O=I.localTime;if(!O)throw new Error("The entry does not have a local audit time");let N=0;do{await ml();let w=u.get(O);if(w){let y=Dt(w);R.push({id:y.recordId,localTime:O,version:y.version,type:y.type,value:y.getValue(i,!0,O),user:y.user}),O=y.previousLocalTime}else break}while(N<1e3&&O);return R.reverse()}static cleanup(){W?.remove()}}Qe.updatedAttributes();let zx=Qe.prototype;return zx[bse]=!0,d&&Qe.setTTLExpiration(d/1e3),z&&Jx(),Qe;function wl($,m,R){let I;for(let O in r){let N=r[O],w=N.isIndexing,y=R?.[O],U=m?.[O];if(y===U&&!w)continue;I=!0;let L=N.indexNulls,D=(0,Sl.getIndexedValues)(U,L);if(D){mx&&N.prefetch(D.map(x=>({key:x,value:$})),Tx);for(let x=0,k=D.length;x<k;x++)N.remove(D[x],$)}if(D=(0,Sl.getIndexedValues)(y,L),D){mx&&N.prefetch(D.map(x=>({key:x,value:$})),Tx);for(let x=0,k=D.length;x<k;x++)N.put(D[x],$)}}return I}a(wl,"updateIndices");function Ka($){switch(typeof $){case"number":return!0;case"string":if($.length<659)return!0;if($.length>Sx)throw new Error("Primary key size is too large: "+$.length);break;case"object":if($===null)return!0;break;case"bigint":if($<2n**64n&&$>-(2n**64n))return!0;break;default:throw new Error("Invalid primary key type: "+typeof $)}if((0,yo.writeKey)($,yse,0)>Sx)throw new Error("Primary key size is too large: "+$.length);return!0}a(Ka,"checkValidId");function QE($,m,R,I,O){let N=a(()=>{if(m?.transaction?.stale&&(m.transaction.stale=!1),R.transaction?.isDone)return O(null,$);let w=i.getEntry($,R);return w&&m&&(w?.version>(m.lastModified||0)&&(m.lastModified=w.version),w?.localTime&&!m.lastRefreshed&&(m.lastRefreshed=w.localTime)),O(w,$)},"whenPrefetched");return I?N():pe>0?(pe--,N()):new Promise((w,y)=>{pe===0?(pe--,i.prefetch([$],()=>{U(),L()})):(Q.push($),se.push(L),Q.length>Qx&&(pe--,U()));function U(){if(Q.length>0){let D=se;i.prefetch(Q,()=>{pe===-1?U():pe++;for(let x of D)x()}),Q=[],se=[],oe>2&&oe--}else pe=oe,oe<Wx&&oe++}a(U,"prefetch");function L(){try{w(N())}catch(D){y(D)}}a(L,"load")})}a(QE,"loadLocalRecord");function Il($){if(!$?.role)return;let m=$.role.permission;if(m.super_user)return wse;let R=m[c],I,O=R?.tables;if(O)return O[s];if(c==="data"&&(I=m[s])&&!I.tables)return I}a(Il,"getTablePermissions");function zE($,m,R,I){if(b){let O;if(R.noCache?O=!0:(m?(!m.value||m.metadataFlags&(El|hl)||m.expiresAt&&m.expiresAt<Date.now())&&(O=!0):O=!0,en(!O,"cache-hit",s)),O){let N=RA($,m,R).then(w=>(w?.value?.[Re]&&ze.error("Can not assign a record with a record property"),R&&(w?.version>(R.lastModified||0)&&(R.lastModified=w.version),R.lastRefreshed=Date.now()),w));if(R?.onlyIfCached||m?.value&&I?.allowStaleWhileRevalidate?.(m,$)){if(N.catch(w=>ze.warn(w)),R?.onlyIfCached&&!I.doesExist())throw new En.ServerError("Entry is not cached",504);return}else return N}}}a(zE,"ensureLoadedFromSource");function Rr($){let m=$?.transaction;if(m){if(!m.lmdbDb)return m.lmdbDb=i,m;do{if(m.lmdbDb?.path===i.path)return m;let R=m.next;if(!R)return m=m.next=new Ki,m.lmdbDb=i,m;m=R}while(!0)}else return new k_}a(Rr,"txnForContext");function JE($,m,R){if(!$)return;WE=$;let I=$.value||$.deref?.()||(WE=i.getEntry($.key))?.value;if(typeof m=="object"){let N=Fs,w=I;for(let y=0,U=m.length;y<U;y++){let L=m[y],D=N?.[L];w=D&&w?D(w,R,!0)?.value:w?.[L],N=D?.definition?.tableClass?.propertyResolvers}return w}let O=Fs[m];return O?O(I,R):I[m]}a(JE,"getAttributeValue");function gA($,m,R,I){let O=Rr(R).getReadTxn(),N=I?.length,w={transaction:O,lazy:N>0||typeof m=="string"||m?.length<4,alwaysPrefetch:!0},y;function U(L,D){let x=L?.value;if(!x)return bo.SKIP;for(let k=0;k<N;k++)if(!y?.includes(k)&&!I[k](x,L))return bo.SKIP;return D!==void 0&&(L.key=D),L}if(a(U,"processEntry"),N>0||!$.hasEntries){let L=$.map(D=>{if(y=null,typeof D=="object"&&D.key!==void 0)return N>0?U(D):D;if(D==null)return bo.SKIP;for(let x=0;x<N;x++){let ie=I[x].idFilter;if(ie){if(!ie(D))return bo.SKIP;y||(y=[]),y.push(x)}}return QE(D,R,w,!1,U)});return Array.isArray($)&&(L=L.filter(D=>D!==bo.SKIP)),L.hasEntries=!0,L}return $}a(gA,"transformToEntries");async function RA($,m,R){let I=m?.metadataFlags,O=m?.version,N,w;if(!i.attemptLock($,O,()=>{clearTimeout(w);let D=i.getEntry($);!D||!D.value||D.metadataFlags&(El|hl)?N(RA($,i.getEntry($),R)):N(D)}))return new Promise(D=>{N=D,w=setTimeout(()=>{i.unlock($,O)},Ose)});let y=m?.value,U={requestContext:R,replacingRecord:y,replacingVersion:O,source:null,resourceCache:R?.resourceCache},L=R?.responseHeaders;return new Promise((D,x)=>{let k;lA(We(U,async ie=>{let _e=performance.now(),re,ae,ve;try{for(let Se of Qe.sources)if(Se.get&&(!Se.get.reliesOnPrototype||Se.prototype.get)&&(U.source=Se,re=await Se.get($,U),re))break;ve=I&El;let j=U.lastModified||ve&&O;ae=ve||j>O||!y,j||(j=(0,Sl.getNextMonotonicTime)());let de=performance.now()-_e;if(Br(de,"cache-resolution",s),L&&L.append("Server-Timing",`cache-resolve;dur=${de.toFixed(2)}`),ie.timestamp=j,d&&!U.expiresAt&&(U.expiresAt=Date.now()+d),re){if(typeof re!="object")throw new Error("Only objects can be cached and stored in tables");typeof re.toJSON=="function"&&(re=re.toJSON()),t&&re[t]!==$&&(re[t]=$)}k=!0,D({version:j,value:re})}catch(j){j.message+=` while resolving record ${$} for ${s}`,y&&((j.code==="ECONNRESET"||j.code==="ECONNREFUSED"||j.code==="EAI_AGAIN")&&!R?.mustRevalidate||R?.staleIfError&&(j.statusCode===500||j.statusCode===502||j.statusCode===503||j.statusCode===504))?(D({version:O,value:y}),ze.trace(j.message,"(returned stale record)")):x(j),U.transaction.abort();return}if(R?.noCacheStore){U.transaction.abort();return}Rr(U).addWrite({key:$,store:i,entry:m,nodeName:"source",commit:(j,de)=>{if(de?.version!==O)return;let Se=wl($,y,re);re?(le.put?.(U,$,re),S($,re,de,j,0,E&&ae||null,U,U.expiresAt,"put",!!ve)):(le.delete?.(U,$),E||h?S($,null,de,j,0,E&&ae||null,U,0,"delete",!!ve):i.remove($,O))}})}),()=>{i.unlock($,O)},ie=>{i.unlock($,O),k&&ze.error("Error committing cache update",ie)})})}a(RA,"getFromSource");function jE(){if(wt!==Nl&&(Nl=wt,(0,No.getWorkerIndex)()===(0,No.getWorkerCount)()-1)){if(yl&&clearTimeout(yl),!wt)return;let $=new Date;$.setMonth(0),$.setDate(1),$.setHours(0),$.setMinutes(0),$.setSeconds(0);let m=Math.ceil((Date.now()-$.getTime())/wt)*wt+$.getTime(),R=a(I=>{ze.trace(`Scheduled next cleanup scan at ${new Date(I)}ms`),yl=setTimeout(()=>q=q.then(async()=>{if(R(Math.max(I+wt,Date.now())),i.rootStore.status!=="open"){clearTimeout(yl);return}let O=50,N=new Array(O),w=0;ze.trace(`Starting cleanup scan for ${s}`);try{let y=0;for(let{key:U,value:L,version:D,expiresAt:x}of i.getRange({start:!1,snapshot:!1,versions:!0,lazy:!0})){let k;L===null&&!E&&D+Ase<Date.now()?k=i.remove(U,D):x&&x+f<Date.now()&&(k=Qe.evict(U,L,D),y++),k&&(await N[w],N[w]=k.catch(ie=>{ze.error("Cleanup error",ie)}),++w>=O&&(w=0)),await ml()}ze.trace(`Finished cleanup scan for ${s}, evicted ${y} entries`)}catch(y){ze.trace(`Error in cleanup scan for ${s}:`,y)}}),Math.min(I-Date.now(),2147483647)).unref()},"startNextTimer");R(m)}}a(jE,"scheduleCleanup");function AA(){W=u?.addDeleteRemovalCallback(n,$=>{let m=i.getEntry($);m?.value===null&&i.remove($,m.version)})}a(AA,"addDeleteRemoval");function Jx(){(0,No.getWorkerIndex)()===0&&setInterval(async()=>{try{let $=z.name,m=r[$];if(!m)throw new Error(`expiresAt attribute ${z} must be indexed`);for(let{value:R}of m.getRange({start:!0,end:Date.now(),versions:!0,snapshot:!1})){let I=i.getEntry(R);I?.value?.[$]<Date.now()&&Qe.evict(R,I.value,I.version),await ml()}}catch($){ze.error("Error in evicting old records",$)}},Rse).unref()}a(Jx,"runRecordExpirationEviction")}function uA(e,t){let r=e.attr_object||(e.attr_object={}),n=r[t];if(n)return n;n=r[t]=Object.create(null);for(let s of e)n[s.attribute_name]=s[t];return n}function Tx(){}function Ise(e){Ox=e}function PE(e,t){let r=t?.type;return e===null?e:r==="Int"||r==="Long"?e==="null"?null:parseInt(e):r==="Float"?e==="null"?null:parseFloat(e):r==="BigInt"?e==="null"?null:BigInt(e):r==="Date"?(typeof e!="number"&&!Cse.test(e)&&(e+="Z"),e==="null"?null:new Date(e)):!r||r==="Any"?(0,BE.autoCast)(e):e}function gx(e,t){if(e==null)return!0;if(!Array.isArray(t))return e===t;if(Array.isArray(e)){let r=e.length;if(e[r-1]===null&&r--,t.length>=r){for(let n=0;n<r;n++)if(t[n]!==e[n])return!1;return!0}return!1}else if(t[0]===e)return!0}function lA(e,t,r){return e?.then?e.then(t,r):t(e)}function vE(e,t){e[Yr]=t,e[Re]=t?.value??null,e[pl]=t?.version}function Rx(e){return e!=null}var vn,bo,Sl,Ax,Rl,En,Tl,gl,ze,yo,No,BE,gse,Ox,Rse,Ase,mx,Ose,pl,bse,Yr,fl,px,Nse,cA,ka,El,hl,yse,Sx,wse,jme,Cse,ml,Bf=Oe(()=>{vn=B(M()),bo=require("lmdb"),Sl=B(Ir()),Ax=require("lodash");gn();Bp();Rl=B(Z());hx();En=B(ee()),Tl=B(ps()),gl=B(bn());be();gf();ze=B(Y());Y_();Wi();yo=require("ordered-binary"),No=B(Ze());Li();BE=B(J());vo();Rs();OE();gse=new Uint8Array(9);gse[8]=192;Rse=6e4,Ase=864e5;Rl.initSync();mx=Rl.get(vn.CONFIG_PARAMS.STORAGE_PREFETCHWRITES),Ose=1e4,pl=Symbol.for("version"),bse=Symbol.for("incremental-update"),Yr=Symbol("entry"),fl=Symbol("is-saving"),px=1,Nse=2,cA=Symbol("loaded-from-source"),ka={isNotification:!0,ensureLoaded:!1},El=1,hl=8,yse=Buffer.allocUnsafeSlow(8192),Sx=1978,wse={read:!0,insert:!0,update:!0,delete:!0,isSuperUser:!0},jme=(0,BE.convertToMS)(Rl.get(vn.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE))||864e5;a(HE,"makeTable");a(uA,"attributesAsObject");a(Tx,"noop");a(Ise,"setServerUtilities");Cse=/[+-][0-9]{2}:[0-9]{2}|[a-zA-Z]$/;a(PE,"coerceType");a(gx,"isDescendantId");ml=a(()=>new Promise(setImmediate),"rest");a(lA,"when");a(vE,"updateResource");a(Rx,"exists")});var qe={};Ve(qe,{database:()=>Yc,databases:()=>et,dropDatabase:()=>Gp,dropTableMeta:()=>vse,getDatabases:()=>yn,getTables:()=>Dse,onUpdatedTable:()=>AR,readMetaDb:()=>Al,resetDatabases:()=>Lse,table:()=>ot,tables:()=>Cr});function Dse(){return kE||yn(),Cr||{}}function yn(){if(kE)return et;kE=!0,Ya=new Map;let e=(0,zt.getHdbBasePath)()&&(0,Je.join)((0,zt.getHdbBasePath)(),Wr.DATABASES_DIR_NAME),t=(0,zt.get)(Wr.CONFIG_PARAMS.DATABASES)||{};if(process.env.SCHEMAS_DATA_PATH&&(t.data={path:process.env.SCHEMAS_DATA_PATH}),e=process.env.STORAGE_PATH||(0,zt.get)(Wr.CONFIG_PARAMS.STORAGE_PATH)||e&&((0,Kr.existsSync)(e)?e:(0,Je.join)((0,zt.getHdbBasePath)(),Wr.LEGACY_DATABASES_DIR_NAME)),!!e){if((0,Kr.existsSync)(e))for(let r of(0,Kr.readdirSync)(e,{withFileTypes:!0})){let n=(0,Je.basename)(r.name,".mdb");r.isFile()&&(0,Je.extname)(r.name).toLowerCase()===".mdb"&&!t[n]?.path&&Al((0,Je.join)(e,r.name),null,n)}if((0,Kr.existsSync)((0,$a.getBaseSchemaPath)())){for(let r of(0,Kr.readdirSync)((0,$a.getBaseSchemaPath)(),{withFileTypes:!0}))if(!r.isFile()){let n=(0,Je.join)((0,$a.getBaseSchemaPath)(),r.name),s=(0,Je.join)((0,$a.getTransactionAuditStoreBasePath)(),r.name);for(let i of(0,Kr.readdirSync)(n,{withFileTypes:!0}))if(i.isFile()&&(0,Je.extname)(i.name).toLowerCase()===".mdb"){let o=(0,Je.join)(s,i.name);Al((0,Je.join)(n,i.name),(0,Je.basename)(i.name,".mdb"),r.name,o,!0)}}}if(t)for(let r in t){let n=t[r],s=n.path;if((0,Kr.existsSync)(s))for(let o of(0,Kr.readdirSync)(s,{withFileTypes:!0}))o.isFile()&&(0,Je.extname)(o.name).toLowerCase()===".mdb"&&Al((0,Je.join)(s,o.name),(0,Je.basename)(o.name,".mdb"),r);let i=n.tables;if(i)for(let o in i){let c=i[o],u=(0,Je.join)(c.path,(0,Je.basename)(o+".mdb"));(0,Kr.existsSync)(u)&&Al(u,o,r,null,!0)}}for(let r in et){let n=Ya.get(r);if(n){let s=et[r];r.includes("delete")&&hn.trace(`defined tables ${Array.from(n.keys())}`);for(let i in s)n.has(i)||(hn.trace(`delete table class ${i}`),delete s[i])}else if(delete et[r],r==="data"){for(let s in Cr)delete Cr[s];delete Cr[VE]}}return Ya=null,et}}function Lse(){kE=!1;for(let[,e]of Ri)e.needsDeletion=!0;yn();for(let[e,t]of Ri)t.needsDeletion&&!e.endsWith("system.mdb")&&(t.close(),Ri.delete(e));return et}function Al(e,t,r=fA,n,s){let i=new _A.default(e,!1);try{let o=Ri.get(e);o?o.needsDeletion=!1:(o=(0,qE.open)(i),Ri.set(e,o));let c=new wo.default(!1),u=o.dbisDb||(o.dbisDb=o.openDB(xE.INTERNAL_DBIS_NAME,c)),_=o.auditStore;_||(n?(0,Kr.existsSync)(n)&&(i.path=n,_=(0,qE.open)(i),_.isLegacy=!0):_=AE(o));let l=wx(r),d=l[VE],f=new Map;for(let{key:E,value:h}of u.getRange({start:!1})){let[p,S]=E.toString().split("/");S===""?S=h.name:S||(S=p,p=t,h.name||(h.name=S,h.indexed=!h.is_hash_attribute)),d?.add(p);let T=f.get(p);T||f.set(p,T={attributes:[]}),(S==null||h.is_hash_attribute)&&(T.primary=h),S!=null&&T.attributes.push(h),Object.defineProperty(h,"key",{value:E,configurable:!0})}for(let[E,h]of f){let{attributes:p,primary:S}=h;if(!S){for(let Q of p)if(Q.is_hash_attribute||Q.isPrimaryKey){S=Q;break}if(!S){hn.fatal(`Unable to find a primary key attribute on table ${E}, with attributes: ${JSON.stringify(p)}`);continue}}let T=l[E],A={},b=[],H,q,v=typeof S.audit=="boolean"?S.audit:(0,zt.get)(Wr.CONFIG_PARAMS.LOGGING_AUDITLOG),P=S.trackDeletes,z=S.expiration,W=S.eviction;if(T)A=T.indices,b=T.attributes,T.schemaVersion++;else{H=S.tableId,H?H>=(u.get(Va)||0)&&u.putSync(Va,H+1):(S.tableId=H=u.get(Va),H||(H=1),u.putSync(Va,H+1),u.putSync(S.key,S));let Q=new wo.default(!S.is_hash_attribute,S.is_hash_attribute);q=r_(o.openDB(S.key,Q)),q.rootStore=o,q.tableId=H}for(let Q of p){Q.attribute=Q.name;try{if(!Q.is_hash_attribute&&(Q.indexed||Q.attribute&&!Q.name)){if(!A[Q.name]){let pe=new wo.default(!Q.is_hash_attribute,Q.is_hash_attribute);A[Q.name]=o.openDB(Q.key,pe),A[Q.name].indexNulls=Q.indexNulls}let se=b.find(pe=>pe.name===Q.name);se?b.splice(b.indexOf(se),1,Q):b.push(Q)}}catch(se){hn.error("Error trying to update attribute",Q,b,A,se)}}if(!T){T=Ix(l,E,HE({primaryStore:q,auditStore:_,audit:v,expirationMS:z&&z*1e3,evictionMS:W&&W*1e3,trackDeletes:P,tableName:E,tableId:H,primaryKey:S.name,databasePath:s?r+"/"+E:r,databaseName:r,indices:A,attributes:p,schemaDefined:S.schemaDefined,dbisDB:u})),T.schemaVersion=1;for(let Q of EA)Q(T)}}return o}catch(o){throw o.message+=` opening database ${e}`,o}}function wx(e){let t=et[e];if(t||(e==="data"?t=et[e]=Cr:e==="system"?Object.defineProperty(et,"system",{value:t=Object.create(null),configurable:!0}):t=et[e]=Object.create(null)),Ya&&!Ya.has(e)){let r=new Set;t[VE]=r,Ya.set(e,r)}return t}function Ix(e,t,r){return e[t]=r,r}function Yc({database:e,table:t}){e||(e=fA),yn();let r=wx(e),n=(0,Je.join)((0,zt.getHdbBasePath)(),Wr.DATABASES_DIR_NAME),s=(0,zt.get)(Wr.CONFIG_PARAMS.DATABASES)||{};process.env.SCHEMAS_DATA_PATH&&(s.data={path:process.env.SCHEMAS_DATA_PATH});let i=t&&s[e]?.tables?.[t]?.path;n=i||s[e]?.path||process.env.STORAGE_PATH||(0,zt.get)(Wr.CONFIG_PARAMS.STORAGE_PATH)||((0,Kr.existsSync)(n)?n:(0,Je.join)((0,zt.getHdbBasePath)(),Wr.LEGACY_DATABASES_DIR_NAME));let o=(0,Je.join)(n,(i?t:e)+".mdb"),c=Ri.get(o);if(!c){let u=new _A.default(o,!1);c=(0,qE.open)(u),Ri.set(o,c)}return c}async function Gp(e){if(!et[e])throw new Error("Schema does not exist");let t=et[e];for(let r in t){let s=t[r].primaryStore.rootStore;Ri.delete(s.path),s.status==="open"&&(await s.close(),await bx.remove(s.path))}if(e==="data"){for(let r in Cr)delete Cr[r];delete Cr[VE]}delete et[e]}function ot({table:e,database:t,expiration:r,eviction:n,scanInterval:s,attributes:i,audit:o,trackDeletes:c,schemaDefined:u,origin:_}){t||(t=fA);let l=Yc({database:t,table:e}),d=et[t],f=d?.[e];if(l.status==="closed")throw new Error(`Can not use a closed data store for ${e}`);let E,h,p,S;u==null&&(u=!0);let T=new wo.default(!1);for(let P of i)P.attribute?(P.name=P.attribute,P.indexed=!0):P.attribute=P.name,P.expiresAt&&(P.indexed=!0);let A,b;if(f){if(E=f.primaryKey,f.primaryStore.rootStore.status==="closed")throw new Error(`Can not use a closed data store from ${e} class`);f.attributes.splice(0,f.attributes.length,...i)}else{let P=l.auditStore;P||(P=AE(l)),h=i.find(se=>se.isPrimaryKey)||{},E=h.name,h.is_hash_attribute=!0,h.schemaDefined=u,c&&(h.trackDeletes=!0),o=h.audit=typeof o=="boolean"?o:(0,zt.get)(Wr.CONFIG_PARAMS.LOGGING_AUDITLOG),r&&(h.expiration=r),n&&(h.eviction=n),_&&(h.origins?h.origins.includes(_)||h.origins.push(_):h.origins=[_]),hn.trace(`${e} table loading, opening primary store`);let z=new wo.default(!1,!0),W=e+"/",Q=r_(l.openDB(W,z));Q.rootStore=l,S=l.dbisDb=l.openDB(xE.INTERNAL_DBIS_NAME,T),Q.tableId=S.get(Va),Q.tableId||(Q.tableId=1),S.putSync(Va,Q.tableId+1),h.tableId=Q.tableId,f=Ix(d,e,HE({primaryStore:Q,auditStore:P,audit:o,trackDeletes:c,expirationMS:r&&r*1e3,evictionMS:n&&n*1e3,primaryKey:E,tableName:e,tableId:Q.tableId,databasePath:t,databaseName:t,indices:{},attributes:i,schemaDefined:u,dbisDB:S})),f.schemaVersion=1,A=!0,v(),S.put(W,h)}p=f.indices,S=S||(l.dbisDb=l.openDB(xE.INTERNAL_DBIS_NAME,T)),f.dbisDB=S;let H=[];for(let{key:P,value:z}of S.getRange({start:!0})){let[W,Q]=P.toString().split("/");if(Q===""&&(Q=z.name),Q){if(W!==e)continue}else Q=W;if(!i.find(pe=>pe.name===Q)?.indexed&&z.indexed&&!z.isPrimaryKey){v(),A=!0,S.remove(P);let pe=f.indices[W];pe&&H.push(pe)}}let q=[];try{for(let P of i||[]){if(P.relationship)continue;let z=e+"/"+(P.name||"");Object.defineProperty(P,"key",{value:z,configurable:!0});let W=S.get(z);if(P.isPrimaryKey){if(W=W||S.get(z=e+"/")||{},o!==f.audit||(+r||void 0)!==(+W.expiration||void 0)||(+n||void 0)!==(+W.eviction||void 0)){let se=Object.assign({},W);typeof o=="boolean"&&(o&&f.enableAuditing(o),se.audit=o),r&&(se.expiration=+r),n&&(se.eviction=+n),A=!0,v(),S.put(z,se)}continue}W?.attribute&&!W.name&&(W.indexed=!0);let Q=!W||W.type!==P.type||W.indexed!==P.indexed||JSON.stringify(W.attributes)!==JSON.stringify(P.attributes)||JSON.stringify(W.elements)!==JSON.stringify(P.elements);if(P.indexed){let se=new wo.default(!0,!1),pe=l.openDB(z,se);(Q||W.indexingPID&&W.indexingPID!==process.pid||W.restartNumber<Ol.workerData?.restartNumber)&&(A=!0,v(),W=S.get(z),(Q||W.indexingPID&&W.indexingPID!==process.pid||W.restartNumber<Ol.workerData?.restartNumber)&&(A=!0,P.lastIndexedKey=W?.lastIndexedKey||!1,P.indexingPID=process.pid,pe.isIndexing=!0,Object.defineProperty(P,"dbi",{value:pe}),P.indexNulls===void 0&&(P.indexNulls=!0),q.push(P)),S.put(z,P)),W?.indexNulls&&P.indexNulls===void 0&&(P.indexNulls=!0),pe.indexNulls=P.indexNulls,p[P.name]=pe}else Q&&(A=!0,v(),S.put(z,P))}}finally{b&&b()}if(A&&(f.schemaVersion++,f.updatedAttributes()),hn.trace(`${e} table loading, running index`),q.length>0||H.length>0?f.indexingOperation=Pse(f,q,H):A&&FE.signalSchemaChange(new GE.SchemaEventMsg(process.pid,"schema-change",f.databaseName,f.tableName)),f.origin=_,A)for(let P of EA)P(f,_!=="cluster");return(r||n||s)&&f.setTTLExpiration({expiration:r,eviction:n,scanInterval:s}),hn.trace(`${e} table loaded`),f;function v(){b||l.transactionSync(()=>({then(P){b=P}}))}a(v,"startTxn")}async function Pse(e,t,r){try{let n=e.schemaVersion;await FE.signalSchemaChange(new GE.SchemaEventMsg(process.pid,"schema-change",e.databaseName,e.tableName));let s;for(let u of r)s=u.drop();let i,o=0,c=t.length;if(await new Promise(u=>setImmediate(u)),c>0){let u=0;for(let{key:_,value:l,version:d}of e.primaryStore.getRange({start:t[0].lastIndexedKey,lazy:c<4,versions:!0,snapshot:!1}))if(l){if(u++,s=e.primaryStore.ifVersion(_,d,()=>{for(let f=0;f<c;f++){let E=t[f],h=E.name,p=(0,Nx.getIndexedValues)(l[h]);if(p)for(let S=0,T=p.length;S<T;S++)E.dbi.put(p[S],_)}}),s.then(()=>u--,f=>{u--,hn.error(f)}),Ol.workerData&&Ol.workerData.restartNumber!==yx.restartNumber&&(i=!0),++o%100===0||i){for(let f of t)f.lastIndexedKey=_,e.dbisDB.put(f.key,f);if(i)return}u>Mse?await s:u>Use&&await new Promise(f=>setImmediate(f))}for(let _ of t)delete _.lastIndexedKey,delete _.indexingPID,_.dbi.isIndexing=!1,s=e.dbisDB.put(_.key,_)}await s,await FE.signalSchemaChange(new GE.SchemaEventMsg(process.pid,"indexing-finished",e.databaseName,e.tableName))}catch(n){hn.error("Error in indexing",n)}}function vse({table:e,database:t}){let r=Yc({database:t,table:e}),n=[],s=r.dbisDb;for(let i of s.getKeys({start:e+"/",end:e+"0"}))n.push(s.remove(i));return Promise.all(n)}function AR(e){EA.push(e)}var zt,xE,qE,Je,Kr,$a,wo,_A,Wr,bx,dA,Nx,FE,GE,Ol,hn,yx,fA,VE,Cr,et,Va,EA,kE,Ri,Ya,Mse,Use,be=Oe(()=>{zt=B(Z()),xE=B(lt()),qE=require("lmdb"),Je=require("path"),Kr=require("fs"),$a=B(Ke());Bf();wo=B(n_()),_A=B(i_()),Wr=B(M()),bx=B(require("fs-extra")),dA=require("../../index"),Nx=B(Ir()),FE=B(ps()),GE=B(bn()),Ol=require("worker_threads"),hn=B(Y()),yx=B(Ze());Li();vo();fA="data",VE=Symbol("defined-tables");(0,zt.initSync)();Cr=Object.create(null),et=Object.create(null);(0,dA._assignPackageExport)("databases",et);(0,dA._assignPackageExport)("tables",Cr);Va=Symbol.for("next-table-id"),EA=[],Ri=new Map;a(Dse,"getTables");a(yn,"getDatabases");a(Lse,"resetDatabases");a(Al,"readMetaDb");a(wx,"ensureDB");a(Ix,"setTable");a(Yc,"database");a(Gp,"dropDatabase");a(ot,"table");Mse=1e3,Use=10;a(Pse,"runIndexing");a(vse,"dropTableMeta");a(AR,"onUpdatedTable")});var J=g((ope,kx)=>{"use strict";var Ai=require("path"),Ux=require("fs-extra"),gr=Y(),Cx=require("fs-extra"),$E=require("os"),Bse=require("net"),Hse=require("recursive-iterator"),it=M(),xse=tO(),Dx=require("papaparse"),YE=require("moment"),{inspect:qse}=require("util"),Lx=require("is-number"),ipe=require("lodash"),Fse=require("minimist"),Gse=require("https"),kse=require("http"),{hdb_errors:KE}=ee(),Vse=/^((\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z)))$/,Px=require("util").promisify(setTimeout),$se=100,Yse=5,Kse="",Wse=4,Mx={true:!0,TRUE:!0,FALSE:!1,false:!1,undefined:null,null:null,NULL:null,NaN:NaN};kx.exports={isEmpty:Qr,isEmptyOrZeroLength:as,arrayHasEmptyValues:Jse,arrayHasEmptyOrZeroLengthValues:jse,buildFolderPath:Xse,isBoolean:vx,errorizeMessage:Qse,stripFileExtension:eie,autoCast:tie,autoCastJSON:Bx,autoCastJSONDeep:mA,removeDir:rie,compareVersions:nie,isCompatibleDataVersion:sie,escapeRawValue:iie,unescapeValue:oie,stringifyProps:aie,timeoutPromise:uie,isClusterOperation:_ie,getClusterUser:fie,checkGlobalSchemaTable:die,getHomeDir:xx,getPropsFilePath:cie,promisifyPapaParse:Eie,removeBOM:qx,createEventPromise:hie,checkProcessRunning:mie,checkSchemaTableExist:pie,checkSchemaExists:Fx,checkTableExists:Gx,getStartOfTomorrowInSeconds:Sie,getLimitKey:Tie,isObject:Zse,isNotEmptyAndHasValue:zse,autoCasterIsNumberCheck:Hx,backtickASTSchemaItems:gie,isPortTaken:lie,createForkArgs:Rie,autoCastBoolean:Aie,async_set_timeout:Px,getTableHashAttribute:Oie,doesSchemaExist:bie,doesTableExist:Nie,stringifyObj:yie,ms_to_time:wie,changeExtension:Iie,getEnvCliRootPath:pA,noBootFile:Cie,httpRequest:Die,transformReq:Lie,convertToMS:Mie,PACKAGE_ROOT:it.PACKAGE_ROOT};function Qse(e){return e instanceof Error?e:new Error(e)}a(Qse,"errorizeMessage");function Qr(e){return e==null}a(Qr,"isEmpty");function zse(e){return!Qr(e)&&(e||e===0||e===""||vx(e))}a(zse,"isNotEmptyAndHasValue");function as(e){return Qr(e)||e.length===0||e.size===0}a(as,"isEmptyOrZeroLength");function Jse(e){if(Qr(e))return!0;for(let t=0;t<e.length;t++)if(Qr(e[t]))return!0;return!1}a(Jse,"arrayHasEmptyValues");function jse(e){if(as(e))return!0;for(let t=0;t<e.length;t++)if(as(e[t]))return!0;return!1}a(jse,"arrayHasEmptyOrZeroLengthValues");function Xse(...e){try{return e.join(Ai.sep)}catch{console.error(e)}}a(Xse,"buildFolderPath");function vx(e){return Qr(e)?!1:e===!0||e===!1}a(vx,"isBoolean");function Zse(e){return Qr(e)?!1:typeof e=="object"}a(Zse,"isObject");function eie(e){return as(e)?Kse:e.slice(0,-Wse)}a(eie,"stripFileExtension");function tie(e){return Qr(e)||e===""||typeof e!="string"?e:Mx[e]!==void 0?Mx[e]:Hx(e)===!0?Number(e):Vse.test(e)?new Date(e):e}a(tie,"autoCast");function Bx(e){if(typeof e=="string"&&(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")))try{return JSON.parse(e)}catch{}return e}a(Bx,"autoCastJSON");function mA(e){if(e&&typeof e=="object"){if(Array.isArray(e))for(let t=0,r=e.length;t<r;t++){let n=e[t],s=mA(n);s!==n&&(e[t]=s)}else for(let t in e){let r=e[t],n=mA(r);n!==r&&(e[t]=n)}return e}else return Bx(e)}a(mA,"autoCastJSONDeep");function Hx(e){if(e.startsWith("0.")&&Lx(e))return!0;let t=e.toUpperCase().includes("E");return!!((e!=="0"&&e.startsWith("0"))===!1&&t===!1&&Lx(e))}a(Hx,"autoCasterIsNumberCheck");async function rie(e){if(as(e))throw new Error(`Directory path: ${e} does not exist`);try{await Cx.emptyDir(e),await Cx.remove(e)}catch(t){throw gr.error(`Error removing files in ${e} -- ${t}`),t}}a(rie,"removeDir");function nie(e,t){if(as(e)){gr.info("Invalid current version sent as parameter.");return}if(as(t)){gr.info("Invalid upgrade version sent as parameter.");return}let r,n=/(\.0+)+$/,s=e.version?e.version:e,i=t.version?t.version:t,o=s.replace(n,"").split("."),c=i.replace(n,"").split("."),u=Math.min(o.length,c.length);for(let _=0;_<u;_++)if(r=parseInt(o[_],10)-parseInt(c[_],10),r)return r;return o.length-c.length}a(nie,"compareVersions");function sie(e,t,r=!1){let n=e.toString().split("."),s=t.toString().split(".");return n[0]===s[0]&&(!r||n[1]===s[1])}a(sie,"isCompatibleDataVersion");function iie(e){if(Qr(e))return e;let t=String(e);return t==="."?it.UNICODE_PERIOD:t===".."?it.UNICODE_PERIOD+it.UNICODE_PERIOD:t.replace(it.FORWARD_SLASH_REGEX,it.UNICODE_FORWARD_SLASH)}a(iie,"escapeRawValue");function oie(e){if(Qr(e))return e;let t=String(e);return t===it.UNICODE_PERIOD?".":t===it.UNICODE_PERIOD+it.UNICODE_PERIOD?"..":String(e).replace(it.ESCAPED_FORWARD_SLASH_REGEX,"/")}a(oie,"unescapeValue");function aie(e,t){if(Qr(e))return gr.info("Properties object is null"),"";let r="";return e.each(function(n,s){try{if(t&&t[n]){let i=t[n];for(let o of i)r+=";"+o+$E.EOL}!as(n)&&n[0]===";"?r+=" "+n+s+$E.EOL:as(n)||(r+=n+"="+s+$E.EOL)}catch{gr.error(`Found bad property during upgrade with key ${n} and value: ${s}`)}}),r}a(aie,"stringifyProps");function xx(){let e;try{e=$E.homedir()}catch{e=process.env.HOME}return e||(e="~/"),e}a(xx,"getHomeDir");function cie(){let e=Ai.join(xx(),it.HDB_HOME_DIR_NAME,it.BOOT_PROPS_FILE_NAME);return Ux.existsSync(e)||(e=Ai.join(__dirname,"../","hdb_boot_properties.file")),e}a(cie,"getPropsFilePath");function uie(e,t){let r,n;return n=new Promise(function(s){r=setTimeout(function(){s(t)},e)}),{promise:n,cancel:function(){clearTimeout(r)}}}a(uie,"timeoutPromise");async function lie(e){if(!e)throw new Error("Invalid port passed as parameter");return new Promise((t,r)=>{let n=Bse.createServer().once("error",s=>{s.code==="EADDRINUSE"?t(!0):r(s)}).once("listening",()=>n.once("close",()=>t(!1)).close()).listen(e)})}a(lie,"isPortTaken");function _ie(e){try{return it.CLUSTER_OPERATIONS[e.toLowerCase()]!==void 0}catch(t){gr.error(`Error checking operation against cluster ops ${t}`)}return!1}a(_ie,"isClusterOperation");function die(e,t){let r=(be(),te(qe)).getDatabases();if(!r[e])return KE.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e);if(!r[e][t])return KE.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(die,"checkGlobalSchemaTable");function fie(e,t){if(Qr(t)){gr.warn("No CLUSTERING_USER defined, clustering disabled");return}if(Qr(e)||as(e)){gr.warn("No users to search.");return}let r;try{let n=e.get(t);n&&n.role.permission.cluster_user===!0&&n.active===!0&&(r=n)}catch(n){gr.error(`unable to find cluster_user due to: ${n.message}`);return}if(r===void 0){gr.warn(`CLUSTERING_USER: ${t} not found or is not active.`);return}return r}a(fie,"getClusterUser");function Eie(){Dx.parsePromise=function(e,t,r){return new Promise(function(n,s){Dx.parse(e,{header:!0,transformHeader:qx,chunk:t.bind(null,s),skipEmptyLines:!0,transform:r,dynamicTyping:!1,error:s,complete:n})})}}a(Eie,"promisifyPapaParse");function qx(e){if(typeof e!="string")throw new TypeError(`Expected a string, got ${typeof e}`);return e.charCodeAt(0)===65279?e.slice(1):e}a(qx,"removeBOM");function hie(e,t,r){return new Promise(n=>{t.once(e,s=>{let i=r;gr.info(`Got cluster status event response: ${qse(s)}`);try{i.cancel()}catch{gr.error("Error trying to cancel timeout.")}n(s)})})}a(hie,"createEventPromise");async function mie(e){let t=!0,r=0;do await Px($se*r++),(await xse.findPs(e)).length>0&&(t=!1);while(t&&r<Yse);if(t)throw new Error(`process ${e} was not started`)}a(mie,"checkProcessRunning");function pie(e,t){let r=Fx(e);if(r)return r;let n=Gx(e,t);if(n)return n}a(pie,"checkSchemaTableExist");function Fx(e){let{getDatabases:t}=(be(),te(qe));if(!t()[e])return KE.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}a(Fx,"checkSchemaExists");function Gx(e,t){let{getDatabases:r}=(be(),te(qe));if(!r()[e][t])return KE.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(Gx,"checkTableExists");function Sie(){let e=YE().utc().add(1,it.MOMENT_DAYS_TAG).startOf(it.MOMENT_DAYS_TAG).unix(),t=YE().utc().unix();return e-t}a(Sie,"getStartOfTomorrowInSeconds");function Tie(){return YE().utc().format("DD-MM-YYYY")}a(Tie,"getLimitKey");function gie(e){try{let t=new Hse(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){gr.error("Got an error back ticking items."),gr.error(t)}}a(gie,"backtickASTSchemaItems");function Rie(e){return[e]}a(Rie,"createForkArgs");function Aie(e){return e===!0||typeof e=="string"&&e.toLowerCase()==="true"}a(Aie,"autoCastBoolean");function Oie(e,t){let{getDatabases:r}=(be(),te(qe)),n=r()[e]?.[t];return n?.primaryKey||n?.hash_attribute}a(Oie,"getTableHashAttribute");function bie(e){let{getDatabases:t}=(be(),te(qe));return t()[e]!==void 0}a(bie,"doesSchemaExist");function Nie(e,t){let{getDatabases:r}=(be(),te(qe));return r()[e]?.[t]!==void 0}a(Nie,"doesTableExist");function yie(e){try{return JSON.stringify(e)}catch{return e}}a(yie,"stringifyObj");function wie(e){let t=YE.duration(e),r=t.seconds()>0?t.seconds()+"s":"",n=t.minutes()>0?t.minutes()+"m ":"",s=t.hours()>0?t.hours()+"h ":"",i=t.days()>0?t.days()+"d ":"";return(t.years()>0?t.years()+"y ":"")+i+s+n+r}a(wie,"ms_to_time");function Iie(e,t){let r=Ai.basename(e,Ai.extname(e));return Ai.join(Ai.dirname(e),r+t)}a(Iie,"changeExtension");function pA(){if(process.env[it.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return process.env[it.CONFIG_PARAMS.ROOTPATH.toUpperCase()];let e=Fse(process.argv);if(e[it.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return e[it.CONFIG_PARAMS.ROOTPATH.toUpperCase()]}a(pA,"getEnvCliRootPath");var hA;function Cie(){if(hA)return hA;let e=pA();pA()&&Ux.pathExistsSync(Ai.join(e,it.HDB_CONFIG_FILE))&&(hA=!0)}a(Cie,"noBootFile");function Die(e,t){let r;return e.protocol==="http:"?r=kse:r=Gse,new Promise((n,s)=>{let i=r.request(e,o=>{o.setEncoding("utf8");let c={body:"",headers:o.headers};o.on("data",u=>{c.body+=u}),o.on("end",()=>{n(c)})});i.on("error",o=>{s(o)}),i.write(JSON.stringify(t)),i.end()})}a(Die,"httpRequest");function Lie(e){if(!e.schema&&!e.database){e.schema=it.DEFAULT_DATABASE_NAME;return}e.database&&(e.schema=e.database)}a(Lie,"transformReq");function Mie(e){let t=0;if(typeof e=="number"&&(t=e),typeof e=="string")switch(t=parseFloat(e),e.slice(-1)){case"M":t*=86400*30;break;case"D":case"d":t*=86400;break;case"H":case"h":t*=3600;break;case"m":t*=60;break}return t*1e3}a(Mie,"convertToMS")});var SA=M(),Vx=J(),bl=Y(),Uie=ms(),Pie=Mr(),vie=jg(),{start:Bie}=(RR(),te(oE)),{closeConnection:Hie}=ft(),$x=require("moment"),Yx=xf(),{cloneDeep:xie}=require("lodash"),qie=process.env[SA.PROCESS_NAME_ENV_PROP],Io=qie.substring(4);a(async function(){let t={id:Io,request:void 0},r=0;try{bl.notify("Starting job:",Io),Bie(),Uie.setSchemaDataToGlobal(),await Pie.setUsersToGlobal();let n=await Yx.getJobById(Io);if(Vx.isEmptyOrZeroLength(n))throw new Error(`Unable to find a record in hdb_job for job: ${Io}`);let{request:s}=n[0];if(Vx.isEmptyOrZeroLength(s))throw new Error("Did not find job request in hdb_job table, unable to proceed");s=xie(s);let i=vie.getOperationFunction(s);bl.trace("Running operation:",s.operation,"for job",Io);let o=await i.job_operation_function(s);bl.trace("Result from job:",Io,o),t.status=SA.JOB_STATUS_ENUM.COMPLETE,t.message=o,t.end_datetime=$x().valueOf(),bl.notify("Successfully completed job:",Io)}catch(n){r=1,bl.error(n),t.status=SA.JOB_STATUS_ENUM.ERROR,t.message=n.message?n.message:n,t.end_datetime=$x().valueOf()}finally{await Yx.updateJob(t),await Hie(),setTimeout(()=>{process.exit(r)},3e3).unref()}},"job")();
|
|
26
|
+
`},compressible:!1,q:.8});Pt.set("application/x-www-form-urlencoded",{deserialize(e){let t={};for(let[r,n]of new URLSearchParams(e))if(t.hasOwnProperty(r)){let s=t[r];Array.isArray(s)?s.push(n):t.key=[s,n]}else t[r]=n},serialize(e){let t=new URLSearchParams;for(let r in e)t.set(r,e);return t.toString()}});fv={type:"application/json",serializeStream:mc,serialize:Wu,deserialize:A7,q:.8};Pt.set("*/*",fv);Pt.set("",fv);a(A7,"tryJSONParse");a(fg,"registerContentHandlers");O7=require("fastify-plugin"),b7=O7(function(e,t,r){e.addHook("preSerialization",async(n,s)=>{if(s.raw.getHeader("content-type"))return;let{serializer:o,type:c}=hf(n.raw);s.type(c),s.serializer(function(u){return(o.serializeStream||o.serialize)(u,{headers:{set:(_,l)=>{s.header(_,l)}}})})}),r()},{name:"content-type-negotiation"});a(hf,"findBestSerializer");cv=ug.default.get(lg.CONFIG_PARAMS.HTTP_COMPRESSIONTHRESHOLD);a(mf,"serialize");a(Ei,"serializeMessage");a(y7,"streamToBuffer");a(Eo,"getDeserializer");a(uv,"deserializerUnknownType");a(N7,"transformIterable")});function mg(e,t,r,n,s,i,o,c){let u=e[0];if(t==="or"){let d=_(u);for(let E=1;E<e.length;E++){let h=e[E],p=_(h);d=d.concat(p)}let f=new Set;return d.filter(E=>{let h=E.key??E;return f.has(h)?!1:(f.add(h),!0)})}else{let d=_(u),f=l(e.slice(1),!0,u.estimated_count);return f.length>0?o(d,f):d}function _(d){return d.conditions?mg(d.conditions,d.operator,r,n,s,i,o,c):Na(d,n,d.descending||s.reverse===!0,r,s.allowFullScan,c)}a(_,"executeCondition");function l(d,f,E){return d.map((h,p)=>{if(h.conditions){let g=h.operator==="or",R=l(h.conditions,!g,E);return g?(B,H)=>R.some(v=>v(B,H)):(B,H)=>R.every(v=>v(B,H))}let S=(h.attribute||h[0])===r.primaryKey,O=Sg(h,r,i,c,S,E);return f&&p<d.length-1&&E&&(E=v7(r.primaryStore,h.estimated_count,E)),O}).filter(Boolean)}a(l,"mapConditionsToFilters")}function Na(e,t,r,n,s,i){let o=e[0]??e.attribute,c=e[1]??e.value,u=e.comparator;if(Array.isArray(o)){let g=o[0],R=vs(n.attributes,g);if(R.relationship){if(o.length<2)throw new Ps.ClientError("Can not directly query a relational attribute, must query an attribute within the target table");let B=R.definition?.tableClass||R.elements?.definition?.tableClass,H=new Map,v=Na({attribute:o.length>2?o.slice(1):o[1],value:c,comparator:u},t,r,B,s,H);if(R.relationship.to){i[o[0]]=H;let M=!!vs(B.attributes,R.relationship.to)?.elements;v=L7(v,R,B.primaryStore,M,H)}if(R.relationship.from){let M=a($=>Na({attribute:R.relationship.from,value:$},t,r,n,s,H),"searchEntry");R.elements?(i[o[0]]=H,v=M7(v,R,B.primaryStore,H,M)):v=v.flatMap(M)}return v}else if(o.length===1)o=o[0];else throw new Ps.ClientError("Unable to query by attribute "+JSON.stringify(o))}let _,l,d,f;c instanceof Date&&(c=c.getTime());let E;switch(pg[u]||u){case"lt":_=!0,l=c;break;case"le":_=!0,l=c,d=!0;break;case"gt":_=c,f=!0;break;case"ge":_=c;break;case"prefix":Array.isArray(c)?c[c.length-1]!=null&&(c=c.concat(null)):c=[c,null],_=c,l=c.slice(0),l[l.length-1]=ss.MAXIMUM_KEY;break;case"starts_with":_=c.toString(),l=c+"\uFFFF";break;case"between":_=c[0],_ instanceof Date&&(_=_.getTime()),l=c[1],l instanceof Date&&(l=l.getTime()),d=!0;break;case"equals":case void 0:_=c,l=c,d=!0;break;case"ne":if(c===null){_=c,f=!0;break}case"sort":case"contains":case"ends_with":_=!0,E=!0;break;default:throw new Ps.ClientError(`Unknown query comparator "${u}"`)}if(r){let g=_;_=l,l=g,g=!f,f=!d,d=g}let h=o===n.primaryKey||o==null,p=h?n.primaryStore:n.indices[o],S;if(!p||p.isIndexing||E||c===null&&!p.indexNulls){if(!s)throw new Ps.ClientError(E?`Can not use ${u} operator without combining with a condition that uses an index`:`"${o}" is not indexed${c===null&&!p.indexNulls?" for nulls, index needs to be rebuilt to search for nulls":p?.isIndexing?" yet":""}, can not search for this attribute`,404);if(S=Sg(e),!S)throw new Ps.ClientError(`Unknown search operator ${e.comparator}`)}let O={start:_,end:l,inclusiveEnd:d,exclusiveStart:f,values:!0,versions:h,transaction:t,reverse:r};if(h){let g=p.getRange(O).map(S?({key:R,value:B})=>new Promise((H,v)=>setImmediate(()=>{try{H(B&&S(B)?R:zu.SKIP)}catch(M){v(M)}})):R=>R.value==null?zu.SKIP:R);return g.hasEntries=!0,g}else return p?p.getRange(O).map(S?({key:g,value:R})=>new Promise((B,H)=>setImmediate(()=>{try{B(S({[o]:g})?R:zu.SKIP)}catch(v){H(v)}})):({value:g})=>g):n.primaryStore.getRange(r?{end:!0,transaction:t,reverse:!0}:{start:!0,transaction:t}).map(({key:g,value:R})=>new Promise((B,H)=>setImmediate(()=>{try{B(R&&S(R)?g:zu.SKIP)}catch(v){H(v)}})))}function vs(e,t){if(Array.isArray(t))if(t.length>1){let r=vs(e,t[0]),n=(r?.definition?.tableClass||r?.elements.definition?.tableClass)?.attributes;return n?vs(n,t.slice(1)):void 0}else t=t.toString();else typeof t!="string"&&(t=t.toString());return e.find(r=>r.name===t)}function L7(e,t,r,n,s){return new e.constructor({[Symbol.iterator](){let i;s.hasMappings=!0;let o;return{next(){if(!i){let u=t.relationship.to;return(async()=>{let _=a((d,f)=>{let E=d;Array.isArray(d)&&(E=Mn(d),o=!0);let h=s.get(E);h?h.push(f):s.set(E,h=[f]),d!==E&&(h.key=d)},"add_entry"),l=0;for await(let d of e){let f=d.value??r.get(d.key??d),E=f?.[u];if(E!=null&&!s.filters?.some(h=>!h(f))){if(n)for(let h=0;h<E.length;h++)_(E[h],d);else _(E,d);l++>100&&(await new Promise(setImmediate),l=0)}}return i=(o?s:s.keys())[Symbol.iterator](),this.next()})()}let c=i.next();return c.done?c:{value:o?c.value[1].key||c.value[0]:c.value}}}}})}function M7(e,t,r,n,s){return new e.constructor({[Symbol.iterator](){let i,o,c=new Set;return{next(){let u;if(o)for(;u=o.next(),!u.done;){let _=Mn(u.value);if(!c.has(_))return c.add(_),u}if(!i)return(async()=>{let _=new Map;n.fromRecord=d=>d[t.relationship.from]?.filter?.(f=>_.has(Mn(f)));let l=0;for await(let d of e){if(n.filters){let f=r.get(d);if(n.filters.some(E=>!E(f)))continue}_.set(Mn(d),d),l++>100&&(await new Promise(setImmediate),l=0)}return i=_.values()[Symbol.iterator](),this.next()})();do{let _=i.next();return _.done?_:(o=s(_.value)[Symbol.iterator](),this.next())}while(!0)},return(){return o?.return?.()},throw(){return o?.throw?.()}}}})}function Sg(e,t,r,n,s,i){let o=e.comparator,c=e[0]??e.attribute,u=e[1]??e.value;if(Array.isArray(c)){if(c.length===0)return()=>!0;if(c.length===1)c=c[0];else if(c.length>1){let l=c[0],d=vs(t.attributes,l),f=d.definition?.tableClass||d.elements.definition?.tableClass,E=n?.[l],h=Sg({attribute:c.length>2?c.slice(1):c[1],value:u,comparator:o},f,r,E?.[l]?.joined,c[1]===f.primaryKey,i);if(!h)return;if(E){E.filters||(E.filters=[]),E.filters.push(h);return}let p=t.propertyResolvers?.[l],S,O=a((g,R)=>{let B,H;if(p){if(p.from&&h.idFilter){if(!S)if(h.idFilter.idSet?.size===1){for(let M of h.idFilter.idSet)e={attribute:p.from,value:M};S=_(p.from,h.idFilter,!0)}else S=_(p.from,h.idFilter,!1);let v=S(g);return S.idFilter&&(O.idFilter=S.idFilter),v}H=p(g,r,R),B=H?.value}else B=g[l];return B?Array.isArray(B)?B.some(h):h(B,H):!1},"recordFilter");return O}}switch(u instanceof Date&&(u=u.getTime()),pg[o]||o){case Eg.SEARCH_TYPES.EQUALS:case void 0:return _(c,l=>l===u,!0);case"contains":return _(c,l=>l?.toString().includes(u));case"ends_with":return _(c,l=>l?.toString().endsWith(u));case"starts_with":return _(c,l=>typeof l=="string"&&l.startsWith(u),!0);case"prefix":return Array.isArray(u)?u[u.length-1]==null&&(u=u.slice(0,-1)):u=[u],_(c,l=>{if(!Array.isArray(l))return!1;for(let d=0,f=u.length;d<f;d++)if(l[d]!==u[d])return!1;return!0},!0);case"between":return u[0]instanceof Date&&(u[0]=u[0].getTime()),u[1]instanceof Date&&(u[1]=u[1].getTime()),_(c,l=>(0,ss.compareKeys)(l,u[0])>=0&&(0,ss.compareKeys)(l,u[1])<=0,!0);case"gt":return _(c,l=>(0,ss.compareKeys)(l,u)>0);case"ge":return _(c,l=>(0,ss.compareKeys)(l,u)>=0);case"lt":return _(c,l=>(0,ss.compareKeys)(l,u)<0);case"le":return _(c,l=>(0,ss.compareKeys)(l,u)<=0);case"ne":return _(c,l=>(0,ss.compareKeys)(l,u)!==0);case"sort":return()=>!0;default:throw new Ps.ClientError(`Unknown query comparator "${o}"`)}function _(l,d,f){let E;f=f&&!s&&t?.indices[l]&&i>3,f&&(e.estimated_count==null&&Sf(t)(e),E=e.estimated_count>>4,(isNaN(E)||E>=i)&&(f=!1));let h=0,p=3;function S(O){let g=O[l],R;if(typeof g!="object"||!g?R=d(g):Array.isArray(g)?R=g.some(d):g instanceof Date&&(R=d(g.getTime())),f&&(p++,!R&&!S.idFilter&&++h/p*(i-p)>E)){let B=Na(e,r.transaction.getReadTxn(),!1,t).map(Mn),H=new Set(B);S.idFilter=v=>H.has(Mn(v)),S.idFilter.idSet=H}return R}return a(S,"recordFilter"),s&&(S.idFilter=d),S}a(_,"attributeComparator")}function Sf(e){function t(r){if(r.estimated_count===void 0){if(r.conditions){let s;if(r.operator==="or"){s=0;for(let i of r.conditions)t(i),s+=i.estimated_count}else{s=1/0;for(let i of r.conditions)t(i),s=isFinite(s)?s*i.estimated_count/Us(e.primaryStore):i.estimated_count}return r.estimated_count=s,r.estimated_count}let n=r.comparator||r.search_type;if(n=pg[n]||n,n===Eg.SEARCH_TYPES.EQUALS||!n){let s=r[0]??r.attribute;if(s==null||s===e.primaryKey)r.estimated_count=1;else if(Array.isArray(s)&&s.length>1){let i=vs(e.attributes,s[0]),o=i.definition?.tableClass||i.elements.definition?.tableClass,c=Sf(o)({value:r.value,attribute:s.length>2?s.slice(1):s[1],comparator:"equals"});r.estimated_count=c*Us(e.indices[i.relationship.from]||e.primaryStore)/(Us(o.primaryStore)||1)}else{let i=e.indices[s];r.estimated_count=i?i.getValuesCount(r[1]??r.value):1/0}}else if(n==="contains"||n==="ends_with"||n==="ne"){let s=r[0]??r.attribute,i=e.indices[s];r.value===null&&n==="ne"?r.estimated_count=Us(e.primaryStore)-(i?i.getValuesCount(null):0):r.estimated_count=1/0}else n==="starts_with"||n==="prefix"?r.estimated_count=C7*Us(e.primaryStore)+1:n==="between"?r.estimated_count=I7*Us(e.primaryStore)+1:n==="sort"?r.estimated_count=Us(e.primaryStore)+1:r.estimated_count=w7*Us(e.primaryStore)+1;typeof r.descending=="boolean"&&(r.estimated_count/=2)}return r.estimated_count}return a(t,"estimateConditionForTable"),t}function Tf(e){if(e)if(pi=e,ba.lastIndex=0,U7.test(e))try{let t=Ju(new ya,"");if(hr!==pi.length)throw new SyntaxError("Unable to parse query, unexpected end of query");return t}catch(t){throw t.statusCode=400,t.message=`Unable to parse query, ${t.message} at position ${hr} in '${pi}'`,t}else{let t=new URLSearchParams(e);return t.conditions=t,t}}function Ju(e,t){let r=ba,n,s,i,o,c,u=decodeURIComponent,_;for(;n=r.exec(pi);){hr=r.lastIndex;let[,l,d]=n;if(o){if(l)throw new SyntaxError(`expected operator, but encountered '${l}'`);o=!1,c=!1}else c=!0;let f;switch(d){case"=":if(s){if(l.length<=2)i=l;else throw new SyntaxError(`invalid FIQL operator ${l}`);u=hv}else{if(u=decodeURIComponent,i="equals",!l)throw new SyntaxError("attribute must be specified before equality comparator");s=ju(l)}break;case"==":case"!=":case"<":case"<=":case">":case">=":case"===":case"!==":if(i=D7[d],u=hg[i]?hv:decodeURIComponent,!l)throw new SyntaxError(`attribute must be specified before comparator ${d}`);s=ju(l);break;case"|":case"&":case"":case void 0:if(s==null){if(s===void 0)throw t?new SyntaxError(`expected '${t}', but encountered ${d[0]?"'"+d[0]+"'":"end of string"}}`):new SyntaxError(`no comparison specified before ${d?"'"+d+"'":"end of string"}`)}else{if(!e.conditions)throw new SyntaxError("conditions/comparisons are not allowed in a property list");let h={comparator:i,attribute:s,value:u(l)};i==="eq"&&mv(h,l),pf(e,_),e.conditions.push(h)}d==="&"&&(_="and"),d==="|"&&(_="or"),s=void 0;break;case",":if(e.conditions)throw new SyntaxError("conditions/comparisons are not allowed in a property list");e.push(ju(l)),s=void 0;break;case"(":ba.lastIndex=hr;let E=Ju(l?[]:new ya,")");switch(l){case"":pf(e,_),e.conditions.push(E);break;case"limit":switch(E.length){case 1:e.limit=+E[0];break;case 2:e.offset=+E[0],e.limit=E[1]-e.offset;break;default:throw new SyntaxError("limit must have 1 or 2 arguments")}break;case"select":Array.isArray(E[0])&&E.length===1&&!E[0].name?(e.select=E[0],e.select.asArray=!0):E.length===1?e.select=E[0]:E.length===2&&E[1]===""?e.select=E.slice(0,1):e.select=E;break;case"group-by":throw new SyntaxError("group by is not implemented yet");case"sort":e.sort=pv(E);break;default:throw new SyntaxError(`unknown query function call ${l}`)}pi[hr]===","?r.lastIndex=++hr:o=!0,s=null;break;case"{":if(e.conditions)throw new SyntaxError("property sets are not allowed in a queries");if(!l)throw new SyntaxError("property sets must have a defined parent property name");ba.lastIndex=hr,f=Ju([],"}"),f.name=l,e.push(f),pi[hr]===","?r.lastIndex=++hr:o=!0;break;case"[":ba.lastIndex=hr,l?(f=Ju(new ya,"]"),f.name=l):f=Ju(e.conditions?new ya:[],"]"),e.conditions?(pf(e,_),e.conditions.push(f),s=null):e.push(f),pi[hr]===","?r.lastIndex=++hr:o=!0;break;case")":case"]":case"}":if(t===d[0]){if(e.conditions){if(s){let h={comparator:i||"equals",attribute:s,value:u(l)};i==="eq"&&mv(h,l),pf(e,_),e.conditions.push(h)}else if(l)throw new SyntaxError("no attribute or comparison specified")}else(l||e.length>0&&c)&&e.push(ju(l));return e}else throw t?new SyntaxError(`expected '${t}', but encountered '${d[0]}'`):new SyntaxError(`unexpected token '${d[0]}'`);default:throw new SyntaxError(`unexpected operator '${d}'`)}if(t!==")"&&(r=s?P7:ba,r.lastIndex=hr),hr===pi.length)return e}if(t)throw new SyntaxError(`expected '${t}', but encountered end of string`)}function pf(e,t){if(e.conditions.length>0)if(e.operator){if(e.operator!==t)throw new SyntaxError("Can not mix operators within a condition grouping")}else e.operator=t}function ju(e){return e.indexOf(".")>-1?e.split(".").map(ju):decodeURIComponent(e)}function hv(e){if(e==="null")return null;if(e.indexOf(":")>-1){let[t,r]=e.split(":");if(t==="number")return+r;if(t==="boolean")return r==="true";if(t==="date")return new Date(decodeURIComponent(r));if(t==="string")return decodeURIComponent(r);throw new Ps.ClientError(`Unknown type ${t}`)}return decodeURIComponent(e)}function mv(e,t){if(t.indexOf("*")>-1)if(t.endsWith("*"))e.comparator="starts_with",e.value=decodeURIComponent(t.slice(0,-1));else throw new Ps.ClientError("wildcard can only be used at the end of a string")}function pv(e){let t=Sv(e[0]);return e.length>1&&(t.next=pv(e.slice(1))),t}function Sv(e){if(Array.isArray(e)){let t=Sv(e[0]);return e[0]=t.attribute,t.attribute=e,t}if(typeof e=="string")switch(e[0]){case"-":return{attribute:e.slice(1),descending:!0};case"+":return{attribute:e.slice(1),descending:!1};default:return{attribute:e,descending:!1}}throw new SyntaxError(`Unknown sort type ${e}`)}function Mn(e){return Array.isArray(e)?e.join("\0"):e}function Us(e){let t=Date.now();return(e.estimatedEntryCountExpires||0)<t&&(e.estimatedEntryCount=e.getStats().entryCount,e.estimatedEntryCountExpires=t+1e4),e.estimatedEntryCount}function v7(e,t,r){return t*r/Us(e)}var Ps,Eg,ss,zu,w7,I7,C7,D7,hg,pg,U7,ba,P7,hr,pi,ya,gf=Oe(()=>{Ps=x(ee()),Eg=x(lt()),ss=require("ordered-binary"),zu=require("lmdb"),w7=.3,I7=.1,C7=.05,D7={"<":"lt","<=":"le",">":"gt",">=":"ge","!=":"ne","==":"eq","===":"equals","!==":"not_equal"},hg={lt:!0,le:!0,gt:!0,ge:!0,ne:!0,eq:!0};a(mg,"executeConditions");a(Na,"searchByIndex");a(vs,"findAttribute");a(L7,"joinTo");a(M7,"joinFrom");pg={eq:"equals",greater_than:"gt",greaterThan:"gt",greater_than_equal:"ge",greaterThanEqual:"ge",less_than:"lt",lessThan:"lt",less_than_equal:"le",lessThanEqual:"le",not_equal:"ne",notEqual:"ne",equal:"equals",sw:"starts_with",startsWith:"starts_with",ew:"ends_with",endsWith:"ends_with",ct:"contains",">":"gt",">=":"ge","<":"lt","<=":"le","...":"between"};a(Sg,"filterByType");a(Sf,"estimateCondition");U7=/[()[\]|!<>.]|(=\w*=)/,ba=/([^?&|=<>!([{}\]),]*)([([{}\])|,&]|[=<>!]*)/g,P7=/([^&|=[\]{}]+)([[\]{}]|[&|=]*)/g;a(Tf,"parseQuery");a(Ju,"parseBlock");a(pf,"assignOperator");a(ju,"decodeProperty");a(hv,"typedDecoding");a(mv,"wildcardDecoding");a(pv,"toSortObject");a(Sv,"toSortEntry");ya=class{static{a(this,"Query")}constructor(){this.conditions=[]}[Symbol.iterator](){return this.conditions[Symbol.iterator]()}get(t){for(let r=0;r<this.conditions.length;r++){let n=this.conditions[r];if(n.attribute===t)return n.value}}};a(Mn,"flattenKey");a(Us,"estimatedEntryCount");a(v7,"intersectionEstimate")});function Ov(e){let t={openapi:B7,info:{title:"HarperDB HTTP REST interface",version:(0,Av.version)()},paths:{},components:{schemas:{},securitySchemes:{basicAuth:{type:"http",scheme:"basic"},bearerAuth:{type:"http",scheme:"bearer",bearerFormat:"JWT"}}}},r=[{basicAuth:[],bearerAuth:[]}];for(let[,n]of e){if(!n.path)continue;let{path:s}=n,i=s.split("/").slice(-1),{attributes:o,primaryKey:c,prototype:u}=n.Resource;if(c=c??"id",!c)continue;let _={},l=[];if(o)for(let{type:R,name:B,elements:H,relationship:v,definition:M}of o){if(v)R==="array"?_[B]={type:"array",items:{$ref:Si+H.type}}:_[B]={$ref:Si+R};else{let $=M??H?.definition;if($){if(!t.components.schemas[$.type]){let W={};$.properties.forEach(z=>{W[z.name]=new Ag(Tg[z.type],z.type)}),t.components.schemas[$.type]=new Rv(W)}R==="array"?_[B]={type:"array",items:{$ref:Si+$.type}}:_[B]={$ref:Si+$.type}}else R==="array"?H.type==="Any"||H.type=="ID"?_[B]={type:"array",items:{format:H.type}}:_[B]={type:"array",items:new Ag(Tg[H.type],H.type)}:R==="Any"||R=="ID"?_[B]={format:R}:_[B]=new Ag(Tg[R],R)}l.push(new Og(B,"query",_[B]))}let d=Object.keys(_),f=new Og(c,"path",{format:"ID"});f.required=!0,f.description="primary key of record";let E=new Og("property","path",{enum:d});E.required=!0,t.components.schemas[i]=new Rv(_);let h=u.post!==Resource.prototype.post||u.update,p=typeof u.put=="function",S=typeof u.get=="function",O=typeof u.delete=="function",g="/"+s+"/";h&&(t.paths[g]={},t.paths[g].post=new H7(i,r,"create a new record auto-assigning a primary key")),S&&(t.paths[g]||(t.paths[g]={}),t.paths[g].get=new gg(l,r,{200:new Rg({$ref:Si+i})},"search for records by the specified property name and value pairs")),O&&(t.paths[g]||(t.paths[g]={}),t.paths[g].delete=new gv(l,r,"delete all the records that match the provided query",{204:new Tv})),g="/"+s+"/{"+c+"}",S&&(t.paths[g]={},t.paths[g].get=new gg([f],r,{200:new Rg({$ref:Si+i})},"retrieve a record by its primary key")),p&&(t.paths[g]||(t.paths[g]={}),t.paths[g].put=new x7([f],r,i,"create or update the record with the URL path that maps to the record's primary key")),O&&(t.paths[g]||(t.paths[g]={}),t.paths[g].delete=new gv([f],r,"delete a record with the given primary key",{204:new Tv})),S&&E.schema.enum.length>0&&(g="/"+s+"/{"+c+"}.{property}",t.paths[g]={},t.paths[g].get=new gg([f,E],r,{200:new Rg({enum:d})},"used to retrieve the specified property of the specified record"))}return t}function H7(e,t,r){this.description=r,this.requestBody={content:{"application/json":{schema:{$ref:Si+e}}}},this.security=t,this.responses={200:{description:bg,headers:{Location:{description:"primary key of new record",schema:{type:"string",format:"ID"}}},content:{"application/json":{schema:{type:"string",format:"ID"}}}}}}function gg(e,t,r,n){this.description=n,this.parameters=e,this.security=t,this.responses=r}function Rg(e){this.description=bg,this.content={"application/json":{schema:e}}}function Tv(){this.description="successfully processed request, no content returned to client"}function x7(e,t,r,n){this.description=n,this.parameters=e,this.security=t,this.requestBody={content:{"application/json":{schema:{$ref:Si+r}}}},this.responses={200:{description:bg}}}function gv(e,t,r,n){this.description=r,this.parameters=e,this.security=t,this.responses=n}function Rv(e){this.type="object",this.properties=e}function Ag(e,t){this.type=e,this.format=t}function Og(e,t,r){this.name=e,this.in=t,this.schema=r}var Av,B7,Tg,Si,bg,bv=Oe(()=>{Av=x(Sd()),B7="3.0.3",Tg={Int:"integer",Float:"number",Long:"integer",String:"string",Boolean:"boolean",Date:"string",Bytes:"string",BigInt:"integer",array:"array"},Si="#/components/schemas/",bg="successful operation";a(Ov,"generateJsonApi");a(H7,"Post");a(gg,"Get");a(Rg,"Response200");a(Tv,"Response204");a(x7,"Put");a(gv,"Delete");a(Rv,"ResourceSchema");a(Ag,"Type");a(Og,"Parameter")});var Af={};ke(Af,{start:()=>G7});async function F7(e,t){let r=e.headers.asObject,n=r.accept==="text/event-stream"?"CONNECT":e.method;e.search&&Tf(e);let s=new fi;try{e.responseHeaders=s;let i=e.url.slice(1),o,c;if(i!==yv){let h=Rf.getMatch(i);if(!h)return t(e);e.handlerPath=h.path,o={url:h.relativeURL,async:!0},c=h.Resource}let u=r["cache-control"];if(u){u=u.toLowerCase();let h=u.match(/max-age=(\d+)/)?.[1];h&&(e.expiresAt=h*1e3+Date.now()),u.includes("only-if-cached")&&(e.onlyIfCached=!0),u.includes("no-cache")&&(e.noCache=!0),u.includes("no-store")&&(e.noCacheStore=!0),u.includes("stale-if-error")&&(e.staleIfError=!0),u.includes("must-revalidate")&&(e.mustRevalidate=!0)}let _=await Ke(e,()=>{if(n==="POST"||n==="PUT"||n==="PATCH"||n==="QUERY")try{e.data=Eo(r["content-type"],!0)(e.body)}catch(h){throw new wa.ClientError(h,400)}if(e.authorize=!0,i===yv&&n==="GET"){if(e?.user?.role?.permission?.super_user)return Ov(Rf);throw new wa.ServerError("Forbidden",403)}switch(n){case"GET":case"HEAD":return c.get(o,e);case"POST":return c.post(o,e.data,e);case"PUT":return c.put(o,e.data,e);case"DELETE":return c.delete(o,e);case"PATCH":return c.patch(o,e.data,e);case"OPTIONS":s.setIfNone("Allow","GET, HEAD, POST, PUT, DELETE, PATCH, OPTIONS, TRACE, QUERY, COPY, MOVE");return;case"CONNECT":return c.connect(o,null,e);case"TRACE":return"HarperDB is the terminating server";case"QUERY":return c.query(o,e.data,e);case"COPY":return c.copy(o,r.destination,e);case"MOVE":return c.move(o,r.destination,e);case"BREW":throw new wa.ClientError("HarperDB is short and stout and can't brew coffee",418);default:throw new wa.ServerError(`Method ${n} is not recognized`,501)}}),l=200,d;if(_==null)l=n==="GET"||n==="HEAD"?404:204,yg.lastModified&&e.lastModified&&s.setIfNone("Last-Modified",new Date(e.lastModified).toUTCString());else if(d=e.lastModified){q7[0]=d;let h=String.fromCharCode(34,(Ft[0]&63)+62,(Ft[0]>>6)+(Ft[1]<<2&63)+62,(Ft[1]>>4)+(Ft[2]<<4&63)+62,(Ft[2]>>2)+62,(Ft[3]&63)+62,(Ft[3]>>6)+(Ft[4]<<2&63)+62,(Ft[4]>>4)+(Ft[5]<<4&63)+62,(Ft[5]>>2)+62,(Ft[6]&63)+62,(Ft[6]>>6)+(Ft[7]<<2&63)+62,34),p=r["if-none-match"];p&&h==p?(_?.onDone&&_.onDone(),l=304,_=void 0):s.setIfNone("ETag",h),yg.lastModified&&s.setIfNone("Last-Modified",new Date(d).toUTCString())}e.createdResource&&(l=201),e.newLocation&&s.setIfNone("Location",e.newLocation);let f={status:l,headers:s,body:void 0},E=_?.wasLoadedFromSource?.();return E!==void 0&&(f.wasCacheMiss=E,!E&&d&&s.setIfNone("Age",Math.round((Date.now()-(e.lastRefreshed||d))/1e3))),_!==void 0&&(f.body=mf(_,e,f),n==="HEAD"&&(f.body=void 0)),f}catch(i){i.statusCode?i.statusCode===500?ho.warn(i):ho.info(i):ho.error(i),i.statusCode===405&&(i.method&&(i.message+=` to handle HTTP method ${i.method.toUpperCase()||""}`),i.allow&&(i.allow.push("trace","head","options"),s.setIfNone("Allow",i.allow.map(c=>c.toUpperCase()).join(", "))));let o={status:i.statusCode||500,headers:s,body:void 0};return o.body=mf(i.contentType?i:i.toString(),e,o),o}}function G7(e){yg=e,!Nv&&(Nv=!0,Rf=e.resources,e.server.http(async(t,r)=>{if(!t.isWebSocket)return F7(t,r)}),e.server.ws(async(t,r,n)=>{Xu++;let s=new Rn;wv||(wv=!0,tu(l=>{Xu>0&&l.push({metric:"ws-connections",connections:Xu,byThread:!0})}));let i;t.on("error",l=>{i=!0,ho.warn(l)});let o;t.on("message",a(function(d){o||(o=Eo(r.headers.asObject["content-type"]));let f=o(d);s.push(f)},"message"));let c;t.on("close",()=>{Xu--,tn(!i,"connection","ws","disconnect"),s.emit("close"),c&&c.return()}),await n;let u=r.url.slice(1),_=Rf.getMatch(u);if(tn(!!_,"connection","ws","connect"),!_)t.send(Ei(`No resource was found to handle ${r.pathname}`,r));else{r.handlerPath=_.path,Hr(h=>({count:h.count,total:Xu}),"connections",r.handlerPath,"connect","ws");let l={url:_.relativeURL,async:!0},d=_.Resource;c=(await Ke(r,()=>d.connect(l,s,r)))[Symbol.asyncIterator]();let E;for(;!(E=await c.next()).done;){let h=Ei(E.value,r);t.send(h),Hr(h.length,"bytes-sent",r.handlerPath,"message","ws")}}t.close()}))}var ho,wa,Ft,q7,yg,yv,Nv,Rf,wv,Xu,Iv=Oe(()=>{pa();Os();ho=x(K()),wa=x(ee());gf();Ec();zi();$d();bv();Ft=new Uint8Array(8),q7=new Float64Array(Ft.buffer,0,1),yg={},yv="openapi";a(F7,"http");Xu=0;a(G7,"start")});var Ng=T((CEe,Cv)=>{var{recordAction:Of,recordActionBinary:k7}=(Os(),te(ru)),V7=require("fastify-plugin"),$7=200;Cv.exports=V7(function(e,t,r){e.addHook("onResponse",async(n,s)=>{s.getResponseTime()}),e.addHook("onSend",async(n,s,i)=>{let o=s.getResponseTime(),c=performance.now(),u=s.request.routeOptions,_,l,d;u.config?.isOperation?(_=n.body?.operation,l="operation"):(_=u.url,l="fastify-route",d=u.method),Of(o,"duration",_,d,l),k7(s.raw.statusCode<400,"success",_,d,l);let f=$7;i?.pipe?(i.on("data",h=>{f+=h.length}),i.on("end",()=>{Of(performance.now()-c,"transfer",_,d,l),Of(f,"bytes-sent",_,d,l)})):(f+=i?.length||0,Of(f,"bytes-sent",_,d,l));let E=o.toFixed(3);s.header("Server-Timing",`db;dur=${E}`)}),r()},{name:"hdb-request-time"})});var Mg=T((MEe,Uv)=>{var wf=require("clone"),If=je(),Y7=J(),yf=U(),DEe=K(),wg=require("fs"),Cg=require("joi"),{string:Nf}=Cg.types(),{hdb_errors:K7,handleHDBError:bf}=ee(),{HDB_ERROR_MSGS:LEe,HTTP_STATUS_CODES:Ig}=K7,{common_validators:Ia}=$n(),Dv=" is required",W7=["insert","update","upsert"],Dg={database:{presence:!1,format:Ia.schema_format,length:Ia.schema_length},schema:{presence:!1,format:Ia.schema_format,length:Ia.schema_length},table:{presence:!0,format:Ia.schema_format,length:Ia.schema_length},action:{inclusion:{within:W7,message:"is required and must be either insert, update, or upsert"}},file_path:{},csv_url:{url:{allowLocal:!0}},data:{},passthrough_headers:{}},Q7={schema:Nf.required(),table:Nf.required(),action:Nf.valid("insert","update","upsert")},{AWS_ACCESS_KEY:z7,AWS_SECRET:J7,AWS_BUCKET:j7,AWS_FILE_KEY:X7,REGION:Z7}=yf.S3_BUCKET_AUTH_KEYS,eee={s3:{presence:!0},[`s3.${z7}`]:{presence:!0,type:"String"},[`s3.${J7}`]:{presence:!0,type:"String"},[`s3.${j7}`]:{presence:!0,type:"String"},[`s3.${X7}`]:{presence:!0,type:"String",hasValidFileExt:[".csv",".json"]},[`s3.${Z7}`]:{presence:!0,type:"String"}},Lv=wf(Dg);Lv.data.presence={message:Dv};var Mv=wf(Dg);Mv.file_path.presence={message:Dv};var tee=Object.assign(wf(Dg),eee),Lg=wf(Q7);Lg.csv_url=Nf.uri().messages({"string.uri":"'csv_url' must be a valid url"}).required();Lg.passthrough_headers=Cg.object();function ree(e){let t=If.validateObject(e,Lv);return Cf(e,t)}a(ree,"dataObject");function nee(e){let t=If.validateBySchema(e,Cg.object(Lg));return Cf(e,t)}a(nee,"urlObject");function see(e){let t=If.validateObject(e,Mv);return Cf(e,t)}a(see,"fileObject");function iee(e){let t=If.validateObject(e,tee);return Cf(e,t)}a(iee,"s3FileObject");function Cf(e,t){if(!t){let r=Y7.checkGlobalSchemaTable(e.schema,e.table);if(r)return bf(new Error,r,Ig.BAD_REQUEST);if(e.operation===yf.OPERATIONS_ENUM.CSV_FILE_LOAD)try{wg.accessSync(e.file_path,wg.constants.R_OK|wg.constants.F_OK)}catch(n){return n.code===yf.NODE_ERROR_CODES.ENOENT?bf(n,`No such file or directory ${n.path}`,Ig.BAD_REQUEST):n.code===yf.NODE_ERROR_CODES.EACCES?bf(n,`Permission denied ${n.path}`,Ig.BAD_REQUEST):bf(n)}}return t}a(Cf,"postValidateChecks");Uv.exports={dataObject:ree,urlObject:nee,fileObject:see,s3FileObject:iee}});var Ug=T((PEe,Pv)=>{"use strict";var Zu=K(),Df=U();async function oee(e,t,r,n=void 0){if(!e||typeof e!="function")throw new Error("Invalid function parameter");let s;try{return s=await e(t),r&&await r(t,s,n),t.operation===Df.OPERATIONS_ENUM.INSERT||t.operation===Df.OPERATIONS_ENUM.UPDATE||t.operation===Df.OPERATIONS_ENUM.UPSERT?(delete s.new_attributes,delete s.txn_time):t.operation===Df.OPERATIONS_ENUM.DELETE&&delete s.txn_time,s}catch(i){throw i.message&&typeof i.message=="string"&&i.message.includes("already exists")?(Zu.info(i.message),i):i.http_resp_msg?(Zu.error(`Error calling operation: ${e.name}`),Zu.error(i.http_resp_msg),i):(Zu.error(`Error calling operation: ${e.name}`),Zu.error(i),i)}}a(oee,"callOperationFunctionAsAwait");Pv.exports={callOperationFunctionAsAwait:oee}});var Bv=T((BEe,vv)=>{"use strict";var Pg=class{static{a(this,"BulkLoadFileObject")}constructor(t,r,n,s,i,o,c=null){this.op=t,this.action=r,this.schema=n,this.table=s,this.file_path=i,this.file_type=o,this.role_perms=c}},vg=class{static{a(this,"BulkLoadDataObject")}constructor(t,r,n,s){this.action=t,this.schema=r,this.table=n,this.data=s}};vv.exports={BulkLoadFileObject:Pg,BulkLoadDataObject:vg}});var xv=T((xEe,Hv)=>{"use strict";var Bg=class{static{a(this,"ClusteringOriginObject")}constructor(t,r,n){this.timestamp=t,this.user=r,this.node_name=n}};Hv.exports=Bg});var kg=T(($Ee,t0)=>{"use strict";var Lf=en(),Uf=Mg(),aee=require("needle"),Un=U(),FEe=tt(),Ca=J(),{handleHDBError:nt,hdb_errors:Wv}=ee(),{HTTP_STATUS_CODES:Gt,HDB_ERROR_MSGS:yt,CHECK_LOGS_WRAPPER:po}=Wv,Da=K(),Hg=require("papaparse");Ca.promisifyPapaParse();var Pn=require("fs-extra"),cee=require("path"),{chain:qv}=require("stream-chain"),Fv=require("stream-json/streamers/StreamArray"),Gv=require("stream-json/utils/Batch"),kv=require("stream-chain/utils/comp"),{finished:Vv}=require("stream"),uee=Z(),Qv=Ug(),lee=ig(),{BulkLoadFileObject:qg,BulkLoadDataObject:_ee}=Bv(),Fg=zT(),{verifyBulkLoadAttributePerms:zv}=lf(),GEe=xv(),kEe=ft(),VEe=ps(),{databases:dee}=(be(),te(qe)),{coerceType:fee}=(Pf(),te(Vg)),$v="No records parsed from csv file.",mo=`${uee.get("HDB_ROOT")}/tmp`,{schema_regex:Eee}=$n(),Yv=1024*1024*2,Kv=5e3,hee={"text/csv":!0,"application/octet-stream":!0,"text/plain":!0,"application/vnd.ms-excel":!0};t0.exports={csvDataLoad:mee,csvURLLoad:pee,csvFileLoad:See,importFromS3:Tee};async function mee(e,t){let r=Uf.dataObject(e);if(r)throw nt(r,r.message,Gt.BAD_REQUEST,void 0,void 0,!0);let n={};try{let s=Xv(e.schema,e.table),i=Hg.parse(e.data,{header:!0,skipEmptyLines:!0,transform:xg.bind(null,s),dynamicTyping:!1}),o=new Fg;e.hdb_user&&e.hdb_user.role&&e.hdb_user.role.permission&&e.hdb_user.role.permission.super_user!==!0&&zv(e.hdb_user.role.permission,this.job_operation_function.name,e.action,e.schema,e.table,i.meta.fields,o);let c=o.getPermsResponse();if(c)throw nt(new Error,c,Gt.BAD_REQUEST,void 0,void 0,!0);let u=new _ee(e.action,e.schema,e.table,i.data);return n=await Qv.callOperationFunctionAsAwait(Zv,u,null),n.message===$v?$v:e0(n.records,n.number_written)}catch(s){throw So(s)}}a(mee,"csvDataLoad");async function pee(e){let t=Uf.urlObject(e);if(t)throw nt(t,t.message,Gt.BAD_REQUEST,void 0,void 0,!0);let r=`${Date.now()}.csv`,n=`${mo}/${r}`;try{await gee(e,r)}catch(s){throw Da.error(yt.DOWNLOAD_FILE_ERR(r)+" - "+s),nt(s,po(yt.DOWNLOAD_FILE_ERR(r)))}try{let s=new qg(this.job_operation_function.name,e.action,e.schema,e.table,n,Un.VALID_S3_FILE_TYPES.CSV,e.hdb_user.role.permission),i=await Gg(s);return await Mf(n),i}catch(s){throw await Mf(n),So(s)}}a(pee,"csvURLLoad");async function See(e){let t=Uf.fileObject(e);if(t)throw nt(t,t.message,Gt.BAD_REQUEST,void 0,void 0,!0);let r=new qg(this.job_operation_function.name,e.action,e.schema,e.table,e.file_path,Un.VALID_S3_FILE_TYPES.CSV,e.hdb_user.role.permission);try{return await Gg(r)}catch(n){throw So(n)}}a(See,"csvFileLoad");async function Tee(e){let t=Uf.s3FileObject(e);if(t)throw nt(t,t.message,Gt.BAD_REQUEST,void 0,void 0,!0);let r;try{let n=cee.extname(e.s3.key),s=`${Date.now()}${n}`;r=`${mo}/${s}`;let i=new qg(this.job_operation_function.name,e.action,e.schema,e.table,r,n,e.hdb_user.role.permission);await Ree(s,e);let o=await Gg(i);return await Mf(r),o}catch(n){throw await Mf(r),So(n)}}a(Tee,"importFromS3");async function gee(e,t){let r;try{let n=e.passthrough_headers?{headers:e.passthrough_headers}:void 0;r=await aee("get",e.csv_url,n)}catch(n){let s=`Error downloading CSV file from ${e.csv_url}, status code: ${n.statusCode}. Check the log for more information.`;throw nt(n,s,n.statusCode,Un.LOG_LEVELS.ERROR,"Error downloading CSV file - "+n)}Oee(r,e.csv_url),await Aee(t,r.raw)}a(gee,"downloadCSVFile");async function Ree(e,t){try{let r=`${mo}/${e}`;await Pn.mkdirp(mo),await Pn.writeFile(`${mo}/${e}`,"",{flag:"a+"});let n=await Pn.createWriteStream(r),s=await lee.getFileStreamFromS3(t);await new Promise((i,o)=>{s.on("error",function(c){o(c)}),s.pipe(n).on("error",function(c){o(c)}).on("close",function(){Da.info(`${t.s3.key} successfully downloaded to ${r}`),i()})})}catch(r){throw Da.error(yt.S3_DOWNLOAD_ERR+" - "+r),nt(r,po(yt.S3_DOWNLOAD_ERR))}}a(Ree,"downloadFileFromS3");async function Aee(e,t){try{await Pn.mkdirp(mo),await Pn.writeFile(`${mo}/${e}`,t)}catch(r){throw Da.error(yt.WRITE_TEMP_FILE_ERR),nt(r,po(yt.DEFAULT_BULK_LOAD_ERR))}}a(Aee,"writeFileToTempFolder");async function Mf(e){if(e)try{await Pn.access(e),await Pn.unlink(e)}catch{Da.warn(`could not delete temp csv file at ${e}, file does not exist`)}}a(Mf,"deleteTempFile");function Oee(e,t){if(e.statusCode!==Wv.HTTP_STATUS_CODES.OK)throw nt(new Error,`CSV Load failed from URL: ${t}, status code: ${e.statusCode}, message: ${e.statusMessage}`,Gt.BAD_REQUEST);if(!hee[e.headers["content-type"]])throw nt(new Error,`CSV Load failed from URL: ${t}, unsupported content type: ${e.headers["content-type"]}`,Gt.BAD_REQUEST);if(!e.raw)throw nt(new Error,`CSV Load failed from URL: ${t}, no csv found at url`,Gt.BAD_REQUEST)}a(Oee,"validateURLResponse");async function Gg(e){try{let t;switch(e.file_type){case Un.VALID_S3_FILE_TYPES.CSV:t=await bee(e);break;case Un.VALID_S3_FILE_TYPES.JSON:t=await yee(e);break;default:throw nt(new Error,yt.DEFAULT_BULK_LOAD_ERR,Gt.BAD_REQUEST,Un.LOG_LEVELS.ERROR,yt.INVALID_FILE_EXT_ERR(e))}return e0(t.records,t.number_written)}catch(t){throw So(t)}}a(Gg,"fileLoad");async function Jv(e,t,r,n,s){let i=n.data?n.data:n;if(i.length===0)return;s&&s.pause();let o={operation:e.action,schema:e.schema,table:e.table,records:i};try{let{attributes:c}=await Lf.validation(o);e.role_perms&&e.role_perms.super_user!==!0&&zv(e.role_perms,e.op,e.action,e.schema,e.table,c,t),s&&s.resume()}catch(c){let u=nt(c);r(u)}}a(Jv,"validateChunk");async function jv(e,t,r,n,s){let i=n.data?n.data:n;if(i.length===0)return;Ca.autoCastJSONDeep(i),s&&s.pause();let o=n.meta?n.meta.fields:null;if(o)i.forEach(c=>{!Ca.isEmpty(c)&&!Ca.isEmpty(c.__parsed_extra)&&delete c.__parsed_extra});else{let c=new Set;i.forEach(u=>{Object.keys(u).forEach(_=>c.add(_))}),o=[...c]}try{let c={schema:e.schema,table:e.table,action:e.action,data:i},u=await Qv.callOperationFunctionAsAwait(Zv,c,null);t.records+=u.records,t.number_written+=u.number_written,s&&s.resume()}catch(c){let u=nt(c,po(yt.INSERT_CSV_ERR),Gt.INTERNAL_SERVER_ERROR,Un.LOG_LEVELS.ERROR,yt.INSERT_CSV_ERR+" - "+c);r(u)}}a(jv,"insertChunk");async function bee(e){let t={records:0,number_written:0},r=Xv(e.schema,e.table);try{let n=new Fg,s=Pn.createReadStream(e.file_path,{highWaterMark:Yv});s.setEncoding("utf8"),await Hg.parsePromise(s,Jv.bind(null,e,n),xg.bind(null,r));let i=n.getPermsResponse();if(i)throw nt(new Error,i,Gt.BAD_REQUEST);return s=Pn.createReadStream(e.file_path,{highWaterMark:Yv}),s.setEncoding("utf8"),await Hg.parsePromise(s,jv.bind(null,e,t),xg.bind(null,r)),s.destroy(),t}catch(n){throw nt(n,po(yt.PAPA_PARSE_ERR),Gt.INTERNAL_SERVER_ERROR,Un.LOG_LEVELS.ERROR,yt.PAPA_PARSE_ERR+n)}}a(bee,"callPapaParse");function Xv(e,t){let r=dee[e][t].attributes,n=new Map;for(let s of r)s.type&&n.set(s.name,i=>fee(i,s));return n}a(Xv,"createTransformMap");function xg(e,t,r){let n=e.get(r);return n?n(t):Ca.autoCast(t)}a(xg,"typeFunction");async function yee(e){let t={records:0,number_written:0},r=a(n=>{throw n},"throwErr");try{let n=new Fg,s=qv([Pn.createReadStream(e.file_path,{encoding:"utf-8"}),Fv.withParser(),c=>c.value,new Gv({batchSize:Kv}),kv(async c=>{await Jv(e,n,r,c)})]);await new Promise((c,u)=>{Vv(s,_=>{_?u(_):c()}),s.resume()});let i=n.getPermsResponse();if(i)throw nt(new Error,i,Gt.BAD_REQUEST);let o=qv([Pn.createReadStream(e.file_path,{encoding:"utf-8"}),Fv.withParser(),c=>c.value,new Gv({batchSize:Kv}),kv(async c=>{await jv(e,t,r,c)})]);return await new Promise((c,u)=>{Vv(o,_=>{_?u(_):c()}),o.resume()}),t}catch(n){throw nt(n,po(yt.INSERT_JSON_ERR),Gt.INTERNAL_SERVER_ERROR,Un.LOG_LEVELS.ERROR,yt.INSERT_JSON_ERR+n)}}a(yee,"insertJson");async function Zv(e){let t={};try{e.data&&e.data.length>0&&Nee(e.data[0])?t=await wee(e.data,e.schema,e.table,e.action):(t.message="No records parsed from csv file.",Da.info(t.message))}catch(r){throw So(r)}return t}a(Zv,"callBulkFileLoad");function Nee(e){let t=Object.keys(e);for(let r of t)if(!Eee.test(r))throw new Error(`Invalid column name '${r}', cancelling load operation`);return!0}a(Nee,"validateColumnNames");async function wee(e,t,r,n){n||(n="insert");let s={operation:n,schema:t,table:r,records:e},i;switch(n){case"insert":i=Lf.insert;break;case"update":i=Lf.update;break;case"upsert":i=Lf.upsert;break;default:throw nt(new Error,yt.INVALID_ACTION_PARAM_ERR(n),Gt.BAD_REQUEST,Un.LOG_LEVELS.ERROR,yt.INVALID_ACTION_PARAM_ERR(n))}try{let o=await i(s),c;switch(n){case"insert":c=o.inserted_hashes;break;case"update":c=o.update_hashes;break;case"upsert":c=o.upserted_hashes;break;default:break}if(Array.isArray(o.skipped_hashes)&&o.skipped_hashes.length>0){let l=global.hdb_schema[t][r].hash_attribute,d=e.length;for(;d--;)o.skipped_hashes.indexOf(e[d][l])>=0&&e.splice(d,1)}let u=Ca.isEmptyOrZeroLength(c)?0:c.length;return{records:e.length,number_written:u,new_attributes:o.new_attributes}}catch(o){throw So(o)}}a(wee,"bulkFileLoad");function e0(e,t){return`successfully loaded ${t} of ${e} records`}a(e0,"buildResponseMsg");function So(e){return nt(e,po(yt.DEFAULT_BULK_LOAD_ERR),Gt.INTERNAL_SERVER_ERROR,Un.LOG_LEVELS.ERROR,yt.DEFAULT_BULK_LOAD_ERR+" - "+e)}a(So,"buildTopLevelErrMsg")});var n0=T((KEe,r0)=>{"use strict";var $g=class{static{a(this,"SqlSearchObject")}constructor(t,r){this.operation="sql",this.sql=t,this.hdb_user=r}};r0.exports=$g});var o0=T((QEe,i0)=>{"use strict";var Iee=U(),s0=require("moment"),Cee=require("uuid").v4,Yg=class{static{a(this,"JobObject")}constructor(){this.id=Cee(),this.type=void 0,this.start_datetime=s0().valueOf(),this.created_datetime=s0().valueOf(),this.end_datetime=void 0,this.status=Iee.JOB_STATUS_ENUM.CREATED,this.message=void 0,this.user=void 0,this.request=void 0}};i0.exports=Yg});var Bf=T((JEe,d0)=>{"use strict";var Dee=require("uuid").v4,u0=en(),l0=Zr(),Lee=Qn(),Mee=Xo(),Uee=n0(),st=U(),Pee=o0(),vee=bS(),ln=K(),Bee=Ic(),La=J(),{promisify:Hee}=require("util"),To=require("moment"),xee=df(),vf=Mg(),a0=ym(),{deleteTransactionLogsBeforeValidator:qee}=$T(),{handleHDBError:Fee,hdb_errors:Gee}=ee(),{HTTP_STATUS_CODES:kee}=Gee,c0=l0.searchByValue,Vee=l0.searchByHash,$ee=u0.insert,Yee=Hee(xee.evaluateSQL),Kee=u0.update;d0.exports={addJob:zee,updateJob:jee,handleGetJob:Wee,handleGetJobsByStartDate:Qee,getJobById:_0};async function Wee(e){try{let t=await _0(e.id);return La.isEmptyOrZeroLength(t)||(t[0]={...t[0]},t[0].request!==void 0&&delete t[0].request,delete t[0].__createdtime__,delete t[0].__updatedtime__),t}catch(t){let r=`There was an error getting job: ${t}`;throw ln.error("There was an error getting job",t),new Error(r)}}a(Wee,"handleGetJob");async function Qee(e){try{let t=await Jee(e);if(ln.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=To(r.start_datetime)),r.end_datetime&&(r.end_datetime_converted=To(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 ln.error(r),new Error(r)}}a(Qee,"handleGetJobsByStartDate");async function zee(e){let t={message:"",error:"",success:!1,createdJob:void 0};if(!e||Object.keys(e).length===0||La.isEmptyOrZeroLength(e.operation)){let l="job parameter is invalid";return ln.info(l),t.error=l,t}if(!st.JOB_TYPE_ENUM[e.operation])return ln.info(`invalid job type specified: ${e.operation}.`),t;let r=e.operation,n;switch(r){case st.OPERATIONS_ENUM.CSV_FILE_LOAD:n=vf.fileObject(e);break;case st.OPERATIONS_ENUM.CSV_URL_LOAD:n=vf.urlObject(e);break;case st.OPERATIONS_ENUM.CSV_DATA_LOAD:n=vf.dataObject(e);break;case st.OPERATIONS_ENUM.IMPORT_FROM_S3:n=vf.s3FileObject(e);break;case st.OPERATIONS_ENUM.DELETE_FILES_BEFORE:case st.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE:n=a0(e,"date");break;case st.OPERATIONS_ENUM.DELETE_AUDIT_LOGS_BEFORE:n=a0(e,"timestamp");break;case st.OPERATIONS_ENUM.DELETE_TRANSACTION_LOGS_BEFORE:n=qee(e);break;default:break}if(n)throw Fee(n,n.message,kee.BAD_REQUEST,void 0,void 0,!0);let s=new Pee;s.type=e.operation===st.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE?st.OPERATIONS_ENUM.DELETE_FILES_BEFORE:e.operation,s.type=e.operation,s.user=e.hdb_user.username;let i=new Lee(st.SYSTEM_SCHEMA_NAME,st.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,"id",s.id,"id",["id"]),o;try{o=Array.from(await c0(i))}catch(l){let d=`There was an error inserting a new job: ${l}`;return ln.error(d),t}let c=Array.isArray(o)?o:Object.keys(o);if(c&&c.length>0){s.id=Dee();try{o=await c0(i)}catch(l){let d=`There was an error inserting a new job: ${l}`;return ln.error(d),t}if(c=Array.isArray(o)?o:Object.keys(o),c&&c.length>0)return ln.error("Error creating a job, could not find a unique job id."),t}s.request=e;let u=new Bee(st.SYSTEM_SCHEMA_NAME,st.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,"id",[s]),_;try{_=await $ee(u)}catch(l){return ln.error(`There was an error inserting a job for job type: ${e.operation} -- ${l}`),t.success=!1,t}if(_.inserted_hashes.length===0)t.message=`Had a problem creating a job with type ${s.operation} and id ${s.id}`;else{let l=`Created a job with type ${s.type} and id ${s.id}`;t.message=l,t.createdJob=s,t.success=!0,ln.trace(l)}return t}a(zee,"addJob");async function Jee(e){let t=To(e.from_date,To.ISO_8601),r=To(e.to_date,To.ISO_8601);if(!t.isValid())throw new Error("Invalid 'from' date, must be in ISO-8601 format (YYYY-MM-DD).");if(!r.isValid())throw new Error("Invalid 'to' date, must be in ISO-8601 format (YYYY-MM-DD)");let n=`select * from system.hdb_job where start_datetime > '${t.valueOf()}' and start_datetime < '${r.valueOf()}'`,s=new Uee(n,e.hdb_user);try{return await Yee(s)}catch(i){throw ln.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(Jee,"getJobsInDateRange");async function _0(e){if(La.isEmptyOrZeroLength(e))return La.errorizeMessage("Invalid job ID specified.");let t=new Mee(st.SYSTEM_SCHEMA_NAME,st.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,[e],["*"]);try{return await Vee(t)}catch(r){let n=`There was an error searching for a job by id: ${e} ${r}`;return ln.error(n),La.errorizeMessage("there was an error searching for jobs. Please check the log for details.")}}a(_0,"getJobById");async function jee(e){if(Object.keys(e).length===0)throw new Error("invalid job object passed to updateJob");if(La.isEmptyOrZeroLength(e.id))throw new Error("invalid ID passed to updateJob");(e.status===st.JOB_STATUS_ENUM.COMPLETE||e.status===st.JOB_STATUS_ENUM.ERROR)&&(e.end_datetime=To().valueOf());let t=new vee(st.SYSTEM_SCHEMA_NAME,st.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,[e]),r;return r=await Kee(t),r}a(jee,"updateJob")});var S0=T((XEe,p0)=>{"use strict";var f0=J(),mr=U(),Xee=require("moment"),Hf=kg(),xf=K(),E0=Bf(),h0=ff(),m0=ki(),Zee=Ze(),ete=of(),Kg=class{static{a(this,"RunnerMessage")}constructor(t,r){this.job=t,this.json=r}};async function tte(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(f0.isEmptyOrZeroLength(e.json.operation))throw new Error("Invalid operation");if(f0.isEmptyOrZeroLength(e.job.id))throw new Error("Empty job id specified");switch(e.json.operation){case mr.JOB_TYPE_ENUM.csv_file_load:await Bs(e,Hf.csvFileLoad);break;case mr.JOB_TYPE_ENUM.csv_url_load:await Bs(e,Hf.csvURLLoad);break;case mr.JOB_TYPE_ENUM.csv_data_load:await Bs(e,Hf.csvDataLoad);break;case mr.JOB_TYPE_ENUM.import_from_s3:await Bs(e,Hf.importFromS3);break;case mr.JOB_TYPE_ENUM.empty_trash:break;case mr.JOB_TYPE_ENUM.export_local:await Bs(e,h0.export_local);break;case mr.JOB_TYPE_ENUM.export_to_s3:await Bs(e,h0.export_to_s3);break;case mr.JOB_TYPE_ENUM.delete_files_before:case mr.JOB_TYPE_ENUM.delete_records_before:await Bs(e,m0.deleteFilesBefore);break;case mr.JOB_TYPE_ENUM.delete_audit_logs_before:await Bs(e,m0.deleteAuditLogsBefore);break;case mr.JOB_TYPE_ENUM.delete_transaction_logs_before:await Bs(e,ete.deleteTransactionLogsBefore);break;default:return`Invalid operation ${e.json.operation} specified`}}a(tte,"parseMessage");async function Bs(e,t){try{e.job.status=mr.JOB_STATUS_ENUM.IN_PROGRESS,e.job.start_datetime=Xee().valueOf(),await E0.updateJob(e.job),await rte(e.job.id)}catch(r){let n=r.message!==void 0?r.message:r;typeof n=="string"?(n=`There was an error running ${t.name} job with id ${e.job.id} - ${n}`,r.message=n):xf.error(`There was an error running ${t.name} job with id ${e.job.id}`),xf.error(n),e.job.message=n,e.job.status=mr.JOB_STATUS_ENUM.ERROR;try{await E0.updateJob(e.job)}catch(s){throw xf.error(`Unable to update job with id ${e.job.id}`),s}throw r}}a(Bs,"runJob");async function rte(e){xf.trace("launching job thread:",e),Zee.startWorker("server/jobs/jobProcess.js",{autoRestart:!1,name:"job",env:Object.assign({},process.env,{[mr.PROCESS_NAME_ENV_PROP]:`JOB-${e}`})})}a(rte,"launchJobThread");p0.exports={parseMessage:tte,RunnerMessage:Kg}});var g0=T((ehe,T0)=>{"use strict";var Wg=class{static{a(this,"OperationFunctionObject")}constructor(t,r=void 0){this.operation_function=t,this.job_operation_function=r}};T0.exports=Wg});var eR=T((rhe,Zg)=>{"use strict";var kf=Zr(),Jg=df(),qf=kg(),Hs=od(),Ff=Hi(),tl=ki(),nte=uS(),el=Ur(),Gf=SS(),kt=VT(),Nt=K(),ste=RS(),ite=Od(),R0=nT(),ote=yd(),ate=sT(),cte=iT(),ute=cT(),lte=lT(),Qg=fT(),A0=ff(),_te=lf(),jg=Bf(),F=U(),{hdb_errors:nl,handleHDBError:rl}=ee(),{HTTP_STATUS_CODES:O0}=nl,zg=ST(),b0=kd(),U0=require("util"),Ma=en(),dte=Ss(),fte=ua(),y0=S0(),N0=Eu(),w0=(Qd(),te(Pu)),I0=Ir(),C0=of(),D0=Zd(),{setServerUtilities:Ete}=(Pf(),te(Vg)),{CONTEXT:hte}=(An(),te(Ep)),{_assignPackageExport:mte}=require("../../index"),{transformReq:pte}=J(),{server:Ste}=(Xt(),te(Ii)),Tte=Ug(),L0=kf.searchByHash,gte=kf.searchByValue,Rte=U0.promisify(kf.search),Ate=U0.promisify(Jg.evaluateSQL),Ote={[F.OPERATIONS_ENUM.CREATE_ATTRIBUTE]:!0,[F.OPERATIONS_ENUM.CREATE_TABLE]:!0,[F.OPERATIONS_ENUM.CREATE_SCHEMA]:!0,[F.OPERATIONS_ENUM.DROP_ATTRIBUTE]:!0,[F.OPERATIONS_ENUM.DROP_TABLE]:!0,[F.OPERATIONS_ENUM.DROP_SCHEMA]:!0},V=g0();async function P0(e,t){try{if(e.body.operation!=="read_log"&&(Nt.log_level===F.LOG_LEVELS.INFO||Nt.log_level===F.LOG_LEVELS.DEBUG||Nt.log_level===F.LOG_LEVELS.TRACE)){let{hdb_user:n,hdb_auth_header:s,password:i,...o}=e.body;Nt.info(o)}}catch(n){Nt.error(n)}let r=await Tte.callOperationFunctionAsAwait(t,e.body,null);if(typeof r!="object"&&(r={message:r}),r instanceof Error)throw r;return Ote[e.body.operation]&&dte.setSchemaDataToGlobal(n=>{n&&Nt.error(n)}),r}a(P0,"processLocalTransaction");var M0=yte();Zg.exports={chooseOperation:v0,getOperationFunction:B0,operation:Xg,processLocalTransaction:P0};Ete(Zg.exports);Ste.operation=Xg;function v0(e){let t;try{t=B0(e)}catch(s){throw Nt.error(`Error when selecting operation function - ${s}`),s}let{operation_function:r,job_operation_function:n}=t;try{if(e.operation==="sql"||e.search_operation&&e.search_operation.operation==="sql"){let s=e.operation==="sql"?e.sql:e.search_operation.sql,i=Jg.convertSQLToAST(s);if(e.parsed_sql_object=i,!e.bypass_auth){let o=Jg.checkASTPermissions(e,i);if(o)throw Nt.error(`${O0.FORBIDDEN} from operation ${e.operation}`),Nt.warn(`User '${e.hdb_user.username}' is not permitted to ${e.operation}`),rl(new Error,o,nl.HTTP_STATUS_CODES.FORBIDDEN,void 0,void 0,!0)}}else if(!e.bypass_auth&&e.operation!==F.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS&&e.operation!==F.OPERATIONS_ENUM.LOGIN&&e.operation!==F.OPERATIONS_ENUM.LOGOUT){let s=n===void 0?r:n,i=e.search_operation?e.search_operation:e;i.hdb_user||(i.hdb_user=e.hdb_user);let o=_te.verifyPerms(i,s);if(o)throw Nt.error(`${O0.FORBIDDEN} from operation ${e.operation}`),Nt.warn(`User '${i.hdb_user.username}' is not permitted to ${i.operation}`),rl(new Error,o,nl.HTTP_STATUS_CODES.FORBIDDEN,void 0,!1,!0)}}catch(s){throw rl(s,"There was an error when trying to choose an operation path")}return r}a(v0,"chooseOperation");function B0(e){if(Nt.trace(`getOperationFunction with operation: ${e.operation}`),M0.has(e.operation))return M0.get(e.operation);throw rl(new Error,nl.HDB_ERROR_MSGS.OP_NOT_FOUND(e.operation),nl.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0)}a(B0,"getOperationFunction");mte("operation",Xg);function Xg(e,t){e.hdb_user=this[hte]?.user,e.bypass_auth=!t;let r=v0(e);return P0({body:e},r)}a(Xg,"operation");async function bte(e){Nt.trace("In serverUtils.catchup");let t=e.transaction,r=t.channel.split(":"),n=r[0],s=r[1];for(let i of t.transactions)try{i.schema=n,i.table=s,i[F.CLUSTERING_FLAG]=!0;let o;switch(i.operation){case F.OPERATIONS_ENUM.INSERT:o=await Ma.insert(i);break;case F.OPERATIONS_ENUM.UPDATE:o=await Ma.update(i);break;case F.OPERATIONS_ENUM.UPSERT:o=await Ma.upsert(i);break;case F.OPERATIONS_ENUM.DELETE:o=await tl.deleteRecord(i);break;default:Nt.warn("invalid operation in catchup");break}await transact_to_clustering_utils.postOperationHandler(i,o,e)}catch(o){Nt.info("Invalid operation in transaction"),Nt.error(o)}}a(bte,"catchup");async function is(e){pte(e);let t,r;try{r=await jg.addJob(e),t=r.createdJob,Nt.info("addJob result",r);let n=new y0.RunnerMessage(t,e);return await y0.parseMessage(n),{message:`Starting job with id ${t.id}`,job_id:t.id}}catch(n){let s=`There was an error executing job: ${n.http_resp_msg?n.http_resp_msg:n}`;throw Nt.error(s),rl(n,s)}}a(is,"executeJob");function yte(){let e=new Map;return e.set(F.OPERATIONS_ENUM.INSERT,new V(Ma.insert)),e.set(F.OPERATIONS_ENUM.UPDATE,new V(Ma.update)),e.set(F.OPERATIONS_ENUM.UPSERT,new V(Ma.upsert)),e.set(F.OPERATIONS_ENUM.SEARCH_BY_CONDITIONS,new V(kf.searchByConditions)),e.set(F.OPERATIONS_ENUM.SEARCH_BY_HASH,new V(L0)),e.set(F.OPERATIONS_ENUM.SEARCH_BY_ID,new V(L0)),e.set(F.OPERATIONS_ENUM.SEARCH_BY_VALUE,new V(gte)),e.set(F.OPERATIONS_ENUM.SEARCH,new V(Rte)),e.set(F.OPERATIONS_ENUM.SQL,new V(Ate)),e.set(F.OPERATIONS_ENUM.CSV_DATA_LOAD,new V(is,qf.csvDataLoad)),e.set(F.OPERATIONS_ENUM.CSV_FILE_LOAD,new V(is,qf.csvFileLoad)),e.set(F.OPERATIONS_ENUM.CSV_URL_LOAD,new V(is,qf.csvURLLoad)),e.set(F.OPERATIONS_ENUM.IMPORT_FROM_S3,new V(is,qf.importFromS3)),e.set(F.OPERATIONS_ENUM.CREATE_SCHEMA,new V(Hs.createSchema)),e.set(F.OPERATIONS_ENUM.CREATE_DATABASE,new V(Hs.createSchema)),e.set(F.OPERATIONS_ENUM.CREATE_TABLE,new V(Hs.createTable)),e.set(F.OPERATIONS_ENUM.CREATE_ATTRIBUTE,new V(Hs.createAttribute)),e.set(F.OPERATIONS_ENUM.DROP_SCHEMA,new V(Hs.dropSchema)),e.set(F.OPERATIONS_ENUM.DROP_DATABASE,new V(Hs.dropSchema)),e.set(F.OPERATIONS_ENUM.DROP_TABLE,new V(Hs.dropTable)),e.set(F.OPERATIONS_ENUM.DROP_ATTRIBUTE,new V(Hs.dropAttribute)),e.set(F.OPERATIONS_ENUM.DESCRIBE_SCHEMA,new V(Ff.describeSchema)),e.set(F.OPERATIONS_ENUM.DESCRIBE_DATABASE,new V(Ff.describeSchema)),e.set(F.OPERATIONS_ENUM.DESCRIBE_TABLE,new V(Ff.describeTable)),e.set(F.OPERATIONS_ENUM.DESCRIBE_ALL,new V(Ff.describeAll)),e.set(F.OPERATIONS_ENUM.DELETE,new V(tl.deleteRecord)),e.set(F.OPERATIONS_ENUM.ADD_USER,new V(el.addUser)),e.set(F.OPERATIONS_ENUM.ALTER_USER,new V(el.alterUser)),e.set(F.OPERATIONS_ENUM.DROP_USER,new V(el.dropUser)),e.set(F.OPERATIONS_ENUM.LIST_USERS,new V(el.listUsersExternal)),e.set(F.OPERATIONS_ENUM.LIST_ROLES,new V(Gf.listRoles)),e.set(F.OPERATIONS_ENUM.ADD_ROLE,new V(Gf.addRole)),e.set(F.OPERATIONS_ENUM.ALTER_ROLE,new V(Gf.alterRole)),e.set(F.OPERATIONS_ENUM.DROP_ROLE,new V(Gf.dropRole)),e.set(F.OPERATIONS_ENUM.USER_INFO,new V(el.userInfo)),e.set(F.OPERATIONS_ENUM.READ_LOG,new V(ste)),e.set(F.OPERATIONS_ENUM.ADD_NODE,new V(ite)),e.set(F.OPERATIONS_ENUM.UPDATE_NODE,new V(R0)),e.set(F.OPERATIONS_ENUM.SET_NODE_REPLICATION,new V(R0)),e.set(F.OPERATIONS_ENUM.REMOVE_NODE,new V(ote)),e.set(F.OPERATIONS_ENUM.CONFIGURE_CLUSTER,new V(ate)),e.set(F.OPERATIONS_ENUM.PURGE_STREAM,new V(cte)),e.set(F.OPERATIONS_ENUM.SET_CONFIGURATION,new V(I0.setConfiguration)),e.set(F.OPERATIONS_ENUM.CLUSTER_STATUS,new V(ute.clusterStatus)),e.set(F.OPERATIONS_ENUM.CLUSTER_NETWORK,new V(lte)),e.set(F.OPERATIONS_ENUM.CLUSTER_SET_ROUTES,new V(Qg.setRoutes)),e.set(F.OPERATIONS_ENUM.CLUSTER_GET_ROUTES,new V(Qg.getRoutes)),e.set(F.OPERATIONS_ENUM.CLUSTER_DELETE_ROUTES,new V(Qg.deleteRoutes)),e.set(F.OPERATIONS_ENUM.EXPORT_TO_S3,new V(is,A0.export_to_s3)),e.set(F.OPERATIONS_ENUM.DELETE_FILES_BEFORE,new V(is,tl.deleteFilesBefore)),e.set(F.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE,new V(is,tl.deleteFilesBefore)),e.set(F.OPERATIONS_ENUM.EXPORT_LOCAL,new V(is,A0.export_local)),e.set(F.OPERATIONS_ENUM.SEARCH_JOBS_BY_START_DATE,new V(jg.handleGetJobsByStartDate)),e.set(F.OPERATIONS_ENUM.GET_JOB,new V(jg.handleGetJob)),e.set(F.OPERATIONS_ENUM.GET_FINGERPRINT,new V(zg.getFingerprint)),e.set(F.OPERATIONS_ENUM.SET_LICENSE,new V(zg.setLicense)),e.set(F.OPERATIONS_ENUM.GET_REGISTRATION_INFO,new V(zg.getRegistrationInfo)),e.set(F.OPERATIONS_ENUM.RESTART,new V(b0.restart)),e.set(F.OPERATIONS_ENUM.RESTART_SERVICE,new V(b0.restartService)),e.set(F.OPERATIONS_ENUM.CATCHUP,new V(bte)),e.set(F.OPERATIONS_ENUM.SYSTEM_INFORMATION,new V(fte.systemInformation)),e.set(F.OPERATIONS_ENUM.DELETE_AUDIT_LOGS_BEFORE,new V(is,tl.deleteAuditLogsBefore)),e.set(F.OPERATIONS_ENUM.READ_AUDIT_LOG,new V(nte)),e.set(F.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS,new V(N0.createTokens)),e.set(F.OPERATIONS_ENUM.REFRESH_OPERATION_TOKEN,new V(N0.refreshOperationToken)),e.set(F.OPERATIONS_ENUM.LOGIN,new V(w0.login)),e.set(F.OPERATIONS_ENUM.LOGOUT,new V(w0.logout)),e.set(F.OPERATIONS_ENUM.GET_CONFIGURATION,new V(I0.getConfiguration)),e.set(F.OPERATIONS_ENUM.CUSTOM_FUNCTIONS_STATUS,new V(kt.customFunctionsStatus)),e.set(F.OPERATIONS_ENUM.GET_CUSTOM_FUNCTIONS,new V(kt.getCustomFunctions)),e.set(F.OPERATIONS_ENUM.GET_COMPONENT_FILE,new V(kt.getComponentFile)),e.set(F.OPERATIONS_ENUM.GET_COMPONENTS,new V(kt.getComponents)),e.set(F.OPERATIONS_ENUM.SET_COMPONENT_FILE,new V(kt.setComponentFile)),e.set(F.OPERATIONS_ENUM.DROP_COMPONENT,new V(kt.dropComponent)),e.set(F.OPERATIONS_ENUM.GET_CUSTOM_FUNCTION,new V(kt.getCustomFunction)),e.set(F.OPERATIONS_ENUM.SET_CUSTOM_FUNCTION,new V(kt.setCustomFunction)),e.set(F.OPERATIONS_ENUM.DROP_CUSTOM_FUNCTION,new V(kt.dropCustomFunction)),e.set(F.OPERATIONS_ENUM.ADD_CUSTOM_FUNCTION_PROJECT,new V(kt.addComponent)),e.set(F.OPERATIONS_ENUM.ADD_COMPONENT,new V(kt.addComponent)),e.set(F.OPERATIONS_ENUM.DROP_CUSTOM_FUNCTION_PROJECT,new V(kt.dropCustomFunctionProject)),e.set(F.OPERATIONS_ENUM.PACKAGE_CUSTOM_FUNCTION_PROJECT,new V(kt.packageComponent)),e.set(F.OPERATIONS_ENUM.PACKAGE_COMPONENT,new V(kt.packageComponent)),e.set(F.OPERATIONS_ENUM.DEPLOY_CUSTOM_FUNCTION_PROJECT,new V(kt.deployComponent)),e.set(F.OPERATIONS_ENUM.DEPLOY_COMPONENT,new V(kt.deployComponent)),e.set(F.OPERATIONS_ENUM.READ_TRANSACTION_LOG,new V(C0.readTransactionLog)),e.set(F.OPERATIONS_ENUM.DELETE_TRANSACTION_LOGS_BEFORE,new V(is,C0.deleteTransactionLogsBefore)),e.set(F.OPERATIONS_ENUM.INSTALL_NODE_MODULES,new V(D0.installModules)),e.set(F.OPERATIONS_ENUM.AUDIT_NODE_MODULES,new V(D0.auditModules)),e.set(F.OPERATIONS_ENUM.GET_BACKUP,new V(Hs.getBackup)),e}a(yte,"initializeOperationFunctionMap")});var $f=T((she,q0)=>{"use strict";var tR=U(),Nte=J(),sl=K(),{handleHDBError:rR,hdb_errors:Vf}=ee(),{isMainThread:wte}=require("worker_threads"),{Readable:Ite}=require("stream"),H0=require("os"),Cte=require("util"),Dte=MS(),Lte=Cte.promisify(Dte.authorize),x0=eR(),{createGzip:Mte,constants:Ute}=require("zlib");function Pte(e){let t=`Found an uncaught exception with message: ${e.message}. ${H0.EOL}Stack: ${e.stack} ${H0.EOL}Terminating ${wte?"HDB":"thread"}.`;console.error(t),sl.fatal(t),process.exit(1)}a(Pte,"handleServerUncaughtException");function vte(e,t,r){if(sl[e.logLevel||"error"](e),e.statusCode)return typeof e.http_resp_msg!="object"?r.code(e.statusCode).send({error:e.http_resp_msg||e.message}):r.code(e.statusCode).send(e.http_resp_msg);let n=e.statusCode?e.statusCode:Vf.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR;return typeof e=="string"?r.code(n).send({error:e}):r.code(n).send(e.message?{error:e.message}:e)}a(vte,"serverErrorHandler");function Bte(e,t,r){if(!e.body||Object.keys(e.body).length===0||typeof e.body!="object"){let n=rR(new Error,"Invalid JSON.",Vf.HTTP_STATUS_CODES.BAD_REQUEST);r(n,null)}if(Nte.isEmpty(e.body.operation)){let n=rR(new Error,"Request body must include an 'operation' property.",Vf.HTTP_STATUS_CODES.BAD_REQUEST);r(n,null)}r()}a(Bte,"reqBodyValidationHandler");function Hte(e,t,r){let n;e.body.operation!==tR.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS&&e.body.operation!==tR.OPERATIONS_ENUM.LOGIN&&e.body.operation!==tR.OPERATIONS_ENUM.LOGOUT?Lte(e,t).then(s=>{n=s,e.body.hdb_user=n,e.body.hdb_auth_header=e.headers.authorization,r()}).catch(s=>{sl.warn(s),sl.warn(`{"ip":"${e.socket.remoteAddress}", "error":"${s.stack}"`);let i=typeof s=="string"?{error:s}:{error:s.message};r(rR(s,i,Vf.HTTP_STATUS_CODES.UNAUTHORIZED),null)}):(e.body.hdb_user=null,e.body.hdb_auth_header=e.headers.authorization,e.body.baseRequest=e.raw?.baseRequest,e.body.baseResponse=t.raw?.baseResponse,e.body.fastifyResponse=t,r())}a(Hte,"authHandler");async function xte(e,t,r=!1){let n;try{r&&(e.body.operation!=="configure_cluster"||e.body.operation!=="set_configuration")&&(e.body.bypass_auth=r),n=x0.chooseOperation(e.body);let s=await x0.processLocalTransaction(e,n);if(s instanceof Ite&&s.headers){for(let[i,o]of s.headers)t.header(i,o);e.headers["accept-encoding"]?.includes("gzip")&&(t.header("content-encoding","gzip"),s=s.pipe(Mte({level:Ute.Z_BEST_SPEED})))}return s}catch(s){throw sl.error(s),s}}a(xte,"handlePostRequest");q0.exports={authHandler:Hte,handlePostRequest:xte,handleServerUncaughtException:Pte,serverErrorHandler:vte,reqBodyValidationHandler:Bte}});var V0=T((ohe,k0)=>{"use strict";var qte=require("fastify-plugin"),{handlePostRequest:F0,authHandler:Fte,reqBodyValidationHandler:Gte}=$f();async function kte(e){e.decorate("hdbCore",{preValidation:[Gte,Fte],request:t=>G0(F0(t,response)),requestWithoutAuthentication:(t,r)=>G0(F0(t,r,!0))})}a(kte,"hdbCore");async function G0(e){if(e=await e,e?.[Symbol.asyncIterator]&&!e[Symbol.iterator]){let t=[];for await(let r of e)t.push(r);return t}return e}a(G0,"convertAsyncIterators");k0.exports=qte(kte)});var K0=T((uhe,Y0)=>{"use strict";var che=require("fs"),nR=Z();nR.initSync();var{CONFIG_PARAMS:$0}=U(),Vte=1024*1024*1024;function $te(e){let t=nR.get($0.HTTP_TIMEOUT),r=nR.get($0.HTTP_KEEPALIVETIMEOUT);return{bodyLimit:Vte,connectionTimeout:t,keepAliveTimeout:r,return503OnClosing:!1,forceCloseConnections:!0,ignoreTrailingSlash:!0,https:e}}a($te,"getServerOptions");Y0.exports=$te});var z0=T((_he,Q0)=>{"use strict";var sR=Z();sR.initSync();var{CONFIG_PARAMS:W0}=U();function Yte(){let e=sR.get(W0.HTTP_CORSACCESSLIST),t=sR.get(W0.HTTP_CORS),r;return t&&(r={origin:!0,allowedHeaders:["Content-Type","Authorization","Accept"],credentials:!1},e&&e.length>0&&e[0]!==null&&e[0]!=="*"&&(r.origin=(n,s)=>s(null,e.indexOf(n)!==-1))),r}a(Yte,"getCORSOptions");Q0.exports=Yte});var X0=T((fhe,j0)=>{"use strict";var J0=Z();J0.initSync();var Kte=U();function Wte(){return J0.get(Kte.CONFIG_PARAMS.HTTP_HEADERSTIMEOUT)??6e4}a(Wte,"getHeaderTimeoutConfig");j0.exports=Wte});var oR={};ke(oR,{customFunctionsServer:()=>Jte,ready:()=>fB,start:()=>zte});function zte(e){let t=e.securePort>0;return{async handleFile(r,n,s,i){xs||(xs=dB(t),Xe.http((await xs).server));let o=await xs,c=(0,iR.dirname)(s),u=(0,iR.dirname)(n);if(u.startsWith("/")&&(u=u.slice(1)),!Z0.has(c)){Z0.add(c);try{o.register(Xte(c,u))}catch(_){if(_.message==="Root plugin has already booted")Ge.warn(`Could not load root fastify route for ${s}, this may require a restart to install properly`);else throw _}}},ready:fB}}async function Jte(){try{Ge.info("In Custom Functions Fastify server"+process.cwd()),Ge.info(`Custom Functions Running with NODE_ENV set as: ${process.env.NODE_ENV}`),Ge.debug(`Custom Functions server process ${process.pid} starting up.`),await jte();let e=iB.get(oB.CONFIG_PARAMS.HTTP_SECUREPORT)>0,t;try{t=xs=await dB(e)}catch(r){throw Ge.error(`Custom Functions buildServer error: ${r}`),r}try{await t.ready()}catch(r){throw Ge.error(`Custom Functions server.ready() error: ${r}`),r}t.server.cantCleanupProperly=!0}catch(e){Ge.error(`Custom Functions ${process.pid} Error: ${e}`),Ge.error(e),process.exit(1)}}async function jte(){try{Ge.info("Custom Functions starting configuration."),await aB.setUsersToGlobal(),Ge.info("Custom Functions completed configuration.")}catch(e){Ge.error(e)}}function Xte(e,t){return async function(r){try{Ge.info("Custom Functions starting buildRoutes"),Ge.trace("Loading fastify routes folder "+e),(0,eB.existsSync)(e)&&r.register(sB.default,s=>({dir:e,dirNameRoutePrefix:!1,options:{hdbCore:s.hdbCore,logger:Ge.loggerWithTag("custom-function"),prefix:`/${t}`}})).after((s,i,o)=>{s?.message?Ge.error(s.message):s&&Ge.error(s),o()})}catch(n){Ge.error(`Custom Functions errored buildRoutes: ${n}`)}}}async function dB(e){Ge.info("Custom Functions starting buildServer.");let t=(0,cB.default)(e),r=(0,tB.default)(t);r.server.headersTimeout=(0,lB.default)(),r.setErrorHandler(_B.serverErrorHandler);let n=(0,uB.default)();return n&&r.register(rB.default,n),r.register(function(s,i,o){s.setNotFoundHandler(function(c,u){r.server.emit("unhandled",c.raw,u.raw)}),o()}),r.register(nB.default),await r.register(Qte),await r.after(),fg(r),Ge.info("Custom Functions completed buildServer."),r}function fB(){if(xs)return xs.then?xs.then(e=>e.ready()):xs.ready()}var iR,eB,tB,rB,nB,sB,iB,oB,Ge,Qte,aB,cB,uB,lB,_B,xs,Z0,EB=Oe(()=>{iR=require("path"),eB=require("fs"),tB=x(require("fastify")),rB=x(require("@fastify/cors")),nB=x(Ng()),sB=x(require("@fastify/autoload")),iB=x(Z()),oB=x(U()),Ge=x(K()),Qte=x(V0()),aB=x(Ur()),cB=x(K0()),uB=x(z0()),lB=x(X0()),_B=x($f());pa();Xt();Z0=new Set;a(zte,"start");a(Jte,"customFunctionsServer");a(jte,"setUp");a(Xte,"buildRouteFolder");a(dB,"buildServer");a(fB,"ready")});var aR={};ke(aR,{start:()=>Zte});function Zte(e){return{handleDirectory(t,r){if(t==="/"){let n=(0,TB.default)(r,e);return e.server.http(async(s,i)=>{if(!s.isWebSocket)return new Promise(o=>n(s._nodeRequest,s._nodeResponse,()=>{o(i(s))}))}),!0}},handleFile(t,r,n){mB||(mB=!0,e.server.http(async(s,i)=>{if(!s.isWebSocket){let o=hB.get(s.pathname);if(o)return{handlesHeaders:!0,body:(0,pB.default)(s,(0,SB.realpathSync)(o))}}return i(s)},{runFirst:!0})),hB.set(r,n)}}}var pB,SB,TB,hB,mB,gB=Oe(()=>{pB=x(require("send")),SB=require("fs"),TB=x(require("serve-static")),hB=new Map;a(Zte,"start")});function rre(e,t=1,r){if(cR++,(0,go.startWorker)("server/threads/threadServer.js",{name:Wf.THREAD_TYPES.HTTP,workerIndex:e,threadCount:t,async onStarted(n){let s=new Promise((o,c)=>{function u(_){_.type===Wf.CLUSTER_MESSAGE_TYPE_ENUM.CHILD_STARTED&&(n.removeListener("message",u),o(n))}a(u,"onMessage"),n.on("message",u),n.on("error",c)});tre.push(s),await s,Ua.push(n),n.expectedIdle=1,n.lastIdle=0,n.requests=1,n.on("message",o=>{if(o.requestId){let c=Kf.get(o.requestId);c&&c(o)}}),n.on("exit",i),n.on("shutdown",i);function i(){let o=Ua.indexOf(n);o>-1&&Ua.splice(o,1)}if(a(i,"removeWorker"),Pa){let o=Pa;Pa=[];for(let c of o)bB[c.localPort](null,c)}}}),r){let n=setInterval(()=>{uR?uR=!1:(clearInterval(n),console.log("shut down dynamic thread due to inactivity"),(0,go.shutdownWorkers)(),cR=0,setTimeout(()=>{global.gc?.()},5e3))},1e4)}}function yB(e=0,t){if(typeof e=="string")try{(0,Qf.existsSync)(e)&&(0,Qf.unlinkSync)(e)}catch{}let r;t?t==="ip"?r=nre:r=sre(t):r=_R;let n=(0,va.createServer)({allowHalfOpen:!0,pauseOnConnect:!r.readsData}).listen(e);if(n._handle){n._handle.onconnection=bB[e]=function(i,o){r.readsData||(o.reading=!1,o.readStop()),uR=!0,r(o,(c,u)=>{if(!c){if(RB){let l=o._socket||new va.Socket({handle:o,writable:!0,readable:!0});RB.deliverSocket(l,e,u),l.resume()}else cR>0?(Pa.length===0&&setTimeout(()=>{Pa.length>0&&console.warn("Incoming sockets/requests have been queued for workers to start, and no workers have handled them. Check to make sure an error is not preventing workers from starting")},1e4).unref(),o.localPort=e,Pa.push(o)):(console.log("start up a dynamic thread to handle request"),rre(0));Hr(!1,"socket-routed");return}c.requests++;let _=o.fd;if(_>=0)c.postMessage({port:e,fd:_,data:u});else{let l=o._socket||new va.Socket({handle:o,writable:!0,readable:!0});cre(l,c,e)}Hr(!0,"socket-routed")})};let s=Xc();lR.info(`HarperDB ${s.version} Server running on port ${e}`)}return n.on("error",s=>{console.error("Error in socket server",s)}),process.env._UNREF_SERVER&&n.unref(),n}function _R(e,t){let r,n=0;for(let s of Ua){if(s.threadId===-1)continue;let i=s.expectedIdle/s.requests;if(i>n)r=s;else if(n>=Yf)return Yf=i,t(r);n=i}Yf=0,t(r)}function nre(e,t){let r={};e.getpeername(r);let n=r.address,s=Ba.get(n),i=Date.now();if(s&&s.worker.threadId!==-1)return s.lastUsed=i,t(s.worker);_R(e,o=>{Ba.set(n,{worker:o,lastUsed:i}),t(o)})}function sre(e){let t=new RegExp(`${e}:\\s*(.+)`,"i");return r.readsData=!0,r;function r(n,s){let i=new va.Socket({handle:n,readable:!0,writable:!0});n._socket=i,i.on("data",o=>{n.readStop();let u=o.toString("latin1").match(t)?.[1],_=Ba.get(u),l=Date.now();if(_&&_.worker.threadId!==-1)return _.lastUsed=l,s(_.worker);_R(n,d=>{Ba.set(u,{worker:d,lastUsed:l}),s(d,o)})})}a(r,"findByHeaderAffinity")}function ore(){Yf=0;for(let e of Ua)e.expectedIdle=e.recentELU.idle+ire,e.requests=1;Ua.sort((e,t)=>e.expectedIdle>t.expectedIdle?-1:1)}function cre(e,t,r){let n=are++;t.postMessage({port:r,requestId:n,event:"connection"}),e.on("data",s=>{let i=s.toString("latin1");t.postMessage({port:r,requestId:n,data:i,event:"data"})}).on("close",s=>{t.postMessage({port:r,requestId:n,event:"close",hadError:s})}).on("error",s=>{t.postMessage({port:r,requestId:n,event:"error",error:s})}).on("drain",s=>{t.postMessage({port:r,requestId:n,event:"drain",error:s})}).on("end",()=>{t.postMessage({port:r,requestId:n,event:"end"})}).resume(),Kf.set(n,s=>{s.event=="data"&&e.write(Buffer.from(s.data,"latin1")),s.event=="end"&&(e.end(s.data&&Buffer.from(s.data,"latin1")),Kf.delete(n)),s.event=="destroy"&&(e.destroy(),Kf.delete(n))})}var go,va,Wf,lR,Qf,OB,ere,Ua,Pa,bB,RB,cR,tre,uR,Yf,AB,Ba,ire,Kf,are,NB=Oe(()=>{go=x(Ze()),va=require("net"),Wf=x(U()),lR=x(K()),Qf=require("fs");Os();OB=require("worker_threads"),ere=x(Vi()),Ua=[],Pa=[],bB=[],cR=0,tre=[];OB.isMainThread&&process.on("uncaughtException",e=>{e.code!=="ECONNRESET"&&e.message!=="write EIO"&&console.error("uncaughtException",e)});a(rre,"startHTTPWorker");a(yB,"startSocketServer");Yf=0;a(_R,"findMostIdleWorker");AB=36e5,Ba=new Map;a(nre,"findByRemoteAddressAffinity");a(sre,"makeFindByHeaderAffinity");setInterval(()=>{let e=Date.now();for(let[t,r]of Ba)r.lastUsed+AB<e&&Ba.delete(t)},AB).unref();ire=1e3;a(ore,"updateWorkerIdleness");(0,go.setMonitorListener)(ore);Kf=new Map,are=1;a(cre,"proxySocket")});var hR={};ke(hR,{Request:()=>dR,createReuseportFd:()=>zf});var wB,dR,fR,ER,zf,Jf=Oe(()=>{wB=require("os"),dR=class{static{a(this,"Request")}#e;constructor(t,r){this.method=t.method;let n=t.url;this._nodeRequest=t,this._nodeResponse=r,this.url=n,this.headers=new ER(t.headers)}get absoluteURL(){return this.protocol+"://"+this.host+this.url}get pathname(){let t=this.url.indexOf("?");return t>-1?this.url.slice(0,t):this.url}set pathname(t){let r=this.url.indexOf("?");r>-1?this.url=t+this.url.slice(r):this.url=t}get protocol(){return this._nodeRequest.socket.encrypted?"https":"http"}get ip(){return this._nodeRequest.socket.remoteAddress}get authorized(){return this._nodeRequest.socket.authorized}get peerCertificate(){return this._nodeRequest.socket.getPeerCertificate()}get mtlsConfig(){return this._nodeRequest.socket.server.mtlsConfig}get body(){return this.#e||(this.#e=new fR(this._nodeRequest))}get host(){return this._nodeRequest.authority||this._nodeRequest.headers.host}get isAborted(){return!1}},fR=class{static{a(this,"RequestBody")}#e;constructor(t){this.#e=t}on(t,r){return this.#e.on(t,r),this}},ER=class{constructor(t){this.asObject=t}static{a(this,"Headers")}set(t,r){this.asObject[t.toLowerCase()]=r}get(t){return this.asObject[t.toLowerCase()]}has(t){return this.asObject.hasOwnProperty(t.toLowerCase())}[Symbol.iterator](){return Object.entries(this.asObject)[Symbol.iterator]()}keys(){return Object.keys(this.asObject)}values(){return Object.values(this.asObject)}forEach(t){for(let[r,n]of this)t(n,r,this)}};(0,wB.platform)()!="win32"&&(zf=require("node-unix-socket").createReuseportFd)});var LB=T((Ihe,DB)=>{"use strict";var ure=require("cluster"),Ro=Z();Ro.initSync();var CB=U(),Ohe=require("util"),qs=K(),bhe=require("fs"),lre=require("fastify"),yhe=Xc(),_re=require("@fastify/cors"),dre=require("@fastify/compress"),fre=require("@fastify/static"),Ere=Ng(),hre=require("path"),{PACKAGE_ROOT:mre}=U(),pre=Ss(),Sre=J(),Tre=Ur(),gre=Vi(),{server:Rre}=(Xt(),te(Ii)),{node_request_key:Nhe}=(Jf(),te(hR)),{authHandler:Are,handlePostRequest:Ore,serverErrorHandler:bre,reqBodyValidationHandler:yre}=$f(),whe=require("net"),{registerContentHandlers:Nre}=(pa(),te(Ev)),wre=6e4,Ire=1024*1024*1024,Cre="TRUE",{CONFIG_PARAMS:il}=CB,Ha;DB.exports={hdbServer:IB,start:IB};async function IB(e){try{qs.info("In Fastify server"+process.cwd()),qs.info(`Running with NODE_ENV set as: ${process.env.NODE_ENV}`),qs.debug(`HarperDB server process ${process.pid} starting up.`),global.clustering_on=!1,global.isMaster=ure.isMaster,await Dre();let t=e.securePort>0;Ha=Lre(t),await Ha.ready(),e||(e={}),e.isOperationsServer=!0;try{Rre.http(Ha.server,e),Ha.server.closeIdleConnections||await Ha.listen({port:0,host:"::"})}catch(r){throw Ha.close(),qs.error(r),qs.error("Error configuring operations server"),r}}catch(t){console.error(`Failed to build server on ${process.pid}`,t),qs.fatal(t),process.exit(1)}}a(IB,"operationsServer");async function Dre(){qs.trace("Configuring HarperDB process."),pre.setSchemaDataToGlobal(),await Tre.setUsersToGlobal(),await gre.getLicense()}a(Dre,"setUp");function Lre(e){qs.debug(`HarperDB process starting to build ${e?"HTTPS":"HTTP"} server.`);let t=Mre(e),r=lre(t);r.server.headersTimeout=Pre(),r.setErrorHandler(bre);let n=Ure();n&&r.register(_re,n),r.register(function(i,o,c){i.setNotFoundHandler(function(u,_){r.server.emit("unhandled",u.raw,_.raw)}),c()}),r.register(Ere),r.register(dre),r.register(fre,{root:hre.join(mre,"studio/build-local")}),Nre(r);let s=Ro.get(CB.HDB_SETTINGS_NAMES.LOCAL_STUDIO_ON);return r.get("/",function(i,o){return!Sre.isEmpty(s)&&s.toString().toLowerCase()==="true"?o.sendFile("index.html"):o.sendFile("running.html")}),r.post("/",{preValidation:[yre,Are],config:{isOperation:!0}},async function(i,o){return i.body?.operation?.startsWith("restart")&&o.header("Connection","close"),Ore(i,o)}),r.get("/health",()=>"HarperDB is running."),qs.debug(`HarperDB process starting up ${e?"HTTPS":"HTTP"} server listener.`),r}a(Lre,"buildServer");function Mre(e){let t=Ro.get(il.OPERATIONSAPI_NETWORK_TIMEOUT),r=Ro.get(il.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT);return{bodyLimit:Ire,connectionTimeout:t,keepAliveTimeout:r,forceCloseConnections:!0,return503OnClosing:!1,https:e}}a(Mre,"getServerOptions");function Ure(){let e=Ro.get(il.OPERATIONSAPI_NETWORK_CORS),t=Ro.get(il.OPERATIONSAPI_NETWORK_CORSACCESSLIST),r;return e&&(e===!0||e.toUpperCase()===Cre)&&(r={origin:!0,allowedHeaders:["Content-Type","Authorization","Accept"],credentials:!1},t&&t.length>0&&t[0]!==null&&t[0]!=="*"&&(r.origin=(n,s)=>s(null,t.indexOf(n)!==-1))),r}a(Ure,"getCORSOpts");function Pre(){return Ro.get(il.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT)??wre}a(Pre,"getHeaderTimeoutConfig")});var GB=T((Uhe,FB)=>{"use strict";var{decode:vre}=require("msgpackr"),{isMainThread:Dhe,parentPort:Bre,threadId:Lhe}=require("worker_threads"),pR=ft(),Fs=tt(),Hre=U(),Ti=K(),MB=Z(),PB=U();Ze();var xre=ps(),{recordAction:qre,recordActionBinary:Fre}=(Os(),te(ru)),{publishToStream:Gre}=pR,{ConsumerEvents:kre}=require("nats"),Mhe={durable:Fs.WORK_QUEUE_CONSUMER_NAMES.durable_name,queue:Fs.WORK_QUEUE_CONSUMER_NAMES.deliver_group},Vre,$re,Yre,vB,BB;FB.exports={initialize:SR,workQueueListener:qB,setSubscription:Kre,setIgnoreOrigin:Qre,getDatabaseSubscriptions:Wre};async function SR(){BB=!0,Ti.notify("Starting clustering ingest service.");let{connection:e,jsm:t,js:r}=await pR.getNATSReferences();Vre=e,$re=e.info.server_name,Yre=t,vB=r}a(SR,"initialize");var Xf=new Map;function Kre(e,t,r){let n=Xf.get(e);n||Xf.set(e,n=new Map),n.set(t,r),BB||SR().then(qB)}a(Kre,"setSubscription");function Wre(){return Xf}a(Wre,"getDatabaseSubscriptions");var HB;function Qre(e){HB=e}a(Qre,"setIgnoreOrigin");var xB=100,UB=new Array(xB),jf=0;async function qB(){let e=await vB.consumers.get(Fs.WORK_QUEUE_CONSUMER_NAMES.stream_name,Fs.WORK_QUEUE_CONSUMER_NAMES.durable_name),t=!1,r;for(Bre?.on("message",async n=>{let{type:s}=n;s===PB.ITC_EVENT_TYPES.SHUTDOWN&&(t=!0,r&&r.close?.()&&r.close())});!t;){r=await e.consume(),(async()=>{for await(let n of await r.status())if(n.type===kre.HeartbeatsMissed){let s=n.data;Ti.trace(`${s} clustering ingest consumer heartbeats missed`),s===2&&(Ti.warn("Restarting clustering ingest consumer due to missed heartbeat threshold being met"),r.stop())}})();try{for await(let n of r)await UB[jf],UB[jf]=zre(n).catch(s=>{Ti.error(s)}),++jf>=xB&&(jf=0)}catch(n){Ti.error("Error consuming clustering ingest, restarting consumer",n)}pR.clearClientCache(),await SR()}}a(qB,"workQueueListener");async function zre(e){let t=vre(e.data);qre(e.data.length,"bytes-received",e.subject,t.operation,"ingest");let r=e.headers,n=!1,s=MB.get(Hre.CONFIG_PARAMS.CLUSTERING_NODENAME);r.has(Fs.MSG_HEADERS.TRANSACTED_NODES)&&r.values(Fs.MSG_HEADERS.TRANSACTED_NODES).indexOf(s)>-1&&(n=!0);let i=r.get(Fs.MSG_HEADERS.ORIGIN);if(n||(n=i===s&&!HB),Fre(n,"echo",e.subject,t.operation,"ingest"),n){e.ack();return}r.append(Fs.MSG_HEADERS.TRANSACTED_NODES,s);try{let{operation:o,schema:c,next:u,table:_,records:l,hash_values:d,__origin:f,expiresAt:E}=t;Ti.trace("processing message:",o,c,_,(l?"records: "+l.map(R=>R?.id):"")+(d?"ids: "+d:""),"with sequence:",e.seq),Ti.trace(`messageProcessor nats msg id: ${e.headers.get(Fs.MSG_HEADERS.NATS_MSG_ID)}`);let h;l||(l=d);let{timestamp:p,user:S,node_name:O}=f||{},g=Xf.get(c)?.get(_);if(!g)throw new Error("Missing table for replication message",_);if(o==="define_schema")t.type=o,g.send(t);else if(l.length===1&&!u)g.send({type:mR(o),value:l[0],id:d?.[0],expiresAt:E,timestamp:p,table:_,onCommit:h,user:S,nodeName:O});else{let R=l.map((B,H)=>({type:mR(o),value:B,expiresAt:E,id:d?.[H],table:_}));for(;u;)R.push({type:mR(u.operation),value:u.record,expiresAt:u.expiresAt,id:u.id,table:u.table}),u=u.next;g.send({type:"transaction",writes:R,table:_,timestamp:p,onCommit:h,user:S,nodeName:O})}MB.get(PB.CONFIG_PARAMS.CLUSTERING_REPUBLISHMESSAGES)!==!1&&Gre(e.subject.split(".").slice(0,-1).join("."),xre.createNatsTableStreamName(c,_),e.headers,e.data)}catch(o){Ti.error(o)}e.ack()}a(zre,"messageProcessor");function mR(e){switch(e){case"insert":case"upsert":case"update":return"put"}return e}a(mR,"convertOperation")});var sE={};ke(sE,{disableNATS:()=>jre,publishToStream:()=>nE,setNATSReplicator:()=>TR,setPublishToStream:()=>Xre,setSubscription:()=>OR,start:()=>Jre});function Jre(){eE.default.get(tE.default.CONFIG_PARAMS.CLUSTERING_ENABLED)&&ene()}function jre(e=!0){KB=e}function Xre(e,t){nE=e,OR=t}function ene(){if(KB||process.env._DISABLE_NATS)return;let e=In(),t=Object.keys(e);t.push("system");for(let r of t){let n=e[r];for(let s in n){let i=n[s];TR(s,r,i)}}yR((r,n)=>{TR(r.tableName,r.databaseName,r),n&&QB(r)}),!kB&&(kB=!0)}function TR(e,t,r){if(!r)return console.error(`Attempt to replicate non-existent table ${e} from database ${t}`);if(r.sources.some(s=>s?.isNATSReplicator))return;r.sourcedFrom(class extends vt{static{a(this,"NATSReplicator")}put(i){return n(this.getContext()).addWrite(t,{operation:"put",table:e,id:this[Ue],record:i})}delete(){return n(this.getContext()).addWrite(t,{operation:"delete",table:e,id:this[Ue]})}publish(i){return n(this.getContext()).addWrite(t,{operation:"publish",table:e,id:this[Ue],record:i})}patch(i){return n(this.getContext()).addWrite(t,{operation:"patch",table:e,id:this[Ue],record:i})}invalidate(){n(this.getContext()).addWrite(t,{operation:"invalidate",table:e,id:this[Ue]})}static defineSchema(i){QB(i)}static subscribe(){let i=new Rn;return OR(t,e,i),i}static subscribeOnThisThread(i){return i<Zre}static isEqual(i){return i.isNATSReplicator}static isNATSReplicator=!0;static shouldReceiveInvalidations=!0},{intermediateSource:!0});function n(s){let i=s?.transaction?.nats;if(!i)if(s?.transaction){s.transaction.nats=i=new Zf(s.transaction,s);let o=s.transaction;for(;o.next;)o=o.next;o.next=s.transaction.nats,i.user=s.user,i.context=s}else i=WB;return i}a(n,"getNATSTransaction")}function QB(e){let t=eE.default.get(tE.default.CONFIG_PARAMS.CLUSTERING_NODENAME);nE(`${RR.SUBJECT_PREFIXES.TXN}.${e.databaseName}.${e.tableName}`,(0,AR.createNatsTableStreamName)(e.databaseName,e.tableName),void 0,{operation:"define_schema",schema:e.databaseName,table:e.tableName,attributes:e.attributes,__origin:{timestamp:Date.now(),node_name:t}})}var VB,RR,AR,$B,YB,eE,tE,rE,KB,nE,OR,Zre,WB,kB,Zf,gR,bR=Oe(()=>{be();An();VB=x(ft()),RR=x(tt()),AR=x(ps());Ec();$B=x(GB()),YB=x(Cr()),eE=x(Z()),tE=x(U()),rE=x(K());a(Jre,"start");a(jre,"disableNATS");nE=VB.publishToStream,OR=$B.setSubscription;a(Xre,"setPublishToStream");Zre=2;a(ene,"assignReplicationSource");a(TR,"setNATSReplicator");a(QB,"publishSchema");Zf=class{constructor(t,r){this.transaction=t;this.options=r}static{a(this,"NATSTransaction")}user;writes_by_db=new Map;addWrite(t,r){r.expiresAt=this.context?.expiresAt;let n=this.writes_by_db.get(t);n||this.writes_by_db.set(t,n=[]),n.push(r)}commit({timestamp:t}){let r=eE.default.get(tE.default.CONFIG_PARAMS.CLUSTERING_NODENAME),n=[];for(let[s,i]of this.writes_by_db){let o=[],c=[],u,_;for(let l of i){let d=l.table,f=l.operation=="put"?"upsert":l.operation;u||(rE.trace(`Sending transaction event ${f}`),_=u={operation:f,schema:s,table:d,__origin:{user:this.user?.username,timestamp:t,node_name:r}},u.hash_values=c,f!=="delete"&&f!=="invalidate"&&(u.records=o)),u.table===d&&u.operation===f?(o.push(l.record),c.push(l.id)):_=_.next={operation:f,table:d,id:l.id,record:l.record},l.expiresAt&&(_.expiresAt=l.expiresAt)}u&&n.push(nE(`${RR.SUBJECT_PREFIXES.TXN}.${s}.${u.table}`,(0,AR.createNatsTableStreamName)(s,u.table),void 0,u)?.catch(l=>{throw rE.error("An error has occurred trying to replicate transaction",u,l),l.statusCode=504,l}))}return Promise.all(n)}},gR=class extends Zf{static{a(this,"ImmmediateNATSTransaction")}constructor(){super({get timestamp(){return(0,YB.getNextMonotonicTime)()}})}addWrite(t,r){super.addWrite(t,r),this.commit({})}};WB=new gR});var cH=T(Ao=>{"use strict";var{isMainThread:tne,parentPort:al,threadId:iE}=require("worker_threads"),{Socket:rne,createServer:nne}=require("net"),{createServer:sne,IncomingMessage:ine}=require("http"),{createServer:one}=require("https"),{readFileSync:xa,unlinkSync:zB,existsSync:ane}=require("fs"),_n=K(),He=Z(),pr=U(),{server:cE}=(Xt(),te(Ii)),{WebSocketServer:cne}=require("ws"),{createServer:une}=require("tls"),{getTicketKeys:lne,restartNumber:_ne,getWorkerIndex:JB}=Ze(),{Headers:tH}=($d(),te(xU)),{recordAction:ol,recordActionBinary:dne}=(Os(),te(ru)),{Request:rH,createReuseportFd:jB}=(Jf(),te(hR)),{checkMemoryLimit:fne}=Vi(),nH=require("tls"),XB=nH.createSecureContext;nH.createSecureContext=function(e){if(!e.cert||!e.key)return XB(e);let t={...e};delete t.key,delete t.cert;let r=XB(t);return r.context.setCert(e.cert),r.context.setKey(e.key,void 0),r};if(process.env.DEV_MODE)try{require("inspector").open(9229)}catch(e){_ne<=1&&_n.trace("Could not start debugging on port 9229, you may already be debugging:",e.message)}process.on("uncaughtException",e=>{e.code!=="ECONNRESET"&&e.message!=="write EIO"&&console.error("uncaughtException",e)});var{HDB_SETTINGS_NAMES:Fhe,CONFIG_PARAMS:Ene}=pr;He.initSync();var hne=He.get(Ene.HTTP_SESSIONAFFINITY),os={};Ao.registerServer=DR;Ao.httpServer=LR;Ao.deliverSocket=CR;Ao.startServers=sH;Ao.when_components_loaded=null;cE.http=LR;cE.request=Tne;cE.socket=gne;cE.ws=Rne;var NR={},oE={},mne,gi={},aE={},pne=[],wR=[];function sH(){return Ao.when_components_loaded=MR().loadRootComponents(!0).then(()=>{al?.on("message",t=>{let{port:r,fd:n,data:s}=t;if(n)CR(n,r,s);else if(t.requestId)Sne(t);else if(t.type===pr.ITC_EVENT_TYPES.SHUTDOWN){_n.trace("received shutdown request",iE);for(let i in os){let o=os[i],c;if(o.closeIdleConnections){let _=Object.getOwnPropertySymbols(o).find(f=>f.description.includes("connections")),l=0,d=setInterval(()=>{l++;let f=l>=100,E=o[_][f?"all":"idle"]();if(E.length===0){f&&clearInterval(d);return}l===1?_n.info(`Closing ${E.length} idle connections`):f&&_n.warn(`Forcefully closing ${E.length} active connections`);for(let h=0,p=E.length;h<p;h++){let S=E[h].socket;S._httpMessage&&!S._httpMessage.finished&&!f||(f?S.destroySoon():S.end(`HTTP/1.1 408 Request Timeout\r
|
|
27
|
+
Connection: close\r
|
|
28
|
+
\r
|
|
29
|
+
`))}},25).unref()}o.close?.(()=>{if(He.get(pr.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET)&&JB()==0)try{zB(He.get(pr.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET))}catch{}clearInterval(c),setTimeout(()=>{console.log("forced close server",i,iE),o.cantCleanupProperly||_n.warn("Had to forcefully exit the thread",iE),process.exit(0)},5e3).unref()})}if(process.env.DEV_MODE)try{require("inspector").close()}catch(i){console.error("Could not close debugger",i)}}}).ref();let e=[];if(jB&&!hne)for(let t in os){let r=os[t];if(isNaN(t)&&JB()==0){ane(t)&&zB(t),e.push(new Promise((s,i)=>{r.listen({path:t},()=>{s(),_n.info("Domain socket listening on "+t)}).on("error",i)}));continue}let n;try{n=jB(+t,"::")}catch(s){console.error(`Unable to bind to port ${t}`,s);continue}e.push(new Promise((s,i)=>{r.listen({fd:n},()=>{s(),_n.trace("Listening on port "+t,iE)}).on("error",i)}))}Promise.all(e).then(()=>{al?.postMessage({type:pr.ITC_EVENT_TYPES.CHILD_STARTED})})})}a(sH,"startServers");tne||sH();function CR(e,t,r){let n=e?.read?e:new rne({fd:e,readable:!0,writable:!0,allowHalfOpen:!0}),s=os[t];if(s.isSecure&&(n.startTime=performance.now()),s)typeof s=="function"?s(n):s.emit("connection",n),r&&n.emit("data",r);else{let i=a(o=>{setTimeout(()=>{let c=os[t];c?(typeof c=="function"?c(n):c.emit("connection",n),r&&n.emit("data",r)):o<5?i(o+1):(_n.error(`Server on port ${t} was not registered`),n.destroy())},1e3)},"retry");i(1)}return n}a(CR,"deliverSocket");var ZB=new Map;function Sne(e){let{port:t,event:r,data:n,requestId:s}=e,i;switch(i=ZB.get(s),r){case"connection":i=CR(void 0,t),ZB.set(s,i),i.write=(c,u,_)=>(al.postMessage({requestId:s,event:"data",data:c.toString("latin1")}),_&&_(),!0),i.end=(c,u,_)=>(al.postMessage({requestId:s,event:"end",data:c?.toString("latin1")}),_&&_(),!0);let o=i.destroy;i.destroy=()=>{o.call(i),al.postMessage({requestId:s,event:"destroy"})};break;case"data":i._readableState.destroyed||i.emit("data",Buffer.from(n,"latin1"));break;case"drain":i._readableState.destroyed||i.emit("drain",{});break;case"end":i._readableState.destroyed||i.emit("end",{});break;case"error":i._readableState.destroyed||i.emit("error",{});break}}a(Sne,"proxyRequest");function DR(e,t,r=!0){!+t&&t!==He.get(pr.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET)&&(t=parseInt(He.get(pr.CONFIG_PARAMS.HTTP_PORT),10));let n=os[t];if(n){let s=n.lastServer||n;if(s===e)throw new Error(`Can not register the same server twice for the same port ${t}`);if(r&&!!s.sessionIdContext!=!!e.sessionIdContext&&+t)throw new Error(`Can not mix secure HTTPS and insecure HTTP on the same port ${t}`);s.off("unhandled",eH),s.on("unhandled",(i,o)=>{e.cantCleanupProperly&&(n.cantCleanupProperly=!0),e.emit("request",i,o)}),n.lastServer=e}else os[t]=e;e.on("unhandled",eH)}a(DR,"registerServer");function iH(e){let t=[],r=parseInt(e?.securePort);return r&&t.push({port:r,secure:!0}),r=parseInt(e?.port),r&&t.push({port:r,secure:!1}),t.length===0&&(t=[],He.get(pr.CONFIG_PARAMS.HTTP_PORT)!=null&&t.push({port:He.get(pr.CONFIG_PARAMS.HTTP_PORT),secure:He.get(pr.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HTTPS)}),He.get(pr.CONFIG_PARAMS.HTTP_SECUREPORT)!=null&&t.push({port:He.get(pr.CONFIG_PARAMS.HTTP_SECUREPORT),secure:!0})),e?.isOperationsServer&&He.get(pr.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET)&&t.push({port:He.get(pr.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET),secure:!1}),t}a(iH,"getPorts");function LR(e,t){for(let{port:r,secure:n}of iH(t))oH(r,n,t?.isOperationsServer),typeof e=="function"?wR[t?.runFirst?"unshift":"push"]({listener:e,port:t?.port||r}):(e.isSecure=n,DR(e,r,!1)),aE[r]=IR(wR,r),mne=IR(pne,r)}a(LR,"httpServer");function oH(e,t,r){if(!gi[e]){let n=r?"operationsApi_network":"http",s={keepAliveTimeout:He.get(n+"_keepAliveTimeout"),headersTimeout:He.get(n+"_headersTimeout"),requestTimeout:He.get(n+"_timeout")},i=He.get(n+"_mtls"),o=He.get(n+"_mtls_required");if(t){n=r?"operationsApi_":"";let u=He.get(n+"tls_privateKey"),_=He.get(n+"tls_certificate"),l=He.get(n+"tls_certificateAuthority");Object.assign(s,{allowHTTP1:!0,key:xa(u),ciphers:He.get("tls_ciphers"),cert:xa(_),ca:l&&xa(l),rejectUnauthorized:!!o,requestCert:!!i,ticketKeys:lne()})}let c=fne();gi[e]=(t?one:sne)(s,async(u,_)=>{try{let d=performance.now(),f=new rH(u,_);r&&(f.isOperationsServer=!0);let E=await aE[e](f);if(!E){if(f._nodeResponse.statusCode)return;E=aH(f)}if(c?E.headers?.set?.("Server","Unlicensed HarperDB, this should only be used for educational and development purposes"):E.headers?.set?.("Server","HarperDB"),E.status===-1){for(let H of E.headers||[])_.setHeader(H[0],H[1]);return u.baseRequest=f,_.baseResponse=E,gi[e].emit("unhandled",u,_)}let h=E.status||200,p=performance.now(),S=p-d,O=E.body,g;if(!E.handlesHeaders){let H=E.headers||new tH;if(O?O.length>=0&&(typeof O=="string"?H.set("Content-Length",Buffer.byteLength(O)):H.set("Content-Length",O.length),g=!0):(H.set("Content-Length","0"),g=!0),H.append){let v=`hdb;dur=${S.toFixed(2)}`;E.wasCacheMiss&&(v+=", miss"),H.append("Server-Timing",v,!0)}_.writeHead(h,H&&(H[Symbol.iterator]?Array.from(H):H)),g&&_.end(O)}let R=f.handlerPath,B=f.method;if(ol(S,"duration",R,B,E.wasCacheMiss==null?void 0:E.wasCacheMiss?"cache-miss":"cache-hit"),dne(h<400,"success",R,B),!g)if(O?.pipe){O.pipe(_),O.destroy&&_.on("close",()=>{O.destroy()});let H=0;O.on("data",v=>{H+=v.length}),O.on("end",()=>{ol(performance.now()-p,"transfer",R,B),ol(H,"bytes-sent",R,B)})}else O?.then?O.then(H=>{_.end(H)},l):_.end(O)}catch(d){l(d)}function l(d){let f=d.headers;_.writeHead(d.statusCode||500,f&&(f[Symbol.iterator]?Array.from(f):f)),_.end(d.toString()),d.statusCode?d.statusCode===500?_n.warn(d):_n.info(d):_n.error(d)}a(l,"onError")}),i&&(gi[e].mtlsConfig=i),t&&(gi[e].on("secureConnection",u=>{u._parent.startTime&&ol(performance.now()-u._parent.startTime,"tls-handshake",e),ol(u.isSessionReused(),"tls-reused",e)}),gi[e].isSecure=!0),DR(gi[e],e)}return gi[e]}a(oH,"getHTTPServer");function IR(e,t){let r=aH;for(let n=e.length;n>0;){let{listener:s,port:i}=e[--n];if(i===t||i==="all"){let o=r;r=a(c=>s(c,o),"next_callback")}}return r}a(IR,"makeCallbackChain");function aH(e){return e.user&&(e._nodeRequest.user=e.user),{status:-1,body:"Not found",headers:new tH}}a(aH,"unhandled");function Tne(e,t){LR(e,{requestOnly:!0,...t})}a(Tne,"onRequest");function gne(e,t){let r;if(t.securePort){let n=He.get("tls_privateKey"),s=He.get("tls_certificate"),i=t.mtls?.certificateAuthority||He.get("tls_certificateAuthority");r=une({ciphers:He.get("tls_ciphers"),key:xa(n),cert:xa(s),ca:i&&xa(i),rejectUnauthorized:!!t.mtls?.required,requestCert:!!t.mtls},e),os[t.securePort]=r}return t.port&&(r=nne(e),os[t.port]=r),r}a(gne,"onSocket");Object.defineProperty(ine.prototype,"upgrade",{get(){return"connection"in this.headers&&"upgrade"in this.headers&&this.headers.connection.startsWith("Upgrade")&&this.headers.upgrade.toLowerCase()=="websocket"},set(e){}});function Rne(e,t){let r;for(let{port:n,secure:s}of iH(t)){oE[n]||(oE[n]=new cne({server:r=oH(n,s)}),oE[n].on("connection",async(c,u)=>{try{let _=new rH(u);_.isWebSocket=!0;let l=aE[n](_),d=u.headers["sec-websocket-protocol"]||"",f=NR[n];if(d){let E;for(let h=0;h<f.length;h++){let p=f[h];p.protocol===d&&(E=!0,p.listener(c,_,l))}if(E)return}for(let E=0;E<f.length;E++){let h=f[E];h.protocol||h.listener(c,_,l)}}catch(_){_n.warn("Error handling WebSocket connection",_)}}),oE[n].on("error",c=>{console.log("Error in setting up WebSocket server",c)}));let i=t?.subProtocol||"",o=NR[n];o||(o=NR[n]=[]),o.push({listener:e,protocol:i}),aE[n]=IR(wR,n)}return r}a(Rne,"onWebSocket");function eH(e,t){t.writeHead(404),t.end(`Not found
|
|
30
|
+
`)}a(eH,"defaultNotFound")});async function dH({clientId:e,user:t,clean:r,will:n}){let s;if(e&&!r){let i=await UR.getResource(e,{});s=new BR(e,t,i),i&&(s.sessionWasPresent=!0)}else{if(e){let i=await UR.get(e);i&&i.delete()}s=new lE(e,t)}return n&&(n.id=e,n.user={username:t?.username},cl.put(n)),s}function PR(){return uE++,uE>65500&&(uE=1),uE}function vR(e,t,r=e){let{topic:n,retain:s}=e;e.data=t,e.async=!0,e.authorize=!0;let i=di.getMatch(n);if(!i)throw new Error(`Can not publish to topic ${n} as it does not exist, no resource has been defined to handle this topic`);e.url=i.relativeURL;let o=i.Resource;return Ke(r,()=>s?t===void 0?o.delete(e,r):o.put(e,e.data,r):o.publish(e,e.data,r))}var uH,Oo,lH,_H,UR,cl,uE,lE,BR,fH=Oe(()=>{be();Uu();uH=x(Cr()),Oo=x(K());zi();lH=x(Ze()),_H=x(cH());Xt();UR=ot({database:"system",table:"hdb_durable_session",attributes:[{name:"id",isPrimaryKey:!0},{name:"subscriptions",type:"array",elements:{attributes:[{name:"topic"},{name:"qos"},{name:"startTime"},{name:"acks"}]}}]}),cl=ot({database:"system",table:"hdb_session_will",attributes:[{name:"id",isPrimaryKey:!0},{name:"topic",type:"string"},{name:"data"},{name:"qos",type:"number"},{name:"retain",type:"boolean"},{name:"user",type:"any"}]});(0,lH.getWorkerIndex)()===0&&(async()=>{await _H.when_components_loaded,await new Promise(e=>setTimeout(e,2e3));for await(let e of cl.search({})){let t=e.data,r=Object.assign({},e);r.user?.username&&(r.user=await Xe.getUser(r.user.username)),Ke(r,()=>{try{vR(r,t)}finally{cl.delete(e.id,r)}})}})();a(dH,"getSession");uE=1;a(PR,"getNextMessageId");lE=class{static{a(this,"SubscriptionsSession")}listener;sessionId;user;subscriptions=[];awaitingAcks;sessionWasPresent;constructor(t,r){this.sessionId=t,this.user=r}async addSubscription(t,r,n){let{topic:s,rh:i,startTime:o}=t,c=s.indexOf("?"),u,_;if(c>-1?(u=s.slice(c),_=s.slice(0,c)):_=s,!_)throw new Error("No topic provided");if(_.indexOf(".")>-1)throw new Error("Dots are not allowed in topic names");let l=this.subscriptions.find(O=>O.topic===s),d;l?(d=i>0,l.end(),this.subscriptions.splice(this.subscriptions.indexOf(l),1)):d=i===2;let f={search:u,async:!0,authorize:!0,user:this.user,startTime:o,omitCurrent:d,url:""};o&&(0,Oo.trace)("Resuming subscription from",s,"from",o);let E=di.getMatch(_);if(!E){let O=new Error(`The topic ${s} does not exist, no resource has been defined to handle this topic`);throw O.statusCode=404,O}if(f.url=E.relativeURL,f.url.indexOf("+")>-1||f.url.indexOf("#")>-1){let O=f.url.slice(1);if(O.indexOf("#")>-1&&O.indexOf("#")!==O.length-1)throw new Error("Multi-level wildcards can only be used at the end of a topic");if(f.isCollection=!0,O.indexOf("+")===O.length-1)f.onlyChildren=!0,f.url="/"+O.slice(0,O.length-1);else{let g=O.split("/"),R;for(let v=0;v<g.length;v++)if(g[v].indexOf("+")>-1)if(g[v]==="+")R=!0;else throw new Error("Single-level wildcards can only be used as a topic level (between or after slashes)");if(n&&R)throw new Error("Filters can not be combined");let B=!0;g[g.length-1]==="#"&&(g.length--,B=!1),R&&(n=a(v=>{let M=v.id;if(!Array.isArray(M)||B&&M.length!==g.length)return!1;for(let $=0;$<g.length;$++)if(g[$]!=="+"&&g[$]!==M[$])return!1;return!0},"filter"));let H=g.indexOf("+");f.url="/"+(H>-1?g.slice(0,H):g).concat("").join("/")}}let h=E.path,p=E.Resource,S=await Ke(f,async()=>{let O=await p.subscribe(f);if(!O)throw new Error(`No subscription was returned from subscribe for topic ${s}`);if(!O[Symbol.asyncIterator])throw new Error(`Subscription is not (async) iterable for topic ${s}`);return(async()=>{for await(let g of O)try{let R;if(g.type&&g.type!=="put"&&g.type!=="delete"&&g.type!=="message"&&g.type!=="patch"||n&&!n(g))continue;r?(g.topic=s,R=this.needsAcknowledge(g)):(g.acknowledge?.(),R=PR());let B=g.id;Array.isArray(B)&&(B=ma(B)),B==null&&(B=""),this.listener(h+"/"+B,g.value,R,t)}catch(R){(0,Oo.warn)(R)}})(),O});return S.topic=s,S.qos=t.qos,this.subscriptions.push(S),S}resume(){}needsAcknowledge(t){let r=PR();return t.acknowledge&&(this.awaitingAcks||(this.awaitingAcks=new Map),this.awaitingAcks.set(r,t.acknowledge)),r}acknowledge(t){let r=this.awaitingAcks?.get(t);r&&(this.awaitingAcks.delete(t),r())}async removeSubscription(t){let r=this.subscriptions.find(n=>n.topic===t);if(r)return r.end(),!0}async publish(t,r){return t.user=this.user,vR(t,r)}setListener(t){this.listener=t}disconnect(t){let r={};Ke(r,async()=>{if(!t){let n=await cl.get(this.sessionId,r);n?.doesExist()&&await vR(n,n.data,r)}await cl.delete(this.sessionId,r)}).catch(n=>{(0,Oo.warn)(`Error publishing MQTT will for ${this.sessionId}`,n)});for(let n of this.subscriptions)n.end();this.subscriptions=[]}};a(vR,"publish");BR=class extends lE{static{a(this,"DurableSubscriptionsSession")}sessionRecord;constructor(t,r,n){super(t,r),this.sessionRecord=n||{id:t,subscriptions:[]}}async resume(){for(let t of this.sessionRecord.subscriptions||[])await this.resumeSubscription({omitCurrent:!0,topic:t.topic,qos:t.qos,startTime:t.startTime},!0,t.acks?r=>!t.acks.includes(r.timestamp):null)}resumeSubscription(t,r,n){return super.addSubscription(t,r,n)}needsAcknowledge(t){this.awaitingAcks||(this.awaitingAcks=new Map);let r=PR(),n={topic:t.topic,timestamp:t.timestamp};return t.acknowledge&&(n.acknowledge=t.acknowledge),this.awaitingAcks.set(r,n),r}acknowledge(t){let r=this.awaitingAcks.get(t);this.awaitingAcks.delete(t),r.acknowledge?.();let n=r.topic;for(let[,s]of this.awaitingAcks)if(s.topic===n&&s.timestamp<r.timestamp){for(let i of this.sessionRecord.subscriptions)if(i.topic===n){i.acks||(i.acks=[]),i.acks.push(r.timestamp),(0,Oo.trace)("Received ack",n,r.timestamp),this.sessionRecord.update();return}}for(let s of this.sessionRecord.subscriptions)s.topic===n&&(s.startTime=r.timestamp);this.sessionRecord.update()}async addSubscription(t,r){await this.resumeSubscription(t,r);let{qos:n,startTime:s}=t;return n>0&&!s&&(this.sessionRecord.subscriptions=this.subscriptions.map(i=>{let o=i.startTime;return o||(o=i.startTime=(0,uH.getNextMonotonicTime)()),(0,Oo.trace)("Added durable subscription",i.topic,o),{qos:i.qos,topic:i.topic,startTime:o}}),UR.put(this.sessionRecord)),t.qos}}});var HR={};ke(HR,{bypassAuth:()=>Ane,start:()=>One});function Ane(){SH=!0}function One({server:e,port:t,network:r,webSocket:n,securePort:s,requireAuthentication:i}){let o=e.mqtt={requireAuthentication:i,sessions:new Set},c,u=r?.mtls;return n&&(c=e.ws((_,l,d)=>{if(_.protocol==="mqtt"){let{onMessage:f,onClose:E}=mH(_,(h,p)=>{if(_.send(h),p&&_._socket.writableNeedDrain)return new Promise(S=>this._socket.once("drain",S))},l,Promise.resolve(d).then(()=>l?.user),o);_.on("message",f),_.on("close",E),_.on("error",h=>{(0,Sr.info)("WebSocket error",h)})}},Object.assign({subProtocol:"mqtt"},n))),(t||s)&&(c=e.socket(async _=>{let l;if(u){if(_.authorized)try{let E=u.user;E!==null&&((E===void 0||E==="Common Name"||E==="CN")&&(E=_.getPeerCertificate().subject.CN),l=await e.getUser(E,null,null))}catch(E){(0,Sr.error)(E)}else if(u.required)return(0,Sr.info)(`Unauthorized connection attempt, no authorized client certificate provided, error: ${_.authorizationError}`),_.end()}!l&&SH&&_.remoteAddress.includes("127.0.0.1")&&(l=await(0,pH.getSuperUser)());let{onMessage:d,onClose:f}=mH(_,E=>_.write(E),null,l,o);_.on("data",d),_.on("close",f),_.on("error",E=>{(0,Sr.info)("Socket error",E)})},{port:t,securePort:s,mtls:u})),c}function mH(e,t,r,n,s){hH||(hH=!0,tu(d=>{_E>0&&d.push({metric:"mqtt-connections",connections:_E,byThread:!0})}));let i;_E++;let o,c={protocolVersion:4},u=(0,fE.parser)({protocolVersion:5});function _(d){u.parse(d)}a(_,"onMessage");function l(){_E--,i||(i=!0,o?.disconnect(),s.sessions.delete(o),tn(!1,"connection","mqtt","disconnect"))}return a(l,"onClose"),u.on("packet",async d=>{n?.then&&(n=await n),o?.then&&await o;try{switch(d.cmd){case"connect":if(c.protocolVersion=d.protocolVersion,d.username)try{n=await Xe.getUser(d.username,d.password.toString(),r),(0,dE.get)(as.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)&&EH.notify({username:n.username,status:as.AUTH_AUDIT_STATUS.SUCCESS,type:as.AUTH_AUDIT_TYPES.AUTHENTICATION,auth_strategy:"MQTT",remote_address:e.remoteAddress})}catch{return(0,dE.get)(as.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGFAILED)&&EH.error({username:n.username,status:as.AUTH_AUDIT_STATUS.FAILURE,type:as.AUTH_AUDIT_TYPES.AUTHENTICATION,auth_strategy:"mqtt",remote_address:e.remoteAddress}),f({cmd:"connack",reasonCode:4,returnCode:134})}if(!n&&s.requireAuthentication)return tn(!1,"connection","mqtt","connect"),f({cmd:"connack",reasonCode:4,returnCode:134});try{if(s.authorizeClient?.(d,n),d.will){let R=e.deserialize||(e.deserialize=Eo(r?.headers.get?.("content-type")));d.will.data=d.will.payload?.length>0?R(d.will.payload):void 0,delete d.will.payload}o=dH({user:n,...d}),o=await o,s.sessions.add(o)}catch(R){return(0,Sr.error)(R),tn(!1,"connection","mqtt","connect"),f({cmd:"connack",reasonCode:R.code||5,returnCode:R.code||128})}tn(!0,"connection","mqtt","connect"),f({cmd:"connack",sessionPresent:o.sessionWasPresent,reasonCode:0,returnCode:0}),o.setListener((R,B,H,v)=>{try{let M=R.indexOf("/",1),$=M>0?R.slice(0,M):R;f({cmd:"publish",topic:R,payload:E(B),messageId:H||Math.floor(Math.random()*1e8),qos:v.qos},$)}catch(M){(0,Sr.error)(M),o?.disconnect(),s.sessions.delete(o)}}),o.sessionWasPresent&&await o.resume();break;case"subscribe":let h=[];for(let R of d.subscriptions){let B;try{B=(await o.addSubscription(R,R.qos>=1)).qos||0}catch(H){(0,Sr.error)(H),B=c.protocolVersion<5?128:H.statusCode===403?135:H.statusCode===404?143:128}h.push(B)}await o.committed,f({cmd:"suback",granted:h,messageId:d.messageId});break;case"unsubscribe":{let R=[];for(let B of d.unsubscriptions)R.push(o.removeSubscription(B)?0:17);f({cmd:"unsuback",granted:R,messageId:d.messageId});break}case"pubrel":f({cmd:"pubcomp",messageId:d.messageId,reasonCode:0});return;case"publish":let p=d.qos===2?"pubrec":"puback",S=e.deserialize||(e.deserialize=Eo(r?.headers.get?.("content-type"))),O=d.payload?.length>0?S(d.payload):void 0,g;try{g=await o.publish(d,O)}catch(R){(0,Sr.warn)(R),d.qos>0&&f({cmd:p,messageId:d.messageId,reasonCode:128},d.topic);break}d.qos>0&&f({cmd:p,messageId:d.messageId,reasonCode:g===!1?144:0},d.topic);break;case"pubrec":f({cmd:"pubrel",messageId:d.messageId,reasonCode:0});break;case"pubcomp":case"puback":o.acknowledge(d.messageId);break;case"pingreq":f({cmd:"pingresp"});break;case"disconnect":i=!0,o?.disconnect(!0),s.sessions.delete(o),tn(!0,"connection","mqtt","disconnect"),e.close?e.close():e.end();break}}catch(h){(0,Sr.error)(h),f({cmd:"disconnect"})}function f(h,p){let S=(0,fE.generate)(h,c);t(S),Hr(S.length,"bytes-sent",p,h.cmd,"mqtt")}a(f,"sendPacket");function E(h){return Ei(h,r)}a(E,"serialize")}),{onMessage:_,onClose:l}}var fE,pH,dE,as,Sr,EH,SH,hH,_E,TH=Oe(()=>{fE=require("mqtt-packet");fH();pH=x(Ur());pa();Os();Xt();dE=x(Z()),as=x(U()),Sr=x(K()),EH=(0,Sr.loggerWithTag)("auth-event"),SH=(0,dE.get)(as.CONFIG_PARAMS.AUTHENTICATION_AUTHORIZELOCAL)??process.env.DEV_MODE;a(Ane,"bypassAuth");a(One,"start");_E=0;a(mH,"onSocket")});var rf={};ke(rf,{component_errors:()=>Fa,loadComponent:()=>EE,loadComponentDirectories:()=>IH,setErrorReporter:()=>wne});function IH(e,t){t&&(qR=t),e&&(FR=e);let r=[];if((0,vn.existsSync)(xR)){let s=(0,vn.readdirSync)(xR,{withFileTypes:!0});for(let i of s){if(!i.isDirectory()&&!i.isSymbolicLink())continue;let o=i.name,c=(0,St.join)(xR,o);r.push(EE(c,qR,"hdb",!1))}}let n=process.env.RUN_HDB_APP;return n&&r.push(EE(n,qR,n,!1,null,process.env.DEV_MODE)),Promise.all(r).then(()=>{wH=!0})}function wne(e){ll=e}async function EE(e,t,r,n,s,i){if(!RH.has(e)){RH.set(e,!0),s&&(FR=s);try{let o;n&&(Fa=new Map);let c=(0,St.join)(e,n?"harperdb-config.yaml":"config.yaml");(0,vn.existsSync)(c)?o=n?(0,NH.getConfigObj)():(0,AH.parseDocument)((0,vn.readFileSync)(c,"utf8"),{simpleKeys:!0}).toJSON():o=GR;let u=[],_=n;for(let l in o){let d=o[l];if(Fa.set(n?l:(0,St.basename)(e),!1),!d)continue;let f,E=d.package;try{if(E){let g=e,R;for(;!(0,vn.existsSync)(R=(0,St.join)(g,"node_modules",l));)if(g=(0,St.dirname)(g),g.length<(0,yH.getHdbBasePath)().length){R=null;break}if(R)f=await EE(R,t,r,!1),_=!0;else throw new Error(`Unable to find package ${l}:${E}`)}else f=Nne[l];if(!f)continue;u.push(f);let h=a(g=>(g.origin=r,ot(g)),"ensureTable"),p=d.network||(d.port||d.securePort)&&d,S=p?.securePort||p?.https&&p.port,O=!p?.https&&p?.port;if(qa.isMainThread&&(f=await f.startOnMainThread?.({server:Xe,ensureTable:h,port:O,securePort:S,resources:t,...d})||f,n&&p))for(let g of[O,S])try{if(+g&&!gH.includes(g)){let R=kR.get(VR.CONFIG_PARAMS.HTTP_SESSIONAFFINITY);R&&ul.default.warn("Session affinity is not recommended and may cause memory leaks"),(R||!zf)&&(gH.push(g),yB(g,R))}}catch(R){console.error("Error listening on socket",g,R,l)}if(t.isWorker&&(f=await f.start?.({server:Xe,ensureTable:h,port:O,securePort:S,resources:t,...d})||f),FR.set(f,!0),(f.handleFile||f.handleDirectory)&&d.files){if(d.files.includes(".."))throw(0,bH.handleHDBError)("Can not reference parent directories");let g=(0,St.join)(e,d.files).replace(/\\/g,"/"),R=g.indexOf("/*");if(R>-1&&d.files!==GR[l]?.files&&!(0,vn.existsSync)(g.slice(0,R)))throw new Error(`The path '${g.slice(0,R)}' does not exist and cannot be used as the base of the resolved 'files' path value '${d.files}'`);let B=(0,St.basename)(e),H=d.path||"/";H=H.startsWith("/")?H:H.startsWith("./")?"/"+B+H.slice(2):H==="."?"/"+B:"/"+B+"/"+H;let v,M,$;if(d.root){let z=d.root;z.startsWith("/")&&(z=z.slice(1)),z.endsWith("/")&&(z=z.slice(0,-1)),z+="/",M=(0,St.join)(e,z)}else($=g.indexOf("/*"))>-1&&(M=g.slice(0,$+1),v=(0,St.relative)(e,M));let W=!1;if(qa.isMainThread&&f.setupDirectory&&(W=await f.setupDirectory?.(H,M,t)),t.isWorker&&f.handleDirectory&&(W=await f.handleDirectory?.(H,M,t)),W)continue;for(let z of await(0,OH.default)(g,{onlyFiles:!1,objectMode:!0})){let{path:se,dirent:Te}=z;_=!0;let oe=(0,St.relative)(e,se).replace(/\\/g,"/");if(v)if(oe.startsWith(v))oe=oe.slice(v.length+1);else throw new Error(`The root path '${d.root}' does not reference a valid part of the file path '${oe}'.The root path should be used to indicate the relative path/part of the file path for determining the exported web path.`);let xe=H+(H.endsWith("/")?"":"/")+oe;try{if(Te.isFile()){let de=await yne(se);qa.isMainThread&&await f.setupFile?.(de,xe,se,t),t.isWorker&&await f.handleFile?.(de,xe,se,t)}else qa.isMainThread&&await f.setupDirectory?.(xe,se,t),t.isWorker&&await f.handleDirectory?.(xe,se,t)}catch(de){de.message=`Could not load ${Te.isFile()?"file":"directory"} '${se}'${d.module?" using '"+d.module+"'":""} for application '${e}' due to: ${de.message}`,ll?.(de),((0,Ga.getWorkerIndex)()===0?console:ul.default).error(de),t.set(d.path||"/",new _l(de)),Fa.set(n?l:(0,St.basename)(e),de.message)}}}}catch(h){h.message=`Could not load component '${l}' for application '${(0,St.basename)(e)}' due to: ${h.message}`,ll?.(h),((0,Ga.getWorkerIndex)()===0?console:ul.default).error(h),t.set(d.path||"/",new _l(h),null,!0),Fa.set(n?l:(0,St.basename)(e),h.message)}}if(qa.isMainThread&&!wH&&i&&(0,Ga.watchDir)(e,async()=>IH()),o.extensionModule)return await zl((0,St.join)(e,o.extensionModule));if(!_&&t.isWorker){let l=`${e} did not load any modules, resources, or files, is this a valid component?`;ll?.(new Error(l)),((0,Ga.getWorkerIndex)()===0?console:ul.default).error(l),Fa.set((0,St.basename)(e),l)}}catch(o){console.error(`Could not load application directory ${e}`,o),o.message=`Could not load application due to ${o.message}`,ll?.(o),t.set("",new _l(o))}}}var vn,St,qa,AH,kR,VR,OH,Ga,ul,bH,yH,bne,NH,yne,xR,FR,wH,qR,Fa,Nne,GR,gH,RH,ll,_l,nf=Oe(()=>{vn=require("fs"),St=require("path"),qa=require("worker_threads"),AH=require("yaml"),kR=x(Z()),VR=x(U());tb();ib();ob();Iv();EB();gB();OH=x(require("fast-glob")),Ga=x(Ze()),ul=x(K());Oh();Xt();bH=x(ee());An();be();NB();yH=x(Z()),bne=x(LB());Qd();bR();TH();NH=x(Ir());Jf();({readFile:yne}=vn.promises),xR=kR.get(VR.CONFIG_PARAMS.COMPONENTSROOT),FR=new Map,Fa=new Map;a(IH,"loadComponentDirectories");Nne={REST:Af,rest:Af,graphqlSchema:Ah,jsResource:yh,fastifyRoutes:oR,login:wh,static:aR,operationsApi:bne,customFunctions:{},http:{},clustering:sE,authentication:Pu,mqtt:HR},GR={rest:!0,graphqlSchema:{files:"*.graphql"},jsResource:{files:"resources.js"},fastifyRoutes:{files:"routes/*.js",path:"."}};Object.defineProperty(GR,"static",{value:{files:"web/**"}});gH=[],RH=new Map;a(wne,"setErrorReporter");a(EE,"loadComponent");_l=class extends vt{constructor(r){super();this.error=r}static{a(this,"ErrorResource")}get(){throw this.error}post(){throw this.error}put(){throw this.error}delete(){throw this.error}connect(){throw this.error}getResource(){return this}publish(){throw this.error}subscribe(){throw this.error}}});var MR=T((dme,DH)=>{var{isMainThread:CH}=require("worker_threads"),{getTables:Ine}=(be(),te(qe)),{loadComponentDirectories:Cne,loadComponent:Dne}=(nf(),te(rf)),{resetResources:Lne}=(Uu(),te(HU)),Mne=FT(),Une=Ir(),{dirname:Pne}=require("path"),{getConnection:vne}=ft(),Bne=Z(),Hne=U(),$R=new Map;async function xne(e=!1){!CH&&Bne.get(Hne.CONFIG_PARAMS.CLUSTERING_ENABLED)&&vne();try{CH&&await Mne()}catch(n){console.error(n)}let t=Lne();Ine(),t.isWorker=e,await Dne(Pne(Une.getConfigFilePath()),t,"hdb",!0,$R),await Cne($R,t);let r=[];for(let[n]of $R)n.ready&&r.push(n.ready());r.length>0&&await Promise.all(r)}a(xne,"loadRootComponents");DH.exports.loadRootComponents=xne});var Ze=T((Eme,Ai)=>{"use strict";var{Worker:qne,MessageChannel:Fne,parentPort:cs,isMainThread:zR,threadId:Gne,workerData:Gs}=require("worker_threads"),{PACKAGE_ROOT:kne}=U(),{join:PH,isAbsolute:Vne,extname:$ne}=require("path"),{server:vH}=(Xt(),te(Ii)),{watch:Yne,readdir:Kne}=require("fs/promises"),{totalmem:LH}=require("os"),dl=U(),BH=Z(),ks=K(),{randomBytes:Wne}=require("crypto"),{_assignPackageExport:Qne}=require("../../index"),zne=U(),MH=1024*1024,Ri=[],dn=[],Jne=50,JR=1e4,jne="restart",HH="request_thread_info",xH="resource_report",qH="thread_info",FH="added-port",Xne="ack",YR;Qne("threads",dn);Ai.exports={startWorker:KR,restartWorkers:XR,shutdownWorkers:nse,workers:Ri,setMonitorListener:_se,onMessageFromWorkers:sse,onMessageByType:WH,broadcast:ose,broadcastWithAcknowledgement:cse,setChildListenerByType:rse,getWorkerIndex:GH,getWorkerCount:kH,getTicketKeys:$H,setMainIsWorker:ese,setTerminateTimeout:Zne,restartNumber:Gs?.restartNumber||1};dn.onMessageByType=WH;dn.sendToThread=function(e,t){if(!t?.type)throw new Error("A message with a type must be provided");let r=dn.find(n=>n.threadId===e);if(r)return r.postMessage(t),!0};var jR;function Zne(e){JR=e}a(Zne,"setTerminateTimeout");function GH(){return Gs?Gs.workerIndex:jR?0:void 0}a(GH,"getWorkerIndex");function kH(){return Gs?Gs.workerCount:jR?1:void 0}a(kH,"getWorkerCount");function ese(e){jR=e}a(ese,"setMainIsWorker");var VH=1,hE;function $H(){return hE||(hE=zR?Wne(48):Gs.ticketKeys,hE)}a($H,"getTicketKeys");Object.defineProperty(vH,"workerIndex",{get(){return GH()}});Object.defineProperty(vH,"workerCount",{get(){return kH()}});var YH={[HH](e,t){use(t)},[xH](e,t){lse(t,e)}};function KR(e,t={}){let r=process.constrainedMemory?.()||LH();r=Math.min(r,LH(),2e4*MH);let n=BH.get(dl.CONFIG_PARAMS.MAXHEAPMEMORY)??Math.max(Math.floor(r/MH/(10+(t.threadCount||1)/4)),512),s=Math.min(Math.max(n>>6,16),64),i=[],o=[];for(let u of dn){let _=new Fne;_.existingPort=u,i.push(_),o.push(_.port2)}$ne(e)||(e+=".js");let c=new qne(Vne(e)?e:PH(kne,e),Object.assign({resourceLimits:{maxOldGenerationSizeMb:n,maxYoungGenerationSizeMb:s},execArgv:["--enable-source-maps"],argv:process.argv.slice(2),workerData:{addPorts:o,addThreadIds:i.map(u=>u.existingPort.threadId),workerIndex:t.workerIndex,workerCount:VH=t.threadCount,name:t.name,restartNumber:Ai.exports.restartNumber,ticketKeys:$H()},transferList:o},t));for(let{port1:u,existingPort:_}of i)_.postMessage({type:FH,port:u,threadId:c.threadId},[u]);return pE(c,!0),c.unexpectedRestarts=t.unexpectedRestarts||0,c.startCopy=()=>KR(e,t),c.on("error",u=>{console.error("Worker error:",u),ks.error("Worker error:",u)}),c.on("exit",u=>{Ri.splice(Ri.indexOf(c),1),!c.wasShutdown&&t.autoRestart!==!1&&(c.unexpectedRestarts<Jne?(t.unexpectedRestarts=c.unexpectedRestarts+1,KR(e,t)):ks.error(`Thread has been restarted ${c.restarts} times and will not be restarted`))}),c.on("message",u=>{YH[u.type]?.(u,c)}),Ri.push(c),fse(),t.onStarted&&t.onStarted(c),c.name=t.name,c}a(KR,"startWorker");var tse=[dl.THREAD_TYPES.HTTP];async function XR(e=null,t=Math.max(VH>3,1),r=!0){if(zR){if(r){let{loadRootComponents:o}=MR();await o()}Ai.exports.restartNumber++,t<1&&(t=t*Ri.length);let n=[],s=[];for(let o of Ri.slice(0)){if(e&&o.name!==e||o.wasShutdown)continue;ks.trace("sending shutdown request to ",o.threadId),o.postMessage({restartNumber:Ai.exports.restartNumber,type:dl.ITC_EVENT_TYPES.SHUTDOWN}),o.wasShutdown=!0,o.emit("shutdown",{});let c=tse.indexOf(o.name)>-1,u=new Promise(_=>{let l=setTimeout(()=>o.terminate(),JR*2).unref();o.on("exit",()=>{clearTimeout(l),n.splice(n.indexOf(u)),!c&&r&&o.startCopy(),_()})});if(n.push(u),c&&r){let _=o.startCopy(),l=new Promise(d=>{let f=a(E=>{E.type===zne.ITC_EVENT_TYPES.CHILD_STARTED&&(ks.trace("Worker has started",_.threadId),d(),s.splice(s.indexOf(l)),_.off("message",f))},"startListener");ks.trace("Waiting for worker to start",_.threadId),_.on("message",f)});s.push(l),n.length>=t&&await Promise.race(n),s.length>=t&&await Promise.race(s)}}await Promise.all(n),await Promise.all(s);let{restartService:i}=kd();r&&(e==="http"||!e)&&BH.get(dl.CONFIG_PARAMS.CLUSTERING_ENABLED)&&await i({service:"clustering"})}else cs.postMessage({type:jne,workerType:e})}a(XR,"restartWorkers");function rse(e,t){YH[e]=t}a(rse,"setChildListenerByType");function nse(e){return XR(e,1/0,!1)}a(nse,"shutdownWorkers");var KH=[];function sse(e){KH.push(e)}a(sse,"onMessageFromWorkers");var WR=new Map;function WH(e,t){let r=WR.get(e);r||WR.set(e,r=[]),r.push(t)}a(WH,"onMessageByType");var ise=10;async function ose(e){let t=0;for(let r of dn)try{r.postMessage(e),t++>ise&&(t=0,await new Promise(setImmediate))}catch(n){ks.error("Unable to send message to worker",n)}}a(ose,"broadcast");var mE=new Map,ase=1;function cse(e){return new Promise(t=>{let r=0;for(let n of dn)try{let s=ase++,i=a(()=>{mE.delete(s),--r===0&&t(),n!==cs&&--n.refCount===0&&n.unref()},"ack_handler");i.port=n,n.ref(),n.refCount=(n.refCount||0)+1,mE.set(e.requestId=s,i),n.hasAckCloseListener||(n.hasAckCloseListener=!0,n.on(n.close?"close":"exit",()=>{for(let[,o]of mE)o.port===n&&o()})),n.postMessage(e),r++}catch(s){ks.error("Unable to send message to worker",s)}r===0&&t()})}a(cse,"broadcastWithAcknowledgement");function use(e){e.postMessage({type:qH,workers:QH()})}a(use,"sendThreadInfo");function QH(){let e=Date.now();return Ri.map(t=>({threadId:t.threadId,name:t.name,heapTotal:t.resources?.heapTotal,heapUsed:t.resources?.heapUsed,externalMemory:t.resources?.external,arrayBuffers:t.resources?.arrayBuffers,sinceLastUpdate:e-t.resources?.updated,...t.recentELU}))}a(QH,"getChildWorkerInfo");function lse(e,t){e.resources=t,e.resources.updated=Date.now()}a(lse,"recordResourceReport");var QR;function _se(e){QR=e}a(_se,"setMonitorListener");var dse=1e3,UH=!1;function fse(){UH||(UH=!0,setInterval(()=>{for(let e of Ri){let t=e.performance.eventLoopUtilization(),r;e.lastTotalELU?r=e.performance.eventLoopUtilization(t,e.lastTotalELU):r=t,e.lastTotalELU=t,e.recentELU=r}QR&&QR()},dse).unref())}a(fse,"startMonitoring");var Ese=1e3;if(cs){pE(cs);for(let e=0,t=Gs.addPorts.length;e<t;e++){let r=Gs.addPorts[e];r.threadId=Gs.addThreadIds[e],pE(r)}setInterval(()=>{let e=process.memoryUsage();cs.postMessage({type:xH,heapTotal:e.heapTotal,heapUsed:e.heapUsed,external:e.external,arrayBuffers:e.arrayBuffers})},Ese).unref(),YR=a(()=>new Promise((e,t)=>{cs.on("message",r),cs.postMessage({type:HH});function r(n){n.type===qH&&(cs.off("message",r),e(n.workers))}a(r,"receiveThreadInfo")}),"getThreadInfo")}else YR=QH;Ai.exports.getThreadInfo=YR;function pE(e,t){dn.push(e),e.on("message",r=>{if(r.type===FH)r.port.threadId=r.threadId,pE(r.port);else if(r.type===Xne){let n=mE.get(r.id);n&&n()}else{for(let s of KH)s(r,e);let n=WR.get(r.type);if(n)for(let s of n)try{s(r,e)}catch(i){ks.error(i)}}}).on("close",()=>{dn.splice(dn.indexOf(e),1)}).on("exit",()=>{dn.splice(dn.indexOf(e),1)}),t?e.refCount=100:e.unref()}a(pE,"addPort");if(zR){let e,t,r=a(async(n,s)=>{s&&(e=s);for(let i of await Kne(n,{withFileTypes:!0}))i.isDirectory()&&i.name!=="node_modules"&&r(PH(n,i.name));try{for await(let{filename:i}of Yne(n,{persistent:!1}))t&&clearTimeout(t),t=setTimeout(async()=>{e&&await e(),await XR(),console.log("Reloaded HarperDB components")},100)}catch(i){console.warn("Error trying to watch component directory",n,i)}},"watch_dir");Ai.exports.watchDir=r,process.env.WATCH_DIR&&r(process.env.WATCH_DIR)}else cs.on("message",async e=>{let{type:t}=e;t===dl.ITC_EVENT_TYPES.SHUTDOWN&&(Ai.exports.restartNumber=e.restartNumber,cs.unref(),setTimeout(()=>{ks.warn("Thread did not voluntarily terminate",Gne),process.exit(0)},JR).unref())})});var QI={};ke(QI,{AUDIT_STORE_OPTIONS:()=>sx,createAuditEntry:()=>e_,openAuditStore:()=>RE,readAuditEntry:()=>Lt,setAuditRetention:()=>mse,transactionKeyEncoder:()=>nx});function RE(e){let t=e.auditStore=e.openDB(ex.AUDIT_STORE_NAME,sx);t.rootStore=e;let r=[];t.addDeleteRemovalCallback=function(i,o){return r[i]=o,{remove(){delete r[i]}}};let n=null;function s(i=SE){clearTimeout(n),n=setTimeout(async()=>{if(t.rootStore.status==="closed")return;let o=0,c;try{for(let{key:u,value:_}of t.getRange({start:0,snapshot:!1,end:Date.now()-ZR})){if((_[0]&15)===rA){let l=Lt(_),d=l.tableId;r[d]?.(l.recordId)}if(c=t.remove(u),await new Promise(setImmediate),++o>=hse){i=10;break}}await c}finally{o===0&&(i=Math.min(i<<1,ZR/10)),s(i)}},i).unref()}return a(s,"scheduleAuditCleanup"),t.scheduleAuditCleanup=s,(0,gE.getWorkerIndex)()===(0,gE.getWorkerCount)()-1&&s(SE),t}function mse(e,t=SE){ZR=e,SE=t}function e_(e,t,r,n,s,i,o){let c=ix[i];if(!c)throw new Error(`Invalid audit entry type ${i}`);let u=1;n&&(n>1?ka.setFloat64(0,n):fn.set($h),u=9),f(0),f(t),d(r),ka.setFloat64(u,e),u+=8,s?d(s):fn[u++]=0,fn[n?8:0]=c;let l=fn.subarray(0,u);if(o)return Buffer.concat([l,o]);return l;function d(E){let h=u;u+=1,u=(0,Va.writeKey)(E,fn,u);let p=u-h-1;p>127?p>16383?(sA.error("Key or username was too large for audit entry",E),u=h+1,fn[h]=0):(fn.copyWithin(h+2,h+1,u),ka.setUint16(h,p|32768),u++):fn[h]=p}function f(E){E<128?fn[u++]=E:E<16384?(ka.setUint16(u,E|32768),u+=2):E<1056964608?(ka.setUint32(u,E|3221225472),u+=4):(fn[u]=255,ka.setUint32(u+1,E),u+=5)}}function Lt(e){try{let t=e.dataView||(e.dataView=new nA(e.buffer,e.byteOffset,e.byteLength)),r;e[0]==66&&(r=t.readFloat64());let n=t.readInt(),s=t.readInt(),i=t.readInt(),o=t.readInt(),c=t.position,u=t.position+=o,_=t.readFloat64();o=t.readInt();let l=t.position,d=t.position+=o;return{type:ix[n&7],tableId:i,get recordId(){return ZH(e,c,u)},version:_,previousLocalTime:r,get user(){return d>l?ZH(e,l,d):void 0},getValue(f,E,h){if(n&eA||n&tA&&!E)return f.decoder.decode(e.subarray(t.position));if(n&tA&&h)return iA(f.getEntry(this.recordId),h,f)}}}catch{return sA.error("Reading audit entry error",e),{}}}function ZH(e,t,r){let n=e.subarray(t,r);return(0,Va.readKey)(n,0,r-t)}var Va,TE,ex,tx,gE,rx,sA,fn,ka,nx,sx,ZR,hse,SE,eA,tA,zH,rA,JH,jH,XH,ix,nA,Ui=Oe(()=>{Va=require("ordered-binary"),TE=x(Z()),ex=x(lt()),tx=x(U()),gE=x(Ze()),rx=x(J());Ho();sA=x(K());AE();(0,TE.initSync)();fn=Buffer.alloc(1024),ka=new DataView(fn.buffer,fn.byteOffset,1024),nx={writeKey(e,t,r){return e===gc?(t.set(gc,r),r+8):typeof e=="number"?((t.dataView||(t.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength))).setFloat64(r,e),r+8):(0,Va.writeKey)(e,t,r)},readKey(e,t,r){return e[t]===66?(e.dataView||(e.dataView=new DataView(e.buffer,e.byteOffset,e.byteLength))).getFloat64(t):(0,Va.readKey)(e,t,r)}},sx={encoding:"binary",keyEncoder:nx},ZR=(0,rx.convertToMS)((0,TE.get)(tx.CONFIG_PARAMS.LOGGING_AUDITRETENTION))||86400*3,hse=1e3,SE=1e4;a(RE,"openAuditStore");a(mse,"setAuditRetention");eA=16,tA=32,zH=1,rA=2,JH=3,jH=4,XH=5,ix={put:zH|eA,[zH]:"put",delete:rA,[rA]:"delete",message:JH|eA,[JH]:"message",invalidate:jH,[jH]:"invalidate",patch:XH|tA,[XH]:"patch"};a(e_,"createAuditEntry");a(Lt,"readAuditEntry");nA=class extends DataView{static{a(this,"Decoder")}position=0;readInt(){let t=this.getUint8(this.position++);return t>=128?t>=192?t===255?(t=this.getUint32(this.position),this.position+=4,t):(t=this.getUint32(this.position-1)&1073741823,this.position+=3,t):(t=this.getUint16(this.position-1)&32767,this.position++,t):t}readFloat64(){try{let t=this.getFloat64(this.position);return this.position+=8,t}catch{debugger}}};a(ZH,"readKeySafely")});var oA={};ke(oA,{add:()=>OE,applyReverse:()=>ox,getRecordAtTime:()=>iA,rebuildUpdateBefore:()=>bE});function OE(e,t,r){isNaN(e[t])?e[t]=r.value:e[t]+=r.value}function bE(e,t){let r=null;for(let n in e)if(n in t){let s=t[n];if(s?.__op__){let i=e[n];if(i?.__op__)if(i.__op__===s.__op__)r||(r={}),r[n]=i;else throw new Error("Can not merge updates with different operations");else r||(r={}),r[n]=i,OE(r,n,s)}}else r||(r={}),r[n]=e[n];return r}function ox(e,t){for(let r in t){let n=t[r];if(n?.__op__){let s=pse[n.__op__]?.reverse;if(s)s(e,r,{value:n.value});else throw new Error(`Unsupported operation ${n.__op__}`)}else e[r]=ax}}function iA(e,t,r){let n=r.rootStore.auditStore,s=Object.assign({},e.value),i=e.localTime;for(;i>t;){let u=n.get(i),_=Lt(u);switch(_.type){case"put":s=_.getValue(r);break;case"patch":ox(s,_.getValue(r));break;case"delete":s=null}i=_.previousLocalTime}let o={},c=0;for(let u in s)s[u]===ax&&(o[u]=!0,c++);for(;c>0&&i>0;){let u=n.get(i),_=Lt(u),l;switch(_.type){case"put":l=_.getValue(r);break;case"patch":l=_.getValue(r);break}for(let d in l)o[d]&&(s[d]=l[d],o[d]=!1,c--);i=_.previousLocalTime}if(c>0)for(let u in o)s[u]=null;return s}var pse,ax,AE=Oe(()=>{Ui();a(OE,"add");OE.reverse=function(e,t,r){isNaN(e[t])||(e[t]-=r.value)};pse={add:OE};a(bE,"rebuildUpdateBefore");a(ox,"applyReverse");ax={};a(iA,"getRecordAtTime")});function Vr(e){return e[wt]||(e[wt]=Object.create(null))}function CE(e,t){let r=e.prototype,n={},s=t.attributes||t.properties||[];for(let o of s){let c=o.name,u,_;if(o.resolve)_={get(){return o.resolve(this,this[ye])},set(l){return o.set(this,l)},configurable:!0};else{switch(o.type){case"String":u=a(function(l){if(!(typeof l=="string"||l==null&&o.nullable!==!1))throw new En.ClientError(`${c} must be a string, attempt to assign ${l}`);Vr(this)[c]=l},"set");break;case"ID":u=a(function(l){if(!(typeof l=="string"||l?.length>0&&l.every?.(d=>typeof d=="string")||l==null&&o.nullable!==!1))throw new En.ClientError(`${c} must be a string, attempt to assign ${l}`);Vr(this)[c]=l},"set");break;case"Float":case"Number":u=a(function(l){if(!(typeof l=="number"||l==null&&o.nullable!==!1))throw new En.ClientError(`${c} must be a number, attempt to assign ${l}`);Vr(this)[c]=l},"set");break;case"Int":u=a(function(l){if(!(l>>0===l||l==null&&o.nullable!==!1))if(typeof l=="number"&&Math.abs((l>>0)-l)<=1)l=Math.round(l);else throw new En.ClientError(`${c} must be an integer between -2147483648 and 2147483647, attempt to assign ${l}`);Vr(this)[c]=l},"set");break;case"Long":u=a(function(l){if(!(Math.round(l)===l&&Math.abs(l)<=9007199254740992||l==null&&o.nullable!==!1))if(typeof l=="number"&&Math.abs(l)<=9007199254740992)l=Math.round(l);else throw new En.ClientError(`${c} must be an integer between -9007199254740992 and 9007199254740992, attempt to assign ${l}`);Vr(this)[c]=l},"set");break;case"BigInt":u=a(function(l){if(!(typeof l=="bigint"||l==null&&o.nullable!==!1))if(typeof l=="string"||typeof l=="number")l=BigInt(l);else throw new En.ClientError(`${c} must be a number, attempt to assign ${l}`);Vr(this)[c]=l},"set");break;case"Boolean":u=a(function(l){if(!(typeof l=="boolean"||l==null&&o.nullable!==!1))throw new En.ClientError(`${c} must be a boolean, attempt to assign ${l}`);Vr(this)[c]=l},"set");break;case"Date":u=a(function(l){if(!(l instanceof Date||l==null&&o.nullable!==!1))if(typeof l=="string"||typeof l=="number")l=new Date(l);else throw new En.ClientError(`${c} must be a Date, attempt to assign ${l}`);Vr(this)[c]=l},"set");break;case"Bytes":u=a(function(l){if(!(l instanceof Uint8Array||l==null&&o.nullable!==!1))throw new En.ClientError(`${c} must be a Buffer or Uint8Array, attempt to assign ${l}`);Vr(this)[c]=l},"set");break;case"Any":case void 0:u=a(function(l){Vr(this)[c]=l},"set");break;default:u=a(function(l){if(!(typeof l=="object"||l==null&&o.nullable!==!1))throw new En.ClientError(`${c} must be an object, attempt to assign ${l}`);Vr(this)[c]=l},"set")}_={get(){let l=this[wt];if(l&&c in l){let f=l[c];if(f?.__op__){let E=this[he]?.[c];return f.update(E)}return f}let d=this[he]?.[c];if(d&&typeof d=="object"){let f=ux(d,o);if(f)return l||(l=this[wt]=Object.create(null)),l[c]=f}return d},set:u,enumerable:!0,configurable:!0}}_.get.isAttribute=!0,n[c]=_,(!(c in r)||Object.getOwnPropertyDescriptor(r,c)?.get?.isAttribute)&&Object.defineProperty(r,c,_)}i("getProperty",function(o){let c=n[o];if(c)return c.get.call(this);let u=this[wt];return u?.[o]!==void 0?u[o]:this[he]?.[o]}),i("set",function(o,c){let u=n[o];if(u)return u.set.call(this,c);if(t.sealed)throw new En.ClientError("Can not add a property to a sealed table schema");Vr(this)[o]=c}),i("deleteProperty",function(o){Vr(this)[o]=void 0}),i("toJSON",function(){let o=this[wt],c;for(let _ in o){c||(c=Object.assign({},this[he]));let l=o[_];if(l?.__op__){let d=c[_];l=l.update(d)}c[_]=l}return Object.keys(this).length>0&&(c||(c=Object.assign({},this[he])),Object.assign(c,this)),c||this[he]}),r.get||i("get",r.getProperty),r.delete||i("delete",r.deleteProperty);function i(o,c){Object.defineProperty(r,o,{value:c,configurable:!0})}a(i,"setMethod")}function ux(e,t){let r;switch(e.constructor){case Object:return t?((r=t.TrackedObject)||(t.TrackedObject=r=class{static{a(this,"TrackedObject")}constructor(s){if(s?.[he])throw new Error("Can not track an already tracked object, check for circular references");this[he]=s}},CE(r,t)),new r(e)):new yE(e);case Array:let n=new wE(e.length);n[he]=e;for(let s=0,i=e.length;s<i;s++){let o=e[s];o&&typeof o=="object"&&(o=ux(o,t?.elements)),n[s]=o}return n;default:return e}}function $_(e){let t=e[wt],r;for(let s in t){r||(r=Object.assign({},e[he]));let i=t[s];if(i&&typeof i=="object")if(i.__op__){let o=r[s];i=i.update(o)}else i=$_(i);r[s]=i}return Object.keys(e).length>0&&(r||(r=Object.assign({},e[he])),Object.assign(r,e)),r||e[he]}function yo(e,t=e[wt]){let r;if(cx.call(e,he)&&e.constructor===Array&&!Object.isFrozen(e)){r=e;for(let n=0,s=e.length;n<s;n++){let i=e[n];if(i&&typeof i=="object"){let o=yo(i);o!==i&&r===e&&(r=e.slice(0)),i=o}r[n]=i}return Object.freeze(r)}for(let n in t){r||(r=Object.assign({},e[he]));let s=t[n];if(s&&typeof s=="object")if(s.__op__){let i=oA[s?.__op__];if(i)i(r,n,s);else throw new Error("Invalid CRDT operation "+s.__op__);continue}else s=yo(s);r[n]=s}return r?Object.freeze(r):cx.call(e,he)?e[he]:e}function NE(e){let t=e[he];if(t===void 0)return!0;if(e.constructor===Array){if(!t||e[bo]||e.length!==t.length)return!0;for(let r=0,n=e.length;r<n;r++){let s=t[r],i=e[r];if(s&&i?.[he]===s){if(NE(i))return!0}else return!0}}else{let r=e[wt];if(r&&!t)return!0;for(let n in r){let s=r[n];if(s&&typeof s=="object"){let i=t[n];if(i&&s[he]===i){if(NE(s))return!0}else return!0}else return!0}}return!1}var En,wt,yE,cx,bo,wE,IE,Y_=Oe(()=>{An();En=x(ee());AE();wt=Symbol("own-data");a(Vr,"getChanges");a(CE,"assignTrackedAccessors");a(ux,"trackObject");yE=class{static{a(this,"GenericTrackedObject")}constructor(t){if(t?.[he])throw new Error("Can not track an already tracked object, check for circular references");this[he]=t}};CE(yE,{});a($_,"collapseData");cx=Object.prototype.hasOwnProperty;a(yo,"deepFreeze");a(NE,"hasChanges");bo=Symbol.for("has-array-changes"),wE=class extends Array{static{a(this,"TrackedArray")}[bo];constructor(t){super(t)}splice(...t){return this[bo]=!0,super.splice(...t)}push(...t){return this[bo]=!0,super.push(...t)}pop(){return this[bo]=!0,super.pop()}unshift(...t){return this[bo]=!0,super.unshift(...t)}shift(){return this[bo]=!0,super.shift()}};wE.prototype.constructor=Array;IE=class{constructor(t){this.value=t}static{a(this,"Addition")}__op__="add";update(t){return(+t||0)+this.value}}});var Ep={};ke(Ep,{CONTEXT:()=>ye,ID_PROPERTY:()=>Ue,IS_COLLECTION:()=>hn,RECORD_PROPERTY:()=>he,Resource:()=>vt,snake_case:()=>Tse,transformForSelect:()=>LE});function Tse(e){return e[0].toLowerCase()+e.slice(1).replace(/[a-z][A-Z][a-z]/g,t=>t[0]+"_"+t.slice(1))}function lx(e,t){if(fl=!1,e==="")return null;if(e=e.slice(1),e.indexOf("/")===-1)return e===""?(fl=!0,null):(e.startsWith("$")&&(e=parseInt(e,36)),t.coerceId(decodeURIComponent(e)));let r=e.split("/"),n=new cA;for(let s=0;s<r.length;s++){let i=r[s];if(!i&&s===r.length-1){fl=!0;break}n[s]=t.coerceId(decodeURIComponent(i))}return n}function $r(e,t){n.reliesOnPrototype=!0;let r=t.hasContent;return n;function n(s,i,o){let c,u,_,l;if(r?(o?(l=i,o=o[ye]||o):i?typeof s=="object"&&s&&(!Array.isArray(s)||typeof s[0]=="object")?(l=s,c=l[this.primaryKey]??null,o=i[ye]||i):l=i:(l=s,c=l[Ue]??l[this.primaryKey]??null),c==null&&(_=!0)):i?o=i[ye]||i:s&&typeof s=="object"&&!Array.isArray(s)&&(o=s),c===void 0)if(typeof s=="string")c=s;else if(typeof s=="object"&&s)if(u=s,s[Symbol.iterator]){c=[],_=!0;for(let E of s){if(typeof E=="object"&&E)break;c.push(E)}c.length===0?c=null:(c.length===1&&(c=c[0]),u.slice&&(u=u.slice(c.length,u.length),u.length===0&&(u=null,_=!1)))}else{if(typeof(c=s.url)=="string"){let E=c.indexOf("?");if(E>-1){let p=this.parseQuery(c.slice(E+1));u?u=Object.assign(p,u):u=p,c=c.slice(0,E)}let h=this.parsePath(c,o,u);h?.id!==void 0?(h.query&&(u?u=Object.assign(h.query,u):u=h.query),_=h.isCollection,c=h.id):c=h}c===void 0&&(c=s.id??null,c==null&&(_=!0))}else c=s??null,c==null&&(_=!0);o||(o={});let d;if(u?.ensureLoaded!=null||u?.async||_?(d=Object.assign({},t),u?.ensureLoaded!=null&&(d.ensureLoaded=u.ensureLoaded),u?.async&&(d.async=u.async),_&&(d.isCollection=!0)):d=t,o.transaction){let E=this.getResource(c,o,d);return E.then?E.then(f):f(E)}else return d.resetTransaction=!0,Ke(o,()=>{let E=this.getResource(c,o,d);return E.then?E.then(f):f(E)},d);function f(E){if(o.authorize){o.authorize=!1;let h=t.type==="read"?E.allowRead(o.user,u,o):t.type==="update"?E.doesExist?.()===!1?E.allowCreate(o.user,l,o):E.allowUpdate(o.user,l,o):t.type==="create"?E.allowCreate(o.user,l,o):E.allowDelete(o.user,u,o);if(h?.then)return h.then(p=>{if(!p)throw new DE(o.user);return typeof l?.then=="function"?l.then(S=>e(E,u,o,S)):e(E,u,o,l)});if(!h)throw new DE(o.user)}return typeof l?.then=="function"?l.then(h=>e(E,u,o,h)):e(E,u,o,l)}a(f,"authorizeActionOnResource")}}function Yr(e,t){let r=new fx.ClientError(`The ${e.constructor.name} does not have a ${t} method implemented`,405);r.allow=[],r.method=t;for(let n of["get","put","post","delete","query","move","copy"])typeof e[n]=="function"&&r.allow.push(n);throw r}function aA(e,t,r){let n=e[he];if(n){let s=e[wt];return i=>{let o,c;return e.hasOwnProperty(i)&&typeof(o=e[i])!="function"?o:s&&i in s?s[i]:(c=t?.[i])?c(e,r):n[i]}}else return t?s=>{let i=t[s];return i?i(e,r):e[s]}:s=>e[s]}function LE(e,t){let r=t?.propertyResolvers,n=t[ye],s;if(typeof e=="string")return a(function o(c){return c.then?c.then(o):Array.isArray(c)?c.map(o):aA(c,r,n)(e)},"transform");if(typeof e=="object"){if(e.asArray)return a(function c(u){if(u.then)return u.then(c);if(Array.isArray(u))return u.map(c);let _=[],l=i(aA(u,r,n));for(let d of e)_.push(l(d));return _},"transform");let o=e.forceNulls;return a(function c(u){if(u.then)return u.then(c);if(Array.isArray(u))return u.map(f=>f&&typeof f=="object"?c(f):f);let _={},l=i(aA(u,r,n)),d;for(let f of e){let E=l(f);E===void 0&&o&&(E=null),E?.then?(d||(d=[]),d.push(E.then(h=>_[f.name||f]=h))):_[f.name||f]=E}return d?Promise.all(d).then(()=>_):_},"transform")}else throw new Error("Invalid select argument type "+typeof e);function i(o){return c=>{if(typeof c=="string")return o(c);if(typeof c=="object")if(c.name){s||(s={});let u=s[c.name];if(!u){let l=r[c.name]?.definition?.tableClass;u=s[c.name]=LE(c.select||c,l)}let _=o(c.name);return u(_)}else return o(c);else return c}}a(i,"handleProperty")}var _x,dx,fx,ye,Ue,hn,he,Sse,vt,DE,fl,cA,An=Oe(()=>{_x=require("crypto");Ec();dx=require("../../index"),fx=x(ee());Y_();zi();gf();ye=Symbol.for("context"),Ue=Symbol.for("primary-key"),hn=Symbol("is-collection"),he=Symbol("stored-record"),Sse={json:"application/json",cbor:"application/cbor",msgpack:"application/x-msgpack",csv:"text/csv"},vt=class{static{a(this,"Resource")}static transactions;constructor(t,r){this[Ue]=t;let n=r?.[ye];this[ye]=n!==void 0?n:r||null}static get=$r(function(t,r,n,s){let i=t.get?.(r);if(i?.then)return i.then(o);return o(i);function o(c){let u;if((u=r?.select)&&c!=null&&!c.selectApplied){let _=LE(u,t.constructor);return typeof c?.map=="function"?c.map(_):_(c)}return c}},{type:"read",resetTransaction:!0,ensureLoaded:!0,async:!0});static put=$r(function(t,r,n,s){if(Array.isArray(s)&&t[hn]){let i=[],o=n.authorize;for(let c of s){let u=t.constructor,_=u.getResource(c[u.primaryKey],n,{async:!0});_.then?i.push(_.then(l=>l.put(c,n))):i.push(_.put(c,n))}return Promise.all(i)}return t.put?t.put(s,r):Yr(t,"put")},{hasContent:!0,type:"update"});static patch=$r(function(t,r,n,s){return t.patch?t.patch(s,r):Yr(t,"patch")},{hasContent:!0,type:"update"});static delete=$r(function(t,r,n,s){return t.delete?t.delete(r):Yr(t,"delete")},{hasContent:!1,type:"delete"});static getNewId(){return(0,_x.randomUUID)()}static create(t,r,n){let s;return t==null?s=this.getNewId():Array.isArray(t)&&typeof t[0]!="object"?s=[...t,this.getNewId()]:typeof t!="object"?s=[t,this.getNewId()]:(s=this.getNewId(),n=r,r=t),Ke(n,()=>{let i=new this(s,n),o=i.update?i.update(r):Yr(i,"update");return n.newLocation=s,n.createdResource=!0,o?.then?o.then(()=>s):s})}static invalidate=$r(function(t,r,n,s){return t.invalidate?t.invalidate(r):Yr(t,"delete")},{hasContent:!1,type:"update"});static post=$r(function(t,r,n,s){return t[Ue]!=null&&t.update?.(),t.post(s,r)},{hasContent:!0,type:"create"});static connect=$r(function(t,r,n,s){return t.connect?t.connect(s,r):Yr(t,"connect")},{hasContent:!0,type:"read"});static subscribe=$r(function(t,r,n,s){return t.subscribe?t.subscribe(r):Yr(t,"subscribe")},{type:"read"});static publish=$r(function(t,r,n,s){return t[Ue]!=null&&t.update?.(),t.publish?t.publish(s,r):Yr(t,"publish")},{hasContent:!0,type:"create"});static search=$r(function(t,r,n,s){let i=t.search?t.search(r):Yr(t,"search"),o=n.select;if(o&&n.hasOwnProperty("select")&&i!=null&&!i.selectApplied){let c=LE(o,t.constructor);return i.map(c)}return i},{type:"read"});static query=$r(function(t,r,n,s){return t.search?t.search(s,r):Yr(t,"search")},{hasContent:!0,type:"read"});static copy=$r(function(t,r,n,s){return t.copy?t.copy(s,r):Yr(t,"copy")},{type:"create"});static move=$r(function(t,r,n,s){return t.move?t.move(s,r):Yr(t,"move")},{type:"delete"});post(t){if(this[hn])return this.constructor.create(this[Ue],t,this[ye]);Yr(this,"post")}static isCollection(t){return t?.[hn]}static coerceId(t){return t}static parseQuery(t){return Tf(t)}static parsePath(t,r,n){let s=t.indexOf(".");if(s>-1){let o=t.slice(s+1);t=t.slice(0,s);let c=r?.headers&&Sse[o];if(c)r.headers.set("accept",c);else if(n)n.property=o;else return{query:{property:o},id:lx(t,this),isCollection:fl}}let i=lx(t,this);return fl?{id:i,isCollection:!0}:i}static getResource(t,r,n){let s,i=r[ye],o;typeof r.isCollection=="boolean"&&r.hasOwnProperty("isCollection")?o=r.isCollection:o=n?.isCollection;let c=o&&this.Collection||this;if(i||(i=i===void 0?r:{}),i.transaction){let u;if(i.resourceCache?u=i.resourceCache:u=i.resourceCache=[],u.asMap){let _=u.asMap.get(t);if(s=_?.find(l=>l.constructor===c),s)return s;_||u.asMap.set(t,_=[]),_.push(s=new c(t,i))}else{if(s=u.find(_=>_[Ue]===t&&_.constructor===c),s)return s;if(u.push(s=new c(t,i)),u.length>10){let _=new Map;for(let l of u){let d=l[Ue],f=_.get(d);f?f.push(l):_.set(d,[l])}i.resourceCache.length=0,i.resourceCache.asMap=_}}}else s=new c(t,i);return o&&(s[hn]=!0),s}subscribe(t){return new Rn}connect(t){return t?.subscribe!==!1?this.subscribe?.(t):new Rn}allowRead(t){return t?.role.permission.super_user}allowUpdate(t){return t?.role.permission.super_user}allowCreate(t){return t?.role.permission.super_user}allowDelete(t){return t?.role.permission.super_user}getId(){return this[Ue]}getContext(){return this[ye]}};vt.prototype[ye]=null;(0,dx._assignPackageExport)("Resource",vt);a(Tse,"snake_case");DE=class extends Error{static{a(this,"AccessError")}constructor(t){t?(super("Unauthorized access to resource"),this.statusCode=403):(super("Must login"),this.statusCode=401)}};a(lx,"pathToId");cA=class extends Array{static{a(this,"MulitPartId")}toString(){return this.join("/")}};a($r,"transactional");a(Yr,"missingMethod");a(aA,"selectFromObject");a(LE,"transformForSelect")});function hx(e,t,r,n){let s=e.primaryStore.env.path,i=e.primaryStore.tableId;$a||((0,ME.onMessageByType)(Ex,l=>{mx(l.path)}),$a=Object.create(null));let o=$a[s]||($a[s]=[]);o.auditStore=e.auditStore,o.lastTxnTime==null&&(o.lastTxnTime=Date.now());let c=o[i];c||(c=o[i]=new Map,c.envs=o,c.tableId=i,c.store=e.primaryStore),t=ma(t);let u=new lA(r);u.startTime=n;let _=c.get(t);return _?_.push(u):(c.set(t,_=[u]),_.tables=c,_.key=t),u.subscriptions=_,u}function mx(e,t){if(!$a)return;let r=$a[e];if(!r)return;try{r.auditStore.resetReadTxn()}catch(s){throw s.message+=" in "+e,s}let n;for(let{key:s,value:i}of r.auditStore.getRange({start:r.lastTxnTime,exclusiveStart:!0})){r.lastTxnTime=s;let o=Lt(i),c=r[o.tableId];if(!c)continue;let u=o.recordId,_,l=ma(o.recordId),d=0;do{let f=c.get(l);if(f){for(let h of f)if(!(d>0&&!(h.includeDescendants&&!(h.onlyChildren&&d>1)))){if(h.startTime>=s){(0,uA.info)("omitting",u,h.startTime,s);continue}try{if(h.crossThreads===!1&&!t)continue;let p;h.supportsTransactions&&h.txnInProgress!==o.version&&(p=!0,h.txnInProgress||(n?n.push(h):n=[h]),h.txnInProgress=o.version),h.listener(u,o,s,p)}catch(p){console.error(p),(0,uA.info)(p)}}}if(l==null)break;let E=l.lastIndexOf?.("/",l.length-2);E>-1?l=l.slice(0,E):l=null,d++}while(!0)}if(n)for(let s of n)s.txnInProgress=null,s.listener(null,{type:"end_txn"},r.lastTxnTime,!0)}function px(e,t){let r=t||e,n=r.env;if(t&&!t.cache&&(t.cache=new Map),!n.hasBroadcastListener){n.hasBroadcastListener=!0;let s=n.path;r.on("aftercommit",()=>{(0,ME.broadcast)({type:Ex,path:s}),mx(s,!0)})}}var uA,ME,Ex,$a,Bme,lA,Sx=Oe(()=>{uA=x(K()),ME=x(Ze());Ec();Uu();Ui();Ex="transaction",Bme=Buffer.alloc(4096);a(hx,"addSubscription");lA=class extends Rn{static{a(this,"Subscription")}listener;subscriptions;startTime;constructor(t){super(),this.listener=t,this.on("close",()=>this.end())}end(){if(this.subscriptions){if(this.subscriptions.splice(this.subscriptions.indexOf(this),1),this.subscriptions.length===0){let t=this.subscriptions.tables,r=this.subscriptions.key;if(t.delete(r),t.size===0){let n=t.envs,s=t.dbi;delete n[s]}}this.subscriptions=null}}toJSON(){return{name:"subscription"}}};a(mx,"notifyFromTransactionData");a(px,"listenToCommits")});var Vg={};ke(Vg,{coerceType:()=>UE,makeTable:()=>BE,setServerUtilities:()=>Ise,updateResource:()=>PE});function BE(e){let{primaryKey:t,indices:r,tableId:n,tableName:s,primaryStore:i,databasePath:o,databaseName:c,auditStore:u,schemaDefined:_,dbisDB:l}=e,{expirationMS:d,evictionMS:f,audit:E,trackDeletes:h}=e,{attributes:p}=e;p||(p=[]),px(i,u);let S=Wh(i,n,u),O=0,g,R,B={},H=Promise.resolve(),v,M,$;for(let Y of p)(Y.assignCreatedTime||Y.name==="__createdtime__")&&(v=Y),(Y.assignUpdatedTime||Y.name==="__updatedtime__")&&(M=Y),Y.expiresAt&&($=Y),Y.isPrimaryKey&&(B=Y);let W,z=[],se=[],Te=1,oe=2,xe={},de={},It=864e5,Nl,wl,Vs,AA=!1,KE,zx=i.getRange({start:!1,end:!1}).constructor,Jx=10,jx=6;E&&yA();class We extends vt{static name=s;static primaryStore=i;static auditStore=u;static primaryKey=t;static tableName=s;static indices=r;static audit=E;static databasePath=o;static databaseName=c;static attributes=p;static expirationTimer;static createdTimeProperty=v;static updatedTimeProperty=M;static propertyResolvers;static sources=[];static get expirationMS(){return d}static dbisDB=l;static schemaDefined=_;static sourcedFrom(m,A){A&&(this.sourceOptions=A,(A.expiration||A.eviction||A.scanInterval)&&this.setTTLExpiration(A)),A?.intermediateSource?(m.intermediateSource=!0,this.sources.unshift(m)):this.sources.push(m),R=m.get&&(!m.get.reliesOnPrototype||m.prototype.get);let I=a(w=>{let N=this.sources.slice(0,-1);if(N=N.filter(P=>P[w]&&(!P[w].reliesOnPrototype||P.prototype[w])),N.length>0)if(N.length===1){let P=N[0];return(L,D,q)=>{if(L?.source!==P)return P[w](D,q,L)}}else return(P,L,D)=>{let q=[];for(let G of N){if(P?.source===G)break;q.push(G[w](L,D,P))}return Promise.all(q)}},"getApplyToIntermediateSource"),b=this.sources[this.sources.length-1],y=a(w=>{if(b[w]&&(!b[w].reliesOnPrototype||b.prototype[w]))return(N,P,L)=>{if(!N?.source)return b[w](P,L,N)}},"getApplyToCanonicalSource");return xe={put:y("put"),patch:y("patch"),delete:y("delete"),publish:y("publish")},de={put:I("put"),patch:I("patch"),delete:I("delete"),publish:I("publish"),invalidate:I("invalidate")},(async()=>{let w=!1,N=a(async(P,L)=>{let D=P.value,q=P.table?et[c][P.table]:We;if(c===Bn.SYSTEM_SCHEMA_NAME&&(P.table===Bn.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME||P.table===Bn.SYSTEM_TABLE_NAMES.USER_TABLE_NAME)&&(w=!0),P.id===void 0&&(P.id=D[q.primaryKey],P.id===void 0))throw new Error("Replication message without an id "+JSON.stringify(P));P.source=m;let G=await q.getResource(P.id,L,Ya);switch(P.type){case"put":return G._writeUpdate(D,!0,Ya);case"patch":return G._writeUpdate(D,!1,Ya);case"delete":return G._writeDelete(Ya);case"publish":return G._writePublish(D,Ya);case"invalidate":return G.invalidate(Ya);default:ze.error("Unknown operation",P.type,P.id)}},"writeUpdate");try{let P=m.subscribe;P&&h==null&&(h=!0);let L=m.subscribeOnThisThread?m.subscribeOnThisThread((0,wo.getWorkerIndex)()):(0,wo.getWorkerIndex)()===0,D=P&&L&&await m.subscribe?.({crossThreads:!1,inTransactionUpdates:!0,supportsTransactions:!0,omitCurrent:!0});if(D){let q;for await(let G of D)try{if(!(G.type==="transaction"?G.writes[0]:G)){ze.error("Bad subscription event",G);continue}if(G.source=m,q)if(G.beginTxn)q.resolve();else{N(G,q);continue}if(G.type==="end_txn")continue;let ae=Ke(G,()=>{if(G.type==="transaction"){let re=[];for(let ce of G.writes)try{re.push(N(ce,G))}catch(ve){throw ve.message+=" writing "+JSON.stringify(ce)+" of event "+JSON.stringify(G),ve}return Promise.all(re)}else if(G.type==="define_schema"){let re=this.attributes.slice(0),ce;for(let ve of G.attributes)re.find(ne=>ne.name===ve.name)||(re.push(ve),ce=!0);ce&&(ot({table:s,database:c,attributes:re,origin:"cluster"}),gl.signalSchemaChange(new Rl.SchemaEventMsg(process.pid,Bn.OPERATIONS_ENUM.CREATE_TABLE,c,s)))}else return G.beginTxn?(q=G,N(G,G),new Promise(re=>{q.resolve=re})):N(G,G)});w&&(await ae,gl.signalUserChange(new Rl.UserEventMsg(process.pid))),G.onCommit&&(ae?.then?ae.then(G.onCommit):G.onCommit())}catch(ie){ze.error("error in subscription handler",ie)}}}catch(P){ze.error(P)}})(),this}static getResource(m,A,I){let b=super.getResource(m,A,I);if(m!=null){za(m);try{if(b.hasOwnProperty(he))return b;if(typeof m=="object"&&m&&!Array.isArray(m))throw new Error(`Invalid id ${JSON.stringify(m)}`);let y=!I?.async||i.cache?.get(m),w=gr(A),N=w.getReadTxn();if(N?.isDone)throw new Error("You can not read from a transaction that has already been committed/aborted");return WE(m,A,{transaction:N},y,P=>{if(P?PE(b,P):b[he]=null,A.onlyIfCached&&A.noCacheStore){if(!b.doesExist())throw new mn.ServerError("Entry is not cached",504)}else if(I?.ensureLoaded){let L=QE(m,P,A,b);if(L)return w?.disregardReadTxn(),b[_A]=!0,fA(L,D=>(PE(b,D),b))}return b})}catch(y){throw y.message.includes("Unable to serialize object")&&(y.message+=": "+JSON.stringify(m)),y}}return b}ensureLoaded(){let m=QE(this[Ue],this[Kr],this[ye]);if(m)return this[_A]=!0,fA(m,A=>{this[Kr]=A,this[he]=A.value,this[Sl]=A.version})}static setTTLExpiration(m){if(typeof m=="number")d=m*1e3,f||(f=0);else if(m&&typeof m=="object")d=m.expiration*1e3,f=(m.eviction||0)*1e3,It=m.scanInterval*1e3;else throw new Error("Invalid expiration value type");if(d<0)throw new Error("Expiration can not be negative");It=It||(d+f)/4,JE()}static enableAuditing(m=!0){E=m,m&&yA(),We.audit=m}static coerceId(m){return m===""?null:UE(m,B)}static async dropTable(){if(delete et[c][s],c===o){for(let m of p)l.remove(We.tableName+"/"+m.name),r[m.name]?.drop();l.remove(We.tableName+"/"),i.drop(),await l.committed}else console.log("legacy dropTable"),await i.close(),await fs.remove(data_path),await fs.remove(data_path===standard_path?data_path+MDB_LOCK_FILE_SUFFIX:path.join(path.dirname(data_path),MDB_LEGACY_LOCK_FILE_NAME));gl.signalSchemaChange(new Rl.SchemaEventMsg(process.pid,Bn.OPERATIONS_ENUM.DROP_TABLE,c,s))}get(m){if(typeof m=="string")return this.getProperty(m);if(this[hn])return this.search(m);if(this[Ue]===null){if(m?.conditions)return this.search(m);let A=We.getRecordCount();return{recordCount:A.recordCount,estimatedRecordRange:A.estimatedRange,records:"./",name:s,database:c,attributes:p}}if(m?.property)return this.getProperty(m.property);if(this.doesExist()||m?.ensureLoaded===!1||this[ye]?.returnNonexistent)return this}allowRead(m,A){let I=Cl(m);if(I?.read){if(I.isSuperUser)return!0;let b=I.attribute_permissions,y=A?.select;if(b?.length>0||AA&&y){if(A||(A={}),y){let w=b?.length>0&&dA(b,"read");A.select=y.map(N=>{let P=N.name||N;if(!w||w[P]){let L=Vs[P]?.definition?.tableClass;if(L){if(N.name||(N={name:N}),!L.prototype.allowRead.call(null,m,N))return!1;if(!N.select)return N.name}return N}}).filter(Boolean)}else A.select=b.filter(w=>w.read&&!Vs[w.attribute_name]).map(w=>w.attribute_name);return A}else return!0}}allowUpdate(m,A){let I=Cl(m);if(I?.update){let b=I.attribute_permissions;if(b?.length>0){let y=dA(b,"update");for(let w in A)if(!y[w])return!1;for(let w of b){let N=w.attribute_name;!w.update&&!(N in A)&&(A[N]=this.getProperty(N))}}return!0}}allowCreate(m,A){if(this[hn]){let I=Cl(m);if(I?.insert){let b=I.attribute_permissions;if(b?.length>0){let y=dA(b,"insert");for(let w in A)if(!y[w])return!1}else return!0}}else return this.allowUpdate(m,{})}allowDelete(m){return Cl(m)?.delete}update(m,A){if(!gr(this[ye]))throw new Error("Can not update a table resource outside of a transaction");if(m===!1)return this;let b;return typeof m=="object"&&m&&(A?(Object.isFrozen(m)&&(m=Object.assign({},m)),this[he]={},this[wt]=m):(b=this[wt],b&&(m=Object.assign(b,m)),this[wt]=b=m)),this._writeUpdate(this[wt],A),this}addTo(m,A){if(typeof A=="number")this[El]===gx?this.set(m,(+this.getProperty(m)||0)+A):(this[El]||this.update(),this.set(m,new IE(A)));else throw new Error("Can not add a non-numeric value")}subtractFrom(m,A){if(typeof A=="number")return this.addTo(m,-A);throw new Error("Can not subtract a non-numeric value")}invalidate(m){let A=this[ye],I=this[Ue];za(I),gr(this[ye]).addWrite({key:I,store:i,invalidated:!0,entry:this[Kr],nodeName:this[ye]?.nodeName,before:xe.invalidate?.bind(this,A,I),beforeIntermediate:de.invalidate?.bind(this,A,I),commit:(y,w)=>{if(w?.version>y)return;let N=null;for(let P in r)N||(N={}),N[P]=this.getProperty(P);S(I,N,this[Kr],y,hl,E,this[ye],0,"invalidate")}})}static evict(m,A,I){let b=this.Source,y;if(!((R||E)&&(!A||(y=i.getEntry(m),!y||!A)||y.version!==I))){if(R){if(i.hasLock(m,y.version))return;let w;for(let N in r)w||(w={}),w[N]=A[N];if(w)return S(m,w,y,I,ml,null,null,0,null,!0)}return i.ifVersion(I,()=>{Il(m,A,null)}),E?S(m,null,y,I,ml,null,null,0,null,!0):i.remove(m,I)}}lock(){throw new Error("Not yet implemented")}static operation(m,A){return m.table||=s,m.schema||=c,Nx.operation(m,A)}put(m){this.update(m,!0)}patch(m){this.update(m,!1)}_writeUpdate(m,A,I){let b=this[ye],y=gr(b),w=this[Ue];za(w);let N=this[Kr];this[El]=A?gx:yse;let P={key:w,store:i,entry:N,nodeName:b?.nodeName,validate:L=>{m||(m=this[wt]),A||m&&NE(m)?(this.validate(m,!A),b?.source||(M&&(m[M.name]=M.type==="Date"?new Date(L):M.type==="String"?new Date(L).toISOString():L),A&&(t&&m[t]!==w&&(m[t]=w),v&&(N?.value?m[v.name]=N?.value[v.name]:m[v.name]=v.type==="Date"?new Date(L):v.type==="String"?new Date(L).toISOString():L),m=yo(m)))):y.removeWrite(P)},before:A?xe.put?()=>xe.put(b,w,m):null:xe.patch?()=>xe.patch(b,w,m):xe.put?()=>xe.put(b,w,yo(this)):null,beforeIntermediate:A?de.put?()=>de.put(b,w,m):null:de.patch?()=>de.patch(b,w,m):de.put?()=>de.put(b,w,yo(this)):null,commit:(L,D,q)=>{if(q){if(b&&D?.version>(b.lastModified||0)&&(b.lastModified=D.version),this[Kr]=D,D?.value?.[he])throw new Error("Can not assign a record to a record, check for circular references");A||(this[he]=D?.value??null)}this[wt]=m,this[Sl]=L;let G=D?.value,ie=m;if(this[El]=0,D?.version>=L)if(E){let ve=D.localTime,ne=D.version;for(;ie&&(ve>L||ne>=L&&ve>0);){let fe=u.get(ve),X=Lt(fe);if(ne=X.version,ne>L){if(X.type==="patch"){let le=X.getValue(i);ie=bE(ie,le)}else if(X.type==="put"||X.type==="delete")return}else if(ne===L)return;ve=X.previousLocalTime}}else{if(A)return;ie=bE(ie,G)}let ae;if(A?ae=ie:(this[he]=G,ae=A?ie:yo(this,ie)),this[he]=ae,ae?.[he])throw new Error("Can not assign a record to a record, check for circular references");let re;A||(re=m),Il(w,G,ae);let ce=A?"put":"patch";S(w,ae,D,L,0,E,b,b.expiresAt||(d?d+Date.now():0),ce,!1,re)}};y.addWrite(P)}async delete(m){if(typeof m=="string")return this.deleteProperty(m);if(this[hn]){for await(let A of this.search(m))(await We.getResource(A[t],this.getContext(),{ensureLoaded:!1}))._writeDelete(m);return}return this[he]?this._writeDelete(m):!1}_writeDelete(m){let A=gr(this[ye]),I=this[Ue];za(I);let b=this[ye];return A.addWrite({key:I,store:i,resource:this,nodeName:b?.nodeName,before:xe.delete?.bind(this,b,I),beforeIntermediate:de.delete?.bind(this,b,I),commit:(y,w,N)=>{let P=w?.value;N&&(b&&w?.version>(b.lastModified||0)&&(b.lastModified=w.version),PE(this,w)),!(w?.version>y)&&(Il(this[Ue],P),ze.trace("Write delete entry",I,y),E||h?(S(I,null,this[Kr],y,0,E,this[ye],0,"delete"),E||JE()):i.remove(this[Ue]))}}),!0}search(m){let A=this[ye],I=gr(A);if(!m)throw new Error("No query provided");let b=m.conditions;b?b.length===void 0&&(b=b[Symbol.iterator]?Array.from(b):[b]):b=Array.isArray(m)?m:m[Symbol.iterator]?Array.from(m):[],this[Ue]&&(b=[{attribute:null,comparator:"prefix",value:this[Ue]}].concat(b));let y,w={};function N(X,le){let Tt;switch(le){case"and":case void 0:if(X.length<1)throw new Error('An "and" operator requires at least one condition');Tt=!0;break;case"or":if(X.length<2)throw new Error('An "or" operator requires at least two conditions');break;default:throw new Error("Invalid operator "+le)}let Hn=Tt&&{},xn;for(let Qe of X){if(Qe.conditions){Qe.conditions=N(Qe.conditions,Qe.operator);continue}let Rr=Qe[0]??Qe.attribute,Jr=Rr==null?B:vs(p,Rr);if(Jr){if(Tt){let Ar=Mn(Rr),qn=Hn[Ar];qn?(qn.push(Qe),xn=!0):Hn[Ar]=[Qe]}(Jr.type||hg[Qe.comparator])&&(Qe[1]===void 0?Qe.value=L(Qe.value,Jr):Qe[1]=L(Qe[1],Jr))}else if(Rr!=null)throw(0,mn.handleHDBError)(new Error,`${Rr} is not a defined attribute`,404)}if(m.enforceExecutionOrder)return X;if(xn)for(let Qe in Hn){let Rr=Hn[Qe],Jr=Rr.length;if(Jr>1)for(let Ar=0;Ar<Jr;Ar++){let qn=Rr[Ar];if(qn.comparator==="ge"||qn.comparator==="greater_than_equal")for(let $s=0;$s<Jr;$s++){let Lo=Rr[$s];(Lo.comparator==="le"||Lo.comparator==="less_than_equal")&&(qn.comparator="between",qn.value=[qn.value,Lo.value],X.splice(X.indexOf(Lo),1))}if(qn.comparator==="equals"||!qn.comparator){for(let $s=0;$s<Jr;$s++)if($s!==Ar){let Lo=Rr[$s];X.splice(X.indexOf(Lo),1)}break}}}return X}a(N,"prepareConditions");function P(X,le){if(m.enforceExecutionOrder)return X;for(let Tt of X)Tt.conditions&&(Tt.conditions=P(Tt.conditions,Tt.operator));return X.length>1&&le!=="or"?(0,yx.sortBy)(X,Sf(We)):X}a(P,"orderConditions");function L(X,le){return Array.isArray(X)?X.map(Tt=>UE(Tt,le)):UE(X,le)}a(L,"coerceTypedValues");let D=m.operator;(b.length>0||D)&&(b=N(b,D));let q=typeof m.sort=="object"&&m.sort,G;if(q&&D!=="or"){let X=q.attribute;if(y=b.find(le=>Mn(le.attribute)===Mn(X)),!y){if(!vs(p,X))throw(0,mn.handleHDBError)(new Error,`${Array.isArray(X)?X.join("."):X} is not a defined attribute`,404);y={attribute:X,comparator:"sort"},b.push(y)}y.descending=!!q.descending}b=P(b,D),q&&(b[0]===y?q.next&&(G={dbOrderedAttribute:q.attribute,attribute:q.next.attribute,descending:q.next.descending,next:q.next.next}):(y&&b.splice(b.indexOf(y),1),G=q));let ie=m.select;if(b.length===0&&(b=[{attribute:t,comparator:"greater_than",value:!0}]),m.explain)return{conditions:b,operator:D,postOrdering:G,selectApplied:!!ie};let ae=I.useReadTxn(),re=mg(b,D,We,ae,m,A,(X,le)=>OA(X,ie,A,le),w),ce=m.ensureLoaded!==!1;G||(re=fe(re));let ve=We.transformEntryForSelect(ie,A,w,ce,!0),ne=We.transformToOrderedSelect(re,ie,G,A,ve);function fe(X){return m.offset||m.limit!==void 0?X.slice(m.offset,m.limit!==void 0?(m.offset||0)+m.limit:void 0):X}return a(fe,"applyOffset"),G&&(ne=fe(ne)),ne.onDone=()=>{ne.onDone=null,I.doneReadTxn()},ne.selectApplied=!0,ne.getColumns=()=>{if(ie){let X=[];for(let le of ie)le==="*"?X.push(...p.map(Tt=>Tt.name)):X.push(le.name||le);return X}return p.map(X=>X.name)},ne}static transformToOrderedSelect(m,A,I,b,y){let w=new zx;if(I){m=OA(m,A,b,null);let N;w.iterate=function(){let L,D=m[Symbol.asyncIterator]?m[Symbol.asyncIterator]():m[Symbol.iterator](),q,G=I.dbOrderedAttribute,ie,ae,re=!0;function ce(ne){let fe=ne.next&&ce(ne.next),X=ne.descending;return(le,Tt)=>{let Hn=zE(le,ne.attribute,b),xn=zE(Tt,ne.attribute,b),Qe=X?(0,Io.compareKeys)(xn,Hn):(0,Io.compareKeys)(Hn,xn);return Qe===0?fe?.(le,Tt)||0:Qe}}a(ce,"createComparator");let ve=ce(I);return{async next(){let ne;if(L)if(ne=L.next(),ne.done){if(q)return w.onDone&&w.onDone(),ne}else return{value:await y(ne.value)};N=[],ie&&N.push(ie);do if(ne=await D.next(),ne.done){if(q=!0,N.length)break;return w.onDone&&w.onDone(),ne}else{let fe=ne.value;if(fe?.then&&(fe=await fe),G){let X=zE(fe,G,b);if(re)re=!1,ae=X;else if(X!==ae){ae=X,ie=fe;break}}N.push(fe)}while(!0);return I.isGrouped,N.sort(ve),L=N[Symbol.iterator](),ne=L.next(),ne.done?(w.onDone&&w.onDone(),ne):{value:await y(ne.value)}},return(){w.onDone&&w.onDone(),D.return()},throw(){w.onDone&&w.onDone(),D.throw()}}};let P=a(L=>{if(typeof A=="object"&&Array.isArray(L.attribute))for(let D=0;D<A.length;D++){let q=A[D],G;if(q.name===L.attribute[0]){for(G=q.sort||(q.sort={});G.next;)G=G.next;G.attribute=L.attribute.slice(1),G.descending=L.descending}else q===L.attribute[0]&&(A[D]=G={name:q,sort:{attribute:L.attribute.slice(1),descending:L.descending}})}L.next&&P(L.next)},"applySortingOnSelect");P(I)}else w.iterate=(m[Symbol.asyncIterator]||m[Symbol.iterator]).bind(m),w=w.map(y);return w}static transformEntryForSelect(m,A,I,b,y){if(m&&(m===t||m?.length===1&&m[0]===t)){let L=a(D=>D?.key??D,"transform");return m===t?L:m.asArray?D=>[L(D)]:D=>({[t]:L(D)})}let w;b&&R&&!m?.every(L=>{let D;return typeof L=="object"?D=L.name:D=L,r[D]||D===t})&&(w=!0);let N,P=a(L=>{let D;if(L!=null){if(KE=L,D=L.value||L.deref?.(),!D&&(L.key===void 0||L.deref)){if(L=WE(L.key??L,A,{transaction:gr(A).getReadTxn(),lazy:m?.length<4},!1,q=>q),L?.then)return L.then(P);D=L?.value}if(w&&(L.metadataFlags&(hl|ml)||L.expiresAt&&L.expiresAt<Date.now())){let q=QE(L.key??L,L,A);if(q?.then)return q.then(P)}}if(D==null)return y?No.SKIP:D;if(m&&!(m[0]==="*"&&m.length===1)){let q,G=a((ae,re)=>{let ce;typeof ae=="object"?ce=ae.name:ce=ae;let ve=Vs?.[ce],ne;if(ve){let fe=I?.[ce];if(fe)if(fe.hasMappings){let le=ve.from?D[ve.from]:Mn(L.key);ne=fe.get(le),ne||(ne=[])}else ne=fe.fromRecord?.(D);else ne=ve(D,A,L);let X=a(le=>{if(le&&typeof le=="object"){let Tt=ve.definition?.tableClass||We;N||(N={});let Hn=N[ce]||(N[ce]=Tt.transformEntryForSelect(ce===ae?null:ae.select||(Array.isArray(ae)?ae:null),A,fe,b));if(Array.isArray(le)){let xn=[],Qe=Tt.transformToOrderedSelect(le,ae.select,typeof ae.sort=="object"&&ae.sort,A,Hn)[Symbol.asyncIterator](),Rr=a(Ar=>{for(;!Ar.done;){if(Ar?.then)return Ar.then(Rr);xn.push(Ar.value),Ar=Qe.next()}re(xn,ce)},"nextValue"),Jr=Rr(Qe.next());Jr&&(q||(q=[]),q.push(Jr));return}else if(le=Hn(le),le?.then){q||(q=[]),q.push(le.then(xn=>re(xn,ce)));return}}re(le,ce)},"handleResolvedValue");ne?.then?(q||(q=[]),q.push(ne.then(X))):X(ne);return}else ne=D[ce],ne&&typeof ne=="object"&&ce!==ae&&(ne=this.transformEntryForSelect(ae.select||ae,A,null)({value:ne}));re(ne,ce)},"selectAttribute"),ie;if(typeof m=="string")G(m,ae=>{ie=ae});else if(Array.isArray(m))if(m.asArray)ie=[],m.forEach((ae,re)=>{ae==="*"?m[re]=D:G(ae,ce=>ie[re]=ce)});else{ie={};let ae=m.forceNulls;for(let re of m)if(re==="*")for(let ce in D)ie[ce]=D[ce];else G(re,(ce,ve)=>{ce===void 0&&ae&&(ce=null),ie[ve]=ce})}else throw new mn.ClientError("Invalid select"+m);return q?Promise.all(q).then(()=>ie):ie}return D},"transform");return P}async subscribe(m){if(!u)throw new Error("Can not subscribe to a table without an audit log");E||ot({table:s,database:c,schemaDefined:_,attributes:p,audit:!0}),m||(m={});let A=!m.rawEvents,I=hx(We,this[Ue]??null,function(N,P,L,D){try{let q=P.getValue?.(i,A);if(!q&&P.type==="patch"&&A){let G=i.getEntry(N);G?.version===P.version?q=G.value:q=P.getValue?.(i,!0,L),P.type="put"}this.send({id:N,timestamp:L,value:q,version:P.version,type:P.type,beginTxn:D})}catch(q){ze.error(q)}},m.startTime||0,this[hn]);this[hn]&&(I.includeDescendants=!0,m.onlyChildren&&(I.onlyChildren=!0)),m.crossThreads===!1&&(I.crossThreads=!1),m.supportsTransactions&&(I.supportsTransactions=!0);let b=this[Ue],y=m.previousCount;y>1e3&&(y=1e3);let w=m.startTime;if(this[hn]){if(w){if(y)throw new mn.ClientError("startTime and previousCount can not be combined for a table level subscription");for(let{key:N,value:P}of u.getRange({start:w,exclusiveStart:!0})){let L=Lt(P);if(L.tableId!==n)continue;let D=L.recordId;(b==null||Ox(b,D))&&I.send({id:D,timestamp:N,...L}),I.startTime=N}}else if(y){let N=[];for(let{key:P,value:L}of u.getRange({start:"z",end:!1,reverse:!0}))try{let D=Lt(L);if(D.tableId!==n)continue;let q=D.recordId;if(b==null||Ox(b,q)){let G=D.getValue(i,A,P);if(N.push({id:q,timestamp:P,value:G,version:D.version,type:D.type}),--y<=0)break}}catch(D){ze.error("Error getting history entry",P,D)}for(let P=N.length;P>0;)I.send(N[--P]);N[0]&&(I.startTime=N[0].timestamp)}else if(!m.omitCurrent)for(let{key:N,value:P,version:L,localTime:D}of i.getRange({start:b??!1,end:b==null?void 0:[b,Io.MAXIMUM_KEY],versions:!0}))P&&I.send({id:N,version:L,timestamp:D,value:P})}else{y&&!w&&(w=0);let N=this[Kr]?.localTime;if(N===Kh&&(i.cache?.delete(b),this[Kr]=i.getEntry(b),ze.trace("re-retrieved record",N,this[Kr]?.localTime),N=this[Kr]?.localTime),ze.trace("Subscription from",w,"from",b,N),w<N){let P=[],L=N;do{let D=u.get(L);if(D){m.omitCurrent=!0;let q=Lt(D),G=q.getValue(i,A,L);A&&(q.type="put"),P.push({id:b,value:G,timestamp:L,...q}),L=q.previousLocalTime}else break;y&&y--}while(L>w&&y!==0);for(let D=P.length;D>0;)I.send(P[--D]);I.startTime=N}!m.omitCurrent&&this.doesExist()&&I.send({id:b,version:this[Sl],timestamp:N,value:this})}return m.listener&&I.on("data",m.listener),I}doesExist(){return!!(this[he]||this[El])}publish(m,A){this._writePublish(m,A)}_writePublish(m,A){let I=gr(this[ye]),b=this[Ue]||null;za(b);let y=this[ye];I.addWrite({key:b,store:i,entry:this[Kr],nodeName:y?.nodeName,validate:()=>{this.validate(m)},before:xe.publish?.bind(this,y,b,m),beforeIntermediate:de.publish?.bind(this,y,b,m),commit:(w,N,P)=>{N===void 0&&h&&!E&&JE(),S(b,N?.value??null,N,N?.version||w,0,!0,y,N?.expiresAt,"message",!1,m)}})}validate(m,A){let I,b=a((y,w,N)=>{if(w.type&&y!=null)if(A&&y.__op__&&(y=y.value),w.properties){typeof y!="object"&&(I||(I=[])).push(`Property ${N} must be an object${w.type?" ("+w.type+")":""}`);let P=w.properties;for(let L=0,D=P.length;L<D;L++){let q=P[L],G=b(y[q.name],q,N+"."+q.name);G&&(y[q.name]=G)}}else switch(w.type){case"Int":(typeof y!="number"||y>>0!==y)&&(I||(I=[])).push(`Property ${N} must be an integer (from -2147483648 to 2147483647)`);break;case"Long":(typeof y!="number"||!(Math.floor(y)===y&&Math.abs(y)<=9007199254740992))&&(I||(I=[])).push(`Property ${N} must be an integer (from -9007199254740992 to 9007199254740992)`);break;case"Float":typeof y!="number"&&(I||(I=[])).push(`Property ${N} must be a number`);break;case"ID":typeof y=="string"||y?.length>0&&y.every?.(P=>typeof P=="string")||(I||(I=[])).push(`Property ${N} must be a string, or an array of strings`);break;case"String":typeof y!="string"&&(I||(I=[])).push(`Property ${N} must be a string`);break;case"Boolean":typeof y!="boolean"&&(I||(I=[])).push(`Property ${N} must be a boolean`);break;case"Date":if(!(y instanceof Date)){if(typeof y=="string"||typeof y=="number")return new Date(y);(I||(I=[])).push(`Property ${N} must be a Date`)}break;case"BigInt":if(typeof y!="bigint"){if(typeof y=="string"||typeof y=="number")return BigInt(y);(I||(I=[])).push(`Property ${N} must be a bigint`)}break;case"Bytes":y instanceof Uint8Array||(I||(I=[])).push(`Property ${N} must be a Buffer or Uint8Array`);break;case"array":if(Array.isArray(y)){if(w.elements)for(let P=0,L=y.length;P<L;P++){let D=y[P],q=b(D,w.elements,N+"[*]");q&&(y[P]=q)}}else(I||(I=[])).push(`Property ${N} must be a Buffer or Uint8Array`);break}w.nullable===!1&&y==null&&(I||(I=[])).push(`Property ${N} is required (and not does not allow null values)`)},"validateValue");for(let y=0,w=p.length;y<w;y++){let N=p[y];if(!N.relationship&&(!A||N.name in m)){let P=b(m[N.name],N,N.name);P&&(m[N.name]=P)}}if(I)throw new mn.ClientError(I.join(". "))}getUpdatedTime(){return this[Sl]}wasLoadedFromSource(){return R?!!this[_A]:void 0}static async addAttributes(m){let A=p.slice(0);for(let I of m){if(!I.name)throw new mn.ClientError("Attribute name is required");if(I.name.match(/[`/]/))throw new mn.ClientError("Attribute names cannot include backticks or forward slashes");A.push(I)}return ot({table:s,database:c,schemaDefined:_,attributes:A}),We.indexingOperation}static async removeAttributes(m){let A=p.filter(I=>!m.includes(I.name));return ot({table:s,database:c,schemaDefined:_,attributes:A}),We.indexingOperation}static getRecordCount(m){let A=i.getStats().entryCount,I=5e3,b=1e3,y;A>I&&!m?.exactCount&&(y=b);let w=0;for(let{value:N}of i.getRange({start:!0,lazy:!0,limit:y}))N!=null&&w++;if(y){let N=w;w=0;for(let{value:ce}of i.getRange({start:"\uFFFF",reverse:!0,lazy:!0,limit:y}))ce!=null&&w++;let P=y*2,L=(w+N)/P,D=Math.pow((w-N+1)/y/2,2)+L*(1-L)/P,q=Math.max(Math.sqrt(D)*A,1),G=Math.round(L*A),ie=Math.max(G-1.96*q,0),ae=Math.min(G+1.96*q,A),re=Math.pow(10,Math.round(Math.log10(q)));return re>G&&(re=re/10),w=Math.round(G/re)*re,{recordCount:w,estimatedRange:[Math.round(ie),Math.round(ae)]}}return{recordCount:w}}static updatedAttributes(){Vs=this.propertyResolvers={$id:(m,A,I)=>({value:I.key}),$updatedtime:(m,A,I)=>I.version,$record:(m,A,I)=>I?{value:m}:m};for(let m of this.attributes){m.resolve=null;let A=m.relationship;if(A)if(m.indexed&&console.error("A relationship property can not be directly indexed, (but you may want to index the foreign key attribute)"),AA=!0,A.to)m.elements?.definition?(Vs[m.name]=m.resolve=(I,b,y)=>{let w=I[A.from?A.from:t],N=m.elements.definition.tableClass;return y?Na({attribute:A.to,value:w},gr(b).getReadTxn(),!1,N).asArray:N.search([{attribute:A.to,value:w}],b).asArray},m.set=()=>{throw new Error("Setting a one-to-many relationship property is not supported")},m.resolve.definition=m.elements.definition,A.from&&(m.resolve.from=A.from)):console.error(`The one-to-many/many-to-many relationship property "${m.name}" in table "${s}" must have an array type referencing a table as the elements`);else if(A.from){let I=m.definition||m.elements?.definition;I?(Vs[m.name]=m.resolve=(b,y,w)=>{let N=b[A.from];if(N!==void 0){if(m.elements){let P,L=N.map(D=>{let q=w?I.tableClass.primaryStore.getEntry(D,{transaction:gr(y).getReadTxn()}):I.tableClass.get(D,y);return q?.then&&(P=!0),q});return A.filterMissing?P?Promise.all(L).then(D=>D.filter(bx)):L.filter(bx):P?Promise.all(L):L}return w?I.tableClass.primaryStore.getEntry(N,{transaction:gr(y).getReadTxn()}):I.tableClass.get(N,y)}},m.set=(b,y)=>{if(Array.isArray(y)){let w=y.map(N=>N[Ue]||N[I.tableClass.primaryKey]);b[A.from]=w}else{let w=y[Ue]||y[I.tableClass.primaryKey];b[A.from]=w}},m.resolve.definition=m.definition||m.elements?.definition,m.resolve.from=A.from):console.error(`The relationship property "${m.name}" in table "${s}" must be a type that references a table`)}else console.error(`The relationship directive on "${m.name}" in table "${s}" must use either "from" or "to" arguments`)}CE(this,this)}static async deleteHistory(m=0){let A;for(let{key:I,value:b}of u.getRange({start:0,end:m}))await pl(),Lt(b).tableId===n&&(A=u.remove(I));await A}static async*getHistory(m=0,A=1/0){for(let{key:I,value:b}of u.getRange({start:m,end:A})){await pl();let y=Lt(b);y.tableId===n&&(yield{id:y.recordId,localTime:I,version:y.version,type:y.type,value:y.getValue(i,!0,I),user:y.user})}}static async getHistoryOfRecord(m){let A=[];if(m==null)throw new Error("An id is required");let I=i.getEntry(m);if(!I)return A;let b=I.localTime;if(!b)throw new Error("The entry does not have a local audit time");let y=0;do{await pl();let w=u.get(b);if(w){let N=Lt(w);A.push({id:N.recordId,localTime:b,version:N.version,type:N.type,value:N.getValue(i,!0,b),user:N.user}),b=N.previousLocalTime}else break}while(y<1e3&&b);return A.reverse()}static cleanup(){W?.remove()}}We.updatedAttributes();let Xx=We.prototype;return Xx[bse]=!0,d&&We.setTTLExpiration(d/1e3),$&&Zx(),We;function Il(Y,m,A){let I;for(let b in r){let y=r[b],w=y.isIndexing,N=A?.[b],P=m?.[b];if(N===P&&!w)continue;I=!0;let L=y.indexNulls,D=(0,Tl.getIndexedValues)(P,L);if(D){Tx&&y.prefetch(D.map(q=>({key:q,value:Y})),Ax);for(let q=0,G=D.length;q<G;q++)y.remove(D[q],Y)}if(D=(0,Tl.getIndexedValues)(N,L),D){Tx&&y.prefetch(D.map(q=>({key:q,value:Y})),Ax);for(let q=0,G=D.length;q<G;q++)y.put(D[q],Y)}}return I}a(Il,"updateIndices");function za(Y){switch(typeof Y){case"number":return!0;case"string":if(Y.length<659)return!0;if(Y.length>Rx)throw new Error("Primary key size is too large: "+Y.length);break;case"object":if(Y===null)return!0;break;case"bigint":if(Y<2n**64n&&Y>-(2n**64n))return!0;break;default:throw new Error("Invalid primary key type: "+typeof Y)}if((0,Io.writeKey)(Y,Nse,0)>Rx)throw new Error("Primary key size is too large: "+Y.length);return!0}a(za,"checkValidId");function WE(Y,m,A,I,b){let y=a(()=>{if(m?.transaction?.stale&&(m.transaction.stale=!1),A.transaction?.isDone)return b(null,Y);let w=i.getEntry(Y,A);return w&&m&&(w?.version>(m.lastModified||0)&&(m.lastModified=w.version),w?.localTime&&!m.lastRefreshed&&(m.lastRefreshed=w.localTime)),b(w,Y)},"whenPrefetched");return I?y():Te>0?(Te--,y()):new Promise((w,N)=>{Te===0?(Te--,i.prefetch([Y],()=>{P(),L()})):(z.push(Y),se.push(L),z.length>jx&&(Te--,P()));function P(){if(z.length>0){let D=se;i.prefetch(z,()=>{Te===-1?P():Te++;for(let q of D)q()}),z=[],se=[],oe>2&&oe--}else Te=oe,oe<Jx&&oe++}a(P,"prefetch");function L(){try{w(y())}catch(D){N(D)}}a(L,"load")})}a(WE,"loadLocalRecord");function Cl(Y){if(!Y?.role)return;let m=Y.role.permission;if(m.super_user)return wse;let A=m[c],I,b=A?.tables;if(b)return b[s];if(c==="data"&&(I=m[s])&&!I.tables)return I}a(Cl,"getTablePermissions");function QE(Y,m,A,I){if(R){let b;if(A.noCache?b=!0:(m?(!m.value||m.metadataFlags&(hl|ml)||m.expiresAt&&m.expiresAt<Date.now())&&(b=!0):b=!0,tn(!b,"cache-hit",s)),b){let y=bA(Y,m,A).then(w=>(w?.value?.[he]&&ze.error("Can not assign a record with a record property"),A&&(w?.version>(A.lastModified||0)&&(A.lastModified=w.version),A.lastRefreshed=Date.now()),w));if(A?.onlyIfCached||m?.value&&I?.allowStaleWhileRevalidate?.(m,Y)){if(y.catch(w=>ze.warn(w)),A?.onlyIfCached&&!I.doesExist())throw new mn.ServerError("Entry is not cached",504);return}else return y}}}a(QE,"ensureLoadedFromSource");function gr(Y){let m=Y?.transaction;if(m){if(!m.lmdbDb)return m.lmdbDb=i,m;do{if(m.lmdbDb?.path===i.path)return m;let A=m.next;if(!A)return m=m.next=new Qi,m.lmdbDb=i,m;m=A}while(!0)}else return new k_}a(gr,"txnForContext");function zE(Y,m,A){if(!Y)return;KE=Y;let I=Y.value||Y.deref?.()||(KE=i.getEntry(Y.key))?.value;if(typeof m=="object"){let y=Vs,w=I;for(let N=0,P=m.length;N<P;N++){let L=m[N],D=y?.[L];w=D&&w?D(w,A,!0)?.value:w?.[L],y=D?.definition?.tableClass?.propertyResolvers}return w}let b=Vs[m];return b?b(I,A):I[m]}a(zE,"getAttributeValue");function OA(Y,m,A,I){let b=gr(A).getReadTxn(),y=I?.length,w={transaction:b,lazy:y>0||typeof m=="string"||m?.length<4,alwaysPrefetch:!0},N;function P(L,D){let q=L?.value;if(!q)return No.SKIP;for(let G=0;G<y;G++)if(!N?.includes(G)&&!I[G](q,L))return No.SKIP;return D!==void 0&&(L.key=D),L}if(a(P,"processEntry"),y>0||!Y.hasEntries){let L=Y.map(D=>{if(N=null,typeof D=="object"&&D.key!==void 0)return y>0?P(D):D;if(D==null)return No.SKIP;for(let q=0;q<y;q++){let ie=I[q].idFilter;if(ie){if(!ie(D))return No.SKIP;N||(N=[]),N.push(q)}}return WE(D,A,w,!1,P)});return Array.isArray(Y)&&(L=L.filter(D=>D!==No.SKIP)),L.hasEntries=!0,L}return Y}a(OA,"transformToEntries");async function bA(Y,m,A){let I=m?.metadataFlags,b=m?.version,y,w;if(!i.attemptLock(Y,b,()=>{clearTimeout(w);let D=i.getEntry(Y);!D||!D.value||D.metadataFlags&(hl|ml)?y(bA(Y,i.getEntry(Y),A)):y(D)}))return new Promise(D=>{y=D,w=setTimeout(()=>{i.unlock(Y,b)},Ose)});let N=m?.value,P={requestContext:A,replacingRecord:N,replacingVersion:b,source:null,resourceCache:A?.resourceCache},L=A?.responseHeaders;return new Promise((D,q)=>{let G;fA(Ke(P,async ie=>{let ae=performance.now(),re,ce,ve;try{for(let le of We.sources)if(le.get&&(!le.get.reliesOnPrototype||le.prototype.get)&&(P.source=le,re=await le.get(Y,P),re))break;ve=I&hl;let fe=P.lastModified||ve&&b;ce=ve||fe>b||!N,fe||(fe=(0,Tl.getNextMonotonicTime)());let X=performance.now()-ae;if(Hr(X,"cache-resolution",s),L&&L.append("Server-Timing",`cache-resolve;dur=${X.toFixed(2)}`),ie.timestamp=fe,d&&!P.expiresAt&&(P.expiresAt=Date.now()+d),re){if(typeof re!="object")throw new Error("Only objects can be cached and stored in tables");typeof re.toJSON=="function"&&(re=re.toJSON()),t&&re[t]!==Y&&(re[t]=Y)}G=!0,D({version:fe,value:re})}catch(fe){fe.message+=` while resolving record ${Y} for ${s}`,N&&((fe.code==="ECONNRESET"||fe.code==="ECONNREFUSED"||fe.code==="EAI_AGAIN")&&!A?.mustRevalidate||A?.staleIfError&&(fe.statusCode===500||fe.statusCode===502||fe.statusCode===503||fe.statusCode===504))?(D({version:b,value:N}),ze.trace(fe.message,"(returned stale record)")):q(fe),P.transaction.abort();return}if(A?.noCacheStore){P.transaction.abort();return}gr(P).addWrite({key:Y,store:i,entry:m,nodeName:"source",commit:(fe,X)=>{if(X?.version!==b)return;let le=Il(Y,N,re);re?(de.put?.(P,Y,re),S(Y,re,X,fe,0,E&&ce||null,P,P.expiresAt,"put",!!ve)):(de.delete?.(P,Y),E||h?S(Y,null,X,fe,0,E&&ce||null,P,0,"delete",!!ve):i.remove(Y,b))}})}),()=>{i.unlock(Y,b)},ie=>{i.unlock(Y,b),G&&ze.error("Error committing cache update",ie)})})}a(bA,"getFromSource");function JE(){if(It!==Nl&&(Nl=It,(0,wo.getWorkerIndex)()===(0,wo.getWorkerCount)()-1)){if(wl&&clearTimeout(wl),!It)return;let Y=new Date;Y.setMonth(0),Y.setDate(1),Y.setHours(0),Y.setMinutes(0),Y.setSeconds(0);let m=Math.ceil((Date.now()-Y.getTime())/It)*It+Y.getTime(),A=a(I=>{ze.trace(`Scheduled next cleanup scan at ${new Date(I)}ms`),wl=setTimeout(()=>H=H.then(async()=>{if(A(Math.max(I+It,Date.now())),i.rootStore.status!=="open"){clearTimeout(wl);return}let b=50,y=new Array(b),w=0;ze.trace(`Starting cleanup scan for ${s}`);try{let N=0;for(let{key:P,value:L,version:D,expiresAt:q}of i.getRange({start:!1,snapshot:!1,versions:!0,lazy:!0})){let G;L===null&&!E&&D+Ase<Date.now()?G=i.remove(P,D):q&&q+f<Date.now()&&(G=We.evict(P,L,D),N++),G&&(await y[w],y[w]=G.catch(ie=>{ze.error("Cleanup error",ie)}),++w>=b&&(w=0)),await pl()}ze.trace(`Finished cleanup scan for ${s}, evicted ${N} entries`)}catch(N){ze.trace(`Error in cleanup scan for ${s}:`,N)}}),Math.min(I-Date.now(),2147483647)).unref()},"startNextTimer");A(m)}}a(JE,"scheduleCleanup");function yA(){W=u?.addDeleteRemovalCallback(n,Y=>{let m=i.getEntry(Y);m?.value===null&&i.remove(Y,m.version)})}a(yA,"addDeleteRemoval");function Zx(){(0,wo.getWorkerIndex)()===0&&setInterval(async()=>{try{let Y=$.name,m=r[Y];if(!m)throw new Error(`expiresAt attribute ${$} must be indexed`);for(let{value:A}of m.getRange({start:!0,end:Date.now(),versions:!0,snapshot:!1})){let I=i.getEntry(A);I?.value?.[Y]<Date.now()&&We.evict(A,I.value,I.version),await pl()}}catch(Y){ze.error("Error in evicting old records",Y)}},Rse).unref()}a(Zx,"runRecordExpirationEviction")}function dA(e,t){let r=e.attr_object||(e.attr_object={}),n=r[t];if(n)return n;n=r[t]=Object.create(null);for(let s of e)n[s.attribute_name]=s[t];return n}function Ax(){}function Ise(e){Nx=e}function UE(e,t){let r=t?.type;return e===null?e:e===""&&r&&r!=="String"&&r!=="Any"?null:r==="Int"||r==="Long"?e==="null"?null:parseInt(e):r==="Float"?e==="null"?null:parseFloat(e):r==="BigInt"?e==="null"?null:BigInt(e):r==="Boolean"?e==="true"?!0:e==="false"?!1:e:r==="Date"?(typeof e!="number"&&!Cse.test(e)&&(e+="Z"),e==="null"?null:new Date(e)):!r||r==="Any"?(0,vE.autoCast)(e):e}function Ox(e,t){if(e==null)return!0;if(!Array.isArray(t))return e===t;if(Array.isArray(e)){let r=e.length;if(e[r-1]===null&&r--,t.length>=r){for(let n=0;n<r;n++)if(t[n]!==e[n])return!1;return!0}return!1}else if(t[0]===e)return!0}function fA(e,t,r){return e?.then?e.then(t,r):t(e)}function PE(e,t){e[Kr]=t,e[he]=t?.value??null,e[Sl]=t?.version}function bx(e){return e!=null}var Bn,No,Tl,yx,Al,mn,gl,Rl,ze,Io,wo,vE,gse,Nx,Rse,Ase,Tx,Ose,Sl,bse,Kr,El,gx,yse,_A,Ya,hl,ml,Nse,Rx,wse,Zme,Cse,pl,Pf=Oe(()=>{Bn=x(U()),No=require("lmdb"),Tl=x(Cr()),yx=require("lodash");An();Bp();Al=x(Z());Sx();mn=x(ee()),gl=x(Ts()),Rl=x(Nn());be();gf();ze=x(K());Y_();zi();Io=require("ordered-binary"),wo=x(Ze());Ui();vE=x(J());Ho();Os();AE();gse=new Uint8Array(9);gse[8]=192;Rse=6e4,Ase=864e5;Al.initSync();Tx=Al.get(Bn.CONFIG_PARAMS.STORAGE_PREFETCHWRITES),Ose=1e4,Sl=Symbol.for("version"),bse=Symbol.for("incremental-update"),Kr=Symbol("entry"),El=Symbol("is-saving"),gx=1,yse=2,_A=Symbol("loaded-from-source"),Ya={isNotification:!0,ensureLoaded:!1},hl=1,ml=8,Nse=Buffer.allocUnsafeSlow(8192),Rx=1978,wse={read:!0,insert:!0,update:!0,delete:!0,isSuperUser:!0},Zme=(0,vE.convertToMS)(Al.get(Bn.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE))||864e5;a(BE,"makeTable");a(dA,"attributesAsObject");a(Ax,"noop");a(Ise,"setServerUtilities");Cse=/[+-][0-9]{2}:[0-9]{2}|[a-zA-Z]$/;a(UE,"coerceType");a(Ox,"isDescendantId");pl=a(()=>new Promise(setImmediate),"rest");a(fA,"when");a(PE,"updateResource");a(bx,"exists")});var qe={};ke(qe,{database:()=>Qc,databases:()=>et,dropDatabase:()=>Gp,dropTableMeta:()=>vse,getDatabases:()=>In,getTables:()=>Dse,onUpdatedTable:()=>yR,readMetaDb:()=>Ol,resetDatabases:()=>Lse,table:()=>ot,tables:()=>Dr});function Dse(){return GE||In(),Dr||{}}function In(){if(GE)return et;GE=!0,Qa=new Map;let e=(0,Qt.getHdbBasePath)()&&(0,Je.join)((0,Qt.getHdbBasePath)(),Qr.DATABASES_DIR_NAME),t=(0,Qt.get)(Qr.CONFIG_PARAMS.DATABASES)||{};if(process.env.SCHEMAS_DATA_PATH&&(t.data={path:process.env.SCHEMAS_DATA_PATH}),e=process.env.STORAGE_PATH||(0,Qt.get)(Qr.CONFIG_PARAMS.STORAGE_PATH)||e&&((0,Wr.existsSync)(e)?e:(0,Je.join)((0,Qt.getHdbBasePath)(),Qr.LEGACY_DATABASES_DIR_NAME)),!!e){if((0,Wr.existsSync)(e))for(let r of(0,Wr.readdirSync)(e,{withFileTypes:!0})){let n=(0,Je.basename)(r.name,".mdb");r.isFile()&&(0,Je.extname)(r.name).toLowerCase()===".mdb"&&!t[n]?.path&&Ol((0,Je.join)(e,r.name),null,n)}if((0,Wr.existsSync)((0,Wa.getBaseSchemaPath)())){for(let r of(0,Wr.readdirSync)((0,Wa.getBaseSchemaPath)(),{withFileTypes:!0}))if(!r.isFile()){let n=(0,Je.join)((0,Wa.getBaseSchemaPath)(),r.name),s=(0,Je.join)((0,Wa.getTransactionAuditStoreBasePath)(),r.name);for(let i of(0,Wr.readdirSync)(n,{withFileTypes:!0}))if(i.isFile()&&(0,Je.extname)(i.name).toLowerCase()===".mdb"){let o=(0,Je.join)(s,i.name);Ol((0,Je.join)(n,i.name),(0,Je.basename)(i.name,".mdb"),r.name,o,!0)}}}if(t)for(let r in t){let n=t[r],s=n.path;if((0,Wr.existsSync)(s))for(let o of(0,Wr.readdirSync)(s,{withFileTypes:!0}))o.isFile()&&(0,Je.extname)(o.name).toLowerCase()===".mdb"&&Ol((0,Je.join)(s,o.name),(0,Je.basename)(o.name,".mdb"),r);let i=n.tables;if(i)for(let o in i){let c=i[o],u=(0,Je.join)(c.path,(0,Je.basename)(o+".mdb"));(0,Wr.existsSync)(u)&&Ol(u,o,r,null,!0)}}for(let r in et){let n=Qa.get(r);if(n){let s=et[r];r.includes("delete")&&pn.trace(`defined tables ${Array.from(n.keys())}`);for(let i in s)n.has(i)||(pn.trace(`delete table class ${i}`),delete s[i])}else if(delete et[r],r==="data"){for(let s in Dr)delete Dr[s];delete Dr[kE]}}return Qa=null,et}}function Lse(){GE=!1;for(let[,e]of Oi)e.needsDeletion=!0;In();for(let[e,t]of Oi)t.needsDeletion&&!e.endsWith("system.mdb")&&(t.close(),Oi.delete(e));return et}function Ol(e,t,r=mA,n,s){let i=new EA.default(e,!1);try{let o=Oi.get(e);o?o.needsDeletion=!1:(o=(0,xE.open)(i),Oi.set(e,o));let c=new Co.default(!1),u=o.dbisDb||(o.dbisDb=o.openDB(HE.INTERNAL_DBIS_NAME,c)),_=o.auditStore;_||(n?(0,Wr.existsSync)(n)&&(i.path=n,_=(0,xE.open)(i),_.isLegacy=!0):_=RE(o));let l=Dx(r),d=l[kE],f=new Map;for(let{key:E,value:h}of u.getRange({start:!1})){let[p,S]=E.toString().split("/");S===""?S=h.name:S||(S=p,p=t,h.name||(h.name=S,h.indexed=!h.is_hash_attribute)),d?.add(p);let O=f.get(p);O||f.set(p,O={attributes:[]}),(S==null||h.is_hash_attribute)&&(O.primary=h),S!=null&&O.attributes.push(h),Object.defineProperty(h,"key",{value:E,configurable:!0})}for(let[E,h]of f){let{attributes:p,primary:S}=h;if(!S){for(let z of p)if(z.is_hash_attribute||z.isPrimaryKey){S=z;break}if(!S){pn.fatal(`Unable to find a primary key attribute on table ${E}, with attributes: ${JSON.stringify(p)}`);continue}}let O=l[E],g={},R=[],B,H,v=typeof S.audit=="boolean"?S.audit:(0,Qt.get)(Qr.CONFIG_PARAMS.LOGGING_AUDITLOG),M=S.trackDeletes,$=S.expiration,W=S.eviction;if(O)g=O.indices,R=O.attributes,O.schemaVersion++;else{B=S.tableId,B?B>=(u.get(Ka)||0)&&u.putSync(Ka,B+1):(S.tableId=B=u.get(Ka),B||(B=1),u.putSync(Ka,B+1),u.putSync(S.key,S));let z=new Co.default(!S.is_hash_attribute,S.is_hash_attribute);H=r_(o.openDB(S.key,z)),H.rootStore=o,H.tableId=B}for(let z of p){z.attribute=z.name;try{if(!z.is_hash_attribute&&(z.indexed||z.attribute&&!z.name)){if(!g[z.name]){let Te=new Co.default(!z.is_hash_attribute,z.is_hash_attribute);g[z.name]=o.openDB(z.key,Te),g[z.name].indexNulls=z.indexNulls}let se=R.find(Te=>Te.name===z.name);se?R.splice(R.indexOf(se),1,z):R.push(z)}}catch(se){pn.error("Error trying to update attribute",z,R,g,se)}}if(!O){O=Lx(l,E,BE({primaryStore:H,auditStore:_,audit:v,expirationMS:$&&$*1e3,evictionMS:W&&W*1e3,trackDeletes:M,tableName:E,tableId:B,primaryKey:S.name,databasePath:s?r+"/"+E:r,databaseName:r,indices:g,attributes:p,schemaDefined:S.schemaDefined,dbisDB:u})),O.schemaVersion=1;for(let z of pA)z(O)}}return o}catch(o){throw o.message+=` opening database ${e}`,o}}function Dx(e){let t=et[e];if(t||(e==="data"?t=et[e]=Dr:e==="system"?Object.defineProperty(et,"system",{value:t=Object.create(null),configurable:!0}):t=et[e]=Object.create(null)),Qa&&!Qa.has(e)){let r=new Set;t[kE]=r,Qa.set(e,r)}return t}function Lx(e,t,r){return e[t]=r,r}function Qc({database:e,table:t}){e||(e=mA),In();let r=Dx(e),n=(0,Je.join)((0,Qt.getHdbBasePath)(),Qr.DATABASES_DIR_NAME),s=(0,Qt.get)(Qr.CONFIG_PARAMS.DATABASES)||{};process.env.SCHEMAS_DATA_PATH&&(s.data={path:process.env.SCHEMAS_DATA_PATH});let i=t&&s[e]?.tables?.[t]?.path;n=i||s[e]?.path||process.env.STORAGE_PATH||(0,Qt.get)(Qr.CONFIG_PARAMS.STORAGE_PATH)||((0,Wr.existsSync)(n)?n:(0,Je.join)((0,Qt.getHdbBasePath)(),Qr.LEGACY_DATABASES_DIR_NAME));let o=(0,Je.join)(n,(i?t:e)+".mdb"),c=Oi.get(o);if(!c){let u=new EA.default(o,!1);c=(0,xE.open)(u),Oi.set(o,c)}return c}async function Gp(e){if(!et[e])throw new Error("Schema does not exist");let t=et[e];for(let r in t){let s=t[r].primaryStore.rootStore;Oi.delete(s.path),s.status==="open"&&(await s.close(),await wx.remove(s.path))}if(e==="data"){for(let r in Dr)delete Dr[r];delete Dr[kE]}delete et[e]}function ot({table:e,database:t,expiration:r,eviction:n,scanInterval:s,attributes:i,audit:o,trackDeletes:c,schemaDefined:u,origin:_}){t||(t=mA);let l=Qc({database:t,table:e}),d=et[t],f=d?.[e];if(l.status==="closed")throw new Error(`Can not use a closed data store for ${e}`);let E,h,p,S;u==null&&(u=!0);let O=new Co.default(!1);for(let M of i)M.attribute?(M.name=M.attribute,M.indexed=!0):M.attribute=M.name,M.expiresAt&&(M.indexed=!0);let g,R;if(f){if(E=f.primaryKey,f.primaryStore.rootStore.status==="closed")throw new Error(`Can not use a closed data store from ${e} class`);f.attributes.splice(0,f.attributes.length,...i)}else{let M=l.auditStore;M||(M=RE(l)),h=i.find(se=>se.isPrimaryKey)||{},E=h.name,h.is_hash_attribute=!0,h.schemaDefined=u,c&&(h.trackDeletes=!0),o=h.audit=typeof o=="boolean"?o:(0,Qt.get)(Qr.CONFIG_PARAMS.LOGGING_AUDITLOG),r&&(h.expiration=r),n&&(h.eviction=n),_&&(h.origins?h.origins.includes(_)||h.origins.push(_):h.origins=[_]),pn.trace(`${e} table loading, opening primary store`);let $=new Co.default(!1,!0),W=e+"/",z=r_(l.openDB(W,$));z.rootStore=l,S=l.dbisDb=l.openDB(HE.INTERNAL_DBIS_NAME,O),z.tableId=S.get(Ka),z.tableId||(z.tableId=1),S.putSync(Ka,z.tableId+1),h.tableId=z.tableId,f=Lx(d,e,BE({primaryStore:z,auditStore:M,audit:o,trackDeletes:c,expirationMS:r&&r*1e3,evictionMS:n&&n*1e3,primaryKey:E,tableName:e,tableId:z.tableId,databasePath:t,databaseName:t,indices:{},attributes:i,schemaDefined:u,dbisDB:S})),f.schemaVersion=1,g=!0,v(),S.put(W,h)}p=f.indices,S=S||(l.dbisDb=l.openDB(HE.INTERNAL_DBIS_NAME,O)),f.dbisDB=S;let B=[];for(let{key:M,value:$}of S.getRange({start:!0})){let[W,z]=M.toString().split("/");if(z===""&&(z=$.name),z){if(W!==e)continue}else z=W;if(!i.find(Te=>Te.name===z)?.indexed&&$.indexed&&!$.isPrimaryKey){v(),g=!0,S.remove(M);let Te=f.indices[W];Te&&B.push(Te)}}let H=[];try{for(let M of i||[]){if(M.relationship)continue;let $=e+"/"+(M.name||"");Object.defineProperty(M,"key",{value:$,configurable:!0});let W=S.get($);if(M.isPrimaryKey){if(W=W||S.get($=e+"/")||{},o!==f.audit||(+r||void 0)!==(+W.expiration||void 0)||(+n||void 0)!==(+W.eviction||void 0)){let se=Object.assign({},W);typeof o=="boolean"&&(o&&f.enableAuditing(o),se.audit=o),r&&(se.expiration=+r),n&&(se.eviction=+n),g=!0,v(),S.put($,se)}continue}W?.attribute&&!W.name&&(W.indexed=!0);let z=!W||W.type!==M.type||W.indexed!==M.indexed||JSON.stringify(W.attributes)!==JSON.stringify(M.attributes)||JSON.stringify(W.elements)!==JSON.stringify(M.elements);if(M.indexed){let se=new Co.default(!0,!1),Te=l.openDB($,se);(z||W.indexingPID&&W.indexingPID!==process.pid||W.restartNumber<bl.workerData?.restartNumber)&&(g=!0,v(),W=S.get($),(z||W.indexingPID&&W.indexingPID!==process.pid||W.restartNumber<bl.workerData?.restartNumber)&&(g=!0,M.lastIndexedKey=W?.lastIndexedKey||!1,M.indexingPID=process.pid,Te.isIndexing=!0,Object.defineProperty(M,"dbi",{value:Te}),M.indexNulls===void 0&&(M.indexNulls=!0),H.push(M)),S.put($,M)),W?.indexNulls&&M.indexNulls===void 0&&(M.indexNulls=!0),Te.indexNulls=M.indexNulls,p[M.name]=Te}else z&&(g=!0,v(),S.put($,M))}}finally{R&&R()}if(g&&(f.schemaVersion++,f.updatedAttributes()),pn.trace(`${e} table loading, running index`),H.length>0||B.length>0?f.indexingOperation=Pse(f,H,B):g&&qE.signalSchemaChange(new FE.SchemaEventMsg(process.pid,"schema-change",f.databaseName,f.tableName)),f.origin=_,g)for(let M of pA)M(f,_!=="cluster");return(r||n||s)&&f.setTTLExpiration({expiration:r,eviction:n,scanInterval:s}),pn.trace(`${e} table loaded`),f;function v(){R||l.transactionSync(()=>({then(M){R=M}}))}a(v,"startTxn")}async function Pse(e,t,r){try{let n=e.schemaVersion;await qE.signalSchemaChange(new FE.SchemaEventMsg(process.pid,"schema-change",e.databaseName,e.tableName));let s;for(let u of r)s=u.drop();let i,o=0,c=t.length;if(await new Promise(u=>setImmediate(u)),c>0){let u=0;for(let{key:_,value:l,version:d}of e.primaryStore.getRange({start:t[0].lastIndexedKey,lazy:c<4,versions:!0,snapshot:!1}))if(l){if(u++,s=e.primaryStore.ifVersion(_,d,()=>{for(let f=0;f<c;f++){let E=t[f],h=E.name,p=(0,Ix.getIndexedValues)(l[h]);if(p)for(let S=0,O=p.length;S<O;S++)E.dbi.put(p[S],_)}}),s.then(()=>u--,f=>{u--,pn.error(f)}),bl.workerData&&bl.workerData.restartNumber!==Cx.restartNumber&&(i=!0),++o%100===0||i){for(let f of t)f.lastIndexedKey=_,e.dbisDB.put(f.key,f);if(i)return}u>Mse?await s:u>Use&&await new Promise(f=>setImmediate(f))}for(let _ of t)delete _.lastIndexedKey,delete _.indexingPID,_.dbi.isIndexing=!1,s=e.dbisDB.put(_.key,_)}await s,await qE.signalSchemaChange(new FE.SchemaEventMsg(process.pid,"indexing-finished",e.databaseName,e.tableName))}catch(n){pn.error("Error in indexing",n)}}function vse({table:e,database:t}){let r=Qc({database:t,table:e}),n=[],s=r.dbisDb;for(let i of s.getKeys({start:e+"/",end:e+"0"}))n.push(s.remove(i));return Promise.all(n)}function yR(e){pA.push(e)}var Qt,HE,xE,Je,Wr,Wa,Co,EA,Qr,wx,hA,Ix,qE,FE,bl,pn,Cx,mA,kE,Dr,et,Ka,pA,GE,Oi,Qa,Mse,Use,be=Oe(()=>{Qt=x(Z()),HE=x(lt()),xE=require("lmdb"),Je=require("path"),Wr=require("fs"),Wa=x(Ye());Pf();Co=x(n_()),EA=x(i_()),Qr=x(U()),wx=x(require("fs-extra")),hA=require("../../index"),Ix=x(Cr()),qE=x(Ts()),FE=x(Nn()),bl=require("worker_threads"),pn=x(K()),Cx=x(Ze());Ui();Ho();mA="data",kE=Symbol("defined-tables");(0,Qt.initSync)();Dr=Object.create(null),et=Object.create(null);(0,hA._assignPackageExport)("databases",et);(0,hA._assignPackageExport)("tables",Dr);Ka=Symbol.for("next-table-id"),pA=[],Oi=new Map;a(Dse,"getTables");a(In,"getDatabases");a(Lse,"resetDatabases");a(Ol,"readMetaDb");a(Dx,"ensureDB");a(Lx,"setTable");a(Qc,"database");a(Gp,"dropDatabase");a(ot,"table");Mse=1e3,Use=10;a(Pse,"runIndexing");a(vse,"dropTableMeta");a(yR,"onUpdatedTable")});var J=T((cpe,Yx)=>{"use strict";var bi=require("path"),Bx=require("fs-extra"),Tr=K(),Mx=require("fs-extra"),VE=require("os"),Bse=require("net"),Hse=require("recursive-iterator"),it=U(),xse=sO(),Ux=require("papaparse"),$E=require("moment"),{inspect:qse}=require("util"),Px=require("is-number"),ape=require("lodash"),Fse=require("minimist"),Gse=require("https"),kse=require("http"),{hdb_errors:YE}=ee(),Vse=/^((\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z)))$/,Hx=require("util").promisify(setTimeout),$se=100,Yse=5,Kse="",Wse=4,vx={true:!0,TRUE:!0,FALSE:!1,false:!1,undefined:null,null:null,NULL:null,NaN:NaN};Yx.exports={isEmpty:zr,isEmptyOrZeroLength:us,arrayHasEmptyValues:Jse,arrayHasEmptyOrZeroLengthValues:jse,buildFolderPath:Xse,isBoolean:xx,errorizeMessage:Qse,stripFileExtension:eie,autoCast:tie,autoCastJSON:qx,autoCastJSONDeep:TA,removeDir:rie,compareVersions:nie,isCompatibleDataVersion:sie,escapeRawValue:iie,unescapeValue:oie,stringifyProps:aie,timeoutPromise:uie,isClusterOperation:_ie,getClusterUser:fie,checkGlobalSchemaTable:die,getHomeDir:Gx,getPropsFilePath:cie,promisifyPapaParse:Eie,removeBOM:kx,createEventPromise:hie,checkProcessRunning:mie,checkSchemaTableExist:pie,checkSchemaExists:Vx,checkTableExists:$x,getStartOfTomorrowInSeconds:Sie,getLimitKey:Tie,isObject:Zse,isNotEmptyAndHasValue:zse,autoCasterIsNumberCheck:Fx,backtickASTSchemaItems:gie,isPortTaken:lie,createForkArgs:Rie,autoCastBoolean:Aie,async_set_timeout:Hx,getTableHashAttribute:Oie,doesSchemaExist:bie,doesTableExist:yie,stringifyObj:Nie,ms_to_time:wie,changeExtension:Iie,getEnvCliRootPath:gA,noBootFile:Cie,httpRequest:Die,transformReq:Lie,convertToMS:Mie,PACKAGE_ROOT:it.PACKAGE_ROOT};function Qse(e){return e instanceof Error?e:new Error(e)}a(Qse,"errorizeMessage");function zr(e){return e==null}a(zr,"isEmpty");function zse(e){return!zr(e)&&(e||e===0||e===""||xx(e))}a(zse,"isNotEmptyAndHasValue");function us(e){return zr(e)||e.length===0||e.size===0}a(us,"isEmptyOrZeroLength");function Jse(e){if(zr(e))return!0;for(let t=0;t<e.length;t++)if(zr(e[t]))return!0;return!1}a(Jse,"arrayHasEmptyValues");function jse(e){if(us(e))return!0;for(let t=0;t<e.length;t++)if(us(e[t]))return!0;return!1}a(jse,"arrayHasEmptyOrZeroLengthValues");function Xse(...e){try{return e.join(bi.sep)}catch{console.error(e)}}a(Xse,"buildFolderPath");function xx(e){return zr(e)?!1:e===!0||e===!1}a(xx,"isBoolean");function Zse(e){return zr(e)?!1:typeof e=="object"}a(Zse,"isObject");function eie(e){return us(e)?Kse:e.slice(0,-Wse)}a(eie,"stripFileExtension");function tie(e){return zr(e)||e===""||typeof e!="string"?e:vx[e]!==void 0?vx[e]:Fx(e)===!0?Number(e):Vse.test(e)?new Date(e):e}a(tie,"autoCast");function qx(e){if(typeof e=="string"&&(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")))try{return JSON.parse(e)}catch{}return e}a(qx,"autoCastJSON");function TA(e){if(e&&typeof e=="object"){if(Array.isArray(e))for(let t=0,r=e.length;t<r;t++){let n=e[t],s=TA(n);s!==n&&(e[t]=s)}else for(let t in e){let r=e[t],n=TA(r);n!==r&&(e[t]=n)}return e}else return qx(e)}a(TA,"autoCastJSONDeep");function Fx(e){if(e.startsWith("0.")&&Px(e))return!0;let t=e.toUpperCase().includes("E");return!!((e!=="0"&&e.startsWith("0"))===!1&&t===!1&&Px(e))}a(Fx,"autoCasterIsNumberCheck");async function rie(e){if(us(e))throw new Error(`Directory path: ${e} does not exist`);try{await Mx.emptyDir(e),await Mx.remove(e)}catch(t){throw Tr.error(`Error removing files in ${e} -- ${t}`),t}}a(rie,"removeDir");function nie(e,t){if(us(e)){Tr.info("Invalid current version sent as parameter.");return}if(us(t)){Tr.info("Invalid upgrade version sent as parameter.");return}let r,n=/(\.0+)+$/,s=e.version?e.version:e,i=t.version?t.version:t,o=s.replace(n,"").split("."),c=i.replace(n,"").split("."),u=Math.min(o.length,c.length);for(let _=0;_<u;_++)if(r=parseInt(o[_],10)-parseInt(c[_],10),r)return r;return o.length-c.length}a(nie,"compareVersions");function sie(e,t,r=!1){let n=e.toString().split("."),s=t.toString().split(".");return n[0]===s[0]&&(!r||n[1]===s[1])}a(sie,"isCompatibleDataVersion");function iie(e){if(zr(e))return e;let t=String(e);return t==="."?it.UNICODE_PERIOD:t===".."?it.UNICODE_PERIOD+it.UNICODE_PERIOD:t.replace(it.FORWARD_SLASH_REGEX,it.UNICODE_FORWARD_SLASH)}a(iie,"escapeRawValue");function oie(e){if(zr(e))return e;let t=String(e);return t===it.UNICODE_PERIOD?".":t===it.UNICODE_PERIOD+it.UNICODE_PERIOD?"..":String(e).replace(it.ESCAPED_FORWARD_SLASH_REGEX,"/")}a(oie,"unescapeValue");function aie(e,t){if(zr(e))return Tr.info("Properties object is null"),"";let r="";return e.each(function(n,s){try{if(t&&t[n]){let i=t[n];for(let o of i)r+=";"+o+VE.EOL}!us(n)&&n[0]===";"?r+=" "+n+s+VE.EOL:us(n)||(r+=n+"="+s+VE.EOL)}catch{Tr.error(`Found bad property during upgrade with key ${n} and value: ${s}`)}}),r}a(aie,"stringifyProps");function Gx(){let e;try{e=VE.homedir()}catch{e=process.env.HOME}return e||(e="~/"),e}a(Gx,"getHomeDir");function cie(){let e=bi.join(Gx(),it.HDB_HOME_DIR_NAME,it.BOOT_PROPS_FILE_NAME);return Bx.existsSync(e)||(e=bi.join(__dirname,"../","hdb_boot_properties.file")),e}a(cie,"getPropsFilePath");function uie(e,t){let r,n;return n=new Promise(function(s){r=setTimeout(function(){s(t)},e)}),{promise:n,cancel:function(){clearTimeout(r)}}}a(uie,"timeoutPromise");async function lie(e){if(!e)throw new Error("Invalid port passed as parameter");return new Promise((t,r)=>{let n=Bse.createServer().once("error",s=>{s.code==="EADDRINUSE"?t(!0):r(s)}).once("listening",()=>n.once("close",()=>t(!1)).close()).listen(e)})}a(lie,"isPortTaken");function _ie(e){try{return it.CLUSTER_OPERATIONS[e.toLowerCase()]!==void 0}catch(t){Tr.error(`Error checking operation against cluster ops ${t}`)}return!1}a(_ie,"isClusterOperation");function die(e,t){let r=(be(),te(qe)).getDatabases();if(!r[e])return YE.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e);if(!r[e][t])return YE.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(die,"checkGlobalSchemaTable");function fie(e,t){if(zr(t)){Tr.warn("No CLUSTERING_USER defined, clustering disabled");return}if(zr(e)||us(e)){Tr.warn("No users to search.");return}let r;try{let n=e.get(t);n&&n.role.permission.cluster_user===!0&&n.active===!0&&(r=n)}catch(n){Tr.error(`unable to find cluster_user due to: ${n.message}`);return}if(r===void 0){Tr.warn(`CLUSTERING_USER: ${t} not found or is not active.`);return}return r}a(fie,"getClusterUser");function Eie(){Ux.parsePromise=function(e,t,r){return new Promise(function(n,s){Ux.parse(e,{header:!0,transformHeader:kx,chunk:t.bind(null,s),skipEmptyLines:!0,transform:r,dynamicTyping:!1,error:s,complete:n})})}}a(Eie,"promisifyPapaParse");function kx(e){if(typeof e!="string")throw new TypeError(`Expected a string, got ${typeof e}`);return e.charCodeAt(0)===65279?e.slice(1):e}a(kx,"removeBOM");function hie(e,t,r){return new Promise(n=>{t.once(e,s=>{let i=r;Tr.info(`Got cluster status event response: ${qse(s)}`);try{i.cancel()}catch{Tr.error("Error trying to cancel timeout.")}n(s)})})}a(hie,"createEventPromise");async function mie(e){let t=!0,r=0;do await Hx($se*r++),(await xse.findPs(e)).length>0&&(t=!1);while(t&&r<Yse);if(t)throw new Error(`process ${e} was not started`)}a(mie,"checkProcessRunning");function pie(e,t){let r=Vx(e);if(r)return r;let n=$x(e,t);if(n)return n}a(pie,"checkSchemaTableExist");function Vx(e){let{getDatabases:t}=(be(),te(qe));if(!t()[e])return YE.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}a(Vx,"checkSchemaExists");function $x(e,t){let{getDatabases:r}=(be(),te(qe));if(!r()[e][t])return YE.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a($x,"checkTableExists");function Sie(){let e=$E().utc().add(1,it.MOMENT_DAYS_TAG).startOf(it.MOMENT_DAYS_TAG).unix(),t=$E().utc().unix();return e-t}a(Sie,"getStartOfTomorrowInSeconds");function Tie(){return $E().utc().format("DD-MM-YYYY")}a(Tie,"getLimitKey");function gie(e){try{let t=new Hse(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){Tr.error("Got an error back ticking items."),Tr.error(t)}}a(gie,"backtickASTSchemaItems");function Rie(e){return[e]}a(Rie,"createForkArgs");function Aie(e){return e===!0||typeof e=="string"&&e.toLowerCase()==="true"}a(Aie,"autoCastBoolean");function Oie(e,t){let{getDatabases:r}=(be(),te(qe)),n=r()[e]?.[t];return n?.primaryKey||n?.hash_attribute}a(Oie,"getTableHashAttribute");function bie(e){let{getDatabases:t}=(be(),te(qe));return t()[e]!==void 0}a(bie,"doesSchemaExist");function yie(e,t){let{getDatabases:r}=(be(),te(qe));return r()[e]?.[t]!==void 0}a(yie,"doesTableExist");function Nie(e){try{return JSON.stringify(e)}catch{return e}}a(Nie,"stringifyObj");function wie(e){let t=$E.duration(e),r=t.seconds()>0?t.seconds()+"s":"",n=t.minutes()>0?t.minutes()+"m ":"",s=t.hours()>0?t.hours()+"h ":"",i=t.days()>0?t.days()+"d ":"";return(t.years()>0?t.years()+"y ":"")+i+s+n+r}a(wie,"ms_to_time");function Iie(e,t){let r=bi.basename(e,bi.extname(e));return bi.join(bi.dirname(e),r+t)}a(Iie,"changeExtension");function gA(){if(process.env[it.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return process.env[it.CONFIG_PARAMS.ROOTPATH.toUpperCase()];let e=Fse(process.argv);if(e[it.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return e[it.CONFIG_PARAMS.ROOTPATH.toUpperCase()]}a(gA,"getEnvCliRootPath");var SA;function Cie(){if(SA)return SA;let e=gA();gA()&&Bx.pathExistsSync(bi.join(e,it.HDB_CONFIG_FILE))&&(SA=!0)}a(Cie,"noBootFile");function Die(e,t){let r;return e.protocol==="http:"?r=kse:r=Gse,new Promise((n,s)=>{let i=r.request(e,o=>{o.setEncoding("utf8");let c={body:"",headers:o.headers};o.on("data",u=>{c.body+=u}),o.on("end",()=>{n(c)})});i.on("error",o=>{s(o)}),i.write(JSON.stringify(t)),i.end()})}a(Die,"httpRequest");function Lie(e){if(!e.schema&&!e.database){e.schema=it.DEFAULT_DATABASE_NAME;return}e.database&&(e.schema=e.database)}a(Lie,"transformReq");function Mie(e){let t=0;if(typeof e=="number"&&(t=e),typeof e=="string")switch(t=parseFloat(e),e.slice(-1)){case"M":t*=86400*30;break;case"D":case"d":t*=86400;break;case"H":case"h":t*=3600;break;case"m":t*=60;break}return t*1e3}a(Mie,"convertToMS")});var RA=U(),Kx=J(),yl=K(),Uie=Ss(),Pie=Ur(),vie=eR(),{start:Bie}=(bR(),te(sE)),{closeConnection:Hie}=ft(),Wx=require("moment"),Qx=Bf(),{cloneDeep:xie}=require("lodash"),qie=process.env[RA.PROCESS_NAME_ENV_PROP],Do=qie.substring(4);a(async function(){let t={id:Do,request:void 0},r=0;try{yl.notify("Starting job:",Do),Bie(),Uie.setSchemaDataToGlobal(),await Pie.setUsersToGlobal();let n=await Qx.getJobById(Do);if(Kx.isEmptyOrZeroLength(n))throw new Error(`Unable to find a record in hdb_job for job: ${Do}`);let{request:s}=n[0];if(Kx.isEmptyOrZeroLength(s))throw new Error("Did not find job request in hdb_job table, unable to proceed");s=xie(s);let i=vie.getOperationFunction(s);yl.trace("Running operation:",s.operation,"for job",Do);let o=await i.job_operation_function(s);yl.trace("Result from job:",Do,o),t.status=RA.JOB_STATUS_ENUM.COMPLETE,t.message=o,t.end_datetime=Wx().valueOf(),yl.notify("Successfully completed job:",Do)}catch(n){r=1,yl.error(n),t.status=RA.JOB_STATUS_ENUM.ERROR,t.message=n.message?n.message:n,t.end_datetime=Wx().valueOf()}finally{await Qx.updateJob(t),await Hie(),setTimeout(()=>{process.exit(r)},3e3).unref()}},"job")();
|