harperdb 4.3.0-beta.14 → 4.3.0-beta.16
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 +58 -56
- package/bin/lite.js +21 -19
- package/launchServiceScripts/launchInstallNATSServer.js +2 -2
- package/launchServiceScripts/launchNatsIngestService.js +21 -19
- package/launchServiceScripts/launchNatsReplyService.js +21 -19
- package/launchServiceScripts/launchUpdateNodes4-0-0.js +21 -19
- package/npm-shrinkwrap.json +94 -94
- package/package.json +3 -3
- package/server/jobs/jobProcess.js +21 -19
- package/server/threads/threadServer.js +21 -19
- package/studio/build-local/asset-manifest.json +2 -2
- package/studio/build-local/index.html +1 -1
- package/studio/build-local/static/js/{main.199e99ce.js → main.1d78c091.js} +2 -2
- package/utility/scripts/restartHdb.js +21 -19
- /package/studio/build-local/static/js/{main.199e99ce.js.LICENSE.txt → main.1d78c091.js.LICENSE.txt} +0 -0
|
@@ -1,30 +1,32 @@
|
|
|
1
|
-
"use strict";var Jq=Object.create;var sc=Object.defineProperty;var Xq=Object.getOwnPropertyDescriptor;var jq=Object.getOwnPropertyNames;var Zq=Object.getPrototypeOf,eG=Object.prototype.hasOwnProperty;var a=(e,t)=>sc(e,"name",{value:t,configurable:!0});var Re=(e,t)=>()=>(e&&(t=e(e=0)),t);var g=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Ye=(e,t)=>{for(var r in t)sc(e,r,{get:t[r],enumerable:!0})},ZA=(e,t,r,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of jq(t))!eG.call(e,n)&&n!==r&&sc(e,n,{get:()=>t[n],enumerable:!(s=Xq(t,n))||s.enumerable});return e};var x=(e,t,r)=>(r=e!=null?Jq(Zq(e)):{},ZA(t||!e||!e.__esModule?sc(r,"default",{value:e,enumerable:!0}):r,e)),ne=e=>ZA(sc({},"__esModule",{value:!0}),e);var rO=g((gae,tO)=>{var tG=require("fast-glob"),{statSync:Th,existsSync:gh,readFileSync:rG,writeFileSync:sG}=require("fs"),{spawnSync:nG,spawn:iG,execFileSync:Tae}=require("child_process"),{isMainThread:oG}=require("worker_threads"),{join:Jn,relative:eO}=require("path"),{PACKAGE_ROOT:Os}=M(),{tmpdir:aG,platform:cG}=require("os");require("source-map-support").install();var uG=["resources","server","dataLayer","components"],nc="ts-build",Rh,lG=__filename.endsWith("tsBuild.js");if(lG){if(oG){let r;try{Th(Jn(Os,nc)),r=!0}catch{}if(r)for(let s of tG.sync(uG.map(n=>n+"/**/*.ts"),{cwd:Os})){let n=0,i=0;try{n=Th(Jn(Os,s)).mtimeMs-5e3,i=Th(Jn(Os,nc,s.replace(/.ts$/,".js"))).mtimeMs}catch{}if(n>i){console.warn(`TypeScript ${s} is not compiled`+(i?` (TS source file was modified at ${new Date(n)} and compiled file at ${new Date(i)})`:"")+", consider enabling auto-compilation of TypeScript in your IDE), compiling now."),Rh=!0;break}}else console.log("TypeScript modules are not compiled, compiling now"),Rh=!0;if(Rh){let s=Jn(Os,"node_modules/.bin/tsc");cG()==="win32"&&(s+=".cmd");let n=nG(s,{cwd:Os});if(n.stdout.length&&console.log(n.stdout.toString()),n.stderr.length&&console.log(n.stderr.toString()),r){let i=Jn(aG(),"harperdb-tsc.pid"),o;if(gh(i))try{process.kill(+rG(i,{encoding:"utf8"}),0),o=!0}catch{}if(!o){console.log("starting tsc background process");let c=iG(s,["--watch"],{cwd:Os,detached:!0,stdio:"ignore"});sG(i,c.pid.toString()),c.unref()}}}}let e=tO.constructor,t=e._findPath;e._findPath=function(r,s,n){if(r.startsWith(".")&&!n&&s.length===1&&s[0].startsWith(Os)&&!s[0].includes("node_modules")){let i=eO(Os,s[0]),o;i.startsWith(nc)?o=Jn(Os,eO(nc,i)):o=Jn(Os,nc,i);let c=Jn(o,r),u=c+".js";if(gh(u))return u;if(c.includes(".")&&gh(c))return c}return t(r,s,n)}}});var M=g((Oae,mO)=>{"use strict";var rs=require("path"),_G=require("fs"),{relative:Rae,join:Aae}=rs,{existsSync:dG}=_G;function fG(){let e=__dirname;for(;!dG(rs.join(e,"package.json"));){let t=rs.dirname(e);if(t===e)throw new Error("Could not find package root");e=t}return e}a(fG,"getHDBPackageRoot");var Xn=fG(),sO="js",$l=sO,EG="harperdb-config.yaml",hG="defaultConfig.yaml",mG="hdb",nO=`harperdb.${$l}`,iO=`customFunctionsServer.${$l}`,pG=`restartHdb.${$l}`,Oh="HarperDB",Vl="Custom Functions",Yl="Clustering Hub",Kl="Clustering Leaf",SG="Clustering Ingest Service",TG="Clustering Reply Service",gG="foreground.pid",RG="hdb.pid",AG="data",OG={HDB:Oh,CLUSTERING_HUB:Yl,CLUSTERING_LEAF:Kl,CLUSTERING_INGEST_SERVICE:SG,CLUSTERING_REPLY_SERVICE:TG,CUSTOM_FUNCTIONS:Vl,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"},bG={HDB:"hdb.log",INSTALL:"install.log",CLUSTERING_HUB:"clustering_hub.log",CLUSTERING_LEAF:"clustering_leaf.log"},NG={NOTIFY:"notify",FATAL:"fatal",ERROR:"error",WARN:"warn",INFO:"info",DEBUG:"debug",TRACE:"trace"},yG={harperdb:Oh,"clustering hub":Yl,"clustering leaf":Kl,"custom functions":Vl,custom_functions:Vl,clustering:"clustering","clustering config":"clustering config",clustering_config:"clustering_config",http_workers:"http_workers"},IG={CLUSTERING_HUB_PROC_DESCRIPTOR:Yl,CLUSTERING_LEAF_PROC_DESCRIPTOR:Kl},Ah={HDB:rs.join(Xn,"server/harperdb"),CUSTOM_FUNCTIONS:rs.join(Xn,"server/customFunctions"),CLUSTERING_HUB:rs.join(Xn,"server/nats"),CLUSTERING_LEAF:rs.join(Xn,"server/nats")},wG={HDB:rs.join(Ah.HDB,nO),CUSTOM_FUNCTIONS:rs.join(Ah.CUSTOM_FUNCTIONS,iO)},CG={MAIN:"bin/harperdb.js",NATS_INGEST_SERVICE:rs.join(Xn,"launchServiceScripts/launchNatsIngestService.js"),NATS_REPLY_SERVICE:rs.join(Xn,"launchServiceScripts/launchNatsReplyService.js"),NODES_UPGRADE_4_0_0:rs.join(Xn,"launchServiceScripts/launchUpdateNodes4-0-0.js")},DG={SUPER_USER:"super_user",CLUSTER_USER:"cluster_user"},oO="support@harperdb.io",LG="customer-success@harperdb.io",aO=1,MG=4141,cO="https://harperdbhelp.zendesk.com/hc/en-us/requests/new",UG="https://www.harperdb.io/product",PG=`For support, please submit a request at ${cO} or contact ${oO}`,uO=`For license support, please contact ${LG}`,vG="None of the specified records were found.",BG="hash attribute not found",HG=`Your current license only supports ${aO} role. ${uO}`,xG="Your current license only supports 3 connections to a node.",qG="127.0.0.1",GG=1,FG=/^\.$/,kG=/^\.\.$/,VG="U+002E",$G=/\//g,YG="U+002F",KG=/U\+002F/g,WG=/^U\+002E$/,QG=/^U\+002EU\+002E$/,zG="d",JG=999999,XG="*",jG="--max-old-space-size=",ZG="system",eF="__hdb_hash",tF=".harperdb",rF=".hdb",sF="keys",nF="hdb_boot_properties.file",iF=".updateConfig.json",oF="SIGTSTP",aF=24,cF=6e4,uF=448,lF="blob",_F="trash",dF="database",fF="schema",EF="transactions",hF=".count",mF="id",pF="PROCESS_NAME",lO={SETTINGS_PATH_KEY:"settings_path"},_O=require("lodash"),SF={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"},TF={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},gF={DATA_VERSION:"data_version",UPGRADE_VERSION:"upgrade_version"},RF={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"},AF={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"},yr="hdb_internal:",OF={CREATE_SCHEMA:yr+"create_schema",CREATE_TABLE:yr+"create_table",CREATE_ATTRIBUTE:yr+"create_attribute",ADD_USER:yr+"add_user",ALTER_USER:yr+"alter_user",DROP_USER:yr+"drop_user",HDB_NODES:yr+"hdb_nodes",HDB_USERS:yr+"hdb_users",HDB_WORKERS:yr+"hdb_workers",CATCHUP:yr+"catchup",SCHEMA_CATCHUP:yr+"schema_catchup",WORKER_ROOM:yr+"cluster_workers"},bF={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"},NF="060493.ks",yF=".license",IF={CREATED:"CREATED",IN_PROGRESS:"IN_PROGRESS",COMPLETE:"COMPLETE",ERROR:"ERROR"},Z={INSERT:"insert",UPDATE:"update",UPSERT:"upsert",SEARCH_BY_CONDITIONS:"search_by_conditions",SEARCH_BY_HASH:"search_by_hash",SEARCH_BY_ID:"search_by_id",SEARCH_BY_VALUE:"search_by_value",SEARCH:"search",SQL:"sql",CSV_DATA_LOAD:"csv_data_load",CSV_FILE_LOAD:"csv_file_load",CSV_URL_LOAD:"csv_url_load",CREATE_SCHEMA:"create_schema",CREATE_DATABASE:"create_database",CREATE_TABLE:"create_table",CREATE_ATTRIBUTE:"create_attribute",DROP_SCHEMA:"drop_schema",DROP_DATABASE:"drop_database",DROP_TABLE:"drop_table",DESCRIBE_SCHEMA:"describe_schema",DESCRIBE_DATABASE:"describe_database",DESCRIBE_TABLE:"describe_table",DESCRIBE_ALL:"describe_all",DELETE:"delete",ADD_USER:"add_user",ALTER_USER:"alter_user",DROP_USER:"drop_user",LIST_USERS:"list_users",LIST_ROLES:"list_roles",ADD_ROLE:"add_role",ALTER_ROLE:"alter_role",DROP_ROLE:"drop_role",USER_INFO:"user_info",READ_LOG:"read_log",ADD_NODE:"add_node",UPDATE_NODE:"update_node",SET_NODE_REPLICATION:"set_node_replication",EXPORT_TO_S3:"export_to_s3",IMPORT_FROM_S3:"import_from_s3",DELETE_FILES_BEFORE:"delete_files_before",DELETE_RECORDS_BEFORE:"delete_records_before",EXPORT_LOCAL:"export_local",SEARCH_JOBS_BY_START_DATE:"search_jobs_by_start_date",GET_JOB:"get_job",DELETE_JOB:"delete_job",UPDATE_JOB:"update_job",GET_FINGERPRINT:"get_fingerprint",SET_LICENSE:"set_license",GET_REGISTRATION_INFO:"registration_info",CONFIGURE_CLUSTER:"configure_cluster",SET_CONFIGURATION:"set_configuration",CLUSTER_STATUS:"cluster_status",CLUSTER_NETWORK:"cluster_network",DROP_ATTRIBUTE:"drop_attribute",REMOVE_NODE:"remove_node",RESTART:"restart",RESTART_SERVICE:"restart_service",CATCHUP:"catchup",SYSTEM_INFORMATION:"system_information",DELETE_AUDIT_LOGS_BEFORE:"delete_audit_logs_before",READ_AUDIT_LOG:"read_audit_log",CREATE_AUTHENTICATION_TOKENS:"create_authentication_tokens",LOGIN:"login",LOGOUT:"logout",REFRESH_OPERATION_TOKEN:"refresh_operation_token",GET_CONFIGURATION:"get_configuration",CUSTOM_FUNCTIONS_STATUS:"custom_functions_status",GET_CUSTOM_FUNCTIONS:"get_custom_functions",GET_CUSTOM_FUNCTION:"get_custom_function",SET_CUSTOM_FUNCTION:"set_custom_function",GET_COMPONENTS:"get_components",GET_COMPONENT_FILE:"get_component_file",SET_COMPONENT_FILE:"set_component_file",DROP_COMPONENT:"drop_component",DROP_CUSTOM_FUNCTION:"drop_custom_function",ADD_CUSTOM_FUNCTION_PROJECT:"add_custom_function_project",ADD_COMPONENT:"add_component",DROP_CUSTOM_FUNCTION_PROJECT:"drop_custom_function_project",PACKAGE_CUSTOM_FUNCTION_PROJECT:"package_custom_function_project",DEPLOY_CUSTOM_FUNCTION_PROJECT:"deploy_custom_function_project",PACKAGE_COMPONENT:"package_component",DEPLOY_COMPONENT:"deploy_component",CLUSTER_SET_ROUTES:"cluster_set_routes",CLUSTER_DELETE_ROUTES:"cluster_delete_routes",CLUSTER_GET_ROUTES:"cluster_get_routes",READ_TRANSACTION_LOG:"read_transaction_log",DELETE_TRANSACTION_LOGS_BEFORE:"delete_transaction_logs_before",INSTALL_NODE_MODULES:"install_node_modules",AUDIT_NODE_MODULES:"audit_node_modules",PURGE_STREAM:"purge_stream",GET_BACKUP:"get_backup"},wF={CSV:".csv",JSON:".json"},CF={AWS_ACCESS_KEY:"aws_access_key_id",AWS_SECRET:"aws_secret_access_key",AWS_BUCKET:"bucket",AWS_FILE_KEY:"key",REGION:"region"},DF={SELECT:"select",INSERT:"insert",UPDATE:"update",DELETE:"delete"},ic={};ic[Z.INSERT]=Z.INSERT;ic[Z.UPDATE]=Z.UPDATE;ic[Z.UPSERT]=Z.UPSERT;ic[Z.DELETE]=Z.DELETE;var xe=Object.create(null);xe[Z.DESCRIBE_ALL]=Z.DESCRIBE_ALL;xe[Z.DESCRIBE_TABLE]=Z.DESCRIBE_TABLE;xe[Z.DESCRIBE_SCHEMA]=Z.DESCRIBE_SCHEMA;xe[Z.READ_LOG]=Z.READ_LOG;xe[Z.ADD_NODE]=Z.ADD_NODE;xe[Z.LIST_USERS]=Z.LIST_USERS;xe[Z.LIST_ROLES]=Z.LIST_ROLES;xe[Z.USER_INFO]=Z.USER_INFO;xe[Z.SQL]=Z.SQL;xe[Z.GET_JOB]=Z.GET_JOB;xe[Z.SEARCH_JOBS_BY_START_DATE]=Z.SEARCH_JOBS_BY_START_DATE;xe[Z.DELETE_FILES_BEFORE]=Z.DELETE_FILES_BEFORE;xe[Z.EXPORT_LOCAL]=Z.EXPORT_LOCAL;xe[Z.EXPORT_TO_S3]=Z.EXPORT_TO_S3;xe[Z.CLUSTER_STATUS]=Z.CLUSTER_STATUS;xe[Z.REMOVE_NODE]=Z.REMOVE_NODE;xe[Z.RESTART]=Z.RESTART;xe[Z.CUSTOM_FUNCTIONS_STATUS]=Z.CUSTOM_FUNCTIONS_STATUS;xe[Z.GET_CUSTOM_FUNCTIONS]=Z.GET_CUSTOM_FUNCTIONS;xe[Z.GET_CUSTOM_FUNCTION]=Z.GET_CUSTOM_FUNCTION;xe[Z.SET_CUSTOM_FUNCTION]=Z.SET_CUSTOM_FUNCTION;xe[Z.DROP_CUSTOM_FUNCTION]=Z.DROP_CUSTOM_FUNCTION;xe[Z.ADD_CUSTOM_FUNCTION_PROJECT]=Z.ADD_CUSTOM_FUNCTION_PROJECT;xe[Z.DROP_CUSTOM_FUNCTION_PROJECT]=Z.DROP_CUSTOM_FUNCTION_PROJECT;xe[Z.PACKAGE_CUSTOM_FUNCTION_PROJECT]=Z.PACKAGE_CUSTOM_FUNCTION_PROJECT;xe[Z.DEPLOY_CUSTOM_FUNCTION_PROJECT]=Z.DEPLOY_CUSTOM_FUNCTION_PROJECT;var LF={DEV:"dev",RUN:"run",START:"start",INSTALL:"install",REGISTER:"register",STOP:"stop",RESTART:"restart",VERSION:"version",UPGRADE:"upgrade",HELP:"help",STATUS:"status",OPERATION:"operation",RENEWCERTS:"renew-certs",COPYDB:"copy-db"},MF={point:"point",lineString:"lineString",multiLineString:"multiLineString",multiPoint:"multiPoint",multiPolygon:"multiPolygon",polygon:"polygon"},dO={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"},UF=_O.invert(dO),PF={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"},w={ANALYTICS_AGGREGATEPERIOD:"analytics_aggregatePeriod",AUTHENTICATION_AUTHORIZELOCAL:"authentication_authorizeLocal",AUTHENTICATION_CACHETTL:"authentication_cacheTTL",AUTHENTICATION_ENABLESESSIONS:"authentication_enableSessions",AUTHENTICATION_OPERATIONTOKENTIMEOUT:"authentication_operationTokenTimeout",AUTHENTICATION_REFRESHTOKENTIMEOUT:"authentication_refreshTokenTimeout",CLUSTERING_USER:"clustering_user",CLUSTERING_ENABLED:"clustering_enabled",CLUSTERING_HUBSERVER_CLUSTER_NAME:"clustering_hubServer_cluster_name",CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT:"clustering_hubServer_cluster_network_port",CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES:"clustering_hubServer_cluster_network_routes",CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT:"clustering_hubServer_leafNodes_network_port",CLUSTERING_HUBSERVER_NETWORK_PORT:"clustering_hubServer_network_port",CLUSTERING_LEAFSERVER_NETWORK_PORT:"clustering_leafServer_network_port",CLUSTERING_LEAFSERVER_NETWORK_ROUTES:"clustering_leafServer_network_routes",CLUSTERING_LEAFSERVER_STREAMS_MAXAGE:"clustering_leafServer_streams_maxAge",CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES:"clustering_leafServer_streams_maxBytes",CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS:"clustering_leafServer_streams_maxMsgs",CLUSTERING_LEAFSERVER_STREAMS_MAXCONSUMEMSGS:"clustering_leafServer_streams_maxConsumeMsgs",CLUSTERING_LEAFSERVER_STREAMS_MAXINGESTTHREADS:"clustering_leafServer_streams_maxIngestThreads",CLUSTERING_LEAFSERVER_STREAMS_PATH:"clustering_leafServer_streams_path",CLUSTERING_NODENAME:"clustering_nodeName",CLUSTERING_TLS_CERTIFICATE:"clustering_tls_certificate",CLUSTERING_TLS_PRIVATEKEY:"clustering_tls_privateKey",CLUSTERING_TLS_CERT_AUTH:"clustering_tls_certificateAuthority",CLUSTERING_TLS_INSECURE:"clustering_tls_insecure",CLUSTERING_TLS_VERIFY:"clustering_tls_verify",CLUSTERING_LOGLEVEL:"clustering_logLevel",CLUSTERING_REPUBLISHMESSAGES:"clustering_republishMessages",CLUSTERING_DATABASELEVEL:"clustering_databaseLevel",CUSTOMFUNCTIONS_NETWORK_HTTPS:"customFunctions_network_https",THREADS:"threads",THREADS_COUNT:"threads_count",THREADS_DEBUG:"threads_debug",THREADS_DEBUG_STARTINGPORT:"threads_debug_startingPort",THREADS_DEBUG_PORT:"threads_debug_port",THREADS_DEBUG_HOST:"threads_debug_host",THREADS_DEBUG_WAITFORDEBUGGER:"threads_debug_waitForDebugger",THREADS_MAXHEAPMEMORY:"threads_maxHeapMemory",HTTP_SESSIONAFFINITY:"http_sessionAffinity",HTTP_COMPRESSIONTHRESHOLD:"http_compressionThreshold",HTTP_CORS:"http_cors",HTTP_CORSACCESSLIST:"http_corsAccessList",HTTP_HEADERSTIMEOUT:"http_headersTimeout",HTTP_KEEPALIVETIMEOUT:"http_keepAliveTimeout",HTTP_TIMEOUT:"http_timeout",HTTP_PORT:"http_port",HTTP_SECUREPORT:"http_securePort",HTTP_MTLS:"http_mtls",HTTP_MTLS_REQUIRED:"http_mtls_required",HTTP_MTLS_USER:"http_mtls_user",HTTP_MAXHEADERSIZE:"http_maxHeaderSize",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",STORAGE_MAXFREESPACETOLOAD:"storage_maxFreeSpaceToLoad",STORAGE_MAXFREESPACETORETAIN:"storage_maxFreeSpaceToRetain",STORAGE_PAGESIZE:"storage_pageSize",STORAGE_COMPRESSION_DICTIONARY:"storage_compression_dictionary",STORAGE_COMPRESSION_THRESHOLD:"storage_compression_threshold",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"},fO={settings_path:lO.SETTINGS_PATH_KEY,hdb_root_key:w.ROOTPATH,hdb_root:w.ROOTPATH,rootpath:w.ROOTPATH,server_port_key:w.OPERATIONSAPI_NETWORK_PORT,server_port:w.OPERATIONSAPI_NETWORK_PORT,cert_key:w.TLS_CERTIFICATE,certificate:w.TLS_CERTIFICATE,private_key_key:w.TLS_PRIVATEKEY,private_key:w.TLS_PRIVATEKEY,http_secure_enabled_key:w.OPERATIONSAPI_NETWORK_HTTPS,https_on:w.OPERATIONSAPI_NETWORK_HTTPS,cors_enabled_key:w.OPERATIONSAPI_NETWORK_CORS,cors_on:w.OPERATIONSAPI_NETWORK_CORS,cors_whitelist_key:w.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_whitelist:w.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_accesslist_key:w.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_accesslist:w.OPERATIONSAPI_NETWORK_CORSACCESSLIST,log_level_key:w.LOGGING_LEVEL,log_level:w.LOGGING_LEVEL,log_path_key:w.LOGGING_ROOT,log_path:w.LOGGING_ROOT,clustering_node_name_key:w.CLUSTERING_NODENAME,node_name:w.CLUSTERING_NODENAME,clustering_enabled_key:w.CLUSTERING_ENABLED,clustering:w.CLUSTERING_ENABLED,max_http_threads:w.THREADS_COUNT,max_hdb_processes:w.THREADS_COUNT,server_timeout_key:w.OPERATIONSAPI_NETWORK_TIMEOUT,server_timeout_ms:w.OPERATIONSAPI_NETWORK_TIMEOUT,server_keep_alive_timeout_key:w.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT,server_keep_alive_timeout:w.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT,server_headers_timeout_key:w.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT,server_headers_timeout:w.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT,disable_transaction_log_key:w.LOGGING_AUDITLOG,disable_transaction_log:w.LOGGING_AUDITLOG,operation_token_timeout_key:w.AUTHENTICATION_OPERATIONTOKENTIMEOUT,operation_token_timeout:w.AUTHENTICATION_OPERATIONTOKENTIMEOUT,refresh_token_timeout_key:w.AUTHENTICATION_REFRESHTOKENTIMEOUT,refresh_token_timeout:w.AUTHENTICATION_REFRESHTOKENTIMEOUT,custom_functions_port_key:w.HTTP_PORT,custom_functions_port:w.HTTP_PORT,custom_functions_directory_key:w.COMPONENTSROOT,custom_functions_directory:w.COMPONENTSROOT,max_custom_function_processes:w.THREADS_COUNT,log_to_file:w.LOGGING_FILE,log_to_stdstreams:w.LOGGING_STDSTREAMS,local_studio_on:w.LOCALSTUDIO_ENABLED,clustering_port:w.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT,clustering_user:w.CLUSTERING_USER,clustering_enabled:w.CLUSTERING_ENABLED,clustering_hubserver_cluster_name:w.CLUSTERING_HUBSERVER_CLUSTER_NAME,clustering_hubserver_cluster_network_port:w.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT,clustering_hubserver_cluster_network_routes:w.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,clustering_hubserver_leafnodes_network_port:w.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT,clustering_hubserver_network_port:w.CLUSTERING_HUBSERVER_NETWORK_PORT,clustering_leafserver_network_port:w.CLUSTERING_LEAFSERVER_NETWORK_PORT,clustering_leafserver_network_routes:w.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,clustering_leafserver_streams_maxage:w.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE,clustering_leafserver_streams_maxbytes:w.CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES,clustering_leafserver_streams_maxconsumemsgs:w.CLUSTERING_LEAFSERVER_STREAMS_MAXCONSUMEMSGS,clustering_leafserver_streams_maxingestthreads:w.CLUSTERING_LEAFSERVER_STREAMS_MAXINGESTTHREADS,clustering_leafserver_streams_maxmsgs:w.CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS,clustering_leafserver_streams_path:w.CLUSTERING_LEAFSERVER_STREAMS_PATH,clustering_nodename:w.CLUSTERING_NODENAME,clustering_tls_certificate:w.CLUSTERING_TLS_CERTIFICATE,clustering_tls_privatekey:w.CLUSTERING_TLS_PRIVATEKEY,clustering_tls_certificateauthority:w.CLUSTERING_TLS_CERT_AUTH,clustering_tls_insecure:w.CLUSTERING_TLS_INSECURE,clustering_tls_verify:w.CLUSTERING_TLS_VERIFY,clustering_loglevel:w.CLUSTERING_LOGLEVEL,clustering_republishmessages:w.CLUSTERING_REPUBLISHMESSAGES,clustering_databaselevel:w.CLUSTERING_DATABASELEVEL,customfunctions_network_port:w.HTTP_PORT,customfunctions_tls_certificate:w.TLS_CERTIFICATE,customfunctions_network_cors:w.HTTP_CORS,customfunctions_network_corsaccesslist:w.HTTP_CORSACCESSLIST,customfunctions_network_headerstimeout:w.HTTP_HEADERSTIMEOUT,customfunctions_network_https:w.CUSTOMFUNCTIONS_NETWORK_HTTPS,customfunctions_network_keepalivetimeout:w.HTTP_KEEPALIVETIMEOUT,customfunctions_tls_privatekey:w.TLS_PRIVATEKEY,customfunctions_tls_certificateauthority:w.TLS_CERTIFICATEAUTHORITY,customfunctions_network_timeout:w.HTTP_TIMEOUT,http_threads:w.THREADS_COUNT,threads:w.THREADS_COUNT,threads_count:w.THREADS_COUNT,threads_debug:w.THREADS_DEBUG,threads_debug_startingport:w.THREADS_DEBUG_STARTINGPORT,threads_debug_port:w.THREADS_DEBUG_PORT,threads_debug_host:w.THREADS_DEBUG_HOST,threads_debug_waitfordebugger:w.THREADS_DEBUG_WAITFORDEBUGGER,threads_maxheapmemory:w.THREADS_MAXHEAPMEMORY,http_session_affinity:w.HTTP_SESSIONAFFINITY,http_compressionthreshold:w.HTTP_COMPRESSIONTHRESHOLD,http_cors:w.HTTP_CORS,http_corsaccesslist:w.HTTP_CORSACCESSLIST,http_headerstimeout:w.HTTP_HEADERSTIMEOUT,http_keepalivetimeout:w.HTTP_KEEPALIVETIMEOUT,http_timeout:w.HTTP_TIMEOUT,http_port:w.HTTP_PORT,http_secureport:w.HTTP_SECUREPORT,http_mtls:w.HTTP_MTLS,http_mtls_user:w.HTTP_MTLS_USER,http_mtls_required:w.HTTP_MTLS_REQUIRED,customfunctions_processes:w.THREADS_COUNT,customfunctions_root:w.COMPONENTSROOT,localstudio_enabled:w.LOCALSTUDIO_ENABLED,logging_file:w.LOGGING_FILE,logging_level:w.LOGGING_LEVEL,logging_root:w.LOGGING_ROOT,logging_rotation_enabled:w.LOGGING_ROTATION_ENABLED,logging_rotation_compress:w.LOGGING_ROTATION_COMPRESS,logging_rotation_interval:w.LOGGING_ROTATION_INTERVAL,logging_rotation_maxsize:w.LOGGING_ROTATION_MAXSIZE,logging_rotation_path:w.LOGGING_ROTATION_PATH,logging_stdstreams:w.LOGGING_STDSTREAMS,logging_auditlog:w.LOGGING_AUDITLOG,logging_auditretention:w.LOGGING_AUDITRETENTION,logging_auditauthevents_logfailed:w.LOGGING_AUDITAUTHEVENTS_LOGFAILED,logging_auditauthevents_logsuccessful:w.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL,operationsapi_authentication_operationtokentimeout:w.AUTHENTICATION_OPERATIONTOKENTIMEOUT,operationsapi_authentication_refreshtokentimeout:w.AUTHENTICATION_REFRESHTOKENTIMEOUT,operationsapi_network_cors:w.OPERATIONSAPI_NETWORK_CORS,operationsapi_network_corsaccesslist:w.OPERATIONSAPI_NETWORK_CORSACCESSLIST,operationsapi_network_headerstimeout:w.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT,operationsapi_network_https:w.OPERATIONSAPI_NETWORK_HTTPS,operationsapi_network_keepalivetimeout:w.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT,operationsapi_network_port:w.OPERATIONSAPI_NETWORK_PORT,operationsapi_network_domainsocket:w.OPERATIONSAPI_NETWORK_DOMAINSOCKET,operationsapi_network_secureport:w.OPERATIONSAPI_NETWORK_SECUREPORT,operationsapi_tls_certificate:w.OPERATIONSAPI_TLS_CERTIFICATE,operationsapi_tls_privatekey:w.OPERATIONSAPI_TLS_PRIVATEKEY,operationsapi_tls_certificateauthority:w.OPERATIONSAPI_TLS_CERTIFICATEAUTHORITY,operationsapi_network_timeout:w.OPERATIONSAPI_NETWORK_TIMEOUT,operationsapi_root:w.ROOTPATH,databases:w.DATABASES,storage_path:w.STORAGE_PATH,ignorescripts:w.IGNORE_SCRIPTS,mqtt_network_port:w.MQTT_NETWORK_PORT,mqtt_websocket:w.MQTT_WEBSOCKET,mqtt_network_secureport:w.MQTT_NETWORK_SECUREPORT,mqtt_network_mtls:w.MQTT_NETWORK_MTLS,mqtt_network_mtls_certificateAuthority:w.MQTT_NETWORK_MTLS_CERTIFICATEAUTHORITY,mqtt_network_mtls_user:w.MQTT_NETWORK_MTLS_USER,mqtt_network_mtls_required:w.MQTT_NETWORK_MTLS_REQUIRED,mqtt_requireauthentication:w.MQTT_REQUIREAUTHENTICATION,analytics_aggregatePeriod:w.ANALYTICS_AGGREGATEPERIOD,authentication_authorizelocal:w.AUTHENTICATION_AUTHORIZELOCAL,authentication_cachettl:w.AUTHENTICATION_CACHETTL,authentication_enablesessions:w.AUTHENTICATION_ENABLESESSIONS,authentication_operationtokentimeout:w.AUTHENTICATION_OPERATIONTOKENTIMEOUT,authentication_refreshtokentimeout:w.AUTHENTICATION_REFRESHTOKENTIMEOUT,componentsroot:w.COMPONENTSROOT,tls_certificate:w.TLS_CERTIFICATE,tls_privatekey:w.TLS_PRIVATEKEY,tls_certificateauthority:w.TLS_CERTIFICATEAUTHORITY,tls_ciphers:w.TLS_CIPHERS};for(let e in w){let t=w[e];fO[t.toLowerCase()]=t}var vF={TABLES:"tables",PATH:"path",AUDIT_PATH:"auditPath"},BF={csv_file_load:"csv_file_load",csv_data_load:Z.CSV_DATA_LOAD,csv_url_load:Z.CSV_URL_LOAD,delete_files_before:"delete_files_before",delete_records_before:"delete_records_before",delete_audit_logs_before:"delete_audit_logs_before",delete_transaction_logs_before:"delete_transaction_logs_before",empty_trash:"empty_trash",export_local:"export_local",export_to_s3:"export_to_s3",import_from_s3:"import_from_s3"},HF={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"},xF={BIDIRECTIONAL:"BIDIRECTIONAL",OUTBOUND:"OUTBOUND",INBOUND:"INBOUND"},qF={VERSION_DEFAULT:"2.2.0"},GF={DEVELOPMENT:8192,DEFAULT:512},FF={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"},VF={ENOENT:"ENOENT",EACCES:"EACCES",EEXIST:"EEXIST"},EO={CREATED_TIME:"__createdtime__",UPDATED_TIME:"__updatedtime__"},$F=Symbol("metadata"),YF="__clustering__",KF=Object.values(EO),WF=15984864e5,hO={LESS:"<",LESS_OR_EQ:"<=",GREATER:">",GREATER_OR_EQ:">=",BETWEEN:"..."},QF=_O.invert(hO),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"},JF=111,XF=`\r
|
|
2
|
-
`,
|
|
3
|
-
`}a(
|
|
4
|
-
`).slice(1)){n=n.trim();let[i]=n.split(" ",1),o=n.slice(i.length+1).trim();t[i]===void 0&&(t[i]={}),t[i][r]=o}}))}catch(r){throw r}return Object.entries(t).filter(([,r])=>r.comm&&r.args&&r.ppid&&r.uid&&r["%cpu"]&&r["%mem"]&&r.args.includes(e)).map(([r,s])=>({pid:Number.parseInt(r,10),name:Dk.basename(s.comm),cmd:s.args,ppid:Number.parseInt(s.ppid,10),uid:Number.parseInt(s.uid,10),cpu:Number.parseFloat(s["%cpu"]),memory:Number.parseFloat(s["%mem"])}))}a(Pk,"findPs")});var Et=g((Lae,UO)=>{"use strict";var vk="__dbis__",Bk="__txns__",Hk="__environment_name__",xk="__dbi_defintion__",qk={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"},Gk=["__createdtime__","__updatedtime__"],Fk="\uFFFF",MO={TIMESTAMP:"timestamp",HASH_VALUE:"hash_value",USER_NAME:"user_name"},kk=Object.values(MO);UO.exports={AUDIT_STORE_NAME:Bk,INTERNAL_DBIS_NAME:vk,DBI_DEFINITION_NAME:xk,SEARCH_TYPES:qk,TIMESTAMP_NAMES:Gk,MAX_SEARCH_KEY_LENGTH:256,ENVIRONMENT_NAME_KEY:Hk,TRANSACTIONS_DBI_NAMES_ENUM:MO,TRANSACTIONS_DBIS:kk,OVERFLOW_MARKER:Fk}});var Ir=g((Mae,kO)=>{"use strict";var PO=M(),vO=Et(),BO={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},HO=a(e=>`${e} Check logs and try again.`,"CHECK_LOGS_WRAPPER"),xO={500:HO("There was an error processing your request."),400:"Invalid request"},Vk=xO[BO.INTERNAL_SERVER_ERROR],$k={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.`},Yk={CONFIG_VALIDATION:e=>`HarperDB config file validation error: ${e}`},Kk={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"},Wk={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 ${vO.INTERNAL_DBIS_NAME}`,CANNOT_DROP_INTERNAL_DBIS_NAME:`cannot drop a dbi named ${vO.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"},Qk={ATTR_NAME_LENGTH_ERR:e=>`transaction aborted due to attribute name ${e} being too long. Attribute names cannot be longer than ${PO.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 ${PO.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"},qO={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"},zk={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."},Jk={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`},Xk={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"},jk={OUTER_JOIN_TRANSLATION_ERROR:"There was an error translating the final SQL outer join data."},Zk={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`},GO={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.`},FO={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}`},eV={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."},tV={CLUSTERING_NOT_ENABLED:"Clustering must be enabled to perform this operation."},rV={...qO,...Kk,...$k,...zk,...Jk,...Xk,...jk,...Zk,...Qk,...GO,...FO,...eV,...tV,...Yk};kO.exports={CHECK_LOGS_WRAPPER:HO,HDB_ERROR_MSGS:rV,DEFAULT_ERROR_MSGS:xO,DEFAULT_ERROR_RESP:Vk,HTTP_STATUS_CODES:BO,LMDB_ERRORS_ENUM:Wk,AUTHENTICATION_ERROR_MSGS:qO,VALIDATION_ERROR_MSGS:GO,ITC_ERRORS:FO}});var se=g((Pae,YO)=>{"use strict";var Go=Ir(),sV=$(),nV=M(),Xl=class extends Error{static{a(this,"HdbError")}constructor(t,r,s,n,i){super(),Error.captureStackTrace(this,VO),this.statusCode=s||Go.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR,this.http_resp_msg=r||(Go.DEFAULT_ERROR_MSGS[s]?Go.DEFAULT_ERROR_MSGS[s]:Go.DEFAULT_ERROR_MSGS[Go.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR]),this.message=t.message?t.message:this.http_resp_msg,this.type=t.name,n&&(this.logLevel=n),typeof this.message!="string"&&(this.stack=t.stack),i&&sV[n](i)}},Mh=class extends Error{static{a(this,"ClientError")}constructor(t,r){if(t instanceof Error)return t.statusCode=r||400,t;super(t),this.statusCode=r||400}},Uh=class extends Error{static{a(this,"ServerError")}constructor(t,r){super(t),this.statusCode=r||500}};function VO(e,t,r,s=nV.LOG_LEVELS.ERROR,n=null,i=!1){if($O(e))return e;let o=new Xl(e,t,r,s,n);return i&&delete o.stack,o}a(VO,"handleHDBError");function $O(e){return e.__proto__.constructor.name===Xl.name}a($O,"isHDBError");YO.exports={isHDBError:$O,handleHDBError:VO,ClientError:Mh,ServerError:Uh,hdb_errors:Go}});var Je=g((Bae,jO)=>{"use strict";var hc=M(),iV=Q(),ir=ee(),mc=require("path"),oV=require("minimist"),KO=require("fs-extra"),WO=require("lodash");ir.initSync();var{CONFIG_PARAMS:jn,DATABASES_PARAM_CONFIG:_c,SYSTEM_SCHEMA_NAME:jl}=hc,dc,fc,Ec;function QO(){if(dc!==void 0)return dc;if(ir.getHdbBasePath()!==void 0)return dc=ir.get(jn.STORAGE_PATH)||mc.join(ir.getHdbBasePath(),hc.DATABASES_DIR_NAME),dc}a(QO,"getBaseSchemaPath");function zO(){if(fc!==void 0)return fc;if(ir.getHdbBasePath()!==void 0)return fc=XO(jl),fc}a(zO,"getSystemSchemaPath");function JO(){if(Ec!==void 0)return Ec;if(ir.getHdbBasePath()!==void 0)return Ec=ir.get(hc.CONFIG_PARAMS.STORAGE_AUDIT_PATH)||mc.join(ir.getHdbBasePath(),hc.TRANSACTIONS_DIR_NAME),Ec}a(JO,"getTransactionAuditStoreBasePath");function aV(e,t){let r=ir.get(jn.DATABASES)?.[e];return t&&r?.tables?.[t]?.auditPath||r?.auditPath||mc.join(JO(),e.toString())}a(aV,"getTransactionAuditStorePath");function XO(e,t){e=e.toString(),t=t&&t.toString();let r=ir.get(hc.CONFIG_PARAMS.DATABASES)?.[e];return t&&r?.tables?.[t]?.path||r?.path||mc.join(QO(),e)}a(XO,"getSchemaPath");function cV(e,t){e=e.toString(),t=t.toString();let r=process.env;Object.assign(r,oV(process.argv));let s=r[jn.DATABASES.toUpperCase()];if(s){let i;try{i=JSON.parse(s)}catch(o){if(!iV.isObject(s))throw o;i=s}for(let o of i){let c=o[jl];if(!c)continue;let u=ir.get(jn.DATABASES);u=u??{};let _=c?.tables?.[t]?.[_c.PATH];if(_)return WO.set(u,[jl,_c.TABLES,t,_c.PATH],_),ir.setProperty(jn.DATABASES,u),_;let l=c?.[_c.PATH];if(l)return WO.set(u,[jl,_c.PATH],l),ir.setProperty(jn.DATABASES,u),l}}let n=r[jn.STORAGE_PATH.toUpperCase()];if(n){if(!KO.pathExistsSync(n))throw new Error(n+" does not exist");let i=mc.join(n,e);return KO.mkdirsSync(i),ir.setProperty(jn.STORAGE_PATH,n),i}return zO()}a(cV,"initSystemSchemaPaths");function uV(){dc=void 0,fc=void 0,Ec=void 0}a(uV,"resetPaths");jO.exports={getBaseSchemaPath:QO,getSystemSchemaPath:zO,getTransactionAuditStorePath:aV,getTransactionAuditStoreBasePath:JO,getSchemaPath:XO,initSystemSchemaPaths:cV,resetPaths:uV}});var wr=g((Gae,sb)=>{"use strict";var lV=Ir().LMDB_ERRORS_ENUM,xae=require("lmdb"),_V=Et(),qae=require("buffer").Buffer,{OVERFLOW_MARKER:ZO,MAX_SEARCH_KEY_LENGTH:Zl}=_V,eb=["number","string","symbol","boolean","bigint"];function dV(e){if(e=e?.primaryStore||e,!e)throw new Error(lV.ENV_REQUIRED)}a(dV,"validateEnv");function fV(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(fV,"stringifyData");function EV(e){return e instanceof Date?e.valueOf():e}a(EV,"convertKeyValueToWrite");function hV(e,t){if(e===null)return t?[null]:void 0;if(e===void 0)return;if(eb.includes(typeof e))return e.length>Zl?[e.slice(0,Zl)+ZO]:[e];let r;if(Array.isArray(e)){r=[];for(let s=0,n=e.length;s<n;s++){let i=e[s];if(eb.includes(typeof i))i.length>Zl?r.push(i.slice(0,Zl)+ZO):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(hV,"getIndexedValues");var e_=0,tb=0;function rb(){tb=Date.now()-performance.now()}a(rb,"adjustStartTime");rb();var mV=6e4;setInterval(rb,mV).unref();function pV(){let e=performance.now()+tb;return e>e_?(e_=e,e):(e_+=488e-6,e_)}a(pV,"getNextMonotonicTime");sb.exports={validateEnv:dV,stringifyData:fV,convertKeyValueToWrite:EV,getNextMonotonicTime:pV,getIndexedValues:hV}});var nb,bs,Ph,pc=Re(()=>{nb=require("events"),bs=class extends nb.EventEmitter{static{a(this,"IterableEventQueue")}resolveNext;queue;hasDataListeners;[Symbol.asyncIterator](){let t=new Ph;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)}},Ph=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 Bi={};Ye(Bi,{server:()=>rt});var ib,rt,or=Re(()=>{ib=require("../index"),rt={};(0,ib._assignPackageExport)("server",rt)});var Hh={};Ye(Hh,{loadGQLSchema:()=>gV,start:()=>Bh,startOnMainThread:()=>TV});function Bh({ensureTable:e}){return{handleFile:t,setupFile:t};async function t(r,s,n,i){let{parse:o,Source:c,Kind:u,NamedTypeNode:_,StringValueNode:l}=await import("graphql"),d=o(new c(r.toString(),n)),f=new Map,E=[],h;for(let S of d.definitions)switch(S.kind){case u.OBJECT_TYPE_DEFINITION:let H=function(P){if(P.kind==="NonNullType"){let X=H(P.type);return X.nullable=!1,X}if(P.kind==="ListType")return{type:"array",elements:H(P.type)};let B={type:P.name?.value};return Object.defineProperty(B,"location",{value:P.loc.startToken}),B};a(H,"getProperty");let T=S.name.value,b=[],R={table:null,database:null,properties:b};f.set(T,R);for(let P of S.directives){if(P.name.value==="table"){for(let k of P.arguments)R[k.name.value]=k.value.value;R.schema&&(R.database=R.schema),R.table||(R.table=T),R.audit&&(R.audit=R.audit!=="false"),R.attributes=R.properties,E.push(R)}if(P.name.value==="sealed"&&(R.sealed=!0),P.name.value==="export"){R.export=!0;for(let k of P.arguments)k.name.value==="name"&&(R.export={name:k.value.value})}}let L=!1;for(let P of S.fields){let k=H(P.type);k.name=P.name.value,b.push(k);for(let B of P.directives)if(B.name.value==="primaryKey")L?console.warn("Can not define two attributes as a primary key"):(k.isPrimaryKey=!0,L=!0);else if(B.name.value==="indexed")k.indexed=!0;else if(B.name.value==="relationship"){let X={};for(let z of B.arguments)X[z.name.value]=z.value.value;k.relationship=X}else if(B.name.value==="createdTime")k.assignCreatedTime=!0;else if(B.name.value==="updatedTime")k.assignUpdatedTime=!0;else if(B.name.value==="expiresAt")k.expiresAt=!0;else if(B.name.value==="allow"){let X=k.authorizedRoles=[];for(let z of B.arguments)z.name.value==="role"&&X.push(z.value.value)}}R.type=T,T==="Query"&&(h=R)}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):SV.includes(S.type)||(0,ob.getWorkerIndex)()===0&&console.error(`The type ${S.type} is unknown at line ${S.location.line}, column ${S.location.column}, in ${n}`)}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,vh.dirname)(s),S.tableClass):i.set((0,vh.dirname)(s)+"/"+(S.export.name||S.type),S.tableClass))}}var vh,ob,SV,TV,gV,ab=Re(()=>{vh=require("path");Ae();ob=x(Ke()),SV=["ID","Int","Float","Long","String","Boolean","Date","Bytes","Any","BigInt"];a(Bh,"start");TV=Bh,gV=Bh({ensureTable:ut}).handleFile});async function t_(e){return RV?(Sc||(Sc=AV(bV)),(await(await Sc).import(e)).namespace):import(e)}async function AV(e){let{StaticModuleRecord:t}=await import("@endo/static-module-record");return require("ses"),lockdown({domainTaming:"unsafe",consoleTaming:"unsafe",errorTaming:"unsafe",errorTrapping:"none",stackFiltering:"verbose"}),Sc=new Compartment({console,Math,Date,fetch:OV,...e()},{},{name:"h-dapp",resolveHook(r,s){return r==="harperdb"?"harperdb":(r=new URL(r,s).toString(),(0,ub.extname)(r)||(r+=".js"),r)},importHook:async r=>{if(r==="harperdb")return{imports:[],exports:["Resource","tables","databases"],execute(n){Object.assign(n,{Resource:Ft,tables:Cr,databases:st})}};let s=await(0,cb.readFile)(new URL(r),{encoding:"utf-8"});return new t(s,r)}}),Sc}function OV(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 bV(){return{Resource:Ft,tables:Cr}}var cb,ub,RV,Sc,xh=Re(()=>{Ns();Ae();cb=require("fs/promises"),ub=require("path"),RV=!1;a(t_,"secureImport");a(AV,"getCompartment");a(OV,"secureOnlyFetch");a(bV,"getGlobalVars")});var Gh={};Ye(Gh,{handleFile:()=>NV});async function NV(e,t,r,s){let n=new Map,i=(0,lb.pathToFileURL)(r).toString(),o=await t_(i);u(o.default)&&s.set((0,qh.dirname)(t),o.default),c(o,(0,qh.dirname)(t));function c(_,l){for(let d in _){let f=_[d];u(f)?s.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"),n}var lb,qh,_b=Re(()=>{lb=require("url");xh();qh=require("path");a(NV,"handleFile")});var kh={};Ye(kh,{start:()=>yV});function yV({resources:e}){e.set("login",Fh),e.loginPath=t=>"/login?redirect="+encodeURIComponent(t.url)}var Fh,db=Re(()=>{Ns();a(yV,"start");Fh=class extends Ft{static{a(this,"Login")}static async get(t,r,s){}static async post(t,r,s){let{username:n,password:i,redirect:o}=r;return{data:await s.login(n,i)}}}});var Tb={};Ye(Tb,{parse:()=>$h,streamAsJSON:()=>Tc,stringify:()=>Hi});function Tc(e){return new Vh({value:e})}function fb(e){return console.error(e),JSON.stringify(e.toString())}function Eb(e,t,r){return e?.then?r?e.then(t,r):e.then(t):t(e)}function Hi(e){try{return JSON.stringify(e)??"null"}catch(t){if(t===pb)return Sb(e);if(t.resolution)return t.resolution.then(()=>Hi(e));throw t}}function Sb(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 s=0;s<e.length;s++)s>0&&(r+=","),r+=Sb(e[s]);return r+"]"}else{r="{";let s=!0;for(let n in e)s?s=!1:r+=",",r+=JSON.stringify(n)+":"+Hi(e[n]);return r+"}"}}else{if(t==="string")return JSON.stringify(e);if(t==="undefined")return"null"}return e.toString()}function $h(e){return CV.test(e)?IV.parse(e):JSON.parse(e)}var hb,mb,IV,wV,pb,Vh,CV,Yh=Re(()=>{hb=require("stream"),mb=x(require("json-bigint-fixes")),IV=(0,mb.default)({useNativeBigInt:!0}),wV=1e4,pb={};BigInt.prototype.toJSON=function(){throw pb};a(Tc,"streamAsJSON");Vh=class extends hb.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],s=t[Symbol.iterator];if((s||r)&&!t.then){yield"[";let n=!0;if((r||s)&&!(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 n?n=!1:yield",",yield*this.serialize(o.value)}for(let i of t)n?n=!1:yield",",yield*this.serialize(i);yield"]";return}if(t.then)try{yield t.then(n=>this.serialize(n),fb)}catch(n){yield fb(n)}else yield Hi(t)}else yield Hi(t)}_read(){if(!this._amReading){if(this._amReading=!0,this.done)return this.push(null);Eb(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>wV?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 Eb(this.readIterator(t.childIterator),s=>{if(s)return t.childIterator=null,this.readIterator(t)});do{let s=t.next();if(s.done)return!0;if(r=s.value,r==null)r="null";else{if(r.then)return this.flush(),Promise.resolve(r).then(n=>{if(n&&typeof n.return=="function")return t.childIterator=n,this.readIterator(t);if(this.push(n+""))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 s of this.activeIterators)t?s.throw(t):s.return();r()}};a(fb,"handleError");a(Eb,"when");a(Hi,"stringify");a(Sb,"jsStringify");CV=/-?\d{16,}/;a($h,"parse")});var Mb=g((rce,Lb)=>{"use strict";var Kh=require("recursive-iterator"),DV=require("alasql"),Wh=require("clone"),gb=Q(),{handleHDBError:Rb,hdb_errors:LV}=se(),{HDB_ERROR_MSGS:Ab,HTTP_STATUS_CODES:Ob}=LV,{getDatabases:MV}=(Ae(),ne(Ge)),UV=["DISTINCT_ARRAY"],bb=Symbol("validateTables"),Qh=Symbol("validateTable"),tce=Symbol("getAllColumns"),Nb=Symbol("validateAllColumns"),r_=Symbol("findColumn"),yb=Symbol("validateOrderBy"),gc=Symbol("validateSegment"),zh=Symbol("validateColumn"),Ib=Symbol("setColumnsForTable"),wb=Symbol("checkColumnsForAsterisk"),Cb=Symbol("validateGroupBy"),Db=Symbol("hasColumns"),Jh=class{static{a(this,"SelectValidator")}constructor(t){this.statement=t,this.attributes=[]}validate(){if(!this.statement)throw new Error("invalid sql statement");this[bb](),this[wb](),this[Nb]()}[bb](){if(this[Db]()){if(!this.statement.from||this.statement.from.length===0)throw"no from clause";this.statement.from.forEach(t=>{this[Qh](t)}),this.statement.joins&&this.statement.joins.forEach(t=>{t.table.as=t.as,this[Qh](t.table)})}}[Db](){let t=!1,r=new Kh(this.statement);for(let{node:s,path:n}of r)if(s&&s.columnid){t=!0;break}return t}[Qh](t){if(!t.databaseid)throw`schema not defined for table ${t.tableid}`;let r=MV();if(!r[t.databaseid])throw Rb(new Error,Ab.SCHEMA_NOT_FOUND(t.databaseid),Ob.NOT_FOUND);if(!r[t.databaseid][t.tableid])throw Rb(new Error,Ab.TABLE_NOT_FOUND(t.databaseid,t.tableid),Ob.NOT_FOUND);r[t.databaseid][t.tableid].attributes.forEach(n=>{let i=Wh(n);i.table=Wh(t),this.attributes.push(i)})}[r_](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)}[wb](){let t=new Kh(this.statement.columns);for(let{node:r,path:s}of t)r&&r.columnid==="*"&&s.indexOf("expression")<0&&this[Ib](r.tableid)}[Ib](t){this.attributes.forEach(r=>{(!t||t&&(r.table.tableid===t||r.table.as===t))&&!r.relation&&this.statement.columns.push(new DV.yy.Column({columnid:r.attribute,tableid:r.table.as?r.table.as:r.table.tableid}))})}[Nb](){this[gc](this.statement.columns,!1),this[gc](this.statement.joins,!1),this[gc](this.statement.where,!1),this[Cb](this.statement.group,!1),this[gc](this.statement.order,!0)}[gc](t,r){if(!t)return;let s=new Kh(t),n=[];for(let{node:i,path:o}of s)!gb.isEmpty(i)&&!gb.isEmpty(i.columnid)&&i.columnid!=="*"&&(r?this[yb](i):n.push(this[zh](i)));return n}[Cb](t){if(!t)return;let r=[];if(this.statement.columns.forEach(s=>{if(!(s.funcid&&UV.indexOf(s.funcid.toUpperCase())>=0)){if(!s.aggregatorid&&!s.columnid){let n=Wh(s);delete n.as,r.push(n)}else if(s.columnid){let n=this[r_](s)[0];n&&r.push(n)}}}),this.statement.group.forEach(s=>{let n=null;if(!s.columnid)r.forEach((i,o)=>{if(i.toString()===s.toString()){n=i,r.splice(o,1);return}});else{let i=this[r_](s);if(!i||i.length===0)throw`unknown column '${s.toString()}' in group by`;if(i.length>1)throw`ambiguously defined column '${s.toString()}' in group by`;r.forEach((o,c)=>{if(o.attribute===i[0].attribute&&o.table.tableid===i[0].table.tableid){n=o,r.splice(c,1);return}})}if(!n)throw`group by column '${s.toString()}' must be in select`}),r.length>0)throw`select column '${r[0].attribute?r[0].attribute:r[0].toString()}' must be in group by`}[yb](t){let r=this.statement.columns.filter(s=>s.as===t.columnid);if(r.length>1)throw`ambiguous column reference ${(t.tableid?t.tableid+".":"")+t.columnid} in order by`;r.length===0&&this[zh](t)}[zh](t){let r=this[r_](t),s=(t.tableid?t.tableid+".":"")+t.columnid;if(r.length===0)throw`unknown column ${s}`;if(r.length>1)throw`ambiguous column reference ${s}`;return r[0]}};Lb.exports=Jh});var Pb=g((nce,Ub)=>{"use strict";var Xh=class{static{a(this,"BridgeMethods")}createSchema(){throw new Error("createSchema bridge method is not defined")}dropSchema(){throw new Error("dropSchema bridge method is not defined")}createTable(){throw new Error("createTable bridge method is not defined")}dropTable(){throw new Error("dropTable bridge method is not defined")}createRecords(){throw new Error("createRecords bridge method is not defined")}updateRecords(){throw new Error("updateRecords bridge method is not defined")}async upsertRecords(){throw new Error("upsertRecords bridge method is not defined")}deleteRecords(){throw new Error("deleteRecords bridge method is not defined")}createAttribute(){throw new Error("createAttribute bridge method is not defined")}dropAttribute(){throw new Error("dropAttribute bridge method is not defined")}searchByConditions(){throw new Error("searchByConditions bridge method is not defined")}searchByHash(){throw new Error("searchByHash bridge method is not defined")}searchByValue(){throw new Error("searchByValue bridge method is not defined")}getDataByHash(){throw new Error("getDataByHash bridge method is not defined")}getDataByValue(){throw new Error("getDataByValue bridge method is not defined")}deleteRecordsBefore(){throw new Error("deleteRecordsBefore bridge method is not defined")}deleteAuditLogsBefore(){throw new Error("deleteAuditLogsBefore bridge method is not defined")}async readAuditLog(){throw new Error("readAuditLog bridge method is not defined")}};Ub.exports=Xh});var Bb=g((oce,vb)=>{"use strict";var jh=class{static{a(this,"DBIDefinition")}constructor(t=!1,r=!1){this.dup_sort=t,this.is_hash_attribute=r,this.useVersions=r}};vb.exports=jh});var Gb={};Ye(Gb,{HAS_EXPIRATION:()=>im,LAST_TIMESTAMP_PLACEHOLDER:()=>Oc,LOCAL_TIMESTAMP:()=>PV,METADATA:()=>Rc,NO_TIMESTAMP:()=>em,PENDING_LOCAL_TIME:()=>om,PREVIOUS_TIMESTAMP_PLACEHOLDER:()=>nm,RecordEncoder:()=>sm,TIMESTAMP_ASSIGN_LAST:()=>BV,TIMESTAMP_ASSIGN_NEW:()=>xb,TIMESTAMP_ASSIGN_PREVIOUS:()=>qb,TIMESTAMP_PLACEHOLDER:()=>s_,TIMESTAMP_RECORD_PREVIOUS:()=>tm,getUpdateRecord:()=>am,handleLocalTimeForGets:()=>a_});function xV(){return Ac[0]=Ac[0]^64,vV.getFloat64(0)}function a_(e){let t=e.getEntry;e.readCount=0,e.cachePuts=!1,e.getEntry=function(i,o){e.readCount++;let c=t.call(this,i,o),u=c?.value,_=u?.[Rc];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?.[Rc]>=0?c.value:c};let s=e.getRange;e.getRange=function(i){let o=s.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[Rc];return _>=0&&(c.metadataFlags=_,c.localTime=u.localTime,c.value=u.value,u.expiresAt>0&&(c.expiresAt=u.expiresAt)),c})};let n=e.useReadTransaction();if(n.done(),!n.done.isTracked){let i=n.constructor,o=n.use,c=n.done;i.prototype.use=function(){this.timerTracked||(this.timerTracked=!0,xi.push(new WeakRef(this))),o.call(this)},i.prototype.done=function(){if(c.call(this),this.isDone)for(let u=0;u<xi.length;u++){let _=xi[u].deref();(!_||_.isDone||_.isCommitted)&&xi.splice(u--,1)}},i.prototype.done.isTracked=!0}return e}function am(e,t,r){return function(s,n,i,o,c=-1,u,_,l,d="put",f,E){if(f||u==null?Fo=i?.localTime?tm|qb:em:Fo=u?i?.localTime?tm|16384:xb|16384:em,l>0&&(c|=im),i_=c,rm=l,i?.version===o&&u===!1)throw new Error("Must retain local time if version is not changed");let h={version:o,instructedWrite:Fo>0},p;try{f&&(h.ifVersion=p=i?.version??null);let S=e.put(s,n,h);if(u){let T=_?.user?.username;if(E&&(n_=e.encoder.encode(E)),f&&i?.localTime){let b=i?.localTime,R=r.get(b);if(R){let L=Lt(R).previousLocalTime;return r.put(b,o_(o,t,s,L,T,d,n_),{ifVersion:p}),S}}r.put(Oc,o_(o,t,s,i?.localTime?1:0,T,d,n_),{append:d!=="invalidate",instructedWrite:!0,ifVersion:p})}return S}catch(S){throw S.message+=" id: "+s+" options: "+h,S}}}var Hb,Zh,s_,Oc,nm,PV,Rc,Ac,vV,em,xb,BV,qb,tm,im,om,HV,n_,Fo,i_,rm,sm,xi,bc=Re(()=>{Hb=require("msgpackr");qi();Zh=x($()),s_=new Uint8Array([1,1,1,1,4,64,0,0]),Oc=new Uint8Array([1,1,1,1,1,0,0,0]),nm=new Uint8Array([1,1,1,1,3,64,0,0]),PV=Symbol("local-timestamp"),Rc=Symbol("metadata"),Ac=new Uint8Array(8),vV=new DataView(Ac.buffer,0,8),em=0,xb=0,BV=1,qb=3,tm=4,im=16,om=1,Fo=0,i_=-1,rm=0,sm=class extends Hb.Encoder{static{a(this,"RecordEncoder")}constructor(t){t.useBigIntExtension=!0,super(t);let r=this.encode;this.encode=function(s,n){if(Fo||i_>=0){let i=0,o=Fo;o&&(i+=8,Fo=0);let c=i_,u=rm;c>=0&&(i+=2,i_=-1,u&&(i+=8,rm=0));let _=HV=r.call(this,s,n|2048|i);n_=_.subarray((_.start||0)+i,_.end);let l=_.start||0;return o&&(s_[4]=o,s_[5]=o>>8,_.set(s_,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,s,n)}}decode(t,r){let s=r?.start||0,n=r>-1?r:r?.end||t.length,i=t[s],o=0;try{if(i<32&&n>2){let c=s,u;if(i===2){if(t.copy)t.copy(Ac,0,c),c+=8;else for(let d=0;d<8;d++)Ac[d]=t[c++];u=xV(),i=t[c]}let _;i<32&&(o=i,c+=2,o&im&&(_=(t.dataView||(t.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength))).getFloat64(c),c+=8));let l=super.decode(t.subarray(c,n),n-c);return{localTime:u,value:l,[Rc]:o,expiresAt:_}}return super.decode(t,r)}catch(c){throw c.message+=", data: "+t.slice(0,40).toString("hex"),c}}};a(xV,"getTimestamp");a(a_,"handleLocalTimeForGets");xi=[];setInterval(()=>{for(let e=0;e<xi.length;e++){let t=xi[e].deref();!t||t.isDone||t.isCommitted?xi.splice(e--,1):t.notCurrent&&(t.openTimer?(t.openTimer>3&&(t.openTimer>60?(Zh.error("Read transaction detected that has been open too long (over 15 minutes), ending transaction",t),t.done()):Zh.error("Read transaction detected that has been open too long (over one minute), make sure read transactions are quickly closed",t)),t.openTimer++):t.openTimer=1)}},15e3).unref();a(am,"getUpdateRecord")});var c_=g((_ce,kb)=>{"use strict";var Fb=ee(),qV=M(),{RecordEncoder:GV}=(bc(),ne(Gb)),lce=require("fs");Fb.initSync();var FV=Fb.get(qV.CONFIG_PARAMS.STORAGE_CACHING)!==!1,cm=class{static{a(this,"OpenDBIObject")}constructor(t,r=!1){this.dupSort=t===!0,this.encoding=t?"ordered-binary":"msgpack",this.useVersions=r,this.sharedStructuresKey=Symbol.for("structures"),r&&(this.cache=FV&&{validated:!0},this.randomAccessStructure=!0,this.freezeData=!0,this.encoder={Encoder:GV})}};kb.exports=cm});var l_=g((fce,Vb)=>{"use strict";var Dr=ee(),ss=M();Dr.initSync();var u_=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=Dr.get(ss.CONFIG_PARAMS.STORAGE_WRITEASYNC)===!0||Dr.get(ss.CONFIG_PARAMS.STORAGE_WRITEASYNC)==="true"||Dr.get(ss.CONFIG_PARAMS.STORAGE_WRITEASYNC)==="TRUE",Dr.get(ss.CONFIG_PARAMS.STORAGE_OVERLAPPINGSYNC)!==void 0&&(this.overlappingSync=Dr.get(ss.CONFIG_PARAMS.STORAGE_OVERLAPPINGSYNC)),Dr.get(ss.CONFIG_PARAMS.STORAGE_MAXFREESPACETOLOAD)&&(this.maxFreeSpaceToLoad=Dr.get(ss.CONFIG_PARAMS.STORAGE_MAXFREESPACETOLOAD)),Dr.get(ss.CONFIG_PARAMS.STORAGE_MAXFREESPACETORETAIN)&&(this.maxFreeSpaceToRetain=Dr.get(ss.CONFIG_PARAMS.STORAGE_MAXFREESPACETORETAIN)),Dr.get(ss.CONFIG_PARAMS.STORAGE_PAGESIZE)&&(this.pageSize=Dr.get(ss.CONFIG_PARAMS.STORAGE_PAGESIZE)),this.noReadAhead=Dr.get(ss.CONFIG_PARAMS.STORAGE_NOREADAHEAD)}};Vb.exports=u_;u_.MAX_DBS=1e4});var We=g((hce,Zb)=>{"use strict";var lm=require("lmdb"),ys=require("fs-extra"),Lr=require("path"),__=wr(),Kb=$(),ar=Ir().LMDB_ERRORS_ENUM,d_=Bb(),_m=c_(),Wb=l_(),Zn=Et(),$b=M(),{table:kV,resetDatabases:VV}=(Ae(),ne(Ge)),Yb=ee(),Is=Zn.INTERNAL_DBIS_NAME,Qb=Zn.DBI_DEFINITION_NAME,$V="data.mdb",YV="lock.mdb",Nc=".mdb",KV="-lock",um=class{static{a(this,"TransactionCursor")}constructor(t,r,s=!1){this.dbi=ns(t,r),this.key_type=this.dbi[Zn.DBI_DEFINITION_NAME].key_type,this.is_hash_attribute=this.dbi[Zn.DBI_DEFINITION_NAME].is_hash_attribute,this.txn=t.beginTxn({readOnly:s===!1}),this.cursor=new lm.Cursor(this.txn,this.dbi)}close(){this.cursor.close(),this.txn.abort()}commit(){this.cursor.close(),this.txn.commit()}};function f_(e,t){if(e===void 0)throw new Error(ar.BASE_PATH_REQUIRED);if(t===void 0)throw new Error(ar.ENV_NAME_REQUIRED)}a(f_,"pathEnvNameValidation");async function dm(e,t,r=!0){try{await ys.access(e)}catch(s){throw s.code==="ENOENT"?new Error(ar.INVALID_BASE_PATH):s}try{let s=Lr.join(e,t+Nc);return await ys.access(s,ys.constants.R_OK|ys.constants.F_OK),s}catch(s){if(s.code==="ENOENT")if(r)try{return await ys.access(Lr.join(e,t,$V),ys.constants.R_OK|ys.constants.F_OK),Lr.join(e,t)}catch(n){if(n.code==="ENOENT")throw new Error(ar.INVALID_ENVIRONMENT)}else throw new Error(ar.INVALID_ENVIRONMENT);throw s}}a(dm,"validateEnvironmentPath");function E_(e,t){if(__.validateEnv(e),t===void 0)throw new Error(ar.DBI_NAME_REQUIRED)}a(E_,"validateEnvDBIName");async function WV(e,t,r=!1,s=!1){f_(e,t);let n=Lr.basename(e);t=t.toString();let i=Yb.get($b.CONFIG_PARAMS.DATABASES);i||Yb.setProperty($b.CONFIG_PARAMS.DATABASES,i={}),i[n]||(i[n]={}),i[n].path=e;try{return await dm(e,t,s),zb(e,t,r)}catch(o){if(o.message===ar.INVALID_ENVIRONMENT){let c=Lr.join(e,t);await ys.mkdirp(s?c:e);let u=new Wb(s?c:c+Nc,!1),_=lm.open(u);_.dbis=Object.create(null);let l=new _m(!1);_.openDB(Is,l),global.lmdb_map===void 0&&(global.lmdb_map=Object.create(null));let d=fm(e,t,r);return _[Zn.ENVIRONMENT_NAME_KEY]=d,global.lmdb_map[d]=_,_}throw o}}a(WV,"createEnvironment");async function QV(e,t,r,s=!0){f_(e,t),t=t.toString();let n=Lr.join(e,t);return kV({table:t,database:Lr.parse(e).name,path:n,attributes:[{name:"id",isPrimaryKey:!0}]})}a(QV,"copyEnvironment");async function zb(e,t,r=!1){f_(e,t),t=t.toString();let s=fm(e,t,r);if(global.lmdb_map===void 0&&(global.lmdb_map=Object.create(null)),global.lmdb_map[s]!==void 0)return global.lmdb_map[s];let n=await dm(e,t),i=Lr.join(e,t+Nc),o=n!=i,c=new Wb(n,o),u=lm.open(c);u.dbis=Object.create(null);let _=Xb(u);for(let l=0;l<_.length;l++)ns(u,_[l]);return u[Zn.ENVIRONMENT_NAME_KEY]=s,global.lmdb_map[s]=u,u}a(zb,"openEnvironment");async function zV(e,t,r=!1){f_(e,t),t=t.toString();let s=Lr.join(e,t+Nc),n=await dm(e,t);if(global.lmdb_map!==void 0){let i=fm(e,t,r);if(global.lmdb_map[i]){let o=global.lmdb_map[i];await Jb(o),delete global.lmdb_map[i]}}await ys.remove(n),await ys.remove(n===s?n+KV:Lr.join(Lr.dirname(n),YV))}a(zV,"deleteEnvironment");async function Jb(e){__.validateEnv(e);let t=e[Zn.ENVIRONMENT_NAME_KEY];await e.close(),t!==void 0&&global.lmdb_map!==void 0&&delete global.lmdb_map[t]}a(Jb,"closeEnvironment");function fm(e,t,r=!1){let n=`${Lr.basename(e)}.${t}`;return r===!0&&(n=`txn.${n}`),n}a(fm,"getCachedEnvironmentName");function JV(e){__.validateEnv(e);let t=Object.create(null),r=ns(e,Is);for(let{key:s,value:n}of r.getRange({start:!1}))if(s!==Is)try{t[s]=Object.assign(new d_,n)}catch{Kb.warn(`an internal error occurred: unable to parse DBI Definition for ${s}`)}return t}a(JV,"listDBIDefinitions");function Xb(e){__.validateEnv(e);let t=[],r=ns(e,Is);for(let{key:s}of r.getRange({start:!1}))s!==Is&&t.push(s);return t}a(Xb,"listDBIs");function XV(e,t){let s=ns(e,Is).getEntry(t),n=new d_;if(s!==void 0){try{n=Object.assign(n,s.value)}catch{Kb.warn(`an internal error occurred: unable to parse DBI Definition for ${s}`)}return n}}a(XV,"getDBIDefinition");function jb(e,t,r,s=!r){if(E_(e,t),t=t.toString(),t===Is)throw new Error(ar.CANNOT_CREATE_INTERNAL_DBIS_NAME);try{return ns(e,t)}catch(n){if(n.message===ar.DBI_DOES_NOT_EXIST){let i=new _m(r,s===!0),o=e.openDB(t,i),c=new d_(r===!0,s);return o[Qb]=c,ns(e,Is).putSync(t,c),e.dbis[t]=o,o}throw n}}a(jb,"createDBI");function ns(e,t){if(E_(e,t),t=t.toString(),e.dbis[t]!==void 0)return e.dbis[t];let r;if(t!==Is?r=XV(e,t):r=new d_,r===void 0)throw new Error(ar.DBI_DOES_NOT_EXIST);let s;try{let n=new _m(r.dup_sort,r.useVersions);if(s=e.openDB(t,n),s.db===void 0)throw new Error("MDB_NOTFOUND")}catch(n){throw n.message.includes("MDB_NOTFOUND")===!0?new Error(ar.DBI_DOES_NOT_EXIST):n}return s[Qb]=r,e.dbis[t]=s,s}a(ns,"openDBI");function jV(e,t){E_(e,t),t=t.toString();let r=ns(e,t),s=r.getStats();return r[Zn.DBI_DEFINITION_NAME].is_hash_attribute&&s.entryCount>0&&s.entryCount--,s}a(jV,"statDBI");async function ZV(e,t){try{let r=Lr.join(e,t+Nc);return(await ys.stat(r)).size}catch{throw new Error(ar.INVALID_ENVIRONMENT)}}a(ZV,"environmentDataSize");function e$(e,t){if(E_(e,t),t=t.toString(),t===Is)throw new Error(ar.CANNOT_DROP_INTERNAL_DBIS_NAME);ns(e,t).dropSync(),e.dbis!==void 0&&delete e.dbis[t],ns(e,Is).removeSync(t)}a(e$,"dropDBI");function t$(e,t,r){let s;for(let n=0;n<r.length;n++){let i=r[n];if(!e.dbis[i])try{ns(e,i)}catch(o){if(o.message===ar.DBI_DOES_NOT_EXIST)jb(e,i,i!==t,i===t),s=!0;else throw o}}s&&VV()}a(t$,"initializeDBIs");Zb.exports={openDBI:ns,openEnvironment:zb,createEnvironment:WV,listDBIs:Xb,listDBIDefinitions:JV,createDBI:jb,dropDBI:e$,statDBI:jV,deleteEnvironment:zV,initializeDBIs:t$,TransactionCursor:um,environmentDataSize:ZV,copyEnvironment:QV,closeEnvironment:Jb}});var tN=g((pce,eN)=>{"use strict";var Em=class{static{a(this,"InsertRecordsResponseObject")}constructor(t=[],r=[],s=void 0){this.written_hashes=t,this.skipped_hashes=r,this.txn_time=s}};eN.exports=Em});var sN=g((Tce,rN)=>{"use strict";var hm=class{static{a(this,"UpdateRecordsResponseObject")}constructor(t=[],r=[],s=void 0,n=[]){this.written_hashes=t,this.skipped_hashes=r,this.txn_time=s,this.original_records=n}};rN.exports=hm});var iN=g((Rce,nN)=>{"use strict";var mm=class{static{a(this,"UpsertRecordsResponseObject")}constructor(t=[],r=void 0,s=[]){this.written_hashes=t,this.txn_time=r,this.original_records=s}};nN.exports=mm});var ko=g((yce,cN)=>{"use strict";var r$=We(),s$=tN(),n$=sN(),i$=iN(),Qs=wr(),yc=Ir().LMDB_ERRORS_ENUM,o$=Et(),Tn=M(),a$=Q(),c$=require("uuid"),Oce=require("lmdb"),{handleHDBError:u$,hdb_errors:l$}=se(),{OVERFLOW_MARKER:bce,MAX_SEARCH_KEY_LENGTH:Nce}=o$,oN=ee();oN.initSync();var h_=oN.get(Tn.CONFIG_PARAMS.STORAGE_PREFETCHWRITES),pm=Tn.TIME_STAMP_NAMES_ENUM.CREATED_TIME,Gi=Tn.TIME_STAMP_NAMES_ENUM.UPDATED_TIME;async function _$(e,t,r,s,n=Qs.getNextMonotonicTime()){Rm(e,t,r,s),Sm(e,t,r);let i=new s$,o=[],c=[];for(let u=0;u<s.length;u++){let _=s[u];aN(_,!0,n);let l=d$(e,t,r,_),d=_[t];o.push(l),c.push(d)}return Tm(o,c,s,i,n)}a(_$,"insertRecords");function d$(e,t,r,s){let n=s[t];return e.dbis[t].ifNoExists(n,()=>{for(let i=0;i<r.length;i++){let o=r[i];if(o===t||s.hasOwnProperty(o)===!1)continue;let c=s[o];if(typeof c=="function"){let l=c([[{}]]);Array.isArray(l)&&(c=l[0][Tn.FUNC_VAL],s[o]=c)}let u=Qs.getIndexedValues(c),_=e.dbis[o];if(u){h_&&_.prefetch(u.map(l=>({key:l,value:n})),m_);for(let l=0,d=u.length;l<d;l++)_.put(u[l],n)}}h_&&e.dbis[t].prefetch([n],m_),e.dbis[t].put(n,s,s[Gi])})}a(d$,"insertRecord");function f$(e,t=[]){let r=0;for(let s=0;s<t.length;s++){let n=t[s];e.splice(n-r,1),r++}}a(f$,"removeSkippedRecords");function aN(e,t,r){let s=r>0;(s||!Number.isInteger(e[Gi]))&&(e[Gi]=r||(r=Qs.getNextMonotonicTime())),t===!0?(s||!Number.isInteger(e[pm]))&&(e[pm]=r||Qs.getNextMonotonicTime()):delete e[pm]}a(aN,"setTimestamps");function Sm(e,t,r){r.indexOf(Tn.TIME_STAMP_NAMES_ENUM.CREATED_TIME)<0&&r.push(Tn.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.indexOf(Tn.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)<0&&r.push(Tn.TIME_STAMP_NAMES_ENUM.UPDATED_TIME),r$.initializeDBIs(e,t,r)}a(Sm,"initializeTransaction");async function E$(e,t,r,s,n=Qs.getNextMonotonicTime()){Rm(e,t,r,s),Sm(e,t,r);let i=new n$,o=[],c=[],u=[];for(let _=0;_<s.length;_++){let l=s[_],d=l[t],f;try{f=gm(e,t,l,d,i,!0,n)}catch{i.skipped_hashes.push(d),o.push(_);continue}c.push(f),u.push(d)}return Tm(c,u,s,i,n,o)}a(E$,"updateRecords");async function h$(e,t,r,s,n=Qs.getNextMonotonicTime()){try{Rm(e,t,r,s)}catch(u){throw u$(u,u.message,l$.HTTP_STATUS_CODES.BAD_REQUEST)}Sm(e,t,r);let i=new i$,o=[],c=[];for(let u=0;u<s.length;u++){let _=s[u],l;a$.isEmpty(_[t])?(l=c$.v4(),_[t]=l):l=_[t];let d=gm(e,t,_,l,i,!1,n);o.push(d),c.push(l)}return Tm(o,c,s,i,n)}a(h$,"upsertRecords");async function Tm(e,t,r,s,n,i=[]){let o=await Promise.all(e);for(let c=0,u=o.length;c<u;c++)o[c]===!0?s.written_hashes.push(t[c]):(s.skipped_hashes.push(t[c]),i.push(c));return s.txn_time=n||Qs.getNextMonotonicTime(),f$(r,i),s}a(Tm,"finalizeWrite");function gm(e,t,r,s,n,i=!1,o){let c=e.dbis[t],u=c.getEntry(s),_=u?.value,l=_;if(!_){if(i)return!1;_={}}if(aN(r,!l,o),Number.isInteger(r[Gi])&&_[Gi]>r[Gi])return!1;l&&n.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 R=p([[_]]);Array.isArray(R)&&(p=R[0][Tn.FUNC_VAL],r[h]=p)}if(p===T)continue;let b=Qs.getIndexedValues(T);if(b){h_&&S.prefetch(b.map(R=>({key:R,value:s})),m_);for(let R=0,L=b.length;R<L;R++)S.remove(b[R],s)}if(b=Qs.getIndexedValues(p),b){h_&&S.prefetch(b.map(R=>({key:R,value:s})),m_);for(let R=0,L=b.length;R<L;R++)S.put(b[R],s)}}let E=Object.assign({},_,r);c.put(s,E,E[Gi])},"do_put");return u?d=c.ifVersion(s,u.version,f):d=c.ifNoExists(s,f),d.then(E=>E?!0:gm(e,t,r,s,n,i,o))}a(gm,"updateUpsertRecord");function m$(e,t,r){if(Qs.validateEnv(e),t===void 0)throw new Error(yc.HASH_ATTRIBUTE_REQUIRED);if(!Array.isArray(r))throw r===void 0?new Error(yc.WRITE_ATTRIBUTES_REQUIRED):new Error(yc.WRITE_ATTRIBUTES_MUST_BE_ARRAY)}a(m$,"validateBasic");function Rm(e,t,r,s){if(m$(e,t,r),!Array.isArray(s))throw s===void 0?new Error(yc.RECORDS_REQUIRED):new Error(yc.RECORDS_MUST_BE_ARRAY)}a(Rm,"validateWrite");function m_(){}a(m_,"noop");cN.exports={insertRecords:_$,updateRecords:E$,upsertRecords:h$}});var Fi=g((wce,p$)=>{p$.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 Js=g((Cce,_N)=>{"use strict";var lN=Q(),uN=M(),Vo=/^[\x20-\x2E|\x30-\x5F|\x61-\x7E]*$/,zs=require("joi"),ei={schema_format:{pattern:Vo,message:"names cannot include backticks or forward slashes"},schema_length:{minimum:1,maximum:250,tooLong:"cannot exceed 250 characters"}},S$=zs.alternatives(zs.string().min(1).max(ei.schema_length.maximum).pattern(Vo).messages({"string.pattern.base":"{:#label} "+ei.schema_format.message}),zs.number(),zs.array()).required(),T$=zs.alternatives(zs.string().min(1).max(ei.schema_length.maximum).pattern(Vo).messages({"string.pattern.base":"{:#label} "+ei.schema_format.message}),zs.number()),g$=zs.alternatives(zs.string().min(1).max(ei.schema_length.maximum).pattern(Vo).messages({"string.pattern.base":"{:#label} "+ei.schema_format.message}),zs.number()).required();function R$(e,t){return t?typeof t!="string"?`'${e}' must be a string`:t.length?t.length>ei.schema_length.maximum?`'${e}' maximum of 250 characters`:Vo.test(t)?"":`'${e}' has illegal characters`:`'${e}' must be at least one character`:`'${e}' is required`}a(R$,"checkValidTable");function A$(e,t){return lN.doesSchemaExist(e)?e:t.message(`Database '${e}' does not exist`)}a(A$,"validateSchemaExists");function O$(e,t){let r=t.state.ancestors[0].schema;return lN.doesTableExist(r,e)?e:t.message(`Table '${e}' does not exist`)}a(O$,"validateTableExists");function b$(e,t){return e.toLowerCase()===uN.SYSTEM_SCHEMA_NAME?t.message(`'subscriptions[${t.state.path[1]}]' invalid database name, '${uN.SYSTEM_SCHEMA_NAME}' name is reserved`):e}a(b$,"validateSchemaName");_N.exports={common_validators:ei,schema_regex:Vo,hdb_schema_table:S$,validateSchemaExists:A$,validateTableExists:O$,validateSchemaName:b$,checkValidTable:R$,hdb_database:T$,hdb_table:g$}});var Xe=g((Lce,dN)=>{"use strict";var cr=require("validate.js");cr.validators.type=function(e,t,r,s){return e===null||typeof e>"u"||cr.validators.type.checks[t](e)?null:` must be a '${t}' value`};cr.validators.type.checks={Object:function(e){return cr.isObject(e)&&!cr.isArray(e)},Array:cr.isArray,Integer:cr.isInteger,Number:cr.isNumber,String:cr.isString,Date:cr.isDate,Boolean:function(e){return typeof e=="boolean"}};cr.validators.hasValidFileExt=function(e,t){return cr.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};dN.exports={validateObject:N$,validateObjectAsync:y$,validateBySchema:I$};function N$(e,t){if(!e||!t)return new Error("validateObject parameters were null");let r=cr(e,t,{format:"flat"});return r?new Error(r):null}a(N$,"validateObject");async function y$(e,t){if(!e||!t)return new Error("validateObject parameters were null");try{await cr.async(e,t,{format:"flat"})}catch(r){let s=r.join(",");return new Error(s)}return null}a(y$,"validateObjectAsync");function I$(e,t){let r=t.validate(e,{allowUnknown:!0,abortEarly:!1,errors:{wrap:{label:"'"}}});if(r.error)return new Error(r.error.message)}a(I$,"validateBySchema")});var p_=g((Uce,fN)=>{var{common_validators:Xs}=Js(),wc=Xe(),Ic="is required",ht={database:{presence:!1,format:Xs.schema_format,length:Xs.schema_length},schema:{presence:!1,format:Xs.schema_format,length:Xs.schema_length},table:{presence:!0,format:Xs.schema_format,length:Xs.schema_length},attribute:{presence:!0,format:Xs.schema_format,length:Xs.schema_length},hash_attribute:{presence:!0,format:Xs.schema_format,length:Xs.schema_length}};function Cc(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(Cc,"makeAttributesStrings");function w$(e){return e=Cc(e),ht.table.presence=!1,ht.attribute.presence=!1,ht.hash_attribute.presence=!1,wc.validateObject(e,ht)}a(w$,"schema_object");function C$(e){return e=Cc(e),ht.table.presence={message:Ic},ht.attribute.presence=!1,ht.hash_attribute.presence=!1,wc.validateObject(e,ht)}a(C$,"table_object");function D$(e){return e=Cc(e),ht.table.presence={message:Ic},ht.attribute.presence=!1,wc.validateObject(e,ht)}a(D$,"create_table_object");function L$(e){return e=Cc(e),ht.table.presence={message:Ic},ht.attribute.presence={message:Ic},ht.hash_attribute.presence=!1,wc.validateObject(e,ht)}a(L$,"attribute_object");function M$(e){return e=Cc(e),ht.table.presence={message:Ic},ht.attribute.presence=!1,ht.hash_attribute.presence=!1,wc.validateObject(e,ht)}a(M$,"describe_table");function U$(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(U$,"validateTableResidence");fN.exports={schema_object:w$,create_table_object:D$,table_object:C$,attribute_object:L$,describe_table:M$,validateTableResidence:U$}});var hN=g((vce,EN)=>{"use strict";var P$=require("uuid"),Am=class{static{a(this,"CreateAttributeObject")}constructor(t,r,s,n){this.schema=t,this.table=r,this.attribute=s,this.id=n||P$.v4(),this.schema_table=`${this.schema}.${this.table}`}};EN.exports=Am});var S_=g((Hce,mN)=>{"use strict";var v$=hN(),Om=class extends v${static{a(this,"LMDBCreateAttributeObject")}constructor(t,r,s,n,i=!0,o=!1){super(t,r,s,n),this.dup_sort=i,this.is_hash_attribute=o}};mN.exports=Om});var SN=g((qce,pN)=>{"use strict";pN.exports=H$;var B$="inserted";function H$(e,t,r,s){let n={message:`${e} ${t.length} of ${r.records.length} records`,skipped_hashes:s};return e===B$?(n.inserted_hashes=t,n):(n.update_hashes=t,n)}a(H$,"returnObject")});var T_=g((Fce,ON)=>{"use strict";var x$=M(),bm=We(),q$=ko(),{getSystemSchemaPath:G$,getSchemaPath:F$}=Je(),k$=Fi(),V$=p_(),$$=S_(),Y$=SN(),{handleHDBError:TN,hdb_errors:RN}=se(),gN=Q(),{HTTP_STATUS_CODES:K$}=RN,Nm=k$.hdb_attribute,AN=[];for(let e=0;e<Nm.attributes.length;e++)AN.push(Nm.attributes[e].attribute);var W$="inserted";ON.exports=Q$;async function Q$(e){let t=V$.attribute_object(e);if(t)throw TN(new Error,t.message,RN.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0);let r=!e.skip_table_check&&gN.checkGlobalSchemaTable(e.schema,e.table);if(r)throw TN(new Error,r,K$.NOT_FOUND);e.is_hash_attribute=e.is_hash_attribute=="true",e.dup_sort=gN.isEmpty(e.dup_sort)||e.dup_sort=="true";let s=[];if(global.hdb_schema[e.schema]&&global.hdb_schema[e.schema][e.table]&&(s=global.hdb_schema[e.schema][e.table].attributes),Array.isArray(s)&&s.length>0){for(let i of s)if(i.attribute===e.attribute)throw new Error(`attribute '${i.attribute}' already exists in ${e.schema}.${e.table}`)}let n=new $$(e.schema,e.table,e.attribute,e.id);try{let i=await bm.openEnvironment(F$(e.schema,e.table),e.table);if(i.dbis[e.attribute]!==void 0)throw new Error(`attribute '${e.attribute}' already exists in ${e.schema}.${e.table}`);bm.createDBI(i,e.attribute,e.dup_sort,e.is_hash_attribute);let o=await bm.openEnvironment(G$(),x$.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME),{written_hashes:c,skipped_hashes:u}=await q$.insertRecords(o,Nm.hash_attribute,AN,[n]);return Y$(W$,c,{records:[n]},u)}catch(i){throw i}}a(Q$,"lmdbCreateAttribute")});var Im=g((Vce,NN)=>{var{hdb_table:z$,hdb_database:bN}=Js(),J$=Xe(),ym=require("joi"),X$={undefined:"undefined",null:"null"},j$=a((e,t)=>{let r=Object.keys(e),s=r.length,n;for(let i=0;i<s;i++){let o=r[i];(!o||o.length===0||X$[o]!==void 0)&&(n===void 0?n=`Invalid attribute name: '${o}'`:n+=`. Invalid attribute name: '${o}'`)}return n?t.message(n):e},"custom_records_val"),Z$=ym.object({database:bN,schema:bN,table:z$,records:ym.array().items(ym.object().custom(j$)).required()});NN.exports=function(e){return J$.validateBySchema(e,Z$)}});var Dc=g((Kce,IN)=>{"use strict";var gn=Q(),yN=$(),Yce=Im(),{getDatabases:e1}=(Ae(),ne(Ge)),{ClientError:ki}=se();IN.exports=t1;function t1(e){if(gn.isEmpty(e))throw new ki("invalid update parameters defined.");if(gn.isEmptyOrZeroLength(e.schema))throw new ki("invalid schema specified.");if(gn.isEmptyOrZeroLength(e.table))throw new ki("invalid table specified.");if(!Array.isArray(e.records))throw new ki("records must be an array");let t=e1()[e.schema]?.[e.table];if(gn.isEmpty(t))throw new ki(`could not retrieve schema:${e.schema} and table ${e.table}`);let r=t.primaryKey,s=new Set,n={},i=!1;return e.operation==="update"&&(i=!0),e.records.forEach(o=>{if(i&&gn.isEmptyOrZeroLength(o[r]))throw yN.error("a valid hash attribute must be provided with update record:",o),new ki("a valid hash attribute must be provided with update record, check log for more info");if(!gn.isEmptyOrZeroLength(o[r])&&(o[r]==="null"||o[r]==="undefined"))throw yN.error(`a valid hash value must be provided with ${e.operation} record:`,o),new ki(`Invalid hash value: '${o[r]}' is not a valid hash attribute value, check log for more info`);!gn.isEmpty(o[r])&&o[r]!==""&&s.has(gn.autoCast(o[r]))&&(o.skip=!0),s.add(gn.autoCast(o[r]));for(let c in o)n[c]=1}),n[r]=1,{schema_table:t,hashes:Array.from(s),attributes:Object.keys(n)}}a(t1,"insertUpdateValidate")});var Lc=g((Qce,wN)=>{"use strict";var r1=M().OPERATIONS_ENUM,wm=class{static{a(this,"InsertObject")}constructor(t,r,s,n,i=void 0){this.operation=r1.INSERT,this.schema=t,this.table=r,this.hash_attribute=s,this.records=n,this.__origin=i}};wN.exports=wm});var Mc=g((Xce,DN)=>{"use strict";var Jce=Lc(),g_=M(),Cm=Q(),CN=$(),s1=require("uuid"),{handleHDBError:R_,hdb_errors:n1}=se(),{HDB_ERROR_MSGS:A_,HTTP_STATUS_CODES:O_}=n1;DN.exports=i1;function i1(e,t,r){for(let n=0;n<t.length;n++)o1(t[n]);let{records:s}=e;for(let n=0;n<s.length;n++){let i=s[n];a1(i,r,e.operation)}}a(i1,"processRows");function o1(e){if(Buffer.byteLength(String(e))>g_.INSERT_MODULE_ENUM.MAX_CHARACTER_SIZE)throw R_(new Error,A_.ATTR_NAME_LENGTH_ERR(e),O_.BAD_REQUEST,void 0,void 0,!0);if(Cm.isEmptyOrZeroLength(e)||Cm.isEmpty(e.trim()))throw R_(new Error,A_.ATTR_NAME_NULLISH_ERR,O_.BAD_REQUEST,void 0,void 0,!0)}a(o1,"validateAttribute");function a1(e,t,r){if(!e.hasOwnProperty(t)||Cm.isEmptyOrZeroLength(e[t])){if(r===g_.OPERATIONS_ENUM.INSERT||r===g_.OPERATIONS_ENUM.UPSERT){e[t]=s1.v4();return}throw CN.error("Update transaction aborted due to record with no hash value:",e),R_(new Error,A_.RECORD_MISSING_HASH_ERR,O_.BAD_REQUEST,void 0,void 0,!0)}if(Buffer.byteLength(String(e[t]))>g_.INSERT_MODULE_ENUM.MAX_CHARACTER_SIZE)throw CN.error(e),R_(new Error,A_.HASH_VAL_LENGTH_ERR,O_.BAD_REQUEST,void 0,void 0,!0)}a(a1,"validateHash")});var MN=g((Zce,LN)=>{"use strict";var Dm=class{static{a(this,"ITCEventObject")}constructor(t,r){this.type=t,this.message=r}};LN.exports=Dm});var vN=g((tue,PN)=>{"use strict";var Lm=We(),c1=$(),UN=Ir().LMDB_ERRORS_ENUM;PN.exports=u1;async function u1(e){try{if(global.lmdb_map!==void 0&&e.operation!==void 0){let t=Object.keys(global.lmdb_map),r;switch(e.operation){case"drop_schema":for(let i=0;i<t.length;i++){let o=t[i];if(o.startsWith(`${e.schema}.`)||o.startsWith(`txn.${e.schema}.`))try{await Lm.closeEnvironment(global.lmdb_map[o])}catch(c){if(c.message!==UN.ENV_REQUIRED)throw c}}break;case"drop_table":let s=`${e.schema}.${e.table}`,n=`txn.${s}`;try{await Lm.closeEnvironment(global.lmdb_map[s]),await Lm.closeEnvironment(global.lmdb_map[n])}catch(i){if(i.message!==UN.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){c1.error(t)}}a(u1,"cleanLMDBMap")});var Rn=g((sue,qN)=>{"use strict";var Uc=require("crypto"),l1=ee(),{CONFIG_PARAMS:_1}=M(),HN="aes-256-cbc",d1=32,f1=16,Mm=64,xN=32,E1=Mm+xN,BN=new Map;qN.exports={encrypt:h1,decrypt:m1,createNatsTableStreamName:p1};function h1(e){let t=Uc.randomBytes(d1),r=Uc.randomBytes(f1),s=Uc.createCipheriv(HN,Buffer.from(t),r),n=s.update(e);n=Buffer.concat([n,s.final()]);let i=t.toString("hex"),o=r.toString("hex"),c=n.toString("hex");return i+o+c}a(h1,"encrypt");function m1(e){let t=e.substr(0,Mm),r=e.substr(Mm,xN),s=e.substr(E1,e.length),n=Buffer.from(r,"hex"),i=Buffer.from(s,"hex"),o=Uc.createDecipheriv(HN,Buffer.from(t,"hex"),n),c=o.update(i);return c=Buffer.concat([c,o.final()]),c.toString()}a(m1,"decrypt");function p1(e,t){let r=l1.get(_1.CLUSTERING_DATABASELEVEL)?e:`${e}.${t}`,s=BN.get(r);return s||(s=Uc.createHash("md5").update(r).digest("hex"),BN.set(r,s)),s}a(p1,"createNatsTableStreamName")});var ti=g((oue,FN)=>{"use strict";var iue=Mr(),b_=$(),GN=p_(),S1=Rn(),N_=Q(),{handleHDBError:y_,hdb_errors:T1}=se(),{HDB_ERROR_MSGS:I_,HTTP_STATUS_CODES:Um}=T1,g1=ee();g1.initSync();var{getDatabases:Pm}=(Ae(),ne(Ge));FN.exports={describeAll:R1,describeTable:w_,describeSchema:A1};async function R1(e){try{let t=N_.isEmptyOrZeroLength(e),r,s;t||(r=e.hdb_user.role.permission,s=r.super_user||r.cluster_user);let n=Pm(),i={},o={},c=[],u=e?.exact_count;for(let l in n){i[l]=!0,!t&&!s&&(o[l]=e.hdb_user.role.permission[l].describe);let d=n[l];for(let f in d)try{let E;if(t||s)E=await w_({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 w_({schema:l,table:f,exact_count:u},h)}E&&c.push(E)}catch(E){b_.error(E)}}let _={};for(let l in c)t||s?(_[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||s?_[l]={}:o[l]&&(_[l]={});return _}catch(t){return b_.error("Got an error in describeAll"),b_.error(t),y_(new Error,I_.DESCRIBE_ALL_ERR)}}a(R1,"describeAll");async function w_(e,t){N_.transformReq(e);let{schema:r,table:s}=e;r=r?.toString(),s=s?.toString();let n=t;e.hdb_user&&!e.hdb_user.role.permission.super_user&&(n=e.hdb_user.role.permission[r].tables[s].attribute_permissions);let i=GN.describe_table(e);if(i)throw i;let c=Pm()[r];if(!c)throw y_(new Error,I_.SCHEMA_NOT_FOUND(e.schema),Um.NOT_FOUND);let u=c[s];if(!u)throw y_(new Error,I_.TABLE_NOT_FOUND(e.schema,e.table),Um.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(n){let f={};n.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=S1.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){b_.warn(`unable to stat table dbi due to ${f}`)}return d}a(w_,"descTable");async function A1(e){N_.transformReq(e);let t=GN.schema_object(e);if(t)throw t;let r;e.hdb_user&&!e.hdb_user.role.permission.super_user&&(r=e.hdb_user.role.permission[e.schema]);let s=e.schema.toString(),i=Pm()[s];if(!i)throw y_(new Error,I_.SCHEMA_NOT_FOUND(e.schema),Um.NOT_FOUND);let o={};for(let c in i){let u;if(r&&r.tables[c]&&(u=r.tables[c]),N_.isEmpty(u)||u.describe){let _=await w_({schema:e.schema,table:c,exact_count:e.exact_count},u?u.attribute_permissions:null);_&&(o[_.name]=_)}}return o}a(A1,"describeSchema")});var An=g((lue,KN)=>{var O1=Fi(),{callbackify:VN,promisify:b1}=require("util"),{getDatabases:$N}=(Ae(),ne(Ge));KN.exports={setSchemaDataToGlobal:kN,getTableSchema:N1,getSystemSchema:y1,setSchemaDataToGlobalAsync:b1(kN)};var YN=ti(),cue=VN(YN.describeAll),uue=VN(YN.describeTable);function kN(e){global.hdb_schema=$N(),e&&e()}a(kN,"setSchemaDataToGlobal");function N1(e,t,r){let s=$N()[e];if(!s)return r(`schema ${e} does not exist`);let n=s[t];return n?r(null,{schema:e,name:t,hash_attribute:n.primaryKey}):r(`table ${e}.${t} does not exist`)}a(N1,"getTableSchema");function y1(){return O1}a(y1,"getSystemSchema")});var Ur=g((due,JN)=>{"use strict";var D_=Im(),kt=Q(),I1=require("util"),L_=ws(),w1=An(),WN=$(),{handleHDBError:Vi,hdb_errors:C1}=se(),{HTTP_STATUS_CODES:$i}=C1,D1=I1.promisify(w1.getTableSchema),L1="updated",QN="inserted",zN="upserted";JN.exports={insert:U1,update:P1,upsert:v1,validation:M1,flush:B1};async function M1(e){if(kt.isEmpty(e))throw new Error("invalid update parameters defined.");if(kt.isEmptyOrZeroLength(e.schema))throw new Error("invalid database specified.");if(kt.isEmptyOrZeroLength(e.table))throw new Error("invalid table specified.");let t=await D1(e.schema,e.table),r=D_(e);if(r)throw r;if(!Array.isArray(e.records))throw new Error("records must be an array");let s=t.hash_attribute,n=new Set,i={},o=!1;return e.operation==="update"&&(o=!0),e.records.forEach(c=>{if(o&&kt.isEmptyOrZeroLength(c[s]))throw WN.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(!kt.isEmptyOrZeroLength(c[s])&&(c[s]==="null"||c[s]==="undefined"))throw WN.error(`a valid hash value must be provided with ${e.operation} record:`,c),new Error(`"${c[s]}" is not a valid hash attribute value`);!kt.isEmpty(c[s])&&c[s]!==""&&n.has(kt.autoCast(c[s]))&&(c.skip=!0),n.add(kt.autoCast(c[s]));for(let u in c)i[u]=1}),i[s]=1,{schema_table:t,hashes:Array.from(n),attributes:Object.keys(i)}}a(M1,"validation");async function U1(e){if(e.operation!=="insert")throw new Error("invalid operation, must be insert");let t=D_(e);if(t)throw Vi(new Error,t.message,$i.BAD_REQUEST);kt.transformReq(e);let r=kt.checkSchemaTableExist(e.schema,e.table);if(r)throw Vi(new Error,r,$i.BAD_REQUEST);let s=await L_.createRecords(e);return C_(QN,s.written_hashes,e,s.skipped_hashes,s.new_attributes,s.txn_time)}a(U1,"insertData");async function P1(e){if(e.operation!=="update")throw new Error("invalid operation, must be update");let t=D_(e);if(t)throw Vi(new Error,t.message,$i.BAD_REQUEST);kt.transformReq(e);let r=kt.checkSchemaTableExist(e.schema,e.table);if(r)throw Vi(new Error,r,$i.BAD_REQUEST);let s=await L_.updateRecords(e);return kt.isEmpty(s.existing_rows)?C_(L1,s.written_hashes,e,s.skipped_hashes,s.new_attributes,s.txn_time):C_(s.update_action,[],e,s.hashes,void 0,s.txn_time)}a(P1,"updateData");async function v1(e){if(e.operation!=="upsert")throw Vi(new Error,"invalid operation, must be upsert",$i.INTERNAL_SERVER_ERROR);let t=D_(e);if(t)throw Vi(new Error,t.message,$i.BAD_REQUEST);kt.transformReq(e);let r=kt.checkSchemaTableExist(e.schema,e.table);if(r)throw Vi(new Error,r,$i.BAD_REQUEST);let s=await L_.upsertRecords(e);return C_(zN,s.written_hashes,e,[],s.new_attributes,s.txn_time)}a(v1,"upsertData");function C_(e,t,r,s,n,i){let o={message:`${e} ${t.length} of ${t.length+s.length} records`,new_attributes:n,txn_time:i};return e===QN?(o.inserted_hashes=t,o.skipped_hashes=s,o):e===zN?(o.upserted_hashes=t,o):(o.update_hashes=t,o.skipped_hashes=s,o)}a(C_,"returnObject");function B1(e){return kt.transformReq(e),L_.flush(e.schema,e.table)}a(B1,"flush")});var Bm=g((Eue,ZN)=>{var H1=Xe(),vm=require("joi"),{hdb_table:x1,hdb_database:XN}=Js(),jN={schema:XN,database:XN,table:x1},q1={date:vm.date().iso().required()},G1={timestamp:vm.date().timestamp().required().messages({"date.format":"'timestamp' is invalid"})};ZN.exports=function(e,t){let r=t==="timestamp"?{...jN,...G1}:{...jN,...q1},s=vm.object(r);return H1.validateBySchema(e,s)}});var ry=g((hue,ty)=>{var F1=Xe(),Hm=require("joi"),{hdb_table:k1,hdb_database:ey}=Js(),V1=Hm.object({schema:ey,database:ey,table:k1,hash_values:Hm.array().required(),ids:Hm.array()});ty.exports=function(e){return F1.validateBySchema(e,V1)}});var ny=g((mue,sy)=>{"use strict";var xm=class{static{a(this,"InsertObject")}constructor(t,r,s,n,i){this.operation=t,this.schema=r,this.table=s,this.hash_attribute=n,this.records=i}},qm=class{static{a(this,"NoSQLSeachObject")}constructor(t,r,s,n,i,o){this.schema=t,this.table=r,this.search_attribute=s,this.hash_attribute=n,this.get_attributes=i,this.search_value=o}},Gm=class{static{a(this,"DeleteResponseObject")}constructor(){this.message=void 0,this.deleted_hashes=[],this.skipped_hashes=[]}};sy.exports={InsertObject:xm,NoSQLSeachObject:qm,DeleteResponseObject:Gm}});var ni=g((Sue,uy)=>{"use strict";var oy=Bm(),$1=ry(),Yi=Q(),iy=require("moment"),ay=$(),{promisify:Y1,callbackify:K1}=require("util"),Ki=M(),W1=An(),Fm=Y1(W1.getTableSchema),km=ws(),{DeleteResponseObject:Q1}=ny(),{handleHDBError:ri,hdb_errors:z1}=se(),{HDB_ERROR_MSGS:M_,HTTP_STATUS_CODES:si}=z1,J1="records successfully deleted",X1=K1(cy);uy.exports={delete:X1,deleteRecord:cy,deleteFilesBefore:j1,deleteAuditLogsBefore:Z1};async function j1(e){let t=oy(e,"date");if(t)throw ri(t,t.message,si.BAD_REQUEST,void 0,void 0,!0);if(Yi.transformReq(e),!iy(e.date,iy.ISO_8601).isValid())throw ri(new Error,M_.INVALID_DATE,si.BAD_REQUEST,Ki.LOG_LEVELS.ERROR,M_.INVALID_DATE,!0);let s=Yi.checkSchemaTableExist(e.schema,e.table);if(s)throw ri(new Error,s,si.NOT_FOUND,Ki.LOG_LEVELS.ERROR,s,!0);let n=await km.deleteRecordsBefore(e);if(await Fm(e.schema,e.table),ay.info(`Finished deleting files before ${e.date}`),n&&n.message)return n.message}a(j1,"deleteFilesBefore");async function Z1(e){let t=oy(e,"timestamp");if(t)throw ri(t,t.message,si.BAD_REQUEST,void 0,void 0,!0);if(Yi.transformReq(e),isNaN(e.timestamp))throw ri(new Error,M_.INVALID_VALUE("Timestamp"),si.BAD_REQUEST,Ki.LOG_LEVELS.ERROR,M_.INVALID_VALUE("Timestamp"),!0);let r=Yi.checkSchemaTableExist(e.schema,e.table);if(r)throw ri(new Error,r,si.NOT_FOUND,Ki.LOG_LEVELS.ERROR,r,!0);let s=await km.deleteAuditLogsBefore(e);return await Fm(e.schema,e.table),ay.info(`Finished deleting audit logs before ${e.timestamp}`),s}a(Z1,"deleteAuditLogsBefore");async function cy(e){e.ids&&(e.hash_values=e.ids);let t=$1(e);if(t)throw ri(t,t.message,si.BAD_REQUEST,void 0,void 0,!0);Yi.transformReq(e);let r=Yi.checkSchemaTableExist(e.schema,e.table);if(r)throw ri(new Error,r,si.NOT_FOUND,Ki.LOG_LEVELS.ERROR,r,!0);try{await Fm(e.schema,e.table);let s=await km.deleteRecords(e);return Yi.isEmptyOrZeroLength(s.message)&&(s.message=`${s.deleted_hashes.length} of ${e.hash_values.length} ${J1}`),s}catch(s){if(s.message===Ki.SEARCH_NOT_FOUND_MESSAGE){let n=new Q1;return n.message=Ki.SEARCH_NOT_FOUND_MESSAGE,n.skipped_hashes=e.hash_values.length,n.deleted_hashes=0,n}throw s}}a(cy,"deleteRecord")});var U_=g((gue,dy)=>{var eY=require("crypto"),ly=9;function tY(e){let t=sY(ly),r=_y(e+t);return t+r}a(tY,"createHash");function rY(e,t){let r=e?.substr(0,ly),s=r+_y(t+r);return e===s}a(rY,"validateHash");function sY(e){let t="0123456789abcdefghijklmnopqurstuvwxyzABCDEFGHIJKLMNOPQURSTUVWXYZ",r=t.length,s="";for(let n=0;n<e;n++){let i=Math.floor(Math.random()*r);s+=t[i]}return s}a(sY,"generateSalt");function _y(e){return eY.createHash("md5").update(e).digest("hex")}a(_y,"md5");dy.exports={hash:tY,validate:rY}});var Ey=g((Aue,fy)=>{var Vm=Xe(),Qt={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 nY(e){return Qt.password.presence=!0,Qt.username.presence=!0,Qt.role.presence=!0,Qt.active.presence=!0,Vm.validateObject(e,Qt)}a(nY,"addUserValidation");function iY(e){return Qt.password.presence=!1,Qt.username.presence=!0,Qt.role.presence=!1,Qt.active.presence=!1,Vm.validateObject(e,Qt)}a(iY,"alterUserValidation");function oY(e){return Qt.password.presence=!1,Qt.username.presence=!0,Qt.role.presence=!1,Qt.active.presence=!1,Vm.validateObject(e,Qt)}a(oY,"dropUserValidation");fy.exports={addUserValidation:nY,alterUserValidation:iY,dropUserValidation:oY}});var Fe=g((Nue,my)=>{"use strict";var{platform:bue}=require("os"),aY="nats-server.zip",$m="nats-server",cY=process.platform==="win32"?`${$m}.exe`:$m,uY=/^[^\s.,*>]+$/,hy="__request__",lY=a(e=>`${e}.${hy}`,"REQUEST_SUBJECT"),_Y={NATS_MSG_ID:"Nats-Msg-Id",ORIGIN:"origin",TRANSACTED_NODES:"transacted_nodes"},dY={HUB_SERVER:"hub.json",LEAF_SERVER:"leaf.json"},fY={HUB:"hub.pid",LEAF:"leaf.pid"},EY={HUB:"-hub",LEAF:"-leaf",ADMIN:"-admin"},hY={SUCCESS:"success",ERROR:"error"},mY={OPEN:"open",CLOSED:"closed",NO_RESPONDERS:"NoResponders",TIMEOUT:"Timeout"},pY={TXN:"txn",MSGID:"msgid"},$o={ERR:"error",WRN:"warn",INF:"info",DBG:"debug",TRC:"trace"},SY={[$o.ERR]:1,[$o.WRN]:2,[$o.INF]:3,[$o.DBG]:4,[$o.TRC]:5},TY={debug:"-D",trace:"-DVV"};my.exports={NATS_SERVER_ZIP:aY,NATS_SERVER_NAME:$m,NATS_BINARY_NAME:cY,PID_FILES:fY,NATS_CONFIG_FILES:dY,SERVER_SUFFIX:EY,NATS_TERM_CONSTRAINTS_RX:uY,REQUEST_SUFFIX:hy,UPDATE_REMOTE_RESPONSE_STATUSES:hY,CLUSTER_STATUS_STATUSES:mY,REQUEST_SUBJECT:lY,SUBJECT_PREFIXES:pY,MSG_HEADERS:_Y,LOG_LEVELS:$o,LOG_LEVEL_FLAGS:TY,LOG_LEVEL_HIERARCHY:SY}});var Sy=g((Iue,py)=>{"use strict";var gY={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 pq=Object.create;var oc=Object.defineProperty;var Sq=Object.getOwnPropertyDescriptor;var Tq=Object.getOwnPropertyNames;var gq=Object.getPrototypeOf,Rq=Object.prototype.hasOwnProperty;var a=(e,t)=>oc(e,"name",{value:t,configurable:!0});var ge=(e,t)=>()=>(e&&(t=e(e=0)),t);var g=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),qe=(e,t)=>{for(var r in t)oc(e,r,{get:t[r],enumerable:!0})},lO=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Tq(t))!Rq.call(e,s)&&s!==r&&oc(e,s,{get:()=>t[s],enumerable:!(n=Sq(t,s))||n.enumerable});return e};var v=(e,t,r)=>(r=e!=null?pq(gq(e)):{},lO(t||!e||!e.__esModule?oc(r,"default",{value:e,enumerable:!0}):r,e)),ie=e=>lO(oc({},"__esModule",{value:!0}),e);var fO=g((qae,dO)=>{var Aq=require("fast-glob"),{statSync:wh,existsSync:Ch,readFileSync:Oq,writeFileSync:bq}=require("fs"),{spawnSync:yq,spawn:Nq,execFileSync:Gae}=require("child_process"),{isMainThread:Iq}=require("worker_threads"),{join:Xs,relative:_O}=require("path"),{PACKAGE_ROOT:bn}=L(),{tmpdir:wq,platform:Cq}=require("os");require("source-map-support").install();var Dq=["resources","server","dataLayer","components"],ac="ts-build",Dh,Lq=__filename.endsWith("tsBuild.js");if(Lq){if(Iq){let r;try{wh(Xs(bn,ac)),r=!0}catch{}if(r)for(let n of Aq.sync(Dq.map(s=>s+"/**/*.ts"),{cwd:bn})){let s=0,i=0;try{s=wh(Xs(bn,n)).mtimeMs-5e3,i=wh(Xs(bn,ac,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."),Dh=!0;break}}else console.log("TypeScript modules are not compiled, compiling now"),Dh=!0;if(Dh){let n=Xs(bn,"node_modules/.bin/tsc");Cq()==="win32"&&(n+=".cmd");let s=yq(n,{cwd:bn});if(s.stdout.length&&console.log(s.stdout.toString()),s.stderr.length&&console.log(s.stderr.toString()),r){let i=Xs(wq(),"harperdb-tsc.pid"),o;if(Ch(i))try{process.kill(+Oq(i,{encoding:"utf8"}),0),o=!0}catch{}if(!o){console.log("starting tsc background process");let c=Nq(n,["--watch"],{cwd:bn,detached:!0,stdio:"ignore"});bq(i,c.pid.toString()),c.unref()}}}}let e=dO.constructor,t=e._findPath;e._findPath=function(r,n,s){if(r.startsWith(".")&&!s&&n.length===1&&n[0].startsWith(bn)&&!n[0].includes("node_modules")){let i=_O(bn,n[0]),o;i.startsWith(ac)?o=Xs(bn,_O(ac,i)):o=Xs(bn,ac,i);let c=Xs(o,r),u=c+".js";if(Ch(u))return u;if(c.includes(".")&&Ch(c))return c}return t(r,n,s)}}});var L=g((Vae,IO)=>{"use strict";var nn=require("path"),Mq=require("fs"),{relative:Fae,join:kae}=nn,{existsSync:Uq}=Mq;function Pq(){let e=__dirname;for(;!Uq(nn.join(e,"package.json"));){let t=nn.dirname(e);if(t===e)throw new Error("Could not find package root");e=t}return e}a(Pq,"getHDBPackageRoot");var js=Pq(),EO="js",jl=EO,vq="harperdb-config.yaml",Bq="defaultConfig.yaml",Hq="hdb",hO=`harperdb.${jl}`,mO=`customFunctionsServer.${jl}`,xq=`restartHdb.${jl}`,Mh="HarperDB",Xl="Custom Functions",Zl="Clustering Hub",e_="Clustering Leaf",Gq="Clustering Ingest Service",qq="Clustering Reply Service",Fq="foreground.pid",kq="hdb.pid",Vq="data",$q={HDB:Mh,CLUSTERING_HUB:Zl,CLUSTERING_LEAF:e_,CLUSTERING_INGEST_SERVICE:Gq,CLUSTERING_REPLY_SERVICE:qq,CUSTOM_FUNCTIONS:Xl,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"},Yq={HDB:"hdb.log",INSTALL:"install.log",CLUSTERING_HUB:"clustering_hub.log",CLUSTERING_LEAF:"clustering_leaf.log"},Kq={NOTIFY:"notify",FATAL:"fatal",ERROR:"error",WARN:"warn",INFO:"info",DEBUG:"debug",TRACE:"trace"},Wq={harperdb:Mh,"clustering hub":Zl,"clustering leaf":e_,"custom functions":Xl,custom_functions:Xl,clustering:"clustering","clustering config":"clustering config",clustering_config:"clustering_config",http_workers:"http_workers"},Qq={CLUSTERING_HUB_PROC_DESCRIPTOR:Zl,CLUSTERING_LEAF_PROC_DESCRIPTOR:e_},Lh={HDB:nn.join(js,"server/harperdb"),CUSTOM_FUNCTIONS:nn.join(js,"server/customFunctions"),CLUSTERING_HUB:nn.join(js,"server/nats"),CLUSTERING_LEAF:nn.join(js,"server/nats")},zq={HDB:nn.join(Lh.HDB,hO),CUSTOM_FUNCTIONS:nn.join(Lh.CUSTOM_FUNCTIONS,mO)},Jq={MAIN:"bin/harperdb.js",NATS_INGEST_SERVICE:nn.join(js,"launchServiceScripts/launchNatsIngestService.js"),NATS_REPLY_SERVICE:nn.join(js,"launchServiceScripts/launchNatsReplyService.js"),NODES_UPGRADE_4_0_0:nn.join(js,"launchServiceScripts/launchUpdateNodes4-0-0.js")},Xq={SUPER_USER:"super_user",CLUSTER_USER:"cluster_user"},pO="support@harperdb.io",jq="customer-success@harperdb.io",SO=1,Zq=4141,TO="https://harperdbhelp.zendesk.com/hc/en-us/requests/new",eF="https://www.harperdb.io/product",tF=`For support, please submit a request at ${TO} or contact ${pO}`,gO=`For license support, please contact ${jq}`,rF="None of the specified records were found.",nF="hash attribute not found",sF=`Your current license only supports ${SO} role. ${gO}`,iF="Your current license only supports 3 connections to a node.",oF="127.0.0.1",aF=1,cF=/^\.$/,uF=/^\.\.$/,lF="U+002E",_F=/\//g,dF="U+002F",fF=/U\+002F/g,EF=/^U\+002E$/,hF=/^U\+002EU\+002E$/,mF="d",pF=999999,SF="*",TF="--max-old-space-size=",gF="system",RF="__hdb_hash",AF=".harperdb",OF=".hdb",bF="keys",yF="hdb_boot_properties.file",NF=".updateConfig.json",IF="SIGTSTP",wF=24,CF=6e4,DF=448,LF="blob",MF="trash",UF="database",PF="schema",vF="transactions",BF=".count",HF="id",xF="PROCESS_NAME",RO={SETTINGS_PATH_KEY:"settings_path"},AO=require("lodash"),GF={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"},qF={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},FF={DATA_VERSION:"data_version",UPGRADE_VERSION:"upgrade_version"},kF={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"},VF={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"},wr="hdb_internal:",$F={CREATE_SCHEMA:wr+"create_schema",CREATE_TABLE:wr+"create_table",CREATE_ATTRIBUTE:wr+"create_attribute",ADD_USER:wr+"add_user",ALTER_USER:wr+"alter_user",DROP_USER:wr+"drop_user",HDB_NODES:wr+"hdb_nodes",HDB_USERS:wr+"hdb_users",HDB_WORKERS:wr+"hdb_workers",CATCHUP:wr+"catchup",SCHEMA_CATCHUP:wr+"schema_catchup",WORKER_ROOM:wr+"cluster_workers"},YF={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"},KF="060493.ks",WF=".license",QF={CREATED:"CREATED",IN_PROGRESS:"IN_PROGRESS",COMPLETE:"COMPLETE",ERROR:"ERROR"},Z={INSERT:"insert",UPDATE:"update",UPSERT:"upsert",SEARCH_BY_CONDITIONS:"search_by_conditions",SEARCH_BY_HASH:"search_by_hash",SEARCH_BY_ID:"search_by_id",SEARCH_BY_VALUE:"search_by_value",SEARCH:"search",SQL:"sql",CSV_DATA_LOAD:"csv_data_load",CSV_FILE_LOAD:"csv_file_load",CSV_URL_LOAD:"csv_url_load",CREATE_SCHEMA:"create_schema",CREATE_DATABASE:"create_database",CREATE_TABLE:"create_table",CREATE_ATTRIBUTE:"create_attribute",DROP_SCHEMA:"drop_schema",DROP_DATABASE:"drop_database",DROP_TABLE:"drop_table",DESCRIBE_SCHEMA:"describe_schema",DESCRIBE_DATABASE:"describe_database",DESCRIBE_TABLE:"describe_table",DESCRIBE_ALL:"describe_all",DELETE:"delete",ADD_USER:"add_user",ALTER_USER:"alter_user",DROP_USER:"drop_user",LIST_USERS:"list_users",LIST_ROLES:"list_roles",ADD_ROLE:"add_role",ALTER_ROLE:"alter_role",DROP_ROLE:"drop_role",USER_INFO:"user_info",READ_LOG:"read_log",ADD_NODE:"add_node",UPDATE_NODE:"update_node",SET_NODE_REPLICATION:"set_node_replication",EXPORT_TO_S3:"export_to_s3",IMPORT_FROM_S3:"import_from_s3",DELETE_FILES_BEFORE:"delete_files_before",DELETE_RECORDS_BEFORE:"delete_records_before",EXPORT_LOCAL:"export_local",SEARCH_JOBS_BY_START_DATE:"search_jobs_by_start_date",GET_JOB:"get_job",DELETE_JOB:"delete_job",UPDATE_JOB:"update_job",GET_FINGERPRINT:"get_fingerprint",SET_LICENSE:"set_license",GET_REGISTRATION_INFO:"registration_info",CONFIGURE_CLUSTER:"configure_cluster",SET_CONFIGURATION:"set_configuration",CLUSTER_STATUS:"cluster_status",CLUSTER_NETWORK:"cluster_network",DROP_ATTRIBUTE:"drop_attribute",REMOVE_NODE:"remove_node",RESTART:"restart",RESTART_SERVICE:"restart_service",CATCHUP:"catchup",SYSTEM_INFORMATION:"system_information",DELETE_AUDIT_LOGS_BEFORE:"delete_audit_logs_before",READ_AUDIT_LOG:"read_audit_log",CREATE_AUTHENTICATION_TOKENS:"create_authentication_tokens",LOGIN:"login",LOGOUT:"logout",REFRESH_OPERATION_TOKEN:"refresh_operation_token",GET_CONFIGURATION:"get_configuration",CUSTOM_FUNCTIONS_STATUS:"custom_functions_status",GET_CUSTOM_FUNCTIONS:"get_custom_functions",GET_CUSTOM_FUNCTION:"get_custom_function",SET_CUSTOM_FUNCTION:"set_custom_function",GET_COMPONENTS:"get_components",GET_COMPONENT_FILE:"get_component_file",SET_COMPONENT_FILE:"set_component_file",DROP_COMPONENT:"drop_component",DROP_CUSTOM_FUNCTION:"drop_custom_function",ADD_CUSTOM_FUNCTION_PROJECT:"add_custom_function_project",ADD_COMPONENT:"add_component",DROP_CUSTOM_FUNCTION_PROJECT:"drop_custom_function_project",PACKAGE_CUSTOM_FUNCTION_PROJECT:"package_custom_function_project",DEPLOY_CUSTOM_FUNCTION_PROJECT:"deploy_custom_function_project",PACKAGE_COMPONENT:"package_component",DEPLOY_COMPONENT:"deploy_component",CLUSTER_SET_ROUTES:"cluster_set_routes",CLUSTER_DELETE_ROUTES:"cluster_delete_routes",CLUSTER_GET_ROUTES:"cluster_get_routes",READ_TRANSACTION_LOG:"read_transaction_log",DELETE_TRANSACTION_LOGS_BEFORE:"delete_transaction_logs_before",INSTALL_NODE_MODULES:"install_node_modules",AUDIT_NODE_MODULES:"audit_node_modules",PURGE_STREAM:"purge_stream",GET_BACKUP:"get_backup"},zF={CSV:".csv",JSON:".json"},JF={AWS_ACCESS_KEY:"aws_access_key_id",AWS_SECRET:"aws_secret_access_key",AWS_BUCKET:"bucket",AWS_FILE_KEY:"key",REGION:"region"},XF={SELECT:"select",INSERT:"insert",UPDATE:"update",DELETE:"delete"},cc={};cc[Z.INSERT]=Z.INSERT;cc[Z.UPDATE]=Z.UPDATE;cc[Z.UPSERT]=Z.UPSERT;cc[Z.DELETE]=Z.DELETE;var xe=Object.create(null);xe[Z.DESCRIBE_ALL]=Z.DESCRIBE_ALL;xe[Z.DESCRIBE_TABLE]=Z.DESCRIBE_TABLE;xe[Z.DESCRIBE_SCHEMA]=Z.DESCRIBE_SCHEMA;xe[Z.READ_LOG]=Z.READ_LOG;xe[Z.ADD_NODE]=Z.ADD_NODE;xe[Z.LIST_USERS]=Z.LIST_USERS;xe[Z.LIST_ROLES]=Z.LIST_ROLES;xe[Z.USER_INFO]=Z.USER_INFO;xe[Z.SQL]=Z.SQL;xe[Z.GET_JOB]=Z.GET_JOB;xe[Z.SEARCH_JOBS_BY_START_DATE]=Z.SEARCH_JOBS_BY_START_DATE;xe[Z.DELETE_FILES_BEFORE]=Z.DELETE_FILES_BEFORE;xe[Z.EXPORT_LOCAL]=Z.EXPORT_LOCAL;xe[Z.EXPORT_TO_S3]=Z.EXPORT_TO_S3;xe[Z.CLUSTER_STATUS]=Z.CLUSTER_STATUS;xe[Z.REMOVE_NODE]=Z.REMOVE_NODE;xe[Z.RESTART]=Z.RESTART;xe[Z.CUSTOM_FUNCTIONS_STATUS]=Z.CUSTOM_FUNCTIONS_STATUS;xe[Z.GET_CUSTOM_FUNCTIONS]=Z.GET_CUSTOM_FUNCTIONS;xe[Z.GET_CUSTOM_FUNCTION]=Z.GET_CUSTOM_FUNCTION;xe[Z.SET_CUSTOM_FUNCTION]=Z.SET_CUSTOM_FUNCTION;xe[Z.DROP_CUSTOM_FUNCTION]=Z.DROP_CUSTOM_FUNCTION;xe[Z.ADD_CUSTOM_FUNCTION_PROJECT]=Z.ADD_CUSTOM_FUNCTION_PROJECT;xe[Z.DROP_CUSTOM_FUNCTION_PROJECT]=Z.DROP_CUSTOM_FUNCTION_PROJECT;xe[Z.PACKAGE_CUSTOM_FUNCTION_PROJECT]=Z.PACKAGE_CUSTOM_FUNCTION_PROJECT;xe[Z.DEPLOY_CUSTOM_FUNCTION_PROJECT]=Z.DEPLOY_CUSTOM_FUNCTION_PROJECT;var jF={DEV:"dev",RUN:"run",START:"start",INSTALL:"install",REGISTER:"register",STOP:"stop",RESTART:"restart",VERSION:"version",UPGRADE:"upgrade",HELP:"help",STATUS:"status",OPERATION:"operation",RENEWCERTS:"renew-certs",COPYDB:"copy-db"},ZF={point:"point",lineString:"lineString",multiLineString:"multiLineString",multiPoint:"multiPoint",multiPolygon:"multiPolygon",polygon:"polygon"},OO={HDB_ROOT_KEY:"HDB_ROOT",SERVER_PORT_KEY:"SERVER_PORT",CERT_KEY:"CERTIFICATE",PRIVATE_KEY_KEY:"PRIVATE_KEY",HTTP_SECURE_ENABLED_KEY:"HTTPS_ON",CORS_ENABLED_KEY:"CORS_ON",CORS_WHITELIST_KEY:"CORS_WHITELIST",LOG_LEVEL_KEY:"LOG_LEVEL",LOGGER_KEY:"LOGGER",LOG_PATH_KEY:"LOG_PATH",LOG_ROTATE:"LOG_ROTATE",LOG_ROTATE_MAX_SIZE:"LOG_ROTATE_MAX_SIZE",LOG_ROTATE_RETAIN:"LOG_ROTATE_RETAIN",LOG_ROTATE_COMPRESS:"LOG_ROTATE_COMPRESS",LOG_ROTATE_DATE_FORMAT:"LOG_ROTATE_DATE_FORMAT",LOG_ROTATE_ROTATE_MODULE:"LOG_ROTATE_ROTATE_MODULE",LOG_ROTATE_WORKER_INTERVAL:"LOG_ROTATE_WORKER_INTERVAL",LOG_ROTATE_ROTATE_INTERVAL:"LOG_ROTATE_ROTATE_INTERVAL",LOG_ROTATE_TIMEZONE:"LOG_ROTATE_TIMEZONE",LOG_DAILY_ROTATE_KEY:"LOG_DAILY_ROTATE",LOG_MAX_DAILY_FILES_KEY:"LOG_MAX_DAILY_FILES",PROPS_ENV_KEY:"NODE_ENV",SETTINGS_PATH_KEY:"settings_path",CLUSTERING_PORT_KEY:"CLUSTERING_PORT",CLUSTERING_NODE_NAME_KEY:"NODE_NAME",CLUSTERING_ENABLED_KEY:"CLUSTERING",ALLOW_SELF_SIGNED_SSL_CERTS:"ALLOW_SELF_SIGNED_SSL_CERTS",MAX_HDB_PROCESSES:"MAX_HDB_PROCESSES",INSTALL_USER:"install_user",CLUSTERING_USER_KEY:"CLUSTERING_USER",MAX_CLUSTERING_PROCESSES:"MAX_CLUSTERING_PROCESSES",SERVER_TIMEOUT_KEY:"SERVER_TIMEOUT_MS",SERVER_KEEP_ALIVE_TIMEOUT_KEY:"SERVER_KEEP_ALIVE_TIMEOUT",SERVER_HEADERS_TIMEOUT_KEY:"SERVER_HEADERS_TIMEOUT",DISABLE_TRANSACTION_LOG_KEY:"DISABLE_TRANSACTION_LOG",OPERATION_TOKEN_TIMEOUT_KEY:"OPERATION_TOKEN_TIMEOUT",REFRESH_TOKEN_TIMEOUT_KEY:"REFRESH_TOKEN_TIMEOUT",CUSTOM_FUNCTIONS_ENABLED_KEY:"CUSTOM_FUNCTIONS",CUSTOM_FUNCTIONS_PORT_KEY:"CUSTOM_FUNCTIONS_PORT",CUSTOM_FUNCTIONS_DIRECTORY_KEY:"CUSTOM_FUNCTIONS_DIRECTORY",MAX_CUSTOM_FUNCTION_PROCESSES:"MAX_CUSTOM_FUNCTION_PROCESSES",LOG_TO_FILE:"LOG_TO_FILE",LOG_TO_STDSTREAMS:"LOG_TO_STDSTREAMS",RUN_IN_FOREGROUND:"RUN_IN_FOREGROUND",LOCAL_STUDIO_ON:"LOCAL_STUDIO_ON",STORAGE_WRITE_ASYNC:"STORAGE_WRITE_ASYNC"},ek=AO.invert(OO),tk={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"},w={ANALYTICS_AGGREGATEPERIOD:"analytics_aggregatePeriod",AUTHENTICATION_AUTHORIZELOCAL:"authentication_authorizeLocal",AUTHENTICATION_CACHETTL:"authentication_cacheTTL",AUTHENTICATION_ENABLESESSIONS:"authentication_enableSessions",AUTHENTICATION_OPERATIONTOKENTIMEOUT:"authentication_operationTokenTimeout",AUTHENTICATION_REFRESHTOKENTIMEOUT:"authentication_refreshTokenTimeout",CLUSTERING_USER:"clustering_user",CLUSTERING_ENABLED:"clustering_enabled",CLUSTERING_HUBSERVER_CLUSTER_NAME:"clustering_hubServer_cluster_name",CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT:"clustering_hubServer_cluster_network_port",CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES:"clustering_hubServer_cluster_network_routes",CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT:"clustering_hubServer_leafNodes_network_port",CLUSTERING_HUBSERVER_NETWORK_PORT:"clustering_hubServer_network_port",CLUSTERING_LEAFSERVER_NETWORK_PORT:"clustering_leafServer_network_port",CLUSTERING_LEAFSERVER_NETWORK_ROUTES:"clustering_leafServer_network_routes",CLUSTERING_LEAFSERVER_STREAMS_MAXAGE:"clustering_leafServer_streams_maxAge",CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES:"clustering_leafServer_streams_maxBytes",CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS:"clustering_leafServer_streams_maxMsgs",CLUSTERING_LEAFSERVER_STREAMS_MAXCONSUMEMSGS:"clustering_leafServer_streams_maxConsumeMsgs",CLUSTERING_LEAFSERVER_STREAMS_MAXINGESTTHREADS:"clustering_leafServer_streams_maxIngestThreads",CLUSTERING_LEAFSERVER_STREAMS_PATH:"clustering_leafServer_streams_path",CLUSTERING_NODENAME:"clustering_nodeName",CLUSTERING_TLS_CERTIFICATE:"clustering_tls_certificate",CLUSTERING_TLS_PRIVATEKEY:"clustering_tls_privateKey",CLUSTERING_TLS_CERT_AUTH:"clustering_tls_certificateAuthority",CLUSTERING_TLS_INSECURE:"clustering_tls_insecure",CLUSTERING_TLS_VERIFY:"clustering_tls_verify",CLUSTERING_LOGLEVEL:"clustering_logLevel",CLUSTERING_REPUBLISHMESSAGES:"clustering_republishMessages",CLUSTERING_DATABASELEVEL:"clustering_databaseLevel",CUSTOMFUNCTIONS_NETWORK_HTTPS:"customFunctions_network_https",THREADS:"threads",THREADS_COUNT:"threads_count",THREADS_DEBUG:"threads_debug",THREADS_DEBUG_STARTINGPORT:"threads_debug_startingPort",THREADS_DEBUG_PORT:"threads_debug_port",THREADS_DEBUG_HOST:"threads_debug_host",THREADS_DEBUG_WAITFORDEBUGGER:"threads_debug_waitForDebugger",THREADS_MAXHEAPMEMORY:"threads_maxHeapMemory",HTTP_SESSIONAFFINITY:"http_sessionAffinity",HTTP_COMPRESSIONTHRESHOLD:"http_compressionThreshold",HTTP_CORS:"http_cors",HTTP_CORSACCESSLIST:"http_corsAccessList",HTTP_HEADERSTIMEOUT:"http_headersTimeout",HTTP_KEEPALIVETIMEOUT:"http_keepAliveTimeout",HTTP_TIMEOUT:"http_timeout",HTTP_PORT:"http_port",HTTP_SECUREPORT:"http_securePort",HTTP_MTLS:"http_mtls",HTTP_MTLS_REQUIRED:"http_mtls_required",HTTP_MTLS_USER:"http_mtls_user",HTTP_MAXHEADERSIZE:"http_maxHeaderSize",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",STORAGE_MAXFREESPACETOLOAD:"storage_maxFreeSpaceToLoad",STORAGE_MAXFREESPACETORETAIN:"storage_maxFreeSpaceToRetain",STORAGE_PAGESIZE:"storage_pageSize",STORAGE_COMPRESSION_DICTIONARY:"storage_compression_dictionary",STORAGE_COMPRESSION_THRESHOLD:"storage_compression_threshold",STORAGE_COMPACTONSTART:"storage_compactOnStart",STORAGE_COMPACTONSTARTKEEPBACKUP:"storage_compactOnStartKeepBackup",DATABASES:"databases",IGNORE_SCRIPTS:"ignoreScripts",MQTT_NETWORK_PORT:"mqtt_network_port",MQTT_WEBSOCKET:"mqtt_webSocket",MQTT_NETWORK_SECUREPORT:"mqtt_network_securePort",MQTT_NETWORK_MTLS:"mqtt_network_mtls",MQTT_NETWORK_MTLS_REQUIRED:"mqtt_network_mtls_required",MQTT_NETWORK_MTLS_CERTIFICATEAUTHORITY:"mqtt_network_mtls_certificateAuthority",MQTT_NETWORK_MTLS_USER:"mqtt_network_mtls_user",MQTT_REQUIREAUTHENTICATION:"mqtt_requireAuthentication",COMPONENTSROOT:"componentsRoot",TLS_CERTIFICATE:"tls_certificate",TLS_PRIVATEKEY:"tls_privateKey",TLS_CERTIFICATEAUTHORITY:"tls_certificateAuthority",TLS_CIPHERS:"tls_ciphers"},bO={settings_path:RO.SETTINGS_PATH_KEY,hdb_root_key:w.ROOTPATH,hdb_root:w.ROOTPATH,rootpath:w.ROOTPATH,server_port_key:w.OPERATIONSAPI_NETWORK_PORT,server_port:w.OPERATIONSAPI_NETWORK_PORT,cert_key:w.TLS_CERTIFICATE,certificate:w.TLS_CERTIFICATE,private_key_key:w.TLS_PRIVATEKEY,private_key:w.TLS_PRIVATEKEY,http_secure_enabled_key:w.OPERATIONSAPI_NETWORK_HTTPS,https_on:w.OPERATIONSAPI_NETWORK_HTTPS,cors_enabled_key:w.OPERATIONSAPI_NETWORK_CORS,cors_on:w.OPERATIONSAPI_NETWORK_CORS,cors_whitelist_key:w.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_whitelist:w.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_accesslist_key:w.OPERATIONSAPI_NETWORK_CORSACCESSLIST,cors_accesslist:w.OPERATIONSAPI_NETWORK_CORSACCESSLIST,log_level_key:w.LOGGING_LEVEL,log_level:w.LOGGING_LEVEL,log_path_key:w.LOGGING_ROOT,log_path:w.LOGGING_ROOT,clustering_node_name_key:w.CLUSTERING_NODENAME,node_name:w.CLUSTERING_NODENAME,clustering_enabled_key:w.CLUSTERING_ENABLED,clustering:w.CLUSTERING_ENABLED,max_http_threads:w.THREADS_COUNT,max_hdb_processes:w.THREADS_COUNT,server_timeout_key:w.OPERATIONSAPI_NETWORK_TIMEOUT,server_timeout_ms:w.OPERATIONSAPI_NETWORK_TIMEOUT,server_keep_alive_timeout_key:w.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT,server_keep_alive_timeout:w.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT,server_headers_timeout_key:w.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT,server_headers_timeout:w.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT,disable_transaction_log_key:w.LOGGING_AUDITLOG,disable_transaction_log:w.LOGGING_AUDITLOG,operation_token_timeout_key:w.AUTHENTICATION_OPERATIONTOKENTIMEOUT,operation_token_timeout:w.AUTHENTICATION_OPERATIONTOKENTIMEOUT,refresh_token_timeout_key:w.AUTHENTICATION_REFRESHTOKENTIMEOUT,refresh_token_timeout:w.AUTHENTICATION_REFRESHTOKENTIMEOUT,custom_functions_port_key:w.HTTP_PORT,custom_functions_port:w.HTTP_PORT,custom_functions_directory_key:w.COMPONENTSROOT,custom_functions_directory:w.COMPONENTSROOT,max_custom_function_processes:w.THREADS_COUNT,log_to_file:w.LOGGING_FILE,log_to_stdstreams:w.LOGGING_STDSTREAMS,local_studio_on:w.LOCALSTUDIO_ENABLED,clustering_port:w.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT,clustering_user:w.CLUSTERING_USER,clustering_enabled:w.CLUSTERING_ENABLED,clustering_hubserver_cluster_name:w.CLUSTERING_HUBSERVER_CLUSTER_NAME,clustering_hubserver_cluster_network_port:w.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT,clustering_hubserver_cluster_network_routes:w.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,clustering_hubserver_leafnodes_network_port:w.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT,clustering_hubserver_network_port:w.CLUSTERING_HUBSERVER_NETWORK_PORT,clustering_leafserver_network_port:w.CLUSTERING_LEAFSERVER_NETWORK_PORT,clustering_leafserver_network_routes:w.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,clustering_leafserver_streams_maxage:w.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE,clustering_leafserver_streams_maxbytes:w.CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES,clustering_leafserver_streams_maxconsumemsgs:w.CLUSTERING_LEAFSERVER_STREAMS_MAXCONSUMEMSGS,clustering_leafserver_streams_maxingestthreads:w.CLUSTERING_LEAFSERVER_STREAMS_MAXINGESTTHREADS,clustering_leafserver_streams_maxmsgs:w.CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS,clustering_leafserver_streams_path:w.CLUSTERING_LEAFSERVER_STREAMS_PATH,clustering_nodename:w.CLUSTERING_NODENAME,clustering_tls_certificate:w.CLUSTERING_TLS_CERTIFICATE,clustering_tls_privatekey:w.CLUSTERING_TLS_PRIVATEKEY,clustering_tls_certificateauthority:w.CLUSTERING_TLS_CERT_AUTH,clustering_tls_insecure:w.CLUSTERING_TLS_INSECURE,clustering_tls_verify:w.CLUSTERING_TLS_VERIFY,clustering_loglevel:w.CLUSTERING_LOGLEVEL,clustering_republishmessages:w.CLUSTERING_REPUBLISHMESSAGES,clustering_databaselevel:w.CLUSTERING_DATABASELEVEL,customfunctions_network_port:w.HTTP_PORT,customfunctions_tls_certificate:w.TLS_CERTIFICATE,customfunctions_network_cors:w.HTTP_CORS,customfunctions_network_corsaccesslist:w.HTTP_CORSACCESSLIST,customfunctions_network_headerstimeout:w.HTTP_HEADERSTIMEOUT,customfunctions_network_https:w.CUSTOMFUNCTIONS_NETWORK_HTTPS,customfunctions_network_keepalivetimeout:w.HTTP_KEEPALIVETIMEOUT,customfunctions_tls_privatekey:w.TLS_PRIVATEKEY,customfunctions_tls_certificateauthority:w.TLS_CERTIFICATEAUTHORITY,customfunctions_network_timeout:w.HTTP_TIMEOUT,http_threads:w.THREADS_COUNT,threads:w.THREADS_COUNT,threads_count:w.THREADS_COUNT,threads_debug:w.THREADS_DEBUG,threads_debug_startingport:w.THREADS_DEBUG_STARTINGPORT,threads_debug_port:w.THREADS_DEBUG_PORT,threads_debug_host:w.THREADS_DEBUG_HOST,threads_debug_waitfordebugger:w.THREADS_DEBUG_WAITFORDEBUGGER,threads_maxheapmemory:w.THREADS_MAXHEAPMEMORY,http_session_affinity:w.HTTP_SESSIONAFFINITY,http_compressionthreshold:w.HTTP_COMPRESSIONTHRESHOLD,http_cors:w.HTTP_CORS,http_corsaccesslist:w.HTTP_CORSACCESSLIST,http_headerstimeout:w.HTTP_HEADERSTIMEOUT,http_keepalivetimeout:w.HTTP_KEEPALIVETIMEOUT,http_timeout:w.HTTP_TIMEOUT,http_port:w.HTTP_PORT,http_secureport:w.HTTP_SECUREPORT,http_mtls:w.HTTP_MTLS,http_mtls_user:w.HTTP_MTLS_USER,http_mtls_required:w.HTTP_MTLS_REQUIRED,customfunctions_processes:w.THREADS_COUNT,customfunctions_root:w.COMPONENTSROOT,localstudio_enabled:w.LOCALSTUDIO_ENABLED,logging_file:w.LOGGING_FILE,logging_level:w.LOGGING_LEVEL,logging_root:w.LOGGING_ROOT,logging_rotation_enabled:w.LOGGING_ROTATION_ENABLED,logging_rotation_compress:w.LOGGING_ROTATION_COMPRESS,logging_rotation_interval:w.LOGGING_ROTATION_INTERVAL,logging_rotation_maxsize:w.LOGGING_ROTATION_MAXSIZE,logging_rotation_path:w.LOGGING_ROTATION_PATH,logging_stdstreams:w.LOGGING_STDSTREAMS,logging_auditlog:w.LOGGING_AUDITLOG,logging_auditretention:w.LOGGING_AUDITRETENTION,logging_auditauthevents_logfailed:w.LOGGING_AUDITAUTHEVENTS_LOGFAILED,logging_auditauthevents_logsuccessful:w.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL,operationsapi_authentication_operationtokentimeout:w.AUTHENTICATION_OPERATIONTOKENTIMEOUT,operationsapi_authentication_refreshtokentimeout:w.AUTHENTICATION_REFRESHTOKENTIMEOUT,operationsapi_network_cors:w.OPERATIONSAPI_NETWORK_CORS,operationsapi_network_corsaccesslist:w.OPERATIONSAPI_NETWORK_CORSACCESSLIST,operationsapi_network_headerstimeout:w.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT,operationsapi_network_https:w.OPERATIONSAPI_NETWORK_HTTPS,operationsapi_network_keepalivetimeout:w.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT,operationsapi_network_port:w.OPERATIONSAPI_NETWORK_PORT,operationsapi_network_domainsocket:w.OPERATIONSAPI_NETWORK_DOMAINSOCKET,operationsapi_network_secureport:w.OPERATIONSAPI_NETWORK_SECUREPORT,operationsapi_tls_certificate:w.OPERATIONSAPI_TLS_CERTIFICATE,operationsapi_tls_privatekey:w.OPERATIONSAPI_TLS_PRIVATEKEY,operationsapi_tls_certificateauthority:w.OPERATIONSAPI_TLS_CERTIFICATEAUTHORITY,operationsapi_network_timeout:w.OPERATIONSAPI_NETWORK_TIMEOUT,operationsapi_root:w.ROOTPATH,databases:w.DATABASES,storage_path:w.STORAGE_PATH,ignorescripts:w.IGNORE_SCRIPTS,mqtt_network_port:w.MQTT_NETWORK_PORT,mqtt_websocket:w.MQTT_WEBSOCKET,mqtt_network_secureport:w.MQTT_NETWORK_SECUREPORT,mqtt_network_mtls:w.MQTT_NETWORK_MTLS,mqtt_network_mtls_certificateAuthority:w.MQTT_NETWORK_MTLS_CERTIFICATEAUTHORITY,mqtt_network_mtls_user:w.MQTT_NETWORK_MTLS_USER,mqtt_network_mtls_required:w.MQTT_NETWORK_MTLS_REQUIRED,mqtt_requireauthentication:w.MQTT_REQUIREAUTHENTICATION,analytics_aggregatePeriod:w.ANALYTICS_AGGREGATEPERIOD,authentication_authorizelocal:w.AUTHENTICATION_AUTHORIZELOCAL,authentication_cachettl:w.AUTHENTICATION_CACHETTL,authentication_enablesessions:w.AUTHENTICATION_ENABLESESSIONS,authentication_operationtokentimeout:w.AUTHENTICATION_OPERATIONTOKENTIMEOUT,authentication_refreshtokentimeout:w.AUTHENTICATION_REFRESHTOKENTIMEOUT,componentsroot:w.COMPONENTSROOT,tls_certificate:w.TLS_CERTIFICATE,tls_privatekey:w.TLS_PRIVATEKEY,tls_certificateauthority:w.TLS_CERTIFICATEAUTHORITY,tls_ciphers:w.TLS_CIPHERS};for(let e in w){let t=w[e];bO[t.toLowerCase()]=t}var rk={TABLES:"tables",PATH:"path",AUDIT_PATH:"auditPath"},nk={csv_file_load:"csv_file_load",csv_data_load:Z.CSV_DATA_LOAD,csv_url_load:Z.CSV_URL_LOAD,delete_files_before:"delete_files_before",delete_records_before:"delete_records_before",delete_audit_logs_before:"delete_audit_logs_before",delete_transaction_logs_before:"delete_transaction_logs_before",empty_trash:"empty_trash",export_local:"export_local",export_to_s3:"export_to_s3",import_from_s3:"import_from_s3"},sk={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"},ik={BIDIRECTIONAL:"BIDIRECTIONAL",OUTBOUND:"OUTBOUND",INBOUND:"INBOUND"},ok={VERSION_DEFAULT:"2.2.0"},ak={DEVELOPMENT:8192,DEFAULT:512},ck={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"},uk={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"},lk={ENOENT:"ENOENT",EACCES:"EACCES",EEXIST:"EEXIST"},yO={CREATED_TIME:"__createdtime__",UPDATED_TIME:"__updatedtime__"},_k=Symbol("metadata"),dk="__clustering__",fk=Object.values(yO),Ek=15984864e5,NO={LESS:"<",LESS_OR_EQ:"<=",GREATER:">",GREATER_OR_EQ:">=",BETWEEN:"..."},hk=AO.invert(NO),mk={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"},pk=111,Sk=`\r
|
|
2
|
+
`,Tk={READ:"read",INSERT:"insert",UPDATE:"update",DELETE:"delete"},gk=["*","%"],Rk="unauthorized_access",Ak="func_val",Ok={HASH_VALUE:"hash_value",TIMESTAMP:"timestamp",USERNAME:"username"},bk={JWT_PRIVATE_KEY_NAME:".jwtPrivate.key",JWT_PUBLIC_KEY_NAME:".jwtPublic.key",JWT_PASSPHRASE_NAME:".jwtPass"},yk={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",NATS_CONSUMER_UPDATE:"nats_consumer_update"},Nk={HDB_CORE:"hdb_core",CUSTOM_FUNCTIONS:"custom_functions"},Ik={HTTP:"http"},wk={STOPPED:"stopped",ONLINE:"online"},Ck="3.x.x",Dk={SUCCESS:"success",FAILURE:"failure"},Lk={AUTHENTICATION:"authentication",AUTHORIZATION:"authorization"};IO.exports={LOCAL_HARPERDB_OPERATIONS:xe,HDB_SUPPORT_ADDRESS:pO,HDB_SUPPORT_URL:TO,HDB_PRICING_URL:eF,SUPPORT_HELP_MSG:tF,LICENSE_HELP_MSG:gO,HDB_PROC_NAME:hO,HDB_PROC_DESCRIPTOR:Mh,CLUSTERING_LEAF_PROC_DESCRIPTOR:e_,CLUSTERING_HUB_PROC_DESCRIPTOR:Zl,SYSTEM_SCHEMA_NAME:gF,HASH_FOLDER_NAME:RF,HDB_HOME_DIR_NAME:AF,UPDATE_FILE_NAME:NF,LICENSE_KEY_DIR_NAME:bF,BOOT_PROPS_FILE_NAME:yF,JOB_TYPE_ENUM:nk,JOB_STATUS_ENUM:QF,SYSTEM_TABLE_NAMES:kF,SYSTEM_TABLE_HASH_ATTRIBUTES:VF,OPERATIONS_ENUM:Z,VALID_S3_FILE_TYPES:zF,S3_BUCKET_AUTH_KEYS:JF,VALID_SQL_OPS_ENUM:XF,GEO_CONVERSION_ENUM:ZF,HDB_SETTINGS_NAMES:OO,HDB_SETTINGS_NAMES_REVERSE_LOOKUP:ek,SERVICE_ACTIONS_ENUM:jF,CLUSTER_MESSAGE_TYPE_ENUM:sk,CLUSTER_CONNECTION_DIRECTION_ENUM:ik,CLUSTER_EVENTS_DEFS_ENUM:ck,PERIOD_REGEX:cF,DOUBLE_PERIOD_REGEX:uF,UNICODE_PERIOD:lF,FORWARD_SLASH_REGEX:_F,UNICODE_FORWARD_SLASH:dF,ESCAPED_FORWARD_SLASH_REGEX:fF,ESCAPED_PERIOD_REGEX:EF,ESCAPED_DOUBLE_PERIOD_REGEX:hF,REG_KEY_FILE_NAME:KF,RESTART_TIMEOUT_MS:CF,HDB_FILE_PERMISSIONS:DF,DATABASES_DIR_NAME:UF,LEGACY_DATABASES_DIR_NAME:PF,TRANSACTIONS_DIR_NAME:vF,LIMIT_COUNT_NAME:BF,ID_ATTRIBUTE_STRING:HF,INSERT_MODULE_ENUM:qF,UPGRADE_JSON_FIELD_NAMES_ENUM:FF,RESTART_CODE:IF,RESTART_CODE_NUM:wF,CLUSTER_OPERATIONS:cc,SYSTEM_DEFAULT_ATTRIBUTE_NAMES:YF,HDB_INTERNAL_SC_CHANNEL_PREFIX:wr,INTERNAL_SC_CHANNELS:$F,CLUSTERING_MESSAGE_TYPES:mk,HDB_FILE_SUFFIX:OF,BLOB_FOLDER_NAME:LF,HDB_TRASH_DIR:MF,ORIGINATOR_SET_VALUE:pk,LICENSE_VALUES:ok,RAM_ALLOCATION_ENUM:ak,TIME_STAMP_NAMES_ENUM:yO,TIME_STAMP_NAMES:fk,PERMS_UPDATE_RELEASE_TIMESTAMP:Ek,SEARCH_NOT_FOUND_MESSAGE:rF,SEARCH_ATTRIBUTE_NOT_FOUND:nF,LICENSE_ROLE_DENIED_RESPONSE:sF,LICENSE_MAX_CONNS_REACHED:iF,BASIC_LICENSE_MAX_NON_CU_ROLES:SO,BASIC_LICENSE_CLUSTER_CONNECTION_LIMIT_WS_ERROR_CODE:Zq,VALUE_SEARCH_COMPARATORS:NO,VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP:hk,LICENSE_FILE_NAME:WF,WEBSOCKET_CLOSE_CODE_DESCRIPTION_LOOKUP:uk,NEW_LINE:Sk,BASIC_LICENSE_MAX_CLUSTER_USER_ROLES:aF,MOMENT_DAYS_TAG:mF,API_TURNOVER_SEC:pF,LOOPBACK:oF,CODE_EXTENSION:jl,WILDCARD_SEARCH_VALUE:SF,NODE_ERROR_CODES:lk,JAVASCRIPT_EXTENSION:EO,PERMS_CRUD_ENUM:Tk,UNAUTHORIZED_PERMISSION_NAME:Rk,SEARCH_WILDCARDS:gk,FUNC_VAL:Ak,READ_AUDIT_LOG_SEARCH_TYPES_ENUM:Ok,JWT_ENUM:bk,CLUSTERING_FLAG:dk,ITC_EVENT_TYPES:yk,CUSTOM_FUNCTION_PROC_NAME:mO,CUSTOM_FUNCTION_PROC_DESCRIPTOR:Xl,SERVICES:Nk,THREAD_TYPES:Ik,MEM_SETTING_KEY:TF,HDB_RESTART_SCRIPT:xq,PROCESS_DESCRIPTORS:$q,SERVICE_SERVERS:zq,SERVICE_SERVERS_CWD:Lh,PROCESS_DESCRIPTORS_VALIDATE:Wq,LAUNCH_SERVICE_SCRIPTS:Jq,LOG_LEVELS:Kq,PROCESS_NAME_ENV_PROP:xF,LOG_NAMES:Yq,PM2_PROCESS_STATUSES:wk,CONFIG_PARAM_MAP:bO,CONFIG_PARAMS:w,HDB_CONFIG_FILE:vq,HDB_DEFAULT_CONFIG_FILE:Bq,ROLE_TYPES_ENUM:Xq,BOOT_PROP_PARAMS:RO,INSTALL_PROMPTS:GF,HDB_ROOT_DIR_NAME:Hq,CLUSTERING_PROCESSES:Qq,FOREGROUND_PID_FILE:Fq,PACKAGE_ROOT:js,PRE_4_0_0_VERSION:Ck,DATABASES_PARAM_CONFIG:rk,METADATA_PROPERTY:_k,AUTH_AUDIT_STATUS:Dk,AUTH_AUDIT_TYPES:Lk,HDB_PID_FILE:kq,DEFAULT_DATABASE_NAME:Vq,LEGACY_CONFIG_PARAMS:tk};fO()});var Uh=g((Yae,DO)=>{"use strict";var wO=require("minimist");DO.exports=Mk;function Mk(e=[],t=!1){if(!Array.isArray(e))return{};let r,n;t?(r=CO(process.env),n=CO(wO(process.argv))):(r=process.env,n=wO(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(Mk,"assignCMDENVVariables");function CO(e){let t,r=Object.keys(e),n=r.length,s={};for(;n--;)t=r[n],s[t.toLowerCase()]=e[t];return s}a(CO,"objKeysToLowerCase")});var $=g((Wae,qh)=>{"use strict";var Hi=require("fs-extra"),{workerData:Uk,threadId:Pk}=require("worker_threads"),ps=require("path"),UO=require("yaml"),PO=require("properties-reader"),Ot=L(),LO=Uh(),vk=require("os"),{PACKAGE_ROOT:vh}=L(),{_assignPackageExport:Bk}=require("../index"),lc={};for(let e in console)lc[e]||(lc[e]=console[e]);var sr={notify:7,fatal:6,error:5,warn:4,info:3,debug:2,trace:1},vO={STDOUT:"stdOut",STDERR:"stdErr"},Hk=ps.join(vh,"logs"),xk=ps.join(vh,"config/yaml/",Ot.HDB_DEFAULT_CONFIG_FILE),Gk=1e4,ms,Wn,nr,t_,r_,_c,Fo,uc;uc===void 0&&BO();qh.exports={notify:GO,fatal:qO,error:dc,warn:Gh,info:n_,debug:xh,trace:Hh,setLogLevel:Kk,log_level:nr,loggerWithTag:qk,suppressLogging:Fk,initLogSettings:BO,setupConsoleLogging:HO,logCustomLevel:$k,closeLogFile:Bh,getLogFilePath:()=>_c,OUTPUTS:vO,AuthAuditLog:zk};Bk("logger",qh.exports);function BO(e=!1){try{if(uc===void 0||e){Bh();let t=Yk(),r=LO(["ROOTPATH"]);try{uc=PO(t)}catch(n){if(!r.ROOTPATH||r.ROOTPATH&&!Hi.pathExistsSync(ps.join(r.ROOTPATH,Ot.HDB_CONFIG_FILE)))throw n}({level:nr,config_log_path:r_,to_file:ms,to_stream:Wn}=Wk(r.ROOTPATH?ps.join(r.ROOTPATH,Ot.HDB_CONFIG_FILE):uc.get("settings_path"))),t_=Ot.LOG_NAMES.HDB,_c=ps.join(r_,t_)}}catch(t){if(uc=void 0,t.code===Ot.NODE_ERROR_CODES.ENOENT){let r=LO(Object.keys(Ot.CONFIG_PARAM_MAP),!0);for(let o in r){let c=Ot.CONFIG_PARAM_MAP[o];c&&c.toLowerCase();let u=r[o];if(c===Ot.CONFIG_PARAMS.LOGGING_LEVEL){nr=u;continue}if(c===Ot.CONFIG_PARAMS.LOGGING_STDSTREAMS){Wn=u;continue}c===Ot.CONFIG_PARAMS.LOGGING_FILE&&(ms=c)}let{default_level:n,default_to_file:s,default_to_stream:i}=Qk();ms=ms===void 0?s:ms,ms=MO(ms),Wn=Wn===void 0?i:Wn,Wn=MO(Wn),nr=nr===void 0?n:nr,r_=Hk,t_=Ot.LOG_NAMES.INSTALL,_c=ps.join(r_,t_);return}throw dc("Error initializing log settings"),dc(t),t}process.env.DEV_MODE&&(Wn=!0),HO()}a(BO,"initLogSettings");var Ph=!0;function HO(){qo("error",dc),qo("warn",Gh),qo("log",n_),qo("info",n_),qo("debug",xh),qo("trace",Hh)}a(HO,"setupConsoleLogging");function qo(e,t){console[e]=function(...r){if(Ph&&t(...r),!/PM2 log:|App \[/.test(r[0]))return lc[e](...r)}}a(qo,"logConsole");function qk(e){let t={tagName:e.replace(/ /g,"-")};return{notify:r(GO),fatal:r(qO),error:r(dc),warn:r(Gh),info:r(n_),debug:r(xh),trace:r(Hh)};function r(n){return function(...s){return n(t,...s)}}}a(qk,"loggerWithTag");function Fk(e){try{Ph=!1,e()}finally{Ph=!0}}a(Fk,"suppressLogging");var kk=Uk?.name?.replace(/ /g,"-")||"main";function Ss(e,t){let r=new Date(Date.now()).toISOString(),n="",s=t.length,i=s-1,o=[e],c=0,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||kk+"/"+Pk);c<s;c++){let _=t[c];_ instanceof Error&&_.stack?n+=_.stack:typeof _=="object"?n+=JSON.stringify(_):n+=_,c<i&&(n+=" ")}return`${r} [${o.join("] [")}]: ${n}
|
|
3
|
+
`}a(Ss,"createLogRecord");function fc(e){ms&&xO(e),Wn&&process.stdout.write(e)}a(fc,"logStdOut");function s_(e){ms&&xO(e),Wn&&process.stderr.write(e)}a(s_,"logStdErr");function xO(e){Vk(),Fo?Hi.appendFileSync(Fo,e):lc.log(e)}a(xO,"logToFile");function Bh(){try{Hi.closeSync(Fo)}catch{}Fo=null}a(Bh,"closeLogFile");function Vk(){if(!Fo){try{if(!_c)debugger;Fo=Hi.openSync(_c,"a")}catch(e){lc.error(e)}setTimeout(()=>{Bh()},Gk).unref()}}a(Vk,"openLogFile");function n_(...e){sr[nr]<=sr.info&&fc(Ss("info",e))}a(n_,"info");function Hh(...e){sr[nr]<=sr.trace&&fc(Ss("trace",e))}a(Hh,"trace");function dc(...e){sr[nr]<=sr.error&&s_(Ss("error",e))}a(dc,"error");function xh(...e){sr[nr]<=sr.debug&&fc(Ss("debug",e))}a(xh,"debug");function GO(...e){sr[nr]<=sr.notify&&fc(Ss("notify",e))}a(GO,"notify");function qO(...e){sr[nr]<=sr.fatal&&s_(Ss("fatal",e))}a(qO,"fatal");function Gh(...e){sr[nr]<=sr.warn&&s_(Ss("warn",e))}a(Gh,"warn");function $k(e,t,...r){t===vO.STDERR?s_(Ss(e,r)):fc(Ss(e,r))}a($k,"logCustomLevel");function Yk(){let e;try{e=vk.homedir()}catch{e=process.env.HOME}e||(e="~/");let t=ps.join(e,Ot.HDB_HOME_DIR_NAME,Ot.BOOT_PROPS_FILE_NAME);return Hi.existsSync(t)||(t=ps.join(vh,"utility/hdb_boot_properties.file")),t}a(Yk,"getPropsFilePath");function Kk(e){nr=e}a(Kk,"setLogLevel");function MO(e){return e===!0||typeof e=="string"&&e.toLowerCase()==="true"}a(MO,"autoCastBoolean");function Wk(e){try{if(e.includes("config/settings.js")){let o=PO(e);return{level:o.get(Ot.HDB_SETTINGS_NAMES.LOG_LEVEL_KEY),config_log_path:ps.dirname(o.get(Ot.HDB_SETTINGS_NAMES.LOG_PATH_KEY)),to_file:o.get(Ot.HDB_SETTINGS_NAMES.LOG_TO_FILE),to_stream:o.get(Ot.HDB_SETTINGS_NAMES.LOG_TO_STDSTREAMS)}}let t=UO.parseDocument(Hi.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===Ot.NODE_ERROR_CODES.ENOENT)throw t;console.error("Error accessing config file for logging"),console.error(t)}}a(Wk,"getLogConfig");function Qk(){try{let e=UO.parseDocument(Hi.readFileSync(xk,"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(Qk,"getDefaultConfig");function zk(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(zk,"AuthAuditLog")});var kO=g((zae,FO)=>{"use strict";var Jk=require("util"),Xk=require("path"),jk=require("child_process"),Zk=Jk.promisify(jk.execFile),eV=1e3*1e3*10;FO.exports={findPs:tV};async function tV(e){let t={};try{await Promise.all(["comm","args","ppid","uid","%cpu","%mem"].map(async r=>{let{stdout:n}=await Zk("ps",["wwxo",`pid,${r}`],{maxBuffer:eV});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:Xk.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(tV,"findPs")});var ut=g((Xae,$O)=>{"use strict";var rV="__dbis__",nV="__txns__",sV="__environment_name__",iV="__dbi_defintion__",oV={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"},aV=["__createdtime__","__updatedtime__"],cV="\uFFFF",VO={TIMESTAMP:"timestamp",HASH_VALUE:"hash_value",USER_NAME:"user_name"},uV=Object.values(VO);$O.exports={AUDIT_STORE_NAME:nV,INTERNAL_DBIS_NAME:rV,DBI_DEFINITION_NAME:iV,SEARCH_TYPES:oV,TIMESTAMP_NAMES:aV,MAX_SEARCH_KEY_LENGTH:256,ENVIRONMENT_NAME_KEY:sV,TRANSACTIONS_DBI_NAMES_ENUM:VO,TRANSACTIONS_DBIS:uV,OVERFLOW_MARKER:cV}});var Cr=g((jae,ZO)=>{"use strict";var YO=L(),KO=ut(),WO={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},QO=a(e=>`${e} Check logs and try again.`,"CHECK_LOGS_WRAPPER"),zO={500:QO("There was an error processing your request."),400:"Invalid request"},lV=zO[WO.INTERNAL_SERVER_ERROR],_V={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.`},dV={CONFIG_VALIDATION:e=>`HarperDB config file validation error: ${e}`},fV={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"},EV={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 ${KO.INTERNAL_DBIS_NAME}`,CANNOT_DROP_INTERNAL_DBIS_NAME:`cannot drop a dbi named ${KO.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"},hV={ATTR_NAME_LENGTH_ERR:e=>`transaction aborted due to attribute name ${e} being too long. Attribute names cannot be longer than ${YO.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 ${YO.INSERT_MODULE_ENUM.MAX_CHARACTER_SIZE} bytes, check log for more info`,INVALID_FORWARD_SLASH_IN_HASH_ERR:"transaction aborted due to record(s) with a hash value that contains a forward slash, check log for more info",RECORD_MISSING_HASH_ERR:"transaction aborted due to record(s) with no hash value, check log for more info"},JO={GENERIC_AUTH_FAIL:"Login failed",USER_INACTIVE:"Cannot complete request: User is inactive",INVALID_TOKEN:"invalid token",NO_ENCRYPTION_KEYS:"unable to generate JWT as there are no encryption keys. please contact your administrator",INVALID_CREDENTIALS:"invalid credentials",PASSWORD_REQUIRED:"password is required",USERNAME_REQUIRED:"username is required",REFRESH_TOKEN_REQUIRED:"refresh_token is required",INVALID_AUTH_OBJECT:"invalid auth_object",INVALID_BODY:"invalid body",TOKEN_EXPIRED:"token expired",REFRESH_TOKEN_SAVE_FAILED:"unable to store refresh_token"},mV={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."},pV={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`},SV={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"},TV={OUTER_JOIN_TRANSLATION_ERROR:"There was an error translating the final SQL outer join data."},gV={ALTER_USER_DUP_ROLES:e=>`Update failed. There are duplicates for the '${e}' role which is not allowed. Update your roles and try again.`,ALTER_USER_ROLE_NOT_FOUND:e=>`Update failed. Requested '${e}' role not found.`,DUP_ROLES_FOUND:e=>`Multiple ${e} roles found. Roles must have unique 'role' value. Please update and try again.`,ROLE_NAME_NOT_FOUND:e=>`${e} role not found`,USER_ALREADY_EXISTS:e=>`User ${e} already exists`,USER_NOT_EXIST:e=>`User ${e} does not exist`},XO={INVALID_DATE:"Invalid date, must be in ISO-8601 format (YYYY-MM-DD).",SEARCH_CONDITIONS_INVALID_SORT_ATTRIBUTE:e=>`invalid sort attribute '${e}', the attribute must either be the table's hash attribute or an attribute used in conditions.`},jO={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}`},RV={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."},AV={CLUSTERING_NOT_ENABLED:"Clustering must be enabled to perform this operation."},OV={...JO,...fV,..._V,...mV,...pV,...SV,...TV,...gV,...hV,...XO,...jO,...RV,...AV,...dV};ZO.exports={CHECK_LOGS_WRAPPER:QO,HDB_ERROR_MSGS:OV,DEFAULT_ERROR_MSGS:zO,DEFAULT_ERROR_RESP:lV,HTTP_STATUS_CODES:WO,LMDB_ERRORS_ENUM:EV,AUTHENTICATION_ERROR_MSGS:JO,VALIDATION_ERROR_MSGS:XO,ITC_ERRORS:jO}});var ne=g((ece,rb)=>{"use strict";var ko=Cr(),bV=$(),yV=L(),i_=class extends Error{static{a(this,"HdbError")}constructor(t,r,n,s,i){super(),Error.captureStackTrace(this,eb),this.statusCode=n||ko.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR,this.http_resp_msg=r||(ko.DEFAULT_ERROR_MSGS[n]?ko.DEFAULT_ERROR_MSGS[n]:ko.DEFAULT_ERROR_MSGS[ko.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&&bV[s](i)}},Fh=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}},kh=class extends Error{static{a(this,"ServerError")}constructor(t,r){super(t),this.statusCode=r||500}};function eb(e,t,r,n=yV.LOG_LEVELS.ERROR,s=null,i=!1){if(tb(e))return e;let o=new i_(e,t,r,n,s);return i&&delete o.stack,o}a(eb,"handleHDBError");function tb(e){return e.__proto__.constructor.name===i_.name}a(tb,"isHDBError");rb.exports={isHDBError:tb,handleHDBError:eb,ClientError:Fh,ServerError:kh,hdb_errors:ko}});var Je=g((rce,ub)=>{"use strict";var Sc=L(),NV=Q(),ir=ee(),Tc=require("path"),IV=require("minimist"),nb=require("fs-extra"),sb=require("lodash");ir.initSync();var{CONFIG_PARAMS:Zs,DATABASES_PARAM_CONFIG:Ec,SYSTEM_SCHEMA_NAME:o_}=Sc,hc,mc,pc;function ib(){if(hc!==void 0)return hc;if(ir.getHdbBasePath()!==void 0)return hc=ir.get(Zs.STORAGE_PATH)||Tc.join(ir.getHdbBasePath(),Sc.DATABASES_DIR_NAME),hc}a(ib,"getBaseSchemaPath");function ob(){if(mc!==void 0)return mc;if(ir.getHdbBasePath()!==void 0)return mc=cb(o_),mc}a(ob,"getSystemSchemaPath");function ab(){if(pc!==void 0)return pc;if(ir.getHdbBasePath()!==void 0)return pc=ir.get(Sc.CONFIG_PARAMS.STORAGE_AUDIT_PATH)||Tc.join(ir.getHdbBasePath(),Sc.TRANSACTIONS_DIR_NAME),pc}a(ab,"getTransactionAuditStoreBasePath");function wV(e,t){let r=ir.get(Zs.DATABASES)?.[e];return t&&r?.tables?.[t]?.auditPath||r?.auditPath||Tc.join(ab(),e.toString())}a(wV,"getTransactionAuditStorePath");function cb(e,t){e=e.toString(),t=t&&t.toString();let r=ir.get(Sc.CONFIG_PARAMS.DATABASES)?.[e];return t&&r?.tables?.[t]?.path||r?.path||Tc.join(ib(),e)}a(cb,"getSchemaPath");function CV(e,t){e=e.toString(),t=t.toString();let r=process.env;Object.assign(r,IV(process.argv));let n=r[Zs.DATABASES.toUpperCase()];if(n){let i;try{i=JSON.parse(n)}catch(o){if(!NV.isObject(n))throw o;i=n}for(let o of i){let c=o[o_];if(!c)continue;let u=ir.get(Zs.DATABASES);u=u??{};let _=c?.tables?.[t]?.[Ec.PATH];if(_)return sb.set(u,[o_,Ec.TABLES,t,Ec.PATH],_),ir.setProperty(Zs.DATABASES,u),_;let l=c?.[Ec.PATH];if(l)return sb.set(u,[o_,Ec.PATH],l),ir.setProperty(Zs.DATABASES,u),l}}let s=r[Zs.STORAGE_PATH.toUpperCase()];if(s){if(!nb.pathExistsSync(s))throw new Error(s+" does not exist");let i=Tc.join(s,e);return nb.mkdirsSync(i),ir.setProperty(Zs.STORAGE_PATH,s),i}return ob()}a(CV,"initSystemSchemaPaths");function DV(){hc=void 0,mc=void 0,pc=void 0}a(DV,"resetPaths");ub.exports={getBaseSchemaPath:ib,getSystemSchemaPath:ob,getTransactionAuditStorePath:wV,getTransactionAuditStoreBasePath:ab,getSchemaPath:cb,initSystemSchemaPaths:CV,resetPaths:DV}});var Dr=g((oce,Eb)=>{"use strict";var LV=Cr().LMDB_ERRORS_ENUM,sce=require("lmdb"),MV=ut(),ice=require("buffer").Buffer,{OVERFLOW_MARKER:lb,MAX_SEARCH_KEY_LENGTH:a_}=MV,_b=["number","string","symbol","boolean","bigint"];function UV(e){if(e=e?.primaryStore||e,!e)throw new Error(LV.ENV_REQUIRED)}a(UV,"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 vV(e){return e instanceof Date?e.valueOf():e}a(vV,"convertKeyValueToWrite");function BV(e,t){if(e===null)return t?[null]:void 0;if(e===void 0)return;if(_b.includes(typeof e))return e.length>a_?[e.slice(0,a_)+lb]:[e];let r;if(Array.isArray(e)){r=[];for(let n=0,s=e.length;n<s;n++){let i=e[n];if(_b.includes(typeof i))i.length>a_?r.push(i.slice(0,a_)+lb):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(BV,"getIndexedValues");var c_=0,db=0;function fb(){db=Date.now()-performance.now()}a(fb,"adjustStartTime");fb();var HV=6e4;setInterval(fb,HV).unref();function xV(){let e=performance.now()+db;return e>c_?(c_=e,e):(c_+=488e-6,c_)}a(xV,"getNextMonotonicTime");Eb.exports={validateEnv:UV,stringifyData:PV,convertKeyValueToWrite:vV,getNextMonotonicTime:xV,getIndexedValues:BV}});var hb,yn,Vh,gc=ge(()=>{hb=require("events"),yn=class extends hb.EventEmitter{static{a(this,"IterableEventQueue")}resolveNext;queue;hasDataListeners;[Symbol.asyncIterator](){let t=new Vh;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)}},Vh=class{static{a(this,"EventQueueIterator")}queue;push(t){this.queue.send(t)}next(){let t=this.queue.getNextMessage();return t?{value:t}:new Promise(r=>this.queue.resolveNext=r)}return(t){return this.queue.emit("close"),{value:t,done:!0}}throw(t){return this.queue.emit("close",t),{done:!0}}}});var xi={};qe(xi,{server:()=>nt});var mb,nt,or=ge(()=>{mb=require("../index"),nt={};(0,mb._assignPackageExport)("server",nt)});var Kh={};qe(Kh,{loadGQLSchema:()=>FV,start:()=>Yh,startOnMainThread:()=>qV});function Yh({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 x=function(P){if(P.kind==="NonNullType"){let X=x(P.type);return X.nullable=!1,X}if(P.kind==="ListType")return{type:"array",elements:x(P.type)};let B={type:P.name?.value};return Object.defineProperty(B,"location",{value:P.loc.startToken}),B};a(x,"getProperty");let T=S.name.value,A=[],R={table:null,database:null,properties:A};f.set(T,R);for(let P of S.directives){if(P.name.value==="table"){for(let k of P.arguments)R[k.name.value]=k.value.value;R.schema&&(R.database=R.schema),R.table||(R.table=T),R.audit&&(R.audit=R.audit!=="false"),R.attributes=R.properties,E.push(R)}if(P.name.value==="sealed"&&(R.sealed=!0),P.name.value==="export"){R.export=!0;for(let k of P.arguments)k.name.value==="name"&&(R.export={name:k.value.value})}}let M=!1;for(let P of S.fields){let k=x(P.type);k.name=P.name.value,A.push(k);for(let B of P.directives)if(B.name.value==="primaryKey")M?console.warn("Can not define two attributes as a primary key"):(k.isPrimaryKey=!0,M=!0);else if(B.name.value==="indexed")k.indexed=!0;else if(B.name.value==="relationship"){let X={};for(let z of B.arguments)X[z.name.value]=z.value.value;k.relationship=X}else if(B.name.value==="createdTime")k.assignCreatedTime=!0;else if(B.name.value==="updatedTime")k.assignUpdatedTime=!0;else if(B.name.value==="expiresAt")k.expiresAt=!0;else if(B.name.value==="allow"){let X=k.authorizedRoles=[];for(let z of B.arguments)z.name.value==="role"&&X.push(z.value.value)}}R.type=T,T==="Query"&&(h=R)}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):GV.includes(S.type)||(0,pb.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,$h.dirname)(n),S.tableClass):i.set((0,$h.dirname)(n)+"/"+(S.export.name||S.type),S.tableClass))}}var $h,pb,GV,qV,FV,Sb=ge(()=>{$h=require("path");Re();pb=v(Ke()),GV=["ID","Int","Float","Long","String","Boolean","Date","Bytes","Any","BigInt"];a(Yh,"start");qV=Yh,FV=Yh({ensureTable:lt}).handleFile});async function u_(e){return kV?(Rc||(Rc=VV(YV)),(await(await Rc).import(e)).namespace):import(e)}async function VV(e){let{StaticModuleRecord:t}=await import("@endo/static-module-record");return require("ses"),lockdown({domainTaming:"unsafe",consoleTaming:"unsafe",errorTaming:"unsafe",errorTrapping:"none",stackFiltering:"verbose"}),Rc=new Compartment({console,Math,Date,fetch:$V,...e()},{},{name:"h-dapp",resolveHook(r,n){return r==="harperdb"?"harperdb":(r=new URL(r,n).toString(),(0,gb.extname)(r)||(r+=".js"),r)},importHook:async r=>{if(r==="harperdb")return{imports:[],exports:["Resource","tables","databases"],execute(s){Object.assign(s,{Resource:Ft,tables:Lr,databases:st})}};let n=await(0,Tb.readFile)(new URL(r),{encoding:"utf-8"});return new t(n,r)}}),Rc}function $V(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 YV(){return{Resource:Ft,tables:Lr}}var Tb,gb,kV,Rc,Wh=ge(()=>{Nn();Re();Tb=require("fs/promises"),gb=require("path"),kV=!1;a(u_,"secureImport");a(VV,"getCompartment");a($V,"secureOnlyFetch");a(YV,"getGlobalVars")});var zh={};qe(zh,{handleFile:()=>KV});async function KV(e,t,r,n){let s=new Map,i=(0,Rb.pathToFileURL)(r).toString(),o=await u_(i);u(o.default)&&n.set((0,Qh.dirname)(t),o.default),c(o,(0,Qh.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 Rb,Qh,Ab=ge(()=>{Rb=require("url");Wh();Qh=require("path");a(KV,"handleFile")});var Xh={};qe(Xh,{start:()=>WV});function WV({resources:e}){e.set("login",Jh),e.loginPath=t=>"/login?redirect="+encodeURIComponent(t.url)}var Jh,Ob=ge(()=>{Nn();a(WV,"start");Jh=class extends Ft{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 Db={};qe(Db,{parse:()=>Zh,streamAsJSON:()=>Ac,stringify:()=>Gi});function Ac(e){return new jh({value:e})}function bb(e){return console.error(e),JSON.stringify(e.toString())}function yb(e,t,r){return e?.then?r?e.then(t,r):e.then(t):t(e)}function Gi(e){try{return JSON.stringify(e)??"null"}catch(t){if(t===wb)return Cb(e);if(t.resolution)return t.resolution.then(()=>Gi(e));throw t}}function Cb(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+=Cb(e[n]);return r+"]"}else{r="{";let n=!0;for(let s in e)n?n=!1:r+=",",r+=JSON.stringify(s)+":"+Gi(e[s]);return r+"}"}}else{if(t==="string")return JSON.stringify(e);if(t==="undefined")return"null"}return e.toString()}function Zh(e){return JV.test(e)?QV.parse(e):JSON.parse(e)}var Nb,Ib,QV,zV,wb,jh,JV,em=ge(()=>{Nb=require("stream"),Ib=v(require("json-bigint-fixes")),QV=(0,Ib.default)({useNativeBigInt:!0}),zV=1e4,wb={};BigInt.prototype.toJSON=function(){throw wb};a(Ac,"streamAsJSON");jh=class extends Nb.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),bb)}catch(s){yield bb(s)}else yield Gi(t)}else yield Gi(t)}_read(){if(!this._amReading){if(this._amReading=!0,this.done)return this.push(null);yb(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>zV?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 yb(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(bb,"handleError");a(yb,"when");a(Gi,"stringify");a(Cb,"jsStringify");JV=/[[,:]\s*-?\d{16,}/;a(Zh,"parse")});var Vb=g((Ace,kb)=>{"use strict";var tm=require("recursive-iterator"),XV=require("alasql"),rm=require("clone"),Lb=Q(),{handleHDBError:Mb,hdb_errors:jV}=ne(),{HDB_ERROR_MSGS:Ub,HTTP_STATUS_CODES:Pb}=jV,{getDatabases:ZV}=(Re(),ie(Fe)),e$=["DISTINCT_ARRAY"],vb=Symbol("validateTables"),nm=Symbol("validateTable"),Rce=Symbol("getAllColumns"),Bb=Symbol("validateAllColumns"),l_=Symbol("findColumn"),Hb=Symbol("validateOrderBy"),Oc=Symbol("validateSegment"),sm=Symbol("validateColumn"),xb=Symbol("setColumnsForTable"),Gb=Symbol("checkColumnsForAsterisk"),qb=Symbol("validateGroupBy"),Fb=Symbol("hasColumns"),im=class{static{a(this,"SelectValidator")}constructor(t){this.statement=t,this.attributes=[]}validate(){if(!this.statement)throw new Error("invalid sql statement");this[vb](),this[Gb](),this[Bb]()}[vb](){if(this[Fb]()){if(!this.statement.from||this.statement.from.length===0)throw"no from clause";this.statement.from.forEach(t=>{this[nm](t)}),this.statement.joins&&this.statement.joins.forEach(t=>{t.table.as=t.as,this[nm](t.table)})}}[Fb](){let t=!1,r=new tm(this.statement);for(let{node:n,path:s}of r)if(n&&n.columnid){t=!0;break}return t}[nm](t){if(!t.databaseid)throw`schema not defined for table ${t.tableid}`;let r=ZV();if(!r[t.databaseid])throw Mb(new Error,Ub.SCHEMA_NOT_FOUND(t.databaseid),Pb.NOT_FOUND);if(!r[t.databaseid][t.tableid])throw Mb(new Error,Ub.TABLE_NOT_FOUND(t.databaseid,t.tableid),Pb.NOT_FOUND);r[t.databaseid][t.tableid].attributes.forEach(s=>{let i=rm(s);i.table=rm(t),this.attributes.push(i)})}[l_](t){return this.attributes.filter(r=>t.tableid?(r.table.as===t.tableid||r.table.tableid===t.tableid)&&r.attribute===t.columnid:r.attribute===t.columnid)}[Gb](){let t=new tm(this.statement.columns);for(let{node:r,path:n}of t)r&&r.columnid==="*"&&n.indexOf("expression")<0&&this[xb](r.tableid)}[xb](t){this.attributes.forEach(r=>{(!t||t&&(r.table.tableid===t||r.table.as===t))&&!r.relation&&this.statement.columns.push(new XV.yy.Column({columnid:r.attribute,tableid:r.table.as?r.table.as:r.table.tableid}))})}[Bb](){this[Oc](this.statement.columns,!1),this[Oc](this.statement.joins,!1),this[Oc](this.statement.where,!1),this[qb](this.statement.group,!1),this[Oc](this.statement.order,!0)}[Oc](t,r){if(!t)return;let n=new tm(t),s=[];for(let{node:i,path:o}of n)!Lb.isEmpty(i)&&!Lb.isEmpty(i.columnid)&&i.columnid!=="*"&&(r?this[Hb](i):s.push(this[sm](i)));return s}[qb](t){if(!t)return;let r=[];if(this.statement.columns.forEach(n=>{if(!(n.funcid&&e$.indexOf(n.funcid.toUpperCase())>=0)){if(!n.aggregatorid&&!n.columnid){let s=rm(n);delete s.as,r.push(s)}else if(n.columnid){let s=this[l_](n)[0];s&&r.push(s)}}}),this.statement.group.forEach(n=>{let s=null;if(!n.columnid)r.forEach((i,o)=>{if(i.toString()===n.toString()){s=i,r.splice(o,1);return}});else{let i=this[l_](n);if(!i||i.length===0)throw`unknown column '${n.toString()}' in group by`;if(i.length>1)throw`ambiguously defined column '${n.toString()}' in group by`;r.forEach((o,c)=>{if(o.attribute===i[0].attribute&&o.table.tableid===i[0].table.tableid){s=o,r.splice(c,1);return}})}if(!s)throw`group by column '${n.toString()}' must be in select`}),r.length>0)throw`select column '${r[0].attribute?r[0].attribute:r[0].toString()}' must be in group by`}[Hb](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[sm](t)}[sm](t){let r=this[l_](t),n=(t.tableid?t.tableid+".":"")+t.columnid;if(r.length===0)throw`unknown column ${n}`;if(r.length>1)throw`ambiguous column reference ${n}`;return r[0]}};kb.exports=im});var Yb=g((bce,$b)=>{"use strict";var om=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")}};$b.exports=om});var Wb=g((Nce,Kb)=>{"use strict";var am=class{static{a(this,"DBIDefinition")}constructor(t=!1,r=!1){this.dup_sort=t,this.is_hash_attribute=r,this.useVersions=r}};Kb.exports=am});var Xb={};qe(Xb,{HAS_EXPIRATION:()=>Em,LAST_TIMESTAMP_PLACEHOLDER:()=>Nc,LOCAL_TIMESTAMP:()=>t$,METADATA:()=>bc,NO_TIMESTAMP:()=>um,PENDING_LOCAL_TIME:()=>hm,PREVIOUS_TIMESTAMP_PLACEHOLDER:()=>fm,RecordEncoder:()=>dm,TIMESTAMP_ASSIGN_LAST:()=>n$,TIMESTAMP_ASSIGN_NEW:()=>zb,TIMESTAMP_ASSIGN_PREVIOUS:()=>Jb,TIMESTAMP_PLACEHOLDER:()=>__,TIMESTAMP_RECORD_PREVIOUS:()=>lm,getUpdateRecord:()=>mm,handleLocalTimeForGets:()=>h_});function i$(){return yc[0]=yc[0]^64,r$.getFloat64(0)}function h_(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?.[bc];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?.[bc]>=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[bc];return _>=0&&(c.metadataFlags=_,c.localTime=u.localTime,c.value=u.value,u.expiresAt>0&&(c.expiresAt=u.expiresAt)),c})};let s=e.useReadTransaction();if(s.done(),!s.done.isTracked){let i=s.constructor,o=s.use,c=s.done;i.prototype.use=function(){this.timerTracked||(this.timerTracked=!0,qi.push(new WeakRef(this))),o.call(this)},i.prototype.done=function(){if(c.call(this),this.isDone)for(let u=0;u<qi.length;u++){let _=qi[u].deref();(!_||_.isDone||_.isCommitted)&&qi.splice(u--,1)}},i.prototype.done.isTracked=!0}return e}function mm(e,t,r){return function(n,s,i,o,c=-1,u,_,l,d="put",f,E){if(f||u==null?Vo=i?.localTime?lm|Jb:um:Vo=u?i?.localTime?lm|16384:zb|16384:um,l>0&&(c|=Em),f_=c,_m=l,i?.version===o&&u===!1)throw new Error("Must retain local time if version is not changed");let h={version:o,instructedWrite:Vo>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&&(d_=e.encoder.encode(E)),f&&i?.localTime){let A=i?.localTime,R=r.get(A);if(R){let M=Mt(R).previousLocalTime;return r.put(A,E_(o,t,n,M,T,d,d_),{ifVersion:p}),S}}r.put(Nc,E_(o,t,n,i?.localTime?1:0,T,d,d_),{append:d!=="invalidate",instructedWrite:!0,ifVersion:p})}return S}catch(S){throw S.message+=" id: "+n+" options: "+h,S}}}var Qb,cm,__,Nc,fm,t$,bc,yc,r$,um,zb,n$,Jb,lm,Em,hm,s$,d_,Vo,f_,_m,dm,qi,Ic=ge(()=>{Qb=require("msgpackr");ei();cm=v($()),__=new Uint8Array([1,1,1,1,4,64,0,0]),Nc=new Uint8Array([1,1,1,1,1,0,0,0]),fm=new Uint8Array([1,1,1,1,3,64,0,0]),t$=Symbol("local-timestamp"),bc=Symbol("metadata"),yc=new Uint8Array(8),r$=new DataView(yc.buffer,0,8),um=0,zb=0,n$=1,Jb=3,lm=4,Em=16,hm=1,Vo=0,f_=-1,_m=0,dm=class extends Qb.Encoder{static{a(this,"RecordEncoder")}constructor(t){t.useBigIntExtension=!0,super(t);let r=this.encode;this.encode=function(n,s){if(Vo||f_>=0){let i=0,o=Vo;o&&(i+=8,Vo=0);let c=f_,u=_m;c>=0&&(i+=2,f_=-1,u&&(i+=8,_m=0));let _=s$=r.call(this,n,s|2048|i);d_=_.subarray((_.start||0)+i,_.end);let l=_.start||0;return o&&(__[4]=o,__[5]=o>>8,_.set(__,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(yc,0,c),c+=8;else for(let d=0;d<8;d++)yc[d]=t[c++];u=i$(),i=t[c]}let _;i<32&&(o=i,c+=2,o&Em&&(_=(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,[bc]:o,expiresAt:_}}return super.decode(t,r)}catch(c){throw c.message+=", data: "+t.slice(0,40).toString("hex"),c}}};a(i$,"getTimestamp");a(h_,"handleLocalTimeForGets");qi=[];setInterval(()=>{for(let e=0;e<qi.length;e++){let t=qi[e].deref();!t||t.isDone||t.isCommitted?qi.splice(e--,1):t.notCurrent&&(t.openTimer?(t.openTimer>3&&(t.openTimer>60?(cm.error("Read transaction detected that has been open too long (over 15 minutes), ending transaction",t),t.done()):cm.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(mm,"getUpdateRecord")});var wc=g((Lce,Zb)=>{"use strict";var jb=ee(),o$=L(),{RecordEncoder:a$}=(Ic(),ie(Xb)),Dce=require("fs");jb.initSync();var c$=jb.get(o$.CONFIG_PARAMS.STORAGE_CACHING)!==!1,pm=class{static{a(this,"OpenDBIObject")}constructor(t,r=!1){this.dupSort=t===!0,this.encoding=t?"ordered-binary":"msgpack",this.useVersions=r,this.sharedStructuresKey=Symbol.for("structures"),r&&(this.cache=c$&&{validated:!0},this.randomAccessStructure=!0,this.freezeData=!0,this.encoder={Encoder:a$})}};Zb.exports=pm});var Cc=g((Uce,ey)=>{"use strict";var Mr=ee(),sn=L();Mr.initSync();var m_=class{static{a(this,"OpenEnvironmentObject")}constructor(t,r=!1){this.path=t,this.mapSize=1073741824,this.maxDbs=1e4,this.maxReaders=1e3,this.sharedStructuresKey=Symbol.for("structures"),this.readOnly=r,this.trackMetrics=!0,this.eventTurnBatching=!1,this.noSync=Mr.get(sn.CONFIG_PARAMS.STORAGE_WRITEASYNC)===!0||Mr.get(sn.CONFIG_PARAMS.STORAGE_WRITEASYNC)==="true"||Mr.get(sn.CONFIG_PARAMS.STORAGE_WRITEASYNC)==="TRUE",Mr.get(sn.CONFIG_PARAMS.STORAGE_OVERLAPPINGSYNC)!==void 0&&(this.overlappingSync=Mr.get(sn.CONFIG_PARAMS.STORAGE_OVERLAPPINGSYNC)),Mr.get(sn.CONFIG_PARAMS.STORAGE_MAXFREESPACETOLOAD)&&(this.maxFreeSpaceToLoad=Mr.get(sn.CONFIG_PARAMS.STORAGE_MAXFREESPACETOLOAD)),Mr.get(sn.CONFIG_PARAMS.STORAGE_MAXFREESPACETORETAIN)&&(this.maxFreeSpaceToRetain=Mr.get(sn.CONFIG_PARAMS.STORAGE_MAXFREESPACETORETAIN)),Mr.get(sn.CONFIG_PARAMS.STORAGE_PAGESIZE)&&(this.pageSize=Mr.get(sn.CONFIG_PARAMS.STORAGE_PAGESIZE)),this.noReadAhead=Mr.get(sn.CONFIG_PARAMS.STORAGE_NOREADAHEAD)}};ey.exports=m_;m_.MAX_DBS=1e4});var We=g((vce,ly)=>{"use strict";var Tm=require("lmdb"),In=require("fs-extra"),Ur=require("path"),p_=Dr(),ny=$(),ar=Cr().LMDB_ERRORS_ENUM,S_=Wb(),gm=wc(),sy=Cc(),ti=ut(),ty=L(),{table:u$,resetDatabases:l$}=(Re(),ie(Fe)),ry=ee(),wn=ti.INTERNAL_DBIS_NAME,iy=ti.DBI_DEFINITION_NAME,_$="data.mdb",d$="lock.mdb",Dc=".mdb",f$="-lock",Sm=class{static{a(this,"TransactionCursor")}constructor(t,r,n=!1){this.dbi=on(t,r),this.key_type=this.dbi[ti.DBI_DEFINITION_NAME].key_type,this.is_hash_attribute=this.dbi[ti.DBI_DEFINITION_NAME].is_hash_attribute,this.txn=t.beginTxn({readOnly:n===!1}),this.cursor=new Tm.Cursor(this.txn,this.dbi)}close(){this.cursor.close(),this.txn.abort()}commit(){this.cursor.close(),this.txn.commit()}};function T_(e,t){if(e===void 0)throw new Error(ar.BASE_PATH_REQUIRED);if(t===void 0)throw new Error(ar.ENV_NAME_REQUIRED)}a(T_,"pathEnvNameValidation");async function Rm(e,t,r=!0){try{await In.access(e)}catch(n){throw n.code==="ENOENT"?new Error(ar.INVALID_BASE_PATH):n}try{let n=Ur.join(e,t+Dc);return await In.access(n,In.constants.R_OK|In.constants.F_OK),n}catch(n){if(n.code==="ENOENT")if(r)try{return await In.access(Ur.join(e,t,_$),In.constants.R_OK|In.constants.F_OK),Ur.join(e,t)}catch(s){if(s.code==="ENOENT")throw new Error(ar.INVALID_ENVIRONMENT)}else throw new Error(ar.INVALID_ENVIRONMENT);throw n}}a(Rm,"validateEnvironmentPath");function g_(e,t){if(p_.validateEnv(e),t===void 0)throw new Error(ar.DBI_NAME_REQUIRED)}a(g_,"validateEnvDBIName");async function E$(e,t,r=!1,n=!1){T_(e,t);let s=Ur.basename(e);t=t.toString();let i=ry.get(ty.CONFIG_PARAMS.DATABASES);i||ry.setProperty(ty.CONFIG_PARAMS.DATABASES,i={}),i[s]||(i[s]={}),i[s].path=e;try{return await Rm(e,t,n),oy(e,t,r)}catch(o){if(o.message===ar.INVALID_ENVIRONMENT){let c=Ur.join(e,t);await In.mkdirp(n?c:e);let u=new sy(n?c:c+Dc,!1),_=Tm.open(u);_.dbis=Object.create(null);let l=new gm(!1);_.openDB(wn,l),global.lmdb_map===void 0&&(global.lmdb_map=Object.create(null));let d=Am(e,t,r);return _[ti.ENVIRONMENT_NAME_KEY]=d,global.lmdb_map[d]=_,_}throw o}}a(E$,"createEnvironment");async function h$(e,t,r,n=!0){T_(e,t),t=t.toString();let s=Ur.join(e,t);return u$({table:t,database:Ur.parse(e).name,path:s,attributes:[{name:"id",isPrimaryKey:!0}]})}a(h$,"copyEnvironment");async function oy(e,t,r=!1){T_(e,t),t=t.toString();let n=Am(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 Rm(e,t),i=Ur.join(e,t+Dc),o=s!=i,c=new sy(s,o),u=Tm.open(c);u.dbis=Object.create(null);let _=cy(u);for(let l=0;l<_.length;l++)on(u,_[l]);return u[ti.ENVIRONMENT_NAME_KEY]=n,global.lmdb_map[n]=u,u}a(oy,"openEnvironment");async function m$(e,t,r=!1){T_(e,t),t=t.toString();let n=Ur.join(e,t+Dc),s=await Rm(e,t);if(global.lmdb_map!==void 0){let i=Am(e,t,r);if(global.lmdb_map[i]){let o=global.lmdb_map[i];await ay(o),delete global.lmdb_map[i]}}await In.remove(s),await In.remove(s===n?s+f$:Ur.join(Ur.dirname(s),d$))}a(m$,"deleteEnvironment");async function ay(e){p_.validateEnv(e);let t=e[ti.ENVIRONMENT_NAME_KEY];await e.close(),t!==void 0&&global.lmdb_map!==void 0&&delete global.lmdb_map[t]}a(ay,"closeEnvironment");function Am(e,t,r=!1){let s=`${Ur.basename(e)}.${t}`;return r===!0&&(s=`txn.${s}`),s}a(Am,"getCachedEnvironmentName");function p$(e){p_.validateEnv(e);let t=Object.create(null),r=on(e,wn);for(let{key:n,value:s}of r.getRange({start:!1}))if(n!==wn)try{t[n]=Object.assign(new S_,s)}catch{ny.warn(`an internal error occurred: unable to parse DBI Definition for ${n}`)}return t}a(p$,"listDBIDefinitions");function cy(e){p_.validateEnv(e);let t=[],r=on(e,wn);for(let{key:n}of r.getRange({start:!1}))n!==wn&&t.push(n);return t}a(cy,"listDBIs");function S$(e,t){let n=on(e,wn).getEntry(t),s=new S_;if(n!==void 0){try{s=Object.assign(s,n.value)}catch{ny.warn(`an internal error occurred: unable to parse DBI Definition for ${n}`)}return s}}a(S$,"getDBIDefinition");function uy(e,t,r,n=!r){if(g_(e,t),t=t.toString(),t===wn)throw new Error(ar.CANNOT_CREATE_INTERNAL_DBIS_NAME);try{return on(e,t)}catch(s){if(s.message===ar.DBI_DOES_NOT_EXIST){let i=new gm(r,n===!0),o=e.openDB(t,i),c=new S_(r===!0,n);return o[iy]=c,on(e,wn).putSync(t,c),e.dbis[t]=o,o}throw s}}a(uy,"createDBI");function on(e,t){if(g_(e,t),t=t.toString(),e.dbis[t]!==void 0)return e.dbis[t];let r;if(t!==wn?r=S$(e,t):r=new S_,r===void 0)throw new Error(ar.DBI_DOES_NOT_EXIST);let n;try{let s=new gm(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(ar.DBI_DOES_NOT_EXIST):s}return n[iy]=r,e.dbis[t]=n,n}a(on,"openDBI");function T$(e,t){g_(e,t),t=t.toString();let r=on(e,t),n=r.getStats();return r[ti.DBI_DEFINITION_NAME].is_hash_attribute&&n.entryCount>0&&n.entryCount--,n}a(T$,"statDBI");async function g$(e,t){try{let r=Ur.join(e,t+Dc);return(await In.stat(r)).size}catch{throw new Error(ar.INVALID_ENVIRONMENT)}}a(g$,"environmentDataSize");function R$(e,t){if(g_(e,t),t=t.toString(),t===wn)throw new Error(ar.CANNOT_DROP_INTERNAL_DBIS_NAME);on(e,t).dropSync(),e.dbis!==void 0&&delete e.dbis[t],on(e,wn).removeSync(t)}a(R$,"dropDBI");function A$(e,t,r){let n;for(let s=0;s<r.length;s++){let i=r[s];if(!e.dbis[i])try{on(e,i)}catch(o){if(o.message===ar.DBI_DOES_NOT_EXIST)uy(e,i,i!==t,i===t),n=!0;else throw o}}n&&l$()}a(A$,"initializeDBIs");ly.exports={openDBI:on,openEnvironment:oy,createEnvironment:E$,listDBIs:cy,listDBIDefinitions:p$,createDBI:uy,dropDBI:R$,statDBI:T$,deleteEnvironment:m$,initializeDBIs:A$,TransactionCursor:Sm,environmentDataSize:g$,copyEnvironment:h$,closeEnvironment:ay}});var dy=g((Hce,_y)=>{"use strict";var Om=class{static{a(this,"InsertRecordsResponseObject")}constructor(t=[],r=[],n=void 0){this.written_hashes=t,this.skipped_hashes=r,this.txn_time=n}};_y.exports=Om});var Ey=g((Gce,fy)=>{"use strict";var bm=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}};fy.exports=bm});var my=g((Fce,hy)=>{"use strict";var ym=class{static{a(this,"UpsertRecordsResponseObject")}constructor(t=[],r=void 0,n=[]){this.written_hashes=t,this.txn_time=r,this.original_records=n}};hy.exports=ym});var $o=g((Kce,Ty)=>{"use strict";var O$=We(),b$=dy(),y$=Ey(),N$=my(),Qn=Dr(),Lc=Cr().LMDB_ERRORS_ENUM,I$=ut(),Ts=L(),w$=Q(),C$=require("uuid"),Vce=require("lmdb"),{handleHDBError:D$,hdb_errors:L$}=ne(),{OVERFLOW_MARKER:$ce,MAX_SEARCH_KEY_LENGTH:Yce}=I$,py=ee();py.initSync();var R_=py.get(Ts.CONFIG_PARAMS.STORAGE_PREFETCHWRITES),Nm=Ts.TIME_STAMP_NAMES_ENUM.CREATED_TIME,Fi=Ts.TIME_STAMP_NAMES_ENUM.UPDATED_TIME;async function M$(e,t,r,n,s=Qn.getNextMonotonicTime()){Dm(e,t,r,n),Im(e,t,r);let i=new b$,o=[],c=[];for(let u=0;u<n.length;u++){let _=n[u];Sy(_,!0,s);let l=U$(e,t,r,_),d=_[t];o.push(l),c.push(d)}return wm(o,c,n,i,s)}a(M$,"insertRecords");function U$(e,t,r,n){let s=n[t];return e.dbis[t].ifNoExists(s,()=>{for(let i=0;i<r.length;i++){let o=r[i];if(o===t||n.hasOwnProperty(o)===!1)continue;let c=n[o];if(typeof c=="function"){let l=c([[{}]]);Array.isArray(l)&&(c=l[0][Ts.FUNC_VAL],n[o]=c)}let u=Qn.getIndexedValues(c),_=e.dbis[o];if(u){R_&&_.prefetch(u.map(l=>({key:l,value:s})),A_);for(let l=0,d=u.length;l<d;l++)_.put(u[l],s)}}R_&&e.dbis[t].prefetch([s],A_),e.dbis[t].put(s,n,n[Fi])})}a(U$,"insertRecord");function P$(e,t=[]){let r=0;for(let n=0;n<t.length;n++){let s=t[n];e.splice(s-r,1),r++}}a(P$,"removeSkippedRecords");function Sy(e,t,r){let n=r>0;(n||!Number.isInteger(e[Fi]))&&(e[Fi]=r||(r=Qn.getNextMonotonicTime())),t===!0?(n||!Number.isInteger(e[Nm]))&&(e[Nm]=r||Qn.getNextMonotonicTime()):delete e[Nm]}a(Sy,"setTimestamps");function Im(e,t,r){r.indexOf(Ts.TIME_STAMP_NAMES_ENUM.CREATED_TIME)<0&&r.push(Ts.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.indexOf(Ts.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)<0&&r.push(Ts.TIME_STAMP_NAMES_ENUM.UPDATED_TIME),O$.initializeDBIs(e,t,r)}a(Im,"initializeTransaction");async function v$(e,t,r,n,s=Qn.getNextMonotonicTime()){Dm(e,t,r,n),Im(e,t,r);let i=new y$,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 wm(c,u,n,i,s,o)}a(v$,"updateRecords");async function B$(e,t,r,n,s=Qn.getNextMonotonicTime()){try{Dm(e,t,r,n)}catch(u){throw D$(u,u.message,L$.HTTP_STATUS_CODES.BAD_REQUEST)}Im(e,t,r);let i=new N$,o=[],c=[];for(let u=0;u<n.length;u++){let _=n[u],l;w$.isEmpty(_[t])?(l=C$.v4(),_[t]=l):l=_[t];let d=Cm(e,t,_,l,i,!1,s);o.push(d),c.push(l)}return wm(o,c,n,i,s)}a(B$,"upsertRecords");async function wm(e,t,r,n,s,i=[]){let o=await Promise.all(e);for(let c=0,u=o.length;c<u;c++)o[c]===!0?n.written_hashes.push(t[c]):(n.skipped_hashes.push(t[c]),i.push(c));return n.txn_time=s||Qn.getNextMonotonicTime(),P$(r,i),n}a(wm,"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(Sy(r,!l,o),Number.isInteger(r[Fi])&&_[Fi]>r[Fi])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 R=p([[_]]);Array.isArray(R)&&(p=R[0][Ts.FUNC_VAL],r[h]=p)}if(p===T)continue;let A=Qn.getIndexedValues(T);if(A){R_&&S.prefetch(A.map(R=>({key:R,value:n})),A_);for(let R=0,M=A.length;R<M;R++)S.remove(A[R],n)}if(A=Qn.getIndexedValues(p),A){R_&&S.prefetch(A.map(R=>({key:R,value:n})),A_);for(let R=0,M=A.length;R<M;R++)S.put(A[R],n)}}let E=Object.assign({},_,r);c.put(n,E,E[Fi])},"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 H$(e,t,r){if(Qn.validateEnv(e),t===void 0)throw new Error(Lc.HASH_ATTRIBUTE_REQUIRED);if(!Array.isArray(r))throw r===void 0?new Error(Lc.WRITE_ATTRIBUTES_REQUIRED):new Error(Lc.WRITE_ATTRIBUTES_MUST_BE_ARRAY)}a(H$,"validateBasic");function Dm(e,t,r,n){if(H$(e,t,r),!Array.isArray(n))throw n===void 0?new Error(Lc.RECORDS_REQUIRED):new Error(Lc.RECORDS_MUST_BE_ARRAY)}a(Dm,"validateWrite");function A_(){}a(A_,"noop");Ty.exports={insertRecords:M$,updateRecords:v$,upsertRecords:B$}});var ki=g((Qce,x$)=>{x$.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 Jn=g((zce,Ay)=>{"use strict";var Ry=Q(),gy=L(),Yo=/^[\x20-\x2E|\x30-\x5F|\x61-\x7E]*$/,zn=require("joi"),ri={schema_format:{pattern:Yo,message:"names cannot include backticks or forward slashes"},schema_length:{minimum:1,maximum:250,tooLong:"cannot exceed 250 characters"}},G$=zn.alternatives(zn.string().min(1).max(ri.schema_length.maximum).pattern(Yo).messages({"string.pattern.base":"{:#label} "+ri.schema_format.message}),zn.number(),zn.array()).required(),q$=zn.alternatives(zn.string().min(1).max(ri.schema_length.maximum).pattern(Yo).messages({"string.pattern.base":"{:#label} "+ri.schema_format.message}),zn.number()),F$=zn.alternatives(zn.string().min(1).max(ri.schema_length.maximum).pattern(Yo).messages({"string.pattern.base":"{:#label} "+ri.schema_format.message}),zn.number()).required();function k$(e,t){return t?typeof t!="string"?`'${e}' must be a string`:t.length?t.length>ri.schema_length.maximum?`'${e}' maximum of 250 characters`:Yo.test(t)?"":`'${e}' has illegal characters`:`'${e}' must be at least one character`:`'${e}' is required`}a(k$,"checkValidTable");function V$(e,t){return Ry.doesSchemaExist(e)?e:t.message(`Database '${e}' does not exist`)}a(V$,"validateSchemaExists");function $$(e,t){let r=t.state.ancestors[0].schema;return Ry.doesTableExist(r,e)?e:t.message(`Table '${e}' does not exist`)}a($$,"validateTableExists");function Y$(e,t){return e.toLowerCase()===gy.SYSTEM_SCHEMA_NAME?t.message(`'subscriptions[${t.state.path[1]}]' invalid database name, '${gy.SYSTEM_SCHEMA_NAME}' name is reserved`):e}a(Y$,"validateSchemaName");Ay.exports={common_validators:ri,schema_regex:Yo,hdb_schema_table:G$,validateSchemaExists:V$,validateTableExists:$$,validateSchemaName:Y$,checkValidTable:k$,hdb_database:q$,hdb_table:F$}});var Xe=g((Xce,Oy)=>{"use strict";var cr=require("validate.js");cr.validators.type=function(e,t,r,n){return e===null||typeof e>"u"||cr.validators.type.checks[t](e)?null:` must be a '${t}' value`};cr.validators.type.checks={Object:function(e){return cr.isObject(e)&&!cr.isArray(e)},Array:cr.isArray,Integer:cr.isInteger,Number:cr.isNumber,String:cr.isString,Date:cr.isDate,Boolean:function(e){return typeof e=="boolean"}};cr.validators.hasValidFileExt=function(e,t){return cr.isString(e)?e===""?"can't be blank":t.filter(r=>e.endsWith(r)).length>0?null:`must include one of the following valid file extensions - '${t.join("', '")}'`:null};Oy.exports={validateObject:K$,validateObjectAsync:W$,validateBySchema:Q$};function K$(e,t){if(!e||!t)return new Error("validateObject parameters were null");let r=cr(e,t,{format:"flat"});return r?new Error(r):null}a(K$,"validateObject");async function W$(e,t){if(!e||!t)return new Error("validateObject parameters were null");try{await cr.async(e,t,{format:"flat"})}catch(r){let n=r.join(",");return new Error(n)}return null}a(W$,"validateObjectAsync");function Q$(e,t){let r=t.validate(e,{allowUnknown:!0,abortEarly:!1,errors:{wrap:{label:"'"}}});if(r.error)return new Error(r.error.message)}a(Q$,"validateBySchema")});var O_=g((Zce,by)=>{var{common_validators:Xn}=Jn(),Uc=Xe(),Mc="is required",mt={database:{presence:!1,format:Xn.schema_format,length:Xn.schema_length},schema:{presence:!1,format:Xn.schema_format,length:Xn.schema_length},table:{presence:!0,format:Xn.schema_format,length:Xn.schema_length},attribute:{presence:!0,format:Xn.schema_format,length:Xn.schema_length},hash_attribute:{presence:!0,format:Xn.schema_format,length:Xn.schema_length}};function Pc(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(Pc,"makeAttributesStrings");function z$(e){return e=Pc(e),mt.table.presence=!1,mt.attribute.presence=!1,mt.hash_attribute.presence=!1,Uc.validateObject(e,mt)}a(z$,"schema_object");function J$(e){return e=Pc(e),mt.table.presence={message:Mc},mt.attribute.presence=!1,mt.hash_attribute.presence=!1,Uc.validateObject(e,mt)}a(J$,"table_object");function X$(e){return e=Pc(e),mt.table.presence={message:Mc},mt.attribute.presence=!1,Uc.validateObject(e,mt)}a(X$,"create_table_object");function j$(e){return e=Pc(e),mt.table.presence={message:Mc},mt.attribute.presence={message:Mc},mt.hash_attribute.presence=!1,Uc.validateObject(e,mt)}a(j$,"attribute_object");function Z$(e){return e=Pc(e),mt.table.presence={message:Mc},mt.attribute.presence=!1,mt.hash_attribute.presence=!1,Uc.validateObject(e,mt)}a(Z$,"describe_table");function e1(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(e1,"validateTableResidence");by.exports={schema_object:z$,create_table_object:X$,table_object:J$,attribute_object:j$,describe_table:Z$,validateTableResidence:e1}});var Ny=g((tue,yy)=>{"use strict";var t1=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||t1.v4(),this.schema_table=`${this.schema}.${this.table}`}};yy.exports=Lm});var b_=g((nue,Iy)=>{"use strict";var r1=Ny(),Mm=class extends r1{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}};Iy.exports=Mm});var Cy=g((iue,wy)=>{"use strict";wy.exports=s1;var n1="inserted";function s1(e,t,r,n){let s={message:`${e} ${t.length} of ${r.records.length} records`,skipped_hashes:n};return e===n1?(s.inserted_hashes=t,s):(s.update_hashes=t,s)}a(s1,"returnObject")});var y_=g((aue,Py)=>{"use strict";var i1=L(),Um=We(),o1=$o(),{getSystemSchemaPath:a1,getSchemaPath:c1}=Je(),u1=ki(),l1=O_(),_1=b_(),d1=Cy(),{handleHDBError:Dy,hdb_errors:My}=ne(),Ly=Q(),{HTTP_STATUS_CODES:f1}=My,Pm=u1.hdb_attribute,Uy=[];for(let e=0;e<Pm.attributes.length;e++)Uy.push(Pm.attributes[e].attribute);var E1="inserted";Py.exports=h1;async function h1(e){let t=l1.attribute_object(e);if(t)throw Dy(new Error,t.message,My.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0);let r=!e.skip_table_check&&Ly.checkGlobalSchemaTable(e.schema,e.table);if(r)throw Dy(new Error,r,f1.NOT_FOUND);e.is_hash_attribute=e.is_hash_attribute=="true",e.dup_sort=Ly.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 _1(e.schema,e.table,e.attribute,e.id);try{let i=await Um.openEnvironment(c1(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}`);Um.createDBI(i,e.attribute,e.dup_sort,e.is_hash_attribute);let o=await Um.openEnvironment(a1(),i1.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME),{written_hashes:c,skipped_hashes:u}=await o1.insertRecords(o,Pm.hash_attribute,Uy,[s]);return d1(E1,c,{records:[s]},u)}catch(i){throw i}}a(h1,"lmdbCreateAttribute")});var Bm=g((uue,By)=>{var{hdb_table:m1,hdb_database:vy}=Jn(),p1=Xe(),vm=require("joi"),S1={undefined:"undefined",null:"null"},T1=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"),g1=vm.object({database:vy,schema:vy,table:m1,records:vm.array().items(vm.object().custom(T1)).required()});By.exports=function(e){return p1.validateBySchema(e,g1)}});var vc=g((due,xy)=>{"use strict";var gs=Q(),Hy=$(),_ue=Bm(),{getDatabases:R1}=(Re(),ie(Fe)),{ClientError:Vi}=ne();xy.exports=A1;function A1(e){if(gs.isEmpty(e))throw new Vi("invalid update parameters defined.");if(gs.isEmptyOrZeroLength(e.schema))throw new Vi("invalid schema specified.");if(gs.isEmptyOrZeroLength(e.table))throw new Vi("invalid table specified.");if(!Array.isArray(e.records))throw new Vi("records must be an array");let t=R1()[e.schema]?.[e.table];if(gs.isEmpty(t))throw new Vi(`could not retrieve schema:${e.schema} and table ${e.table}`);let r=t.primaryKey,n=new Set,s={},i=!1;return e.operation==="update"&&(i=!0),e.records.forEach(o=>{if(i&&gs.isEmptyOrZeroLength(o[r]))throw Hy.error("a valid hash attribute must be provided with update record:",o),new Vi("a valid hash attribute must be provided with update record, check log for more info");if(!gs.isEmptyOrZeroLength(o[r])&&(o[r]==="null"||o[r]==="undefined"))throw Hy.error(`a valid hash value must be provided with ${e.operation} record:`,o),new Vi(`Invalid hash value: '${o[r]}' is not a valid hash attribute value, check log for more info`);!gs.isEmpty(o[r])&&o[r]!==""&&n.has(gs.autoCast(o[r]))&&(o.skip=!0),n.add(gs.autoCast(o[r]));for(let c in o)s[c]=1}),s[r]=1,{schema_table:t,hashes:Array.from(n),attributes:Object.keys(s)}}a(A1,"insertUpdateValidate")});var Bc=g((Eue,Gy)=>{"use strict";var O1=L().OPERATIONS_ENUM,Hm=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}};Gy.exports=Hm});var Hc=g((pue,Fy)=>{"use strict";var mue=Bc(),N_=L(),xm=Q(),qy=$(),b1=require("uuid"),{handleHDBError:I_,hdb_errors:y1}=ne(),{HDB_ERROR_MSGS:w_,HTTP_STATUS_CODES:C_}=y1;Fy.exports=N1;function N1(e,t,r){for(let s=0;s<t.length;s++)I1(t[s]);let{records:n}=e;for(let s=0;s<n.length;s++){let i=n[s];w1(i,r,e.operation)}}a(N1,"processRows");function I1(e){if(Buffer.byteLength(String(e))>N_.INSERT_MODULE_ENUM.MAX_CHARACTER_SIZE)throw I_(new Error,w_.ATTR_NAME_LENGTH_ERR(e),C_.BAD_REQUEST,void 0,void 0,!0);if(xm.isEmptyOrZeroLength(e)||xm.isEmpty(e.trim()))throw I_(new Error,w_.ATTR_NAME_NULLISH_ERR,C_.BAD_REQUEST,void 0,void 0,!0)}a(I1,"validateAttribute");function w1(e,t,r){if(!e.hasOwnProperty(t)||xm.isEmptyOrZeroLength(e[t])){if(r===N_.OPERATIONS_ENUM.INSERT||r===N_.OPERATIONS_ENUM.UPSERT){e[t]=b1.v4();return}throw qy.error("Update transaction aborted due to record with no hash value:",e),I_(new Error,w_.RECORD_MISSING_HASH_ERR,C_.BAD_REQUEST,void 0,void 0,!0)}if(Buffer.byteLength(String(e[t]))>N_.INSERT_MODULE_ENUM.MAX_CHARACTER_SIZE)throw qy.error(e),I_(new Error,w_.HASH_VAL_LENGTH_ERR,C_.BAD_REQUEST,void 0,void 0,!0)}a(w1,"validateHash")});var Vy=g((Tue,ky)=>{"use strict";var Gm=class{static{a(this,"ITCEventObject")}constructor(t,r){this.type=t,this.message=r}};ky.exports=Gm});var Ky=g((Rue,Yy)=>{"use strict";var qm=We(),C1=$(),$y=Cr().LMDB_ERRORS_ENUM;Yy.exports=D1;async function D1(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 qm.closeEnvironment(global.lmdb_map[o])}catch(c){if(c.message!==$y.ENV_REQUIRED)throw c}}break;case"drop_table":let n=`${e.schema}.${e.table}`,s=`txn.${n}`;try{await qm.closeEnvironment(global.lmdb_map[n]),await qm.closeEnvironment(global.lmdb_map[s])}catch(i){if(i.message!==$y.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){C1.error(t)}}a(D1,"cleanLMDBMap")});var Rs=g((Oue,Jy)=>{"use strict";var xc=require("crypto"),L1=ee(),{CONFIG_PARAMS:M1}=L(),Qy="aes-256-cbc",U1=32,P1=16,Fm=64,zy=32,v1=Fm+zy,Wy=new Map;Jy.exports={encrypt:B1,decrypt:H1,createNatsTableStreamName:x1};function B1(e){let t=xc.randomBytes(U1),r=xc.randomBytes(P1),n=xc.createCipheriv(Qy,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(B1,"encrypt");function H1(e){let t=e.substr(0,Fm),r=e.substr(Fm,zy),n=e.substr(v1,e.length),s=Buffer.from(r,"hex"),i=Buffer.from(n,"hex"),o=xc.createDecipheriv(Qy,Buffer.from(t,"hex"),s),c=o.update(i);return c=Buffer.concat([c,o.final()]),c.toString()}a(H1,"decrypt");function x1(e,t){let r=L1.get(M1.CLUSTERING_DATABASELEVEL)?e:`${e}.${t}`,n=Wy.get(r);return n||(n=xc.createHash("md5").update(r).digest("hex"),Wy.set(r,n)),n}a(x1,"createNatsTableStreamName")});var As=g((Nue,jy)=>{"use strict";var yue=Pr(),D_=$(),Xy=O_(),G1=Rs(),L_=Q(),{handleHDBError:M_,hdb_errors:q1}=ne(),{HDB_ERROR_MSGS:U_,HTTP_STATUS_CODES:km}=q1,F1=ee();F1.initSync();var{getDatabases:Vm}=(Re(),ie(Fe));jy.exports={describeAll:k1,describeTable:P_,describeSchema:V1};async function k1(e){try{let t=L_.isEmptyOrZeroLength(e),r,n;t||(r=e.hdb_user.role.permission,n=r.super_user||r.cluster_user);let s=Vm(),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 P_({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 P_({schema:l,table:f,exact_count:u},h)}E&&c.push(E)}catch(E){D_.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 D_.error("Got an error in describeAll"),D_.error(t),M_(new Error,U_.DESCRIBE_ALL_ERR)}}a(k1,"describeAll");async function P_(e,t){L_.transformReq(e);let{schema:r,table:n}=e;r=r?.toString(),n=n?.toString();let s=t;e.hdb_user&&!e.hdb_user.role.permission.super_user&&(s=e.hdb_user.role.permission[r].tables[n].attribute_permissions);let i=Xy.describe_table(e);if(i)throw i;let c=Vm()[r];if(!c)throw M_(new Error,U_.SCHEMA_NOT_FOUND(e.schema),km.NOT_FOUND);let u=c[n];if(!u)throw M_(new Error,U_.TABLE_NOT_FOUND(e.schema,e.table),km.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=G1.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){D_.warn(`unable to stat table dbi due to ${f}`)}return d}a(P_,"descTable");async function V1(e){L_.transformReq(e);let t=Xy.schema_object(e);if(t)throw t;let r;e.hdb_user&&!e.hdb_user.role.permission.super_user&&(r=e.hdb_user.role.permission[e.schema]);let n=e.schema.toString(),i=Vm()[n];if(!i)throw M_(new Error,U_.SCHEMA_NOT_FOUND(e.schema),km.NOT_FOUND);let o={};for(let c in i){let u;if(r&&r.tables[c]&&(u=r.tables[c]),L_.isEmpty(u)||u.describe){let _=await P_({schema:e.schema,table:c,exact_count:e.exact_count},u?u.attribute_permissions:null);_&&(o[_.name]=_)}}return o}a(V1,"describeSchema")});var Os=g((Due,nN)=>{var $1=ki(),{callbackify:eN,promisify:Y1}=require("util"),{getDatabases:tN}=(Re(),ie(Fe));nN.exports={setSchemaDataToGlobal:Zy,getTableSchema:K1,getSystemSchema:W1,setSchemaDataToGlobalAsync:Y1(Zy)};var rN=As(),wue=eN(rN.describeAll),Cue=eN(rN.describeTable);function Zy(e){global.hdb_schema=tN(),e&&e()}a(Zy,"setSchemaDataToGlobal");function K1(e,t,r){let n=tN()[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(K1,"getTableSchema");function W1(){return $1}a(W1,"getSystemSchema")});var vr=g((Mue,aN)=>{"use strict";var B_=Bm(),kt=Q(),Q1=require("util"),H_=Cn(),z1=Os(),sN=$(),{handleHDBError:$i,hdb_errors:J1}=ne(),{HTTP_STATUS_CODES:Yi}=J1,X1=Q1.promisify(z1.getTableSchema),j1="updated",iN="inserted",oN="upserted";aN.exports={insert:eY,update:tY,upsert:rY,validation:Z1,flush:nY};async function Z1(e){if(kt.isEmpty(e))throw new Error("invalid update parameters defined.");if(kt.isEmptyOrZeroLength(e.schema))throw new Error("invalid database specified.");if(kt.isEmptyOrZeroLength(e.table))throw new Error("invalid table specified.");let t=await X1(e.schema,e.table),r=B_(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&&kt.isEmptyOrZeroLength(c[n]))throw sN.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(!kt.isEmptyOrZeroLength(c[n])&&(c[n]==="null"||c[n]==="undefined"))throw sN.error(`a valid hash value must be provided with ${e.operation} record:`,c),new Error(`"${c[n]}" is not a valid hash attribute value`);!kt.isEmpty(c[n])&&c[n]!==""&&s.has(kt.autoCast(c[n]))&&(c.skip=!0),s.add(kt.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(Z1,"validation");async function eY(e){if(e.operation!=="insert")throw new Error("invalid operation, must be insert");let t=B_(e);if(t)throw $i(new Error,t.message,Yi.BAD_REQUEST);kt.transformReq(e);let r=kt.checkSchemaTableExist(e.schema,e.table);if(r)throw $i(new Error,r,Yi.BAD_REQUEST);let n=await H_.createRecords(e);return v_(iN,n.written_hashes,e,n.skipped_hashes,n.new_attributes,n.txn_time)}a(eY,"insertData");async function tY(e){if(e.operation!=="update")throw new Error("invalid operation, must be update");let t=B_(e);if(t)throw $i(new Error,t.message,Yi.BAD_REQUEST);kt.transformReq(e);let r=kt.checkSchemaTableExist(e.schema,e.table);if(r)throw $i(new Error,r,Yi.BAD_REQUEST);let n=await H_.updateRecords(e);return kt.isEmpty(n.existing_rows)?v_(j1,n.written_hashes,e,n.skipped_hashes,n.new_attributes,n.txn_time):v_(n.update_action,[],e,n.hashes,void 0,n.txn_time)}a(tY,"updateData");async function rY(e){if(e.operation!=="upsert")throw $i(new Error,"invalid operation, must be upsert",Yi.INTERNAL_SERVER_ERROR);let t=B_(e);if(t)throw $i(new Error,t.message,Yi.BAD_REQUEST);kt.transformReq(e);let r=kt.checkSchemaTableExist(e.schema,e.table);if(r)throw $i(new Error,r,Yi.BAD_REQUEST);let n=await H_.upsertRecords(e);return v_(oN,n.written_hashes,e,[],n.new_attributes,n.txn_time)}a(rY,"upsertData");function v_(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===iN?(o.inserted_hashes=t,o.skipped_hashes=n,o):e===oN?(o.upserted_hashes=t,o):(o.update_hashes=t,o.skipped_hashes=n,o)}a(v_,"returnObject");function nY(e){return kt.transformReq(e),H_.flush(e.schema,e.table)}a(nY,"flush")});var Ym=g((Pue,lN)=>{var sY=Xe(),$m=require("joi"),{hdb_table:iY,hdb_database:cN}=Jn(),uN={schema:cN,database:cN,table:iY},oY={date:$m.date().iso().required()},aY={timestamp:$m.date().timestamp().required().messages({"date.format":"'timestamp' is invalid"})};lN.exports=function(e,t){let r=t==="timestamp"?{...uN,...aY}:{...uN,...oY},n=$m.object(r);return sY.validateBySchema(e,n)}});var fN=g((vue,dN)=>{var cY=Xe(),Km=require("joi"),{hdb_table:uY,hdb_database:_N}=Jn(),lY=Km.object({schema:_N,database:_N,table:uY,hash_values:Km.array().required(),ids:Km.array()});dN.exports=function(e){return cY.validateBySchema(e,lY)}});var hN=g((Bue,EN)=>{"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}},Qm=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}},zm=class{static{a(this,"DeleteResponseObject")}constructor(){this.message=void 0,this.deleted_hashes=[],this.skipped_hashes=[]}};EN.exports={InsertObject:Wm,NoSQLSeachObject:Qm,DeleteResponseObject:zm}});var ii=g((xue,gN)=>{"use strict";var pN=Ym(),_Y=fN(),Ki=Q(),mN=require("moment"),SN=$(),{promisify:dY,callbackify:fY}=require("util"),Wi=L(),EY=Os(),Jm=dY(EY.getTableSchema),Xm=Cn(),{DeleteResponseObject:hY}=hN(),{handleHDBError:ni,hdb_errors:mY}=ne(),{HDB_ERROR_MSGS:x_,HTTP_STATUS_CODES:si}=mY,pY="records successfully deleted",SY=fY(TN);gN.exports={delete:SY,deleteRecord:TN,deleteFilesBefore:TY,deleteAuditLogsBefore:gY};async function TY(e){let t=pN(e,"date");if(t)throw ni(t,t.message,si.BAD_REQUEST,void 0,void 0,!0);if(Ki.transformReq(e),!mN(e.date,mN.ISO_8601).isValid())throw ni(new Error,x_.INVALID_DATE,si.BAD_REQUEST,Wi.LOG_LEVELS.ERROR,x_.INVALID_DATE,!0);let n=Ki.checkSchemaTableExist(e.schema,e.table);if(n)throw ni(new Error,n,si.NOT_FOUND,Wi.LOG_LEVELS.ERROR,n,!0);let s=await Xm.deleteRecordsBefore(e);if(await Jm(e.schema,e.table),SN.info(`Finished deleting files before ${e.date}`),s&&s.message)return s.message}a(TY,"deleteFilesBefore");async function gY(e){let t=pN(e,"timestamp");if(t)throw ni(t,t.message,si.BAD_REQUEST,void 0,void 0,!0);if(Ki.transformReq(e),isNaN(e.timestamp))throw ni(new Error,x_.INVALID_VALUE("Timestamp"),si.BAD_REQUEST,Wi.LOG_LEVELS.ERROR,x_.INVALID_VALUE("Timestamp"),!0);let r=Ki.checkSchemaTableExist(e.schema,e.table);if(r)throw ni(new Error,r,si.NOT_FOUND,Wi.LOG_LEVELS.ERROR,r,!0);let n=await Xm.deleteAuditLogsBefore(e);return await Jm(e.schema,e.table),SN.info(`Finished deleting audit logs before ${e.timestamp}`),n}a(gY,"deleteAuditLogsBefore");async function TN(e){e.ids&&(e.hash_values=e.ids);let t=_Y(e);if(t)throw ni(t,t.message,si.BAD_REQUEST,void 0,void 0,!0);Ki.transformReq(e);let r=Ki.checkSchemaTableExist(e.schema,e.table);if(r)throw ni(new Error,r,si.NOT_FOUND,Wi.LOG_LEVELS.ERROR,r,!0);try{await Jm(e.schema,e.table);let n=await Xm.deleteRecords(e);return Ki.isEmptyOrZeroLength(n.message)&&(n.message=`${n.deleted_hashes.length} of ${e.hash_values.length} ${pY}`),n}catch(n){if(n.message===Wi.SEARCH_NOT_FOUND_MESSAGE){let s=new hY;return s.message=Wi.SEARCH_NOT_FOUND_MESSAGE,s.skipped_hashes=e.hash_values.length,s.deleted_hashes=0,s}throw n}}a(TN,"deleteRecord")});var G_=g((que,ON)=>{var RY=require("crypto"),RN=9;function AY(e){let t=bY(RN),r=AN(e+t);return t+r}a(AY,"createHash");function OY(e,t){let r=e?.substr(0,RN),n=r+AN(t+r);return e===n}a(OY,"validateHash");function bY(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(bY,"generateSalt");function AN(e){return RY.createHash("md5").update(e).digest("hex")}a(AN,"md5");ON.exports={hash:AY,validate:OY}});var yN=g((kue,bN)=>{var jm=Xe(),Qt={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 yY(e){return Qt.password.presence=!0,Qt.username.presence=!0,Qt.role.presence=!0,Qt.active.presence=!0,jm.validateObject(e,Qt)}a(yY,"addUserValidation");function NY(e){return Qt.password.presence=!1,Qt.username.presence=!0,Qt.role.presence=!1,Qt.active.presence=!1,jm.validateObject(e,Qt)}a(NY,"alterUserValidation");function IY(e){return Qt.password.presence=!1,Qt.username.presence=!0,Qt.role.presence=!1,Qt.active.presence=!1,jm.validateObject(e,Qt)}a(IY,"dropUserValidation");bN.exports={addUserValidation:yY,alterUserValidation:NY,dropUserValidation:IY}});var ke=g((Yue,IN)=>{"use strict";var{platform:$ue}=require("os"),wY="nats-server.zip",Zm="nats-server",CY=process.platform==="win32"?`${Zm}.exe`:Zm,DY=/^[^\s.,*>]+$/,NN="__request__",LY=a(e=>`${e}.${NN}`,"REQUEST_SUBJECT"),MY={NATS_MSG_ID:"Nats-Msg-Id",ORIGIN:"origin",TRANSACTED_NODES:"transacted_nodes"},UY={HUB_SERVER:"hub.json",LEAF_SERVER:"leaf.json"},PY={HUB:"hub.pid",LEAF:"leaf.pid"},vY={HUB:"-hub",LEAF:"-leaf",ADMIN:"-admin"},BY={SUCCESS:"success",ERROR:"error"},HY={OPEN:"open",CLOSED:"closed",NO_RESPONDERS:"NoResponders",TIMEOUT:"Timeout"},xY={TXN:"txn",MSGID:"msgid"},Ko={ERR:"error",WRN:"warn",INF:"info",DBG:"debug",TRC:"trace"},GY={[Ko.ERR]:1,[Ko.WRN]:2,[Ko.INF]:3,[Ko.DBG]:4,[Ko.TRC]:5},qY={debug:"-D",trace:"-DVV"};IN.exports={NATS_SERVER_ZIP:wY,NATS_SERVER_NAME:Zm,NATS_BINARY_NAME:CY,PID_FILES:PY,NATS_CONFIG_FILES:UY,SERVER_SUFFIX:vY,NATS_TERM_CONSTRAINTS_RX:DY,REQUEST_SUFFIX:NN,UPDATE_REMOTE_RESPONSE_STATUSES:BY,CLUSTER_STATUS_STATUSES:HY,REQUEST_SUBJECT:LY,SUBJECT_PREFIXES:xY,MSG_HEADERS:MY,LOG_LEVELS:Ko,LOG_LEVEL_FLAGS:qY,LOG_LEVEL_HIERARCHY:GY}});var CN=g((Wue,wN)=>{"use strict";var FY={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
|
-
`)},RY="certificate.pem",AY="privateKey.pem",OY="ca.pem";py.exports={CERTIFICATE_VALUES:gY,CERTIFICATE_PEM_NAME:RY,PRIVATEKEY_PEM_NAME:AY,CA_PEM_NAME:OY}});var Km=g((Cue,Oy)=>{"use strict";var Ay=require("fs-extra"),ie=require("joi"),bY=require("os"),{boolean:Ne,string:zt,number:Ze,array:Ym}=ie.types(),{totalmem:Ty}=require("os"),Wi=require("path"),NY=$(),P_=Q(),wue=Sy(),gy=M(),yY=Xe(),Ry="log",IY="components",wY="Invalid logging.rotation.maxSize unit. Available units are G, M or K",CY="Invalid logging.rotation.interval unit. Available units are D, H or M (minutes)",DY="Invalid logging.rotation.maxSize value. Value should be a number followed by unit e.g. '10M'",LY="Invalid logging.rotation.interval value. Value should be a number followed by unit e.g. '10D'",MY="rootPath config parameter is undefined",UY="clustering.enabled config parameter is undefined",Qi=Ze.min(0).required(),v_=Ym.items({host:zt.required(),port:Qi}).empty(null),js;Oy.exports={configValidator:PY,routesValidator:GY,route_constraints:v_};function PY(e){if(js=e.rootPath,P_.isEmpty(js))throw MY;let t=Ne.required(),r=Ze.min(0).max(1e3).empty(null).default(qY),s=zt.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path").empty(null).default(Pc),n=zt.optional().empty(null),i=zt.pattern(/^[^\s.,*>]+$/).messages({"string.pattern.base":"{:#label} invalid, must not contain ., * or >"}).empty(null).required(),o=ie.string().empty(null).default(Pc),c=ie.custom(BY).empty(null).default(Pc),u=e.clustering?.enabled;if(P_.isEmpty(u))throw UY;let _;return u===!0?_=ie.object({enabled:t,hubServer:ie.object({cluster:ie.object({name:ie.required().empty(null),network:ie.object({port:Qi,routes:v_}).required()}).required(),leafNodes:ie.object({network:ie.object({port:Qi}).required()}).required(),network:ie.object({port:Qi}).required()}).required(),leafServer:ie.object({network:ie.object({port:Qi,routes:v_}).required(),streams:ie.object({maxAge:Ze.min(120).allow(null).optional(),maxBytes:Ze.min(1).allow(null).optional(),maxMsgs:Ze.min(1).allow(null).optional(),path:o}).required()}).required(),logLevel:ie.valid("error","warn","info","debug","trace"),nodeName:i,republishMessages:Ne.optional(),databaseLevel:Ne.optional(),tls:ie.object({certificate:n,certificateAuthority:n,privateKey:n,insecure:Ne.required(),verify:Ne.optional()}),user:zt.optional().empty(null)}).required():_=ie.object({enabled:t,tls:ie.object({certificate:n,certificateAuthority:n,privateKey:n,insecure:Ne.required()})}).required(),ie.object({authentication:ie.object({authorizeLocal:Ne,cacheTTL:Ze.required(),enableSessions:Ne}),analytics:ie.object({aggregatePeriod:Ze}),componentsRoot:s.optional(),clustering:_,localStudio:ie.object({enabled:t}).required(),logging:ie.object({auditAuthEvents:ie.object({logFailed:Ne,logSuccessful:Ne}),file:Ne.required(),level:ie.valid("notify","fatal","error","warn","info","debug","trace"),rotation:ie.object({enabled:Ne.optional(),compress:Ne.optional(),interval:zt.custom(xY).optional().empty(null),maxSize:zt.custom(HY).optional().empty(null),path:zt.optional().empty(null).default(Pc)}).required(),root:s,stdStreams:Ne.required(),auditLog:Ne.required()}).required(),operationsApi:ie.object({network:ie.object({cors:Ne.optional(),corsAccessList:Ym.optional(),headersTimeout:Ze.min(1).optional(),keepAliveTimeout:Ze.min(1).optional(),port:Ze.optional().empty(null),domainSocket:ie.optional().empty("hdb/operations-server").default(Pc),securePort:Ze.optional().empty(null),timeout:Ze.min(1).optional()}).optional(),tls:ie.object({certificate:n,certificateAuthority:n,privateKey:n})}).required(),rootPath:zt.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path").required(),mqtt:ie.object({network:ie.object({port:Qi,securePort:Qi,mtls:ie.alternatives([Ne.optional(),ie.object({user:zt.optional(),certificateAuthority:n,required:Ne.optional()})])}).required(),webSocket:Ne.optional(),requireAuthentication:Ne.optional()}),http:ie.object({compressionThreshold:Ze.optional(),cors:Ne.optional(),corsAccessList:Ym.optional(),headersTimeout:Ze.min(1).optional(),port:Ze.min(0).optional().empty(null),securePort:Ze.min(0).optional().empty(null),maxHeaderSize:Ze.optional(),mtls:ie.alternatives([Ne.optional(),ie.object({user:zt.optional(),certificateAuthority:n,required:Ne.optional()})])}).required(),threads:ie.alternatives(r.optional(),ie.object({count:r.optional(),debug:ie.alternatives(Ne.optional(),ie.object({startingPort:Ze.min(1).optional(),host:zt.optional(),waitForDebugger:Ne.optional()})),maxHeapMemory:Ze.min(0).optional()})),storage:ie.object({writeAsync:Ne.required(),overlappingSync:Ne.optional(),caching:Ne.optional(),compression:ie.alternatives([Ne.optional(),ie.object({dictionary:zt.optional(),threshold:Ze.optional()})]),noReadAhead:Ne.optional(),path:c,prefetchWrites:Ne.optional(),maxFreeSpaceToLoad:Ze.optional(),maxFreeSpaceToRetain:Ze.optional()}).required(),ignoreScripts:Ne.optional(),tls:ie.object({certificate:n.optional(),certificateAuthority:n.optional(),privateKey:n.optional(),ciphers:zt.optional()})}).validate(e,{allowUnknown:!0,abortEarly:!1,errors:{wrap:{label:"'"}}})}a(PY,"configValidator");function vY(e){return Ay.existsSync(e)?null:`Specified path ${e} does not exist.`}a(vY,"doesPathExist");function BY(e,t){ie.assert(e,zt.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path"));let r=vY(e);if(r)return t.message(r)}a(BY,"validatePath");function HY(e,t){let r=e.slice(-1);if(r!=="G"&&r!=="M"&&r!=="K")return t.message(wY);let s=e.slice(0,-1);return isNaN(parseInt(s))?t.message(DY):e}a(HY,"validateRotationMaxSize");function xY(e,t){let r=e.slice(-1);if(r!=="D"&&r!=="H"&&r!=="M")return t.message(CY);let s=e.slice(0,-1);return isNaN(parseInt(s))?t.message(LY):e}a(xY,"validateRotationInterval");function qY(e,t){let r=t.state.path.join("."),s=bY.cpus().length,n=s-1;n<=2&&(n=2);let i=process.constrainedMemory?.()||Ty();return i=Math.round(Math.min(i,Ty())/1e6),n=Math.max(Math.min(n,Math.round((i-750)/300)),1),NY.info(`Detected ${s} cores and ${i}MB on this machine, defaulting ${r} to ${n}`),n}a(qY,"setDefaultThreads");function Pc(e,t){let r=t.state.path.join(".");if(!P_.isEmpty(t.original)&&r!=="operationsApi.network.domainSocket")return t.original;if(P_.isEmpty(js))throw new Error(`Error setting default root for: ${r}. HDB root is not defined`);switch(r){case"componentsRoot":return Wi.join(js,IY);case"logging.root":return Wi.join(js,Ry);case"clustering.leafServer.streams.path":return Wi.join(js,"clustering","leaf");case"storage.path":let s=Wi.join(js,gy.LEGACY_DATABASES_DIR_NAME);return Ay.existsSync(s)?s:Wi.join(js,gy.DATABASES_DIR_NAME);case"logging.rotation.path":return Wi.join(js,Ry);case"operationsApi.network.domainSocket":return r==null?null:Wi.join(js,"operations-server");default:throw new Error(`Error setting default root for config parameter: ${r}. Unrecognized config parameter`)}}a(Pc,"setDefaultRoot");function GY(e){let t=ie.object({routes:v_});return yY.validateBySchema({routes:e},t)}a(GY,"routesValidator")});var Br=g((Mue,My)=>{"use strict";var vr=M(),Mt=Q(),bt=$(),{configValidator:FY,routesValidator:by}=Km(),ur=require("fs-extra"),kY=require("yaml"),Cs=require("path"),VY=require("is-number"),yy=require("properties-reader"),$Y=require("lodash"),{handleHDBError:YY}=se(),{HTTP_STATUS_CODES:KY,HDB_ERROR_MSGS:B_}=Ir(),Lue=require("minimist"),{server:WY}=(or(),ne(Bi)),{DATABASES_PARAM_CONFIG:vc,CONFIG_PARAMS:Pr,CONFIG_PARAM_MAP:Ds}=vr,QY="Unable to get config value because config is uninitialized",zY="Config successfully initialized",JY="Error backing up config file",XY="Empty parameter sent to getConfigValue",Iy=Cs.join(vr.PACKAGE_ROOT,"config","yaml",vr.HDB_DEFAULT_CONFIG_FILE),jY="Configuration successfully set. You must restart HarperDB for new config settings to take effect.",Ny={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"},H_,Nt,x_;My.exports={createConfigFile:ZY,getDefaultConfig:eK,getConfigValue:Cy,initConfig:Qm,flattenConfig:Yo,updateConfigValue:Dy,updateConfigObject:rK,getConfiguration:iK,setConfiguration:oK,readConfigFile:Jm,getClusteringRoutes:aK,initOldConfig:Ly,getConfigFromFile:cK,getConfigFilePath:zi,addConfig:uK,deleteConfigFromFile:lK,getConfigObj:_K};function ZY(e){let t=ii(Iy);H_=Yo(t.toJSON());let r;for(let o in e){let c=Ds[o.toLowerCase()];if(c===Pr.DATABASES){r=e[o];continue}if(!c&&o.endsWith("_package")&&(c=o),c!==void 0){let u=c.split("_"),_=Wm(c,e[o]);c==="rootPath"&&_?.endsWith("/")&&(_=_.slice(0,-1));try{t.setIn([...u],_)}catch(l){bt.error(l)}}}r&&wy(t,r),zm(t);let s=t.toJSON();Nt=Yo(s);let n=t.getIn(["rootPath"]),i=Cs.join(n,vr.HDB_CONFIG_FILE);ur.createFileSync(i),ur.writeFileSync(i,String(t)),bt.trace(`Config file written to ${i}`)}a(ZY,"createConfigFile");function wy(e,t){let r;try{try{r=JSON.parse(t)}catch(s){if(!Mt.isObject(t))throw s;r=t}for(let s of r){let n=Object.keys(s)[0];if(s[n].hasOwnProperty(vc.TABLES))for(let i in s[n][vc.TABLES])for(let o in s[n][vc.TABLES][i]){let c=s[n][vc.TABLES][i][o],u=[Pr.DATABASES,n,vc.TABLES,i,o];e.hasIn(u)?e.setIn(u,c):e.addIn(u,c)}else for(let i in s[n]){let o=s[n][i],c=[Pr.DATABASES,n,i];e.hasIn(c)?e.setIn(c,o):e.addIn(c,o)}}}catch(s){bt.error("Error parsing schemas CLI/env config arguments",s)}}a(wy,"setSchemasConfig");function eK(e){if(H_===void 0){let r=ii(Iy);H_=Yo(r.toJSON())}let t=Ds[e.toLowerCase()];if(t!==void 0)return H_[t.toLowerCase()]}a(eK,"getDefaultConfig");function Cy(e){if(e==null){bt.error(XY);return}if(Nt===void 0){bt.trace(QY);return}let t=Ds[e.toLowerCase()];if(t!==void 0)return Nt[t.toLowerCase()]}a(Cy,"getConfigValue");function zi(e=Mt.getPropsFilePath()){let t=Mt.getEnvCliRootPath();return t?Cs.join(t,vr.HDB_CONFIG_FILE):yy(e).get(vr.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY)}a(zi,"getConfigFilePath");function Qm(e=!1){if(Nt===void 0||e){let t;if(!Mt.noBootFile()){t=Mt.getPropsFilePath();try{ur.accessSync(t,ur.constants.F_OK|ur.constants.R_OK)}catch(i){throw bt.error(i),new Error(`HarperDB properties file at path ${t} does not exist`)}}let r=zi(t),s;if(r.includes("config/settings.js"))try{Ly(r);return}catch(i){if(i.code!==vr.NODE_ERROR_CODES.ENOENT)throw i}try{s=ii(r)}catch(i){if(i.code===vr.NODE_ERROR_CODES.ENOENT){bt.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 bt.error(i),new Error(`Error reading HarperDB config file at ${r}`)}tK(s,r),zm(s);let n=s.toJSON();if(WY.config=n,Nt=Yo(n),Nt.logging_rotation_rotate)for(let i in Ny)Nt[i]&&bt.error(`Config ${Ny[i]} has been deprecated. Please check https://docs.harperdb.io/docs/ for further details.`);bt.trace(zY)}}a(Qm,"initConfig");function tK(e,t){let r=e.getIn(["rootPath"]),s=!1;e.hasIn(["storage","path"])||(e.setIn(["storage","path"],Cs.join(r,"database")),s=!0),e.hasIn(["clustering","leafServer","streams","path"])||(e.setIn(["clustering","leafServer","streams","path"],Cs.join(r,"clustering","leaf")),s=!0),e.hasIn(["logging","rotation","path"])||(e.setIn(["logging","rotation","path"],Cs.join(r,"log")),s=!0),e.hasIn(["clustering","tls","verify"])||(e.setIn(["clustering","tls","verify"],!0),s=!0),s&&(bt.trace("Updating config file with missing config params"),ur.writeFileSync(t,String(e)))}a(tK,"checkForUpdatedConfig");function zm(e){let t=e.toJSON();t.componentsRoot=t.componentsRoot??t?.customFunctions?.root,t?.http?.threads&&(t.threads=t?.http?.threads);let r=FY(t);if(r.error)throw B_.CONFIG_VALIDATION(r.error.message);typeof r.value.threads=="object"?e.setIn(["threads","count"],r.value.threads.count):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(zm,"validateConfig");function rK(e,t){Nt===void 0&&(Nt={});let r=Ds[e.toLowerCase()];if(r===void 0){bt.trace(`Unable to update config object because config param '${e}' does not exist`);return}Nt[r.toLowerCase()]=t}a(rK,"updateConfigObject");function Dy(e,t,r=void 0,s=!1,n=!1,i=!1){Nt===void 0&&Qm();let o=Cy(Ds.hdb_root),c=Cs.join(o,vr.HDB_CONFIG_FILE),u=ii(c),_;if(r===void 0&&e.toLowerCase()===Pr.DATABASES)_=t;else if(r===void 0){let f;if(i)f=e;else if(f=Ds[e.toLowerCase()],f===void 0)throw new Error(`Unable to update config, unrecognized config parameter: ${e}`);let E=f.split("_"),h=Wm(f,t);u.setIn([...E],h)}else for(let f in r){let E=Ds[f.toLowerCase()];if(E===Pr.HTTP_SECUREPORT&&r[f]===Nt[Pr.HTTP_PORT]?.toString()&&u.setIn(["http","port"],null),E===Pr.OPERATIONSAPI_NETWORK_SECUREPORT&&r[f]===Nt[Pr.OPERATIONSAPI_NETWORK_PORT.toLowerCase()]?.toString()&&u.setIn(["operationsApi","network","port"],null),E===Pr.DATABASES){_=r[f];continue}if(E?.startsWith("threads_")){let h=u.getIn(["threads"]);h>=0&&(u.deleteIn(["threads"]),u.setIn(["threads","count"],h))}if(!E&&f.endsWith("_package")&&(E=f),E!==void 0){let h=E.split("_"),p=vr.LEGACY_CONFIG_PARAMS[f.toUpperCase()];p&&p.startsWith("customFunctions")&&u.hasIn(p.split("_"))&&(E=p,h=p.split("_"));let S=Wm(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){bt.error(T)}}}_&&wy(u,_),zm(u);let l=u.getIn(["rootPath"]),d=Cs.join(l,vr.HDB_CONFIG_FILE);s===!0&&sK(c,l),ur.writeFileSync(d,String(u)),n&&(Nt=Yo(u.toJSON())),bt.trace(`Config parameter: ${e} updated with value: ${t}`)}a(Dy,"updateConfigValue");function sK(e,t){try{let r=Cs.join(t,"backup",`${vr.HDB_CONFIG_FILE}.bak`);ur.copySync(e,r),bt.trace(`Config file: ${e} backed up to: ${r}`)}catch(r){bt.error(JY),bt.error(r)}}a(sK,"backupConfigFile");var nK=["databases"];function Yo(e){return e.http&&Object.assign(e.http,e?.customFunctions?.network),e?.operationsApi?.network&&(e.operationsApi.network=Object.assign({},e.http,e.operationsApi.network)),e?.operationsApi&&(e.operationsApi.tls=Object.assign({},e.tls,e.operationsApi.tls)),x_=e,r(e);function r(s){let n={};for(let i in s)if(s.hasOwnProperty(i)){if(typeof s[i]=="object"&&s[i]!==null&&!Array.isArray(s[i])&&!nK.includes(i)){let o=r(s[i]);for(let c in o){if(!o.hasOwnProperty(c))continue;c!=="package"&&(i=i.toLowerCase());let u=i+"_"+c;!Pr[u.toUpperCase()]&&Ds[u]&&(n[Ds[u].toLowerCase()]=o[c]),n[u]=o[c]}}s[i]!==void 0&&(n[i.toLowerCase()]=s[i])}return n}a(r,"squashObj")}a(Yo,"flattenConfig");function Wm(e,t){if(e===Pr.CLUSTERING_NODENAME||e===Pr.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(VY(t))return parseFloat(t);if(t===!0||t===!1||Array.isArray(t)||Mt.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 Mt.autoCast(t)}a(Wm,"castConfigValue");function iK(){let e=Mt.getPropsFilePath(),t=zi(e);return ii(t).toJSON()}a(iK,"getConfiguration");async function oK(e){let{operation:t,hdb_user:r,hdb_auth_header:s,...n}=e;try{return Dy(void 0,void 0,n,!0),jY}catch(i){throw typeof i=="string"||i instanceof String?YY(i,i,KY.BAD_REQUEST,void 0,void 0,!0):i}}a(oK,"setConfiguration");function Jm(){let e=Mt.getPropsFilePath();try{ur.accessSync(e,ur.constants.F_OK|ur.constants.R_OK)}catch(s){if(!Mt.noBootFile())throw bt.error(s),new Error(`HarperDB properties file at path ${e} does not exist`)}let t=zi(e);return ii(t).toJSON()}a(Jm,"readConfigFile");function ii(e){return kY.parseDocument(ur.readFileSync(e,"utf8"),{simpleKeys:!0})}a(ii,"parseYamlDoc");function aK(){let e=Jm(),t=e?.clustering?.hubServer?.cluster?.network?.routes;t=Mt.isEmptyOrZeroLength(t)?[]:t;let r=by(t);if(r)throw B_.CONFIG_VALIDATION(r.message);let s=e?.clustering?.leafServer?.network?.routes;s=Mt.isEmptyOrZeroLength(s)?[]:s;let n=by(s);if(n)throw B_.CONFIG_VALIDATION(n.message);if(!Mt.isEmptyOrZeroLength(s)&&!Mt.isEmptyOrZeroLength(t)){let i=t.filter(o=>s.some(c=>c.host===o.host&&c.port===o.port));if(!Mt.isEmptyOrZeroLength(i)){let o=`Duplicate hub and leaf routes found ${JSON.stringify(i)}`;throw B_.CONFIG_VALIDATION(o)}}return{hub_routes:t,leaf_routes:s}}a(aK,"getClusteringRoutes");function Ly(e){let t=yy(e);Nt={};for(let r in Ds){let s=t.get(r.toUpperCase());if(Mt.isEmpty(s)||typeof s=="string"&&s.trim().length===0)continue;let n=Ds[r].toLowerCase();n===Pr.LOGGING_ROOT?Nt[n]=Cs.dirname(s):Nt[n]=s}return Nt}a(Ly,"initOldConfig");function cK(e){let t=Jm();return $Y.get(t,e.replaceAll("_","."))}a(cK,"getConfigFromFile");async function uK(e,t){let r=ii(zi());r.hasIn([e])?r.setIn([e],t):r.addIn([e],t),await ur.writeFile(zi(),String(r))}a(uK,"addConfig");function lK(e){let t=zi(Mt.getPropsFilePath()),r=ii(t);r.deleteIn(e);let s=r.getIn(["rootPath"]),n=Cs.join(s,vr.HDB_CONFIG_FILE);ur.writeFileSync(n,String(r))}a(lK,"deleteConfigFromFile");function _K(){return x_||(Qm(),x_)}a(_K,"getConfigObj")});var Py=g((Pue,Uy)=>{"use strict";var q_=M(),G_=class{static{a(this,"BaseLicense")}constructor(t=0,r=q_.RAM_ALLOCATION_ENUM.DEFAULT,s=q_.LICENSE_VALUES.VERSION_DEFAULT,n){this.exp_date=t,this.ram_allocation=r,this.version=s,this.fingerprint=n}},Xm=class extends G_{static{a(this,"ExtendedLicense")}constructor(t=0,r=q_.RAM_ALLOCATION_ENUM.DEFAULT,s=q_.LICENSE_VALUES.VERSION_DEFAULT,n,i=!1){super(t,r,s,n),this.enterprise=i}};Uy.exports={BaseLicense:G_,ExtendedLicense:Xm}});var Ji=g((Bue,Gy)=>{"use strict";var Wo=require("fs-extra"),By=U_(),Hy=require("crypto"),dK=require("moment"),fK=require("uuid").v4,Jt=$(),Zm=require("path"),EK=Q(),oi=M(),{totalmem:vy}=require("os"),hK=Py().ExtendedLicense,Ko="invalid license key format",mK="061183",pK="mofi25",SK="aes-256-cbc",TK=16,gK=32,xy=ee();xy.initSync();var jm;Gy.exports={validateLicense:qy,generateFingerPrint:AK,licenseSearch:rp,getLicense:NK,checkMemoryLimit:yK};function ep(){return Zm.join(xy.getHdbBasePath(),oi.LICENSE_KEY_DIR_NAME,oi.LICENSE_FILE_NAME)}a(ep,"getLicenseDirPath");function RK(){let e=ep();return Zm.join(e,oi.LICENSE_FILE_NAME)}a(RK,"getLicenseFilePath");function tp(){let e=ep();return Zm.join(e,oi.REG_KEY_FILE_NAME)}a(tp,"getFingerPrintFilePath");async function AK(){let e=tp();try{return await Wo.readFile(e,"utf8")}catch(t){if(t.code==="ENOENT")return await OK();throw Jt.error(`Error writing fingerprint file to ${e}`),Jt.error(t),new Error("There was an error generating the fingerprint")}}a(AK,"generateFingerPrint");async function OK(){let e=fK(),t=By.hash(e),r=tp();try{await Wo.mkdirp(ep()),await Wo.writeFile(r,t)}catch(s){if(s.code==="EEXIST")return t;throw Jt.error(`Error writing fingerprint file to ${r}`),Jt.error(s),new Error("There was an error generating the fingerprint")}return t}a(OK,"writeFingerprint");function qy(e,t){let r={valid_license:!1,valid_date:!1,valid_machine:!1,exp_date:null,ram_allocation:oi.RAM_ALLOCATION_ENUM.DEFAULT,version:oi.LICENSE_VALUES.VERSION_DEFAULT};if(!e)return Jt.error("empty license key passed to validate."),r;let s=tp(),n=!1;try{n=Wo.statSync(s)}catch(i){Jt.error(i)}if(n){let i;try{i=Wo.readFileSync(s,"utf8")}catch{Jt.error("error validating this machine in the license"),r.valid_machine=!1;return}let o=e.split(pK),c=o[1];c=Buffer.concat([Buffer.from(c)],TK);let u=Buffer.concat([Buffer.from(i)],gK),_=Hy.createDecipheriv(SK,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=bK(o[0],i);if(E)l=E;else throw r.valid_license=!1,r.valid_machine=!1,console.error(Ko),Jt.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),Jt.error(Ko),new Error(Ko)}else r.exp_date=l;r.exp_date<dK().valueOf()&&(r.valid_date=!1),By.validate(o[1],`${mK}${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||Jt.error("Invalid licence"),r}a(qy,"validateLicense");function bK(e,t){try{let r=Hy.createDecipher("aes192",t),s=r.update(e,"hex","utf8");return s.trim(),s+=r.final("utf8"),s}catch{Jt.warn("Check old license failed")}}a(bK,"checkOldLicense");function rp(){let e=new hK,t=[];try{t=Wo.readFileSync(RK(),"utf-8").split(oi.NEW_LINE)}catch(r){r.code==="ENOENT"?Jt.info("no license file found"):Jt.error(`could not search for licenses due to: '${r.message}`)}for(let r=0;r<t.length;++r){let s=t[r];try{if(EK.isEmptyOrZeroLength(s))continue;let n=JSON.parse(s),i=qy(n.license_key,n.company);i.valid_machine===!0&&i.valid_date===!0&&i.valid_machine===!0&&(e.exp_date=i.exp_date>e.exp_date?i.exp_date:e.exp_date,e.ram_allocation=i.ram_allocation,e.enterprise=!0)}catch(n){Jt.error("There was an error parsing the license string."),Jt.error(n),e.ram_allocation=oi.RAM_ALLOCATION_ENUM.DEFAULT,e.enterprise=!1}}return jm=e,e}a(rp,"licenseSearch");async function NK(){return jm||await rp(),jm}a(NK,"getLicense");function yK(){let e=rp().ram_allocation,t=process.constrainedMemory?.()||vy();if(t=Math.round(Math.min(t,vy())/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(yK,"checkMemoryLimit")});var is=g((Fue,rI)=>{"use strict";var $y="username is required",Yy="nothing to update, must supply active, role or password to update",Ky="password cannot be an empty string",Wy="If role is specified, it cannot be empty.",Qy="active must be true or false";rI.exports={addUser:vK,alterUser:BK,dropUser:xK,getSuperUser:kK,userInfo:qK,listUsers:k_,listUsersExternal:GK,setUsersToGlobal:zo,findAndValidateUser:eI,getClusterUser:VK,USERNAME_REQUIRED:$y,ALTERUSER_NOTHING_TO_UPDATE:Yy,EMPTY_PASSWORD:Ky,EMPTY_ROLE:Wy,ACTIVE_BOOLEAN:Qy};var zy=Ur(),IK=ni(),ip=U_(),Jy=Ey(),Xy=Mr(),op=On(),Hr=Q(),jy=require("validate.js"),Te=$(),{promisify:wK}=require("util"),ap=Rn(),Fy=M(),ky=Fe(),CK=Br(),xue=ee(),que=Ji(),DK=Fi(),{table:Gue}=(Ae(),ne(Ge)),{handleHDBError:Zs,hdb_errors:LK}=se(),{HTTP_STATUS_CODES:en,AUTHENTICATION_ERROR_MSGS:sp,HDB_ERROR_MSGS:Qo}=LK,{UserEventMsg:cp}=Ls(),np=require("lodash"),{server:up}=(or(),ne(Bi)),MK=$();up.getUser=(e,t)=>eI(e,t,t!=null);var Zy={username:!0,active:!0,role:!0,password:!0},Vy=new Map,F_=Xy.searchByValue,UK=Xy.searchByHash,PK=wK(IK.delete);async function vK(e){let t=jy.cleanAttributes(e,Zy),r=Jy.addUserValidation(t);if(r)throw Zs(new Error,r.message,en.BAD_REQUEST,void 0,void 0,!0);let s={schema:"system",table:"hdb_role",search_attribute:"role",search_value:t.role,get_attributes:["id","permission","role"]},n;try{n=await F_(s),n=n&&Array.from(n)}catch(u){throw Te.error("There was an error searching for a role in add user"),Te.error(u),u}if(!n||n.length<1)throw Zs(new Error,Qo.ROLE_NAME_NOT_FOUND(t.role),en.NOT_FOUND,void 0,void 0,!0);if(n.length>1)throw Zs(new Error,Qo.DUP_ROLES_FOUND(t.role),en.CONFLICT,void 0,void 0,!0);n[0].permission.cluster_user===!0&&(t.hash=ap.encrypt(t.password)),t.password=ip.hash(t.password),t.role=n[0].id;let i={operation:"insert",schema:"system",table:"hdb_user",records:[t]},o;try{o=await zy.insert(i)}catch(u){throw Te.error("There was an error searching for a user."),Te.error(u),u}Te.debug(o);try{await zo()}catch(u){throw Te.error("Got an error setting users to global"),Te.error(u),u}if(o.skipped_hashes.length===1)throw Zs(new Error,Qo.USER_ALREADY_EXISTS(t.username),en.CONFLICT,void 0,void 0,!0);let c=Object.assign({},t);return c.role=n[0],op.signalUserChange(new cp(process.pid)),`${c.username} successfully added`}a(vK,"addUser");async function BK(e){let t=jy.cleanAttributes(e,Zy);if(Hr.isEmptyOrZeroLength(t.username))throw new Error($y);if(Hr.isEmptyOrZeroLength(t.password)&&Hr.isEmptyOrZeroLength(t.role)&&Hr.isEmptyOrZeroLength(t.active))throw new Error(Yy);if(!Hr.isEmpty(t.password)&&Hr.isEmptyOrZeroLength(t.password.trim()))throw new Error(Ky);if(!Hr.isEmpty(t.active)&&!Hr.isBoolean(t.active))throw new Error(Qy);let r=HK(t.username);if(!Hr.isEmpty(t.password)&&!Hr.isEmptyOrZeroLength(t.password.trim())&&(r&&(t.hash=ap.encrypt(t.password)),t.password=ip.hash(t.password)),t.role==="")throw new Error(Wy);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 F_(i)||[])}catch(c){throw Te.error("Got an error searching for a role."),Te.error(c),c}if(!o||o.length===0){let c=Qo.ALTER_USER_ROLE_NOT_FOUND(t.role);throw Te.error(c),Zs(new Error,c,en.NOT_FOUND,void 0,void 0,!0)}if(o.length>1){let c=Qo.ALTER_USER_DUP_ROLES(t.role);throw Te.error(c),Zs(new Error,c,en.CONFLICT,void 0,void 0,!0)}t.role=o[0].id}let s={operation:"update",schema:"system",table:"hdb_user",records:[t]},n;try{n=await zy.update(s)}catch(i){throw Te.error("Error during update."),Te.error(i),i}try{await zo()}catch(i){throw Te.error("Got an error setting users to global"),Te.error(i),i}return op.signalUserChange(new cp(process.pid)),n}a(BK,"alterUser");function HK(e){let t=!1,r=global.hdb_users.get(e);return r&&r.role.permission.cluster_user===!0&&(t=!0),t}a(HK,"isClusterUser");async function xK(e){try{let t=Jy.dropUserValidation(e);if(t)throw new Error(t);let r={table:"hdb_user",schema:"system",hash_values:[e.username]};if(Hr.isEmpty(global.hdb_users.get(e.username)))throw Zs(new Error,Qo.USER_NOT_EXIST(e.username),en.NOT_FOUND,void 0,void 0,!0);let s;try{s=await PK(r)}catch(n){throw Te.error("Got an error deleting a user."),Te.error(n),n}Te.debug(s);try{await zo()}catch(n){throw Te.error("Got an error setting users to global."),Te.error(n),n}return op.signalUserChange(new cp(process.pid)),`${e.username} successfully deleted`}catch(t){throw t}}a(xK,"dropUser");async function qK(e){let t={};try{if(!e||!e.hdb_user)return"There was no user info in the body";t=np.cloneDeep(e.hdb_user);let r={schema:"system",table:"hdb_role",hash_values:[t.role.id],get_attributes:["*"]},s;try{s=await UK(r)}catch(n){throw Te.error("Got an error searching for a role."),Te.error(n),n}t.role=s[0],delete t.password,delete t.refresh_token,delete t.hash}catch(r){throw Te.error(r),r}return t}a(qK,"userInfo");async function GK(){let e;try{e=await k_()}catch(t){throw Te.error("Got an error listing users."),Te.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(GK,"listUsersExternal");async function k_(){try{let e={schema:"system",table:"hdb_role",search_value:"*",search_attribute:"role",get_attributes:["*"]},t;try{t=await F_(e)}catch(o){throw Te.error("Got an error searching for roles."),Te.error(o),o}let r={};for(let o of t)r[o.id]=np.cloneDeep(o);if(Object.keys(r).length===0)return null;let s={schema:"system",table:"hdb_user",search_value:"*",search_attribute:"username",get_attributes:["*"]},n;try{n=await F_(s)}catch(o){throw Te.error("Got an error searching for users."),Te.error(o),o}let i=new Map;for(let o of n)o=np.cloneDeep(o),o.role=r[o.role],FK(o.role),i.set(o.username,o);return i}catch(e){throw Te.error("got an error listing users"),Te.error(e),Hr.errorizeMessage(e)}return null}a(k_,"listUsers");function FK(e){try{if(!e){Te.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(DK)){let r={read:!!e.permission.super_user,insert:!1,update:!1,delete:!1,attribute_permissions:[]};e.permission.system.tables[t]=r}}catch(t){Te.error("Got an error trying to set system permissions."),Te.error(t)}}a(FK,"appendSystemTablesToRole");async function zo(){try{let e=await k_();global.hdb_users=e}catch(e){throw Te.error(e),e}}a(zo,"setUsersToGlobal");async function eI(e,t,r=!0){global.hdb_users||await zo();let s=global.hdb_users.get(e);if(!s){if(!r)return{username:e};throw Zs(new Error,sp.GENERIC_AUTH_FAIL,en.UNAUTHORIZED,void 0,void 0,!0)}if(s&&!s.active)throw Zs(new Error,sp.USER_INACTIVE,en.UNAUTHORIZED,void 0,void 0,!0);let n={active:s.active,username:s.username};if(s.refresh_token&&(n.refresh_token=s.refresh_token),s.role&&(n.role=s.role),r===!0){if(Vy.get(t)===s.password)return n;if(ip.validate(s.password,t))Vy.set(t,s.password);else throw Zs(new Error,sp.GENERIC_AUTH_FAIL,en.UNAUTHORIZED,void 0,void 0,!0)}return n}a(eI,"findAndValidateUser");async function kK(){global.hdb_users||await zo();for(let[,e]of global.hdb_users)if(e.role.role==="super_user")return e}a(kK,"getSuperUser");async function VK(){let e=await k_(),t=CK.getConfigFromFile(Fy.CONFIG_PARAMS.CLUSTERING_USER),r=e.get(t);if(!Hr.isEmpty(r)&&r?.role?.role===Fy.ROLE_TYPES_ENUM.CLUSTER_USER)return r.decrypt_hash=ap.decrypt(r.hash),r.uri_encoded_d_hash=encodeURIComponent(r.decrypt_hash),r.uri_encoded_name=encodeURIComponent(r.username),r.sys_name=r.username+ky.SERVER_SUFFIX.ADMIN,r.sys_name_encoded=r.uri_encoded_name+ky.SERVER_SUFFIX.ADMIN,r}a(VK,"getClusterUser");var tI=[];up.invalidateUser=function(e){for(let t of tI)try{t(e)}catch(r){MK.error("Error invalidating user",r)}};up.onInvalidatedUser=function(e){tI.push(e)}});var Hc=g((Yue,oI)=>{"use strict";var Xi=$(),xr=M(),$K=vN(),Vue=An(),$ue=ti(),YK=is(),{validateEvent:sI}=Ls(),Bc=ws(),KK=require("process"),{resetDatabases:WK}=(Ae(),ne(Ge)),QK={[xr.ITC_EVENT_TYPES.SCHEMA]:zK,[xr.ITC_EVENT_TYPES.USER]:iI};async function zK(e){let t=sI(e);if(t){Xi.error(t);return}Xi.trace("ITC schemaHandler received schema event:",e),await $K(e.message),await JK(e.message)}a(zK,"schemaHandler");async function JK(e){try{Bc.resetReadTxn(xr.SYSTEM_SCHEMA_NAME,xr.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME),Bc.resetReadTxn(xr.SYSTEM_SCHEMA_NAME,xr.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME),Bc.resetReadTxn(xr.SYSTEM_SCHEMA_NAME,xr.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME);let t=WK();e.table&&e.database&&await t[e.database][e.table].put(Symbol.for("write-verify"),null)}catch(t){Xi.error(t)}}a(JK,"syncSchemaMetadata");var nI=[];async function iI(e){try{try{Bc.resetReadTxn(xr.SYSTEM_SCHEMA_NAME,xr.SYSTEM_TABLE_NAMES.USER_TABLE_NAME),Bc.resetReadTxn(xr.SYSTEM_SCHEMA_NAME,xr.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME)}catch(r){Xi.warn(r)}let t=sI(e);if(t){Xi.error(t);return}Xi.trace(`ITC userHandler ${xr.HDB_ITC_CLIENT_PREFIX}${KK.pid} received user event:`,e),await YK.setUsersToGlobal();for(let r of nI)r()}catch(t){Xi.error(t)}}a(iI,"userHandler");iI.addListener=function(e){nI.push(e)};oI.exports=QK});var Ls=g((Xue,cI)=>{"use strict";var Wue=$(),lp=Q(),XK=M(),{ITC_ERRORS:xc}=Ir(),{parentPort:Que,threadId:jK,isMainThread:ZK,workerData:zue}=require("worker_threads"),{onMessageFromWorkers:eW,broadcast:Jue,broadcastWithAcknowledgement:tW}=Ke();cI.exports={sendItcEvent:rW,validateEvent:aI,SchemaEventMsg:sW,UserEventMsg:nW};var V_;eW(async(e,t)=>{V_=V_||Hc(),aI(e),V_[e.type]&&await V_[e.type](e),e.requestId&&t&&t.postMessage({type:"ack",id:e.requestId})});function rW(e){return!ZK&&e.message&&(e.message.originator=jK),tW(e)}a(rW,"sendItcEvent");function aI(e){if(typeof e!="object")return xc.INVALID_ITC_DATA_TYPE;if(!e.hasOwnProperty("type")||lp.isEmpty(e.type))return xc.MISSING_TYPE;if(!e.hasOwnProperty("message")||lp.isEmpty(e.message))return xc.MISSING_MSG;if(!e.message.hasOwnProperty("originator")||lp.isEmpty(e.message.originator))return xc.MISSING_ORIGIN;if(XK.ITC_EVENT_TYPES[e.type.toUpperCase()]===void 0)return xc.INVALID_EVENT(e.type)}a(aI,"validateEvent");function sW(e,t,r,s=void 0,n=void 0){this.originator=e,this.operation=t,this.schema=r,this.table=s,this.attribute=n}a(sW,"SchemaEventMsg");function nW(e){this.originator=e}a(nW,"UserEventMsg")});var On=g((ele,dI)=>{"use strict";var uI=M(),Zue=Q(),$_=$(),lI=MN(),Jo,{sendItcEvent:_I}=Ls();function iW(e){try{$_.trace("signalSchemaChange called with message:",e),Jo=Jo||Hc();let t=new lI(uI.ITC_EVENT_TYPES.SCHEMA,e);return Jo.schema(t),_I(t)}catch(t){$_.error(t)}}a(iW,"signalSchemaChange");function oW(e){try{$_.trace("signalUserChange called with message:",e),Jo=Jo||Hc();let t=new lI(uI.ITC_EVENT_TYPES.USER,e);return Jo.user(t),_I(t)}catch(t){$_.error(t)}}a(oW,"signalUserChange");dI.exports={signalSchemaChange:iW,signalUserChange:oW}});var Y_=g((rle,EI)=>{"use strict";var fI=Q(),aW=M(),cW=$(),uW=T_(),lW=S_(),_W=On(),{SchemaEventMsg:dW}=Ls(),fW="already exists in";EI.exports=EW;async function EW(e,t,r){if(fI.isEmptyOrZeroLength(r))return r;let s=[];fI.isEmptyOrZeroLength(t.attributes)||t.attributes.forEach(i=>{s.push(i.attribute)});let n=r.filter(i=>s.indexOf(i)<0);return n.length===0||await Promise.all(n.map(async i=>{await hW(e,t.schema,t.name,i)})),n}a(EW,"lmdbCheckForNewAttributes");async function hW(e,t,r,s){let n=new lW(t,r,s,void 0,!0);e&&(n.hdb_auth_header=e);try{await mW(n)}catch(i){if(typeof i=="object"&&i.message!==void 0&&i.message.includes(fW))cW.warn(`attribute ${t}.${r}.${s} already exists`);else throw i}}a(hW,"createNewAttribute");async function mW(e){let t;return t=await uW(e),_W.signalSchemaChange(new dW(process.pid,aW.OPERATIONS_ENUM.CREATE_ATTRIBUTE,e.schema,e.table,e.attribute)),t}a(mW,"createAttribute")});var Xo=g((nle,hI)=>{"use strict";var _p=class{static{a(this,"LMDBTransactionObject")}constructor(t,r,s,n,i=void 0){this.operation=t,this.user_name=r,this.timestamp=s,this.hash_values=n,this.origin=i}};hI.exports=_p});var pI=g((ole,mI)=>{"use strict";var pW=Xo(),SW=M().OPERATIONS_ENUM,dp=class extends pW{static{a(this,"LMDBInsertTransactionObject")}constructor(t,r,s,n,i=void 0){super(SW.INSERT,r,s,n,i),this.records=t}};mI.exports=dp});var TI=g((cle,SI)=>{"use strict";var TW=Xo(),gW=M().OPERATIONS_ENUM,fp=class extends TW{static{a(this,"LMDBUpdateTransactionObject")}constructor(t,r,s,n,i,o=void 0){super(gW.UPDATE,s,n,i,o),this.records=t,this.original_records=r}};SI.exports=fp});var RI=g((lle,gI)=>{"use strict";var RW=Xo(),AW=M().OPERATIONS_ENUM,Ep=class extends RW{static{a(this,"LMDBUpsertTransactionObject")}constructor(t,r,s,n,i,o=void 0){super(AW.UPSERT,s,n,i,o),this.records=t,this.original_records=r}};gI.exports=Ep});var OI=g((dle,AI)=>{"use strict";var OW=Xo(),bW=M().OPERATIONS_ENUM,hp=class extends OW{static{a(this,"LMDBDeleteTransactionObject")}constructor(t,r,s,n,i=void 0){super(bW.DELETE,s,n,t,i),this.original_records=r}};AI.exports=hp});var qc=g((hle,II)=>{"use strict";var Ele=require("path"),bI=We(),NW=pI(),yW=TI(),IW=RI(),wW=OI(),jo=Et(),NI=Q(),{CONFIG_PARAMS:CW}=M(),yI=ee();yI.initSync();var K_=M().OPERATIONS_ENUM,{getTransactionAuditStorePath:DW}=Je();II.exports=LW;async function LW(e,t){if(yI.get(CW.LOGGING_AUDITLOG)===!1)return;let r=DW(e.schema,e.table),s=await bI.openEnvironment(r,e.table,!0),n=MW(e,t);if(!(n===void 0||n.hash_values.length===0)&&s!==void 0){bI.initializeDBIs(s,jo.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,jo.TRANSACTIONS_DBIS);let i=n.timestamp;return await s.dbis[jo.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP].ifNoExists(i,()=>{s.dbis[jo.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP].put(i,n),NI.isEmpty(n.user_name)||s.dbis[jo.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].put(n.user_name,i);for(let o=0;o<n.hash_values.length;o++)s.dbis[jo.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE].put(n.hash_values[o],i)})}}a(LW,"writeTransaction");function MW(e,t){let r=NI.isEmpty(e.hdb_user)?void 0:e.hdb_user.username;if(e.operation===K_.INSERT)return new NW(e.records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===K_.UPDATE)return new yW(e.records,t.original_records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===K_.UPSERT)return new IW(e.records,t.original_records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===K_.DELETE)return new wW(t.deleted,t.original_records,r,t.txn_time,e.__origin)}a(MW,"createTransactionObject")});var mp=g((Sle,wI)=>{"use strict";var UW=Dc(),ple=Lc(),Gc=M(),PW=Mc(),vW=ko().insertRecords,BW=We(),HW=$(),xW=Y_(),{getSchemaPath:qW}=Je(),GW=qc();wI.exports=FW;async function FW(e){try{let{schema_table:t,attributes:r}=UW(e);PW(e,r,t.hash_attribute),e.schema!==Gc.SYSTEM_SCHEMA_NAME&&(r.includes(Gc.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||r.push(Gc.TIME_STAMP_NAMES_ENUM.CREATED_TIME),r.includes(Gc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||r.push(Gc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let s=await xW(e.hdb_auth_header,t,r),n=qW(e.schema,e.table),i=await BW.openEnvironment(n,e.table),o=await vW(i,t.hash_attribute,r,e.records,e.__origin?.timestamp);try{await GW(e,o)}catch(c){HW.error(`unable to write transaction due to ${c.message}`)}return{written_hashes:o.written_hashes,skipped_hashes:o.skipped_hashes,schema_table:t,new_attributes:s,txn_time:o.txn_time}}catch(t){throw t}}a(FW,"lmdbCreateRecords")});var LI=g((gle,DI)=>{"use strict";var CI=M(),kW=mp(),VW=Lc(),$W=require("fs-extra"),{getSchemaPath:YW}=Je();DI.exports=KW;async function KW(e){let t=[{name:e.schema,createddate:Date.now()}],r=new VW(CI.SYSTEM_SCHEMA_NAME,CI.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,void 0,t);await kW(r),await $W.mkdirp(YW(e.schema))}a(KW,"lmdbCreateSchema")});var UI=g((Ale,MI)=>{"use strict";var pp=class{static{a(this,"DeleteRecordsResponseObject")}constructor(t=[],r=[],s=void 0,n=[]){this.deleted=t,this.skipped=r,this.txn_time=s,this.original_records=n}};MI.exports=pp});var HI=g((Ile,BI)=>{"use strict";var PI=We(),Sp=wr(),Tp=Ir().LMDB_ERRORS_ENUM,WW=Et(),vI=$(),ble=Q(),QW=require("lmdb"),zW=UI(),JW=M(),{OVERFLOW_MARKER:Nle,MAX_SEARCH_KEY_LENGTH:yle}=WW,XW=JW.TIME_STAMP_NAMES_ENUM.UPDATED_TIME;async function jW(e,t,r,s){if(Sp.validateEnv(e),t===void 0)throw new Error(Tp.HASH_ATTRIBUTE_REQUIRED);if(!Array.isArray(r))throw r===void 0?new Error(Tp.IDS_REQUIRED):new Error(Tp.IDS_MUST_BE_ITERABLE);try{let n=PI.listDBIs(e);PI.initializeDBIs(e,t,n);let i=new zW,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||s&&h[XW]>s){i.skipped.push(o);continue}let p=e.dbis[t].ifVersion(o,QW.IF_EXISTS,()=>{e.dbis[t].remove(o);for(let S=0;S<n.length;S++){let T=n[S];if(!h.hasOwnProperty(T)||T===t)continue;let b=e.dbis[T],R=h[T];if(R!=null)try{let L=Sp.getIndexedValues(R);if(L)for(let H=0,P=L.length;H<P;H++)b.remove(L[H],o)}catch{vI.warn(`cannot delete from attribute: ${T}, ${R}:${o}`)}}});c.push(p),u.push(o),i.original_records.push(h)}catch(h){vI.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=Sp.getNextMonotonicTime(),i}catch(n){throw n}}a(jW,"deleteRecords");BI.exports={deleteRecords:jW}});var Fc=g((Cle,qI)=>{"use strict";var Zo=Q(),ZW=HI(),eQ=We(),{getSchemaPath:tQ}=Je(),rQ=qc(),sQ=$();qI.exports=nQ;async function nQ(e,t=!0){let s=global.hdb_schema[e.schema][e.table].hash_attribute;if(Zo.isEmpty(s))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][s];Zo.isEmpty(u)||e.hash_values.push(u)}}if(Zo.isEmptyOrZeroLength(e.hash_values))return xI([],[]);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]={[s]:e.hash_values[c]}}let n=tQ(e.schema,e.table),i=await eQ.openEnvironment(n,e.table),o=await ZW.deleteRecords(i,s,e.hash_values,e.__origin?.timestamp);try{t===!0&&await rQ(e,o)}catch(c){sQ.error(`unable to write transaction due to ${c.message}`)}return xI(o.deleted,o.skipped,o.txn_time)}catch(n){throw n}}a(nQ,"lmdbDeleteRecords");function xI(e,t,r){let s=e.length+t.length,n=s===1?"record":"records";return{message:`${e.length} of ${s} ${n} successfully deleted`,deleted_hashes:e,skipped_hashes:t,txn_time:r}}a(xI,"createDeleteResponse")});var Rp=g((Mle,GI)=>{"use strict";var iQ=M(),Lle=wr();function gp(e,t){let r=Object.create(null);if(t.length===1&&iQ.SEARCH_WILDCARDS.indexOf(t[0])>=0)Object.assign(r,e);else for(let s=0;s<t.length;s++){let n=t[s],i=e[n];r[n]=i===void 0?null:i}return r}a(gp,"parseRow");function oQ(e,t,r,s){let n=gp(r,e);s.push(n)}a(oQ,"searchAll");function aQ(e,t,r,s){let n=gp(r,e);s[t]=n}a(aQ,"searchAllToMap");function cQ(e,t,r){r[e]===void 0&&(r[e]=[]),r[e].push(t)}a(cQ,"iterateDBI");function ji(e,t,r,s,n){let i=Object.create(null);i[n]=e;let o;s===n?o=e:(o=t,s!==void 0&&(i[s]=o)),r[0].push(o),r[1].push(i)}a(ji,"pushResults");function uQ(e,t,r,s,n,i){t.toString().endsWith(e)&&ji(t,r,s,n,i)}a(uQ,"endsWith");function lQ(e,t,r,s,n,i){t.toString().includes(e)&&ji(t,r,s,n,i)}a(lQ,"contains");function _Q(e,t,r,s,n,i){t>e&&ji(t,r,s,n,i)}a(_Q,"greaterThanCompare");function dQ(e,t,r,s,n,i){t>=e&&ji(t,r,s,n,i)}a(dQ,"greaterThanEqualCompare");function fQ(e,t,r,s,n,i){t<e&&ji(t,r,s,n,i)}a(fQ,"lessThanCompare");function EQ(e,t,r,s,n,i){t<=e&&ji(t,r,s,n,i)}a(EQ,"lessThanEqualCompare");GI.exports={parseRow:gp,searchAll:oQ,searchAllToMap:aQ,iterateDBI:cQ,endsWith:uQ,contains:lQ,greaterThanCompare:_Q,greaterThanEqualCompare:dQ,lessThanCompare:fQ,lessThanEqualCompare:EQ,pushResults:ji}});var ea=g((Hle,WI)=>{"use strict";var ai=We(),Ple=$(),qr=wr(),W_=Et(),lt=Ir().LMDB_ERRORS_ENUM,vle=Q(),hQ=M(),Q_=Rp(),{parseRow:mQ}=Q_,Ble=require("lmdb"),{OVERFLOW_MARKER:FI,MAX_SEARCH_KEY_LENGTH:pQ}=W_;function kI(e,t,r,s=!1,n=void 0,i=void 0){return Zi(e,t,r,(o,c)=>c.getRange({transaction:o,start:s?void 0:!1,end:s?!1:void 0,limit:n,offset:i,reverse:s}))}a(kI,"iterateFullIndex");function kc(e,t,r,s,n,i=!1,o=void 0,c=void 0,u=!1,_=!1){return Zi(e,t,r,(l,d,f,E)=>{let b={transaction:l,start:i===!0?n:s,end:i===!0?s:n,reverse:i,limit:o,offset:c,inclusiveEnd:i===!0?!u:!_,exclusiveStart:i===!0?_:u};return E===r?(b.values=!1,d.getRange(b).map(R=>({value:R}))):d.getRange(b)})}a(kc,"iterateRangeBetween");function Zi(e,t,r,s){let n=e.database||e,i=ai.openDBI(n,r);i[W_.DBI_DEFINITION_NAME].is_hash_attribute?t=r:t&&ai.openDBI(n,t);let o;e.database?o=e:(o=e.useReadTransaction(),o.database=e);let c=s(o,i,n,t);return c.transaction=o,e.database||(c.onDone=()=>{o.done()}),c}a(Zi,"setupTransaction");function VI(e,t,r,s){let n;return function(i,o){if(typeof i=="string"&&i.endsWith(FI)){if(!n)if(r)n=ai.openDBI(e,r);else{let u=ai.listDBIs(e);for(let _=0,l=u.length;_<l&&(n=ai.openDBI(e,u[_]),!n[W_.DBI_DEFINITION_NAME].is_hash_attribute);_++);}i=n.get(o,{transaction:t,lazy:!0})[s]}return i}}a(VI,"getOverflowCheck");function SQ(e,t,r,s=!1,n=void 0,i=void 0){if(qr.validateEnv(e),t===void 0)throw new Error(lt.HASH_ATTRIBUTE_REQUIRED);return Zi(e,t,t,(o,c,u)=>(z_(r),r=Vc(u,r),c.getRange({transaction:o,start:s?void 0:!1,end:s?!1:void 0,limit:n,offset:i,reverse:s}).map(_=>mQ(_.value,r))))}a(SQ,"searchAll");function TQ(e,t,r,s=!1,n=void 0,i=void 0){if(qr.validateEnv(e),t===void 0)throw new Error(lt.HASH_ATTRIBUTE_REQUIRED);z_(r),r=Vc(e.database||e,r);let o=new Map;for(let{key:c,value:u}of kI(e,t,t,s,n,i))o.set(c,Q_.parseRow(u,r));return o}a(TQ,"searchAllToMap");function gQ(e,t,r=!1,s=void 0,n=void 0){if(qr.validateEnv(e),t===void 0)throw new Error(lt.ATTRIBUTE_REQUIRED);let i=Object.create(null),o=kI(e,void 0,t,r,s,n),c=o.transaction,u=VI(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(gQ,"iterateDBI");function RQ(e,t){if(qr.validateEnv(e),t===void 0)throw new Error(lt.HASH_ATTRIBUTE_REQUIRED);return ai.statDBI(e,t).entryCount}a(RQ,"countAll");function AQ(e,t,r,s,n=!1,i=void 0,o=void 0){return ci(e,r,s),Zi(e,t,r,(c,u,_,l)=>(s=qr.convertKeyValueToWrite(s),l===r?u.get(s,{transaction:c,lazy:!0})===void 0?[]:[{key:s,value:s}]:u.getValues(s,{transaction:c,reverse:n,limit:i,offset:o}).map(d=>({key:s,value:d}))))}a(AQ,"equals");function OQ(e,t,r){return ci(e,t,r),ai.openDBI(e,t).getValuesCount(r)}a(OQ,"count");function bQ(e,t,r,s,n=!1,i=void 0,o=void 0){return ci(e,r,s),Zi(e,null,r,(c,u)=>{s=qr.convertKeyValueToWrite(s);let _=!0;typeof s=="number"&&(_=!1);let l;if(n===!0){let d;for(let f of u.getKeys({transaction:c,start:s}))if(!f.startsWith(s)){d=f;break}return d!==void 0&&(Number.isInteger(o)?o++:i++),l=u.getRange({transaction:c,start:d,end:void 0,reverse:n,limit:i,offset:o}).map(f=>{let{key:E}=f;if(E!==d){if(E.toString().startsWith(s))return f;if(_===!0)return l.DONE}}),l.filter(f=>f)}else return l=u.getRange({transaction:c,start:s,reverse:n,limit:i,offset:o}).map(d=>{if(d.key.toString().startsWith(s))return d;if(_===!0)return l.DONE}),_?l:l.filter(d=>d)})}a(bQ,"startsWith");function NQ(e,t,r,s,n=!1,i=void 0,o=void 0){return $I(e,t,r,s,n,i,o,!0)}a(NQ,"endsWith");function $I(e,t,r,s,n=!1,i=void 0,o=void 0,c=!1){return ci(e,r,s),Zi(e,null,r,(u,_,l,d)=>{let f=VI(l,u,d,r);return o=Number.isInteger(o)?o:0,_.getKeys({transaction:u,end:n?!1:void 0,reverse:n}).flatMap(E=>{let h=E.toString();return h.endsWith(FI)?_.getValues(E,{transaction:u}).map(p=>{let S=f(E,p);if(c?S.endsWith(s):S.includes(s))return{key:S,value:p}}).filter(p=>p):(c?h.endsWith(s):h.includes(s))?_[W_.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($I,"contains");function yQ(e,t,r,s,n=!1,i=void 0,o=void 0){ci(e,r,s);let c=typeof s,u;return c==="string"?u="\uFFFF":c==="number"?u=1/0:c==="boolean"&&(u=!0),kc(e,t,r,s,u,n,i,o,!0,!1)}a(yQ,"greaterThan");function IQ(e,t,r,s,n=!1,i=void 0,o=void 0){ci(e,r,s);let c=typeof s,u;return c==="string"?u="\uFFFF":c==="number"?u=1/0:c==="boolean"&&(u=!0),kc(e,t,r,s,u,n,i,o,!1,!1)}a(IQ,"greaterThanEqual");function wQ(e,t,r,s,n=!1,i=void 0,o=void 0){ci(e,r,s);let c=typeof s,u;return c==="string"?u="\0":c==="number"?u=-1/0:c==="boolean"&&(u=!1),kc(e,t,r,u,s,n,i,o,!1,!0)}a(wQ,"lessThan");function CQ(e,t,r,s,n=!1,i=void 0,o=void 0){ci(e,r,s);let c=typeof s,u;return c==="string"?u="\0":c==="number"?u=-1/0:c==="boolean"&&(u=!1),kc(e,t,r,u,s,n,i,o,!1,!1)}a(CQ,"lessThanEqual");function DQ(e,t,r,s,n,i=!1,o=void 0,c=void 0){if(qr.validateEnv(e),r===void 0)throw new Error(lt.ATTRIBUTE_REQUIRED);if(s===void 0)throw new Error(lt.START_VALUE_REQUIRED);if(n===void 0)throw new Error(lt.END_VALUE_REQUIRED);if(s=qr.convertKeyValueToWrite(s),n=qr.convertKeyValueToWrite(n),s>n)throw new Error(lt.END_VALUE_MUST_BE_GREATER_THAN_START_VALUE);return kc(e,t,r,s,n,i,o,c)}a(DQ,"between");function LQ(e,t,r,s){qr.validateEnv(e);let n=e.database||e,i=e.database?e:null;if(t===void 0)throw new Error(lt.HASH_ATTRIBUTE_REQUIRED);if(z_(r),r=Vc(n,r),s===void 0)throw new Error(lt.ID_REQUIRED);let o=null,c=n.dbis[t].get(s,{transaction:i,lazy:r.length<3});return c&&(o=Q_.parseRow(c,r)),o}a(LQ,"searchByHash");function MQ(e,t,r){qr.validateEnv(e);let s=e.database||e,n=e.database?e:null;if(t===void 0)throw new Error(lt.HASH_ATTRIBUTE_REQUIRED);if(r===void 0)throw new Error(lt.ID_REQUIRED);let i=!0;return s.dbis[t].get(r,{transaction:n,lazy:!0})===void 0&&(i=!1),i}a(MQ,"checkHashExists");function UQ(e,t,r,s,n=[]){return KI(e,t,r,s,n),YI(e,t,r,s,n).map(i=>i[1])}a(UQ,"batchSearchByHash");function PQ(e,t,r,s,n=[]){KI(e,t,r,s,n);let i=new Map;for(let[o,c]of YI(e,t,r,s,n))i.set(o,c);return i}a(PQ,"batchSearchByHashToMap");function YI(e,t,r,s,n=[]){return Zi(e,t,t,(i,o,c)=>{r=Vc(c,r);let u=r.length<3;return s.map(_=>{let l=c.dbis[t].get(_,{transaction:i,lazy:u});if(l)return[_,Q_.parseRow(l,r)];n.push(_)}).filter(_=>_)})}a(YI,"batchHashSearch");function KI(e,t,r,s,n){if(qr.validateEnv(e),t===void 0)throw new Error(lt.HASH_ATTRIBUTE_REQUIRED);if(z_(r),s==null)throw new Error(lt.IDS_REQUIRED);if(!s[Symbol.iterator])throw new Error(lt.IDS_MUST_BE_ITERABLE)}a(KI,"initializeBatchSearchByHash");function z_(e){if(!Array.isArray(e))throw e===void 0?new Error(lt.FETCH_ATTRIBUTES_REQUIRED):new Error(lt.FETCH_ATTRIBUTES_MUST_BE_ARRAY)}a(z_,"validateFetchAttributes");function ci(e,t,r){if(qr.validateEnv(e),t===void 0)throw new Error(lt.ATTRIBUTE_REQUIRED);if(r===void 0)throw new Error(lt.SEARCH_VALUE_REQUIRED);if(r?.length>pQ)throw new Error(lt.SEARCH_VALUE_TOO_LARGE)}a(ci,"validateComparisonFunctions");function Vc(e,t){return t.length===1&&hQ.SEARCH_WILDCARDS.indexOf(t[0])>=0&&(t=ai.listDBIs(e)),t}a(Vc,"setGetWholeRowAttributes");WI.exports={searchAll:SQ,searchAllToMap:TQ,count:OQ,countAll:RQ,equals:AQ,startsWith:bQ,endsWith:NQ,contains:$I,searchByHash:LQ,setGetWholeRowAttributes:Vc,batchSearchByHash:UQ,batchSearchByHashToMap:PQ,checkHashExists:MQ,iterateDBI:gQ,greaterThan:yQ,greaterThanEqual:IQ,lessThan:wQ,lessThanEqual:CQ,between:DQ}});var ta=g((qle,jI)=>{var QI=require("lodash"),zI=Xe(),Ee=require("joi"),vQ=Q(),{hdb_schema_table:$c,checkValidTable:JI,hdb_table:XI,hdb_database:J_}=Js(),{handleHDBError:BQ,hdb_errors:HQ}=se(),{getDatabases:xQ}=(Ae(),ne(Ge)),{HTTP_STATUS_CODES:qQ}=HQ,GQ=Ee.object({database:J_,schema:J_,table:XI,search_attribute:$c,search_value:Ee.any().required(),get_attributes:Ee.array().min(1).items(Ee.alternatives($c,Ee.object())).optional(),desc:Ee.bool(),limit:Ee.number().integer().min(1),offset:Ee.number().integer().min(0)}),FQ=Ee.object({database:J_,schema:J_,table:XI,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($c,Ee.object())).optional(),sort:Ee.object({attribute:Ee.alternatives($c,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($c,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()});jI.exports=function(e,t){let r=null;switch(t){case"value":r=zI.validateBySchema(e,GQ);break;case"hashes":let i=function(o){n?n+=". "+o:n=o};var s=i;a(i,"addError");let n;i(JI("database",e.schema)),i(JI("table",e.table)),e.hash_values?Array.isArray(e.hash_values)?e.hash_values.every(o=>typeof o=="string"||typeof o=="number")||i("'hash_values' must be strings or numbers"):i("'hash_values' must be an array"):i("'hash_values' is required"),e.get_attributes?Array.isArray(e.get_attributes)?e.get_attributes.length===0?i("'get_attributes' must contain at least 1 item"):e.get_attributes.every(o=>typeof o=="string"||typeof o=="number")||i("'get_attributes' must be strings or numbers"):i("'get_attributes' must be an array"):i("'get_attributes' is required"),n&&(r=new Error(n.trim()));break;case"conditions":r=zI.validateBySchema(e,FQ);break;default:throw new Error(`Error validating search, unknown type: ${t}`)}if(!r&&e.schema!=="system"){let n=vQ.checkGlobalSchemaTable(e.schema,e.table);if(n)return BQ(new Error,n,qQ.NOT_FOUND);let o=xQ()[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 _=QI.filter(c,l=>l!=="*"&&l.attribute!=="*"&&!Array.isArray(l)&&!l.name&&!QI.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 Ap=g((Fle,ZI)=>{"use strict";var kQ=We(),VQ=ta(),{getSchemaPath:$Q}=Je();ZI.exports=YQ;function YQ(e){let t=VQ(e,"hashes");if(t)throw t;let r=$Q(e.schema,e.table);return kQ.openEnvironment(r,e.table)}a(YQ,"initialize")});var Op=g((Vle,ew)=>{"use strict";var KQ=ea(),WQ=Ap();ew.exports=QQ;async function QQ(e){let t=await WQ(e),r=t.useReadTransaction();r.database=t;let s=global.hdb_schema[e.schema][e.table];try{return KQ.batchSearchByHashToMap(r,s.hash_attribute,e.get_attributes,e.hash_values)}finally{r.done()}}a(QQ,"lmdbGetDataByHash")});var ra=g((Yle,tw)=>{"use strict";var bp=class{static{a(this,"SearchByHashObject")}constructor(t,r,s,n){this.schema=t,this.table=r,this.hash_values=s,this.get_attributes=n}};tw.exports=bp});var sw=g((Qle,rw)=>{"use strict";var Wle=ra(),zQ=ea(),JQ=Ap();rw.exports=XQ;async function XQ(e){let t=await JQ(e),r=global.hdb_schema[e.schema][e.table];return zQ.batchSearchByHash(t,r.hash_attribute,e.get_attributes,e.hash_values)}a(XQ,"lmdbSearchByHash")});var tn=g((Jle,nw)=>{"use strict";var Np=class{static{a(this,"SearchObject")}constructor(t,r,s,n,i,o,c,u=!1,_=void 0,l=void 0){this.schema=t,this.table=r,this.search_attribute=s,this.search_value=n,this.hash_attribute=i,this.get_attributes=o,this.end_value=c,this.reverse=u,this.limit=_,this.offset=l}};nw.exports=Np});var X_=g((jle,lw)=>{"use strict";var Xt=ea(),jQ=We(),ZQ=Q(),he=Et(),eo=M(),ez=Fi(),iw=Ir().LMDB_ERRORS_ENUM,{getSchemaPath:tz}=Je(),bn=eo.SEARCH_WILDCARDS;async function rz(e,t,r){let s;e.schema===eo.SYSTEM_SCHEMA_NAME?s=ez[e.table]:s=global.hdb_schema[e.schema][e.table];let n=uw(e,s.hash_attribute,r,t);return aw(e,n,s.hash_attribute,r)}a(rz,"prepSearch");async function aw(e,t,r,s){let n=tz(e.schema,e.table),i=await jQ.openEnvironment(n,e.table),o=cw(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(sz(e,r)===!1){let l=e.search_attribute;if(l===r)return s?ow(o,()=>!0):o.map(f=>({[r]:f.key}));let d=a(f=>({[r]:f.value,[l]:f.key}),"toObject");return s?ow(o,d):o.map(d)}let _=e.search_attribute===r?o.map(l=>l.key):o.map(l=>l.value);return s===!0?Xt.batchSearchByHashToMap(c,r,e.get_attributes,_):Xt.batchSearchByHash(c,r,e.get_attributes,_)}a(aw,"executeSearch");function cw(e,t,r,s){let n,i=s;t.get_attributes.indexOf(s)<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:n=Xt.equals(e,i,t.search_attribute,t.search_value,o,c,u);break;case he.SEARCH_TYPES.CONTAINS:n=Xt.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:n=Xt.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:n=Xt.startsWith(e,i,t.search_attribute,t.search_value,o,c,u);break;case he.SEARCH_TYPES.BATCH_SEARCH_BY_HASH:return Xt.batchSearchByHash(e,t.search_attribute,t.get_attributes,[t.search_value]);case he.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP:return Xt.batchSearchByHashToMap(e,t.search_attribute,t.get_attributes,[t.search_value]);case he.SEARCH_TYPES.SEARCH_ALL:return Xt.searchAll(e,s,t.get_attributes,o,c,u);case he.SEARCH_TYPES.SEARCH_ALL_TO_MAP:return Xt.searchAllToMap(e,s,t.get_attributes,o,c,u);case he.SEARCH_TYPES.BETWEEN:n=Xt.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:n=Xt.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:n=Xt.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:n=Xt.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:n=Xt.lessThanEqual(e,i,t.search_attribute,t.search_value,o,c,u);break;default:return Object.create(null)}return n}a(cw,"searchByType");function ow(e,t){let r=new Map;for(let s of e)r.set(s.value,t(s));return r}a(ow,"createMapFromIterable");function sz(e,t){if(e.get_attributes.length===1&&e.get_attributes[0]==="*")return!0;let r=[e.search_attribute];e.get_attributes.indexOf(t)>=0&&r.push(t);let s=!1;for(let n=0;n<e.get_attributes.length;n++)if(r.indexOf(e.get_attributes[n])<0){s=!0;break}return s}a(sz,"checkToFetchMore");function uw(e,t,r,s){if(ZQ.isEmpty(s)){let n=e.search_value;typeof n=="object"?n=JSON.stringify(n):n=n.toString();let i=n.charAt(0),o=n.charAt(n.length-1),c=!1;if(e.search_attribute===t&&(c=!0),bn.indexOf(n)>-1)return r===!0?he.SEARCH_TYPES.SEARCH_ALL_TO_MAP:he.SEARCH_TYPES.SEARCH_ALL;if(n.indexOf(bn[0])<0&&n.indexOf(bn[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(bn.indexOf(i)>=0&&bn.indexOf(o)>=0)return e.search_value=e.search_value.slice(1,-1),he.SEARCH_TYPES.CONTAINS;if(bn.indexOf(i)>=0)return e.search_value=e.search_value.substr(1),he.SEARCH_TYPES.ENDS_WITH;if(bn.indexOf(o)>=0)return e.search_value=e.search_value.slice(0,-1),he.SEARCH_TYPES.STARTS_WITH;if(n.includes(bn[0])||n.includes(bn[1]))return he.SEARCH_TYPES.EQUALS;throw new Error(iw.UNKNOWN_SEARCH_TYPE)}else switch(s){case eo.VALUE_SEARCH_COMPARATORS.BETWEEN:return he.SEARCH_TYPES.BETWEEN;case eo.VALUE_SEARCH_COMPARATORS.GREATER:return he.SEARCH_TYPES.GREATER_THAN;case eo.VALUE_SEARCH_COMPARATORS.GREATER_OR_EQ:return he.SEARCH_TYPES.GREATER_THAN_EQUAL;case eo.VALUE_SEARCH_COMPARATORS.LESS:return he.SEARCH_TYPES.LESS_THAN;case eo.VALUE_SEARCH_COMPARATORS.LESS_OR_EQ:return he.SEARCH_TYPES.LESS_THAN_EQUAL;default:throw new Error(iw.UNKNOWN_SEARCH_TYPE)}}a(uw,"createSearchTypeFromSearchObject");lw.exports={executeSearch:aw,createSearchTypeFromSearchObject:uw,prepSearch:rz,searchByType:cw}});var dw=g((t_e,_w)=>{"use strict";var e_e=tn(),nz=ta(),iz=Q(),oz=M(),az=X_();_w.exports=cz;function cz(e,t){if(!iz.isEmpty(t)&&oz.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[t]===void 0)throw new Error(`Value search comparator - ${t} - is not valid`);let s=nz(e,"value");if(s)throw s;return az.prepSearch(e,t,!0)}a(cz,"lmdbGetDataByValue")});var Yc=g((n_e,fw)=>{"use strict";var s_e=tn(),uz=ta(),lz=Q(),_z=M(),dz=X_();fw.exports=fz;async function fz(e,t){if(!lz.isEmpty(t)&&_z.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[t]===void 0)throw new Error(`Value search comparator - ${t} - is not valid`);let s=uz(e,"value");if(s)throw s;return dz.prepSearch(e,t,!1)}a(fz,"lmdbSearchByValue")});var hw=g((a_e,Ew)=>{"use strict";var o_e=Et(),yp=class{static{a(this,"SearchByConditionsObject")}constructor(t,r,s,n,i=void 0,o=void 0,c="and"){this.schema=t,this.table=r,this.get_attributes=s,this.limit=i,this.offset=o,this.conditions=n,this.operator=c}},Ip=class{static{a(this,"SearchCondition")}constructor(t,r,s){this.search_attribute=t,this.search_type=r,this.search_value=s}},wp=class{static{a(this,"SortAttribute")}constructor(t,r){this.attribute=t,this.desc=r}};Ew.exports={SearchByConditionsObject:yp,SearchCondition:Ip,SortAttribute:wp}});var gw=g((__e,Tw)=>{"use strict";var u_e=hw().SearchByConditionsObject,Ez=tn(),hz=ta(),Cp=ea(),j_=Et(),{Resource:l_e}=(Ns(),ne(Dp)),Sw=X_(),mz=Rp(),pz=require("lodash"),{getSchemaPath:Sz}=Je(),mw=We(),{handleHDBError:Tz,hdb_errors:gz}=se(),{HTTP_STATUS_CODES:Rz}=gz,Az=1e8;Tw.exports=Oz;async function Oz(e){let t=hz(e,"conditions");if(t)throw Tz(t,t.message,Rz.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=Sz(e.schema,e.table),s=await mw.openEnvironment(r,e.table),n=global.hdb_schema[e.schema][e.table];for(let _ of e.conditions)mw.openDBI(s,_.search_attribute);let i=pz.sortBy(e.conditions,_=>{if(_.estimated_count===void 0){let l=_.search_type;l===j_.SEARCH_TYPES.EQUALS?_.estimated_count=Cp.count(s,_.search_attribute,_.search_value):l===j_.SEARCH_TYPES.CONTAINS||l===j_.SEARCH_TYPES.ENDS_WITH?_.estimated_count=1/0:_.estimated_count=Az}return _.estimated_count}),o=s.useReadTransaction();o.database=s;let c=await pw(o,e,i[0],n.hash_attribute),u;if(!e.operator||e.operator.toLowerCase()==="and"){let _=s.dbis[n.hash_attribute],l=i.slice(1).map(Sw.filterByType),d=l.length,f=Cp.setGetWholeRowAttributes(s,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=>mz.parseRow(E,f))}else{for(let d=1;d<i.length;d++){let f=i[d],E=await pw(o,e,f,n.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=Cp.batchSearchByHash(o,n.hash_attribute,e.get_attributes,c)}return u.onDone=()=>{o.done()},u}a(Oz,"lmdbSearchByConditions");async function pw(e,t,r,s){let n=new Ez(t.schema,t.table,void 0,void 0,s,t.get_attributes),i=r.search_type;return n.search_attribute=r.search_attribute,i===j_.SEARCH_TYPES.BETWEEN?(n.search_value=r.search_value[0],n.end_value=r.search_value[1]):n.search_value=r.search_value,Sw.searchByType(e,n,i,s).map(o=>o.value)}a(pw,"executeConditionSearch")});var sa=g((f_e,Rw)=>{"use strict";var bz=M().OPERATIONS_ENUM,Lp=class{static{a(this,"DeleteObject")}constructor(t,r,s,n=void 0){this.operation=bz.DELETE,this.schema=t,this.table=r,this.hash_values=s,this.__origin=n}};Rw.exports=Lp});var Mp=g((h_e,Cw)=>{"use strict";var Nw=tn(),yw=sa(),Iw=Yc(),ww=Fc(),lr=M(),Aw=Q(),Ow=We(),{getTransactionAuditStorePath:Nz,getSchemaPath:yz}=Je(),bw=$();Cw.exports=Iz;async function Iz(e){try{if(Aw.isEmpty(global.hdb_schema[e.schema])||Aw.isEmpty(global.hdb_schema[e.schema][e.table]))throw new Error(`unknown schema:${e.schema} and table ${e.table}`);await wz(e),await Cz(e);let t=yz(e.schema,e.table);try{await Ow.deleteEnvironment(t,e.table)}catch(r){if(r.message==="invalid environment")bw.warn(`cannot delete environment for ${e.schema}.${e.table}, environment not found`);else throw r}try{let r=Nz(e.schema,e.table);await Ow.deleteEnvironment(r,e.table,!0)}catch(r){if(r.message==="invalid environment")bw.warn(`cannot delete environment for ${e.schema}.${e.table}, environment not found`);else throw r}}catch(t){throw t}}a(Iz,"lmdbDropTable");async function wz(e){let t=new Nw(lr.SYSTEM_SCHEMA_NAME,lr.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,lr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_TABLE_KEY,`${e.schema}.${e.table}`,void 0,[lr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),r=Array.from(await Iw(t)),s=[];for(let i=0;i<r.length;i++){let o=r[i];s.push(o.id)}if(s.length===0)return;let n=new yw(lr.SYSTEM_SCHEMA_NAME,lr.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,s);await ww(n)}a(wz,"deleteAttributesFromSystem");async function Cz(e){let t=new Nw(lr.SYSTEM_SCHEMA_NAME,lr.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,lr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY,e.table,void 0,[lr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY,lr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_KEY,lr.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),r,s;try{r=Array.from(await Iw(t))}catch(i){throw i}for(let i=0;i<r.length;i++){let o=r[i];o.name===e.table&&o.schema===e.schema&&(s=o)}if(!s)throw new Error(`${e.schema}.${e.table} was not found`);let n=new yw(lr.SYSTEM_SCHEMA_NAME,lr.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,[s.id]);try{await ww(n)}catch(i){throw i}}a(Cz,"dropTableFromSystem")});var Lw=g((p_e,Dw)=>{"use strict";var Dz=require("fs-extra"),Lz=tn(),Mz=ra(),Uz=sa(),Pz=Mp(),vz=Fc(),Bz=Op(),Hz=Yc(),Nn=M(),{getSchemaPath:xz}=Je(),{handleHDBError:qz,hdb_errors:Gz}=se(),{HDB_ERROR_MSGS:Fz,HTTP_STATUS_CODES:kz}=Gz;Dw.exports=Vz;async function Vz(e){let t;try{t=await $z(e.schema);let r=new Lz(Nn.SYSTEM_SCHEMA_NAME,Nn.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,Nn.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_KEY,t,void 0,[Nn.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY]),s=Array.from(await Hz(r));for(let o=0;o<s.length;o++){let c={schema:t,table:s[o].name};try{await Pz(c)}catch(u){if(u.message!=="invalid environment")throw u}}let n=new Uz(Nn.SYSTEM_SCHEMA_NAME,Nn.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,[t]);await vz(n);let i=xz(t);await Dz.remove(i)}catch(r){throw r}}a(Vz,"lmdbDropSchema");async function $z(e){let t=new Mz(Nn.SYSTEM_SCHEMA_NAME,Nn.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,[e],[Nn.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY]),r,s;try{r=Array.from(await Bz(t))}catch(n){throw n}for(let[,n]of r)n.name===e&&(s=e);if(!s)throw qz(new Error,Fz.SCHEMA_NOT_FOUND(e),kz.NOT_FOUND,void 0,void 0,!0);return s}a($z,"validateDropSchema")});var Z_=g((T_e,Mw)=>{"use strict";var Up=class{static{a(this,"CreateTableObject")}constructor(t,r,s){this.schema=t,this.table=r,this.hash_attribute=s}};Mw.exports=Up});var Pw=g((A_e,Uw)=>{"use strict";var Yz=require("fs-extra"),ed=We(),{getTransactionAuditStorePath:Kz}=Je(),Pp=Et(),R_e=Z_();Uw.exports=Wz;async function Wz(e){let t;try{let r=Kz(e.schema,e.table);await Yz.mkdirp(r),t=await ed.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{ed.createDBI(t,Pp.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,!1,!0),ed.createDBI(t,Pp.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE,!0,!1),ed.createDBI(t,Pp.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(Wz,"createTransactionsAuditEnvironment")});var xw=g((b_e,Hw)=>{"use strict";var vp=M(),vw=We(),Qz=ko(),{getSystemSchemaPath:zz,getSchemaPath:Jz}=Je(),Xz=Fi(),jz=T_(),Bp=S_(),Zz=$(),e2=Pw(),xp=Xz.hdb_table,Bw=[];for(let e=0;e<xp.attributes.length;e++)Bw.push(xp.attributes[e].attribute);Hw.exports=t2;async function t2(e,t){let r=Jz(t.schema,t.table),s=new Bp(t.schema,t.table,vp.TIME_STAMP_NAMES_ENUM.CREATED_TIME,void 0,!0),n=new Bp(t.schema,t.table,vp.TIME_STAMP_NAMES_ENUM.UPDATED_TIME,void 0,!0),i=new Bp(t.schema,t.table,t.hash_attribute,void 0,!1,!0);try{if(await vw.createEnvironment(r,t.table),e!==void 0){let o=await vw.openEnvironment(zz(),vp.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME);await Qz.insertRecords(o,xp.hash_attribute,Bw,[e]),s.skip_table_check=!0,n.skip_table_check=!0,i.skip_table_check=!0,await Hp(s),await Hp(n),await Hp(i)}await e2(t)}catch(o){throw o}}a(t2,"lmdbCreateTable");async function Hp(e){try{await jz(e)}catch(t){Zz.warn(`failed to create attribute ${e.attribute} due to ${t.message}`)}}a(Hp,"createAttribute")});var Gw=g((y_e,qw)=>{"use strict";var r2=Dc(),s2=Mc(),n2=Y_(),Kc=M(),i2=ko().updateRecords,o2=We(),{getSchemaPath:a2}=Je(),c2=qc(),u2=$();qw.exports=l2;async function l2(e){try{let{schema_table:t,attributes:r}=r2(e);s2(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 s=await n2(e.hdb_auth_header,t,r),n=a2(e.schema,e.table),i=await o2.openEnvironment(n,e.table),o=await i2(i,t.hash_attribute,r,e.records,e.__origin?.timestamp);try{await c2(e,o)}catch(c){u2.error(`unable to write transaction due to ${c.message}`)}return{written_hashes:o.written_hashes,skipped_hashes:o.skipped_hashes,schema_table:t,new_attributes:s,txn_time:o.txn_time}}catch(t){throw t}}a(l2,"lmdbUpdateRecords")});var kw=g((w_e,Fw)=>{"use strict";var _2=M().OPERATIONS_ENUM,qp=class{static{a(this,"UpsertObject")}constructor(t,r,s,n=void 0){this.operation=_2.UPSERT,this.schema=t,this.table=r,this.records=s,this.__origin=n}};Fw.exports=qp});var $w=g((L_e,Vw)=>{"use strict";var D_e=kw(),d2=Dc(),f2=Mc(),E2=Y_(),Wc=M(),h2=ko().upsertRecords,m2=We(),{getSchemaPath:p2}=Je(),S2=qc(),T2=$(),{handleHDBError:g2,hdb_errors:R2}=se();Vw.exports=A2;async function A2(e){let t;try{t=d2(e)}catch(u){throw g2(u,u.message,R2.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0)}let{schema_table:r,attributes:s}=t;f2(e,s,r.hash_attribute),e.schema!==Wc.SYSTEM_SCHEMA_NAME&&(s.includes(Wc.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||s.push(Wc.TIME_STAMP_NAMES_ENUM.CREATED_TIME),s.includes(Wc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||s.push(Wc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let n=await E2(e.hdb_auth_header,r,s),i=p2(e.schema,e.table),o=await m2.openEnvironment(i,e.table),c=await h2(o,r.hash_attribute,s,e.records,e.__origin?.timestamp);try{await S2(e,c)}catch(u){T2.error(`unable to write transaction due to ${u.message}`)}return{written_hashes:c.written_hashes,schema_table:r,new_attributes:n,txn_time:c.txn_time}}a(A2,"lmdbUpsertRecords")});var Kw=g((U_e,Yw)=>{"use strict";var Gp=class{static{a(this,"DeleteBeforeObject")}constructor(t,r,s){this.schema=t,this.table=r,this.timestamp=s}};Yw.exports=Gp});var Qw=g((v_e,Ww)=>{"use strict";var Fp=class{static{a(this,"DeleteAuditLogsBeforeResults")}constructor(t=void 0,r=void 0,s=0){this.start_timestamp=t,this.end_timestamp=r,this.transactions_deleted=s}};Ww.exports=Fp});var Xw=g((x_e,Jw)=>{"use strict";var kp=We(),{getTransactionAuditStorePath:O2}=Je(),H_e=Kw(),Qc=Et(),b2=Q(),zw=Qw(),N2=require("util").promisify,y2=N2(setTimeout),I2=1e4,w2=100;Jw.exports=C2;async function C2(e){let t=O2(e.schema,e.table),r=await kp.openEnvironment(t,e.table,!0),s=kp.listDBIs(r);kp.initializeDBIs(r,Qc.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,s);let n,i=new zw;do n=await D2(r,e.timestamp),i.start_timestamp===void 0&&(i.start_timestamp=n.start_timestamp),n.end_timestamp!==void 0&&(i.end_timestamp=n.end_timestamp),i.transactions_deleted+=n.transactions_deleted,await y2(w2);while(n.transactions_deleted>0);return i}a(C2,"deleteAuditLogsBefore");async function D2(e,t){let r=new zw;try{let s=e.dbis[Qc.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP],n;for(let{key:i,value:o}of s.getRange({start:!1})){if(i>=t)break;r.start_timestamp===void 0&&(r.start_timestamp=i),n=s.remove(i);let c=o[Qc.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME];b2.isEmpty(c)||(n=e.dbis[Qc.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].remove(c,i));for(let u=0;u<o.hash_values.length;u++)n=e.dbis[Qc.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE].remove(o.hash_values[u],i);if(r.transactions_deleted++,r.end_timestamp=i,r.transactions_deleted>I2)break}return await n,r}catch(s){throw s}}a(D2,"deleteTransactions")});var Zw=g((G_e,jw)=>{"use strict";var Vp=class{static{a(this,"DropAttributeObject")}constructor(t,r,s){this.schema=t,this.table=r,this.attribute=s}};jw.exports=Vp});var tC=g((V_e,eC)=>{"use strict";var L2=tn(),M2=sa(),k_e=Zw(),rn=M(),U2=Q(),$p=We(),P2=Fi(),v2=Yc(),B2=Fc(),{getSchemaPath:H2}=Je();eC.exports=x2;async function x2(e,t=!0){let r;e.schema===rn.SYSTEM_SCHEMA_NAME?r=P2[e.table]:r=global.hdb_schema[e.schema][e.table];let s=await G2(e),n=H2(e.schema,e.table),i=await $p.openEnvironment(n,e.table);return t===!0&&await q2(e,i,r.hash_attribute),$p.dropDBI(i,e.attribute),s}a(x2,"lmdbDropAttribute");async function q2(e,t,r){let s=$p.openDBI(t,r),n,i=e.attribute;for(let{key:o,value:c,version:u}of s.getRange({start:!1,versions:!0})){let _={};for(let l in c)l!==i&&(_[l]=c[l]);n=t.dbis[r].put(o,_,u)}await n}a(q2,"removeAttributeFromAllObjects");async function G2(e){let t=new L2(rn.SYSTEM_SCHEMA_NAME,rn.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,rn.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_TABLE_KEY,`${e.schema}.${e.table}`,void 0,[rn.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY,rn.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ATTRIBUTE_KEY]),s=Array.from(await v2(t)).filter(o=>o[rn.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ATTRIBUTE_KEY]===e.attribute);if(U2.isEmptyOrZeroLength(s))throw new Error(`Attribute '${e.attribute}' was not found in '${e.schema}.${e.table}'`);let n=s.map(o=>o[rn.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),i=new M2(rn.SYSTEM_SCHEMA_NAME,rn.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,n);return B2(i)}a(G2,"dropAttributeFromSystem")});var aC=g((K_e,oC)=>{"use strict";var Yp=We(),na=Et(),Y_e=wr(),Kp=M(),rC=Q(),{getTransactionAuditStorePath:F2}=Je(),k2=ea(),td=Xo(),V2=$();oC.exports=$2;async function $2(e){let t=F2(e.schema,e.table),r=await Yp.openEnvironment(t,e.table,!0),s=Yp.listDBIs(r);Yp.initializeDBIs(r,na.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,s);let n;switch(e.search_type){case Kp.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.TIMESTAMP:return sC(r,e.search_values);case Kp.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.HASH_VALUE:return n=global.hdb_schema[e.schema][e.table].hash_attribute,K2(r,e.search_values,n);case Kp.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.USERNAME:return Y2(r,e.search_values);default:return sC(r)}}a($2,"readAuditLog");function sC(e,t=[0,Date.now()]){rC.isEmpty(t[0])&&(t[0]=0),rC.isEmpty(t[1])&&(t[1]=Date.now());let r=e.dbis[na.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP],s;for(let n of r.getKeys({start:t[1]}))if(n!==t[1]){s=n;break}return r.getRange({start:t[0],end:s}).map(({value:n})=>Object.assign(new td,n))}a(sC,"searchTransactionsByTimestamp");function Y2(e,t=[]){let r=new Map;for(let s=0;s<t.length;s++){let n=t[s],i=[];for(let o of e.dbis[na.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].getValues(n))i.push(o);r.set(n,iC(e,i))}return Object.fromEntries(r)}a(Y2,"searchTransactionsByUsername");function K2(e,t,r){let s=new Map;for(let c=0,u=t.length;c<u;c++){let _=t[c],l=k2.equals(e,na.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,na.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE,_);for(let{value:d}of l){let f=Number(d);s.has(f)?s.get(f).push(_.toString()):s.set(f,[_.toString()])}}let n=Array.from(s.keys()),i=iC(e,n),o=new Map;for(let c=0;c<i.length;c++){let u=i[c],_=u.timestamp,l=s.get(_);nC(u,"records",r,l,o),nC(u,"original_records",r,l,o)}return Object.fromEntries(o)}a(K2,"searchTransactionsByHashValues");function nC(e,t,r,s,n){let i=e.timestamp;if(e[t])for(let o=0;o<e[t].length;o++){let c=e[t][o],u=c[r].toString();if(s.indexOf(u)>=0)if(n.has(u)){let _=n.get(u),l=_[_.length-1];if(l.timestamp===i)l[t]=[c];else{let d=new td(e.operation,e.user_name,i,void 0);d[t]=[c],_.push(d)}}else{let _=new td(e.operation,e.user_name,i,void 0);_[t]=[c],n.set(u,[_])}}}a(nC,"loopRecords");function iC(e,t){let r=[];try{let s=e.dbis[na.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP];for(let n=0;n<t.length;n++)try{let i=s.get(t[n]);if(i){let o=Object.assign(new td,i);r.push(o)}}catch(i){V2.warn(i)}return r}catch(s){throw s}}a(iC,"batchSearchTransactions")});var uC=g((J_e,cC)=>{"use strict";var{getSchemaPath:Q_e}=Je(),z_e=We(),{database:W2}=(Ae(),ne(Ge));cC.exports={writeTransaction:Q2};async function Q2(e,t,r){return W2({database:e,table:t}).transaction(r)}a(Q2,"writeTransaction")});var fC=g((j_e,dC)=>{"use strict";var{getSchemaPath:lC}=Je(),_C=We();dC.exports={flush:z2,resetReadTxn:J2};async function z2(e,t){return(await _C.openEnvironment(lC(e,t),t.toString())).flushed}a(z2,"flush");async function J2(e,t){try{(await _C.openEnvironment(lC(e,t),t.toString())).resetReadTxn()}catch{}}a(J2,"resetReadTxn")});var pC=g((ede,mC)=>{"use strict";var{Readable:X2}=require("stream"),{getDatabases:j2}=(Ae(),ne(Ge)),{readSync:Z2,openSync:eJ,createReadStream:EC}=require("fs"),{open:tJ}=require("lmdb"),hC=c_(),rJ=l_(),{AUDIT_STORE_OPTIONS:sJ}=(qi(),ne(SC)),{INTERNAL_DBIS_NAME:nJ,AUDIT_STORE_NAME:iJ}=Et();mC.exports=aJ;var Wp=32768,oJ=100;async function aJ(e){let t=e.database||e.schema||"data",r=j2()[t],s=new Date().toISOString(),n=e.tables||e.table&&[e.table];if(n){let _=r[n[0]];if(!_)throw new Error(`Can not find table ${n[0]}`);let l=_.dbisDB,d=tJ({noSync:!0,maxDbs:rJ.MAX_DBS}),f,E=d.openDB(nJ,new hC(!1)),h=l.useReadTransaction(),p=0,S=a(async function(b,R){R.encoding="binary",R.encoder=void 0;let L=d.openDB(b,R),H=l.openDB(b,R);for(let{key:P,version:k,value:B}of H.getRange({transaction:h,versions:H.useVersions}))f=L.put(P,B,k),p++%oJ===0&&(await new Promise(X=>setTimeout(X,20)),h.openTimer&&(h.openTimer=0))},"copyDatabase");for(let{key:b,value:R}of l.getRange({transaction:h,start:!1}))if(n.some(L=>b.startsWith?.(L+"/"))){E.put(b,R);let[,L]=b.split("/"),H=!L,P=new hC(!H,H);await S(b,P)}e.include_audit&&await S(iJ,Object.assign({},sJ)),await f;let T=EC(d.path);return T.headers=u(),T.on("close",()=>{h.done(),d.close()}),T}let o=r[Object.keys(r)[0]].primaryStore,c=eJ(o.path);return o.transaction(()=>{let _=Buffer.alloc(Wp);Z2(c,_,0,Wp),o.resetReadTxn();let l=o.useReadTransaction();l.renew();let d=EC(null,{fd:c,start:Wp}),f=new X2.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",s),_}}a(aJ,"getBackup")});var RC=g((rde,gC)=>{"use strict";var cJ=$(),{handleHDBError:uJ}=se(),lJ=Pb(),_J=T_(),dJ=mp(),fJ=LI(),EJ=Fc(),hJ=Op(),mJ=sw(),pJ=dw(),SJ=Yc(),TJ=gw(),gJ=Lw(),RJ=xw(),AJ=Gw(),OJ=$w(),bJ=Xw(),NJ=Mp(),yJ=tC(),IJ=aC(),wJ=uC(),TC=fC(),CJ=pC(),Qp=class extends lJ{static{a(this,"LMDBBridge")}async searchByConditions(t){return TJ(t)}async getDataByHash(t){return await hJ(t)}async searchByHash(t){return await mJ(t)}async getDataByValue(t,r){return await pJ(t,r)}async searchByValue(t){return await SJ(t)}async createSchema(t){return await fJ(t)}async dropSchema(t){return await gJ(t)}async createTable(t,r){return await RJ(t,r)}async dropTable(t){return await NJ(t)}async createAttribute(t){return await _J(t)}async createRecords(t){return await dJ(t)}async updateRecords(t){return await AJ(t)}async upsertRecords(t){try{return await OJ(t)}catch(r){throw uJ(r,null,null,cJ.ERR,r)}}async deleteRecords(t){return await EJ(t)}async dropAttribute(t){return await yJ(t)}async deleteAuditLogsBefore(t){return await bJ(t)}async readAuditLog(t){return await IJ(t)}writeTransaction(t,r,s){return wJ.writeTransaction(t,r,s)}flush(t,r){return TC.flush(t,r)}resetReadTxn(t,r){return TC.resetReadTxn(t,r)}getBackup(t){return CJ(t)}};gC.exports=Qp});function PJ(){UJ=setInterval(function(){for(let e of zp)if(e.stale){let t=e[Oe]?.url;bC.error(`Transaction was open too long and has been aborted, from table: ${e.lmdbDb?.name+(t?" path: "+t:"")}`),e.abort()}else e.stale=!0},MJ).unref()}var Jp,OC,bC,DJ,zp,LJ,zc,AC,to,rd,MJ,UJ,Xp=Re(()=>{Jp=x(wr()),OC=x(se()),bC=x($());Ns();DJ=100,zp=new Set,LJ=25e3,to=class e{static{a(this,"DatabaseTransaction")}writes=[];lmdbDb;readTxn;readTxnRefCount;readTxnsUsed;validated=0;timestamp=0;open=1;getReadTxn(){if(this.readTxnRefCount=(this.readTxnRefCount||0)+1,this.stale&&(this.stale=!1),this.readTxn)return this.readTxn.openTimer&&(this.readTxn.openTimer=0),this.readTxn;if(this.open===1)return this.readTxnsUsed=1,this.readTxn=this.lmdbDb.useReadTransaction(),this.readTxn.openTimer&&(this.readTxn.openTimer=0),zp.add(this),this.readTxn}useReadTxn(){return this.getReadTxn(),this.readTxn.use(),this.readTxnsUsed++,this.readTxn}doneReadTxn(){this.readTxn&&(this.readTxn.done(),--this.readTxnsUsed===0&&(zp.delete(this),this.readTxn=null))}disregardReadTxn(){--this.readTxnRefCount===0&&this.readTxnsUsed===1&&this.doneReadTxn()}checkOverloaded(){if(zc&&performance.now()-AC>LJ)throw new OC.ServerError("Outstanding write transactions have too long of queue, please try again later",503)}addWrite(t){if(this.open===0)throw new Error("Can not use a transaction that is no longer open");if(this.open===2){let r=new e;return r.addWrite(t),r.commit({})}else this.writes.push(t)}removeWrite(t){let r=this.writes.indexOf(t);r>-1&&(this.writes[r]=null)}commit(t={}){let r=this.timestamp;r||(r=this.timestamp=t.timestamp=t.timestamp||(0,Jp.getNextMonotonicTime)());let s=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}s||this.doneReadTxn(),this.open=t?.letItLinger?2:0;let n,i=[],o=0;this.writes=this.writes.filter(l=>l);let c=a(l=>{l.commit(r,l.entry,s)},"doWrite"),u=a(()=>{let l=this.writes[o++];if(l)if(l.key){s>0&&(l.entry=l.store.getEntry(l.key));let d=l.store.ifVersion(l.key,l.entry?.version??null,u);n=n||d}else u();else for(let d of this.writes)c(d)},"nextCondition");if(this.writes.length<DJ>>s?u():n=this.writes[0].store.transaction(()=>{for(let l of this.writes)l.entry=l.store.getEntry(l.key),c(l);return!0}),n)return zc||(zc=n,AC=performance.now(),zc.then(()=>{zc=null})),n.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=s+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=0,this.writes=[]}},rd=class extends to{static{a(this,"ImmediateTransaction")}_timestamp;addWrite(t){super.addWrite(t),this.commit()}get timestamp(){return this._timestamp||(this._timestamp=(0,Jp.getNextMonotonicTime)())}getReadTxn(){}},MJ=3e4;a(PJ,"startMonitoringTxns");PJ()});function je(e,t,r){if(!t)t=e,e={};else if(!e)e={};else if(e?.transaction?.open===1&&typeof t=="function")return t(e.transaction);if(typeof t!="function")throw new Error("Callback function must be provided to transaction");let s=e.transaction=new to;e.timestamp&&(s.timestamp=e.timestamp),s[Oe]=e,e.resourceCache||(e.resourceCache=[]);let n;try{if(n=t(s),n?.then)return n.then(i,o)}catch(c){o(c)}return i(n);function i(c){let u=s.commit({letItLinger:r?.letItLinger});return u.then?u.then(()=>c):c}function o(c){throw s.abort({}),c}}var NC,ro=Re(()=>{NC=require("../index");Ns();Xp();a(je,"transaction");(0,NC._assignPackageExport)("transaction",je);je.commit=function(e){let t=(e[Oe]||e)?.transaction;if(!t)throw new Error("No active transaction is available to commit");return t.commit()};je.abort=function(e){let t=(e[Oe]||e)?.transaction;if(!t)throw new Error("No active transaction is available to abort");return t.abort()}});var PC={};Ye(PC,{ResourceBridge:()=>eS});function tS({get_attributes:e},t){if(e){if(e[0]==="*"){if(t.schemaDefined)return;e=t.attributes.map(r=>r.name)}return e.forceNulls=!0,e}}function IC(e,t){let r=sn(e),s=tS(e,r);if(!r)throw new Ms.ClientError(`Table ${e.table} not found`);let n;s&&r.attributes.length-s.length>2&&s.length<5&&(n=!0);let i={user:e.hdb_user},o;je(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:n,select:s},i);return l=l&&nd(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 sn(e){let t=e.database||e.schema||BJ,r=Us()[t];if(!r)throw(0,Ms.handleHDBError)(new Error,vJ.SCHEMA_NOT_FOUND(t),404);return r[e.table]}function wC(e,t,r){let s=e.length+t.length,n=s===1?"record":"records";return{message:`${e.length} of ${s} ${n} successfully deleted`,deleted_hashes:e,skipped_hashes:t,txn_time:r}}async function*CC(e,t,r){let s;for await(let n of e.getHistory(t,r)){let i=n.type;i==="put"&&(i="upsert");let{id:o,version:c,value:u}=n;s?.timestamp===c?(s.hash_values.push(o),s.records.push(u)):(s&&(yield s),s={operation:i,user_name:n.user,timestamp:c,hash_values:[o],records:[u]})}s&&(yield s)}var DC,sd,Ms,LC,MC,Ps,jp,Zp,UC,vJ,BJ,HJ,xJ,yC,eS,vC=Re(()=>{"use strict";DC=x(RC()),sd=x(ta()),Ms=x(se());Ae();LC=x(Dc()),MC=x(Mc()),Ps=x(M()),jp=x(On()),Zp=x(Ls()),UC=x(Q());ro();id();({HDB_ERROR_MSGS:vJ}=Ms.hdb_errors),BJ="data",HJ=1e4,xJ=10,eS=class extends DC.default{static{a(this,"ResourceBridge")}constructor(t){super(t),yC=this}async searchByConditions(t){t.select!==void 0&&(t.get_attributes=t.select);for(let o of t.conditions||[])o?.attribute!==void 0&&(o.search_attribute=o.attribute),o?.comparator!==void 0&&(o.search_type=o.comparator),o?.value!==void 0&&(o.search_value=o.value);let r=(0,sd.default)(t,"conditions");if(r)throw(0,Ms.handleHDBError)(r,r.message,400,void 0,void 0,!0);let s=sn(t);if(!s)throw new Ms.ClientError(`Table ${t.table} not found`);let n=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"),s.search({conditions:n,operator:t.operator?t.operator.toLowerCase():void 0,limit:t.limit,offset:t.offset,reverse:t.reverse,select:tS(t,s),sort:t.sort,allowFullScan:!0})}async createTable(t,r){let s=r.attributes,n=!!s,i=r.primary_key||r.hash_attribute;if(s)for(let o of s)o.is_primary_key?(o.isPrimaryKey=!0,delete o.is_primary_key):o.name===i&&i&&(o.isPrimaryKey=!0);else{if(!i)throw new Ms.ClientError("A primary key must be specified with a `primary_key` property or with `attributes`");s=[{name:i,isPrimaryKey:!0},{name:"__createdtime__",indexed:!0},{name:"__updatedtime__",indexed:!0}]}ut({database:r.schema,table:r.table,attributes:s,schemaDefined:n,expiration:r.expiration})}async createAttribute(t){return await sn(t).addAttributes([{name:t.attribute,indexed:t.indexed??!0}]),`attribute ${t.schema}.${t.table}.${t.attribute} successfully created.`}async dropAttribute(t){let r=sn(t);if(await r.removeAttributes([t.attribute]),!r.schemaDefined){let s=t.attribute,n,i=a((o,c,u)=>(c=Object.assign({},c),delete c[s],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}))n=i(o,c,u),await new Promise(_=>setImmediate(_));await n}return`successfully deleted ${t.schema}.${t.table}.${t.attribute}`}dropTable(t){sn(t).dropTable()}createSchema(t){return Jc({database:t.schema,table:null}),jp.signalSchemaChange(new Zp.SchemaEventMsg(process.pid,Ps.OPERATIONS_ENUM.CREATE_SCHEMA,t.schema))}async dropSchema(t){await rS(t.schema),jp.signalSchemaChange(new Zp.SchemaEventMsg(process.pid,Ps.OPERATIONS_ENUM.DROP_SCHEMA,t.schema))}async updateRecords(t){return t.requires_existing=!0,this.upsertRecords(t)}async createRecords(t){return t.requires_no_existing=!0,yC.upsertRecords(t)}async upsertRecords(t){let{schema_table:r,attributes:s}=(0,LC.default)(t);(0,MC.default)(t,s,r.primaryKey);let n,i=Us()[t.schema][t.table],o={user:t.hdb_user,expiresAt:t.expiresAt};return je(o,async c=>{if(!i.schemaDefined){n=[];for(let l of s)i.attributes.find(f=>f.name==l)||n.push(l);n.length>0&&await i.addAttributes(n.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=nd(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:n,skipped_hashes:_}})}async deleteRecords(t){let r=Us()[t.schema][t.table],s={user:t.hdb_user};return je(s,async n=>{let i=t.hash_values||t.records.map(u=>u[r.primaryKey]),o=[],c=[];for(let u of i)await r.delete(u,s)?o.push(u):c.push(u);return wC(o,c,n.timestamp)})}async deleteRecordsBefore(t){let r=Us()[t.schema][t.table];if(!r.createdTimeProperty)throw new Ms.ClientError("Table must have a '__createdtime__' attribute or @createdTime timestamp defined to perform this operation");let s=await r.search({conditions:[{attribute:r.createdTimeProperty.name,value:Date.parse(t.date),comparator:Ps.VALUE_SEARCH_COMPARATORS.LESS}]}),n=!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,UC.async_set_timeout)(xJ),u=[],n=!0},"chunkDelete");for await(let l of s)u.push(l[r.primaryKey]),c++,c%HJ===0&&await _();return u.length>0&&await _(),n?wC(i,o,void 0):{message:"No records found to delete"}}searchByHash(t){t.select!==void 0&&(t.get_attributes=t.select);let r=(0,sd.default)(t,"hashes");if(r)throw r;return IC(t)}async getDataByHash(t){let r=new Map;t._returnKeyValue=!0;for await(let{key:s,value:n}of IC(t,!0))r.set(s,n);return r}searchByValue(t,r){if(r&&Ps.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 s=(0,sd.default)(t,"value");if(s)throw s;let n=sn(t);if(!n)throw new Ms.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===Ps.VALUE_SEARCH_COMPARATORS.BETWEEN&&(i=[i,t.end_value]);let o=i==="*"?[]:[{attribute:t.search_attribute,value:i,comparator:r}];return n.search({conditions:o,allowFullScan:!0,limit:t.limit,offset:t.offset,reverse:t.reverse,select:tS(t,n)})}async getDataByValue(t,r){let s=new Map,n=sn(t);t.get_attributes&&!t.get_attributes.includes(n.primaryKey)&&t.get_attributes[0]!=="*"&&t.get_attributes.push(n.primaryKey);for await(let i of this.searchByValue(t,r))s.set(i[n.primaryKey],i);return s}resetReadTxn(t,r){sn({schema:t,table:r})?.primaryStore.resetReadTxn()}async deleteAuditLogsBefore(t){return sn(t).deleteHistory(t.timestamp)}async readAuditLog(t){let r=sn(t),s={};switch(t.search_type){case Ps.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.HASH_VALUE:for(let i of t.search_values)s[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 s;case Ps.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.USERNAME:let n=t.search_values;for await(let i of CC(r))n.includes(i.user_name)&&(s[i.user_name]||(s[i.user_name]=[])).push(i);return s;default:return CC(r,t.search_values?.[0],t.search_values?.[1])}}};a(tS,"getSelect");a(IC,"getRecords");a(sn,"getTable");a(wC,"createDeleteResponse");a(CC,"groupRecordsInHistory")});var ws=g((pde,BC)=>{"use strict";var{ResourceBridge:qJ}=(vC(),ne(PC)),GJ=ee();GJ.initSync();var od;function FJ(){return od||(od=new qJ,od)}a(FJ,"getBridge");BC.exports=FJ()});var GC=g((Tde,qC)=>{"use strict";var HC=require("lodash"),Xc=require("mathjs"),kJ=require("jsonata"),xC=Q();qC.exports={distinct_array:e=>Array.isArray(e)&&e.length>1?HC.uniqWith(e,HC.isEqual):e,searchJSON:VJ,mad:jc.bind(null,Xc.mad),mean:jc.bind(null,Xc.mean),mode:jc.bind(null,Xc.mode),prod:jc.bind(null,Xc.prod),median:jc.bind(null,Xc.median)};function jc(e,t,r,s){return s===1?t==null?[]:[t]:s===2?(t!=null&&r.push(t),r):r!=null&&r.length>0?e(r):null}a(jc,"aggregateFunction");function VJ(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(xC.isEmpty(this.__ala__.res)&&(this.__ala__.res={}),xC.isEmpty(this.__ala__.res[r])){let s=kJ(e);this.__ala__.res[r]=s}return this.__ala__.res[r].evaluate(t)}a(VJ,"searchJSON")});var kC=g((Rde,FC)=>{"use strict";var mt=require("moment"),sS="YYYY-MM-DDTHH:mm:ss.SSSZZ";mt.suppressDeprecationWarnings=!0;FC.exports={current_date:()=>mt().utc().format("YYYY-MM-DD"),current_time:()=>mt().utc().format("HH:mm:ss.SSS"),extract:(e,t)=>{switch(t.toLowerCase()){case"year":return mt(e).utc().format("YYYY");case"month":return mt(e).utc().format("MM");case"day":return mt(e).utc().format("DD");case"hour":return mt(e).utc().format("HH");case"minute":return mt(e).utc().format("mm");case"second":return mt(e).utc().format("ss");case"millisecond":return mt(e).utc().format("SSS");default:break}},date:e=>mt(e).utc().format(sS),date_format:(e,t)=>mt(e).utc().format(t),date_add:(e,t,r)=>mt(e).utc().add(t,r).valueOf(),date_sub:(e,t,r)=>mt(e).utc().subtract(t,r).valueOf(),date_diff:(e,t,r)=>{let s=mt(e).utc(),n=mt(t).utc();return r?s.diff(n,r,!0):s.diff(n)},now:()=>mt().utc().valueOf(),get_server_time:()=>mt().format(sS),offset_utc:(e,t)=>mt(e).utc().utcOffset(t).format(sS)}});var KC=g((Ade,YC)=>{"use strict";var $J=require("@turf/area"),YJ=require("@turf/length"),KJ=require("@turf/circle"),WJ=require("@turf/difference"),QJ=require("@turf/distance"),zJ=require("@turf/boolean-contains"),JJ=require("@turf/boolean-equal"),XJ=require("@turf/boolean-disjoint"),jJ=require("@turf/helpers"),VC=M(),pe=Q(),yn=$();YC.exports={geoArea:ZJ,geoLength:e4,geoCircle:t4,geoDifference:r4,geoDistance:$C,geoNear:s4,geoContains:n4,geoEqual:i4,geoCrosses:o4,geoConvert:a4};function ZJ(e){if(pe.isEmpty(e))return NaN;typeof e=="string"&&(e=pe.autoCastJSON(e));try{return $J.default(e)}catch(t){return yn.trace(t,e),NaN}}a(ZJ,"geoArea");function e4(e,t){if(pe.isEmpty(e))return NaN;typeof e=="string"&&(e=pe.autoCastJSON(e));try{return YJ.default(e,{units:t||"kilometers"})}catch(r){return yn.trace(r,e),NaN}}a(e4,"geoLength");function t4(e,t,r){if(pe.isEmpty(e))return NaN;if(pe.isEmpty(t))return NaN;typeof e=="string"&&(e=pe.autoCastJSON(e));try{return KJ.default(e,t,{units:r||"kilometers"})}catch(s){return yn.trace(s,e,t),NaN}}a(t4,"geoCircle");function r4(e,t){if(pe.isEmpty(e))return NaN;if(pe.isEmpty(t))return NaN;typeof e=="string"&&(e=pe.autoCastJSON(e)),typeof t=="string"&&(t=pe.autoCastJSON(t));try{return WJ(e,t)}catch(r){return yn.trace(r,e,t),NaN}}a(r4,"geoDifference");function $C(e,t,r){if(pe.isEmpty(e))return NaN;if(pe.isEmpty(t))return NaN;typeof e=="string"&&(e=pe.autoCastJSON(e)),typeof t=="string"&&(t=pe.autoCastJSON(t));try{return QJ.default(e,t,{units:r||"kilometers"})}catch(s){return yn.trace(s,e,t),NaN}}a($C,"geoDistance");function s4(e,t,r,s){if(pe.isEmpty(e)||pe.isEmpty(t))return!1;if(pe.isEmpty(r))throw new Error("distance is required");if(typeof e=="string"&&(e=pe.autoCastJSON(e)),typeof t=="string"&&(t=pe.autoCastJSON(t)),isNaN(r))throw new Error("distance must be a number");try{return $C(e,t,s)<=r}catch(n){return yn.trace(n,e,t),!1}}a(s4,"geoNear");function n4(e,t){if(pe.isEmpty(e)||pe.isEmpty(t)||e.coordinates&&e.coordinates.includes?.(null)||t.coordinates&&t.coordinates.includes?.(null))return!1;typeof e=="string"&&(e=pe.autoCastJSON(e)),typeof t=="string"&&(t=pe.autoCastJSON(t));try{return zJ.default(e,t)}catch(r){return yn.trace(r,e,t),!1}}a(n4,"geoContains");function i4(e,t){if(pe.isEmpty(e)||pe.isEmpty(t)||e.coordinates&&e.coordinates.includes?.(null)||t.coordinates&&t.coordinates.includes?.(null))return!1;typeof e=="string"&&(e=pe.autoCastJSON(e)),typeof t=="string"&&(t=pe.autoCastJSON(t));try{return JJ.default(e,t)}catch(r){return yn.trace(r,e,t),!1}}a(i4,"geoEqual");function o4(e,t){if(pe.isEmpty(e)||pe.isEmpty(t)||e.coordinates&&e.coordinates.includes?.(null)||t.coordinates&&t.coordinates.includes?.(null))return!1;typeof e=="string"&&(e=pe.autoCastJSON(e)),typeof t=="string"&&(t=pe.autoCastJSON(t));try{return!XJ.default(e,t)}catch(r){return yn.trace(r,e,t),!1}}a(o4,"geoCrosses");function a4(e,t,r){if(pe.isEmptyOrZeroLength(e))throw new Error("coordinates is required");if(pe.isEmpty(t))throw new Error("geo_type is required");if(pe.isEmpty(VC.GEO_CONVERSION_ENUM[t]))throw new Error(`geo_type of ${t} is invalid please use one of the following types: ${Object.keys(VC.GEO_CONVERSION_ENUM).join(",")}`);return typeof e=="string"&&(e=pe.autoCastJSON(e)),jJ[t](e,r)}a(a4,"geoConvert")});var ad=g((bde,WC)=>{var so=GC(),Gr=kC(),nn=KC();WC.exports=e=>{e.aggr.mad=e.aggr.MAD=so.mad,e.aggr.mean=e.aggr.MEAN=so.mean,e.aggr.mode=e.aggr.MODE=so.mode,e.aggr.prod=e.aggr.PROD=so.prod,e.aggr.median=e.aggr.MEDIAN=so.median,e.fn.distinct_array=e.fn.DISTINCT_ARRAY=so.distinct_array,e.fn.search_json=e.fn.SEARCH_JSON=so.searchJSON,e.fn.__ala__=e,e.fn.current_date=e.fn.CURRENT_DATE=Gr.current_date,e.fn.current_time=e.fn.CURRENT_TIME=Gr.current_time,e.fn.extract=e.fn.EXTRACT=Gr.extract,e.fn.date=e.fn.DATE=Gr.date,e.fn.date_format=e.fn.DATE_FORMAT=Gr.date_format,e.fn.date_add=e.fn.DATE_ADD=Gr.date_add,e.fn.date_sub=e.fn.DATE_SUB=Gr.date_sub,e.fn.date_diff=e.fn.DATE_DIFF=e.fn.datediff=e.fn.DATEDIFF=Gr.date_diff,e.fn.now=e.fn.NOW=Gr.now,e.fn.offset_utc=e.fn.OFFSET_UTC=Gr.offset_utc,e.fn.get_server_time=e.fn.GET_SERVER_TIME=Gr.get_server_time,e.fn.getdate=e.fn.GETDATE=Gr.now,e.fn.current_timestamp=e.fn.CURRENT_TIMESTAMP=Gr.now,e.fn.geoarea=e.fn.GEOAREA=e.fn.geoArea=nn.geoArea,e.fn.geocircle=e.fn.GEOCIRCLE=e.fn.geoCircle=nn.geoCircle,e.fn.geocontains=e.fn.GEOCONTAINS=e.fn.geoContains=nn.geoContains,e.fn.geoconvert=e.fn.GEOCONVERT=e.fn.geoConvert=nn.geoConvert,e.fn.geocrosses=e.fn.GEOCROSSES=e.fn.geoCrosses=nn.geoCrosses,e.fn.geodifference=e.fn.GEODIFFERENCE=e.fn.geoDifference=nn.geoDifference,e.fn.geodistance=e.fn.GEODISTANCE=e.fn.geoDistance=nn.geoDistance,e.fn.geoequal=e.fn.GEOEQUAL=e.fn.geoEqual=nn.geoEqual,e.fn.geolength=e.fn.GEOLENGTH=e.fn.geoLength=nn.geoLength,e.fn.geonear=e.fn.GEONEAR=e.fn.geoNear=nn.geoNear}});var XC=g((Nde,JC)=>{"use strict";var Zc=require("lodash"),_r=require("alasql");_r.options.cache=!1;var c4=ad(),QC=require("clone"),cd=require("recursive-iterator"),le=$(),Ce=Q(),ia=ws(),u4=M(),{hdb_errors:l4}=se(),{getDatabases:zC}=(Ae(),ne(Ge)),_4="IS NULL",vs="There was a problem performing this search. Please check the logs and try again.";c4(_r);var nS=class{static{a(this,"SQLSearch")}constructor(t,r){if(Ce.isEmpty(t))throw le.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 s=await this._checkEmptySQL();if(!Ce.isEmptyOrZeroLength(s))return le.trace("No results returned from checkEmptySQL SQLSearch method."),s}catch(s){throw le.error("Error thrown from checkEmptySQL in SQLSearch class method search."),le.error(s),new Error(vs)}try{let s=await this._getFetchAttributeValues();if(s)return s}catch(s){throw le.error("Error thrown from getFetchAttributeValues in SQLSearch class method search."),le.error(s),new Error(vs)}if(Object.keys(this.data).length===0)return le.trace('SQLSearch class field: "data" is empty.'),[];let r;try{r=await this._processJoins()}catch(s){throw le.error("Error thrown from processJoins in SQLSearch class method search."),le.error(s),new Error(vs)}try{await this._getFinalAttributeData(r.existing_attributes,r.joined_length)}catch(s){throw le.error("Error thrown from getFinalAttributeData in SQLSearch class method search."),le.error(s),new Error(vs)}try{return t=await this._finalSQL(),t}catch(s){throw le.error("Error thrown from finalSQL in SQLSearch class method search."),le.error(s),new Error(vs)}}_getColumns(){let t=new cd(this.statement);for(let{node:r,path:s}of t)r&&r.columnid&&(this.columns[s[0]]||(this.columns[s[0]]=[]),this.columns[s[0]].push(QC(r)))}_getTables(){let t=[];this.all_table_attributes.forEach(r=>{t.push(r.table)}),this.tables=Zc.uniqBy(t,r=>[r.databaseid,r.tableid,r.as].join()),this.tables.forEach(r=>{let s=`${r.databaseid}_${r.as?r.as:r.tableid}`;this.data[s]={},this.data[s].__hash_name=zC()[r.databaseid][r.tableid].primaryKey,this.data[s].__merged_data={},this.data[s].__merged_attributes=[],this.data[s].__merged_attr_map={}})}_conditionsToFetchAttributeValues(){if(Ce.isEmpty(this.statement.where)){le.trace('AST "where" statement is empty.');return}let t=!1;for(let{node:r}of new cd(this.statement.where))if(r&&r.op&&r.op==="OR"&&(t=!0),!Ce.isEmpty(r)&&r.right)if(Ce.isNotEmptyAndHasValue(r.right.value)){let s=Ce.autoCast(r.right.value);[!0,!1].indexOf(s)>=0&&(r.right=new _r.yy.LogicValue({value:s}))}else Array.isArray(r.right)&&r.right.forEach((s,n)=>{let i=Ce.autoCast(s.value);[!0,!1].indexOf(i)>=0?r.right[n]=new _r.yy.LogicValue({value:i}):s instanceof _r.yy.StringValue&&Ce.autoCasterIsNumberCheck(i.toString())&&(r.right[n]=new _r.yy.NumValue({value:i}))});if(t){le.trace('Where clause contains "OR", exact match search not performed on attributes.');return}for(let{node:r}of new cd(this.statement.where))if(r&&r.left&&r.right&&(r.left.columnid||r.right.value)&&r.op){let s=new Set,n=r.left.columnid?r.left:r.right,i=this._findColumn(n);if(!i)continue;let o=[i.table.databaseid,i.table.tableid,i.attribute].join("/");if(!Ce.isEmpty(u4.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)?s.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)s.add(u[_].value);else{c=!0;break}break;default:c=!0;break}this.exact_search_values[o].ignore=c,c?this.exact_search_values[o].values=new Set:this.exact_search_values[o].values=new Set([...this.exact_search_values[o].values,...s])}}}_setAliasesForColumns(){if(Ce.isEmptyOrZeroLength(this.all_table_attributes)&&Ce.isEmptyOrZeroLength(this.statement.from)&&Ce.isEmptyOrZeroLength(this.columns.columns))return;let t=[],r={};this.statement.columns.forEach((s,n)=>{if(s.columnid==="*"){t.push(n);return}if(s.aggregatorid&&(this.has_aggregator=!0),!s.aggregatorid&&!s.funcid)if(s.as_orig=s.as?s.as:s.columnid,this.statement.joins)if(r[s.as_orig]>=0){let i=r[s.as_orig]+1;s.as=`[${s.as_orig+i}]`,r[s.as_orig]=i}else s.as=`[${s.as_orig}]`,r[s.as_orig]=0;else s.as=`[${s.as_orig}]`;!s.aggregatorid&&s.funcid&&s.args&&(s.as_orig=s.as?s.as:s.toString().replace(/'/g,'"'),s.as=`[${s.as_orig}]`),s.aggregatorid&&s.expression.columnid!=="*"&&(s.as_orig=s.as?s.as:s.expression.tableid?`${s.aggregatorid}(${s.expression.tableid}.${s.expression.columnid})`:`${s.aggregatorid}(${s.expression.columnid})`,s.as=`[${s.as_orig}]`)}),this.statement.columns.length>1&&t.length>0&&Zc.pullAt(this.statement.columns,t)}_findColumn(t){let r=this.all_table_attributes.filter(s=>{if(t.columnid_orig&&t.tableid_orig)return(s.table.as===t.tableid_orig||s.table.tableid===t.tableid_orig)&&s.attribute===t.columnid_orig;if(t.tableid)return(s.table.as===t.tableid||s.table.tableid===t.tableid)&&s.attribute===t.columnid;let n=t.columnid_orig?t.columnid_orig:t.columnid;return s.attribute===n});if(Ce.isEmptyOrZeroLength(r)){let s=this.columns.columns.filter(n=>n.as?t.columnid===n.as:!1);Ce.isEmptyOrZeroLength(s)||(r=this.all_table_attributes.filter(n=>n.attribute===s[0].columnid&&s[0].tableid&&s[0].tableid===(n.table.as?n.table.as:n.table.tableid)))}return r[0]}async _checkEmptySQL(){let t=[];if(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 _r.promise(r)}catch(r){throw le.error("Error thrown from AlaSQL in SQLSearch class method checkEmptySQL."),le.error(r),new Error("There was a problem with the SQL statement")}return t}_addFetchColumns(t){t&&t.length>0&&t.forEach(r=>{let s=this._findColumn(r);s&&this.fetch_attributes.push(QC(s))})}_addColumnToMergedAttributes(t,r){this.data[t].__merged_attributes.push(r),this.data[t].__merged_attr_map[r]=this.data[t].__merged_attributes.length-1}_setMergedHashAttribute(t,r){this.data[t].__merged_data[r].splice(0,1,r)}_updateMergedAttribute(t,r,s,n){let i=this.data[t].__merged_attr_map[s];this.data[t].__merged_data[r].splice(i,1,n)}async _getFetchAttributeValues(){if(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(_4)>-1&&this.tables.forEach(n=>{let i={columnid:zC()[n.databaseid][n.tableid].primaryKey,tableid:n.tableid};this._addFetchColumns([i])}),this.statement.order&&(this._updateOrderByToAliases(),this._addNonAggregatorsToFetchColumns()),this.fetch_attributes=Zc.uniqBy(this.fetch_attributes,n=>[n.table.databaseid,n.table.as?n.table.as:n.table.tableid,n.attribute].join()),r)return await this._simpleSQLQuery();let s=this.fetch_attributes.reduce((n,i)=>{let o=`${i.table.databaseid}_${i.table.as?i.table.as:i.table.tableid}`,c=this.data[o].__hash_name;return n[o]||(n[o]=[],n[o].push(null),this._addColumnToMergedAttributes(o,c)),i.attribute!==c&&(n[o].push(null),this._addColumnToMergedAttributes(o,i.attribute)),n},{});for(let n of this.fetch_attributes){let i=`${n.table.databaseid}_${n.table.as?n.table.as:n.table.tableid}`,o=this.data[i].__hash_name,c={schema:n.table.databaseid,table:n.table.tableid,get_attributes:[n.attribute]},u=!1,_=[n.table.databaseid,n.table.tableid,n.attribute].join("/");if(n.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 ia.getDataByHash(c);for(let d of c.hash_values)l.get(d)&&!this.data[i].__merged_data[d]&&(this.data[i].__merged_data[d]=[...s[i]],this._setMergedHashAttribute(i,d))}catch(l){throw le.error("Error thrown from getDataByHash function in SQLSearch class method getFetchAttributeValues exact match."),le.error(l),new Error(vs)}else try{c.search_attribute=n.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 ia.getDataByValue(d);for(let[E,h]of f)this.data[i].__merged_data[E]?this._updateMergedAttribute(i,E,n.attribute,h[n.attribute]):(this.data[i].__merged_data[E]=[...s[i]],this._updateMergedAttribute(i,E,n.attribute,h[n.attribute]),this._setMergedHashAttribute(i,E))}))}catch(l){throw le.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues exact match."),le.error(l),new Error(vs)}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 ia.getDataByValue(c,E.operation);if(u)for(let[p]of h)this.data[i].__merged_data[p]||(this.data[i].__merged_data[p]=[...s[i]],this._setMergedHashAttribute(i,p));else for(let[p,S]of h)this.data[i].__merged_data[p]?this._updateMergedAttribute(i,p,n.attribute,S[n.attribute]):(this.data[i].__merged_data[p]=[...s[i]],this._updateMergedAttribute(i,p,n.attribute,S[n.attribute]),this._setMergedHashAttribute(i,p))}}catch(l){throw le.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues comparator search values."),le.error(l),new Error(vs)}else try{c.search_attribute=n.attribute,c.search_value="*";let l=await ia.getDataByValue(c);if(u)for(let[d]of l)this.data[i].__merged_data[d]||(this.data[i].__merged_data[d]=[...s[i]],this._setMergedHashAttribute(i,d));else for(let[d,f]of l)this.data[i].__merged_data[d]?this._updateMergedAttribute(i,d,n.attribute,f[n.attribute]):(this.data[i].__merged_data[d]=[...s[i]],this._updateMergedAttribute(i,d,n.attribute,f[n.attribute]),this._setMergedHashAttribute(i,d))}catch(l){throw le.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues no comparator search values."),le.error(l),new Error(vs)}}}_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 _r.yy.Column||(t=!1)}),t)}_updateOrderByToAliases(){this.statement.order.forEach(t=>{if(t.expression.aggregatorid){t.is_aggregator=!0;return}if(t.expression.value){t.is_ordinal=!0,this.has_ordinal=!0;return}else t.is_ordinal=!1;let r=this.statement.columns.filter(n=>{let i=n.aggregatorid?n.expression:n,o=n.aggregatorid?n.as_orig:i.as_orig;return t.expression.tableid?i.columnid_orig===t.expression.columnid_orig&&i.tableid_orig===t.expression.tableid_orig:i.columnid_orig===t.expression.columnid_orig||t.expression.columnid_orig===o});r[0]||r.push(this._findColumn(t.expression));let s=r[0];if(t.is_func=!!s.funcid,t.is_aggregator=!!s.aggregatorid,s.as)if(s.as&&!t.expression.tableid)t.expression.columnid=s.as,t.expression.columnid_orig=s.as_orig;else{let n=new _r.yy.Column;n.columnid=s.as,n.columnid_orig=s.as_orig,t.expression=n}else{t.initial_select_column=Object.assign(new _r.yy.Column,t.expression),t.initial_select_column.as=`[${t.expression.columnid_orig}]`,t.expression.columnid=t.initial_select_column.as;return}if(!t.is_aggregator){let n=t.is_func?new _r.yy.FuncValue:new _r.yy.Column;t.initial_select_column=Object.assign(n,s)}})}_addNonAggregatorsToFetchColumns(){let r=this.statement.order.filter(s=>!s.is_aggregator&&!s.is_ordinal).map(s=>s.is_func?{columnid:s.initial_select_column.args.filter(i=>!!i.columnid_orig)[0].columnid_orig}:{columnid:s.expression.columnid_orig});this._addFetchColumns(r)}async _processJoins(){let t=[],r=[],s=this.statement.from[0],n=[s],i=["? "+(s.as?" AS "+s.as:s.tableid)];t.push(Object.values(this.data[`${s.databaseid_orig}_${s.as?s.as_orig:s.tableid_orig}`].__merged_data)),this.statement.joins&&this.statement.joins.forEach(E=>{E.joinmode&&E.joinmode!=="INNER"&&(this.has_outer_join=!0),n.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={};n.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,n);f=await _r.promise(h,t),t=null}catch(E){throw le.error("Error thrown from AlaSQL in SQLSearch class method processJoins."),le.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=Zc.difference(h,[...E.keys].map(S=>S.toString()));for(let S=0,T=p.length;S<T;S++){let b=p[S];delete this.data[`${E.schema}_${E.table}`].__merged_data[b]}})}return{existing_attributes:c,joined_length:f?f.length:0}}async _getFinalAttributeData(t,r){if(r===0)return;let s=[],n=new cd(this.columns);for(let{node:i}of n)if(i&&i.columnid){let o=this._findColumn(i);if(o){let c=o.table.as?o.table.as:o.table.tableid;(!t[c]||t[c].indexOf(o.attribute)<0)&&s.push(o)}}s=Zc.uniqBy(s,i=>[i.table.databaseid,i.table.as?i.table.as:i.table.tableid,i.attribute].join());try{await this._getData(s)}catch(i){throw le.error("Error thrown from getData in SQLSearch class method getFinalAttributeData."),le.error(i),new Error(vs)}}async _getData(t){try{let r=t.reduce((s,n)=>{let i=`${n.table.databaseid}_${n.table.as?n.table.as:n.table.tableid}`;return s[i]?s[i].columns.push(n.attribute):s[i]={schema:n.table.databaseid,table:n.table.tableid,columns:[n.attribute]},s},{});for(let s in r){let n=r[s],i=this.data[s].__merged_data,o=[];for(let l in i)o.push(i[l][0]);this.data[s].__merged_attributes.push(...n.columns);let c={schema:n.schema,table:n.table,hash_values:o,get_attributes:n.columns},u=await ia.getDataByHash(c),_=n.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=n.columns[h],S=E[p]===void 0?null:E[p];this.data[s].__merged_data[f].push(S)}}}}catch(r){throw le.error("Error thrown from getDataByHash function in SQLSearch class method getData."),le.error(r),r}}async _finalSQL(){let t=[],r=this.statement.from[0];t.push(Object.values(this.data[`${r.databaseid_orig}_${r.as?r.as_orig:r.tableid_orig}`].__merged_data)),r.as=r.as?r.as:r.tableid,r.databaseid="",r.tableid="?",this.statement.joins&&this.statement.joins.forEach(n=>{n.as=n.as?n.as:n.table.tableid,t.push(Object.values(this.data[`${n.table.databaseid_orig}_${n.table.as?n.table.as_orig:n.table.tableid_orig}`].__merged_data)),n.table.databaseid="",n.table.tableid="?"}),this.statement.order&&this.statement.order.forEach(n=>{if(n.is_ordinal)return;this.statement.columns.filter(o=>{let c=o.aggregatorid?o.expression:o,u=o.aggregatorid?o.as_orig:c.as_orig;return n.expression.tableid?c.columnid_orig===n.expression.columnid_orig&&c.tableid_orig===n.expression.tableid_orig:c.columnid_orig===n.expression.columnid_orig||n.expression.columnid_orig===u}).length===0&&(n.expression.columnid=n.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 s;try{let n=this._buildSQL();le.trace(`Final SQL: ${n}`),s=await _r.promise(n,t),this.has_outer_join&&(s=this._translateUndefinedValues(s)),le.trace(`Final AlaSQL results data included ${s.length} rows`)}catch(n){throw le.error("Error thrown from AlaSQL in SQLSearch class method finalSQL."),le.error(n),new Error("There was a problem running the generated sql.")}return s}_translateUndefinedValues(t){try{let r=[];for(let s of t){let n=Object.create(null);Object.keys(s).forEach(i=>{s[i]===void 0?n[i]=null:n[i]=s[i]}),r.push(n)}return r}catch(r){return le.error(l4.HDB_ERROR_MSGS.OUTER_JOIN_TRANSLATION_ERROR),le.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(s=>{if(s.funcid&&s.as){let n=s.toString().replace(" AS "+s.as,"");r=r.replace(s.toString(),n)}}),t===!0?this._convertColumnsToIndexes(r,this.tables):r}_convertColumnsToIndexes(t,r){let s=t,n={};r.forEach(i=>{i.databaseid_orig?n[`${i.databaseid_orig}_${i.as?i.as_orig:i.tableid_orig}`]=i.as?i.as:i.tableid:n[`${i.databaseid}_${i.as?i.as:i.tableid}`]=`\`${i.as?i.as:i.tableid}\``});for(let i in this.data)this.data[i].__merged_attributes.forEach((o,c)=>{let u=n[i],_=new RegExp(`${u}.\`${o}\``,"g"),l=`${u}.[${c}]`;s=s.replace(_,l)});for(let i in this.data)this.data[i].__merged_attributes.forEach((o,c)=>{let u=new RegExp(`\`${o}\``,"g"),_=`[${c}]`;s=s.replace(u,_)});return s}async _simpleSQLQuery(){let t=this.statement.columns.reduce((s,n)=>(n.as_orig&&n.as_orig!=n.columnid_orig?s[n.columnid_orig]=n.as_orig:s[n.columnid_orig]||(s[n.columnid_orig]=n.columnid_orig),s),{}),r=this.fetch_attributes.reduce((s,n)=>{let i=`${n.table.databaseid}_${n.table.as?n.table.as:n.table.tableid}`;return s[i]||(s[i]={}),s[i][t[n.attribute]]=null,s},{});for(let s of this.fetch_attributes){let n=`${s.table.databaseid}_${s.table.as?s.table.as:s.table.tableid}`,i={schema:s.table.databaseid,table:s.table.tableid,get_attributes:[s.attribute]};try{i.search_attribute=s.attribute,i.search_value="*";let o=await ia.getDataByValue(i);for(let[c,u]of o)this.data[n].__merged_data[c]||(u[s.attribute]===void 0&&(u[s.attribute]=null),this.data[n].__merged_data[c]=Object.assign({},r[n])),this.data[n].__merged_data[c][t[s.attribute]]=u[s.attribute]??null}catch(o){throw le.error("There was an error when processing this SQL operation. Check your logs"),le.error(o),new Error(vs)}}return Object.values(Object.values(this.data)[0].__merged_data)}};JC.exports=nS});var Mr=g((Ide,jC)=>{"use strict";var d4=Mb();jC.exports={searchByConditions:E4,searchByHash:h4,searchByValue:m4,search:p4};var iS=ws(),{transformReq:oS}=Q(),f4=XC();async function E4(e){return oS(e),iS.searchByConditions(e)}a(E4,"searchByConditions");async function h4(e){oS(e),e.ids&&(e.hash_values=e.ids);let t=[];for await(let r of iS.searchByHash(e))r&&t.push(r);return t}a(h4,"searchByHash");async function m4(e){oS(e),e.hasOwnProperty("desc")===!0&&(e.reverse=e.desc);let t=[];for await(let r of iS.searchByValue(e))t.push(r);return t}a(m4,"searchByValue");function p4(e,t){try{let r=new d4(e);r.validate(),new f4(r.statement,r.attributes).search().then(n=>{t(null,n)}).catch(n=>{t(n,null)})}catch(r){return t(r)}}a(p4,"search")});var ud=g((Cde,ZC)=>{"use strict";var S4=ws();ZC.exports={writeTransaction:T4};function T4(e,t,r){return S4.writeTransaction(e,t,r)}a(T4,"writeTransaction")});var sD=g((Mde,rD)=>{"use strict";var g4=Mr(),R4=An(),eD=$(),A4=Ur(),Lde=ud(),O4=require("clone"),cS=require("alasql"),b4=ad(),tD=require("util"),N4=tD.promisify(R4.getTableSchema),y4=tD.promisify(g4.search),I4=M(),aS=Q();b4(cS);rD.exports={update:C4};var w4="There was a problem performing this update. Please check the logs and try again.";async function C4({statement:e,hdb_user:t}){let r=await N4(e.table.databaseid,e.table.tableid),s=D4(e.columns);aS.backtickASTSchemaItems(e);let{table:n,where:i}=e,o=O4(n),c=aS.isEmpty(i)?"":` WHERE ${i.toString()}`,u=`SELECT ${r.hash_attribute} FROM ${n.toString()} ${c}`,_=cS.parse(u).statements[0],l=await y4(_),d=L4(s,l);return M4(o,d,t)}a(C4,"update");function D4(e){try{let t={};return e.forEach(r=>{"value"in r.expression?t[r.column.columnid]=r.expression.value??null:t[r.column.columnid]=cS.compile(`SELECT ${r.expression.toString()} AS [${I4.FUNC_VAL}] FROM ?`)}),t}catch(t){throw eD.error(t),new Error(w4)}}a(D4,"createUpdateRecord");function L4(e,t){return aS.isEmptyOrZeroLength(t)?[]:t.map(r=>Object.assign(r,e))}a(L4,"buildUpdateRecords");async function M4(e,t,r){let s={operation:"update",schema:e.databaseid_orig,table:e.tableid_orig,records:t,hdb_user:r},n=await A4.update(s);try{delete n.new_attributes,delete n.txn_time}catch(i){eD.error(`Error delete new_attributes from update response: ${i}`)}return n}a(M4,"updateRecords")});var iD=g((Bde,nD)=>{var U4=require("alasql"),P4=Mr(),v4=$(),B4=ws(),lS=require("util"),uS=Q(),H4=M(),x4=An(),Pde=ud(),vde=Ur(),q4="record",G4="successfully deleted",F4=lS.callbackify(Y4),k4=lS.promisify(P4.search),V4=lS.promisify(x4.getTableSchema);nD.exports={convertDelete:F4};function $4(e){return`${e.deleted_hashes.length} ${q4}${e.deleted_hashes.length===1?"":"s"} ${G4}`}a($4,"generateReturnMessage");async function Y4({statement:e,hdb_user:t}){let r=await V4(e.table.databaseid,e.table.tableid);uS.backtickASTSchemaItems(e);let{table:s,where:n}=e,i=uS.isEmpty(n)?"":` WHERE ${n.toString()}`,o=`SELECT ${r.hash_attribute} FROM ${s.toString()} ${i}`,c=U4.parse(o).statements[0],u={operation:H4.OPERATIONS_ENUM.DELETE,schema:s.databaseid_orig,table:s.tableid_orig,hdb_user:t};try{u.records=await k4(c);let _=await B4.deleteRecords(u);return uS.isEmptyOrZeroLength(_.message)&&(_.message=$4(_)),delete _.txn_time,_}catch(_){throw v4.error(_),_.hdb_code?_.message:_}}a(Y4,"convertDelete")});var lD=g((xde,uD)=>{"use strict";var K4=ti(),{hdb_errors:oD}=se(),{getDatabases:aD}=(Ae(),ne(Ge));uD.exports={checkSchemaExists:cD,checkSchemaTableExists:W4,schema_describe:K4};async function cD(e){if(!aD()[e])return oD.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}a(cD,"checkSchemaExists");async function W4(e,t){let r=await cD(e);if(r)return r;if(!aD()[e][t])return oD.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(W4,"checkSchemaTableExists")});var eu=g((Gde,Q4)=>{Q4.exports={name:"harperdb",version:"4.3.0-beta.14",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.7","nats-server":"2.10.11"},exports:{".":"./index.js"},homepage:"https://www.harperdb.io/",bugs:"support@harperdb.io",author:{name:"HarperDB",email:"support@harperdb.io"},license:"SEE LICENSE IN LICENSE",scripts:{submodules:"git submodule update --init --recursive",build:"eslint -c ./.eslintbuild bin/ dataLayer/ security/ server/ sqlTranslator/ upgrade/ utility/ validation/",pretty:"eslint --fix bin/ dataLayer/ security/ server/ sqlTranslator/ upgrade/ utility/ validation/","cover:test":"pm2 kill && rimraf ./.nyc_output/* && node utility/devops/register.js --reset_license && nyc --no-clean --reporter=lcovonly npm run test:apitests && nyc --no-clean --reporter=lcovonly npm run test:resources && nyc --no-clean --reporter=lcovonly npm run test:logging && nyc --no-clean --reporter=lcovonly npm run test:upgrade && nyc --no-clean --reporter=lcovonly npm run test:nats && nyc --no-clean --reporter=lcovonly npm run test:cfserver && nyc --no-clean --reporter=lcovonly npm run test:hdbserver && nyc --no-clean --reporter=lcovonly npm run test:bin && nyc --no-clean --reporter=lcovonly npm run test:main && nyc merge .nyc_output coverage.json && node ./utility/devops/register.js --reset_license",test:"pm2 kill && rimraf ./.nyc_output/* && node utility/devops/register.js --reset_license && npm run test:apitests && npm run test:resources && npm run test:logging && npm run test:upgrade && npm run test:nats && npm run test:cfserver && npm run test:hdbserver && npm run test:bin && npm run test:main && nyc merge .nyc_output coverage.json && node ./utility/devops/register.js --reset_license","test:resources":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/resources/**/*.js' --config '../unitTests/.mocharc.json'","test:bin":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/bin/**/*.js' --config '../unitTests/.mocharc.json'","test:main":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/**/*.js' --config '../unitTests/.mocharc-main.json'","test:lmdbbridge":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/dataLayer/harperBridge/lmdbBridge/**/*.js' --config '../unitTests/.mocharc.json'","test:lmdbutility":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/utility/lmdb/**/*.js' --config '../unitTests/.mocharc.json'","test:hdbserver":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/server/harperdb/hdbServer-test.js' --config '../unitTests/.mocharc.json'","test:cfserver":"npm run submodules && cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/server/fastifyRoutes/customFunctionsServer-test.js' --config '../unitTests/.mocharc.json'","test:nats":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/server/nats/**/*.js' --config '../unitTests/.mocharc.json'","test:upgrade":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/upgrade/**/*.js' --config '../unitTests/.mocharc.json'","test:apitests":"pm2 kill && cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/apiTests/**/*-test.mjs' --config '../unitTests/.mocharc.json'","test:logging":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/utility/logging/*.js' --config '../unitTests/.mocharc.json'","test:ci":" cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/**/*.js' --retries 3 --config '../unitTests/.mocharc-main.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/dataLayer/harperBridge/lmdbBridge/**/*.js' --parallel --retries 3 --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/utility/lmdb/**/*.js' --parallel --retries 3 --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/server/harperdb/hdbServer-test.js' --parallel --retries 3 --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/server/customFunctions/customFunctionsServer-test.js' --parallel --retries 3 --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/upgrade/**/*.js' --parallel --retries 3 --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/server/nats/**/*.js' --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter","hdb-check":"./utility/devops/hdb-check.sh","download-prebuilds":"node ./utility/devops/build/download-prebuilds.js",prebuild:"date",postinstall:"node ./launchServiceScripts/launchInstallNATSServer.js",build_nats_dependency:"node ./utility/devops/nats/builder.js",coverage:"nyc --reporter=lcov npm test"},dependencies:{"@aws-sdk/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:"3.0.0-beta.10",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.19.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"},alasql:{xlsx:"0.18.5"}},optionalDependencies:{bufferutil:"^4.0.7","utf-8-validate":"^5.0.10"}}});var iu={};Ye(iu,{addAnalyticsListener:()=>nu,recordAction:()=>Fr,recordActionBinary:()=>os,setAnalyticsEnabled:()=>z4});function z4(e){TD=e}function Fr(e,t,r,s,n){if(!TD)return;let i=t+(r?"-"+r:"");s!==void 0&&(i+="-"+s),n!==void 0&&(i+="-"+n);let o=dd.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:s,type:n},dd.set(i,o)}ld||J4()}function os(e,t,r,s,n){Fr(!!e,t,r,s,n)}function nu(e){AD.push(e)}function J4(){ld=performance.now(),setTimeout(async()=>{let e=performance.now()-ld;ld=0;let t=[],r={time:Date.now(),period:e,threadId:no.threadId,metrics:t};for(let[n,i]of dd){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 OD){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 bD()}let s=process.memoryUsage();t.push({metric:"memory",threadId:no.threadId,byThread:!0,...s});for(let n of AD)n(t);dd=new Map,no.parentPort?no.parentPort.postMessage({type:RD,report:r}):ID({report:r})},gD).unref()}async function X4(e,t=6e4){let r=fS(),s=ND(),n=new Promise(p=>{let S=performance.now();setImmediate(()=>{let T=performance.now();T-S>5e3&&(0,tu.warn)("Unusually high event queue latency on the main thread of "+Math.round(T-S)+"ms"),S=performance.now()}),s.primaryStore.prefetch([1],()=>{let T=performance.now();T-S>5e3&&(0,tu.warn)("Unusually high task queue latency on the main thread of "+Math.round(T-S)+"ms"),p(T-S)})}),i;for(let p of s.primaryStore.getRange({start:1/0,end:!1,reverse:!0}))if(p.value?.time){i=p.value.time;break}if(Date.now()-t<i)return;let o,c=new Map,u=new Map,_=[],l;for(let{key:p,value:S}of r.primaryStore.getRange({start:i||!1,exclusiveStart:!0,end:1/0})){if(!S)continue;if(o){if(p>o+t)break}else o=p;l=p;let{metrics:T,threadId:b}=S;for(let R of T||[]){let{path:L,method:H,type:P,metric:k,count:B,total:X,distribution:z,threads:J,...de}=R;B||(B=1);let ce=k+(L?"-"+L:"");H!==void 0&&(ce+="-"+H),P!==void 0&&(ce+="-"+P);let fe=c.get(ce);if(fe){if(fe.threads){let Be=fe.threads[b];if(Be)fe=Be;else{fe.threads[b]=Object.assign({},de);continue}}fe.count||(fe.count=1);let Le=fe.count;for(let Be in de){let Dt=de[Be];typeof Dt=="number"&&(fe[Be]=(fe[Be]*Le+Dt*B)/(Le+B))}fe.count+=B,X>=0&&(fe.total+=X,fe.ratio=fe.total/fe.count)}else fe=Object.assign({period:t},R),delete fe.distribution,c.set(ce,fe),fe.byThread&&(fe.threads=[],fe.threads[b]=Object.assign({},de),_.push(fe));if(z){z=z.map(Be=>typeof Be=="number"?{value:Be,count:1}:Be);let Le=u.get(ce);Le?Le.push(...z):u.set(ce,z)}}await bD()}for(let p of _){let{path:S,method:T,type:b,metric:R,count:L,total:H,distribution:P,threads:k,...B}=p;k=k.filter(X=>X);for(let X in B){if(typeof p[X]!="number")continue;let z=0;for(let J of k){let de=J[X];typeof de=="number"&&(z+=de)}p[X]=z}p.count=k.length,delete p.threads,delete p.byThread}for(let[p,S]of u){let T=c.get(p);S.sort((Be,Dt)=>Be.value>Dt.value?1:-1);let b=T.count-1,R=[],L=0,H=0,P;for(let Be of OD){let Dt=b*Be;for(;L<Dt;)P=S[H++],L+=P.count,H===1&&L--;let ql=S[H>1?H-2:0];P||(P=S[0]),R.push(P.value-(P.value-ql.value)*(L-Dt)/P.count)}let[k,B,X,z,J,de,ce,fe,Le]=R;Object.assign(T,{p1:k,p10:B,p25:X,median:z,p75:J,p90:de,p95:ce,p99:fe,p999:Le})}let d;for(let[p,S]of c)S.id=(0,_d.getNextMonotonicTime)(),S.time=l,s.primaryStore.put(S.id,S,{append:!0}).then(T=>{T||s.primaryStore.put(S.id,S)}),d=!0;let f=Date.now(),{idle:E,active:h}=performance.eventLoopUtilization();if(d||h*10>E){let p=(0,_d.getNextMonotonicTime)(),S={id:p,metric:"main-thread-utilization",idle:E-_D,active:h-dD,taskQueueLatency:await n,time:f,...process.memoryUsage()};s.primaryStore.put(p,S,{append:!0}).then(T=>{T||s.primaryStore.put(p,S)})}_D=E,dD=h}async function fD(e,t){let r=Date.now()-t;for(let s of e.primaryStore.getKeys({start:!1,end:r}))e.primaryStore.remove(s)}function fS(){return ED||(ED=ut({table:"hdb_raw_analytics",database:"system",audit:!1,trackDeletes:!1,attributes:[{name:"id",isPrimaryKey:!0},{name:"action"},{name:"metrics"}]}))}function ND(){return hD||(hD=ut({table:"hdb_analytics",database:"system",audit:!1,trackDeletes:!1,attributes:[{name:"id",isPrimaryKey:!0},{name:"metric"},{name:"path"},{name:"method"},{name:"type"}]}))}function e3(){yD=!0;let e=(0,su.get)(dS.CONFIG_PARAMS.ANALYTICS_AGGREGATEPERIOD)*1e3;e&&setInterval(async()=>{await X4(gD,e),await fD(fS(),j4),await fD(ND(),Z4)},Math.min(e/2,2147483647)).unref()}function ID(e,t){let r=e.report;r.threadId=t?.threadId||no.threadId;for(let s of r.metrics)s.metric==="bytes-sent"&&(mD+=s.mean*s.count);r.totalBytesProcessed=mD,t&&(r.metrics.push({metric:"utilization",...t.performance.eventLoopUtilization(pD.get(t))}),pD.set(t,t.performance.eventLoopUtilization())),r.id=(0,_d.getNextMonotonicTime)(),fS().primaryStore.put(r.id,r),yD||e3(),t3&&(wD=s3(r))}async function s3(e){if(await wD,!ui){let r=(0,ru.dirname)((0,tu.getLogFilePath)());try{ui=await(0,_S.open)((0,ru.join)(r,"analytics.log"),"r+")}catch{ui=await(0,_S.open)((0,ru.join)(r,"analytics.log"),"w+")}}let t=(await ui.stat()).size;if(t>r3){let r=Buffer.alloc(t);await ui.read(r,{position:0}),r=r.subarray(r.indexOf(10,r.length/2)+1),await ui.write(r,{position:0}),await ui.truncate(r.length),t=r.length}await ui.write(JSON.stringify(e)+`
|
|
8
|
-
`,t)}var
|
|
6
|
+
`)},kY="certificate.pem",VY="privateKey.pem",$Y="ca.pem";wN.exports={CERTIFICATE_VALUES:FY,CERTIFICATE_PEM_NAME:kY,PRIVATEKEY_PEM_NAME:VY,CA_PEM_NAME:$Y}});var tp=g((zue,PN)=>{"use strict";var UN=require("fs-extra"),oe=require("joi"),YY=require("os"),{boolean:be,string:zt,number:Ze,array:ep}=oe.types(),{totalmem:DN}=require("os"),Qi=require("path"),KY=$(),q_=Q(),Que=CN(),LN=L(),WY=Xe(),MN="log",QY="components",zY="Invalid logging.rotation.maxSize unit. Available units are G, M or K",JY="Invalid logging.rotation.interval unit. Available units are D, H or M (minutes)",XY="Invalid logging.rotation.maxSize value. Value should be a number followed by unit e.g. '10M'",jY="Invalid logging.rotation.interval value. Value should be a number followed by unit e.g. '10D'",ZY="rootPath config parameter is undefined",eK="clustering.enabled config parameter is undefined",zi=Ze.min(0).required(),F_=ep.items({host:zt.required(),port:zi}).empty(null),jn;PN.exports={configValidator:tK,routesValidator:aK,route_constraints:F_};function tK(e){if(jn=e.rootPath,q_.isEmpty(jn))throw ZY;let t=be.required(),r=Ze.min(0).max(1e3).empty(null).default(oK),n=zt.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path").empty(null).default(Gc),s=zt.optional().empty(null),i=zt.pattern(/^[^\s.,*>]+$/).messages({"string.pattern.base":"{:#label} invalid, must not contain ., * or >"}).empty(null).required(),o=oe.string().empty(null).default(Gc),c=oe.custom(nK).empty(null).default(Gc),u=e.clustering?.enabled;if(q_.isEmpty(u))throw eK;let _;return u===!0?_=oe.object({enabled:t,hubServer:oe.object({cluster:oe.object({name:oe.required().empty(null),network:oe.object({port:zi,routes:F_}).required()}).required(),leafNodes:oe.object({network:oe.object({port:zi}).required()}).required(),network:oe.object({port:zi}).required()}).required(),leafServer:oe.object({network:oe.object({port:zi,routes:F_}).required(),streams:oe.object({maxAge:Ze.min(120).allow(null).optional(),maxBytes:Ze.min(1).allow(null).optional(),maxMsgs:Ze.min(1).allow(null).optional(),path:o}).required()}).required(),logLevel:oe.valid("error","warn","info","debug","trace"),nodeName:i,republishMessages:be.optional(),databaseLevel:be.optional(),tls:oe.object({certificate:s,certificateAuthority:s,privateKey:s,insecure:be.required(),verify:be.optional()}),user:zt.optional().empty(null)}).required():_=oe.object({enabled:t,tls:oe.object({certificate:s,certificateAuthority:s,privateKey:s,insecure:be.required()})}).required(),oe.object({authentication:oe.object({authorizeLocal:be,cacheTTL:Ze.required(),enableSessions:be}),analytics:oe.object({aggregatePeriod:Ze}),componentsRoot:n.optional(),clustering:_,localStudio:oe.object({enabled:t}).required(),logging:oe.object({auditAuthEvents:oe.object({logFailed:be,logSuccessful:be}),file:be.required(),level:oe.valid("notify","fatal","error","warn","info","debug","trace"),rotation:oe.object({enabled:be.optional(),compress:be.optional(),interval:zt.custom(iK).optional().empty(null),maxSize:zt.custom(sK).optional().empty(null),path:zt.optional().empty(null).default(Gc)}).required(),root:n,stdStreams:be.required(),auditLog:be.required()}).required(),operationsApi:oe.object({network:oe.object({cors:be.optional(),corsAccessList:ep.optional(),headersTimeout:Ze.min(1).optional(),keepAliveTimeout:Ze.min(1).optional(),port:Ze.optional().empty(null),domainSocket:oe.optional().empty("hdb/operations-server").default(Gc),securePort:Ze.optional().empty(null),timeout:Ze.min(1).optional()}).optional(),tls:oe.object({certificate:s,certificateAuthority:s,privateKey:s})}).required(),rootPath:zt.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path").required(),mqtt:oe.object({network:oe.object({port:zi,securePort:zi,mtls:oe.alternatives([be.optional(),oe.object({user:zt.optional(),certificateAuthority:s,required:be.optional()})])}).required(),webSocket:be.optional(),requireAuthentication:be.optional()}),http:oe.object({compressionThreshold:Ze.optional(),cors:be.optional(),corsAccessList:ep.optional(),headersTimeout:Ze.min(1).optional(),port:Ze.min(0).optional().empty(null),securePort:Ze.min(0).optional().empty(null),maxHeaderSize:Ze.optional(),mtls:oe.alternatives([be.optional(),oe.object({user:zt.optional(),certificateAuthority:s,required:be.optional()})])}).required(),threads:oe.alternatives(r.optional(),oe.object({count:r.optional(),debug:oe.alternatives(be.optional(),oe.object({startingPort:Ze.min(1).optional(),host:zt.optional(),waitForDebugger:be.optional()})),maxHeapMemory:Ze.min(0).optional()})),storage:oe.object({writeAsync:be.required(),overlappingSync:be.optional(),caching:be.optional(),compression:oe.alternatives([be.optional(),oe.object({dictionary:zt.optional(),threshold:Ze.optional()})]),compactOnStart:be.optional(),compactOnStartKeepBackup:be.optional(),noReadAhead:be.optional(),path:c,prefetchWrites:be.optional(),maxFreeSpaceToLoad:Ze.optional(),maxFreeSpaceToRetain:Ze.optional()}).required(),ignoreScripts:be.optional(),tls:oe.object({certificate:s.optional(),certificateAuthority:s.optional(),privateKey:s.optional(),ciphers:zt.optional()})}).validate(e,{allowUnknown:!0,abortEarly:!1,errors:{wrap:{label:"'"}}})}a(tK,"configValidator");function rK(e){return UN.existsSync(e)?null:`Specified path ${e} does not exist.`}a(rK,"doesPathExist");function nK(e,t){oe.assert(e,zt.pattern(/^[\\\/]$|([\\\/][a-zA-Z_0-9\:-]+)+$/,"directory path"));let r=rK(e);if(r)return t.message(r)}a(nK,"validatePath");function sK(e,t){let r=e.slice(-1);if(r!=="G"&&r!=="M"&&r!=="K")return t.message(zY);let n=e.slice(0,-1);return isNaN(parseInt(n))?t.message(XY):e}a(sK,"validateRotationMaxSize");function iK(e,t){let r=e.slice(-1);if(r!=="D"&&r!=="H"&&r!=="M")return t.message(JY);let n=e.slice(0,-1);return isNaN(parseInt(n))?t.message(jY):e}a(iK,"validateRotationInterval");function oK(e,t){let r=t.state.path.join("."),n=YY.cpus().length,s=n-1;s<=2&&(s=2);let i=process.constrainedMemory?.()||DN();return i=Math.round(Math.min(i,DN())/1e6),s=Math.max(Math.min(s,Math.round((i-750)/300)),1),KY.info(`Detected ${n} cores and ${i}MB on this machine, defaulting ${r} to ${s}`),s}a(oK,"setDefaultThreads");function Gc(e,t){let r=t.state.path.join(".");if(!q_.isEmpty(t.original)&&r!=="operationsApi.network.domainSocket")return t.original;if(q_.isEmpty(jn))throw new Error(`Error setting default root for: ${r}. HDB root is not defined`);switch(r){case"componentsRoot":return Qi.join(jn,QY);case"logging.root":return Qi.join(jn,MN);case"clustering.leafServer.streams.path":return Qi.join(jn,"clustering","leaf");case"storage.path":let n=Qi.join(jn,LN.LEGACY_DATABASES_DIR_NAME);return UN.existsSync(n)?n:Qi.join(jn,LN.DATABASES_DIR_NAME);case"logging.rotation.path":return Qi.join(jn,MN);case"operationsApi.network.domainSocket":return r==null?null:Qi.join(jn,"operations-server");default:throw new Error(`Error setting default root for config parameter: ${r}. Unrecognized config parameter`)}}a(Gc,"setDefaultRoot");function aK(e){let t=oe.object({routes:F_});return WY.validateBySchema({routes:e},t)}a(aK,"routesValidator")});var lr=g((jue,VN)=>{"use strict";var Hr=L(),Ut=Q(),bt=$(),{configValidator:cK,routesValidator:vN}=tp(),ur=require("fs-extra"),uK=require("yaml"),Dn=require("path"),lK=require("is-number"),HN=require("properties-reader"),_K=require("lodash"),{handleHDBError:dK}=ne(),{HTTP_STATUS_CODES:fK,HDB_ERROR_MSGS:k_}=Cr(),Xue=require("minimist"),{server:EK}=(or(),ie(xi)),{DATABASES_PARAM_CONFIG:qc,CONFIG_PARAMS:Br,CONFIG_PARAM_MAP:Ln}=Hr,hK="Unable to get config value because config is uninitialized",mK="Config successfully initialized",pK="Error backing up config file",SK="Empty parameter sent to getConfigValue",xN=Dn.join(Hr.PACKAGE_ROOT,"config","yaml",Hr.HDB_DEFAULT_CONFIG_FILE),TK="Configuration successfully set. You must restart HarperDB for new config settings to take effect.",BN={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"},V_,yt,$_;VN.exports={createConfigFile:gK,getDefaultConfig:RK,getConfigValue:qN,initConfig:np,flattenConfig:Wo,updateConfigValue:FN,updateConfigObject:OK,getConfiguration:NK,setConfiguration:IK,readConfigFile:ip,getClusteringRoutes:wK,initOldConfig:kN,getConfigFromFile:CK,getConfigFilePath:Ji,addConfig:DK,deleteConfigFromFile:LK,getConfigObj:MK};function gK(e){let t=oi(xN);V_=Wo(t.toJSON());let r;for(let o in e){let c=Ln[o.toLowerCase()];if(c===Br.DATABASES){r=e[o];continue}if(!c&&o.endsWith("_package")&&(c=o),c!==void 0){let u=c.split("_"),_=rp(c,e[o]);c==="rootPath"&&_?.endsWith("/")&&(_=_.slice(0,-1));try{t.setIn([...u],_)}catch(l){bt.error(l)}}}r&&GN(t,r),sp(t);let n=t.toJSON();yt=Wo(n);let s=t.getIn(["rootPath"]),i=Dn.join(s,Hr.HDB_CONFIG_FILE);ur.createFileSync(i),ur.writeFileSync(i,String(t)),bt.trace(`Config file written to ${i}`)}a(gK,"createConfigFile");function GN(e,t){let r;try{try{r=JSON.parse(t)}catch(n){if(!Ut.isObject(t))throw n;r=t}for(let n of r){let s=Object.keys(n)[0];if(n[s].hasOwnProperty(qc.TABLES))for(let i in n[s][qc.TABLES])for(let o in n[s][qc.TABLES][i]){let c=n[s][qc.TABLES][i][o],u=[Br.DATABASES,s,qc.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=[Br.DATABASES,s,i];e.hasIn(c)?e.setIn(c,o):e.addIn(c,o)}}}catch(n){bt.error("Error parsing schemas CLI/env config arguments",n)}}a(GN,"setSchemasConfig");function RK(e){if(V_===void 0){let r=oi(xN);V_=Wo(r.toJSON())}let t=Ln[e.toLowerCase()];if(t!==void 0)return V_[t.toLowerCase()]}a(RK,"getDefaultConfig");function qN(e){if(e==null){bt.error(SK);return}if(yt===void 0){bt.trace(hK);return}let t=Ln[e.toLowerCase()];if(t!==void 0)return yt[t.toLowerCase()]}a(qN,"getConfigValue");function Ji(e=Ut.getPropsFilePath()){let t=Ut.getEnvCliRootPath();return t?Dn.join(t,Hr.HDB_CONFIG_FILE):HN(e).get(Hr.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY)}a(Ji,"getConfigFilePath");function np(e=!1){if(yt===void 0||e){let t;if(!Ut.noBootFile()){t=Ut.getPropsFilePath();try{ur.accessSync(t,ur.constants.F_OK|ur.constants.R_OK)}catch(i){throw bt.error(i),new Error(`HarperDB properties file at path ${t} does not exist`)}}let r=Ji(t),n;if(r.includes("config/settings.js"))try{kN(r);return}catch(i){if(i.code!==Hr.NODE_ERROR_CODES.ENOENT)throw i}try{n=oi(r)}catch(i){if(i.code===Hr.NODE_ERROR_CODES.ENOENT){bt.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 bt.error(i),new Error(`Error reading HarperDB config file at ${r}`)}AK(n,r),sp(n);let s=n.toJSON();if(EK.config=s,yt=Wo(s),yt.logging_rotation_rotate)for(let i in BN)yt[i]&&bt.error(`Config ${BN[i]} has been deprecated. Please check https://docs.harperdb.io/docs/ for further details.`);bt.trace(mK)}}a(np,"initConfig");function AK(e,t){let r=e.getIn(["rootPath"]),n=!1;e.hasIn(["storage","path"])||(e.setIn(["storage","path"],Dn.join(r,"database")),n=!0),e.hasIn(["clustering","leafServer","streams","path"])||(e.setIn(["clustering","leafServer","streams","path"],Dn.join(r,"clustering","leaf")),n=!0),e.hasIn(["logging","rotation","path"])||(e.setIn(["logging","rotation","path"],Dn.join(r,"log")),n=!0),e.hasIn(["clustering","tls","verify"])||(e.setIn(["clustering","tls","verify"],!0),n=!0),n&&(bt.trace("Updating config file with missing config params"),ur.writeFileSync(t,String(e)))}a(AK,"checkForUpdatedConfig");function sp(e){let t=e.toJSON();t.componentsRoot=t.componentsRoot??t?.customFunctions?.root,t?.http?.threads&&(t.threads=t?.http?.threads);let r=cK(t);if(r.error)throw k_.CONFIG_VALIDATION(r.error.message);typeof r.value.threads=="object"?e.setIn(["threads","count"],r.value.threads.count):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(sp,"validateConfig");function OK(e,t){yt===void 0&&(yt={});let r=Ln[e.toLowerCase()];if(r===void 0){bt.trace(`Unable to update config object because config param '${e}' does not exist`);return}yt[r.toLowerCase()]=t}a(OK,"updateConfigObject");function FN(e,t,r=void 0,n=!1,s=!1,i=!1){yt===void 0&&np();let o=qN(Ln.hdb_root),c=Dn.join(o,Hr.HDB_CONFIG_FILE),u=oi(c),_;if(r===void 0&&e.toLowerCase()===Br.DATABASES)_=t;else if(r===void 0){let f;if(i)f=e;else if(f=Ln[e.toLowerCase()],f===void 0)throw new Error(`Unable to update config, unrecognized config parameter: ${e}`);let E=f.split("_"),h=rp(f,t);u.setIn([...E],h)}else for(let f in r){let E=Ln[f.toLowerCase()];if(E===Br.HTTP_SECUREPORT&&r[f]===yt[Br.HTTP_PORT]?.toString()&&u.setIn(["http","port"],null),E===Br.OPERATIONSAPI_NETWORK_SECUREPORT&&r[f]===yt[Br.OPERATIONSAPI_NETWORK_PORT.toLowerCase()]?.toString()&&u.setIn(["operationsApi","network","port"],null),E===Br.DATABASES){_=r[f];continue}if(E?.startsWith("threads_")){let h=u.getIn(["threads"]);h>=0&&(u.deleteIn(["threads"]),u.setIn(["threads","count"],h))}if(!E&&f.endsWith("_package")&&(E=f),E!==void 0){let h=E.split("_"),p=Hr.LEGACY_CONFIG_PARAMS[f.toUpperCase()];p&&p.startsWith("customFunctions")&&u.hasIn(p.split("_"))&&(E=p,h=p.split("_"));let S=rp(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){bt.error(T)}}}_&&GN(u,_),sp(u);let l=u.getIn(["rootPath"]),d=Dn.join(l,Hr.HDB_CONFIG_FILE);n===!0&&bK(c,l),ur.writeFileSync(d,String(u)),s&&(yt=Wo(u.toJSON())),bt.trace(`Config parameter: ${e} updated with value: ${t}`)}a(FN,"updateConfigValue");function bK(e,t){try{let r=Dn.join(t,"backup",`${Hr.HDB_CONFIG_FILE}.bak`);ur.copySync(e,r),bt.trace(`Config file: ${e} backed up to: ${r}`)}catch(r){bt.error(pK),bt.error(r)}}a(bK,"backupConfigFile");var yK=["databases"];function Wo(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)),$_=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])&&!yK.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;!Br[u.toUpperCase()]&&Ln[u]&&(s[Ln[u].toLowerCase()]=o[c]),s[u]=o[c]}}n[i]!==void 0&&(s[i.toLowerCase()]=n[i])}return s}a(r,"squashObj")}a(Wo,"flattenConfig");function rp(e,t){if(e===Br.CLUSTERING_NODENAME||e===Br.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(lK(t))return parseFloat(t);if(t===!0||t===!1||Array.isArray(t)||Ut.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 Ut.autoCast(t)}a(rp,"castConfigValue");function NK(){let e=Ut.getPropsFilePath(),t=Ji(e);return oi(t).toJSON()}a(NK,"getConfiguration");async function IK(e){let{operation:t,hdb_user:r,hdb_auth_header:n,...s}=e;try{return FN(void 0,void 0,s,!0),TK}catch(i){throw typeof i=="string"||i instanceof String?dK(i,i,fK.BAD_REQUEST,void 0,void 0,!0):i}}a(IK,"setConfiguration");function ip(){let e=Ut.getPropsFilePath();try{ur.accessSync(e,ur.constants.F_OK|ur.constants.R_OK)}catch(n){if(!Ut.noBootFile())throw bt.error(n),new Error(`HarperDB properties file at path ${e} does not exist`)}let t=Ji(e);return oi(t).toJSON()}a(ip,"readConfigFile");function oi(e){return uK.parseDocument(ur.readFileSync(e,"utf8"),{simpleKeys:!0})}a(oi,"parseYamlDoc");function wK(){let e=ip(),t=e?.clustering?.hubServer?.cluster?.network?.routes;t=Ut.isEmptyOrZeroLength(t)?[]:t;let r=vN(t);if(r)throw k_.CONFIG_VALIDATION(r.message);let n=e?.clustering?.leafServer?.network?.routes;n=Ut.isEmptyOrZeroLength(n)?[]:n;let s=vN(n);if(s)throw k_.CONFIG_VALIDATION(s.message);if(!Ut.isEmptyOrZeroLength(n)&&!Ut.isEmptyOrZeroLength(t)){let i=t.filter(o=>n.some(c=>c.host===o.host&&c.port===o.port));if(!Ut.isEmptyOrZeroLength(i)){let o=`Duplicate hub and leaf routes found ${JSON.stringify(i)}`;throw k_.CONFIG_VALIDATION(o)}}return{hub_routes:t,leaf_routes:n}}a(wK,"getClusteringRoutes");function kN(e){let t=HN(e);yt={};for(let r in Ln){let n=t.get(r.toUpperCase());if(Ut.isEmpty(n)||typeof n=="string"&&n.trim().length===0)continue;let s=Ln[r].toLowerCase();s===Br.LOGGING_ROOT?yt[s]=Dn.dirname(n):yt[s]=n}return yt}a(kN,"initOldConfig");function CK(e){let t=ip();return _K.get(t,e.replaceAll("_","."))}a(CK,"getConfigFromFile");async function DK(e,t){let r=oi(Ji());r.hasIn([e])?r.setIn([e],t):r.addIn([e],t),await ur.writeFile(Ji(),String(r))}a(DK,"addConfig");function LK(e){let t=Ji(Ut.getPropsFilePath()),r=oi(t);r.deleteIn(e);let n=r.getIn(["rootPath"]),s=Dn.join(n,Hr.HDB_CONFIG_FILE);ur.writeFileSync(s,String(r))}a(LK,"deleteConfigFromFile");function MK(){return $_||(np(),$_)}a(MK,"getConfigObj")});var YN=g((ele,$N)=>{"use strict";var Y_=L(),K_=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}},op=class extends K_{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}};$N.exports={BaseLicense:K_,ExtendedLicense:op}});var Xi=g((rle,XN)=>{"use strict";var zo=require("fs-extra"),WN=G_(),QN=require("crypto"),UK=require("moment"),PK=require("uuid").v4,Jt=$(),cp=require("path"),vK=Q(),ai=L(),{totalmem:KN}=require("os"),BK=YN().ExtendedLicense,Qo="invalid license key format",HK="061183",xK="mofi25",GK="aes-256-cbc",qK=16,FK=32,zN=ee();zN.initSync();var ap;XN.exports={validateLicense:JN,generateFingerPrint:VK,licenseSearch:_p,getLicense:KK,checkMemoryLimit:WK};function up(){return cp.join(zN.getHdbBasePath(),ai.LICENSE_KEY_DIR_NAME,ai.LICENSE_FILE_NAME)}a(up,"getLicenseDirPath");function kK(){let e=up();return cp.join(e,ai.LICENSE_FILE_NAME)}a(kK,"getLicenseFilePath");function lp(){let e=up();return cp.join(e,ai.REG_KEY_FILE_NAME)}a(lp,"getFingerPrintFilePath");async function VK(){let e=lp();try{return await zo.readFile(e,"utf8")}catch(t){if(t.code==="ENOENT")return await $K();throw Jt.error(`Error writing fingerprint file to ${e}`),Jt.error(t),new Error("There was an error generating the fingerprint")}}a(VK,"generateFingerPrint");async function $K(){let e=PK(),t=WN.hash(e),r=lp();try{await zo.mkdirp(up()),await zo.writeFile(r,t)}catch(n){if(n.code==="EEXIST")return t;throw Jt.error(`Error writing fingerprint file to ${r}`),Jt.error(n),new Error("There was an error generating the fingerprint")}return t}a($K,"writeFingerprint");function JN(e,t){let r={valid_license:!1,valid_date:!1,valid_machine:!1,exp_date:null,ram_allocation:ai.RAM_ALLOCATION_ENUM.DEFAULT,version:ai.LICENSE_VALUES.VERSION_DEFAULT};if(!e)return Jt.error("empty license key passed to validate."),r;let n=lp(),s=!1;try{s=zo.statSync(n)}catch(i){Jt.error(i)}if(s){let i;try{i=zo.readFileSync(n,"utf8")}catch{Jt.error("error validating this machine in the license"),r.valid_machine=!1;return}let o=e.split(xK),c=o[1];c=Buffer.concat([Buffer.from(c)],qK);let u=Buffer.concat([Buffer.from(i)],FK),_=QN.createDecipheriv(GK,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=YK(o[0],i);if(E)l=E;else throw r.valid_license=!1,r.valid_machine=!1,console.error(Qo),Jt.error(Qo),new Error(Qo)}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(Qo),Jt.error(Qo),new Error(Qo)}else r.exp_date=l;r.exp_date<UK().valueOf()&&(r.valid_date=!1),WN.validate(o[1],`${HK}${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||Jt.error("Invalid licence"),r}a(JN,"validateLicense");function YK(e,t){try{let r=QN.createDecipher("aes192",t),n=r.update(e,"hex","utf8");return n.trim(),n+=r.final("utf8"),n}catch{Jt.warn("Check old license failed")}}a(YK,"checkOldLicense");function _p(){let e=new BK,t=[];try{t=zo.readFileSync(kK(),"utf-8").split(ai.NEW_LINE)}catch(r){r.code==="ENOENT"?Jt.info("no license file found"):Jt.error(`could not search for licenses due to: '${r.message}`)}for(let r=0;r<t.length;++r){let n=t[r];try{if(vK.isEmptyOrZeroLength(n))continue;let s=JSON.parse(n),i=JN(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){Jt.error("There was an error parsing the license string."),Jt.error(s),e.ram_allocation=ai.RAM_ALLOCATION_ENUM.DEFAULT,e.enterprise=!1}}return ap=e,e}a(_p,"licenseSearch");async function KK(){return ap||await _p(),ap}a(KK,"getLicense");function WK(){let e=_p().ram_allocation,t=process.constrainedMemory?.()||KN();if(t=Math.round(Math.min(t,KN())/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(WK,"checkMemoryLimit")});var an=g((ale,fI)=>{"use strict";var tI="username is required",rI="nothing to update, must supply active, role or password to update",nI="password cannot be an empty string",sI="If role is specified, it cannot be empty.",iI="active must be true or false";fI.exports={addUser:rW,alterUser:nW,dropUser:iW,getSuperUser:uW,userInfo:oW,listUsers:Q_,listUsersExternal:aW,setUsersToGlobal:Xo,findAndValidateUser:_I,getClusterUser:lW,USERNAME_REQUIRED:tI,ALTERUSER_NOTHING_TO_UPDATE:rI,EMPTY_PASSWORD:nI,EMPTY_ROLE:sI,ACTIVE_BOOLEAN:iI};var oI=vr(),QK=ii(),Ep=G_(),aI=yN(),cI=Pr(),hp=bs(),xr=Q(),uI=require("validate.js"),Ae=$(),{promisify:zK}=require("util"),mp=Rs(),jN=L(),ZN=ke(),JK=lr(),sle=ee(),ile=Xi(),XK=ki(),{table:ole}=(Re(),ie(Fe)),{handleHDBError:Zn,hdb_errors:jK}=ne(),{HTTP_STATUS_CODES:es,AUTHENTICATION_ERROR_MSGS:dp,HDB_ERROR_MSGS:Jo}=jK,{UserEventMsg:pp}=Mn(),fp=require("lodash"),{server:Sp}=(or(),ie(xi)),ZK=$();Sp.getUser=(e,t)=>_I(e,t,t!=null);var lI={username:!0,active:!0,role:!0,password:!0},eI=new Map,W_=cI.searchByValue,eW=cI.searchByHash,tW=zK(QK.delete);async function rW(e){let t=uI.cleanAttributes(e,lI),r=aI.addUserValidation(t);if(r)throw Zn(new Error,r.message,es.BAD_REQUEST,void 0,void 0,!0);let n={schema:"system",table:"hdb_role",search_attribute:"role",search_value:t.role,get_attributes:["id","permission","role"]},s;try{s=await W_(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 Zn(new Error,Jo.ROLE_NAME_NOT_FOUND(t.role),es.NOT_FOUND,void 0,void 0,!0);if(s.length>1)throw Zn(new Error,Jo.DUP_ROLES_FOUND(t.role),es.CONFLICT,void 0,void 0,!0);s[0].permission.cluster_user===!0&&(t.hash=mp.encrypt(t.password)),t.password=Ep.hash(t.password),t.role=s[0].id;let i={operation:"insert",schema:"system",table:"hdb_user",records:[t]},o;try{o=await oI.insert(i)}catch(u){throw Ae.error("There was an error searching for a user."),Ae.error(u),u}Ae.debug(o);try{await Xo()}catch(u){throw Ae.error("Got an error setting users to global"),Ae.error(u),u}if(o.skipped_hashes.length===1)throw Zn(new Error,Jo.USER_ALREADY_EXISTS(t.username),es.CONFLICT,void 0,void 0,!0);let c=Object.assign({},t);return c.role=s[0],hp.signalUserChange(new pp(process.pid)),`${c.username} successfully added`}a(rW,"addUser");async function nW(e){let t=uI.cleanAttributes(e,lI);if(xr.isEmptyOrZeroLength(t.username))throw new Error(tI);if(xr.isEmptyOrZeroLength(t.password)&&xr.isEmptyOrZeroLength(t.role)&&xr.isEmptyOrZeroLength(t.active))throw new Error(rI);if(!xr.isEmpty(t.password)&&xr.isEmptyOrZeroLength(t.password.trim()))throw new Error(nI);if(!xr.isEmpty(t.active)&&!xr.isBoolean(t.active))throw new Error(iI);let r=sW(t.username);if(!xr.isEmpty(t.password)&&!xr.isEmptyOrZeroLength(t.password.trim())&&(r&&(t.hash=mp.encrypt(t.password)),t.password=Ep.hash(t.password)),t.role==="")throw new Error(sI);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 W_(i)||[])}catch(c){throw Ae.error("Got an error searching for a role."),Ae.error(c),c}if(!o||o.length===0){let c=Jo.ALTER_USER_ROLE_NOT_FOUND(t.role);throw Ae.error(c),Zn(new Error,c,es.NOT_FOUND,void 0,void 0,!0)}if(o.length>1){let c=Jo.ALTER_USER_DUP_ROLES(t.role);throw Ae.error(c),Zn(new Error,c,es.CONFLICT,void 0,void 0,!0)}t.role=o[0].id}let n={operation:"update",schema:"system",table:"hdb_user",records:[t]},s;try{s=await oI.update(n)}catch(i){throw Ae.error("Error during update."),Ae.error(i),i}try{await Xo()}catch(i){throw Ae.error("Got an error setting users to global"),Ae.error(i),i}return hp.signalUserChange(new pp(process.pid)),s}a(nW,"alterUser");function sW(e){let t=!1,r=global.hdb_users.get(e);return r&&r.role.permission.cluster_user===!0&&(t=!0),t}a(sW,"isClusterUser");async function iW(e){try{let t=aI.dropUserValidation(e);if(t)throw new Error(t);let r={table:"hdb_user",schema:"system",hash_values:[e.username]};if(xr.isEmpty(global.hdb_users.get(e.username)))throw Zn(new Error,Jo.USER_NOT_EXIST(e.username),es.NOT_FOUND,void 0,void 0,!0);let n;try{n=await tW(r)}catch(s){throw Ae.error("Got an error deleting a user."),Ae.error(s),s}Ae.debug(n);try{await Xo()}catch(s){throw Ae.error("Got an error setting users to global."),Ae.error(s),s}return hp.signalUserChange(new pp(process.pid)),`${e.username} successfully deleted`}catch(t){throw t}}a(iW,"dropUser");async function oW(e){let t={};try{if(!e||!e.hdb_user)return"There was no user info in the body";t=fp.cloneDeep(e.hdb_user);let r={schema:"system",table:"hdb_role",hash_values:[t.role.id],get_attributes:["*"]},n;try{n=await eW(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(oW,"userInfo");async function aW(){let e;try{e=await Q_()}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(aW,"listUsersExternal");async function Q_(){try{let e={schema:"system",table:"hdb_role",search_value:"*",search_attribute:"role",get_attributes:["*"]},t;try{t=await W_(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]=fp.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 W_(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=fp.cloneDeep(o),o.role=r[o.role],cW(o.role),i.set(o.username,o);return i}catch(e){throw Ae.error("got an error listing users"),Ae.error(e),xr.errorizeMessage(e)}return null}a(Q_,"listUsers");function cW(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(XK)){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(cW,"appendSystemTablesToRole");async function Xo(){try{let e=await Q_();global.hdb_users=e}catch(e){throw Ae.error(e),e}}a(Xo,"setUsersToGlobal");async function _I(e,t,r=!0){global.hdb_users||await Xo();let n=global.hdb_users.get(e);if(!n){if(!r)return{username:e};throw Zn(new Error,dp.GENERIC_AUTH_FAIL,es.UNAUTHORIZED,void 0,void 0,!0)}if(n&&!n.active)throw Zn(new Error,dp.USER_INACTIVE,es.UNAUTHORIZED,void 0,void 0,!0);let s={active:n.active,username:n.username};if(n.refresh_token&&(s.refresh_token=n.refresh_token),n.role&&(s.role=n.role),r===!0){if(eI.get(t)===n.password)return s;if(Ep.validate(n.password,t))eI.set(t,n.password);else throw Zn(new Error,dp.GENERIC_AUTH_FAIL,es.UNAUTHORIZED,void 0,void 0,!0)}return s}a(_I,"findAndValidateUser");async function uW(){global.hdb_users||await Xo();for(let[,e]of global.hdb_users)if(e.role.role==="super_user")return e}a(uW,"getSuperUser");async function lW(){let e=await Q_(),t=JK.getConfigFromFile(jN.CONFIG_PARAMS.CLUSTERING_USER),r=e.get(t);if(!xr.isEmpty(r)&&r?.role?.role===jN.ROLE_TYPES_ENUM.CLUSTER_USER)return r.decrypt_hash=mp.decrypt(r.hash),r.uri_encoded_d_hash=encodeURIComponent(r.decrypt_hash),r.uri_encoded_name=encodeURIComponent(r.username),r.sys_name=r.username+ZN.SERVER_SUFFIX.ADMIN,r.sys_name_encoded=r.uri_encoded_name+ZN.SERVER_SUFFIX.ADMIN,r}a(lW,"getClusterUser");var dI=[];Sp.invalidateUser=function(e){for(let t of dI)try{t(e)}catch(r){ZK.error("Error invalidating user",r)}};Sp.onInvalidatedUser=function(e){dI.push(e)}});var kc=g((_le,pI)=>{"use strict";var ji=$(),Gr=L(),_W=Ky(),ule=Os(),lle=As(),dW=an(),{validateEvent:EI}=Mn(),Fc=Cn(),fW=require("process"),{resetDatabases:EW}=(Re(),ie(Fe)),hW={[Gr.ITC_EVENT_TYPES.SCHEMA]:mW,[Gr.ITC_EVENT_TYPES.USER]:mI};async function mW(e){let t=EI(e);if(t){ji.error(t);return}ji.trace("ITC schemaHandler received schema event:",e),await _W(e.message),await pW(e.message)}a(mW,"schemaHandler");async function pW(e){try{Fc.resetReadTxn(Gr.SYSTEM_SCHEMA_NAME,Gr.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME),Fc.resetReadTxn(Gr.SYSTEM_SCHEMA_NAME,Gr.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME),Fc.resetReadTxn(Gr.SYSTEM_SCHEMA_NAME,Gr.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME);let t=EW();e.table&&e.database&&await t[e.database][e.table].put(Symbol.for("write-verify"),null)}catch(t){ji.error(t)}}a(pW,"syncSchemaMetadata");var hI=[];async function mI(e){try{try{Fc.resetReadTxn(Gr.SYSTEM_SCHEMA_NAME,Gr.SYSTEM_TABLE_NAMES.USER_TABLE_NAME),Fc.resetReadTxn(Gr.SYSTEM_SCHEMA_NAME,Gr.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME)}catch(r){ji.warn(r)}let t=EI(e);if(t){ji.error(t);return}ji.trace(`ITC userHandler ${Gr.HDB_ITC_CLIENT_PREFIX}${fW.pid} received user event:`,e),await dW.setUsersToGlobal();for(let r of hI)r()}catch(t){ji.error(t)}}a(mI,"userHandler");mI.addListener=function(e){hI.push(e)};pI.exports=hW});var Mn=g((ple,TI)=>{"use strict";var fle=$(),Tp=Q(),SW=L(),{ITC_ERRORS:Vc}=Cr(),{parentPort:Ele,threadId:TW,isMainThread:gW,workerData:hle}=require("worker_threads"),{onMessageFromWorkers:RW,broadcast:mle,broadcastWithAcknowledgement:AW}=Ke();TI.exports={sendItcEvent:OW,validateEvent:SI,SchemaEventMsg:bW,UserEventMsg:yW};var z_;RW(async(e,t)=>{z_=z_||kc(),SI(e),z_[e.type]&&await z_[e.type](e),e.requestId&&t&&t.postMessage({type:"ack",id:e.requestId})});function OW(e){return!gW&&e.message&&(e.message.originator=TW),AW(e)}a(OW,"sendItcEvent");function SI(e){if(typeof e!="object")return Vc.INVALID_ITC_DATA_TYPE;if(!e.hasOwnProperty("type")||Tp.isEmpty(e.type))return Vc.MISSING_TYPE;if(!e.hasOwnProperty("message")||Tp.isEmpty(e.message))return Vc.MISSING_MSG;if(!e.message.hasOwnProperty("originator")||Tp.isEmpty(e.message.originator))return Vc.MISSING_ORIGIN;if(SW.ITC_EVENT_TYPES[e.type.toUpperCase()]===void 0)return Vc.INVALID_EVENT(e.type)}a(SI,"validateEvent");function bW(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(bW,"SchemaEventMsg");function yW(e){this.originator=e}a(yW,"UserEventMsg")});var bs=g((gle,OI)=>{"use strict";var gI=L(),Tle=Q(),J_=$(),RI=Vy(),jo,{sendItcEvent:AI}=Mn();function NW(e){try{J_.trace("signalSchemaChange called with message:",e),jo=jo||kc();let t=new RI(gI.ITC_EVENT_TYPES.SCHEMA,e);return jo.schema(t),AI(t)}catch(t){J_.error(t)}}a(NW,"signalSchemaChange");function IW(e){try{J_.trace("signalUserChange called with message:",e),jo=jo||kc();let t=new RI(gI.ITC_EVENT_TYPES.USER,e);return jo.user(t),AI(t)}catch(t){J_.error(t)}}a(IW,"signalUserChange");OI.exports={signalSchemaChange:NW,signalUserChange:IW}});var X_=g((Ale,yI)=>{"use strict";var bI=Q(),wW=L(),CW=$(),DW=y_(),LW=b_(),MW=bs(),{SchemaEventMsg:UW}=Mn(),PW="already exists in";yI.exports=vW;async function vW(e,t,r){if(bI.isEmptyOrZeroLength(r))return r;let n=[];bI.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 BW(e,t.schema,t.name,i)})),s}a(vW,"lmdbCheckForNewAttributes");async function BW(e,t,r,n){let s=new LW(t,r,n,void 0,!0);e&&(s.hdb_auth_header=e);try{await HW(s)}catch(i){if(typeof i=="object"&&i.message!==void 0&&i.message.includes(PW))CW.warn(`attribute ${t}.${r}.${n} already exists`);else throw i}}a(BW,"createNewAttribute");async function HW(e){let t;return t=await DW(e),MW.signalSchemaChange(new UW(process.pid,wW.OPERATIONS_ENUM.CREATE_ATTRIBUTE,e.schema,e.table,e.attribute)),t}a(HW,"createAttribute")});var Zo=g((ble,NI)=>{"use strict";var gp=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}};NI.exports=gp});var wI=g((Nle,II)=>{"use strict";var xW=Zo(),GW=L().OPERATIONS_ENUM,Rp=class extends xW{static{a(this,"LMDBInsertTransactionObject")}constructor(t,r,n,s,i=void 0){super(GW.INSERT,r,n,s,i),this.records=t}};II.exports=Rp});var DI=g((wle,CI)=>{"use strict";var qW=Zo(),FW=L().OPERATIONS_ENUM,Ap=class extends qW{static{a(this,"LMDBUpdateTransactionObject")}constructor(t,r,n,s,i,o=void 0){super(FW.UPDATE,n,s,i,o),this.records=t,this.original_records=r}};CI.exports=Ap});var MI=g((Dle,LI)=>{"use strict";var kW=Zo(),VW=L().OPERATIONS_ENUM,Op=class extends kW{static{a(this,"LMDBUpsertTransactionObject")}constructor(t,r,n,s,i,o=void 0){super(VW.UPSERT,n,s,i,o),this.records=t,this.original_records=r}};LI.exports=Op});var PI=g((Mle,UI)=>{"use strict";var $W=Zo(),YW=L().OPERATIONS_ENUM,bp=class extends $W{static{a(this,"LMDBDeleteTransactionObject")}constructor(t,r,n,s,i=void 0){super(YW.DELETE,n,s,t,i),this.original_records=r}};UI.exports=bp});var $c=g((vle,xI)=>{"use strict";var Ple=require("path"),vI=We(),KW=wI(),WW=DI(),QW=MI(),zW=PI(),ea=ut(),BI=Q(),{CONFIG_PARAMS:JW}=L(),HI=ee();HI.initSync();var j_=L().OPERATIONS_ENUM,{getTransactionAuditStorePath:XW}=Je();xI.exports=jW;async function jW(e,t){if(HI.get(JW.LOGGING_AUDITLOG)===!1)return;let r=XW(e.schema,e.table),n=await vI.openEnvironment(r,e.table,!0),s=ZW(e,t);if(!(s===void 0||s.hash_values.length===0)&&n!==void 0){vI.initializeDBIs(n,ea.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,ea.TRANSACTIONS_DBIS);let i=s.timestamp;return await n.dbis[ea.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP].ifNoExists(i,()=>{n.dbis[ea.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP].put(i,s),BI.isEmpty(s.user_name)||n.dbis[ea.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].put(s.user_name,i);for(let o=0;o<s.hash_values.length;o++)n.dbis[ea.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE].put(s.hash_values[o],i)})}}a(jW,"writeTransaction");function ZW(e,t){let r=BI.isEmpty(e.hdb_user)?void 0:e.hdb_user.username;if(e.operation===j_.INSERT)return new KW(e.records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===j_.UPDATE)return new WW(e.records,t.original_records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===j_.UPSERT)return new QW(e.records,t.original_records,r,t.txn_time,t.written_hashes,e.__origin);if(e.operation===j_.DELETE)return new zW(t.deleted,t.original_records,r,t.txn_time,e.__origin)}a(ZW,"createTransactionObject")});var yp=g((xle,GI)=>{"use strict";var eQ=vc(),Hle=Bc(),Yc=L(),tQ=Hc(),rQ=$o().insertRecords,nQ=We(),sQ=$(),iQ=X_(),{getSchemaPath:oQ}=Je(),aQ=$c();GI.exports=cQ;async function cQ(e){try{let{schema_table:t,attributes:r}=eQ(e);tQ(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 iQ(e.hdb_auth_header,t,r),s=oQ(e.schema,e.table),i=await nQ.openEnvironment(s,e.table),o=await rQ(i,t.hash_attribute,r,e.records,e.__origin?.timestamp);try{await aQ(e,o)}catch(c){sQ.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(cQ,"lmdbCreateRecords")});var kI=g((qle,FI)=>{"use strict";var qI=L(),uQ=yp(),lQ=Bc(),_Q=require("fs-extra"),{getSchemaPath:dQ}=Je();FI.exports=fQ;async function fQ(e){let t=[{name:e.schema,createddate:Date.now()}],r=new lQ(qI.SYSTEM_SCHEMA_NAME,qI.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,void 0,t);await uQ(r),await _Q.mkdirp(dQ(e.schema))}a(fQ,"lmdbCreateSchema")});var $I=g((kle,VI)=>{"use strict";var Np=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}};VI.exports=Np});var QI=g((Wle,WI)=>{"use strict";var YI=We(),Ip=Dr(),wp=Cr().LMDB_ERRORS_ENUM,EQ=ut(),KI=$(),$le=Q(),hQ=require("lmdb"),mQ=$I(),pQ=L(),{OVERFLOW_MARKER:Yle,MAX_SEARCH_KEY_LENGTH:Kle}=EQ,SQ=pQ.TIME_STAMP_NAMES_ENUM.UPDATED_TIME;async function TQ(e,t,r,n){if(Ip.validateEnv(e),t===void 0)throw new Error(wp.HASH_ATTRIBUTE_REQUIRED);if(!Array.isArray(r))throw r===void 0?new Error(wp.IDS_REQUIRED):new Error(wp.IDS_MUST_BE_ITERABLE);try{let s=YI.listDBIs(e);YI.initializeDBIs(e,t,s);let i=new mQ,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[SQ]>n){i.skipped.push(o);continue}let p=e.dbis[t].ifVersion(o,hQ.IF_EXISTS,()=>{e.dbis[t].remove(o);for(let S=0;S<s.length;S++){let T=s[S];if(!h.hasOwnProperty(T)||T===t)continue;let A=e.dbis[T],R=h[T];if(R!=null)try{let M=Ip.getIndexedValues(R);if(M)for(let x=0,P=M.length;x<P;x++)A.remove(M[x],o)}catch{KI.warn(`cannot delete from attribute: ${T}, ${R}:${o}`)}}});c.push(p),u.push(o),i.original_records.push(h)}catch(h){KI.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=Ip.getNextMonotonicTime(),i}catch(s){throw s}}a(TQ,"deleteRecords");WI.exports={deleteRecords:TQ}});var Kc=g((zle,JI)=>{"use strict";var ta=Q(),gQ=QI(),RQ=We(),{getSchemaPath:AQ}=Je(),OQ=$c(),bQ=$();JI.exports=yQ;async function yQ(e,t=!0){let n=global.hdb_schema[e.schema][e.table].hash_attribute;if(ta.isEmpty(n))throw new Error(`could not retrieve hash attribute for schema:${e.schema} and table ${e.table}`);try{if(ta.isEmptyOrZeroLength(e.hash_values)&&!ta.isEmptyOrZeroLength(e.records)){e.hash_values=[];for(let c=0;c<e.records.length;c++){let u=e.records[c][n];ta.isEmpty(u)||e.hash_values.push(u)}}if(ta.isEmptyOrZeroLength(e.hash_values))return zI([],[]);if(!Array.isArray(e.hash_values))throw new Error("hash_values must be an array");if(ta.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=AQ(e.schema,e.table),i=await RQ.openEnvironment(s,e.table),o=await gQ.deleteRecords(i,n,e.hash_values,e.__origin?.timestamp);try{t===!0&&await OQ(e,o)}catch(c){bQ.error(`unable to write transaction due to ${c.message}`)}return zI(o.deleted,o.skipped,o.txn_time)}catch(s){throw s}}a(yQ,"lmdbDeleteRecords");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}}a(zI,"createDeleteResponse")});var Dp=g((jle,XI)=>{"use strict";var NQ=L(),Xle=Dr();function Cp(e,t){let r=Object.create(null);if(t.length===1&&NQ.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(Cp,"parseRow");function IQ(e,t,r,n){let s=Cp(r,e);n.push(s)}a(IQ,"searchAll");function wQ(e,t,r,n){let s=Cp(r,e);n[t]=s}a(wQ,"searchAllToMap");function CQ(e,t,r){r[e]===void 0&&(r[e]=[]),r[e].push(t)}a(CQ,"iterateDBI");function Zi(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(Zi,"pushResults");function DQ(e,t,r,n,s,i){t.toString().endsWith(e)&&Zi(t,r,n,s,i)}a(DQ,"endsWith");function LQ(e,t,r,n,s,i){t.toString().includes(e)&&Zi(t,r,n,s,i)}a(LQ,"contains");function MQ(e,t,r,n,s,i){t>e&&Zi(t,r,n,s,i)}a(MQ,"greaterThanCompare");function UQ(e,t,r,n,s,i){t>=e&&Zi(t,r,n,s,i)}a(UQ,"greaterThanEqualCompare");function PQ(e,t,r,n,s,i){t<e&&Zi(t,r,n,s,i)}a(PQ,"lessThanCompare");function vQ(e,t,r,n,s,i){t<=e&&Zi(t,r,n,s,i)}a(vQ,"lessThanEqualCompare");XI.exports={parseRow:Cp,searchAll:IQ,searchAllToMap:wQ,iterateDBI:CQ,endsWith:DQ,contains:LQ,greaterThanCompare:MQ,greaterThanEqualCompare:UQ,lessThanCompare:PQ,lessThanEqualCompare:vQ,pushResults:Zi}});var ra=g((n_e,sw)=>{"use strict";var ci=We(),e_e=$(),qr=Dr(),Z_=ut(),_t=Cr().LMDB_ERRORS_ENUM,t_e=Q(),BQ=L(),ed=Dp(),{parseRow:HQ}=ed,r_e=require("lmdb"),{OVERFLOW_MARKER:jI,MAX_SEARCH_KEY_LENGTH:xQ}=Z_;function ZI(e,t,r,n=!1,s=void 0,i=void 0){return eo(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(ZI,"iterateFullIndex");function Wc(e,t,r,n,s,i=!1,o=void 0,c=void 0,u=!1,_=!1){return eo(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(R=>({value:R}))):d.getRange(A)})}a(Wc,"iterateRangeBetween");function eo(e,t,r,n){let s=e.database||e,i=ci.openDBI(s,r);i[Z_.DBI_DEFINITION_NAME].is_hash_attribute?t=r:t&&ci.openDBI(s,t);let o;e.database?o=e:(o=e.useReadTransaction(),o.database=e);let c=n(o,i,s,t);return c.transaction=o,e.database||(c.onDone=()=>{o.done()}),c}a(eo,"setupTransaction");function ew(e,t,r,n){let s;return function(i,o){if(typeof i=="string"&&i.endsWith(jI)){if(!s)if(r)s=ci.openDBI(e,r);else{let u=ci.listDBIs(e);for(let _=0,l=u.length;_<l&&(s=ci.openDBI(e,u[_]),!s[Z_.DBI_DEFINITION_NAME].is_hash_attribute);_++);}i=s.get(o,{transaction:t,lazy:!0})[n]}return i}}a(ew,"getOverflowCheck");function GQ(e,t,r,n=!1,s=void 0,i=void 0){if(qr.validateEnv(e),t===void 0)throw new Error(_t.HASH_ATTRIBUTE_REQUIRED);return eo(e,t,t,(o,c,u)=>(td(r),r=Qc(u,r),c.getRange({transaction:o,start:n?void 0:!1,end:n?!1:void 0,limit:s,offset:i,reverse:n}).map(_=>HQ(_.value,r))))}a(GQ,"searchAll");function qQ(e,t,r,n=!1,s=void 0,i=void 0){if(qr.validateEnv(e),t===void 0)throw new Error(_t.HASH_ATTRIBUTE_REQUIRED);td(r),r=Qc(e.database||e,r);let o=new Map;for(let{key:c,value:u}of ZI(e,t,t,n,s,i))o.set(c,ed.parseRow(u,r));return o}a(qQ,"searchAllToMap");function FQ(e,t,r=!1,n=void 0,s=void 0){if(qr.validateEnv(e),t===void 0)throw new Error(_t.ATTRIBUTE_REQUIRED);let i=Object.create(null),o=ZI(e,void 0,t,r,n,s),c=o.transaction,u=ew(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(FQ,"iterateDBI");function kQ(e,t){if(qr.validateEnv(e),t===void 0)throw new Error(_t.HASH_ATTRIBUTE_REQUIRED);return ci.statDBI(e,t).entryCount}a(kQ,"countAll");function VQ(e,t,r,n,s=!1,i=void 0,o=void 0){return ui(e,r,n),eo(e,t,r,(c,u,_,l)=>(n=qr.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(VQ,"equals");function $Q(e,t,r){return ui(e,t,r),ci.openDBI(e,t).getValuesCount(r)}a($Q,"count");function YQ(e,t,r,n,s=!1,i=void 0,o=void 0){return ui(e,r,n),eo(e,null,r,(c,u)=>{n=qr.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(YQ,"startsWith");function KQ(e,t,r,n,s=!1,i=void 0,o=void 0){return tw(e,t,r,n,s,i,o,!0)}a(KQ,"endsWith");function tw(e,t,r,n,s=!1,i=void 0,o=void 0,c=!1){return ui(e,r,n),eo(e,null,r,(u,_,l,d)=>{let f=ew(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(jI)?_.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))?_[Z_.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(tw,"contains");function WQ(e,t,r,n,s=!1,i=void 0,o=void 0){ui(e,r,n);let c=typeof n,u;return c==="string"?u="\uFFFF":c==="number"?u=1/0:c==="boolean"&&(u=!0),Wc(e,t,r,n,u,s,i,o,!0,!1)}a(WQ,"greaterThan");function QQ(e,t,r,n,s=!1,i=void 0,o=void 0){ui(e,r,n);let c=typeof n,u;return c==="string"?u="\uFFFF":c==="number"?u=1/0:c==="boolean"&&(u=!0),Wc(e,t,r,n,u,s,i,o,!1,!1)}a(QQ,"greaterThanEqual");function zQ(e,t,r,n,s=!1,i=void 0,o=void 0){ui(e,r,n);let c=typeof n,u;return c==="string"?u="\0":c==="number"?u=-1/0:c==="boolean"&&(u=!1),Wc(e,t,r,u,n,s,i,o,!1,!0)}a(zQ,"lessThan");function JQ(e,t,r,n,s=!1,i=void 0,o=void 0){ui(e,r,n);let c=typeof n,u;return c==="string"?u="\0":c==="number"?u=-1/0:c==="boolean"&&(u=!1),Wc(e,t,r,u,n,s,i,o,!1,!1)}a(JQ,"lessThanEqual");function XQ(e,t,r,n,s,i=!1,o=void 0,c=void 0){if(qr.validateEnv(e),r===void 0)throw new Error(_t.ATTRIBUTE_REQUIRED);if(n===void 0)throw new Error(_t.START_VALUE_REQUIRED);if(s===void 0)throw new Error(_t.END_VALUE_REQUIRED);if(n=qr.convertKeyValueToWrite(n),s=qr.convertKeyValueToWrite(s),n>s)throw new Error(_t.END_VALUE_MUST_BE_GREATER_THAN_START_VALUE);return Wc(e,t,r,n,s,i,o,c)}a(XQ,"between");function jQ(e,t,r,n){qr.validateEnv(e);let s=e.database||e,i=e.database?e:null;if(t===void 0)throw new Error(_t.HASH_ATTRIBUTE_REQUIRED);if(td(r),r=Qc(s,r),n===void 0)throw new Error(_t.ID_REQUIRED);let o=null,c=s.dbis[t].get(n,{transaction:i,lazy:r.length<3});return c&&(o=ed.parseRow(c,r)),o}a(jQ,"searchByHash");function ZQ(e,t,r){qr.validateEnv(e);let n=e.database||e,s=e.database?e:null;if(t===void 0)throw new Error(_t.HASH_ATTRIBUTE_REQUIRED);if(r===void 0)throw new Error(_t.ID_REQUIRED);let i=!0;return n.dbis[t].get(r,{transaction:s,lazy:!0})===void 0&&(i=!1),i}a(ZQ,"checkHashExists");function ez(e,t,r,n,s=[]){return nw(e,t,r,n,s),rw(e,t,r,n,s).map(i=>i[1])}a(ez,"batchSearchByHash");function tz(e,t,r,n,s=[]){nw(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(tz,"batchSearchByHashToMap");function rw(e,t,r,n,s=[]){return eo(e,t,t,(i,o,c)=>{r=Qc(c,r);let u=r.length<3;return n.map(_=>{let l=c.dbis[t].get(_,{transaction:i,lazy:u});if(l)return[_,ed.parseRow(l,r)];s.push(_)}).filter(_=>_)})}a(rw,"batchHashSearch");function nw(e,t,r,n,s){if(qr.validateEnv(e),t===void 0)throw new Error(_t.HASH_ATTRIBUTE_REQUIRED);if(td(r),n==null)throw new Error(_t.IDS_REQUIRED);if(!n[Symbol.iterator])throw new Error(_t.IDS_MUST_BE_ITERABLE)}a(nw,"initializeBatchSearchByHash");function td(e){if(!Array.isArray(e))throw e===void 0?new Error(_t.FETCH_ATTRIBUTES_REQUIRED):new Error(_t.FETCH_ATTRIBUTES_MUST_BE_ARRAY)}a(td,"validateFetchAttributes");function ui(e,t,r){if(qr.validateEnv(e),t===void 0)throw new Error(_t.ATTRIBUTE_REQUIRED);if(r===void 0)throw new Error(_t.SEARCH_VALUE_REQUIRED);if(r?.length>xQ)throw new Error(_t.SEARCH_VALUE_TOO_LARGE)}a(ui,"validateComparisonFunctions");function Qc(e,t){return t.length===1&&BQ.SEARCH_WILDCARDS.indexOf(t[0])>=0&&(t=ci.listDBIs(e)),t}a(Qc,"setGetWholeRowAttributes");sw.exports={searchAll:GQ,searchAllToMap:qQ,count:$Q,countAll:kQ,equals:VQ,startsWith:YQ,endsWith:KQ,contains:tw,searchByHash:jQ,setGetWholeRowAttributes:Qc,batchSearchByHash:ez,batchSearchByHashToMap:tz,checkHashExists:ZQ,iterateDBI:FQ,greaterThan:WQ,greaterThanEqual:QQ,lessThan:zQ,lessThanEqual:JQ,between:XQ}});var na=g((i_e,uw)=>{var iw=require("lodash"),ow=Xe(),fe=require("joi"),rz=Q(),{hdb_schema_table:zc,checkValidTable:aw,hdb_table:cw,hdb_database:rd}=Jn(),{handleHDBError:nz,hdb_errors:sz}=ne(),{getDatabases:iz}=(Re(),ie(Fe)),{HTTP_STATUS_CODES:oz}=sz,az=fe.object({database:rd,schema:rd,table:cw,search_attribute:zc,search_value:fe.any().required(),get_attributes:fe.array().min(1).items(fe.alternatives(zc,fe.object())).optional(),desc:fe.bool(),limit:fe.number().integer().min(1),offset:fe.number().integer().min(0)}),cz=fe.object({database:rd,schema:rd,table:cw,operator:fe.string().valid("and","or").default("and").lowercase(),offset:fe.number().integer().min(0),limit:fe.number().integer().min(1),get_attributes:fe.array().min(1).items(fe.alternatives(zc,fe.object())).optional(),sort:fe.object({attribute:fe.alternatives(zc,fe.array().min(1)),descending:fe.bool().optional()}).optional(),conditions:fe.array().min(1).items(fe.alternatives(fe.object({operator:fe.string().valid("and","or").default("and").lowercase(),conditions:fe.array()}),fe.object({search_attribute:fe.alternatives(zc,fe.array().min(1)),search_type:fe.string().valid("equals","contains","starts_with","ends_with","greater_than","greater_than_equal","less_than","less_than_equal","between","not_equal").optional(),search_value:fe.when("search_type",{switch:[{is:"equals",then:fe.any()},{is:"between",then:fe.array().items(fe.alternatives([fe.string(),fe.number()])).length(2)}],otherwise:fe.alternatives(fe.string(),fe.number())}).required()}))).required()});uw.exports=function(e,t){let r=null;switch(t){case"value":r=ow.validateBySchema(e,az);break;case"hashes":let i=function(o){s?s+=". "+o:s=o};var n=i;a(i,"addError");let s;i(aw("database",e.schema)),i(aw("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=ow.validateBySchema(e,cz);break;default:throw new Error(`Error validating search, unknown type: ${t}`)}if(!r&&e.schema!=="system"){let s=rz.checkGlobalSchemaTable(e.schema,e.table);if(s)return nz(new Error,s,oz.NOT_FOUND);let o=iz()[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 _=iw.filter(c,l=>l!=="*"&&l.attribute!=="*"&&!Array.isArray(l)&&!l.name&&!iw.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 Lp=g((a_e,lw)=>{"use strict";var uz=We(),lz=na(),{getSchemaPath:_z}=Je();lw.exports=dz;function dz(e){let t=lz(e,"hashes");if(t)throw t;let r=_z(e.schema,e.table);return uz.openEnvironment(r,e.table)}a(dz,"initialize")});var Mp=g((u_e,_w)=>{"use strict";var fz=ra(),Ez=Lp();_w.exports=hz;async function hz(e){let t=await Ez(e),r=t.useReadTransaction();r.database=t;let n=global.hdb_schema[e.schema][e.table];try{return fz.batchSearchByHashToMap(r,n.hash_attribute,e.get_attributes,e.hash_values)}finally{r.done()}}a(hz,"lmdbGetDataByHash")});var sa=g((__e,dw)=>{"use strict";var Up=class{static{a(this,"SearchByHashObject")}constructor(t,r,n,s){this.schema=t,this.table=r,this.hash_values=n,this.get_attributes=s}};dw.exports=Up});var Ew=g((E_e,fw)=>{"use strict";var f_e=sa(),mz=ra(),pz=Lp();fw.exports=Sz;async function Sz(e){let t=await pz(e),r=global.hdb_schema[e.schema][e.table];return mz.batchSearchByHash(t,r.hash_attribute,e.get_attributes,e.hash_values)}a(Sz,"lmdbSearchByHash")});var ts=g((m_e,hw)=>{"use strict";var Pp=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}};hw.exports=Pp});var nd=g((S_e,Rw)=>{"use strict";var Xt=ra(),Tz=We(),gz=Q(),Ee=ut(),to=L(),Rz=ki(),mw=Cr().LMDB_ERRORS_ENUM,{getSchemaPath:Az}=Je(),ys=to.SEARCH_WILDCARDS;async function Oz(e,t,r){let n;e.schema===to.SYSTEM_SCHEMA_NAME?n=Rz[e.table]:n=global.hdb_schema[e.schema][e.table];let s=gw(e,n.hash_attribute,r,t);return Sw(e,s,n.hash_attribute,r)}a(Oz,"prepSearch");async function Sw(e,t,r,n){let s=Az(e.schema,e.table),i=await Tz.openEnvironment(s,e.table),o=Tw(i,e,t,r),c=o.transaction||i;if([Ee.SEARCH_TYPES.BATCH_SEARCH_BY_HASH,Ee.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP,Ee.SEARCH_TYPES.SEARCH_ALL,Ee.SEARCH_TYPES.SEARCH_ALL_TO_MAP].indexOf(t)>=0)return o;if(bz(e,r)===!1){let l=e.search_attribute;if(l===r)return n?pw(o,()=>!0):o.map(f=>({[r]:f.key}));let d=a(f=>({[r]:f.value,[l]:f.key}),"toObject");return n?pw(o,d):o.map(d)}let _=e.search_attribute===r?o.map(l=>l.key):o.map(l=>l.value);return n===!0?Xt.batchSearchByHashToMap(c,r,e.get_attributes,_):Xt.batchSearchByHash(c,r,e.get_attributes,_)}a(Sw,"executeSearch");function Tw(e,t,r,n){let s,i=n;t.get_attributes.indexOf(n)<0&&(i=void 0);let{reverse:o,limit:c,offset:u}=t;switch(o=typeof o=="boolean"?o:!1,c=Number.isInteger(c)?c:void 0,u=Number.isInteger(u)?u:void 0,r){case Ee.SEARCH_TYPES.EQUALS:s=Xt.equals(e,i,t.search_attribute,t.search_value,o,c,u);break;case Ee.SEARCH_TYPES.CONTAINS:s=Xt.contains(e,i,t.search_attribute,t.search_value,o,c,u);break;case Ee.SEARCH_TYPES.ENDS_WITH:case Ee.SEARCH_TYPES._ENDS_WITH:s=Xt.endsWith(e,i,t.search_attribute,t.search_value,o,c,u);break;case Ee.SEARCH_TYPES.STARTS_WITH:case Ee.SEARCH_TYPES._STARTS_WITH:s=Xt.startsWith(e,i,t.search_attribute,t.search_value,o,c,u);break;case Ee.SEARCH_TYPES.BATCH_SEARCH_BY_HASH:return Xt.batchSearchByHash(e,t.search_attribute,t.get_attributes,[t.search_value]);case Ee.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP:return Xt.batchSearchByHashToMap(e,t.search_attribute,t.get_attributes,[t.search_value]);case Ee.SEARCH_TYPES.SEARCH_ALL:return Xt.searchAll(e,n,t.get_attributes,o,c,u);case Ee.SEARCH_TYPES.SEARCH_ALL_TO_MAP:return Xt.searchAllToMap(e,n,t.get_attributes,o,c,u);case Ee.SEARCH_TYPES.BETWEEN:s=Xt.between(e,i,t.search_attribute,t.search_value,t.end_value,o,c,u);break;case Ee.SEARCH_TYPES.GREATER_THAN:case Ee.SEARCH_TYPES._GREATER_THAN:s=Xt.greaterThan(e,i,t.search_attribute,t.search_value,o,c,u);break;case Ee.SEARCH_TYPES.GREATER_THAN_EQUAL:case Ee.SEARCH_TYPES._GREATER_THAN_EQUAL:s=Xt.greaterThanEqual(e,i,t.search_attribute,t.search_value,o,c,u);break;case Ee.SEARCH_TYPES.LESS_THAN:case Ee.SEARCH_TYPES._LESS_THAN:s=Xt.lessThan(e,i,t.search_attribute,t.search_value,o,c,u);break;case Ee.SEARCH_TYPES.LESS_THAN_EQUAL:case Ee.SEARCH_TYPES._LESS_THAN_EQUAL:s=Xt.lessThanEqual(e,i,t.search_attribute,t.search_value,o,c,u);break;default:return Object.create(null)}return s}a(Tw,"searchByType");function pw(e,t){let r=new Map;for(let n of e)r.set(n.value,t(n));return r}a(pw,"createMapFromIterable");function bz(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(bz,"checkToFetchMore");function gw(e,t,r,n){if(gz.isEmpty(n)){let s=e.search_value;typeof s=="object"?s=JSON.stringify(s):s=s.toString();let i=s.charAt(0),o=s.charAt(s.length-1),c=!1;if(e.search_attribute===t&&(c=!0),ys.indexOf(s)>-1)return r===!0?Ee.SEARCH_TYPES.SEARCH_ALL_TO_MAP:Ee.SEARCH_TYPES.SEARCH_ALL;if(s.indexOf(ys[0])<0&&s.indexOf(ys[1])<0)return c===!0?r===!0?Ee.SEARCH_TYPES.BATCH_SEARCH_BY_HASH_TO_MAP:Ee.SEARCH_TYPES.BATCH_SEARCH_BY_HASH:Ee.SEARCH_TYPES.EQUALS;if(ys.indexOf(i)>=0&&ys.indexOf(o)>=0)return e.search_value=e.search_value.slice(1,-1),Ee.SEARCH_TYPES.CONTAINS;if(ys.indexOf(i)>=0)return e.search_value=e.search_value.substr(1),Ee.SEARCH_TYPES.ENDS_WITH;if(ys.indexOf(o)>=0)return e.search_value=e.search_value.slice(0,-1),Ee.SEARCH_TYPES.STARTS_WITH;if(s.includes(ys[0])||s.includes(ys[1]))return Ee.SEARCH_TYPES.EQUALS;throw new Error(mw.UNKNOWN_SEARCH_TYPE)}else switch(n){case to.VALUE_SEARCH_COMPARATORS.BETWEEN:return Ee.SEARCH_TYPES.BETWEEN;case to.VALUE_SEARCH_COMPARATORS.GREATER:return Ee.SEARCH_TYPES.GREATER_THAN;case to.VALUE_SEARCH_COMPARATORS.GREATER_OR_EQ:return Ee.SEARCH_TYPES.GREATER_THAN_EQUAL;case to.VALUE_SEARCH_COMPARATORS.LESS:return Ee.SEARCH_TYPES.LESS_THAN;case to.VALUE_SEARCH_COMPARATORS.LESS_OR_EQ:return Ee.SEARCH_TYPES.LESS_THAN_EQUAL;default:throw new Error(mw.UNKNOWN_SEARCH_TYPE)}}a(gw,"createSearchTypeFromSearchObject");Rw.exports={executeSearch:Sw,createSearchTypeFromSearchObject:gw,prepSearch:Oz,searchByType:Tw}});var Ow=g((R_e,Aw)=>{"use strict";var g_e=ts(),yz=na(),Nz=Q(),Iz=L(),wz=nd();Aw.exports=Cz;function Cz(e,t){if(!Nz.isEmpty(t)&&Iz.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[t]===void 0)throw new Error(`Value search comparator - ${t} - is not valid`);let n=yz(e,"value");if(n)throw n;return wz.prepSearch(e,t,!0)}a(Cz,"lmdbGetDataByValue")});var Jc=g((b_e,bw)=>{"use strict";var O_e=ts(),Dz=na(),Lz=Q(),Mz=L(),Uz=nd();bw.exports=Pz;async function Pz(e,t){if(!Lz.isEmpty(t)&&Mz.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[t]===void 0)throw new Error(`Value search comparator - ${t} - is not valid`);let n=Dz(e,"value");if(n)throw n;return Uz.prepSearch(e,t,!1)}a(Pz,"lmdbSearchByValue")});var Nw=g((I_e,yw)=>{"use strict";var N_e=ut(),vp=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}},Bp=class{static{a(this,"SearchCondition")}constructor(t,r,n){this.search_attribute=t,this.search_type=r,this.search_value=n}},Hp=class{static{a(this,"SortAttribute")}constructor(t,r){this.attribute=t,this.desc=r}};yw.exports={SearchByConditionsObject:vp,SearchCondition:Bp,SortAttribute:Hp}});var Lw=g((L_e,Dw)=>{"use strict";var C_e=Nw().SearchByConditionsObject,vz=ts(),Bz=na(),xp=ra(),sd=ut(),{Resource:D_e}=(Nn(),ie(Gp)),Cw=nd(),Hz=Dp(),xz=require("lodash"),{getSchemaPath:Gz}=Je(),Iw=We(),{handleHDBError:qz,hdb_errors:Fz}=ne(),{HTTP_STATUS_CODES:kz}=Fz,Vz=1e8;Dw.exports=$z;async function $z(e){let t=Bz(e,"conditions");if(t)throw qz(t,t.message,kz.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=Gz(e.schema,e.table),n=await Iw.openEnvironment(r,e.table),s=global.hdb_schema[e.schema][e.table];for(let _ of e.conditions)Iw.openDBI(n,_.search_attribute);let i=xz.sortBy(e.conditions,_=>{if(_.estimated_count===void 0){let l=_.search_type;l===sd.SEARCH_TYPES.EQUALS?_.estimated_count=xp.count(n,_.search_attribute,_.search_value):l===sd.SEARCH_TYPES.CONTAINS||l===sd.SEARCH_TYPES.ENDS_WITH?_.estimated_count=1/0:_.estimated_count=Vz}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(Cw.filterByType),d=l.length,f=xp.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=>Hz.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=xp.batchSearchByHash(o,s.hash_attribute,e.get_attributes,c)}return u.onDone=()=>{o.done()},u}a($z,"lmdbSearchByConditions");async function ww(e,t,r,n){let s=new vz(t.schema,t.table,void 0,void 0,n,t.get_attributes),i=r.search_type;return s.search_attribute=r.search_attribute,i===sd.SEARCH_TYPES.BETWEEN?(s.search_value=r.search_value[0],s.end_value=r.search_value[1]):s.search_value=r.search_value,Cw.searchByType(e,s,i,n).map(o=>o.value)}a(ww,"executeConditionSearch")});var ia=g((U_e,Mw)=>{"use strict";var Yz=L().OPERATIONS_ENUM,qp=class{static{a(this,"DeleteObject")}constructor(t,r,n,s=void 0){this.operation=Yz.DELETE,this.schema=t,this.table=r,this.hash_values=n,this.__origin=s}};Mw.exports=qp});var Fp=g((v_e,qw)=>{"use strict";var Bw=ts(),Hw=ia(),xw=Jc(),Gw=Kc(),_r=L(),Uw=Q(),Pw=We(),{getTransactionAuditStorePath:Kz,getSchemaPath:Wz}=Je(),vw=$();qw.exports=Qz;async function Qz(e){try{if(Uw.isEmpty(global.hdb_schema[e.schema])||Uw.isEmpty(global.hdb_schema[e.schema][e.table]))throw new Error(`unknown schema:${e.schema} and table ${e.table}`);await zz(e),await Jz(e);let t=Wz(e.schema,e.table);try{await Pw.deleteEnvironment(t,e.table)}catch(r){if(r.message==="invalid environment")vw.warn(`cannot delete environment for ${e.schema}.${e.table}, environment not found`);else throw r}try{let r=Kz(e.schema,e.table);await Pw.deleteEnvironment(r,e.table,!0)}catch(r){if(r.message==="invalid environment")vw.warn(`cannot delete environment for ${e.schema}.${e.table}, environment not found`);else throw r}}catch(t){throw t}}a(Qz,"lmdbDropTable");async function zz(e){let t=new Bw(_r.SYSTEM_SCHEMA_NAME,_r.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,_r.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_TABLE_KEY,`${e.schema}.${e.table}`,void 0,[_r.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),r=Array.from(await xw(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 Hw(_r.SYSTEM_SCHEMA_NAME,_r.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,n);await Gw(s)}a(zz,"deleteAttributesFromSystem");async function Jz(e){let t=new Bw(_r.SYSTEM_SCHEMA_NAME,_r.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,_r.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY,e.table,void 0,[_r.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY,_r.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_KEY,_r.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),r,n;try{r=Array.from(await xw(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 Hw(_r.SYSTEM_SCHEMA_NAME,_r.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,[n.id]);try{await Gw(s)}catch(i){throw i}}a(Jz,"dropTableFromSystem")});var kw=g((H_e,Fw)=>{"use strict";var Xz=require("fs-extra"),jz=ts(),Zz=sa(),e2=ia(),t2=Fp(),r2=Kc(),n2=Mp(),s2=Jc(),Ns=L(),{getSchemaPath:i2}=Je(),{handleHDBError:o2,hdb_errors:a2}=ne(),{HDB_ERROR_MSGS:c2,HTTP_STATUS_CODES:u2}=a2;Fw.exports=l2;async function l2(e){let t;try{t=await _2(e.schema);let r=new jz(Ns.SYSTEM_SCHEMA_NAME,Ns.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME,Ns.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_KEY,t,void 0,[Ns.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY]),n=Array.from(await s2(r));for(let o=0;o<n.length;o++){let c={schema:t,table:n[o].name};try{await t2(c)}catch(u){if(u.message!=="invalid environment")throw u}}let s=new e2(Ns.SYSTEM_SCHEMA_NAME,Ns.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,[t]);await r2(s);let i=i2(t);await Xz.remove(i)}catch(r){throw r}}a(l2,"lmdbDropSchema");async function _2(e){let t=new Zz(Ns.SYSTEM_SCHEMA_NAME,Ns.SYSTEM_TABLE_NAMES.SCHEMA_TABLE_NAME,[e],[Ns.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_NAME_KEY]),r,n;try{r=Array.from(await n2(t))}catch(s){throw s}for(let[,s]of r)s.name===e&&(n=e);if(!n)throw o2(new Error,c2.SCHEMA_NOT_FOUND(e),u2.NOT_FOUND,void 0,void 0,!0);return n}a(_2,"validateDropSchema")});var id=g((G_e,Vw)=>{"use strict";var kp=class{static{a(this,"CreateTableObject")}constructor(t,r,n){this.schema=t,this.table=r,this.hash_attribute=n}};Vw.exports=kp});var Yw=g((k_e,$w)=>{"use strict";var d2=require("fs-extra"),od=We(),{getTransactionAuditStorePath:f2}=Je(),Vp=ut(),F_e=id();$w.exports=E2;async function E2(e){let t;try{let r=f2(e.schema,e.table);await d2.mkdirp(r),t=await od.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{od.createDBI(t,Vp.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,!1,!0),od.createDBI(t,Vp.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE,!0,!1),od.createDBI(t,Vp.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(E2,"createTransactionsAuditEnvironment")});var zw=g(($_e,Qw)=>{"use strict";var $p=L(),Kw=We(),h2=$o(),{getSystemSchemaPath:m2,getSchemaPath:p2}=Je(),S2=ki(),T2=y_(),Yp=b_(),g2=$(),R2=Yw(),Wp=S2.hdb_table,Ww=[];for(let e=0;e<Wp.attributes.length;e++)Ww.push(Wp.attributes[e].attribute);Qw.exports=A2;async function A2(e,t){let r=p2(t.schema,t.table),n=new Yp(t.schema,t.table,$p.TIME_STAMP_NAMES_ENUM.CREATED_TIME,void 0,!0),s=new Yp(t.schema,t.table,$p.TIME_STAMP_NAMES_ENUM.UPDATED_TIME,void 0,!0),i=new Yp(t.schema,t.table,t.hash_attribute,void 0,!1,!0);try{if(await Kw.createEnvironment(r,t.table),e!==void 0){let o=await Kw.openEnvironment(m2(),$p.SYSTEM_TABLE_NAMES.TABLE_TABLE_NAME);await h2.insertRecords(o,Wp.hash_attribute,Ww,[e]),n.skip_table_check=!0,s.skip_table_check=!0,i.skip_table_check=!0,await Kp(n),await Kp(s),await Kp(i)}await R2(t)}catch(o){throw o}}a(A2,"lmdbCreateTable");async function Kp(e){try{await T2(e)}catch(t){g2.warn(`failed to create attribute ${e.attribute} due to ${t.message}`)}}a(Kp,"createAttribute")});var Xw=g((K_e,Jw)=>{"use strict";var O2=vc(),b2=Hc(),y2=X_(),Xc=L(),N2=$o().updateRecords,I2=We(),{getSchemaPath:w2}=Je(),C2=$c(),D2=$();Jw.exports=L2;async function L2(e){try{let{schema_table:t,attributes:r}=O2(e);b2(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 y2(e.hdb_auth_header,t,r),s=w2(e.schema,e.table),i=await I2.openEnvironment(s,e.table),o=await N2(i,t.hash_attribute,r,e.records,e.__origin?.timestamp);try{await C2(e,o)}catch(c){D2.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(L2,"lmdbUpdateRecords")});var Zw=g((Q_e,jw)=>{"use strict";var M2=L().OPERATIONS_ENUM,Qp=class{static{a(this,"UpsertObject")}constructor(t,r,n,s=void 0){this.operation=M2.UPSERT,this.schema=t,this.table=r,this.records=n,this.__origin=s}};jw.exports=Qp});var tC=g((X_e,eC)=>{"use strict";var J_e=Zw(),U2=vc(),P2=Hc(),v2=X_(),jc=L(),B2=$o().upsertRecords,H2=We(),{getSchemaPath:x2}=Je(),G2=$c(),q2=$(),{handleHDBError:F2,hdb_errors:k2}=ne();eC.exports=V2;async function V2(e){let t;try{t=U2(e)}catch(u){throw F2(u,u.message,k2.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0)}let{schema_table:r,attributes:n}=t;P2(e,n,r.hash_attribute),e.schema!==jc.SYSTEM_SCHEMA_NAME&&(n.includes(jc.TIME_STAMP_NAMES_ENUM.CREATED_TIME)||n.push(jc.TIME_STAMP_NAMES_ENUM.CREATED_TIME),n.includes(jc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME)||n.push(jc.TIME_STAMP_NAMES_ENUM.UPDATED_TIME));let s=await v2(e.hdb_auth_header,r,n),i=x2(e.schema,e.table),o=await H2.openEnvironment(i,e.table),c=await B2(o,r.hash_attribute,n,e.records,e.__origin?.timestamp);try{await G2(e,c)}catch(u){q2.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(V2,"lmdbUpsertRecords")});var nC=g((Z_e,rC)=>{"use strict";var zp=class{static{a(this,"DeleteBeforeObject")}constructor(t,r,n){this.schema=t,this.table=r,this.timestamp=n}};rC.exports=zp});var iC=g((tde,sC)=>{"use strict";var Jp=class{static{a(this,"DeleteAuditLogsBeforeResults")}constructor(t=void 0,r=void 0,n=0){this.start_timestamp=t,this.end_timestamp=r,this.transactions_deleted=n}};sC.exports=Jp});var cC=g((sde,aC)=>{"use strict";var Xp=We(),{getTransactionAuditStorePath:$2}=Je(),nde=nC(),Zc=ut(),Y2=Q(),oC=iC(),K2=require("util").promisify,W2=K2(setTimeout),Q2=1e4,z2=100;aC.exports=J2;async function J2(e){let t=$2(e.schema,e.table),r=await Xp.openEnvironment(t,e.table,!0),n=Xp.listDBIs(r);Xp.initializeDBIs(r,Zc.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,n);let s,i=new oC;do s=await X2(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 W2(z2);while(s.transactions_deleted>0);return i}a(J2,"deleteAuditLogsBefore");async function X2(e,t){let r=new oC;try{let n=e.dbis[Zc.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[Zc.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME];Y2.isEmpty(c)||(s=e.dbis[Zc.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].remove(c,i));for(let u=0;u<o.hash_values.length;u++)s=e.dbis[Zc.TRANSACTIONS_DBI_NAMES_ENUM.HASH_VALUE].remove(o.hash_values[u],i);if(r.transactions_deleted++,r.end_timestamp=i,r.transactions_deleted>Q2)break}return await s,r}catch(n){throw n}}a(X2,"deleteTransactions")});var lC=g((ode,uC)=>{"use strict";var jp=class{static{a(this,"DropAttributeObject")}constructor(t,r,n){this.schema=t,this.table=r,this.attribute=n}};uC.exports=jp});var dC=g((ude,_C)=>{"use strict";var j2=ts(),Z2=ia(),cde=lC(),rs=L(),eJ=Q(),Zp=We(),tJ=ki(),rJ=Jc(),nJ=Kc(),{getSchemaPath:sJ}=Je();_C.exports=iJ;async function iJ(e,t=!0){let r;e.schema===rs.SYSTEM_SCHEMA_NAME?r=tJ[e.table]:r=global.hdb_schema[e.schema][e.table];let n=await aJ(e),s=sJ(e.schema,e.table),i=await Zp.openEnvironment(s,e.table);return t===!0&&await oJ(e,i,r.hash_attribute),Zp.dropDBI(i,e.attribute),n}a(iJ,"lmdbDropAttribute");async function oJ(e,t,r){let n=Zp.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(oJ,"removeAttributeFromAllObjects");async function aJ(e){let t=new j2(rs.SYSTEM_SCHEMA_NAME,rs.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,rs.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_SCHEMA_TABLE_KEY,`${e.schema}.${e.table}`,void 0,[rs.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY,rs.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ATTRIBUTE_KEY]),n=Array.from(await rJ(t)).filter(o=>o[rs.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ATTRIBUTE_KEY]===e.attribute);if(eJ.isEmptyOrZeroLength(n))throw new Error(`Attribute '${e.attribute}' was not found in '${e.schema}.${e.table}'`);let s=n.map(o=>o[rs.SYSTEM_DEFAULT_ATTRIBUTE_NAMES.ATTR_ID_KEY]),i=new Z2(rs.SYSTEM_SCHEMA_NAME,rs.SYSTEM_TABLE_NAMES.ATTRIBUTE_TABLE_NAME,s);return nJ(i)}a(aJ,"dropAttributeFromSystem")});var SC=g((dde,pC)=>{"use strict";var eS=We(),oa=ut(),_de=Dr(),tS=L(),fC=Q(),{getTransactionAuditStorePath:cJ}=Je(),uJ=ra(),ad=Zo(),lJ=$();pC.exports=_J;async function _J(e){let t=cJ(e.schema,e.table),r=await eS.openEnvironment(t,e.table,!0),n=eS.listDBIs(r);eS.initializeDBIs(r,oa.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,n);let s;switch(e.search_type){case tS.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.TIMESTAMP:return EC(r,e.search_values);case tS.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.HASH_VALUE:return s=global.hdb_schema[e.schema][e.table].hash_attribute,fJ(r,e.search_values,s);case tS.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.USERNAME:return dJ(r,e.search_values);default:return EC(r)}}a(_J,"readAuditLog");function EC(e,t=[0,Date.now()]){fC.isEmpty(t[0])&&(t[0]=0),fC.isEmpty(t[1])&&(t[1]=Date.now());let r=e.dbis[oa.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 ad,s))}a(EC,"searchTransactionsByTimestamp");function dJ(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[oa.TRANSACTIONS_DBI_NAMES_ENUM.USER_NAME].getValues(s))i.push(o);r.set(s,mC(e,i))}return Object.fromEntries(r)}a(dJ,"searchTransactionsByUsername");function fJ(e,t,r){let n=new Map;for(let c=0,u=t.length;c<u;c++){let _=t[c],l=uJ.equals(e,oa.TRANSACTIONS_DBI_NAMES_ENUM.TIMESTAMP,oa.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=mC(e,s),o=new Map;for(let c=0;c<i.length;c++){let u=i[c],_=u.timestamp,l=n.get(_);hC(u,"records",r,l,o),hC(u,"original_records",r,l,o)}return Object.fromEntries(o)}a(fJ,"searchTransactionsByHashValues");function hC(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 ad(e.operation,e.user_name,i,void 0);d[t]=[c],_.push(d)}}else{let _=new ad(e.operation,e.user_name,i,void 0);_[t]=[c],s.set(u,[_])}}}a(hC,"loopRecords");function mC(e,t){let r=[];try{let n=e.dbis[oa.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 ad,i);r.push(o)}}catch(i){lJ.warn(i)}return r}catch(n){throw n}}a(mC,"batchSearchTransactions")});var gC=g((mde,TC)=>{"use strict";var{getSchemaPath:Ede}=Je(),hde=We(),{database:EJ}=(Re(),ie(Fe));TC.exports={writeTransaction:hJ};async function hJ(e,t,r){return EJ({database:e,table:t}).transaction(r)}a(hJ,"writeTransaction")});var bC=g((Sde,OC)=>{"use strict";var{getSchemaPath:RC}=Je(),AC=We();OC.exports={flush:mJ,resetReadTxn:pJ};async function mJ(e,t){return(await AC.openEnvironment(RC(e,t),t.toString())).flushed}a(mJ,"flush");async function pJ(e,t){try{(await AC.openEnvironment(RC(e,t),t.toString())).resetReadTxn()}catch{}}a(pJ,"resetReadTxn")});var wC=g((gde,IC)=>{"use strict";var{Readable:SJ}=require("stream"),{getDatabases:TJ}=(Re(),ie(Fe)),{readSync:gJ,openSync:RJ,createReadStream:yC}=require("fs"),{open:AJ}=require("lmdb"),NC=wc(),OJ=Cc(),{AUDIT_STORE_OPTIONS:bJ}=(ei(),ie(CC)),{INTERNAL_DBIS_NAME:yJ,AUDIT_STORE_NAME:NJ}=ut();IC.exports=wJ;var rS=32768,IJ=100;async function wJ(e){let t=e.database||e.schema||"data",r=TJ()[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=AJ({noSync:!0,maxDbs:OJ.MAX_DBS}),f,E=d.openDB(yJ,new NC(!1)),h=l.useReadTransaction(),p=0,S=a(async function(A,R){R.encoding="binary",R.encoder=void 0;let M=d.openDB(A,R),x=l.openDB(A,R);for(let{key:P,version:k,value:B}of x.getRange({start:null,transaction:h,versions:x.useVersions}))f=M.put(P,B,k),p++%IJ===0&&(await new Promise(X=>setTimeout(X,20)),h.openTimer&&(h.openTimer=0))},"copyDatabase");for(let{key:A,value:R}of l.getRange({transaction:h,start:!1}))if(s.some(M=>A.startsWith?.(M+"/"))){E.put(A,R);let[,M]=A.split("/"),x=!M,P=new NC(!x,x);await S(A,P)}e.include_audit&&await S(NJ,Object.assign({},bJ)),await f;let T=yC(d.path);return T.headers=u(),T.on("close",()=>{h.done(),d.close()}),T}let o=r[Object.keys(r)[0]].primaryStore,c=RJ(o.path);return o.transaction(()=>{let _=Buffer.alloc(rS);gJ(c,_,0,rS),o.resetReadTxn();let l=o.useReadTransaction();l.renew();let d=yC(null,{fd:c,start:rS}),f=new SJ.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(wJ,"getBackup")});var MC=g((Ade,LC)=>{"use strict";var CJ=$(),{handleHDBError:DJ}=ne(),LJ=Yb(),MJ=y_(),UJ=yp(),PJ=kI(),vJ=Kc(),BJ=Mp(),HJ=Ew(),xJ=Ow(),GJ=Jc(),qJ=Lw(),FJ=kw(),kJ=zw(),VJ=Xw(),$J=tC(),YJ=cC(),KJ=Fp(),WJ=dC(),QJ=SC(),zJ=gC(),DC=bC(),JJ=wC(),nS=class extends LJ{static{a(this,"LMDBBridge")}async searchByConditions(t){return qJ(t)}async getDataByHash(t){return await BJ(t)}async searchByHash(t){return await HJ(t)}async getDataByValue(t,r){return await xJ(t,r)}async searchByValue(t){return await GJ(t)}async createSchema(t){return await PJ(t)}async dropSchema(t){return await FJ(t)}async createTable(t,r){return await kJ(t,r)}async dropTable(t){return await KJ(t)}async createAttribute(t){return await MJ(t)}async createRecords(t){return await UJ(t)}async updateRecords(t){return await VJ(t)}async upsertRecords(t){try{return await $J(t)}catch(r){throw DJ(r,null,null,CJ.ERR,r)}}async deleteRecords(t){return await vJ(t)}async dropAttribute(t){return await WJ(t)}async deleteAuditLogsBefore(t){return await YJ(t)}async readAuditLog(t){return await QJ(t)}writeTransaction(t,r,n){return zJ.writeTransaction(t,r,n)}flush(t,r){return DC.flush(t,r)}resetReadTxn(t,r){return DC.resetReadTxn(t,r)}getBackup(t){return JJ(t)}};LC.exports=nS});function t4(){e4=setInterval(function(){for(let e of sS)if(e.stale){let t=e[ye]?.url;vC.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 iS,PC,vC,XJ,sS,jJ,eu,UC,ro,cd,ZJ,e4,oS=ge(()=>{iS=v(Dr()),PC=v(ne()),vC=v($());Nn();XJ=100,sS=new Set,jJ=25e3,ro=class e{static{a(this,"DatabaseTransaction")}writes=[];lmdbDb;readTxn;readTxnRefCount;readTxnsUsed;validated=0;timestamp=0;open=1;getReadTxn(){if(this.readTxnRefCount=(this.readTxnRefCount||0)+1,this.stale&&(this.stale=!1),this.readTxn)return this.readTxn.openTimer&&(this.readTxn.openTimer=0),this.readTxn;if(this.open===1)return this.readTxnsUsed=1,this.readTxn=this.lmdbDb.useReadTransaction(),this.readTxn.openTimer&&(this.readTxn.openTimer=0),sS.add(this),this.readTxn}useReadTxn(){return this.getReadTxn(),this.readTxn.use(),this.readTxnsUsed++,this.readTxn}doneReadTxn(){this.readTxn&&(this.readTxn.done(),--this.readTxnsUsed===0&&(sS.delete(this),this.readTxn=null))}disregardReadTxn(){--this.readTxnRefCount===0&&this.readTxnsUsed===1&&this.doneReadTxn()}checkOverloaded(){if(eu&&performance.now()-UC>jJ)throw new PC.ServerError("Outstanding write transactions have too long of queue, please try again later",503)}addWrite(t){if(this.open===0)throw new Error("Can not use a transaction that is no longer open");if(this.open===2){let r=new e;return r.addWrite(t),r.commit({})}else this.writes.push(t)}removeWrite(t){let r=this.writes.indexOf(t);r>-1&&(this.writes[r]=null)}commit(t={}){let r=this.timestamp;r||(r=this.timestamp=t.timestamp=t.timestamp||(0,iS.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(),this.open=t?.letItLinger?2:0;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<XJ>>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 eu||(eu=s,UC=performance.now(),eu.then(()=>{eu=null})),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=0,this.writes=[]}},cd=class extends ro{static{a(this,"ImmediateTransaction")}_timestamp;addWrite(t){super.addWrite(t),this.commit()}get timestamp(){return this._timestamp||(this._timestamp=(0,iS.getNextMonotonicTime)())}getReadTxn(){}},ZJ=3e4;a(t4,"startMonitoringTxns");t4()});function je(e,t,r){if(!t)t=e,e={};else if(!e)e={};else if(e?.transaction?.open===1&&typeof t=="function")return t(e.transaction);if(typeof t!="function")throw new Error("Callback function must be provided to transaction");let n=e.transaction=new ro;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({letItLinger:r?.letItLinger});return u.then?u.then(()=>c):c}function o(c){throw n.abort({}),c}}var BC,no=ge(()=>{BC=require("../index");Nn();oS();a(je,"transaction");(0,BC._assignPackageExport)("transaction",je);je.commit=function(e){let t=(e[ye]||e)?.transaction;if(!t)throw new Error("No active transaction is available to commit");return t.commit()};je.abort=function(e){let t=(e[ye]||e)?.transaction;if(!t)throw new Error("No active transaction is available to abort");return t.abort()}});var YC={};qe(YC,{ResourceBridge:()=>uS});function lS({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 xC(e,t){let r=ns(e),n=lS(e,r);if(!r)throw new Un.ClientError(`Table ${e.table} not found`);let s;n&&r.attributes.length-n.length>2&&n.length<5&&(s=!0);let i={user:e.hdb_user},o;je(i,()=>new Promise(_=>o=_));let c=e.ids||e.hash_values,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&&ld(l),t?{value:{key:_,value:l}}:{value:l}}else return o(),{done:!0}},return(_){return o(),{value:_,done:!0}},throw(_){return o(),{done:!0}}}}}}function ns(e){let t=e.database||e.schema||n4,r=dr()[t];if(!r)throw(0,Un.handleHDBError)(new Error,r4.SCHEMA_NOT_FOUND(t),404);return r[e.table]}function GC(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*qC(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 FC,ud,Un,kC,VC,Pn,aS,cS,$C,r4,n4,s4,i4,HC,uS,KC=ge(()=>{"use strict";FC=v(MC()),ud=v(na()),Un=v(ne());Re();kC=v(vc()),VC=v(Hc()),Pn=v(L()),aS=v(bs()),cS=v(Mn()),$C=v(Q());no();_d();({HDB_ERROR_MSGS:r4}=Un.hdb_errors),n4="data",s4=1e4,i4=10,uS=class extends FC.default{static{a(this,"ResourceBridge")}constructor(t){super(t),HC=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,ud.default)(t,"conditions");if(r)throw(0,Un.handleHDBError)(r,r.message,400,void 0,void 0,!0);let n=ns(t);if(!n)throw new Un.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:lS(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 Un.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}]}lt({database:r.schema,table:r.table,attributes:n,schemaDefined:s,expiration:r.expiration})}async createAttribute(t){return await ns(t).addAttributes([{name:t.attribute,indexed:t.indexed??!0}]),`attribute ${t.schema}.${t.table}.${t.attribute} successfully created.`}async dropAttribute(t){let r=ns(t);if(await r.removeAttributes([t.attribute]),!r.schemaDefined){let n=t.attribute,s,i=a((o,c,u)=>(c=Object.assign({},c),delete c[n],r.primaryStore.ifVersion(o,u,()=>r.primaryStore.put(o,c,u)).then(_=>{if(!_){let{value:l,version:d}=r.primaryStore.getEntry(o);return i(o,l,d)}})),"deleteRecord");for(let{key:o,value:c,version:u}of r.primaryStore.getRange({start:!0,versions:!0}))s=i(o,c,u),await new Promise(_=>setImmediate(_));await s}return`successfully deleted ${t.schema}.${t.table}.${t.attribute}`}dropTable(t){ns(t).dropTable()}createSchema(t){return tu({database:t.schema,table:null}),aS.signalSchemaChange(new cS.SchemaEventMsg(process.pid,Pn.OPERATIONS_ENUM.CREATE_SCHEMA,t.schema))}async dropSchema(t){await _S(t.schema),aS.signalSchemaChange(new cS.SchemaEventMsg(process.pid,Pn.OPERATIONS_ENUM.DROP_SCHEMA,t.schema))}async updateRecords(t){return t.requires_existing=!0,this.upsertRecords(t)}async createRecords(t){return t.requires_no_existing=!0,HC.upsertRecords(t)}async upsertRecords(t){let{schema_table:r,attributes:n}=(0,kC.default)(t);(0,VC.default)(t,n,r.primaryKey);let s,i=dr()[t.schema][t.table],o={user:t.hdb_user,expiresAt:t.expiresAt};return je(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=ld(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=dr()[t.schema][t.table],n={user:t.hdb_user};return je(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 GC(o,c,s.timestamp)})}async deleteRecordsBefore(t){let r=dr()[t.schema][t.table];if(!r.createdTimeProperty)throw new Un.ClientError("Table must have a '__createdtime__' attribute or @createdTime timestamp defined to perform this operation");let n=await r.search({conditions:[{attribute:r.createdTimeProperty.name,value:Date.parse(t.date),comparator:Pn.VALUE_SEARCH_COMPARATORS.LESS}]}),s=!1,i=[],o=[],c=0,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,$C.async_set_timeout)(i4),u=[],s=!0},"chunkDelete");for await(let l of n)u.push(l[r.primaryKey]),c++,c%s4===0&&await _();return u.length>0&&await _(),s?GC(i,o,void 0):{message:"No records found to delete"}}searchByHash(t){t.select!==void 0&&(t.get_attributes=t.select);let r=(0,ud.default)(t,"hashes");if(r)throw r;return xC(t)}async getDataByHash(t){let r=new Map;t._returnKeyValue=!0;for await(let{key:n,value:s}of xC(t,!0))r.set(n,s);return r}searchByValue(t,r){if(r&&Pn.VALUE_SEARCH_COMPARATORS_REVERSE_LOOKUP[r]===void 0)throw new Error(`Value search comparator - ${r} - is not valid`);t.select!==void 0&&(t.get_attributes=t.select),t.attribute!==void 0&&(t.search_attribute=condition.attribute),t.value!==void 0&&(t.search_value=condition.value);let n=(0,ud.default)(t,"value");if(n)throw n;let s=ns(t);if(!s)throw new Un.ClientError(`Table ${t.table} not found`);let i=t.search_value;i.includes?.("*")&&(i.startsWith("*")?i.endsWith("*")?i!=="*"&&(r="contains",i=i.slice(1,-1)):(r="ends_with",i=i.slice(1)):i.endsWith("*")&&(r="starts_with",i=i.slice(0,-1))),r===Pn.VALUE_SEARCH_COMPARATORS.BETWEEN&&(i=[i,t.end_value]);let o=i==="*"?[]:[{attribute:t.search_attribute,value:i,comparator:r}];return s.search({conditions:o,allowFullScan:!0,limit:t.limit,offset:t.offset,reverse:t.reverse,select:lS(t,s)})}async getDataByValue(t,r){let n=new Map,s=ns(t);t.get_attributes&&!t.get_attributes.includes(s.primaryKey)&&t.get_attributes[0]!=="*"&&t.get_attributes.push(s.primaryKey);for await(let i of this.searchByValue(t,r))n.set(i[s.primaryKey],i);return n}resetReadTxn(t,r){ns({schema:t,table:r})?.primaryStore.resetReadTxn()}async deleteAuditLogsBefore(t){return ns(t).deleteHistory(t.timestamp)}async readAuditLog(t){let r=ns(t),n={};switch(t.search_type){case Pn.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.HASH_VALUE:for(let i of t.search_values)n[i]=(await r.getHistoryOfRecord(i)).map(o=>{let c=o.type;return c==="put"&&(c="upsert"),{operation:c,timestamp:o.version,user_name:o.user,hash_values:[i],records:[o.value]}});return n;case Pn.READ_AUDIT_LOG_SEARCH_TYPES_ENUM.USERNAME:let s=t.search_values;for await(let i of qC(r))s.includes(i.user_name)&&(n[i.user_name]||(n[i.user_name]=[])).push(i);return n;default:return qC(r,t.search_values?.[0],t.search_values?.[1])}}};a(lS,"getSelect");a(xC,"getRecords");a(ns,"getTable");a(GC,"createDeleteResponse");a(qC,"groupRecordsInHistory")});var Cn=g((Hde,WC)=>{"use strict";var{ResourceBridge:o4}=(KC(),ie(YC)),a4=ee();a4.initSync();var dd;function c4(){return dd||(dd=new o4,dd)}a(c4,"getBridge");WC.exports=c4()});var XC=g((Gde,JC)=>{"use strict";var QC=require("lodash"),ru=require("mathjs"),u4=require("jsonata"),zC=Q();JC.exports={distinct_array:e=>Array.isArray(e)&&e.length>1?QC.uniqWith(e,QC.isEqual):e,searchJSON:l4,mad:nu.bind(null,ru.mad),mean:nu.bind(null,ru.mean),mode:nu.bind(null,ru.mode),prod:nu.bind(null,ru.prod),median:nu.bind(null,ru.median)};function nu(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(nu,"aggregateFunction");function l4(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(zC.isEmpty(this.__ala__.res)&&(this.__ala__.res={}),zC.isEmpty(this.__ala__.res[r])){let n=u4(e);this.__ala__.res[r]=n}return this.__ala__.res[r].evaluate(t)}a(l4,"searchJSON")});var ZC=g((Fde,jC)=>{"use strict";var pt=require("moment"),dS="YYYY-MM-DDTHH:mm:ss.SSSZZ";pt.suppressDeprecationWarnings=!0;jC.exports={current_date:()=>pt().utc().format("YYYY-MM-DD"),current_time:()=>pt().utc().format("HH:mm:ss.SSS"),extract:(e,t)=>{switch(t.toLowerCase()){case"year":return pt(e).utc().format("YYYY");case"month":return pt(e).utc().format("MM");case"day":return pt(e).utc().format("DD");case"hour":return pt(e).utc().format("HH");case"minute":return pt(e).utc().format("mm");case"second":return pt(e).utc().format("ss");case"millisecond":return pt(e).utc().format("SSS");default:break}},date:e=>pt(e).utc().format(dS),date_format:(e,t)=>pt(e).utc().format(t),date_add:(e,t,r)=>pt(e).utc().add(t,r).valueOf(),date_sub:(e,t,r)=>pt(e).utc().subtract(t,r).valueOf(),date_diff:(e,t,r)=>{let n=pt(e).utc(),s=pt(t).utc();return r?n.diff(s,r,!0):n.diff(s)},now:()=>pt().utc().valueOf(),get_server_time:()=>pt().format(dS),offset_utc:(e,t)=>pt(e).utc().utcOffset(t).format(dS)}});var nD=g((kde,rD)=>{"use strict";var _4=require("@turf/area"),d4=require("@turf/length"),f4=require("@turf/circle"),E4=require("@turf/difference"),h4=require("@turf/distance"),m4=require("@turf/boolean-contains"),p4=require("@turf/boolean-equal"),S4=require("@turf/boolean-disjoint"),T4=require("@turf/helpers"),eD=L(),Se=Q(),Is=$();rD.exports={geoArea:g4,geoLength:R4,geoCircle:A4,geoDifference:O4,geoDistance:tD,geoNear:b4,geoContains:y4,geoEqual:N4,geoCrosses:I4,geoConvert:w4};function g4(e){if(Se.isEmpty(e))return NaN;typeof e=="string"&&(e=Se.autoCastJSON(e));try{return _4.default(e)}catch(t){return Is.trace(t,e),NaN}}a(g4,"geoArea");function R4(e,t){if(Se.isEmpty(e))return NaN;typeof e=="string"&&(e=Se.autoCastJSON(e));try{return d4.default(e,{units:t||"kilometers"})}catch(r){return Is.trace(r,e),NaN}}a(R4,"geoLength");function A4(e,t,r){if(Se.isEmpty(e))return NaN;if(Se.isEmpty(t))return NaN;typeof e=="string"&&(e=Se.autoCastJSON(e));try{return f4.default(e,t,{units:r||"kilometers"})}catch(n){return Is.trace(n,e,t),NaN}}a(A4,"geoCircle");function O4(e,t){if(Se.isEmpty(e))return NaN;if(Se.isEmpty(t))return NaN;typeof e=="string"&&(e=Se.autoCastJSON(e)),typeof t=="string"&&(t=Se.autoCastJSON(t));try{return E4(e,t)}catch(r){return Is.trace(r,e,t),NaN}}a(O4,"geoDifference");function tD(e,t,r){if(Se.isEmpty(e))return NaN;if(Se.isEmpty(t))return NaN;typeof e=="string"&&(e=Se.autoCastJSON(e)),typeof t=="string"&&(t=Se.autoCastJSON(t));try{return h4.default(e,t,{units:r||"kilometers"})}catch(n){return Is.trace(n,e,t),NaN}}a(tD,"geoDistance");function b4(e,t,r,n){if(Se.isEmpty(e)||Se.isEmpty(t))return!1;if(Se.isEmpty(r))throw new Error("distance is required");if(typeof e=="string"&&(e=Se.autoCastJSON(e)),typeof t=="string"&&(t=Se.autoCastJSON(t)),isNaN(r))throw new Error("distance must be a number");try{return tD(e,t,n)<=r}catch(s){return Is.trace(s,e,t),!1}}a(b4,"geoNear");function y4(e,t){if(Se.isEmpty(e)||Se.isEmpty(t)||e.coordinates&&e.coordinates.includes?.(null)||t.coordinates&&t.coordinates.includes?.(null))return!1;typeof e=="string"&&(e=Se.autoCastJSON(e)),typeof t=="string"&&(t=Se.autoCastJSON(t));try{return m4.default(e,t)}catch(r){return Is.trace(r,e,t),!1}}a(y4,"geoContains");function N4(e,t){if(Se.isEmpty(e)||Se.isEmpty(t)||e.coordinates&&e.coordinates.includes?.(null)||t.coordinates&&t.coordinates.includes?.(null))return!1;typeof e=="string"&&(e=Se.autoCastJSON(e)),typeof t=="string"&&(t=Se.autoCastJSON(t));try{return p4.default(e,t)}catch(r){return Is.trace(r,e,t),!1}}a(N4,"geoEqual");function I4(e,t){if(Se.isEmpty(e)||Se.isEmpty(t)||e.coordinates&&e.coordinates.includes?.(null)||t.coordinates&&t.coordinates.includes?.(null))return!1;typeof e=="string"&&(e=Se.autoCastJSON(e)),typeof t=="string"&&(t=Se.autoCastJSON(t));try{return!S4.default(e,t)}catch(r){return Is.trace(r,e,t),!1}}a(I4,"geoCrosses");function w4(e,t,r){if(Se.isEmptyOrZeroLength(e))throw new Error("coordinates is required");if(Se.isEmpty(t))throw new Error("geo_type is required");if(Se.isEmpty(eD.GEO_CONVERSION_ENUM[t]))throw new Error(`geo_type of ${t} is invalid please use one of the following types: ${Object.keys(eD.GEO_CONVERSION_ENUM).join(",")}`);return typeof e=="string"&&(e=Se.autoCastJSON(e)),T4[t](e,r)}a(w4,"geoConvert")});var fd=g(($de,sD)=>{var so=XC(),Fr=ZC(),ss=nD();sD.exports=e=>{e.aggr.mad=e.aggr.MAD=so.mad,e.aggr.mean=e.aggr.MEAN=so.mean,e.aggr.mode=e.aggr.MODE=so.mode,e.aggr.prod=e.aggr.PROD=so.prod,e.aggr.median=e.aggr.MEDIAN=so.median,e.fn.distinct_array=e.fn.DISTINCT_ARRAY=so.distinct_array,e.fn.search_json=e.fn.SEARCH_JSON=so.searchJSON,e.fn.__ala__=e,e.fn.current_date=e.fn.CURRENT_DATE=Fr.current_date,e.fn.current_time=e.fn.CURRENT_TIME=Fr.current_time,e.fn.extract=e.fn.EXTRACT=Fr.extract,e.fn.date=e.fn.DATE=Fr.date,e.fn.date_format=e.fn.DATE_FORMAT=Fr.date_format,e.fn.date_add=e.fn.DATE_ADD=Fr.date_add,e.fn.date_sub=e.fn.DATE_SUB=Fr.date_sub,e.fn.date_diff=e.fn.DATE_DIFF=e.fn.datediff=e.fn.DATEDIFF=Fr.date_diff,e.fn.now=e.fn.NOW=Fr.now,e.fn.offset_utc=e.fn.OFFSET_UTC=Fr.offset_utc,e.fn.get_server_time=e.fn.GET_SERVER_TIME=Fr.get_server_time,e.fn.getdate=e.fn.GETDATE=Fr.now,e.fn.current_timestamp=e.fn.CURRENT_TIMESTAMP=Fr.now,e.fn.geoarea=e.fn.GEOAREA=e.fn.geoArea=ss.geoArea,e.fn.geocircle=e.fn.GEOCIRCLE=e.fn.geoCircle=ss.geoCircle,e.fn.geocontains=e.fn.GEOCONTAINS=e.fn.geoContains=ss.geoContains,e.fn.geoconvert=e.fn.GEOCONVERT=e.fn.geoConvert=ss.geoConvert,e.fn.geocrosses=e.fn.GEOCROSSES=e.fn.geoCrosses=ss.geoCrosses,e.fn.geodifference=e.fn.GEODIFFERENCE=e.fn.geoDifference=ss.geoDifference,e.fn.geodistance=e.fn.GEODISTANCE=e.fn.geoDistance=ss.geoDistance,e.fn.geoequal=e.fn.GEOEQUAL=e.fn.geoEqual=ss.geoEqual,e.fn.geolength=e.fn.GEOLENGTH=e.fn.geoLength=ss.geoLength,e.fn.geonear=e.fn.GEONEAR=e.fn.geoNear=ss.geoNear}});var cD=g((Yde,aD)=>{"use strict";var su=require("lodash"),fr=require("alasql");fr.options.cache=!1;var C4=fd(),iD=require("clone"),Ed=require("recursive-iterator"),le=$(),Ce=Q(),aa=Cn(),D4=L(),{hdb_errors:L4}=ne(),{getDatabases:oD}=(Re(),ie(Fe)),M4="IS NULL",vn="There was a problem performing this search. Please check the logs and try again.";C4(fr);var fS=class{static{a(this,"SQLSearch")}constructor(t,r){if(Ce.isEmpty(t))throw le.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 le.trace("No results returned from checkEmptySQL SQLSearch method."),n}catch(n){throw le.error("Error thrown from checkEmptySQL in SQLSearch class method search."),le.error(n),new Error(vn)}try{let n=await this._getFetchAttributeValues();if(n)return n}catch(n){throw le.error("Error thrown from getFetchAttributeValues in SQLSearch class method search."),le.error(n),new Error(vn)}if(Object.keys(this.data).length===0)return le.trace('SQLSearch class field: "data" is empty.'),[];let r;try{r=await this._processJoins()}catch(n){throw le.error("Error thrown from processJoins in SQLSearch class method search."),le.error(n),new Error(vn)}try{await this._getFinalAttributeData(r.existing_attributes,r.joined_length)}catch(n){throw le.error("Error thrown from getFinalAttributeData in SQLSearch class method search."),le.error(n),new Error(vn)}try{return t=await this._finalSQL(),t}catch(n){throw le.error("Error thrown from finalSQL in SQLSearch class method search."),le.error(n),new Error(vn)}}_getColumns(){let t=new Ed(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(iD(r)))}_getTables(){let t=[];this.all_table_attributes.forEach(r=>{t.push(r.table)}),this.tables=su.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=oD()[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)){le.trace('AST "where" statement is empty.');return}let t=!1;for(let{node:r}of new Ed(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 fr.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 fr.yy.LogicValue({value:i}):n instanceof fr.yy.StringValue&&Ce.autoCasterIsNumberCheck(i.toString())&&(r.right[s]=new fr.yy.NumValue({value:i}))});if(t){le.trace('Where clause contains "OR", exact match search not performed on attributes.');return}for(let{node:r}of new Ed(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(D4.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&&su.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 fr.promise(r)}catch(r){throw le.error("Error thrown from AlaSQL in SQLSearch class method checkEmptySQL."),le.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(iD(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(M4)>-1&&this.tables.forEach(s=>{let i={columnid:oD()[s.databaseid][s.tableid].primaryKey,tableid:s.tableid};this._addFetchColumns([i])}),this.statement.order&&(this._updateOrderByToAliases(),this._addNonAggregatorsToFetchColumns()),this.fetch_attributes=su.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 aa.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 le.error("Error thrown from getDataByHash function in SQLSearch class method getFetchAttributeValues exact match."),le.error(l),new Error(vn)}else try{c.search_attribute=s.attribute,await Promise.all(Array.from(this.exact_search_values[_].values).map(async l=>{let d=Object.assign({},c);d.search_value=l;let f=await aa.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 le.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues exact match."),le.error(l),new Error(vn)}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 aa.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 le.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues comparator search values."),le.error(l),new Error(vn)}else try{c.search_attribute=s.attribute,c.search_value="*";let l=await aa.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 le.error("Error thrown from getDataByValue function in SQLSearch class method getFetchAttributeValues no comparator search values."),le.error(l),new Error(vn)}}}_isSimpleSelect(){let t=!0;return Object.keys(this.statement).length!==2||!this.statement.columns||!this.statement.from||this.statement.from.length!==1?(t=!1,t):(this.statement.columns.forEach(r=>{r instanceof fr.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 fr.yy.Column;s.columnid=n.as,s.columnid_orig=n.as_orig,t.expression=s}else{t.initial_select_column=Object.assign(new fr.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 fr.yy.FuncValue:new fr.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 fr.promise(h,t),t=null}catch(E){throw le.error("Error thrown from AlaSQL in SQLSearch class method processJoins."),le.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=su.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 Ed(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=su.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 le.error("Error thrown from getData in SQLSearch class method getFinalAttributeData."),le.error(i),new Error(vn)}}async _getData(t){try{let r=t.reduce((n,s)=>{let i=`${s.table.databaseid}_${s.table.as?s.table.as:s.table.tableid}`;return n[i]?n[i].columns.push(s.attribute):n[i]={schema:s.table.databaseid,table:s.table.tableid,columns:[s.attribute]},n},{});for(let n in r){let s=r[n],i=this.data[n].__merged_data,o=[];for(let l in i)o.push(i[l][0]);this.data[n].__merged_attributes.push(...s.columns);let c={schema:s.schema,table:s.table,hash_values:o,get_attributes:s.columns},u=await aa.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 le.error("Error thrown from getDataByHash function in SQLSearch class method getData."),le.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();le.trace(`Final SQL: ${s}`),n=await fr.promise(s,t),this.has_outer_join&&(n=this._translateUndefinedValues(n)),le.trace(`Final AlaSQL results data included ${n.length} rows`)}catch(s){throw le.error("Error thrown from AlaSQL in SQLSearch class method finalSQL."),le.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 le.error(L4.HDB_ERROR_MSGS.OUTER_JOIN_TRANSLATION_ERROR),le.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 aa.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 le.error("There was an error when processing this SQL operation. Check your logs"),le.error(o),new Error(vn)}}return Object.values(Object.values(this.data)[0].__merged_data)}};aD.exports=fS});var Pr=g((Wde,uD)=>{"use strict";var U4=Vb();uD.exports={searchByConditions:v4,searchByHash:B4,searchByValue:H4,search:x4};var ES=Cn(),{transformReq:hS}=Q(),P4=cD();async function v4(e){return hS(e),ES.searchByConditions(e)}a(v4,"searchByConditions");async function B4(e){hS(e),e.ids&&(e.hash_values=e.ids);let t=[];for await(let r of ES.searchByHash(e))r&&t.push(r);return t}a(B4,"searchByHash");async function H4(e){hS(e),e.hasOwnProperty("desc")===!0&&(e.reverse=e.desc);let t=[];for await(let r of ES.searchByValue(e))t.push(r);return t}a(H4,"searchByValue");function x4(e,t){try{let r=new U4(e);r.validate(),new P4(r.statement,r.attributes).search().then(s=>{t(null,s)}).catch(s=>{t(s,null)})}catch(r){return t(r)}}a(x4,"search")});var hd=g((zde,lD)=>{"use strict";var G4=Cn();lD.exports={writeTransaction:q4};function q4(e,t,r){return G4.writeTransaction(e,t,r)}a(q4,"writeTransaction")});var ED=g((jde,fD)=>{"use strict";var F4=Pr(),k4=Os(),_D=$(),V4=vr(),Xde=hd(),$4=require("clone"),pS=require("alasql"),Y4=fd(),dD=require("util"),K4=dD.promisify(k4.getTableSchema),W4=dD.promisify(F4.search),Q4=L(),mS=Q();Y4(pS);fD.exports={update:J4};var z4="There was a problem performing this update. Please check the logs and try again.";async function J4({statement:e,hdb_user:t}){let r=await K4(e.table.databaseid,e.table.tableid),n=X4(e.columns);mS.backtickASTSchemaItems(e);let{table:s,where:i}=e,o=$4(s),c=mS.isEmpty(i)?"":` WHERE ${i.toString()}`,u=`SELECT ${r.hash_attribute} FROM ${s.toString()} ${c}`,_=pS.parse(u).statements[0],l=await W4(_),d=j4(n,l);return Z4(o,d,t)}a(J4,"update");function X4(e){try{let t={};return e.forEach(r=>{"value"in r.expression?t[r.column.columnid]=r.expression.value??null:t[r.column.columnid]=pS.compile(`SELECT ${r.expression.toString()} AS [${Q4.FUNC_VAL}] FROM ?`)}),t}catch(t){throw _D.error(t),new Error(z4)}}a(X4,"createUpdateRecord");function j4(e,t){return mS.isEmptyOrZeroLength(t)?[]:t.map(r=>Object.assign(r,e))}a(j4,"buildUpdateRecords");async function Z4(e,t,r){let n={operation:"update",schema:e.databaseid_orig,table:e.tableid_orig,records:t,hdb_user:r},s=await V4.update(n);try{delete s.new_attributes,delete s.txn_time}catch(i){_D.error(`Error delete new_attributes from update response: ${i}`)}return s}a(Z4,"updateRecords")});var mD=g((rfe,hD)=>{var e3=require("alasql"),t3=Pr(),r3=$(),n3=Cn(),TS=require("util"),SS=Q(),s3=L(),i3=Os(),efe=hd(),tfe=vr(),o3="record",a3="successfully deleted",c3=TS.callbackify(d3),u3=TS.promisify(t3.search),l3=TS.promisify(i3.getTableSchema);hD.exports={convertDelete:c3};function _3(e){return`${e.deleted_hashes.length} ${o3}${e.deleted_hashes.length===1?"":"s"} ${a3}`}a(_3,"generateReturnMessage");async function d3({statement:e,hdb_user:t}){let r=await l3(e.table.databaseid,e.table.tableid);SS.backtickASTSchemaItems(e);let{table:n,where:s}=e,i=SS.isEmpty(s)?"":` WHERE ${s.toString()}`,o=`SELECT ${r.hash_attribute} FROM ${n.toString()} ${i}`,c=e3.parse(o).statements[0],u={operation:s3.OPERATIONS_ENUM.DELETE,schema:n.databaseid_orig,table:n.tableid_orig,hdb_user:t};try{u.records=await u3(c);let _=await n3.deleteRecords(u);return SS.isEmptyOrZeroLength(_.message)&&(_.message=_3(_)),delete _.txn_time,_}catch(_){throw r3.error(_),_.hdb_code?_.message:_}}a(d3,"convertDelete")});var RD=g((sfe,gD)=>{"use strict";var f3=As(),{hdb_errors:pD}=ne(),{getDatabases:SD}=(Re(),ie(Fe));gD.exports={checkSchemaExists:TD,checkSchemaTableExists:E3,schema_describe:f3};async function TD(e){if(!SD()[e])return pD.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}a(TD,"checkSchemaExists");async function E3(e,t){let r=await TD(e);if(r)return r;if(!SD()[e][t])return pD.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(E3,"checkSchemaTableExists")});var iu=g((ofe,h3)=>{h3.exports={name:"harperdb",version:"4.3.0-beta.16",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.7","nats-server":"2.10.11"},exports:{".":"./index.js"},homepage:"https://www.harperdb.io/",bugs:"support@harperdb.io",author:{name:"HarperDB",email:"support@harperdb.io"},license:"SEE LICENSE IN LICENSE",scripts:{submodules:"git submodule update --init --recursive",build:"eslint -c ./.eslintbuild bin/ dataLayer/ security/ server/ sqlTranslator/ upgrade/ utility/ validation/",pretty:"eslint --fix bin/ dataLayer/ security/ server/ sqlTranslator/ upgrade/ utility/ validation/","cover:test":"pm2 kill && rimraf ./.nyc_output/* && node utility/devops/register.js --reset_license && nyc --no-clean --reporter=lcovonly npm run test:apitests && nyc --no-clean --reporter=lcovonly npm run test:resources && nyc --no-clean --reporter=lcovonly npm run test:logging && nyc --no-clean --reporter=lcovonly npm run test:upgrade && nyc --no-clean --reporter=lcovonly npm run test:nats && nyc --no-clean --reporter=lcovonly npm run test:cfserver && nyc --no-clean --reporter=lcovonly npm run test:hdbserver && nyc --no-clean --reporter=lcovonly npm run test:bin && nyc --no-clean --reporter=lcovonly npm run test:main && nyc merge .nyc_output coverage.json && node ./utility/devops/register.js --reset_license",test:"pm2 kill && rimraf ./.nyc_output/* && node utility/devops/register.js --reset_license && npm run test:apitests && npm run test:resources && npm run test:logging && npm run test:upgrade && npm run test:nats && npm run test:cfserver && npm run test:hdbserver && npm run test:bin && npm run test:main && nyc merge .nyc_output coverage.json && node ./utility/devops/register.js --reset_license","test:resources":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/resources/**/*.js' --config '../unitTests/.mocharc.json'","test:bin":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/bin/**/*.js' --config '../unitTests/.mocharc.json'","test:main":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/**/*.js' --config '../unitTests/.mocharc-main.json'","test:lmdbbridge":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/dataLayer/harperBridge/lmdbBridge/**/*.js' --config '../unitTests/.mocharc.json'","test:lmdbutility":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/utility/lmdb/**/*.js' --config '../unitTests/.mocharc.json'","test:hdbserver":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/server/harperdb/hdbServer-test.js' --config '../unitTests/.mocharc.json'","test:cfserver":"npm run submodules && cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/server/fastifyRoutes/customFunctionsServer-test.js' --config '../unitTests/.mocharc.json'","test:nats":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/server/nats/**/*.js' --config '../unitTests/.mocharc.json'","test:upgrade":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/upgrade/**/*.js' --config '../unitTests/.mocharc.json'","test:apitests":"pm2 kill && cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/apiTests/**/*-test.mjs' --config '../unitTests/.mocharc.json'","test:logging":"cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/utility/logging/*.js' --config '../unitTests/.mocharc.json'","test:ci":" cd bin/ && ../node_modules/mocha/bin/_mocha '../unitTests/**/*.js' --retries 3 --config '../unitTests/.mocharc-main.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/dataLayer/harperBridge/lmdbBridge/**/*.js' --parallel --retries 3 --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/utility/lmdb/**/*.js' --parallel --retries 3 --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/server/harperdb/hdbServer-test.js' --parallel --retries 3 --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/server/customFunctions/customFunctionsServer-test.js' --parallel --retries 3 --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/upgrade/**/*.js' --parallel --retries 3 --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter && ../node_modules/mocha/bin/_mocha '../unitTests/server/nats/**/*.js' --config '../unitTests/.mocharc.json' --reporter mocha-teamcity-reporter","hdb-check":"./utility/devops/hdb-check.sh","download-prebuilds":"node ./utility/devops/build/download-prebuilds.js",prebuild:"date",postinstall:"node ./launchServiceScripts/launchInstallNATSServer.js",build_nats_dependency:"node ./utility/devops/nats/builder.js",coverage:"nyc --reporter=lcov npm test"},dependencies:{"@aws-sdk/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.7",jsonwebtoken:"9.0.2",lmdb:"3.0.0-beta.13",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.19.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"},alasql:{xlsx:"0.18.5"}},optionalDependencies:{bufferutil:"^4.0.7","utf-8-validate":"^5.0.10"}}});var lu={};qe(lu,{addAnalyticsListener:()=>uu,recordAction:()=>kr,recordActionBinary:()=>cn,setAnalyticsEnabled:()=>m3});function m3(e){DD=e}function kr(e,t,r,n,s){if(!DD)return;let i=t+(r?"-"+r:"");n!==void 0&&(i+="-"+n),s!==void 0&&(i+="-"+s);let o=Sd.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},Sd.set(i,o)}md||p3()}function cn(e,t,r,n,s){kr(!!e,t,r,n,s)}function uu(e){UD.push(e)}function p3(){md=performance.now(),setTimeout(async()=>{let e=performance.now()-md;md=0;let t=[],r={time:Date.now(),period:e,threadId:io.threadId,metrics:t};for(let[s,i]of Sd){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 PD){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 vD()}let n=process.memoryUsage();t.push({metric:"memory",threadId:io.threadId,byThread:!0,...n});for(let s of UD)s(t);Sd=new Map,io.parentPort?io.parentPort.postMessage({type:MD,report:r}):xD({report:r})},LD).unref()}async function S3(e,t=6e4){let r=AS(),n=BD(),s=new Promise(p=>{let S=performance.now();setImmediate(()=>{let T=performance.now();T-S>5e3&&(0,ou.warn)("Unusually high event queue latency on the main thread of "+Math.round(T-S)+"ms"),S=performance.now()}),n.primaryStore.prefetch([1],()=>{let T=performance.now();T-S>5e3&&(0,ou.warn)("Unusually high task queue latency on the main thread of "+Math.round(T-S)+"ms"),p(T-S)})}),i;for(let p of n.primaryStore.getRange({start:1/0,end:!1,reverse:!0}))if(p.value?.time){i=p.value.time;break}if(Date.now()-t<i)return;let o,c=new Map,u=new Map,_=[],l;for(let{key:p,value:S}of r.primaryStore.getRange({start:i||!1,exclusiveStart:!0,end:1/0})){if(!S)continue;if(o){if(p>o+t)break}else o=p;l=p;let{metrics:T,threadId:A}=S;for(let R of T||[]){let{path:M,method:x,type:P,metric:k,count:B,total:X,distribution:z,threads:J,...me}=R;B||(B=1);let ce=k+(M?"-"+M:"");x!==void 0&&(ce+="-"+x),P!==void 0&&(ce+="-"+P);let de=c.get(ce);if(de){if(de.threads){let Be=de.threads[A];if(Be)de=Be;else{de.threads[A]=Object.assign({},me);continue}}de.count||(de.count=1);let Le=de.count;for(let Be in me){let Lt=me[Be];typeof Lt=="number"&&(de[Be]=(de[Be]*Le+Lt*B)/(Le+B))}de.count+=B,X>=0&&(de.total+=X,de.ratio=de.total/de.count)}else de=Object.assign({period:t},R),delete de.distribution,c.set(ce,de),de.byThread&&(de.threads=[],de.threads[A]=Object.assign({},me),_.push(de));if(z){z=z.map(Be=>typeof Be=="number"?{value:Be,count:1}:Be);let Le=u.get(ce);Le?Le.push(...z):u.set(ce,z)}}await vD()}for(let p of _){let{path:S,method:T,type:A,metric:R,count:M,total:x,distribution:P,threads:k,...B}=p;k=k.filter(X=>X);for(let X in B){if(typeof p[X]!="number")continue;let z=0;for(let J of k){let me=J[X];typeof me=="number"&&(z+=me)}p[X]=z}p.count=k.length,delete p.threads,delete p.byThread}for(let[p,S]of u){let T=c.get(p);S.sort((Be,Lt)=>Be.value>Lt.value?1:-1);let A=T.count-1,R=[],M=0,x=0,P;for(let Be of PD){let Lt=A*Be;for(;M<Lt;)P=S[x++],M+=P.count,x===1&&M--;let Wl=S[x>1?x-2:0];P||(P=S[0]),R.push(P.value-(P.value-Wl.value)*(M-Lt)/P.count)}let[k,B,X,z,J,me,ce,de,Le]=R;Object.assign(T,{p1:k,p10:B,p25:X,median:z,p75:J,p90:me,p95:ce,p99:de,p999:Le})}let d;for(let[p,S]of c)S.id=(0,pd.getNextMonotonicTime)(),S.time=l,n.primaryStore.put(S.id,S,{append:!0}).then(T=>{T||n.primaryStore.put(S.id,S)}),d=!0;let f=Date.now(),{idle:E,active:h}=performance.eventLoopUtilization();if(d||h*10>E){let p=(0,pd.getNextMonotonicTime)(),S={id:p,metric:"main-thread-utilization",idle:E-AD,active:h-OD,taskQueueLatency:await s,time:f,...process.memoryUsage()};n.primaryStore.put(p,S,{append:!0}).then(T=>{T||n.primaryStore.put(p,S)})}AD=E,OD=h}async function bD(e,t){let r=Date.now()-t;for(let n of e.primaryStore.getKeys({start:!1,end:r}))e.primaryStore.remove(n)}function AS(){return yD||(yD=lt({table:"hdb_raw_analytics",database:"system",audit:!1,trackDeletes:!1,attributes:[{name:"id",isPrimaryKey:!0},{name:"action"},{name:"metrics"}]}))}function BD(){return ND||(ND=lt({table:"hdb_analytics",database:"system",audit:!1,trackDeletes:!1,attributes:[{name:"id",isPrimaryKey:!0},{name:"metric"},{name:"path"},{name:"method"},{name:"type"}]}))}function R3(){HD=!0;let e=(0,cu.get)(RS.CONFIG_PARAMS.ANALYTICS_AGGREGATEPERIOD)*1e3;e&&setInterval(async()=>{await S3(LD,e),await bD(AS(),T3),await bD(BD(),g3)},Math.min(e/2,2147483647)).unref()}function xD(e,t){let r=e.report;r.threadId=t?.threadId||io.threadId;for(let n of r.metrics)n.metric==="bytes-sent"&&(ID+=n.mean*n.count);r.totalBytesProcessed=ID,t&&(r.metrics.push({metric:"utilization",...t.performance.eventLoopUtilization(wD.get(t))}),wD.set(t,t.performance.eventLoopUtilization())),r.id=(0,pd.getNextMonotonicTime)(),AS().primaryStore.put(r.id,r),HD||R3(),A3&&(GD=b3(r))}async function b3(e){if(await GD,!li){let r=(0,au.dirname)((0,ou.getLogFilePath)());try{li=await(0,gS.open)((0,au.join)(r,"analytics.log"),"r+")}catch{li=await(0,gS.open)((0,au.join)(r,"analytics.log"),"w+")}}let t=(await li.stat()).size;if(t>O3){let r=Buffer.alloc(t);await li.read(r,{position:0}),r=r.subarray(r.indexOf(10,r.length/2)+1),await li.write(r,{position:0}),await li.truncate(r.length),t=r.length}await li.write(JSON.stringify(e)+`
|
|
8
|
+
`,t)}var io,CD,ou,au,gS,pd,cu,RS,Sd,DD,md,LD,MD,UD,PD,AD,OD,vD,T3,g3,yD,ND,HD,ID,wD,A3,GD,li,O3,ws=ge(()=>{io=require("worker_threads"),CD=v(Ke());Re();ou=v($()),au=require("path"),gS=require("fs/promises"),pd=v(Dr()),cu=v(ee()),RS=v(L());or();(0,cu.initSync)();Sd=new Map,DD=(0,cu.get)(RS.CONFIG_PARAMS.ANALYTICS_AGGREGATEPERIOD)>-1;a(m3,"setAnalyticsEnabled");a(kr,"recordAction");nt.recordAnalytics=kr;a(cn,"recordActionBinary");md=0,LD=1e3,MD="analytics-report",UD=[];a(uu,"addAnalyticsListener");PD=[.01,.1,.25,.5,.75,.9,.95,.99,.999,1];a(p3,"sendAnalytics");a(S3,"aggregation");AD=0,OD=0,vD=a(()=>new Promise(setImmediate),"rest");a(bD,"cleanup");T3=36e5,g3=31536e6;a(AS,"getRawAnalyticsTable");a(BD,"getAnalyticsTable");(0,CD.setChildListenerByType)(MD,xD);a(R3,"startScheduledTasks");ID=0,wD=new Map,A3=!1;a(xD,"recordAnalytics");O3=1e6;a(b3,"logAnalytics")});var wS=g((Tfe,zD)=>{"use strict";var{decode:y3}=require("msgpackr"),{isMainThread:mfe,parentPort:pfe,threadId:Sfe}=require("worker_threads"),_u=it(),ca=ke(),yS=L(),jt=$(),bS=ee(),N3=L(),{onMessageByType:I3}=Ke(),kD=Rs(),{recordAction:w3,recordActionBinary:C3}=(ws(),ie(lu)),{publishToStream:D3}=_u,{ConsumerEvents:qD}=require("nats"),L3=Pr(),{promisify:M3}=require("util"),VD=M3(setTimeout),Rd=1e4,Ad,gd,U3,P3,$D,du=new Map,ua=new Map;zD.exports={initialize:NS,ingestConsumer:IS,setSubscription:v3,setIgnoreOrigin:x3,getDatabaseSubscriptions:H3,updateConsumer:YD};async function NS(){I3(yS.ITC_EVENT_TYPES.NATS_CONSUMER_UPDATE,async n=>{await YD(n)}),$D=!0,jt.notify("Initializing clustering ingest service.");let{connection:e,jsm:t,js:r}=await _u.getNATSReferences();Ad=e,gd=e.info.server_name,U3=t,P3=r}a(NS,"initialize");async function YD(e){if(e.status==="start"){let{js:t,jsm:r}=await KD(e.node_domain_name);IS(e.stream_name,t,r,e.node_domain_name)}else if(e.status==="stop"){let t=du.get(e.stream_name+e.node_domain_name);t&&(jt.notify("Closing ingest consumer for node:",e.node_domain_name,"stream:",e.stream_name),await t.close?.(),du.set(e.stream_name+e.node_domain_name,"close")),ua.get(e.node_domain_name)==="failed"&&ua.set(e.node_domain_name,"close")}}a(YD,"updateConsumer");var Od=new Map;function v3(e,t,r){let n=Od.get(e);n||Od.set(e,n=new Map),n.set(t,r),$D||NS().then(B3)}a(v3,"setSubscription");async function B3(){let e=await L3.searchByValue({database:"system",table:"hdb_nodes",search_attribute:"name",search_value:"*"});for await(let t of e){let r=t.name+ca.SERVER_SUFFIX.LEAF,n,s;for(let i of t.subscriptions)if(i.subscribe===!0){if(!n&&({js:n,jsm:s}=await KD(r),!n))break;let{schema:o,table:c}=i,u=kD.createNatsTableStreamName(o,c);IS(u,n,s,r)}}}a(B3,"accessConsumers");async function KD(e){let t,r,n=1;for(;!r;)try{t=await Ad.jetstream({domain:e}),r=await Ad.jetstreamManager({domain:e,checkAPI:!1})}catch(s){if(ua.get(e)==="close")break;ua.set(e,"failed"),n%10===1&&jt.warn("Nats ingest attempting to connect to:",e,"Nats error:",s.message);let i=n++*100<Rd?n++*100:Rd;await VD(i)}return{js:t,jsm:r}}a(KD,"connectToRemoteJS");function H3(){return Od}a(H3,"getDatabaseSubscriptions");var WD;function x3(e){WD=e}a(x3,"setIgnoreOrigin");var QD=100,FD=new Array(QD),Td=0;async function IS(e,t,r,n){let{connection:s}=await _u.getNATSReferences();Ad=s,gd=s.info.server_name;let i,o=1;for(;!i;)try{i=await t.consumers.get(e,gd),jt.notify("Initializing ingest consumer for node:",n,"stream:",e)}catch(_){if(ua.get(n)==="close")break;o%10===1&&jt.warn("Nats ingest error getting consumer:",n,"stream:",e,"Nats error:",_.message),_.code==="404"&&(jt.notify("Nats ingest creating consumer for node:",n,"stream:",e),i=await _u.createConsumer(r,e,gd,new Date(Date.now()).toISOString()));let l=o++*100<Rd?o++*100:Rd;await VD(l)}let c=!1,u;for(;!c;){if(du.get(e+n)==="close"||ua.get(n)==="close"){du.delete(e+n),c=!0;continue}u=await i.consume({max_messages:bS.get(yS.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXCONSUMEMSGS)??100}),du.set(e+n,u);let _=!1;(async()=>{for await(let l of await u.status())if(l.type===qD.ConsumerDeleted&&(await u.close(),c=!0),l.type===qD.HeartbeatsMissed){let d=l.data;jt.trace(`${d} clustering ingest consumer heartbeats missed, node: ${n} stream: ${u.consumer.stream}`),d===2&&(jt.warn(`Restarting clustering ingest consumer due to missed heartbeat threshold being met, node: ${n} stream: ${u.consumer.stream}`),u.stop(),_=!0)}})();try{for await(let l of u)await FD[Td],FD[Td]=G3(l).catch(d=>{jt.error(d)}),++Td>=QD&&(Td=0)}catch(l){l.message==="consumer deleted"?(jt.notify("Nats consumer deleted, closing messages for node:",n,"stream:",u.consumer.stream),await u.close(),c=!0):jt.error("Error consuming clustering ingest, restarting consumer",l)}_u.clearClientCache(),!c&&_&&await NS()}}a(IS,"ingestConsumer");async function G3(e){let t=y3(e.data);w3(e.data.length,"bytes-received",e.subject,t.operation,"ingest"),jt.trace("Nats message processor message size:",e?.msg?._msg?.size,"bytes");let r=e.headers,n=!1,s=bS.get(yS.CONFIG_PARAMS.CLUSTERING_NODENAME);r.has(ca.MSG_HEADERS.TRANSACTED_NODES)&&r.values(ca.MSG_HEADERS.TRANSACTED_NODES).indexOf(s)>-1&&(n=!0);let i=r.get(ca.MSG_HEADERS.ORIGIN);if(n||(n=i===s&&!WD),C3(n,"echo",e.subject,t.operation,"ingest"),n){e.ack();return}r.append(ca.MSG_HEADERS.TRANSACTED_NODES,s);try{let{operation:o,schema:c,next:u,table:_,records:l,hash_values:d,__origin:f,expiresAt:E}=t;jt.trace("processing message:",o,c,_,(l?"records: "+l.map(M=>M?.id):"")+(d?"ids: "+d:""),"with sequence:",e.seq),jt.trace(`messageProcessor nats msg id: ${e.headers.get(ca.MSG_HEADERS.NATS_MSG_ID)}`);let h;l||(l=d);let p=new Promise(M=>h=M),{timestamp:S,user:T,node_name:A}=f||{},R=Od.get(c)?.get(_);if(!R)throw new Error("Missing table for replication message",_);if(o==="define_schema")t.type=o,t.onCommit=h,R.send(t);else if(l.length===1&&!u)R.send({type:OS(o),value:l[0],id:d?.[0],expiresAt:E,timestamp:S,table:_,onCommit:h,user:T,nodeName:A});else{let M=l.map((x,P)=>({type:OS(o),value:x,expiresAt:E,id:d?.[P],table:_}));for(;u;)M.push({type:OS(u.operation),value:u.record,expiresAt:u.expiresAt,id:u.id,table:u.table}),u=u.next;R.send({type:"transaction",writes:M,table:_,timestamp:S,onCommit:h,user:T,nodeName:A})}bS.get(N3.CONFIG_PARAMS.CLUSTERING_REPUBLISHMESSAGES)!==!1&&D3(e.subject.split(".").slice(0,-1).join("."),kD.createNatsTableStreamName(c,_),e.headers,e.data),await p}catch(o){jt.error(o)}e.ack()}a(G3,"messageProcessor");function OS(e){switch(e){case"insert":case"upsert":case"update":return"put"}return e}a(OS,"convertOperation")});var it=g((Nfe,dL)=>{"use strict";var Pt=ee();Pt.initSync();var q3=require("fs-extra"),F3=require("semver"),hu=require("path"),{monotonicFactory:k3}=require("ulidx"),XD=k3(),V3=require("util"),jD=require("child_process"),$3=V3.promisify(jD.exec),Y3=jD.spawn,Vt=ke(),De=L(),bd=Q(),Bn=$(),yd=Rs(),K3=hd(),fu=lr(),{broadcast:W3,onMessageByType:Q3,getWorkerIndex:z3}=Ke(),{isMainThread:ZD}=require("worker_threads"),{Encoder:J3,decode:MS}=require("msgpackr"),eL=new J3,{isEmpty:uo}=bd,tL=an(),Rfe=48*36e11;ZD&&Q3(De.ITC_EVENT_TYPES.RESTART,()=>{Er=void 0,co=void 0});var{connect:X3,StorageType:j3,RetentionPolicy:Z3,AckPolicy:US,DeliverPolicy:PS,DiscardPolicy:eX,NatsConnection:Afe,JetStreamManager:Ofe,JetStreamClient:bfe,StringCodec:yfe,JSONCodec:tX,createInbox:vS,headers:rX,ErrorCode:JD}=require("nats"),{PACKAGE_ROOT:nX}=L(),sX=iu(),{recordAction:iX}=(ws(),ie(lu)),rL=tX(),oX="clustering",aX=sX.engines[Vt.NATS_SERVER_NAME],cX=hu.join(nX,"dependencies"),LS=hu.join(cX,`${process.platform}-${process.arch}`,Vt.NATS_BINARY_NAME),CS,DS,Eu,oo,ao;dL.exports={runCommand:nL,checkNATSServerInstalled:uX,createConnection:BS,getConnection:Nd,getJetStreamManager:mu,getJetStream:iL,getNATSReferences:Hn,getServerList:_X,createLocalStream:HS,listStreams:oL,deleteLocalStream:dX,getServerConfig:pu,listRemoteStreams:fX,viewStream:EX,viewStreamIterator:hX,publishToStream:mX,request:TX,reloadNATS:xS,reloadNATSHub:gX,reloadNATSLeaf:RX,extractServerName:SX,requestErrorHandler:AX,createLocalTableStream:lL,createTableStreams:yX,purgeTableStream:_L,purgeSchemaTableStreams:NX,getStreamInfo:IX,updateLocalStreams:CX,closeConnection:lX,getJsmServerName:Id,addNatsMsgHeader:aL,clearClientCache:sL,updateRemoteConsumer:OX,createConsumer:cL,updateConsumerIterator:bX};async function nL(e,t=void 0){let{stdout:r,stderr:n}=await $3(e,{cwd:t});if(n)throw new Error(n.replace(`
|
|
9
9
|
`,""));return r.replace(`
|
|
10
|
-
`,"")}a(YD,"runCommand");async function V3(){try{await g3.access(AS)}catch{return!1}let e=await YD(`${AS} --version`,void 0),t=e.substring(e.lastIndexOf("v")+1,e.length);return R3.eq(t,F3)}a(V3,"checkNATSServerInstalled");async function IS(e,t,r,s=!0,n="127.0.0.1"){if(!t&&!r){let o=await VD.getClusterUser();if(co(o))throw new Error("Unable to get nats connection. Cluster user is undefined.");t=o.username,r=o.decrypt_hash}Bs.trace("create nats connection called");let i=await L3({name:n,port:e,user:t,pass:r,maxReconnectAttempts:-1,waitOnFirstConnect:s,timeout:2e5,tls:{keyFile:Ut.get(De.CONFIG_PARAMS.CLUSTERING_TLS_PRIVATEKEY),certFile:Ut.get(De.CONFIG_PARAMS.CLUSTERING_TLS_CERTIFICATE),caFile:Ut.get(De.CONFIG_PARAMS.CLUSTERING_TLS_CERT_AUTH),rejectUnauthorized:!1}});return i.protocol.transport.socket.unref(),Bs.trace("create connection established a nats client connection with id",i?.info?.client_id),i.closed().then(o=>{o&&Bs.error("Error with Nats client connection, connection closed",o),KD()}),i}a(IS,"createConnection");function KD(){dr=void 0,io=void 0,oo=void 0,ao=void 0}a(KD,"clearClientCache");async function $3(){dr&&(await dr.drain(),dr=void 0,io=void 0,oo=void 0,ao=void 0)}a($3,"closeConnection");var dr,ao;async function gd(){return ao||(ao=IS(Ut.get(De.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),void 0,void 0),dr=await ao),dr||ao}a(gd,"getConnection");async function _u(){if(io)return io;co(dr)&&await gd();let{domain:e}=du(De.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);if(co(e))throw new Error("Error getting JetStream domain. Unable to get JetStream manager.");return io=await dr.jetstreamManager({domain:e,timeout:6e4}),io}a(_u,"getJetStreamManager");async function WD(){if(oo)return oo;co(dr)&&await gd();let{domain:e}=du(De.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);if(co(e))throw new Error("Error getting JetStream domain. Unable to get JetStream manager.");return oo=dr.jetstream({domain:e,timeout:6e4}),oo}a(WD,"getJetStream");async function Hs(){let e=dr||await gd(),t=io||await _u(),r=oo||await WD();return{connection:e,jsm:t,js:r}}a(Hs,"getNATSReferences");async function Y3(e){let t=Ut.get(De.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),{sys_name:r,decrypt_hash:s}=await VD.getClusterUser(),n=await IS(t,r,s),i=yS(),o=n.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 n.publish("$SYS.REQ.SERVER.PING.VARZ",void 0,{reply:i}),await n.publish("$SYS.REQ.SERVER.PING",void 0,{reply:i}),await n.flush(),await Sd.async_set_timeout(e),await o.drain(),await n.close(),await _,c}a(Y3,"getServerList");async function wS(e,t){let{jsm:r}=await Hs(),s=Ut.get(De.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE);s=s===null?0:s*1e9;let n=Ut.get(De.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS);n=n===null?-1:n;let i=Ut.get(De.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES);i=i===null?-1:i,await r.streams.add({name:e,storage:M3.File,retention:U3.Limits,subjects:t,discard:P3.Old,max_msgs:n,max_bytes:i,max_age:s})}a(wS,"createLocalStream");async function QD(){let{jsm:e}=await Hs(),t=await e.streams.list().next(),r=[];return t.forEach(s=>{r.push(s)}),r}a(QD,"listStreams");async function K3(e){let{jsm:t}=await Hs();await t.streams.delete(e)}a(K3,"deleteLocalStream");async function W3(e){let{connection:t}=await Hs(),r=[],s=yS(),n=t.subscribe(s),i=(async()=>{for await(let o of n)r.push($D.decode(o.data))})();return await t.publish(`$JS.${e}.API.STREAM.LIST`,void 0,{reply:s}),await t.flush(),await n.drain(),await i,r}a(W3,"listRemoteStreams");async function Q3(e,t=void 0,r=void 0){let{jsm:s,js:n}=await Hs(),i=qD(),o={durable_name:i,ack_policy:bS.Explicit};t&&(o.deliver_policy=NS.StartTime,o.opt_start_time=new Date(t).toISOString()),await s.consumers.add(e,o);let c=await n.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=OS(l.data),f={nats_timestamp:l.info.timestampNanos,nats_sequence:l.info.streamSequence,entry:d};if(l.headers&&(f.origin=l.headers.get(Vt.MSG_HEADERS.ORIGIN)),_.push(f),l.ack(),l.info.pending===0)break}return await c.delete(),_}a(Q3,"viewStream");async function*z3(e,t=void 0,r=void 0){let{jsm:s,js:n}=await Hs(),i=qD(),o={durable_name:i,ack_policy:bS.Explicit};t&&(o.deliver_policy=NS.StartTime,o.opt_start_time=new Date(t).toISOString()),await s.consumers.add(e,o);let c=await n.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=OS(_.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(Vt.MSG_HEADERS.ORIGIN)),yield f}if(_.ack(),_.info.pending===0)break}await c.delete()}a(z3,"viewStreamIterator");async function J3(e,t,r,s){Bs.trace(`publishToStream called with subject: ${e}, stream: ${t}, entries:`,s.operation),r=zD(s,r);let{js:n}=await Hs(),i=await Rd(),o=`${e}.${i}`,c=s instanceof Uint8Array?s:kD.encode(s);try{Bs.trace(`publishToStream publishing to subject: ${o}`),q3(c.length,"bytes-sent",e,s.operation,"replication"),await n.publish(o,c,{headers:r})}catch(u){if(u.code&&u.code.toString()==="503")return XD(async()=>{try{await n.publish(o,c,{headers:r})}catch{if(u.code&&u.code.toString()==="503"){Bs.trace(`publishToStream creating stream: ${t}`);let l=o.split(".");l[2]="*",await wS(t,[o]),await n.publish(o,c,{headers:r})}else throw u}});throw u}}a(J3,"publishToStream");function zD(e,t){t===void 0&&(t=B3());let r=Ut.get(De.CONFIG_PARAMS.CLUSTERING_NODENAME);return!t.has(Vt.MSG_HEADERS.ORIGIN)&&r&&t.append(Vt.MSG_HEADERS.ORIGIN,r),t}a(zD,"addNatsMsgHeader");function du(e){e=e.toLowerCase();let t=lu.join(Ut.get(De.CONFIG_PARAMS.ROOTPATH),G3);if(e===De.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase())return co(RS)&&(RS={port:cu.getConfigFromFile(De.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),server_name:cu.getConfigFromFile(De.CONFIG_PARAMS.CLUSTERING_NODENAME)+Vt.SERVER_SUFFIX.HUB,config_file:Vt.NATS_CONFIG_FILES.HUB_SERVER,pid_file_path:lu.join(t,Vt.PID_FILES.HUB),hdb_nats_path:t}),RS;if(e===De.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())return co(gS)&&(gS={port:cu.getConfigFromFile(De.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),server_name:cu.getConfigFromFile(De.CONFIG_PARAMS.CLUSTERING_NODENAME)+Vt.SERVER_SUFFIX.LEAF,config_file:Vt.NATS_CONFIG_FILES.LEAF_SERVER,domain:cu.getConfigFromFile(De.CONFIG_PARAMS.CLUSTERING_NODENAME)+Vt.SERVER_SUFFIX.LEAF,pid_file_path:lu.join(t,Vt.PID_FILES.LEAF),hdb_nats_path:t}),gS;Bs.error(`Unable to get Nats server config. Unrecognized process: ${e}`)}a(du,"getServerConfig");async function JD(e,t,r,s){try{await e.consumers.add(t,{ack_policy:bS.Explicit,durable_name:r,deliver_policy:NS.StartTime,opt_start_time:s})}catch(n){if(n.message!=="consumer already exists")throw n}}a(JD,"createConsumer");async function X3(e,t,r){await e.consumers.delete(t,r)}a(X3,"removeConsumer");function j3(e){return e.split(".")[1]}a(j3,"extractServerName");async function Z3(e,t,r=6e4,s=yS()){if(!Sd.isObject(t))throw new Error("data param must be an object");let n=kD.encode(t),{connection:i}=await Hs(),o={timeout:r};s&&(o.reply=s,o.noMux=!0);let c=await i.request(e,n,o);return OS(c.data)}a(Z3,"request");function CS(e){return new Promise(async(t,r)=>{let s=N3(AS,["--signal",`reload=${e}`],{cwd:__dirname}),n,i;s.on("error",o=>{r(o)}),s.stdout.on("data",o=>{i+=o.toString()}),s.stderr.on("data",o=>{n+=o.toString()}),s.stderr.on("close",o=>{n&&r(n),t(i)})})}a(CS,"reloadNATS");async function eX(){let{pid_file_path:e}=du(De.PROCESS_DESCRIPTORS.CLUSTERING_HUB);await CS(e)}a(eX,"reloadNATSHub");async function tX(){let{pid_file_path:e}=du(De.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);await CS(e)}a(tX,"reloadNATSLeaf");function rX(e,t,r){let s;switch(e.code){case xD.NoResponders:s=`Unable to ${t}, node '${r}' is not listening.`;break;case xD.Timeout:s=`Unable to ${t}, node '${r}' is listening but did not respond.`;break;default:s=e.message;break}return s}a(rX,"requestErrorHandler");async function sX(e,t){let r=t+Vt.SERVER_SUFFIX.LEAF,{connection:s}=await Hs(),{jsm:n}=await _X(r),{schema:i,table:o}=e,c=Td.createNatsTableStreamName(i,o),u=e.start_time?e.start_time:new Date(Date.now()).toISOString();await XD(async()=>{if(e.subscribe===!0)await JD(n,c,s.info.server_name,u);else try{await X3(n,c,s.info.server_name)}catch(_){Bs.trace(_)}})}a(sX,"updateRemoteConsumer");async function nX(e,t,r,s){let n=Td.createNatsTableStreamName(e,t),i=r+Vt.SERVER_SUFFIX.LEAF,o={type:De.ITC_EVENT_TYPES.NATS_CONSUMER_UPDATE,status:s,stream_name:n,node_domain_name:i};if(!FD&&C3()<Ut.get(De.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXINGESTTHREADS)){let{updateConsumer:c}=TS();await c(o)}await I3(o),s==="stop"&&await Sd.async_set_timeout(1e3)}a(nX,"updateConsumerIterator");function XD(e){return y3.writeTransaction(De.SYSTEM_SCHEMA_NAME,De.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,e)}a(XD,"exclusiveLock");async function jD(e,t){let r=Td.createNatsTableStreamName(e,t),s=await Rd(),n=cX(e,t,s);await wS(r,[n])}a(jD,"createLocalTableStream");async function iX(e){for(let t=0,r=e.length;t<r;t++){let s=e[t].schema,n=e[t].table;await jD(s,n)}}a(iX,"createTableStreams");async function ZD(e,t){if(Ut.get(De.CONFIG_PARAMS.CLUSTERING_ENABLED))try{let r=Td.createNatsTableStreamName(e,t),{jsm:s}=await Hs();await s.streams.purge(r)}catch(r){if(r.message==="stream not found")Bs.warn(r);else throw r}}a(ZD,"purgeTableStream");async function oX(e,t){if(Ut.get(De.CONFIG_PARAMS.CLUSTERING_ENABLED))for(let r=0,s=t.length;r<s;r++)await ZD(e,t[r])}a(oX,"purgeSchemaTableStreams");async function aX(e){return(await _u()).streams.info(e)}a(aX,"getStreamInfo");function cX(e,t,r){return`${Vt.SUBJECT_PREFIXES.TXN}.${e}${t?"."+t:""}.${r}`}a(cX,"createSubjectName");async function Rd(){if(uu)return uu;if(uu=(await _u())?.nc?.info?.server_name,uu===void 0)throw new Error("Unable to get jetstream manager server name");return uu}a(Rd,"getJsmServerName");async function uX(){let e=await _u(),t=await Rd(),r=await QD();for(let s of r){let n=s.config,i=n.subjects[0];if(!i)continue;let o=lX(s),c=i.split(".");if(c[c.length-1]===t&&!o||n.name==="__HARPERDB_WORK_QUEUE__")continue;let _=i.split(".");_[_.length-1]=t;let l=_.join(".");Bs.trace(`Updating stream subject name from: ${i} to: ${l}`),n.subjects[0]=l,await e.streams.update(n.name,n)}}a(uX,"updateLocalStreams");function lX(e){let{config:t}=e,r=!1,s=Ut.get(De.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE);s=s===null?0:s*1e9;let n=Ut.get(De.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES);n=n===null?-1:n;let i=Ut.get(De.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS);return i=i===null?-1:i,s!==t.max_age&&(t.max_age=s,r=!0),n!==t.max_bytes&&(t.max_bytes=n,r=!0),i!==t.max_msgs&&(t.max_msgs=i,r=!0),r}a(lX,"updateStreamLimits");async function _X(e){let t,r;try{t=await dr.jetstream({domain:e}),r=await dr.jetstreamManager({domain:e})}catch(s){throw Bs.error("Unable to connect to:",e),s}return{js:t,jsm:r}}a(_X,"connectToRemoteJS")});var fu=g((ufe,nL)=>{"use strict";var ca=p_(),ua=lD(),dX=$(),fX=require("uuid").v4,cfe=require("clone"),Od=On(),la=M(),EX=require("util"),li=ws(),{handleHDBError:fr,hdb_errors:hX}=se(),{HDB_ERROR_MSGS:Ad,HTTP_STATUS_CODES:Er}=hX,{SchemaEventMsg:bd}=Ls(),tL=nt(),{getDatabases:mX}=(Ae(),ne(Ge)),{transformReq:_a}=Q();nL.exports={createSchema:pX,createSchemaStructure:rL,createTable:SX,createTableStructure:sL,createAttribute:OX,dropSchema:TX,dropTable:gX,dropAttribute:RX,getBackup:bX};async function pX(e){let t=await rL(e);return Od.signalSchemaChange(new bd(process.pid,e.operation,e.schema)),t}a(pX,"createSchema");async function rL(e){let t=ca.schema_object(e);if(t)throw fr(t,t.message,Er.BAD_REQUEST,void 0,void 0,!0);if(_a(e),!await ua.checkSchemaExists(e.schema))throw fr(new Error,Ad.SCHEMA_EXISTS_ERR(e.schema),Er.BAD_REQUEST,la.LOG_LEVELS.ERROR,Ad.SCHEMA_EXISTS_ERR(e.schema),!0);return await li.createSchema(e),`database '${e.schema}' successfully created`}a(rL,"createSchemaStructure");async function SX(e){return _a(e),e.hash_attribute=e.primary_key??e.hash_attribute,await sL(e)}a(SX,"createTable");async function sL(e){let t=ca.create_table_object(e);if(t)throw fr(t,t.message,Er.BAD_REQUEST,void 0,void 0,!0);if(ca.validateTableResidence(e.residence),!await ua.checkSchemaTableExists(e.schema,e.table))throw fr(new Error,Ad.TABLE_EXISTS_ERR(e.schema,e.table),Er.BAD_REQUEST,la.LOG_LEVELS.ERROR,Ad.TABLE_EXISTS_ERR(e.schema,e.table),!0);let s={name:e.table,schema:e.schema,id:fX(),hash_attribute:e.hash_attribute};try{if(e.residence)if(global.clustering_on)s.residence=e.residence,await li.createTable(s,e);else throw fr(new Error,"Clustering does not appear to be enabled. Cannot insert table with property 'residence'.",Er.BAD_REQUEST);else await li.createTable(s,e);return`table '${e.schema}.${e.table}' successfully created.`}catch(n){throw n}}a(sL,"createTableStructure");async function TX(e){let t=!e.schema&&!e.database?new Error("database is required"):void 0,r=ca.schema_object(e),s=t??r;if(s)throw fr(s,s.message,Er.BAD_REQUEST,void 0,void 0,!0);_a(e);let n=await ua.checkSchemaExists(e.schema);if(n)throw fr(new Error,n,Er.NOT_FOUND,la.LOG_LEVELS.ERROR,n,!0);let i=await ua.schema_describe.describeSchema({schema:e.schema}),o=Object.keys(global.hdb_schema[e.schema]);return await li.dropSchema(e),Od.signalSchemaChange(new bd(process.pid,e.operation,e.schema)),await tL.purgeSchemaTableStreams(e.schema,o),`successfully deleted '${e.schema}'`}a(TX,"dropSchema");async function gX(e){let t=ca.table_object(e);if(t)throw fr(t,t.message,Er.BAD_REQUEST,void 0,void 0,!0);_a(e);let r=await ua.checkSchemaTableExists(e.schema,e.table);if(r)throw fr(new Error,r,Er.NOT_FOUND,la.LOG_LEVELS.ERROR,r,!0);return await li.dropTable(e),await tL.purgeTableStream(e.schema,e.table),`successfully deleted table '${e.schema}.${e.table}'`}a(gX,"dropTable");async function RX(e){let t=ca.attribute_object(e);if(t)throw fr(t,t.message,Er.BAD_REQUEST,void 0,void 0,!0);_a(e);let r=await ua.checkSchemaTableExists(e.schema,e.table);if(r)throw fr(new Error,r,Er.NOT_FOUND,la.LOG_LEVELS.ERROR,r,!0);if(e.attribute===global.hdb_schema[e.schema][e.table].hash_attribute)throw fr(new Error,"You cannot drop a hash attribute",Er.BAD_REQUEST,void 0,void 0,!0);if(la.TIME_STAMP_NAMES.indexOf(e.attribute)>=0)throw fr(new Error,`cannot drop internal timestamp attribute: ${e.attribute}`,Er.BAD_REQUEST,void 0,void 0,!0);try{return await li.dropAttribute(e),AX(e),Od.signalSchemaChange(new bd(process.pid,e.operation,e.schema,e.table,e.attribute)),`successfully deleted attribute '${e.attribute}'`}catch(s){throw dX.error(`Got an error deleting attribute ${EX.inspect(e)}.`),s}}a(RX,"dropAttribute");function AX(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(AX,"dropAttributeFromGlobal");async function OX(e){_a(e);let t=mX()[e.schema][e.table].attributes;for(let{name:r}of t)if(r===e.attribute)throw fr(new Error,`attribute '${e.attribute}' already exists in ${e.schema}.${e.table}`,Er.BAD_REQUEST,void 0,void 0,!0);return await li.createAttribute(e),Od.signalSchemaChange(new bd(process.pid,e.operation,e.schema,e.table,e.attribute)),`attribute '${e.schema}.${e.table}.${e.attribute}' successfully created.`}a(OX,"createAttribute");function bX(e){return li.getBackup(e)}a(bX,"getBackup")});var oL=g((_fe,iL)=>{"use strict";var{OPERATIONS_ENUM:NX}=M(),DS=class{static{a(this,"ReadAuditLogObject")}constructor(t,r,s=void 0,n=void 0){this.operation=NX.READ_AUDIT_LOG,this.schema=t,this.table=r,this.search_type=s,this.search_values=n}};iL.exports=DS});var LS=g((Efe,_L)=>{"use strict";var yX=ws(),ffe=oL(),Nd=Q(),yd=M(),IX=ee(),{handleHDBError:aL,hdb_errors:wX}=se(),{HDB_ERROR_MSGS:cL,HTTP_STATUS_CODES:uL}=wX,CX=Object.values(yd.READ_AUDIT_LOG_SEARCH_TYPES_ENUM),lL="To use this operation audit log must be enabled in harperdb-config.yaml";_L.exports=DX;async function DX(e){if(Nd.isEmpty(e.schema))throw new Error(cL.SCHEMA_REQUIRED_ERR);if(Nd.isEmpty(e.table))throw new Error(cL.TABLE_REQUIRED_ERR);if(!IX.get(yd.CONFIG_PARAMS.LOGGING_AUDITLOG))throw aL(new Error,lL,uL.BAD_REQUEST,yd.LOG_LEVELS.ERROR,lL,!0);let t=Nd.checkSchemaTableExist(e.schema,e.table);if(t)throw aL(new Error,t,uL.NOT_FOUND,yd.LOG_LEVELS.ERROR,t,!0);if(!Nd.isEmpty(e.search_type)&&CX.indexOf(e.search_type)<0)throw new Error(`Invalid search_type '${e.search_type}'`);return await yX.readAuditLog(e)}a(DX,"readAuditLog")});var fL=g((mfe,dL)=>{"use strict";var{OPERATIONS_ENUM:LX}=M(),MS=class{static{a(this,"GetBackupObject")}constructor(t,r,s=void 0,n=void 0){this.operation=LX.GET_BACKUP,this.schema=t,this.table=r}};dL.exports=MS});var mL=g((gfe,hL)=>{"use strict";var MX=ws(),Sfe=fL(),US=Q(),UX=M(),Tfe=ee(),{handleHDBError:PX,hdb_errors:vX}=se(),{HDB_ERROR_MSGS:EL,HTTP_STATUS_CODES:BX}=vX;hL.exports=HX;async function HX(e){if(US.isEmpty(e.schema))throw new Error(EL.SCHEMA_REQUIRED_ERR);if(US.isEmpty(e.table))throw new Error(EL.TABLE_REQUIRED_ERR);let t=US.checkSchemaTableExist(e.schema,e.table);if(t)throw PX(new Error,t,BX.NOT_FOUND,UX.LOG_LEVELS.ERROR,t,!0);return await MX.getBackup(read_audit_log_object)}a(HX,"getBackup")});var AL=g((Afe,RL)=>{var _i=require("validate.js"),SL=Xe(),da=M(),{handleHDBError:xX,hdb_errors:qX}=se(),{HDB_ERROR_MSGS:_t,HTTP_STATUS_CODES:GX}=qX,PS=a(()=>({role:{presence:!0,format:"[\\w\\-\\_]+"},id:{presence:!0,format:"[\\w\\-\\_]+"},permission:{presence:!0}}),"constraintsTemplate"),FX={STRUCTURE_USER:"structure_user"},pL=Object.values(da.ROLE_TYPES_ENUM),kX="attribute_permissions",VX="attribute_name",{PERMS_CRUD_ENUM:fa}=da,$X=[kX,...Object.values(fa)],TL=[fa.READ,fa.INSERT,fa.UPDATE],YX=[VX,...TL];function KX(e){let t=PS();return t.role.presence=!0,t.id.presence=!1,t.permission.presence=!0,gL(e,t)}a(KX,"addRoleValidation");function WX(e){let t=PS();return t.role.presence=!1,t.id.presence=!0,t.permission.presence=!0,gL(e,t)}a(WX,"alterRoleValidation");function QX(e){let t=PS();return t.role.presence=!1,t.id.presence=!0,t.permission.presence=!1,SL.validateObject(e,t)}a(QX,"dropRoleValidation");var zX=["operation","role","id","permission","hdb_user","hdb_auth_header"];function gL(e,t){let r={main_permissions:[],schema_permissions:{}},s=Object.keys(e),n=[];for(let o=0,c=s.length;o<c;o++)zX.includes(s[o])||n.push(s[o]);n.length>0&&pt(_t.INVALID_ROLE_JSON_KEYS(n),r);let i=SL.validateObject(e,t);if(i&&i.message.split(",").forEach(o=>{pt(o,r)}),e.permission){let o=JX(e);o&&pt(o,r),pL.forEach(c=>{e.permission[c]&&!_i.isBoolean(e.permission[c])&&pt(_t.SU_CU_ROLE_BOOLEAN_ERROR(c),r)})}for(let o in e.permission)if(pL.indexOf(o)<0){if(o===FX.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]||pt(_t.SCHEMA_NOT_FOUND(d),r)}continue}pt(_t.STRUCTURE_USER_ROLE_TYPE_ERROR(o),r);continue}let c=e.permission[o];if(!o||!global.hdb_schema[o]){pt(_t.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]){pt(_t.TABLE_NOT_FOUND(o,u),r);continue}if(Object.keys(_).forEach(l=>{$X.includes(l)||pt(_t.INVALID_PERM_KEY(l),r,o,u)}),Object.values(fa).forEach(l=>{_i.isDefined(_[l])?_i.isBoolean(_[l])||pt(_t.TABLE_PERM_NOT_BOOLEAN(l),r,o,u):pt(_t.TABLE_PERM_MISSING(l),r,o,u)}),_i.isDefined(_.attribute_permissions)){if(!_i.isArray(_.attribute_permissions)){pt(_t.ATTR_PERMS_NOT_ARRAY,r,o,u);continue}}else{pt(_t.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=>{!YX.includes(p)&&p!==fa.DELETE&&pt(_t.INVALID_ATTR_PERM_KEY(p),r,o,u)}),!_i.isDefined(E.attribute_name)){pt(_t.ATTR_PERM_MISSING_NAME,r,o,u);continue}let h=E.attribute_name;if(!l.includes(h)){pt(_t.INVALID_ATTRIBUTE_IN_PERMS(h),r,o,u);continue}TL.forEach(p=>{_i.isDefined(E[p])?_i.isBoolean(E[p])||pt(_t.ATTR_PERM_NOT_BOOLEAN(p,h),r,o,u):pt(_t.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}`;pt(_t.MISMATCHED_TABLE_ATTR_PERMS(f),r,o,u)}}}}return XX(r)}a(gL,"customValidate");RL.exports={addRoleValidation:KX,alterRoleValidation:WX,dropRoleValidation:QX};function JX(e){let{operation:t,permission:r}=e;if(t===da.OPERATIONS_ENUM.ADD_ROLE||t===da.OPERATIONS_ENUM.ALTER_ROLE){let s=r.super_user===!0,n=r.cluster_user===!0;if(Object.keys(r).length>1&&(s||n)){if(n&&s)return _t.SU_CU_ROLE_COMBINED_ERROR;{let o=r.super_user?da.ROLE_TYPES_ENUM.SUPER_USER:da.ROLE_TYPES_ENUM.CLUSTER_USER;return _t.SU_CU_ROLE_NO_PERMS_ALLOWED(o)}}}return null}a(JX,"validateNoSUPerms");function XX(e){let{main_permissions:t,schema_permissions:r}=e;if(t.length>0||Object.keys(r).length>0){let s={error:_t.ROLE_PERMS_ERROR,...e};return xX(new Error,s,GX.BAD_REQUEST)}else return null}a(XX,"generateRolePermResponse");function pt(e,t,r,s){if(!r)t.main_permissions.push(e);else{let n=s?r+"_"+s:r;t.schema_permissions[n]?t.schema_permissions[n].push(e):t.schema_permissions[n]=[e]}}a(pt,"addPermError")});var GS=g((bfe,yL)=>{"use strict";var OL=Ur(),bL=Mr(),jX=ni(),BS=AL(),HS=On(),ZX=require("uuid").v4,ej=require("util"),Id=M(),tj=Q(),xS=bL.searchByValue,rj=bL.searchByHash,sj=ej.promisify(jX.delete),nj=tn(),ij=ra(),{hdb_errors:oj,handleHDBError:uo}=se(),{HDB_ERROR_MSGS:NL,HTTP_STATUS_CODES:Eu}=oj,{UserEventMsg:qS}=Ls();yL.exports={addRole:aj,alterRole:cj,dropRole:uj,listRoles:lj};function vS(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(vS,"scrubRoleDetails");async function aj(e){let t=BS.addRoleValidation(e);if(t)throw t;e=vS(e);let r={schema:"system",table:"hdb_role",search_attribute:"role",search_value:e.role,hash_attribute:"id",get_attributes:["*"]},s;try{s=Array.from(await xS(r)||[])}catch(i){throw uo(i)}if(s&&s.length>0)throw uo(new Error,NL.ROLE_ALREADY_EXISTS(e.role),Eu.CONFLICT,void 0,void 0,!0);e.id||(e.id=ZX());let n={operation:"insert",schema:"system",table:"hdb_role",hash_attribute:"id",records:[e]};return await OL.insert(n),HS.signalUserChange(new qS(process.pid)),e=vS(e),e}a(aj,"addRole");async function cj(e){let t=BS.alterRoleValidation(e);if(t)throw t;e=vS(e);let r={operation:"update",schema:"system",table:"hdb_role",records:[e]},s;try{s=await OL.update(r)}catch(n){throw uo(n)}if(s&&s?.message==="updated 0 of 1 records")throw uo(new Error,"Invalid role id",Eu.BAD_REQUEST,void 0,void 0,!0);return await HS.signalUserChange(new qS(process.pid)),e}a(cj,"alterRole");async function uj(e){let t=BS.dropRoleValidation(e);if(t)throw uo(new Error,t,Eu.BAD_REQUEST,void 0,void 0,!0);let r=new ij(Id.SYSTEM_SCHEMA_NAME,Id.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME,[e.id],["role"]),s=Array.from(await rj(r));if(s.length===0)throw uo(new Error,NL.ROLE_NOT_FOUND,Eu.NOT_FOUND,void 0,void 0,!0);let n=new nj(Id.SYSTEM_SCHEMA_NAME,Id.SYSTEM_TABLE_NAMES.USER_TABLE_NAME,"role",e.id,void 0,["username","active"]),i=Array.from(await xS(n)),o=!1;if(tj.isEmptyOrZeroLength(i)===!1){for(let u=0;u<i.length;u++)if(i[u].active===!0){o=!0;break}}if(o===!0)throw uo(new Error,`Cannot drop role ${s[0].role} as it has active user(s) tied to this role`,Eu.CONFLICT,void 0,void 0,!0);let c={table:"hdb_role",schema:"system",hash_values:[e.id]};return await sj(c),HS.signalUserChange(new qS(process.pid)),`${s[0].role} successfully deleted`}a(uj,"dropRole");async function lj(){return xS({table:"hdb_role",schema:"system",hash_attribute:"id",search_attribute:"id",search_value:"*",get_attributes:["*"]})}a(lj,"listRoles")});var DL=g((yfe,CL)=>{"use strict";var _j=ee(),di=require("joi"),dj=Xe(),IL=require("moment"),fj=require("fs-extra"),FS=require("path"),Ej=require("lodash"),hu=M(),{LOG_LEVELS:lo}=M(),hj="YYYY-MM-DD hh:mm:ss",mj=FS.resolve(__dirname,"../logs");CL.exports=function(e){return dj.validateBySchema(e,pj)};var pj=di.object({from:di.custom(wL),until:di.custom(wL),level:di.valid(lo.NOTIFY,lo.FATAL,lo.ERROR,lo.WARN,lo.INFO,lo.DEBUG,lo.TRACE),order:di.valid("asc","desc"),limit:di.number().min(1),start:di.number().min(0),log_name:di.custom(Sj)});function wL(e,t){if(IL(e,IL.ISO_8601).format(hj)==="Invalid date")return t.message(`'${t.state.path[0]}' date '${e}' is invalid.`)}a(wL,"validateDatetime");function Sj(e,t){if(Ej.invert(hu.LOG_NAMES)[e]===void 0)return t.message(`'log_name' '${e}' is invalid.`);let s=_j.get(hu.HDB_SETTINGS_NAMES.LOG_PATH_KEY),n=e===void 0?hu.LOG_NAMES.HDB:e,i=n===hu.LOG_NAMES.INSTALL?FS.join(mj,hu.LOG_NAMES.INSTALL):FS.join(s,n);return fj.existsSync(i)?null:t.message(`'log_name' '${e}' does not exist.`)}a(Sj,"validateReadLogPath")});var VS=g((wfe,ML)=>{"use strict";var wd=M(),Tj=$(),gj=ee(),Rj=DL(),kS=require("path"),LL=require("fs-extra"),{once:Aj}=require("events"),{handleHDBError:Oj,hdb_errors:bj}=se(),{PACKAGE_ROOT:Nj}=M(),yj=kS.join(Nj,"logs"),Ij=1e3,wj=200;ML.exports=Cj;async function Cj(e){let t=Rj(e);if(t)throw Oj(t,t.message,bj.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0);let r=gj.get(wd.HDB_SETTINGS_NAMES.LOG_PATH_KEY),s=e.log_name===void 0?wd.LOG_NAMES.HDB:e.log_name,n=s===wd.LOG_NAMES.INSTALL?kS.join(yj,wd.LOG_NAMES.INSTALL):kS.join(r,s),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?Ij: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(LL.statSync(n).size-(h+5)*wj,0));let S=LL.createReadStream(n,{start:p});S.on("error",P=>{Tj.error(P)});let T=0,b=[],R="",L;S.on("data",P=>{let k=/(?:^|\n)(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:[\d\.]+Z) \[(.+?)]: /g;P=R+P;let B=0,X;for(;(X=k.exec(P))&&!S.destroyed;){L&&(L.message=P.slice(B,X.index),H(L));let[z,J,de]=X,ce=de.split("] ["),fe=ce[0],Le=ce[1];ce.splice(0,2),L={timestamp:J,thread:fe,level:Le,tags:ce,message:""},B=X.index+z.length}R=P.slice(B)}),S.on("end",P=>{S.destroyed||L&&(L.message=R.trim(),H(L))}),S.resume();function H(P){let k,B,X;switch(!0){case(i&&c&&_):k=new Date(P.timestamp),B=new Date(u),X=new Date(l),P.level===o&&k>=B&&k<=X&&T<E?T++:P.level===o&&k>=B&&k<=X&&(fi(P,f,b),T++,T===h&&S.destroy());break;case(i&&c):k=new Date(P.timestamp),B=new Date(u),P.level===o&&k>=B&&T<E?T++:P.level===o&&k>=B&&(fi(P,f,b),T++,T===h&&S.destroy());break;case(i&&_):k=new Date(P.timestamp),X=new Date(l),P.level===o&&k<=X&&T<E?T++:P.level===o&&k<=X&&(fi(P,f,b),T++,T===h&&S.destroy());break;case(c&&_):k=new Date(P.timestamp),B=new Date(u),X=new Date(l),k>=B&&k<=X&&T<E?T++:k>=B&&k<=X&&(fi(P,f,b),T++,T===h&&S.destroy());break;case i:P.level===o&&T<E?T++:P.level===o&&(fi(P,f,b),T++,T===h&&S.destroy());break;case c:k=new Date(P.timestamp),B=new Date(u),k>=B&&T<E?T++:k>=B&&T>=E&&(fi(P,f,b),T++,T===h&&S.destroy());break;case _:k=new Date(P.timestamp),X=new Date(l),k<=X&&T<E?T++:k<=X&&T>=E&&(fi(P,f,b),T++,T===h&&S.destroy());break;default:T<E?T++:(fi(P,f,b),T++,T===h&&S.destroy())}}return a(H,"onLogMessage"),await Aj(S,"close"),b}a(Cj,"readLog");function fi(e,t,r){t==="desc"?Dj(e,r):t==="asc"?Lj(e,r):r.push(e)}a(fi,"pushLineToResult");function Dj(e,t){let r=new Date(e.timestamp),s=0,n=t.length;for(;s<n;){let i=s+n>>>1;new Date(t[i].timestamp)>r?s=i+1:n=i}t.splice(s,0,e)}a(Dj,"insertDescending");function Lj(e,t){let r=new Date(e.timestamp),s=0,n=t.length;for(;s<n;){let i=s+n>>>1;new Date(t[i].timestamp)<r?s=i+1:n=i}t.splice(s,0,e)}a(Lj,"insertAscending")});var Cd=g((Ufe,BL)=>{"use strict";var $S=require("joi"),{string:mu,boolean:UL,date:Mj}=$S.types(),Uj=Xe(),{validateSchemaExists:Dfe,validateTableExists:Lfe,validateSchemaName:Mfe}=Js(),Pj=M(),vj=Fe(),PL=ee();PL.initSync();var Bj=mu.invalid(PL.get(Pj.CONFIG_PARAMS.CLUSTERING_NODENAME)).pattern(vj.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(),vL={operation:mu.valid("add_node","update_node","set_node_replication"),node_name:Bj,subscriptions:$S.array().items({table:mu.optional(),schema:mu.optional(),database:mu.optional(),subscribe:UL.required(),publish:UL.required().custom(xj),start_time:Mj.iso()}).min(1).required()};function Hj(e){return Uj.validateBySchema(e,$S.object(vL))}a(Hj,"addUpdateNodeValidator");function xj(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(xj,"checkForFalsy");BL.exports={addUpdateNodeValidator:Hj,validation_schema:vL}});var xL=g((vfe,HL)=>{var qj=Xe(),Gj={user:{presence:!0},schema:{presence:!0},table:{presence:!0},operation:{presence:!0}};HL.exports=function(e){return qj.validateObject(e,Gj)}});var Dd=g((Bfe,qL)=>{"use strict";var Fj=M().OPERATIONS_ENUM,YS=class{static{a(this,"UpdateObject")}constructor(t,r,s,n=void 0){this.operation=Fj.UPDATE,this.schema=t,this.table=r,this.records=s,this.__origin=n}};qL.exports=YS});var FL=g((xfe,GL)=>{"use strict";var kj={OPERATION:"operation",REFRESH:"refresh"},KS=class{static{a(this,"JWTTokens")}constructor(t,r){this.operation_token=t,this.refresh_token=r}},WS=class{static{a(this,"JWTRSAKeys")}constructor(t,r,s){this.public_key=t,this.private_key=r,this.passphrase=s}};GL.exports={JWTTokens:KS,TOKEN_TYPE_ENUM:kj,JWTRSAKeys:WS}});var Tu=g((Gfe,YL)=>{"use strict";var Su=require("jsonwebtoken"),QS=require("fs-extra"),zS=Q(),as=M(),{handleHDBError:hr,hdb_errors:Vj}=se(),{HTTP_STATUS_CODES:mr,AUTHENTICATION_ERROR_MSGS:pr}=Vj,pu=$(),kL=U_(),jS=is(),$j=Ur().update,Yj=Dd(),Kj=On(),{UserEventMsg:Wj}=Ls(),Ei=ee();Ei.initSync();var JS=require("path"),{JWTTokens:Qj,JWTRSAKeys:zj,TOKEN_TYPE_ENUM:Ld}=FL(),Jj=Ei.get(as.HDB_SETTINGS_NAMES.OPERATION_TOKEN_TIMEOUT_KEY)?Ei.get(as.HDB_SETTINGS_NAMES.OPERATION_TOKEN_TIMEOUT_KEY):"1d",Xj=Ei.get(as.HDB_SETTINGS_NAMES.REFRESH_TOKEN_TIMEOUT_KEY)?Ei.get(as.HDB_SETTINGS_NAMES.REFRESH_TOKEN_TIMEOUT_KEY):"30d",Md="RS256",XS;YL.exports={createTokens:jj,validateOperationToken:eZ,refreshOperationToken:Zj,validateRefreshToken:$L};async function jj(e){if(zS.isEmpty(e)||typeof e!="object")throw hr(new Error,pr.INVALID_AUTH_OBJECT,mr.BAD_REQUEST,void 0,void 0,!0);if(zS.isEmpty(e.username))throw hr(new Error,pr.USERNAME_REQUIRED,mr.BAD_REQUEST,void 0,void 0,!0);if(zS.isEmpty(e.password))throw hr(new Error,pr.PASSWORD_REQUIRED,mr.BAD_REQUEST,void 0,void 0,!0);let t;try{if(t=await jS.findAndValidateUser(e.username,e.password),!t)throw hr(new Error,pr.INVALID_CREDENTIALS,mr.UNAUTHORIZED,void 0,void 0,!0)}catch(f){throw pu.error(f),hr(new Error,pr.INVALID_CREDENTIALS,mr.UNAUTHORIZED,void 0,void 0,!0)}let r=await Ud(),s=!1,n=!1;t.role&&t.role.permission&&(s=t.role.permission.super_user===!0,n=t.role.permission.cluster_user===!0);let i={username:e.username,super_user:s,cluster_user:n},o=await VL(i,r.private_key,r.passphrase),c=await Su.sign(i,{key:r.private_key,passphrase:r.passphrase},{expiresIn:Xj,algorithm:Md,subject:Ld.REFRESH}),u=kL.hash(c),_=new Yj(as.SYSTEM_SCHEMA_NAME,as.SYSTEM_TABLE_NAMES.USER_TABLE_NAME,[{username:e.username,refresh_token:u}]),l,d;try{l=await $j(_)}catch(f){pu.error(f),d=f}if(d!==void 0||l.skipped_hashes.length>0)throw hr(new Error,pr.REFRESH_TOKEN_SAVE_FAILED,mr.INTERNAL_SERVER_ERROR);return Kj.signalUserChange(new Wj(process.pid)),new Qj(o,c)}a(jj,"createTokens");async function VL(e,t,r){return await Su.sign(e,{key:t,passphrase:r},{expiresIn:Jj,algorithm:Md,subject:Ld.OPERATION})}a(VL,"signOperationToken");async function Ud(){if(XS===void 0)try{let e=JS.join(Ei.getHdbBasePath(),as.LICENSE_KEY_DIR_NAME,as.JWT_ENUM.JWT_PASSPHRASE_NAME),t=JS.join(Ei.getHdbBasePath(),as.LICENSE_KEY_DIR_NAME,as.JWT_ENUM.JWT_PRIVATE_KEY_NAME),r=JS.join(Ei.getHdbBasePath(),as.LICENSE_KEY_DIR_NAME,as.JWT_ENUM.JWT_PUBLIC_KEY_NAME),s=(await QS.readFile(e)).toString(),n=(await QS.readFile(t)).toString(),i=(await QS.readFile(r)).toString();XS=new zj(i,n,s)}catch(e){throw pu.error(e),hr(new Error,pr.NO_ENCRYPTION_KEYS,mr.INTERNAL_SERVER_ERROR)}return XS}a(Ud,"getJWTRSAKeys");async function Zj(e){if(!e)throw hr(new Error,pr.INVALID_BODY,mr.BAD_REQUEST,void 0,void 0,!0);if(!e.refresh_token)throw hr(new Error,pr.REFRESH_TOKEN_REQUIRED,mr.BAD_REQUEST,void 0,void 0,!0);await $L(e.refresh_token);let t=await Ud(),r=await Su.decode(e.refresh_token);return{operation_token:await VL({username:r.username,super_user:r.super_user,cluster_user:r.cluster_user},t.private_key,t.passphrase)}}a(Zj,"refreshOperationToken");async function eZ(e){try{let t=await Ud(),r=await Su.verify(e,t.public_key,{algorithms:Md,subject:Ld.OPERATION});return await jS.findAndValidateUser(r.username,void 0,!1)}catch(t){throw pu.warn(t),t.name&&t.name==="TokenExpiredError"?hr(new Error,pr.TOKEN_EXPIRED,mr.FORBIDDEN):hr(new Error,pr.INVALID_TOKEN,mr.UNAUTHORIZED)}}a(eZ,"validateOperationToken");async function $L(e){let t;try{let r=await Ud(),s=await Su.verify(e,r.public_key,{algorithms:Md,subject:Ld.REFRESH});t=await jS.findAndValidateUser(s.username,void 0,!1)}catch(r){throw pu.warn(r),r.name&&r.name==="TokenExpiredError"?hr(new Error,pr.TOKEN_EXPIRED,mr.FORBIDDEN):hr(new Error,pr.INVALID_TOKEN,mr.UNAUTHORIZED)}if(!kL.validate(t.refresh_token,e))throw hr(new Error,pr.INVALID_TOKEN,mr.UNAUTHORIZED);return t}a($L,"validateRefreshToken")});var ZS=g((Vfe,QL)=>{"use strict";var tZ=xL(),Ea=require("passport"),rZ=require("passport-local").Strategy,sZ=require("passport-http").BasicStrategy,nZ=require("util"),iZ=is(),WL=nZ.callbackify(iZ.findAndValidateUser),kfe=Ir(),oZ=M(),KL=Tu();Ea.use(new rZ(function(e,t,r){WL(e,t,r)}));Ea.use(new sZ(function(e,t,r){WL(e,t,r)}));Ea.serializeUser(function(e,t){t(null,e)});Ea.deserializeUser(function(e,t){t(null,e)});function aZ(e,t,r){if(e.raw?.user!==void 0)return r(null,e.raw.user);let s,n;if(e.headers?.authorization){let o=e.headers.authorization.split(" ");s=o[0],n=o[1]}function i(o,c){return o?r(o):c?r(null,c):r("Must login")}switch(a(i,"handleResponse"),s){case"Basic":Ea.authenticate("basic",{session:!1},(o,c)=>{i(o,c)})(e,t,r);break;case"Bearer":e.body?.operation&&e.body.operation===oZ.OPERATIONS_ENUM.REFRESH_OPERATION_TOKEN?KL.validateRefreshToken(n).then(o=>{e.body.refresh_token=n,r(null,o)}).catch(o=>{r(o)}):KL.validateOperationToken(n).then(o=>{r(null,o)}).catch(o=>{r(o)});break;default:Ea.authenticate("local",{session:!1},function(o,c){i(o,c)})(e,t,r);break}}a(aZ,"authorize");function cZ(e,t){let r=tZ(e);if(r){t(r);return}let s={authorized:!0,messages:[]},n=e.user.role;if(!n?.permission)return t("Invalid role");let i=JSON.parse(n.permission);if(i.super_user)return t(null,s);if(!i[e.schema])return s.authorized=!1,s.messages.push(`Not authorized to access ${e.schema} schema`),t(null,s);if(!i[e.schema].tables[e.table])return s.authorized=!1,s.messages.push(`Not authorized to access ${e.table} table`),t(null,s);if(!i[e.schema].tables[e.table][e.operation])return s.authorized=!1,s.messages.push(`Not authorized to access ${e.operation} on ${e.table} table`),t(null,s);if(i[e.schema].tables[e.table].attribute_permissions&&!e.attributes)return s.authorized=!1,s.messages.push(`${e.schema}.${e.table} has attribute permissions. Missing attributes to validate`),t(null,s);if(i[e.schema].tables[e.table].attribute_permissions&&e.attributes){let o=i[e.schema].tables[e.table].attribute_permissions;for(let c in o)e.attributes.indexOf(o[c].attribute_name)>-1&&!o[c][e.operation]&&(s.authorized=!1,s.messages.push(`Not authorized to ${e.operation} ${o[c].attribute_name} `))}return t(null,s)}a(cZ,"checkPermissions");QL.exports={authorize:aZ,checkPermissions:cZ}});var hi=g((Yfe,zL)=>{"use strict";var eT=class{static{a(this,"Node")}constructor(t,r,s){this.name=t,this.subscriptions=r,this.system_info=s}},tT=class{static{a(this,"NodeSubscription")}constructor(t,r,s,n){this.schema=t,this.table=r,this.publish=s,this.subscribe=n}};zL.exports={Node:eT,NodeSubscription:tT}});var XL=g((Wfe,JL)=>{"use strict";var uZ=M().OPERATIONS_ENUM,rT=class{static{a(this,"UpsertObject")}constructor(t,r,s,n=void 0){this.operation=uZ.UPSERT,this.schema=t,this.table=r,this.records=s,this.__origin=n}};JL.exports=rT});var gu=g((zfe,jL)=>{"use strict";var sT=class{static{a(this,"RemotePayloadObject")}constructor(t,r,s,n){this.operation=t,this.node_name=r,this.subscriptions=s,this.system_info=n}},nT=class{static{a(this,"RemotePayloadSubscription")}constructor(t,r,s,n,i,o,c){this.schema=t,this.table=r,this.hash_attribute=s,this.publish=n,this.subscribe=i,this.start_time=o,c!==void 0&&(this.attributes=c)}};jL.exports={RemotePayloadObject:sT,RemotePayloadSubscription:nT}});var eM=g((Xfe,ZL)=>{"use strict";var iT=class{static{a(this,"TableSizeObject")}constructor(t,r,s=0,n=0,i=0,o=0){this.schema=t,this.table=r,this.table_size=s,this.record_count=n,this.transaction_log_size=i,this.transaction_log_record_count=o}};ZL.exports=iT});var sM=g((rEe,rM)=>{"use strict";var lZ=eM(),Zfe=Et(),tM=We(),_Z=$(),{getSchemaPath:eEe,getTransactionAuditStorePath:tEe}=Je(),{getDatabases:dZ}=(Ae(),ne(Ge));rM.exports=fZ;async function fZ(e){let t=new lZ;try{let r=dZ()[e.schema]?.[e.name],s=r.primaryStore.getStats(),n=r.auditStore?.getStats(),i=await tM.environmentDataSize(schema_path,e.name),o=await tM.environmentDataSize(txn_path,e.name);t.schema=e.schema,t.table=e.name,t.table_size=i,t.record_count=s.entryCount,t.transaction_log_size=o,t.transaction_log_record_count=n.entryCount}catch(r){_Z.warn(`unable to stat table dbi due to ${r}`)}return t}a(fZ,"lmdbGetTableSize")});var iM=g((nEe,nM)=>{"use strict";var oT=class{static{a(this,"SystemInformationObject")}constructor(t,r,s,n,i,o,c){this.system=t,this.time=r,this.cpu=s,this.memory=n,this.disk=i,this.network=o,this.harperdb_processes=c}};nM.exports=oT});var ha=g((uEe,lM)=>{"use strict";var EZ=require("fs-extra"),hZ=require("path"),Zt=require("systeminformation"),mi=$(),oM=nt(),oEe=Fe(),vd=M(),mZ=sM(),uM=ti(),{getThreadInfo:aM}=Ke(),mT=ee();mT.initSync();var pZ=iM(),{openEnvironment:aEe}=We(),{getSchemaPath:cEe}=Je(),{database:SZ}=(Ae(),ne(Ge)),Pd;lM.exports={getHDBProcessInfo:lT,getNetworkInfo:dT,getDiskInfo:_T,getMemoryInfo:uT,getCPUInfo:cT,getTimeInfo:aT,getSystemInformation:fT,systemInformation:TZ,getTableSize:ET,getMetrics:hT};function aT(){return Zt.time()}a(aT,"getTimeInfo");async function cT(){try{let{family:e,model:t,stepping:r,revision:s,voltage:n,speedmin:i,speedmax:o,governor:c,socket:u,cache:_,...l}=await Zt.cpu();l.cpu_speed=await Zt.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,...b}=await Zt.currentLoad();return b.cpus=[],T.forEach(R=>{let{raw_load:L,raw_load_idle:H,raw_load_irq:P,raw_load_nice:k,raw_load_system:B,raw_load_user:X,...z}=R;b.cpus.push(z)}),l.current_load=b,l}catch(e){return mi.error(`error in getCPUInfo: ${e}`),{}}}a(cT,"getCPUInfo");async function uT(){try{let{buffers:e,cached:t,slab:r,buffcache:s,...n}=await Zt.mem();return Object.assign(n,process.memoryUsage())}catch(e){return mi.error(`error in getMemoryInfo: ${e}`),{}}}a(uT,"getMemoryInfo");async function lT(){let e={core:[],clustering:[]};try{let t=await Zt.processes(),r;try{r=Number.parseInt(await EZ.readFile(hZ.join(mT.get(vd.CONFIG_PARAMS.ROOTPATH),vd.HDB_PID_FILE),"utf8"))}catch(s){if(s.code===vd.NODE_ERROR_CODES.ENOENT)mi.warn("Unable to locate 'hdb.pid' file, try stopping and starting HarperDB. This could be because HarperDB is not running.");else throw s}t.list.forEach(s=>{s.pid===r?e.core.push(s):s.name==="nats-server"&&e.clustering.push(s)});for(let s of e.core)for(let n of t.list)n.pid===s.parentPid&&(n.name==="PM2"||n.command==="PM2")&&(s.parent="PM2");return e}catch(t){return mi.error(`error in getHDBProcessInfo: ${t}`),e}}a(lT,"getHDBProcessInfo");async function _T(){let e={};try{let{rIO_sec:t,wIO_sec:r,tIO_sec:s,ms:n,...i}=await Zt.disksIO();e.io=i;let{rx_sec:o,tx_sec:c,wx_sec:u,..._}=await Zt.fsStats();return e.read_write=_,e.size=await Zt.fsSize(),e}catch(t){return mi.error(`error in getDiskInfo: ${t}`),e}}a(_T,"getDiskInfo");async function dT(){let e={default_interface:null,latency:{},interfaces:[],stats:[],connections:[]};try{return e.default_interface=await Zt.networkInterfaceDefault(),e.latency=await Zt.inetChecksite("google.com"),(await Zt.networkInterfaces()).forEach(s=>{let{internal:n,virtual:i,mtu:o,dhcp:c,dnsSuffix:u,ieee8021xAuth:_,ieee8021xState:l,carrier_changes:d,...f}=s;e.interfaces.push(f)}),(await Zt.networkStats()).forEach(s=>{let{rx_sec:n,tx_sec:i,ms:o,...c}=s;e.stats.push(c)}),e}catch(t){return mi.error(`error in getNetworkInfo: ${t}`),e}}a(dT,"getNetworkInfo");async function fT(){if(Pd!==void 0)return Pd;let e={};try{let{codepage:t,logofile:r,serial:s,build:n,servicepack:i,uefi:o,...c}=await Zt.osInfo();e=c;let u=await Zt.versions("node, npm");return e.node_version=u.node,e.npm_version=u.npm,Pd=e,Pd}catch(t){return mi.error(`error in getSystemInformation: ${t}`),e}}a(fT,"getSystemInformation");async function ET(){let e=[],t=await uM.describeAll();for(let r of Object.values(t))for(let s of Object.values(r))e.push(await mZ(s));return e}a(ET,"getTableSize");async function hT(){let e=await uM.describeAll(),t={};for(let r in e){let s=t[r]={};for(let n in e[r])try{let i=SZ({database:r,table:n}),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}}),s[n]=o}catch(i){mi.notify(`Error getting stats for table ${n}: ${i}`)}}return t}a(hT,"getMetrics");async function cM(){if(mT.get(vd.CONFIG_PARAMS.CLUSTERING_ENABLED)){let{jsm:e}=await oM.getNATSReferences(),t=await oM.listStreams(),r=[];for(let s of t){let n=[],i=await e.consumers.list(s.config.name);for await(let c of i)n.push({name:c.name,created:c.created,num_ack_pending:c.num_ack_pending,num_redelivered:c.num_redelivered,num_waiting:c.num_waiting,num_pending:c.num_pending});let o={stream_name:s.config.name,database:s.config.subjects[0].split(".")[1],table:s.config.subjects[0].split(".")[2],state:s.state,consumers:n};r.push(o)}return r}}a(cM,"getNatsStreamInfo");async function TZ(e){let t=new pZ;if(!Array.isArray(e.attributes)||e.attributes.length===0)return t.system=await fT(),t.time=aT(),t.cpu=await cT(),t.memory=await uT(),t.disk=await _T(),t.network=await dT(),t.harperdb_processes=await lT(),t.table_size=await ET(),t.metrics=await hT(),t.threads=await aM(),t.replication=await cM(),t;for(let r=0;r<e.attributes.length;r++)switch(e.attributes[r]){case"system":t.system=await fT();break;case"time":t.time=aT();break;case"cpu":t.cpu=await cT();break;case"memory":t.memory=await uT();break;case"disk":t.disk=await _T();break;case"network":t.network=await dT();break;case"harperdb_processes":t.harperdb_processes=await lT();break;case"table_size":t.table_size=await ET();break;case"database_metrics":case"metrics":t.metrics=await hT();break;case"threads":t.threads=await aM();break;case"replication":t.replication=await cM();break;default:break}return t}a(TZ,"systemInformation")});var Hd=g((_Ee,_M)=>{"use strict";_M.exports={version:gZ,printVersion:RZ};var Bd=eu();function gZ(){if(Bd)return Bd.version}a(gZ,"version");function RZ(){Bd&&console.log(`HarperDB Version ${Bd.version}`)}a(RZ,"printVersion")});var cs=g((hEe,hM)=>{"use strict";var AZ=Ur(),pT=Q(),OZ=require("util"),_o=M(),dM=ee();dM.initSync();var bZ=ZS(),fM=Mr(),{Node:fEe,NodeSubscription:EEe}=hi(),NZ=ra(),yZ=XL(),{RemotePayloadObject:IZ,RemotePayloadSubscription:wZ}=gu(),{handleHDBError:CZ,hdb_errors:DZ}=se(),{HTTP_STATUS_CODES:LZ,HDB_ERROR_MSGS:MZ}=DZ,UZ=tn(),PZ=ha(),vZ=Hd(),{getDatabases:BZ}=(Ae(),ne(Ge)),HZ=OZ.promisify(bZ.authorize),xZ=fM.searchByHash,qZ=fM.searchByValue;hM.exports={authHeaderToUser:GZ,isEmpty:FZ,getNodeRecord:kZ,upsertNodeRecord:VZ,buildNodePayloads:$Z,checkClusteringEnabled:YZ,getAllNodeRecords:KZ,getSystemInfo:WZ,reverseSubscription:EM};async function GZ(e){let t={headers:{authorization:e.hdb_auth_header}};return e.hdb_user=await HZ(t,null),e}a(GZ,"authHeaderToUser");function FZ(e){return e==null}a(FZ,"isEmpty");async function kZ(e){let t=new NZ(_o.SYSTEM_SCHEMA_NAME,_o.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[e],["*"]);return xZ(t)}a(kZ,"getNodeRecord");async function VZ(e){let t=new yZ(_o.SYSTEM_SCHEMA_NAME,_o.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[e]);return AZ.upsert(t)}a(VZ,"upsertNodeRecord");function EM(e){if(pT.isEmpty(e.subscribe)||pT.isEmpty(e.publish))throw new Error("Received invalid subscription object");let{schema:t,table:r,hash_attribute:s}=e,n={schema:t,table:r,hash_attribute:s};return e.subscribe===!0&&e.publish===!1?(n.subscribe=!1,n.publish=!0):e.subscribe===!1&&e.publish===!0?(n.subscribe=!0,n.publish=!1):(n.subscribe=e.subscribe,n.publish=e.publish),n}a(EM,"reverseSubscription");function $Z(e,t,r,s){let n=[];for(let i=0,o=e.length;i<o;i++){let c=e[i],{schema:u,table:_}=c,l=pT.getTableHashAttribute(u,_),{subscribe:d,publish:f}=EM(c),E=BZ()[u]?.[_],h=new wZ(u,_,l,f,d,c.start_time,E.schemaDefined?E.attributes:void 0);n.push(h)}return new IZ(r,t,n,s)}a($Z,"buildNodePayloads");function YZ(){if(!dM.get(_o.CONFIG_PARAMS.CLUSTERING_ENABLED))throw CZ(new Error,MZ.CLUSTERING_NOT_ENABLED,LZ.BAD_REQUEST,void 0,void 0,!0)}a(YZ,"checkClusteringEnabled");async function KZ(){let e=new UZ(_o.SYSTEM_SCHEMA_NAME,_o.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,"name","*",void 0,["*"]);return Array.from(await qZ(e))}a(KZ,"getAllNodeRecords");async function WZ(){let e=await PZ.getSystemInformation();return{hdb_version:vZ.version(),node_version:e.node_version,platform:e.platform}}a(WZ,"getSystemInfo")});var ST=g((pEe,OM)=>{"use strict";var xd=nt(),mM=Q(),pM=Fe(),SM=M(),qd=$(),TM=fu(),QZ=Z_(),{RemotePayloadObject:zZ}=gu(),{handleHDBError:gM,hdb_errors:JZ}=se(),{HTTP_STATUS_CODES:RM}=JZ,{NodeSubscription:AM}=hi();OM.exports=XZ;async function XZ(e,t){let r;try{r=await xd.request(`${t}.${pM.REQUEST_SUFFIX}`,new zZ(SM.OPERATIONS_ENUM.DESCRIBE_ALL,t,void 0,void 0)),qd.trace("Response from remote describe all request:",r)}catch(o){qd.error(`addNode received error from describe all request to remote node: ${o}`);let c=xd.requestErrorHandler(o,"add_node",t);throw gM(new Error,c,RM.INTERNAL_SERVER_ERROR,"error",c)}if(r.status===pM.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let o=`Error returned from remote node ${t}: ${r.message}`;throw gM(new Error,o,RM.INTERNAL_SERVER_ERROR,"error",o)}let s=r.message,n=[],i=[];for(let o of e){let{table:c}=o,u=o.database??o.schema??"data";if(u===SM.SYSTEM_SCHEMA_NAME){await xd.createLocalTableStream(u,c);let h=new AM(u,c,o.publish,o.subscribe);h.start_time=o.start_time,i.push(h);continue}let _=mM.doesSchemaExist(u),l=s[u]!==void 0,d=c?mM.doesTableExist(u,c):!0,f=c?s?.[u]?.[c]!==void 0:!0;if(!_&&!l||!d&&!f){n.push(o);continue}if(!_&&l&&(qd.trace(`addNode creating schema: ${u}`),await TM.createSchema({operation:"create_schema",schema:u})),!d&&f){qd.trace(`addNode creating table: ${c} in schema: ${u} with attributes ${JSON.stringify(s[u][c].attributes)}`);let h=new QZ(u,c,s[u][c].hash_attribute);s[u][c].attributes&&(h.attributes=s[u][c].attributes),await TM.createTable(h)}await xd.createLocalTableStream(u,c);let E=new AM(u,c,o.publish,o.subscribe);E.start_time=o.start_time,i.push(E)}return{added:i,skipped:n}}a(XZ,"reviewSubscriptions")});var Vd=g((TEe,yM)=>{"use strict";var{handleHDBError:Gd,hdb_errors:jZ}=se(),{HTTP_STATUS_CODES:Fd}=jZ,{addUpdateNodeValidator:ZZ}=Cd(),kd=$(),NM=M(),bM=Fe(),e5=Q(),Ru=nt(),Au=cs(),t5=ee(),r5=ST(),{Node:s5,NodeSubscription:n5}=hi(),{broadcast:i5}=Ke(),o5="Unable to create subscriptions due to schema and/or tables not existing on the local or remote node",a5="Some subscriptions were unsuccessful due to schema and/or tables not existing on the local or remote node",c5=t5.get(NM.CONFIG_PARAMS.CLUSTERING_NODENAME);yM.exports=u5;async function u5(e,t=!1){kd.trace("addNode called with:",e),Au.checkClusteringEnabled();let r=ZZ(e);if(r)throw Gd(r,r.message,Fd.BAD_REQUEST,void 0,void 0,!0);let s=e.node_name;if(!t){let d=await Au.getNodeRecord(s);if(!e5.isEmptyOrZeroLength(d))throw Gd(new Error,`Node '${s}' has already been added, perform update_node to proceed.`,Fd.BAD_REQUEST,void 0,void 0,!0)}let{added:n,skipped:i}=await r5(e.subscriptions,s),o={message:void 0,added:n,skipped:i};if(n.length===0)return o.message=o5,o;let c=Au.buildNodePayloads(n,c5,NM.OPERATIONS_ENUM.ADD_NODE,await Au.getSystemInfo()),u=[];for(let d=0,f=n.length;d<f;d++){let E=n[d];n[d].start_time===void 0&&delete n[d].start_time,u.push(new n5(E.schema,E.table,E.publish,E.subscribe))}kd.trace("addNode sending remote payload:",c);let _;try{_=await Ru.request(`${s}.${bM.REQUEST_SUFFIX}`,c)}catch(d){kd.error(`addNode received error from request: ${d}`);for(let E=0,h=n.length;E<h;E++){let p=n[E];p.publish=!1,p.subscribe=!1,await Ru.updateRemoteConsumer(p,s)}let f=Ru.requestErrorHandler(d,"add_node",s);throw Gd(new Error,f,Fd.INTERNAL_SERVER_ERROR,"error",f)}if(_.status===bM.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let d=`Error returned from remote node ${s}: ${_.message}`;throw Gd(new Error,d,Fd.INTERNAL_SERVER_ERROR,"error",d)}kd.trace(_);for(let d=0,f=n.length;d<f;d++){let E=n[d];await Ru.updateRemoteConsumer(E,s),E.subscribe===!0&&await Ru.updateConsumerIterator(E.schema,E.table,s,"start")}let l=new s5(s,u,_.system_info);return await Au.upsertNodeRecord(l),i5({type:"nats_update"}),i.length>0?o.message=a5:o.message=`Successfully added '${s}' to manifest`,o}a(u5,"addNode")});var RT=g((AEe,CM)=>{"use strict";var{handleHDBError:TT,hdb_errors:l5}=se(),{HTTP_STATUS_CODES:gT}=l5,{addUpdateNodeValidator:_5}=Cd(),Ou=$(),wM=M(),IM=Fe(),REe=Q(),bu=nt(),Nu=cs(),d5=ee(),{cloneDeep:f5}=require("lodash"),E5=ST(),{Node:h5,NodeSubscription:m5}=hi(),{broadcast:p5}=Ke(),S5="Unable to update subscriptions due to schema and/or tables not existing on the local or remote node",T5="Some subscriptions were unsuccessful due to schema and/or tables not existing on the local or remote node",g5=d5.get(wM.CONFIG_PARAMS.CLUSTERING_NODENAME);CM.exports=R5;async function R5(e){Ou.trace("updateNode called with:",e),Nu.checkClusteringEnabled();let t=_5(e);if(t)throw TT(t,t.message,gT.BAD_REQUEST,void 0,void 0,!0);let r=e.node_name,s,n=await Nu.getNodeRecord(r);n.length>0&&(s=f5(n));let{added:i,skipped:o}=await E5(e.subscriptions,r),c={message:void 0,updated:i,skipped:o};if(i.length===0)return c.message=S5,c;let u=Nu.buildNodePayloads(i,g5,wM.OPERATIONS_ENUM.UPDATE_NODE,await Nu.getSystemInfo());for(let l=0,d=i.length;l<d;l++){let f=i[l];Ou.trace(`updateNode updating work stream for node: ${r} subscription:`,f),i[l].start_time===void 0&&delete i[l].start_time}Ou.trace("updateNode sending remote payload:",u);let _;try{_=await bu.request(`${r}.${IM.REQUEST_SUFFIX}`,u)}catch(l){Ou.error(`updateNode received error from request: ${l}`);let d=bu.requestErrorHandler(l,"update_node",r);throw TT(new Error,d,gT.INTERNAL_SERVER_ERROR,"error",d)}if(_.status===IM.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let l=`Error returned from remote node ${r}: ${_.message}`;throw TT(new Error,l,gT.INTERNAL_SERVER_ERROR,"error",l)}Ou.trace(_);for(let l=0,d=i.length;l<d;l++){let f=i[l];await bu.updateRemoteConsumer(f,r),f.subscribe===!0?await bu.updateConsumerIterator(f.schema,f.table,r,"start"):await bu.updateConsumerIterator(f.schema,f.table,r,"stop")}return s||(s=[new h5(r,[],_.system_info)]),await A5(s[0],i,_.system_info),o.length>0?c.message=T5:c.message=`Successfully updated '${r}'`,c}a(R5,"updateNode");async function A5(e,t,r){let s=e;for(let n=0,i=t.length;n<i;n++){let o=t[n],c=!1;for(let u=0,_=e.subscriptions.length;u<_;u++){let l=s.subscriptions[u];if(l.schema===o.schema&&l.table===o.table){l.publish=o.publish,l.subscribe=o.subscribe,c=!0;break}}c||s.subscriptions.push(new m5(o.schema,o.table,o.publish,o.subscribe))}s.system_info=r,await Nu.upsertNodeRecord(s),p5({type:"nats_update"})}a(A5,"updateNodeTable")});var PM=g((bEe,UM)=>{"use strict";var MM=require("joi"),{string:DM}=MM.types(),O5=Xe(),LM=M(),b5=ee(),N5=Fe();UM.exports=y5;function y5(e){let t=DM.invalid(b5.get(LM.CONFIG_PARAMS.CLUSTERING_NODENAME)).pattern(N5.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=MM.object({operation:DM.valid(LM.OPERATIONS_ENUM.REMOVE_NODE).required(),node_name:t});return O5.validateBySchema(e,r)}a(y5,"removeNodeValidator")});var Yd=g((yEe,qM)=>{"use strict";var{handleHDBError:vM,hdb_errors:I5}=se(),{HTTP_STATUS_CODES:BM}=I5,w5=PM(),yu=$(),HM=cs(),C5=Q(),$d=M(),xM=Fe(),AT=nt(),D5=ee(),{RemotePayloadObject:L5}=gu(),{NodeSubscription:M5}=hi(),U5=sa(),P5=ni(),{broadcast:v5}=Ke(),B5=D5.get($d.CONFIG_PARAMS.CLUSTERING_NODENAME);qM.exports=H5;async function H5(e){yu.trace("removeNode called with:",e),HM.checkClusteringEnabled();let t=w5(e);if(t)throw vM(t,t.message,BM.BAD_REQUEST,void 0,void 0,!0);let r=e.node_name,s=await HM.getNodeRecord(r);if(C5.isEmptyOrZeroLength(s))throw vM(new Error,`Node '${r}' was not found.`,BM.BAD_REQUEST,void 0,void 0,!0);s=s[0];let n=new L5($d.OPERATIONS_ENUM.REMOVE_NODE,B5,[]),i,o=!1;for(let u=0,_=s.subscriptions.length;u<_;u++){let l=s.subscriptions[u];l.subscribe===!0&&await AT.updateConsumerIterator(l.schema,l.table,r,"stop");try{await AT.updateRemoteConsumer(new M5(l.schema,l.table,!1,!1),r)}catch(d){yu.error(d)}}try{i=await AT.request(`${r}.${xM.REQUEST_SUFFIX}`,n),yu.trace("Remove node reply from remote node:",r,i)}catch(u){yu.error("removeNode received error from request:",u),o=!0}let c=new U5($d.SYSTEM_SCHEMA_NAME,$d.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[r]);return await P5.deleteRecord(c),v5({type:"nats_update"}),i?.status===xM.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR||o?(yu.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(H5,"removeNode")});var kM=g((wEe,FM)=>{"use strict";var GM=require("joi"),{string:x5,array:q5}=GM.types(),G5=Xe(),F5=Cd();FM.exports=k5;function k5(e){let t=GM.object({operation:x5.valid("configure_cluster").required(),connections:q5.items(F5.validation_schema).required()});return G5.validateBySchema(e,t)}a(k5,"configureClusterValidator")});var OT=g((DEe,WM)=>{"use strict";var V5=M(),Kd=$(),$5=Q(),Y5=Yd(),K5=Vd(),VM=cs(),W5=kM(),{handleHDBError:$M,hdb_errors:Q5}=se(),{HTTP_STATUS_CODES:YM}=Q5,z5="Configure cluster complete.",J5="Failed to configure the cluster. Check the logs for more details.",X5="Configure cluster was partially successful. Errors occurred when attempting to configure the following nodes. Check the logs for more details.";WM.exports=j5;async function j5(e){Kd.trace("configure cluster called with:",e),VM.checkClusteringEnabled();let t=W5(e);if(t)throw $M(t,t.message,YM.BAD_REQUEST,void 0,void 0,!0);let r=await VM.getAllNodeRecords(),s=[];for(let f=0,E=r.length;f<E;f++)s.push(KM(Y5,{operation:V5.OPERATIONS_ENUM.REMOVE_NODE,node_name:r[f].name},r[f].name));let n=await Promise.allSettled(s);Kd.trace("All results from configure_cluster remove node:",n);let i=[],o=e.connections.length;for(let f=0;f<o;f++){let E=e.connections[f];i.push(KM(K5,E,E.node_name))}let c=await Promise.allSettled(i);Kd.trace("All results from configure_cluster add node:",c);let u=[],_=[],l=!1,d=n.concat(c);for(let f=0,E=d.length;f<E;f++){let h=d[f];h.status==="rejected"&&(Kd.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($5.isEmptyOrZeroLength(u))return{message:z5,connections:_};if(l)return{message:X5,failed_nodes:u,connections:_};throw $M(new Error,J5,YM.INTERNAL_SERVER_ERROR,void 0,void 0,!0)}a(j5,"configureCluster");async function KM(e,t,r){try{return{node_name:r,result:await e(t)}}catch(s){throw{node_name:r,error:s}}}a(KM,"functionWrapper")});var zM=g((MEe,QM)=>{"use strict";var Wd=require("joi"),Z5=Xe(),{validateSchemaExists:e8,validateTableExists:t8,validateSchemaName:r8}=Js(),s8=Wd.object({operation:Wd.string().valid("purge_stream"),schema:Wd.string().custom(e8).custom(r8).required(),table:Wd.string().custom(t8).required()});function n8(e){return Z5.validateBySchema(e,s8)}a(n8,"purgeStreamValidator");QM.exports=n8});var bT=g((PEe,JM)=>{"use strict";var{handleHDBError:i8,hdb_errors:o8}=se(),{HTTP_STATUS_CODES:a8}=o8,c8=zM(),u8=nt(),l8=cs();JM.exports=_8;async function _8(e){if(e.purge_ingest!==!0){let n=c8(e);if(n)throw i8(n,n.message,a8.BAD_REQUEST,void 0,void 0,!0)}l8.checkClusteringEnabled();let{schema:t,table:r,purge_ingest:s}=e;return await u8.purgeTableStream(t,r,s),s?"Successfully purged ingest":`Successfully purged table '${t}.${r}'`}a(_8,"purgeStream")});var IT=g((BEe,rU)=>{"use strict";var yT=cs(),d8=nt(),ZM=ee(),Qd=M(),fo=Fe(),f8=Q(),NT=$(),{RemotePayloadObject:E8}=gu(),{ErrorCode:XM}=require("nats"),jM=ZM.get(Qd.CONFIG_PARAMS.CLUSTERING_ENABLED),eU=ZM.get(Qd.CONFIG_PARAMS.CLUSTERING_NODENAME);rU.exports={clusterStatus:h8,buildNodeStatus:tU};async function h8(){let e={node_name:eU,is_enabled:jM,connections:[]};if(!jM)return e;let t=await yT.getAllNodeRecords();if(f8.isEmptyOrZeroLength(t))return e;let r=[];for(let s=0,n=t.length;s<n;s++)r.push(tU(t[s],e.connections));return await Promise.allSettled(r),e}a(h8,"clusterStatus");async function tU(e,t){let r=e.name,s=new E8(Qd.OPERATIONS_ENUM.CLUSTER_STATUS,eU,void 0,await yT.getSystemInfo()),n,i,o=fo.CLUSTER_STATUS_STATUSES.OPEN;try{let u=Date.now();n=await d8.request(fo.REQUEST_SUBJECT(r),s),i=Date.now()-u,n.status===fo.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR&&(o=fo.CLUSTER_STATUS_STATUSES.CLOSED,NT.error(`Error getting node status from ${r} `,n))}catch(u){NT.warn(`Error getting node status from ${r}`,u),u.code===XM.NoResponders?o=fo.CLUSTER_STATUS_STATUSES.NO_RESPONDERS:u.code===XM.Timeout?o=fo.CLUSTER_STATUS_STATUSES.TIMEOUT:o=fo.CLUSTER_STATUS_STATUSES.CLOSED}let c=new m8(r,o,n?.message?.ports?.clustering,n?.message?.ports?.operations_api,i,n?.message?.uptime,e.subscriptions,n?.message?.system_info);try{let u={name:r,system_info:n?.message?.system_info};e.system_info?.hdb_version!==Qd.PRE_4_0_0_VERSION&&await yT.upsertNodeRecord(u)}catch(u){NT.error("Cluster status encountered an error updating system info for node:",r,u)}t.push(c)}a(tU,"buildNodeStatus");function m8(e,t,r,s,n,i,o,c){this.node_name=e,this.status=t,this.ports={clustering:r,operations_api:s},this.latency_ms=n,this.uptime=i,this.subscriptions=o,this.system_info=c}a(m8,"NodeStatusObject")});var CT=g((xEe,sU)=>{"use strict";var{handleHDBError:p8,hdb_errors:S8}=se(),{HTTP_STATUS_CODES:T8}=S8,g8=nt(),R8=cs(),wT=Q(),zd=require("joi"),A8=Xe(),O8=2e3,b8=zd.object({timeout:zd.number().min(1),connected_nodes:zd.boolean(),routes:zd.boolean()});sU.exports=N8;async function N8(e){R8.checkClusteringEnabled();let t=A8.validateBySchema(e,b8);if(t)throw p8(t,t.message,T8.BAD_REQUEST,void 0,void 0,!0);let{timeout:r,connected_nodes:s,routes:n}=e,i=s===void 0||wT.autoCastBoolean(s),o=n===void 0||wT.autoCastBoolean(n),c={nodes:[]},u=await g8.getServerList(r??O8),_={};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:wT.autoCast(p.split(":")[1])})):[]),c.nodes.push(h)}}return c}a(N8,"clusterNetwork")});var aU=g((GEe,oU)=>{"use strict";var DT=require("joi"),nU=Xe(),{route_constraints:iU}=Km();oU.exports={setRoutesValidator:y8,deleteRoutesValidator:I8};function y8(e){let t=DT.object({server:DT.valid("hub","leaf").required(),routes:iU.required()});return nU.validateBySchema(e,t)}a(y8,"setRoutesValidator");function I8(e){let t=DT.object({routes:iU.required()});return nU.validateBySchema(e,t)}a(I8,"deleteRoutesValidator")});var MT=g((kEe,_U)=>{"use strict";var Eo=Br(),LT=Q(),Jd=M(),cU=aU(),{handleHDBError:uU,hdb_errors:w8}=se(),{HTTP_STATUS_CODES:lU}=w8,C8="cluster routes successfully set",D8="cluster routes successfully deleted";_U.exports={setRoutes:L8,getRoutes:M8,deleteRoutes:U8};function L8(e){let t=cU.setRoutesValidator(e);if(t)throw uU(t,t.message,lU.BAD_REQUEST,void 0,void 0,!0);let r=Eo.getClusteringRoutes(),s=e.server==="hub"?r.hub_routes:r.leaf_routes,n=e.server==="hub"?r.leaf_routes:r.hub_routes,i=[],o=[];for(let c=0,u=e.routes.length;c<u;c++){let _=e.routes[c];_.port=LT.autoCast(_.port);let l=s.some(f=>f.host===_.host&&f.port===_.port),d=n.some(f=>f.host===_.host&&f.port===_.port);l||d?i.push(_):(s.push(_),o.push(_))}return e.server==="hub"?Eo.updateConfigValue(Jd.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,s):Eo.updateConfigValue(Jd.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,s),{message:C8,set:o,skipped:i}}a(L8,"setRoutes");function M8(){let e=Eo.getClusteringRoutes();return{hub:e.hub_routes,leaf:e.leaf_routes}}a(M8,"getRoutes");function U8(e){let t=cU.deleteRoutesValidator(e);if(t)throw uU(t,t.message,lU.BAD_REQUEST,void 0,void 0,!0);let r=Eo.getClusteringRoutes(),s=r.hub_routes,n=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=s.length;E<h;E++){let p=s[E];if(d.host===p.host&&d.port===p.port){s.splice(E,1),f=!0,c=!0,i.push(d);break}}if(!f){let E=!0;for(let h=0,p=n.length;h<p;h++){let S=n[h];if(d.host===S.host&&d.port===S.port){n.splice(h,1),u=!0,E=!1,i.push(d);break}}E&&o.push(d)}}return c&&(s=LT.isEmptyOrZeroLength(s)?null:s,Eo.updateConfigValue(Jd.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,s)),u&&(n=LT.isEmptyOrZeroLength(n)?null:n,Eo.updateConfigValue(Jd.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,n)),{message:D8,deleted:i,skipped:o}}a(U8,"deleteRoutes")});var fU=g(($Ee,dU)=>{"use strict";var Iu=require("alasql"),ho=require("recursive-iterator"),xs=$(),P8=Q(),wu=M(),UT=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,B8(this.ast,this.affected_attributes,this.table_lookup,this.schema_lookup,this.table_to_schema_lookup)}getAttributesBySchemaTableName(t,r){if(!t||!r||!this.affected_attributes)return[];if(this.affected_attributes.has(t))return!this.affected_attributes.get(t).has(r)&&(r=this.table_lookup.get(r),!r)?[]:this.affected_attributes.get(t).get(r)}getAllTables(){let t=[];if(!this.affected_attributes)return t;for(let r of this.affected_attributes.keys())t.push(Array.from(this.affected_attributes.get(r).keys()));return t}getTablesBySchemaName(t){return!t||!this.affected_attributes?[]:Array.from(this.affected_attributes.get(t).keys())}getSchemas(){return this.affected_attributes?Array.from(this.affected_attributes.keys()):[]}getAst(){return this.ast}updateAttributeWildcardsForRolePerms(t){let r=this.ast.columns.filter(n=>wu.SEARCH_WILDCARDS.includes(n.columnid));if(r.length===0)return this.ast;let s=this.ast.from[0].databaseid;return this.ast.columns=this.ast.columns.filter(n=>!wu.SEARCH_WILDCARDS.includes(n.columnid)),r.forEach(n=>{let i=this.table_to_schema_lookup.has(n.tableid)?this.table_to_schema_lookup.get(n.tableid):s,o=this.table_lookup.has(n.tableid)?this.table_lookup.get(n.tableid):this.ast.from[0].tableid;if(t[i]&&t[i].tables[o]&&t[i].tables[o][wu.PERMS_CRUD_ENUM.READ]){let c;t[i].tables[o].attribute_permissions.length>0?c=v8(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(_=>!wu.SEARCH_WILDCARDS.includes(_));c.forEach(({attribute_name:_})=>{let l=new Iu.yy.Column({columnid:_});n.tableid&&(l.tableid=n.tableid),this.ast.columns.push(l),u.includes(_)||u.push(_)}),this.affected_attributes.get(i).set(o,u)}}),this.ast}};function v8(e){return e.filter(t=>t[wu.PERMS_CRUD_ENUM.READ])}a(v8,"filterReadRestrictedAttrs");function B8(e,t,r,s,n){H8(e,t,r,s,n)}a(B8,"interpretAST");function Cu(e,t,r,s,n){if(!(!e||!e.databaseid)&&(t.has(e.databaseid)||t.set(e.databaseid,new Map),t.get(e.databaseid).has(e.tableid)||t.get(e.databaseid).set(e.tableid,[]),e.as&&(r.has(e.as)||r.set(e.as,e.tableid),s&&!s.has(e.as)&&s.set(e.as,e.databaseid)),n)){let i=e.databaseid,o=e.tableid;e.as&&(o=e.as),n.set(o,i)}}a(Cu,"addSchemaTableToMap");function H8(e,t,r,s,n){if(!e){xs.info("getRecordAttributesAST: invalid SQL syntax tree");return}e instanceof Iu.yy.Insert?F8(e,t,r):e instanceof Iu.yy.Select?x8(e,t,r,s,n):e instanceof Iu.yy.Update?q8(e,t,r):e instanceof Iu.yy.Delete?G8(e,t,r):xs.error("AST in getRecordAttributesAST() is not a valid SQL type.")}a(H8,"getRecordAttributesAST");function x8(e,t,r,s,n){if(!e){xs.info("getSelectAttributes: invalid SQL syntax tree");return}if(!e.from||e.from[0]===void 0)return;let i=e.from[0].databaseid;if(P8.isEmptyOrZeroLength(i)){xs.error("No schema specified");return}e.from.forEach(c=>{Cu(c,t,r,s,n)}),e.joins&&e.joins.forEach(c=>{c.as&&(c.table.as=c.as),Cu(c.table,t,r,s,n)});let o=new ho(e.columns);for(let{node:c}of o)if(c&&c.columnid){let u=c.tableid,_=s.has(u)?s.get(u):i;if(u||(u=e.from[0].tableid),!t.get(_).has(u))if(r.has(u))u=r.get(u);else{xs.info(`table specified as ${u} not found.`);return}t.get(_).get(u).indexOf(c.columnid)<0&&t.get(_).get(u).push(c.columnid)}if(e.where){let c=new ho(e.where),u=e.from[0].tableid;for(let{node:_}of c)if(_&&_.columnid){let l=_.tableid?_.tableid:u;if(!t.get(i).has(l))if(r.has(l))l=r.get(l);else{xs.info(`table specified as ${l} not found.`);continue}t.get(i).get(l).indexOf(_.columnid)<0&&t.get(i).get(l).push(_.columnid)}}if(e.joins&&e.joins.forEach(c=>{let u=new ho(c.on);for(let{node:_}of u)if(_&&_.columnid){let l=_.tableid,d=n.get(l);if(!t.get(d).has(l))if(r.has(l))l=r.get(l);else{xs.info(`table specified as ${l} not found.`);continue}t.get(d).get(l).indexOf(_.columnid)<0&&t.get(d).get(l).push(_.columnid)}}),e.order){let c=new ho(e.order);for(let{node:u}of c)if(u&&u.columnid){let _=u.tableid,l=s.has(_)?s.get(_):i;if(_||(_=e.from[0].tableid),!t.get(l).has(_))if(r.has(_))_=r.get(_);else{xs.info(`table specified as ${_} not found.`);return}t.get(l).get(_).indexOf(u.columnid)<0&&t.get(l).get(_).push(u.columnid)}}}a(x8,"getSelectAttributes");function q8(e,t,r){if(!e){xs.info("getUpdateAttributes: invalid SQL syntax tree");return}let s=new ho(e.columns),n=e.table.databaseid;Cu(e.table,t,r);for(let{node:i}of s)i&&i.columnid&&PT(e.table.tableid,n,i.columnid,t,r)}a(q8,"getUpdateAttributes");function G8(e,t,r){if(!e){xs.info("getDeleteAttributes: invalid SQL syntax tree");return}let s=new ho(e.where),n=e.table.databaseid;Cu(e.table,t,r);for(let{node:i}of s)i&&i.columnid&&PT(e.table.tableid,n,i.columnid,t,r)}a(G8,"getDeleteAttributes");function F8(e,t,r){if(!e){xs.info("getInsertAttributes: invalid SQL syntax tree");return}let s=new ho(e.columns),n=e.into.databaseid;Cu(e.into,t,r);for(let{node:i}of s)i&&i.columnid&&PT(e.into.tableid,n,i.columnid,t,r)}a(F8,"getInsertAttributes");function PT(e,t,r,s,n){if(!s.get(t))return;let i=e;s.get(t).has(i)||(i=n.get(i)),s.get(t).get(i).push(r)}a(PT,"pushAttribute");dU.exports=UT});var HT=g((KEe,pU)=>{var Xd=Ji(),EU=require("chalk"),kr=$(),hU=require("prompt"),{promisify:k8}=require("util"),vT=M(),V8=require("fs-extra"),$8=require("path"),Y8=Q(),K8=Hd(),mU=ee();mU.initSync();var W8=require("moment"),Q8=k8(hU.get),z8=$8.join(mU.getHdbBasePath(),vT.LICENSE_KEY_DIR_NAME,vT.LICENSE_FILE_NAME,vT.LICENSE_FILE_NAME);pU.exports={getFingerprint:X8,setLicense:J8,parseLicense:BT,register:j8,getRegistrationInfo:e6};async function J8(e){if(e&&e.key&&e.company){try{kr.info(`parsing license key: ${e.key} and `);let t=e.company.toString();await BT(e.key.trim(),t.trim())}catch(t){let r="There was an error parsing the license key.";throw kr.error(r),kr.error(t),new Error(r)}return"Wrote license key file. Registration successful."}throw new Error("Invalid key or company specified for license file.")}a(J8,"setLicense");async function X8(){let e={};try{e=await Xd.generateFingerPrint()}catch(t){let r="Error generating fingerprint.";throw kr.error(r),kr.error(t),new Error(r)}return e}a(X8,"getFingerprint");async function BT(e,t){if(!e||!t)throw new Error("Invalid entries for License Key and Customer Company");kr.info("Validating license input...");let r=Xd.validateLicense(e,t);if(kr.info("checking for valid license..."),!r.valid_license)throw new Error("Invalid license found.");if(kr.info("checking valid license date..."),!r.valid_date)throw new Error("This License has expired.");if(kr.info(`checking for valid machine license ${r.valid_machine}`),!r.valid_machine)throw new Error("This license is in use on another machine.");try{kr.info("writing license to disk"),await V8.writeFile(z8,JSON.stringify({license_key:e,company:t}))}catch(s){throw kr.error("Failed to write License"),s}return"Registration successful."}a(BT,"parseLicense");async function j8(){let e=await Z8();return BT(e.HDB_LICENSE,e.CUSTOMER_COMPANY)}a(j8,"register");async function Z8(){let e=await Xd.generateFingerPrint(),t={properties:{CUSTOMER_COMPANY:{description:EU.magenta("[COMPANY] Please enter your company name"),required:!0},HDB_LICENSE:{description:EU.magenta(`[HDB_LICENSE] Your fingerprint is ${e} Please enter your license key`),required:!0}}};try{hU.start()}catch(s){kr.error(s)}let r;try{r=await Q8(t)}catch(s){throw console.error("There was a problem prompting for registration input. Exiting."),s}return r}a(Z8,"promptForRegistration");async function e6(){let e={registered:!1,version:null,ram_allocation:null,license_expiration_date:null},t;try{t=await Xd.getLicense()}catch(r){throw kr.error(`There was an error when searching licenses due to: ${r.message}`),r}if(Y8.isEmptyOrZeroLength(t))throw new Error("There were no licenses found.");if(e.registered=t.enterprise,e.version=K8.version(),e.ram_allocation=t.ram_allocation,isNaN(t.exp_date))e.license_expiration_date=t.enterprise?t.exp_date:null;else{let r=W8.utc(t.exp_date).format("YYYY-MM-DD");e.license_expiration_date=t.enterprise?r:null}return e}a(e6,"getRegistrationInfo")});var TU=g((QEe,SU)=>{"use strict";var t6=Fe(),xT=class{static{a(this,"HubConfigObject")}constructor(t,r,s,n,i,o,c,u,_,l,d,f,E,h){this.port=t,o===null&&(o=void 0),this.server_name=r+t6.SERVER_SUFFIX.HUB,this.pid_file=s,this.max_payload=67108864,this.reconnect_error_reports=100,this.jetstream={enabled:!1},this.tls={cert_file:n,key_file:i,ca_file:o,insecure:c,verify:u},this.leafnodes={port:_,tls:{cert_file:n,key_file:i,ca_file:o,insecure:c}},this.cluster={name:l,port:d,routes:f,tls:{cert_file:n,key_file:i,ca_file:o,insecure:c,verify:u}},this.accounts={SYS:{users:E},HDB:{users:h}},this.system_account="SYS"}};SU.exports=xT});var AU=g((JEe,RU)=>{"use strict";var gU=Fe(),qT=class{static{a(this,"LeafConfigObject")}constructor(t,r,s,n,i,o,c,u,_,l,d){this.port=t,d===null&&(d=void 0),this.server_name=r+gU.SERVER_SUFFIX.LEAF,this.pid_file=s,this.max_payload=67108864,this.jetstream={enabled:!0,store_dir:n,domain:r+gU.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"}};RU.exports=qT});var bU=g((jEe,OU)=>{"use strict";var GT=class{static{a(this,"HdbUserObject")}constructor(t,r){this.user=t,this.password=r}};OU.exports=GT});var yU=g((ehe,NU)=>{"use strict";var r6=Fe(),FT=class{static{a(this,"SysUserObject")}constructor(t,r){this.user=t+r6.SERVER_SUFFIX.ADMIN,this.password=r}};NU.exports=FT});var $T=g((rhe,CU)=>{"use strict";var ma=require("path"),ef=require("fs-extra"),s6=TU(),n6=AU(),i6=bU(),o6=yU(),kT=is(),Sa=Q(),Sr=Br(),Zd=M(),Du=Fe(),{CONFIG_PARAMS:dt}=Zd,Lu=$(),Mu=ee(),IU=Rn(),VT=nt(),pa="clustering",a6=1e4,wU=500;CU.exports={generateNatsConfig:u6,removeNatsConfig:l6,getHubConfigPath:c6};function c6(){let e=Mu.get(dt.ROOTPATH);return ma.join(e,pa,Du.NATS_CONFIG_FILES.HUB_SERVER)}a(c6,"getHubConfigPath");async function u6(e=!1,t=void 0){Mu.initSync();let r=Mu.get(dt.ROOTPATH),s=ma.join(r,pa,Du.PID_FILES.HUB),n=ma.join(r,pa,Du.PID_FILES.LEAF),i=Sr.getConfigFromFile(dt.CLUSTERING_LEAFSERVER_STREAMS_PATH),o=ma.join(r,pa,Du.NATS_CONFIG_FILES.HUB_SERVER),c=ma.join(r,pa,Du.NATS_CONFIG_FILES.LEAF_SERVER),u=Sr.getConfigFromFile(dt.CLUSTERING_TLS_CERTIFICATE),_=Sr.getConfigFromFile(dt.CLUSTERING_TLS_PRIVATEKEY),l=Sr.getConfigFromFile(dt.CLUSTERING_TLS_CERT_AUTH),d=Sr.getConfigFromFile(dt.CLUSTERING_TLS_INSECURE),f=Sr.getConfigFromFile(dt.CLUSTERING_TLS_VERIFY),E=Sr.getConfigFromFile(dt.CLUSTERING_NODENAME),h=Sr.getConfigFromFile(dt.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT);await VT.checkNATSServerInstalled()||tf("nats-server dependency is either missing or the wrong version. Run 'npm install' to fix");let p=await kT.listUsers(),S=Sr.getConfigFromFile(dt.CLUSTERING_USER),T=await kT.getClusterUser();(Sa.isEmpty(T)||T.active!==!0)&&tf(`Invalid cluster user '${S}'. A valid user with the role 'cluster_user' must be defined under clustering.user in harperdb-config.yaml`),e||(await jd(dt.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),await jd(dt.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT),await jd(dt.CLUSTERING_HUBSERVER_NETWORK_PORT),await jd(dt.CLUSTERING_LEAFSERVER_NETWORK_PORT));let b=[],R=[];for(let[z,J]of p.entries())J.role.role===Zd.ROLE_TYPES_ENUM.CLUSTER_USER&&J.active&&(b.push(new o6(J.username,IU.decrypt(J.hash))),R.push(new i6(J.username,IU.decrypt(J.hash))));let L=[],{hub_routes:H}=Sr.getClusteringRoutes();if(!Sa.isEmptyOrZeroLength(H))for(let z of H)L.push(`tls://${T.sys_name_encoded}:${T.uri_encoded_d_hash}@${z.host}:${z.port}`);let P=new s6(Sr.getConfigFromFile(dt.CLUSTERING_HUBSERVER_NETWORK_PORT),E,s,u,_,l,d,f,h,Sr.getConfigFromFile(dt.CLUSTERING_HUBSERVER_CLUSTER_NAME),Sr.getConfigFromFile(dt.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),L,b,R);l==null&&(delete P.tls.ca_file,delete P.leafnodes.tls.ca_file),t=Sa.isEmpty(t)?void 0:t.toLowerCase(),(t===void 0||t===Zd.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase())&&(await ef.writeJson(o,P),Lu.trace(`Hub server config written to ${o}`));let k=`tls://${T.sys_name_encoded}:${T.uri_encoded_d_hash}@0.0.0.0:${h}`,B=`tls://${T.uri_encoded_name}:${T.uri_encoded_d_hash}@0.0.0.0:${h}`,X=new n6(Sr.getConfigFromFile(dt.CLUSTERING_LEAFSERVER_NETWORK_PORT),E,n,i,[k],[B],b,R,u,_,l,d);l==null&&delete X.tls.ca_file,(t===void 0||t===Zd.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())&&(await ef.writeJson(c,X),Lu.trace(`Leaf server config written to ${c}`))}a(u6,"generateNatsConfig");async function jd(e){let t=Mu.get(e);return Sa.isEmpty(t)&&tf(`port undefined for '${e}'`),await Sa.isPortTaken(t)&&tf(`'${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(jd,"isPortAvailable");function tf(e){let t=`Error generating clustering config: ${e}`;Lu.error(t),console.error(t),process.exit(1)}a(tf,"generateNatsConfigError");async function l6(e){let{port:t,config_file:r}=VT.getServerConfig(e),{username:s,decrypt_hash:n}=await kT.getClusterUser(),i=0,o=2e3;for(;i<wU;){try{let _=await VT.createConnection(t,s,n,!1);if(_.protocol.connected===!0){_.close();break}}catch(_){Lu.trace(`removeNatsConfig waiting for ${e}. Caught and swallowed error ${_}`)}if(i++,i>=wU)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 Sa.async_set_timeout(o*(i*2))}let c="0".repeat(a6),u=ma.join(Mu.get(dt.ROOTPATH),pa,r);await ef.writeFile(u,c),await ef.remove(u),Lu.notify(e,"started.")}a(l6,"removeNatsConfig")});var vU=g((nhe,PU)=>{"use strict";var Vr=ee(),_6=Ji(),me=M(),Uu=Fe(),wn=require("path"),{PACKAGE_ROOT:sf}=M(),DU=ee(),rf=Q(),Ta="/dev/null",d6=wn.join(sf,"launchServiceScripts"),LU=wn.join(sf,"utility/scripts"),f6=wn.join(LU,me.HDB_RESTART_SCRIPT),MU=wn.resolve(sf,"dependencies",`${process.platform}-${process.arch}`,Uu.NATS_BINARY_NAME);function UU(){let t=_6.licenseSearch().ram_allocation||me.RAM_ALLOCATION_ENUM.DEFAULT,r=me.MEM_SETTING_KEY+t,s={[me.PROCESS_NAME_ENV_PROP]:me.PROCESS_DESCRIPTORS.HDB,IS_SCRIPTED_SERVICE:!0};return rf.noBootFile()&&(s[me.CONFIG_PARAMS.ROOTPATH.toUpperCase()]=rf.getEnvCliRootPath()),{name:me.PROCESS_DESCRIPTORS.HDB,script:me.LAUNCH_SERVICE_SCRIPTS.MAIN,exec_mode:"fork",env:s,node_args:r,cwd:sf}}a(UU,"generateMainServerConfig");var E6=9930;function h6(){Vr.initSync(!0);let e=Vr.get(me.CONFIG_PARAMS.ROOTPATH),t=wn.join(e,"clustering",Uu.NATS_CONFIG_FILES.HUB_SERVER),r=wn.join(Vr.get(me.HDB_SETTINGS_NAMES.LOG_PATH_KEY),me.LOG_NAMES.HDB),s=DU.get(me.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),n=Uu.LOG_LEVEL_FLAGS[Vr.get(me.CONFIG_PARAMS.CLUSTERING_LOGLEVEL)]??void 0,i={name:me.PROCESS_DESCRIPTORS.CLUSTERING_HUB+(s!==E6?"-"+s:""),script:MU,args:n?`${n} -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 Vr.get(me.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(i.out_file=Ta,i.error_file=Ta),i}a(h6,"generateNatsHubServerConfig");var m6=9940;function p6(){Vr.initSync(!0);let e=Vr.get(me.CONFIG_PARAMS.ROOTPATH),t=wn.join(e,"clustering",Uu.NATS_CONFIG_FILES.LEAF_SERVER),r=wn.join(Vr.get(me.HDB_SETTINGS_NAMES.LOG_PATH_KEY),me.LOG_NAMES.HDB),s=DU.get(me.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),n=Uu.LOG_LEVEL_FLAGS[Vr.get(me.CONFIG_PARAMS.CLUSTERING_LOGLEVEL)]??void 0,i={name:me.PROCESS_DESCRIPTORS.CLUSTERING_LEAF+(s!==m6?"-"+s:""),script:MU,args:n?`${n} -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 Vr.get(me.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(i.out_file=Ta,i.error_file=Ta),i}a(p6,"generateNatsLeafServerConfig");function S6(){Vr.initSync();let e=wn.join(Vr.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:d6,autorestart:!1};return Vr.get(me.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(t.out_file=Ta,t.error_file=Ta),t}a(S6,"generateClusteringUpgradeV4ServiceConfig");function T6(){let e={[me.PROCESS_NAME_ENV_PROP]:me.PROCESS_DESCRIPTORS.RESTART_HDB};return rf.noBootFile()&&(e[me.CONFIG_PARAMS.ROOTPATH.toUpperCase()]=rf.getEnvCliRootPath()),{...{name:me.PROCESS_DESCRIPTORS.RESTART_HDB,exec_mode:"fork",env:e,instances:1,autorestart:!1,cwd:LU},script:f6}}a(T6,"generateRestart");function g6(){return{apps:[UU()]}}a(g6,"generateAllServiceConfigs");PU.exports={generateAllServiceConfigs:g6,generateMainServerConfig:UU,generateRestart:T6,generateNatsHubServerConfig:h6,generateNatsLeafServerConfig:p6,generateClusteringUpgradeV4ServiceConfig:S6}});var zU=g((ahe,QU)=>{"use strict";var ve=M(),R6=Q(),Dn=$T(),nf=nt(),Cn=Fe(),pi=vU(),of=ee(),Si=$(),A6=cs(),{startWorker:BU,onMessageFromWorkers:O6}=Ke(),b6=ha(),ohe=require("util"),N6=require("child_process"),y6=require("fs"),{execFile:I6}=N6,ye;QU.exports={enterPM2Mode:w6,start:Ti,stop:YT,reload:xU,restart:qU,list:KT,describe:FU,connect:Ln,kill:U6,startAllServices:P6,startService:WT,getUniqueServicesList:kU,restartAllServices:v6,isServiceRegistered:VU,reloadStopStart:$U,restartHdb:GU,deleteProcess:L6,startClusteringProcesses:KU,startClusteringThreads:WU,isHdbRestartRunning:M6,isClusteringRunning:H6,stopClustering:B6,reloadClustering:x6};var Pu=!1;O6(e=>{e.type==="restart"&&of.initSync(!0)});function w6(){Pu=!0}a(w6,"enterPM2Mode");function Ln(){return ye||(ye=require("pm2")),new Promise((e,t)=>{ye.connect((r,s)=>{Si.setupConsoleLogging(),r&&t(r),e(s)})})}a(Ln,"connect");var Tr,C6=10,HU;function Ti(e,t=!1){if(Pu)return D6(e);let r=I6(e.script,e.args.split(" "),e);r.name=e.name,r.on("exit",async i=>{let o=Tr.indexOf(r);o>-1&&Tr.splice(o,1),!HU&&i!==0&&(e.restarts=(e.restarts||0)+1,e.restarts<C6&&(y6.existsSync(Dn.getHubConfigPath())?Ti(e):(await Dn.generateNatsConfig(!0),Ti(e),await new Promise(c=>setTimeout(c,3e3)),await Dn.removeNatsConfig(ve.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await Dn.removeNatsConfig(ve.PROCESS_DESCRIPTORS.CLUSTERING_LEAF))))});let s={serviceName:e.name.replace(/ /g,"-")};function n(i){let o=of.get(ve.CONFIG_PARAMS.CLUSTERING_LOGLEVEL),c=/\[\d+][^\[]+\[(\w+)]/g,u,_=0,l;for(;u=c.exec(i);){if(u.index&&Cn.LOG_LEVEL_HIERARCHY[o]>=Cn.LOG_LEVEL_HIERARCHY[l||"info"]){let E=l===Cn.LOG_LEVELS.ERR||l===Cn.LOG_LEVELS.WRN?Si.OUTPUTS.STDERR:Si.OUTPUTS.STDOUT;Si.logCustomLevel(l||"info",E,s,i.slice(_,u.index).trim())}let[d,f]=u;_=u.index+d.length,l=Cn.LOG_LEVELS[f]}if(Cn.LOG_LEVEL_HIERARCHY[o]>=Cn.LOG_LEVEL_HIERARCHY[l||"info"]){let d=l===Cn.LOG_LEVELS.ERR||l===Cn.LOG_LEVELS.WRN?Si.OUTPUTS.STDERR:Si.OUTPUTS.STDOUT;Si.logCustomLevel(l||"info",d,s,i.slice(_).trim())}}if(a(n,"extractMessages"),r.stdout.on("data",n),r.stderr.on("data",n),r.unref(),Tr=[],!Tr&&!t){let i=a(()=>{HU=!0,Tr&&(Tr.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)}Tr.push(r)}a(Ti,"start");function D6(e){return new Promise(async(t,r)=>{try{await Ln()}catch(s){r(s)}ye.start(e,(s,n)=>{s&&(ye.disconnect(),r(s)),ye.disconnect(),t(n)})})}a(D6,"startWithPM2");function YT(e){if(!Pu){for(let t of Tr||[])t.name===e&&(Tr.splice(Tr.indexOf(t),1),t.kill());return}return new Promise(async(t,r)=>{try{await Ln()}catch(s){r(s)}ye.stop(e,async(s,n)=>{s&&(ye.disconnect(),r(s)),ye.delete(e,(i,o)=>{i&&(ye.disconnect(),r(s)),ye.disconnect(),t(o)})})})}a(YT,"stop");function xU(e){return new Promise(async(t,r)=>{try{await Ln()}catch(s){r(s)}ye.reload(e,(s,n)=>{s&&(ye.disconnect(),r(s)),ye.disconnect(),t(n)})})}a(xU,"reload");function qU(e){if(!Pu)for(let t of Tr||[])t.name===e&&t.kill();return new Promise(async(t,r)=>{try{await Ln()}catch(s){r(s)}ye.restart(e,(s,n)=>{ye.disconnect(),t(n)})})}a(qU,"restart");function L6(e){return new Promise(async(t,r)=>{try{await Ln()}catch(s){r(s)}ye.delete(e,(s,n)=>{s&&(ye.disconnect(),r(s)),ye.disconnect(),t(n)})})}a(L6,"deleteProcess");async function GU(){await Ti(pi.generateRestart())}a(GU,"restartHdb");async function M6(){let e=await KT();for(let t in e)if(e[t].name===ve.PROCESS_DESCRIPTORS.RESTART_HDB)return!0;return!1}a(M6,"isHdbRestartRunning");function KT(){return new Promise(async(e,t)=>{try{await Ln()}catch(r){t(r)}ye.list((r,s)=>{r&&(ye.disconnect(),t(r)),ye.disconnect(),e(s)})})}a(KT,"list");function FU(e){return new Promise(async(t,r)=>{try{await Ln()}catch(s){r(s)}ye.describe(e,(s,n)=>{s&&(ye.disconnect(),r(s)),ye.disconnect(),t(n)})})}a(FU,"describe");function U6(){if(!Pu){for(let e of Tr||[])e.kill();Tr=[];return}return new Promise(async(e,t)=>{try{await Ln()}catch(r){t(r)}ye.killDaemon((r,s)=>{r&&(ye.disconnect(),t(r)),ye.disconnect(),e(s)})})}a(U6,"kill");async function P6(){try{await KU(),await WU(),await Ti(pi.generateAllServiceConfigs())}catch(e){throw ye?.disconnect(),e}}a(P6,"startAllServices");async function WT(e,t=!1){try{let r;switch(e=e.toLowerCase(),e){case ve.PROCESS_DESCRIPTORS.HDB.toLowerCase():r=pi.generateMainServerConfig();break;case ve.PROCESS_DESCRIPTORS.CLUSTERING_INGEST_SERVICE.toLowerCase():r=pi.generateNatsIngestServiceConfig();break;case ve.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE.toLowerCase():r=pi.generateNatsReplyServiceConfig();break;case ve.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase():r=pi.generateNatsHubServerConfig(),await Ti(r,t),await Dn.removeNatsConfig(e);return;case ve.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase():r=pi.generateNatsLeafServerConfig(),await Ti(r,t),await Dn.removeNatsConfig(e);return;case ve.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0.toLowerCase():r=pi.generateClusteringUpgradeV4ServiceConfig();break;default:throw new Error(`Start service called with unknown service config: ${e}`)}await Ti(r)}catch(r){throw ye?.disconnect(),r}}a(WT,"startService");async function kU(){try{let e=await KT(),t={};for(let r=0,s=e.length;r<s;r++){let n=e[r];t[n.name]===void 0&&(t[n.name]={name:n.name,exec_mode:n.pm2_env.exec_mode})}return t}catch(e){throw ye?.disconnect(),e}}a(kU,"getUniqueServicesList");async function v6(e=[]){try{let t=!1,r=await kU();for(let s=0,n=Object.values(r).length;s<n;s++){let o=Object.values(r)[s].name;e.includes(o)||(o===ve.PROCESS_DESCRIPTORS.HDB?t=!0:await qU(o))}t&&await $U(ve.PROCESS_DESCRIPTORS.HDB)}catch(t){throw ye?.disconnect(),t}}a(v6,"restartAllServices");async function VU(e){if(Tr?.find(r=>r.name===e))return!0;let t=await b6.getHDBProcessInfo();return t.core.length&&t.core[0]?.parent==="PM2"}a(VU,"isServiceRegistered");async function $U(e){let t=of.get(ve.CONFIG_PARAMS.THREADS_COUNT)??of.get(ve.CONFIG_PARAMS.THREADS),r=await FU(e),s=R6.isEmptyOrZeroLength(r)?0:r.length;t!==s?(await YT(e),await WT(e)):e===ve.PROCESS_DESCRIPTORS.HDB?await GU():await xU(e)}a($U,"reloadStopStart");var YU;async function KU(e=!1){for(let t in ve.CLUSTERING_PROCESSES){let r=ve.CLUSTERING_PROCESSES[t];await WT(r,e)}}a(KU,"startClusteringProcesses");async function WU(){YU=BU(ve.LAUNCH_SERVICE_SCRIPTS.NATS_REPLY_SERVICE,{name:ve.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE});try{await nf.deleteLocalStream("__HARPERDB_WORK_QUEUE__")}catch{}await nf.updateLocalStreams();let e=await A6.getAllNodeRecords();for(let t=0,r=e.length;t<r;t++)if(e[t].system_info?.hdb_version===ve.PRE_4_0_0_VERSION){Si.info("Starting clustering upgrade 4.0.0 process"),BU(ve.LAUNCH_SERVICE_SCRIPTS.NODES_UPGRADE_4_0_0,{name:"Upgrade-4-0-0"});break}}a(WU,"startClusteringThreads");async function B6(){for(let e in ve.CLUSTERING_PROCESSES)if(e!==ve.CLUSTERING_PROCESSES.CLUSTERING_INGEST_PROC_DESCRIPTOR)if(e===ve.CLUSTERING_PROCESSES.CLUSTERING_REPLY_SERVICE_DESCRIPTOR)await YU.terminate();else{let t=ve.CLUSTERING_PROCESSES[e];await YT(t)}}a(B6,"stopClustering");async function H6(){for(let e in ve.CLUSTERING_PROCESSES){let t=ve.CLUSTERING_PROCESSES[e];if(await VU(t)===!1)return!1}return!0}a(H6,"isClusteringRunning");async function x6(){await Dn.generateNatsConfig(!0),await nf.reloadNATSHub(),await nf.reloadNATSLeaf(),await Dn.removeNatsConfig(ve.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase()),await Dn.removeNatsConfig(ve.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())}a(x6,"reloadClustering")});var _f=g((lhe,rP)=>{"use strict";var q6=require("minimist"),{isMainThread:zT,parentPort:jU}=require("worker_threads"),it=M(),{PROCESS_DESCRIPTORS_VALIDATE:vu}=it,on=$(),JT=Q(),cf=$T(),af=nt(),uhe=Fe(),ZU=Br(),an=zU(),JU=ha(),G6=bh(),{restartWorkers:uf,onMessageByType:F6}=Ke(),{handleHDBError:k6,hdb_errors:V6}=se(),{HTTP_STATUS_CODES:$6}=V6,lf=ee();lf.initSync();var Bu=`Restarting HarperDB. This may take up to ${it.RESTART_TIMEOUT_MS/1e3} seconds.`,Y6="Restart is not available from the CLI when running in non-pm2 mode. Either call restart from the API or stop and start HarperDB.",XU="Clustering is not enabled so cannot be restarted",K6="Invalid service",ga,us;rP.exports={restart:eP,restartService:XT};zT&&F6(it.ITC_EVENT_TYPES.RESTART,e=>{e.workerType?XT({service:e.workerType}):eP({operation:"restart"})});async function eP(e){us=Object.keys(e).length===0,ga=await an.isServiceRegistered(it.HDB_PROC_DESCRIPTOR);let t=q6(process.argv);if(t.service){await XT(t);return}if(us&&!ga){console.error(Y6);return}if(us&&console.log(Bu),ga){an.enterPM2Mode(),on.notify(Bu);let r=G6(Object.keys(it.CONFIG_PARAM_MAP),!0);return JT.isEmptyOrZeroLength(Object.keys(r))||ZU.updateConfigValue(void 0,void 0,r,!0,!0),W6(),Bu}return zT?(on.notify(Bu),setTimeout(()=>{uf()},50)):jU.postMessage({type:it.ITC_EVENT_TYPES.RESTART}),Bu}a(eP,"restart");async function XT(e){let{service:t}=e;if(it.PROCESS_DESCRIPTORS_VALIDATE[t]===void 0)throw k6(new Error,K6,$6.BAD_REQUEST,void 0,void 0,!0);if(ga=await an.isServiceRegistered(it.HDB_PROC_DESCRIPTOR),!zT)return jU.postMessage({type:it.ITC_EVENT_TYPES.RESTART,workerType:t}),t==="custom_functions"&&(t="Custom Functions"),`Restarting ${t}`;let r;switch(t){case vu.clustering:if(!lf.get(it.CONFIG_PARAMS.CLUSTERING_ENABLED)){r=XU;break}us&&console.log("Restarting clustering"),on.notify("Restarting clustering"),await tP();break;case vu.clustering_config:case vu["clustering config"]:if(!lf.get(it.CONFIG_PARAMS.CLUSTERING_ENABLED)){r=XU;break}us&&console.log("Restarting clustering_config"),on.notify("Restarting clustering_config"),await an.reloadClustering();break;case"custom_functions":case"custom functions":case vu.harperdb:case vu.http_workers:if(us&&!ga){r=`Restart ${t} is not available from the CLI when running in non-pm2 mode. Either call restart ${t} from the API or stop and start HarperDB.`;break}us&&console.log("Restarting http_workers"),on.notify("Restarting http_workers"),us?await an.restart(it.HDB_PROC_DESCRIPTOR):setTimeout(()=>{uf("http")},200);break;default:r=`Unrecognized service: ${t}`;break}return r?(on.error(r),us&&console.error(r),r):(t==="custom_functions"&&(t="Custom Functions"),`Restarting ${t}`)}a(XT,"restartService");async function W6(){await tP(),await an.restart(it.HDB_PROC_DESCRIPTOR),await JT.async_set_timeout(2e3),lf.get(it.CONFIG_PARAMS.CLUSTERING_ENABLED)&&await QT(),us&&(await af.closeConnection(),process.exit(0))}a(W6,"restartPM2Mode");async function tP(){if(!ZU.getConfigFromFile(it.CONFIG_PARAMS.CLUSTERING_ENABLED))return;if((await JU.getHDBProcessInfo()).clustering.length===0)on.trace("Clustering not running, restart will start clustering services"),await cf.generateNatsConfig(!0),await an.startClusteringProcesses(),await an.startClusteringThreads(),await QT(),us&&await af.closeConnection();else{await cf.generateNatsConfig(!0),ga?(on.trace("Restart clustering restarting PM2 managed Hub and Leaf servers"),await an.restart(it.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await an.restart(it.PROCESS_DESCRIPTORS.CLUSTERING_LEAF)):(await JU.getHDBProcessInfo()).clustering.forEach(n=>{on.trace("Restart clustering killing process pid",n.pid),process.kill(n.pid)}),await JT.async_set_timeout(3e3),await QT(),await af.updateLocalStreams(),us&&await af.closeConnection(),on.trace("Restart clustering restarting ingest and reply service threads");let t=uf(it.LAUNCH_SERVICE_SCRIPTS.NATS_INGEST_SERVICE),r=uf(it.LAUNCH_SERVICE_SCRIPTS.NATS_REPLY_SERVICE);await t,await r}}a(tP,"restartClustering");async function QT(){await cf.removeNatsConfig(it.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await cf.removeNatsConfig(it.PROCESS_DESCRIPTORS.CLUSTERING_LEAF)}a(QT,"removeNatsConfig")});var fP=g((fhe,dP)=>{"use strict";var dhe=require("lodash"),gr=M(),{handleHDBError:sP,hdb_errors:Q6}=se(),{HDB_ERROR_MSGS:z6,HTTP_STATUS_CODES:J6}=Q6,jT=$();dP.exports={getRolePermissions:j6};var mo=Object.create(null),X6=a(e=>({key:e,perms:{}}),"perms_template_obj"),aP=a((e=!1)=>({describe:e,tables:{}}),"schema_perms_template"),cP=a((e=!1,t=!1,r=!1,s=!1)=>({[gr.PERMS_CRUD_ENUM.READ]:e,[gr.PERMS_CRUD_ENUM.INSERT]:t,[gr.PERMS_CRUD_ENUM.UPDATE]:r,[gr.PERMS_CRUD_ENUM.DELETE]:s}),"permissions_template"),ZT=a((e=!1,t=!1,r=!1,s=!1,n=!1)=>({attribute_permissions:[],describe:e,...cP(t,r,s,n)}),"table_perms_template"),nP=a((e,t=cP())=>({attribute_name:e,describe:_P(t),[Hu]:t[Hu],[eg]:t[eg],[tg]:t[tg]}),"attr_perms_template"),iP=a((e,t=!1)=>({attribute_name:e,describe:t,[Hu]:t}),"timestamp_attr_perms_template"),{READ:Hu,INSERT:eg,UPDATE:tg}=gr.PERMS_CRUD_ENUM,uP=Object.values(gr.PERMS_CRUD_ENUM),lP=[Hu,eg,tg];function j6(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[gr.SYSTEM_SCHEMA_NAME],t=e.role;let s=JSON.stringify([e.__updatedtime__,r]);if(mo[t]&&mo[t].key===s)return mo[t].perms;let n=Z6(e,r);return mo[t]?mo[t].key=s:mo[t]=X6(s),mo[t].perms=n,n}catch(r){if(!e[gr.TIME_STAMP_NAMES_ENUM.UPDATED_TIME]||e[gr.TIME_STAMP_NAMES_ENUM.UPDATED_TIME]<gr.PERMS_UPDATE_RELEASE_TIMESTAMP){let s=`Role permissions for role '${t}' must be updated to align with new structure from the 2.2.0 release.`;throw jT.error(s),jT.debug(r),sP(new Error,z6.OUTDATED_PERMS_TRANSLATION_ERROR,J6.BAD_REQUEST)}else{let s=`There was an error while translating role permissions for role: ${t}.
|
|
11
|
-
${r.stack}`;throw jT.error(s),sP(new Error)}}}a(j6,"getRolePermissions");function Z6(e,t){let r=Object.create(null);r.super_user=!1;let s=e.permission;r[gr.SYSTEM_SCHEMA_NAME]=s[gr.SYSTEM_SCHEMA_NAME],r.structure_user=s.structure_user;let n=Array.isArray(e.permission.structure_user)||e.permission.structure_user===!0?e.permission.structure_user:[];return Object.keys(t).forEach(i=>{if(n===!0||n.indexOf(i)>-1){r[i]=e9(t[i]);return}r[i]=aP(),s[i]?(s[i].describe&&(r[i].describe=!0),Object.keys(t[i]).forEach(o=>{if(s[i].tables[o]){let c=s[i].tables[o],u=t[i][o],_=t9(c,u);r[i].describe||uP.forEach(l=>{_[l]&&(r[i].describe=!0)}),r[i].tables[o]=_}else r[i].tables[o]=ZT()})):Object.keys(t[i]).forEach(o=>{r[i].tables[o]=ZT()})}),r}a(Z6,"translateRolePermissions");function e9(e){let t=aP(!0);return Object.keys(e).forEach(r=>{t.tables[r]=ZT(!0,!0,!0,!0,!0)}),t}a(e9,"createStructureUserPermissions");function t9(e,t){let{attribute_permissions:r}=e;if(r.length>0){let n=Object.assign({},e);n.attribute_permissions=[];let i=r.reduce((_,l)=>{let{attribute_name:d}=l,f=l;return gr.TIME_STAMP_NAMES.includes(d)&&(f=iP(d,l[Hu])),_[d]=f,_},{}),o=t.primaryKey||t.hash_attribute,c=!!i[o],u=nP(o);return t.attributes.forEach(({attribute:_})=>{if(i[_]){let l=i[_];l.describe=_P(l),n.attribute_permissions.push(l),c||r9(l,u)}else if(_!==o){let l;gr.TIME_STAMP_NAMES.includes(_)?l=iP(_):l=nP(_),n.attribute_permissions.push(l)}}),c||n.attribute_permissions.push(u),n.describe=oP(n),n}else return e.describe=oP(e),e}a(t9,"getTableAttrPerms");function oP(e){return uP.filter(t=>e[t]).length>0}a(oP,"getSchemaTableDescribePerm");function _P(e){return lP.filter(t=>e[t]).length>0}a(_P,"getAttributeDescribePerm");function r9(e,t){lP.forEach(r=>{e[r]&&!t[r]&&(t[r]=!0,t.describe=!0)})}a(r9,"checkForHashPerms")});var EP={};Ye(EP,{Resources:()=>df,keyArrayToString:()=>Ra,resetResources:()=>s9,resources:()=>gi});function s9(){return gi=new df}function Ra(e){return Array.isArray(e)?e[e.length-1]===null?e.slice(0,-1).join("/")+"/":e.join("/"):e}var df,gi,xu=Re(()=>{ro();df=class extends Map{static{a(this,"Resources")}isWorker=!0;loginPath;set(t,r,s,n){if(!r)throw new Error("Must provide a resource");t.startsWith("/")&&(t=t.replace(/^\/+/,""));let i={Resource:r,path:t,type:s,hasSubPaths:!1,relativeURL:""},o=super.get(t);if(o&&(o.Resource.databaseName!==r.databaseName||o.Resource.tableName!==r.tableName)&&!n)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 s=2,n;for(;(s=t.indexOf("/",s))>-1;){let c=t.slice(0,s),u=this.get(c);if(u){if(u.relativeURL=t.slice(s),!u.hasSubPaths)return u;n=u}s+=2}if(n)return n;let i=t.indexOf("?"),o=i>-1?t.slice(0,i):t;return n=this.get(o),n?n.relativeURL=i>-1?t.slice(i):"":n||(n=this.get(""),n&&(t[0]!=="/"&&(t="/"+t),n.relativeURL=t)),n}getResource(t,r){let s=this.getMatch(t);if(s)return t=s.relativeURL,s.Resource.getResource(this.pathToId(t,s.Resource),r)}call(t,r,s){return je(r,async()=>{let n=this.getMatch(t);if(n)return t=n.relativeURL,s(n.Resource,n.path,t)})}setRepresentation(t,r,s){}};a(s9,"resetResources");a(Ra,"keyArrayToString")});var hP={};Ye(hP,{Headers:()=>Ri,appendHeader:()=>rg});function rg(e,t,r,s){if(e.append)e.append(t,r,s);else if(e.set){let n=e.get(t);if(n)if(s)r=(typeof n=="string"?n:n.join(", "))+", "+r;else if(typeof n=="string")r=[n,r];else{n.push(r);return}return e.set(t,r)}else e[t]=(e[t]?e[t]+", ":"")+r}var Ri,qu=Re(()=>{Ri=class extends Map{static{a(this,"Headers")}set(t,r){return typeof t!="string"&&(t=""+t),typeof r!="string"&&(r=""+r),super.set(t.toLowerCase(),[t,r])}get(t){return typeof t!="string"&&(t=""+t),super.get(t.toLowerCase())?.[1]}has(t){return typeof t!="string"&&(t=""+t),super.has(t.toLowerCase())}setIfNone(t,r){typeof t!="string"&&(t=""+t),typeof r!="string"&&(r=""+r);let s=t.toLowerCase();if(!super.has(s))return super.set(s,[t,r])}append(t,r,s){typeof t!="string"&&(t=""+t),typeof r!="string"&&(r=""+r);let n=t.toLowerCase(),i=super.get(n);if(i){let o=i[1];if(s)r=(typeof o=="string"?o:o.join(", "))+", "+r;else if(typeof o=="string")r=[o,r];else{o.push(r);return}}return super.set(n,[t,r])}[Symbol.iterator](){return super.values()[Symbol.iterator]()}};a(rg,"appendHeader")});var Gu={};Ye(Gu,{authentication:()=>OP,bypassAuth:()=>l9,login:()=>d9,logout:()=>f9,start:()=>_9});function l9(){AP=!0}async function OP(e,t){let r=e.headers.asObject,s=r.authorization,n=r.cookie,i=r.origin,o=[];try{if(i){let E=e.isOperationsServer?a9?o9:[]:i9?n9:[];if(E.includes(i)||E.includes("*")){if(e.method==="OPTIONS"){let h=new Ri([["Access-Control-Allow-Methods","POST, GET, PUT, DELETE, PATCH, OPTIONS"],["Access-Control-Allow-Headers","Accept, Content-Type, Authorization"],["Access-Control-Allow-Origin",i]]);return ff&&h.set("Access-Control-Allow-Credentials","true"),{status:200,headers:h}}o.push("Access-Control-Allow-Origin",i),ff&&o.push("Access-Control-Allow-Credentials","true")}}let u,_;if(ff){let E=(i?i.replace(/^https?:\/\//,"").replace(/\W/,"_")+"-":"")+"hdb-session=",h=n?.indexOf(E);if(h>=0){let p=n.indexOf(";",h),S=n.indexOf("=",h);u=n.slice(S+1,p===-1?n.length:p),_=await pP.get(u)}e.session=_||(_={})}e.user=null;let l=a((E,h,p)=>{let S=new Aa.AuthAuditLog(E,h,Pt.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===Pt.AUTH_AUDIT_STATUS.SUCCESS?mP.notify(S):mP.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 rt.getUser(E,null,null),l(E,Pt.AUTH_AUDIT_STATUS.SUCCESS,"mTLS")):(0,Aa.debug)("HTTPS/WSS mTLS authorized connection (mTLS did not authorize a user)","from",e.ip)}let d;if(!e.user)if(s){if(d=po.get(s),!d){let[E,h]=s.split(" "),p,S;try{switch(E){case"Basic":[p,S]=atob(h).split(":"),d=p||S?await rt.getUser(p,S,e):null;break;case"Bearer":try{d=await(0,Ef.validateOperationToken)(h)}catch(T){if(T.message==="invalid token")try{return await(0,Ef.validateRefreshToken)(h),c({status:-1})}catch{throw T}}break}}catch(T){return u9&&(po.get(h)||(po.set(h,h),l(p,Pt.AUTH_AUDIT_STATUS.FAILURE,E))),c({status:401,body:Ai({error:T.message},e)})}po.set(s,d),c9&&l(d.username,Pt.AUTH_AUDIT_STATUS.SUCCESS,E)}e.user=d}else _?.user?e.user=await rt.getUser(_.user,null,e):(AP&&(e.ip?.includes("127.0.0.1")||e.ip=="::1")||e?._nodeRequest?.socket?.server?._pipeName&&e.ip===void 0)&&(e.user=await(0,TP.getSuperUser)());ff&&(e.session.update=function(E){if(!u){u=(0,gP.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,pP.put(E)},e.login=async function(E,h){e.user=await rt.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")&&gi.loginPath?(f.status=302,f.headers.set("Location",gi.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 Ri);for(let d=0;d<_;){let f=o[d++];l.set(f,o[d++])}}return o=null,u}a(c,"applyResponseHeaders")}function _9({server:e,port:t}){e.request(OP,{port:t||"all"}),SP||(SP=!0,setInterval(()=>{po=new Map},ls.get(Pt.CONFIG_PARAMS.AUTHENTICATION_CACHETTL)).unref(),RP.user.addListener(()=>{po=new Map}))}async function d9(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 f9(e){if(!e.baseRequest.session)throw new Error("No session for logout");return await e.baseRequest.session.update({user:null}),"Logout successful"}var TP,Ef,gP,ls,Pt,Aa,RP,mP,n9,i9,o9,a9,pP,ff,AP,c9,u9,po,SP,hf=Re(()=>{TP=x(is());or();xu();Ef=x(Tu());Ae();gP=require("uuid"),ls=x(ee()),Pt=x(M()),Aa=x($()),RP=x(Hc());qu();Oa();mP=(0,Aa.loggerWithTag)("auth-event");ls.initSync();n9=ls.get(Pt.CONFIG_PARAMS.HTTP_CORSACCESSLIST),i9=ls.get(Pt.CONFIG_PARAMS.HTTP_CORS),o9=ls.get(Pt.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_CORSACCESSLIST),a9=ls.get(Pt.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_CORS),pP=ut({table:"hdb_session",database:"system",attributes:[{name:"id",isPrimaryKey:!0},{name:"user"}]}),ff=ls.get(Pt.CONFIG_PARAMS.AUTHENTICATION_ENABLESESSIONS)??!0,AP=ls.get(Pt.CONFIG_PARAMS.AUTHENTICATION_AUTHORIZELOCAL)??process.env.DEV_MODE,c9=ls.get(Pt.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)??!1,u9=ls.get(Pt.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGFAILED)??!1,po=new Map;rt.onInvalidatedUser(()=>{po=new Map});a(l9,"bypassAuth");a(OP,"authentication");a(_9,"start");a(d9,"login");a(f9,"logout")});var DP=g((bhe,CP)=>{"use strict";var Ie=require("joi"),bP=require("fs-extra"),NP=require("path"),Un=Xe(),yP=ee(),IP=M(),wP=$(),{hdb_errors:E9}=se(),{HDB_ERROR_MSGS:er}=E9,Mn=/^[a-zA-Z0-9-_]+$/;CP.exports={getDropCustomFunctionValidator:m9,setCustomFunctionValidator:p9,addComponentValidator:R9,dropCustomFunctionProjectValidator:A9,packageComponentValidator:O9,deployComponentValidator:b9,setComponentFileValidator:S9,getComponentFileValidator:g9,dropComponentFileValidator:T9};function mf(e,t,r){try{let s=yP.get(IP.CONFIG_PARAMS.COMPONENTSROOT),n=NP.join(s,t);return bP.existsSync(n)?e?t:r.message(er.PROJECT_EXISTS):e?r.message(er.NO_PROJECT):t}catch(s){return wP.error(s),r.message(er.VALIDATION_ERR)}}a(mf,"checkProjectExists");function Fu(e,t){return e.includes("..")?t.message("Invalid file path"):e}a(Fu,"checkFilePath");function h9(e,t,r,s){try{let n=yP.get(IP.CONFIG_PARAMS.COMPONENTSROOT),i=NP.join(n,e,t,r+".js");return bP.existsSync(i)?r:s.message(er.NO_FILE)}catch(n){return wP.error(n),s.message(er.VALIDATION_ERR)}}a(h9,"checkFileExists");function m9(e){let t=Ie.object({project:Ie.string().pattern(Mn).custom(mf.bind(null,!0)).required().messages({"string.pattern.base":er.BAD_PROJECT_NAME}),type:Ie.string().valid("helpers","routes").required(),file:Ie.string().pattern(Mn).custom(h9.bind(null,e.project,e.type)).custom(Fu).required().messages({"string.pattern.base":er.BAD_FILE_NAME})});return Un.validateBySchema(e,t)}a(m9,"getDropCustomFunctionValidator");function p9(e){let t=Ie.object({project:Ie.string().pattern(Mn).custom(mf.bind(null,!0)).required().messages({"string.pattern.base":er.BAD_PROJECT_NAME}),type:Ie.string().valid("helpers","routes").required(),file:Ie.string().custom(Fu).required(),function_content:Ie.string().required()});return Un.validateBySchema(e,t)}a(p9,"setCustomFunctionValidator");function S9(e){let t=Ie.object({project:Ie.string().pattern(Mn).required().messages({"string.pattern.base":er.BAD_PROJECT_NAME}),file:Ie.string().custom(Fu).required(),payload:Ie.string().allow("").optional(),encoding:Ie.string().valid("utf8","ASCII","binary","hex","base64","utf16le","latin1","ucs2").optional()});return Un.validateBySchema(e,t)}a(S9,"setComponentFileValidator");function T9(e){let t=Ie.object({project:Ie.string().pattern(Mn).required().messages({"string.pattern.base":er.BAD_PROJECT_NAME}),file:Ie.string().custom(Fu).optional()});return Un.validateBySchema(e,t)}a(T9,"dropComponentFileValidator");function g9(e){let t=Ie.object({project:Ie.string().required(),file:Ie.string().custom(Fu).required(),encoding:Ie.string().valid("utf8","ASCII","binary","hex","base64","utf16le","latin1","ucs2").optional()});return Un.validateBySchema(e,t)}a(g9,"getComponentFileValidator");function R9(e){let t=Ie.object({project:Ie.string().pattern(Mn).custom(mf.bind(null,!1)).required().messages({"string.pattern.base":er.BAD_PROJECT_NAME})});return Un.validateBySchema(e,t)}a(R9,"addComponentValidator");function A9(e){let t=Ie.object({project:Ie.string().pattern(Mn).custom(mf.bind(null,!0)).required().messages({"string.pattern.base":er.BAD_PROJECT_NAME})});return Un.validateBySchema(e,t)}a(A9,"dropCustomFunctionProjectValidator");function O9(e){let t=Ie.object({project:Ie.string().pattern(Mn).required().messages({"string.pattern.base":er.BAD_PROJECT_NAME}),skip_node_modules:Ie.boolean()});return Un.validateBySchema(e,t)}a(O9,"packageComponentValidator");function b9(e){let t=Ie.object({project:Ie.string().pattern(Mn).required().messages({"string.pattern.base":er.BAD_PROJECT_NAME}),payload:Ie.string().optional().messages({"string.pattern.base":er.BAD_PACKAGE}),package:Ie.string().optional()});return Un.validateBySchema(e,t)}a(b9,"deployComponentValidator")});var gf=g((yhe,HP)=>{"use strict";var pf=require("joi"),Sf=require("path"),LP=require("fs-extra"),{exec:N9}=require("child_process"),y9=require("util"),MP=y9.promisify(N9),ku=M(),{handleHDBError:ba,hdb_errors:I9}=se(),{HTTP_STATUS_CODES:Na}=I9,Vu=ee(),w9=Xe(),ya=$();Vu.initSync();var sg=Vu.get(ku.CONFIG_PARAMS.COMPONENTSROOT),UP="npm install --omit=dev --json",C9=`${UP} --dry-run`;HP.exports={installModules:U9,auditModules:P9,installAllRootModules:D9,uninstallRootModule:L9,linkHarperdb:M9};async function D9(e=!1){await Tf(),await $u(e?"npm install --ignore-scripts":"npm install",Vu.get(ku.CONFIG_PARAMS.ROOTPATH))}a(D9,"installAllRootModules");async function L9(e){await $u(`npm uninstall ${e}`,Vu.get(ku.CONFIG_PARAMS.ROOTPATH))}a(L9,"uninstallRootModule");async function M9(){await Tf(),await $u(`npm link ${ku.PACKAGE_ROOT}`,Vu.get(ku.CONFIG_PARAMS.ROOTPATH))}a(M9,"linkHarperdb");async function $u(e,t=void 0){let r,s;try{({stdout:r,stderr:s}=await MP(e,{cwd:t}))}catch(n){throw new Error(n.stderr.replace(`
|
|
12
|
-
|
|
13
|
-
`,"")}a($u,"runCommand");async function U9(e){ya.info(`starting installModules for request: ${e}`);let t=BP(e);if(t)throw ba(t,t.message,Na.BAD_REQUEST);let{projects:r,dry_run:s}=e,n=s===!0?C9:UP;await Tf(),await vP(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 _=Sf.join(sg,u),l,d=null;try{let{stdout:f,stderr:E}=await MP(n,{cwd:_});l=f?f.replace(`
|
|
10
|
+
`,"")}a(nL,"runCommand");async function uX(){try{await q3.access(LS)}catch{return!1}let e=await nL(`${LS} --version`,void 0),t=e.substring(e.lastIndexOf("v")+1,e.length);return F3.eq(t,aX)}a(uX,"checkNATSServerInstalled");async function BS(e,t,r,n=!0,s="127.0.0.1"){if(!t&&!r){let o=await tL.getClusterUser();if(uo(o))throw new Error("Unable to get nats connection. Cluster user is undefined.");t=o.username,r=o.decrypt_hash}Bn.trace("create nats connection called");let i=await X3({name:s,port:e,user:t,pass:r,maxReconnectAttempts:-1,waitOnFirstConnect:n,timeout:2e5,tls:{keyFile:Pt.get(De.CONFIG_PARAMS.CLUSTERING_TLS_PRIVATEKEY),certFile:Pt.get(De.CONFIG_PARAMS.CLUSTERING_TLS_CERTIFICATE),caFile:Pt.get(De.CONFIG_PARAMS.CLUSTERING_TLS_CERT_AUTH),rejectUnauthorized:!1}});return i.protocol.transport.socket.unref(),Bn.trace("create connection established a nats client connection with id",i?.info?.client_id),i.closed().then(o=>{o&&Bn.error("Error with Nats client connection, connection closed",o),sL()}),i}a(BS,"createConnection");function sL(){Er=void 0,oo=void 0,ao=void 0,co=void 0}a(sL,"clearClientCache");async function lX(){Er&&(await Er.drain(),Er=void 0,oo=void 0,ao=void 0,co=void 0)}a(lX,"closeConnection");var Er,co;async function Nd(){return co||(co=BS(Pt.get(De.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),void 0,void 0),Er=await co),Er||co}a(Nd,"getConnection");async function mu(){if(oo)return oo;uo(Er)&&await Nd();let{domain:e}=pu(De.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);if(uo(e))throw new Error("Error getting JetStream domain. Unable to get JetStream manager.");return oo=await Er.jetstreamManager({domain:e,timeout:6e4}),oo}a(mu,"getJetStreamManager");async function iL(){if(ao)return ao;uo(Er)&&await Nd();let{domain:e}=pu(De.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);if(uo(e))throw new Error("Error getting JetStream domain. Unable to get JetStream manager.");return ao=Er.jetstream({domain:e,timeout:6e4}),ao}a(iL,"getJetStream");async function Hn(){let e=Er||await Nd(),t=oo||await mu(),r=ao||await iL();return{connection:e,jsm:t,js:r}}a(Hn,"getNATSReferences");async function _X(e){let t=Pt.get(De.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),{sys_name:r,decrypt_hash:n}=await tL.getClusterUser(),s=await BS(t,r,n),i=vS(),o=s.subscribe(i),c=[],u,_=(async()=>{for await(let l of o){let d=rL.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 bd.async_set_timeout(e),await o.drain(),await s.close(),await _,c}a(_X,"getServerList");async function HS(e,t){let{jsm:r}=await Hn(),n=Pt.get(De.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE);n=n===null?0:n*1e9;let s=Pt.get(De.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXMSGS);s=s===null?-1:s;let i=Pt.get(De.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES);i=i===null?-1:i,await r.streams.add({name:e,storage:j3.File,retention:Z3.Limits,subjects:t,discard:eX.Old,max_msgs:s,max_bytes:i,max_age:n})}a(HS,"createLocalStream");async function oL(){let{jsm:e}=await Hn(),t=await e.streams.list().next(),r=[];return t.forEach(n=>{r.push(n)}),r}a(oL,"listStreams");async function dX(e){let{jsm:t}=await Hn();await t.streams.delete(e)}a(dX,"deleteLocalStream");async function fX(e){let{connection:t}=await Hn(),r=[],n=vS(),s=t.subscribe(n),i=(async()=>{for await(let o of s)r.push(rL.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(fX,"listRemoteStreams");async function EX(e,t=void 0,r=void 0){let{jsm:n,js:s}=await Hn(),i=XD(),o={durable_name:i,ack_policy:US.Explicit};t&&(o.deliver_policy=PS.StartTime,o.opt_start_time=new Date(t).toISOString()),await n.consumers.add(e,o);let c=await s.consumers.get(e,i),u=r?await c.fetch({max_messages:r,expires:2e3}):await c.consume();if(c._info.num_pending===0)return[];let _=[];for await(let l of u){let d=MS(l.data),f={nats_timestamp:l.info.timestampNanos,nats_sequence:l.info.streamSequence,entry:d};if(l.headers&&(f.origin=l.headers.get(Vt.MSG_HEADERS.ORIGIN)),_.push(f),l.ack(),l.info.pending===0)break}return await c.delete(),_}a(EX,"viewStream");async function*hX(e,t=void 0,r=void 0){let{jsm:n,js:s}=await Hn(),i=XD(),o={durable_name:i,ack_policy:US.Explicit};t&&(o.deliver_policy=PS.StartTime,o.opt_start_time=new Date(t).toISOString()),await n.consumers.add(e,o);let c=await s.consumers.get(e,i),u=r?await c.fetch({max_messages:r,expires:2e3}):await c.consume();if(c._info.num_pending===0)return[];for await(let _ of u){let l=MS(_.data);l[0]||(l=[l]);for(let d of l){let f={nats_timestamp:_.info.timestampNanos,nats_sequence:_.info.streamSequence,entry:d};_.headers&&(f.origin=_.headers.get(Vt.MSG_HEADERS.ORIGIN)),yield f}if(_.ack(),_.info.pending===0)break}await c.delete()}a(hX,"viewStreamIterator");async function mX(e,t,r,n){Bn.trace(`publishToStream called with subject: ${e}, stream: ${t}, entries:`,n.operation),r=aL(n,r);let{js:s}=await Hn(),i=await Id(),o=`${e}.${i}`,c=n instanceof Uint8Array?n:eL.encode(n);try{Bn.trace(`publishToStream publishing to subject: ${o}`),iX(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 uL(async()=>{try{await s.publish(o,c,{headers:r})}catch{if(u.code&&u.code.toString()==="503"){Bn.trace(`publishToStream creating stream: ${t}`);let l=o.split(".");l[2]="*",await HS(t,[o]),await s.publish(o,c,{headers:r})}else throw u}});throw u}}a(mX,"publishToStream");function aL(e,t){t===void 0&&(t=rX());let r=Pt.get(De.CONFIG_PARAMS.CLUSTERING_NODENAME);return!t.has(Vt.MSG_HEADERS.ORIGIN)&&r&&t.append(Vt.MSG_HEADERS.ORIGIN,r),t}a(aL,"addNatsMsgHeader");function pu(e){e=e.toLowerCase();let t=hu.join(Pt.get(De.CONFIG_PARAMS.ROOTPATH),oX);if(e===De.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase())return uo(DS)&&(DS={port:fu.getConfigFromFile(De.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),server_name:fu.getConfigFromFile(De.CONFIG_PARAMS.CLUSTERING_NODENAME)+Vt.SERVER_SUFFIX.HUB,config_file:Vt.NATS_CONFIG_FILES.HUB_SERVER,pid_file_path:hu.join(t,Vt.PID_FILES.HUB),hdb_nats_path:t}),DS;if(e===De.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())return uo(CS)&&(CS={port:fu.getConfigFromFile(De.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),server_name:fu.getConfigFromFile(De.CONFIG_PARAMS.CLUSTERING_NODENAME)+Vt.SERVER_SUFFIX.LEAF,config_file:Vt.NATS_CONFIG_FILES.LEAF_SERVER,domain:fu.getConfigFromFile(De.CONFIG_PARAMS.CLUSTERING_NODENAME)+Vt.SERVER_SUFFIX.LEAF,pid_file_path:hu.join(t,Vt.PID_FILES.LEAF),hdb_nats_path:t}),CS;Bn.error(`Unable to get Nats server config. Unrecognized process: ${e}`)}a(pu,"getServerConfig");async function cL(e,t,r,n){try{await e.consumers.add(t,{ack_policy:US.Explicit,durable_name:r,deliver_policy:PS.StartTime,opt_start_time:n})}catch(s){if(s.message!=="consumer already exists")throw s}}a(cL,"createConsumer");async function pX(e,t,r){await e.consumers.delete(t,r)}a(pX,"removeConsumer");function SX(e){return e.split(".")[1]}a(SX,"extractServerName");async function TX(e,t,r=6e4,n=vS()){if(!bd.isObject(t))throw new Error("data param must be an object");let s=eL.encode(t),{connection:i}=await Hn(),o={timeout:r};n&&(o.reply=n,o.noMux=!0);let c=await i.request(e,s,o);return MS(c.data)}a(TX,"request");function xS(e){return new Promise(async(t,r)=>{let n=Y3(LS,["--signal",`reload=${e}`],{cwd:__dirname}),s,i;n.on("error",o=>{r(o)}),n.stdout.on("data",o=>{i+=o.toString()}),n.stderr.on("data",o=>{s+=o.toString()}),n.stderr.on("close",o=>{s&&r(s),t(i)})})}a(xS,"reloadNATS");async function gX(){let{pid_file_path:e}=pu(De.PROCESS_DESCRIPTORS.CLUSTERING_HUB);await xS(e)}a(gX,"reloadNATSHub");async function RX(){let{pid_file_path:e}=pu(De.PROCESS_DESCRIPTORS.CLUSTERING_LEAF);await xS(e)}a(RX,"reloadNATSLeaf");function AX(e,t,r){let n;switch(e.code){case JD.NoResponders:n=`Unable to ${t}, node '${r}' is not listening.`;break;case JD.Timeout:n=`Unable to ${t}, node '${r}' is listening but did not respond.`;break;default:n=e.message;break}return n}a(AX,"requestErrorHandler");async function OX(e,t){let r=t+Vt.SERVER_SUFFIX.LEAF,{connection:n}=await Hn(),{jsm:s}=await LX(r),{schema:i,table:o}=e,c=yd.createNatsTableStreamName(i,o),u=e.start_time?e.start_time:new Date(Date.now()).toISOString();await uL(async()=>{if(e.subscribe===!0)await cL(s,c,n.info.server_name,u);else try{await pX(s,c,n.info.server_name)}catch(_){Bn.trace(_)}})}a(OX,"updateRemoteConsumer");async function bX(e,t,r,n){let s=yd.createNatsTableStreamName(e,t),i=r+Vt.SERVER_SUFFIX.LEAF,o={type:De.ITC_EVENT_TYPES.NATS_CONSUMER_UPDATE,status:n,stream_name:s,node_domain_name:i};if(!ZD&&z3()<Pt.get(De.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXINGESTTHREADS)){let{updateConsumer:c}=wS();await c(o)}await W3(o),n==="stop"&&await bd.async_set_timeout(1e3)}a(bX,"updateConsumerIterator");function uL(e){return K3.writeTransaction(De.SYSTEM_SCHEMA_NAME,De.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,e)}a(uL,"exclusiveLock");async function lL(e,t){let r=yd.createNatsTableStreamName(e,t),n=await Id(),s=wX(e,t,n);await HS(r,[s])}a(lL,"createLocalTableStream");async function yX(e){for(let t=0,r=e.length;t<r;t++){let n=e[t].schema,s=e[t].table;await lL(n,s)}}a(yX,"createTableStreams");async function _L(e,t,r=void 0){if(Pt.get(De.CONFIG_PARAMS.CLUSTERING_ENABLED))try{let n=yd.createNatsTableStreamName(e,t),{jsm:s}=await Hn();await s.streams.purge(n,r)}catch(n){if(n.message==="stream not found")Bn.warn(n);else throw n}}a(_L,"purgeTableStream");async function NX(e,t){if(Pt.get(De.CONFIG_PARAMS.CLUSTERING_ENABLED))for(let r=0,n=t.length;r<n;r++)await _L(e,t[r])}a(NX,"purgeSchemaTableStreams");async function IX(e){return(await mu()).streams.info(e)}a(IX,"getStreamInfo");function wX(e,t,r){return`${Vt.SUBJECT_PREFIXES.TXN}.${e}${t?"."+t:""}.${r}`}a(wX,"createSubjectName");async function Id(){if(Eu)return Eu;if(Eu=(await mu())?.nc?.info?.server_name,Eu===void 0)throw new Error("Unable to get jetstream manager server name");return Eu}a(Id,"getJsmServerName");async function CX(){let e=await mu(),t=await Id(),r=await oL();for(let n of r){let s=n.config,i=s.subjects[0];if(!i)continue;let o=DX(n),c=i.split(".");if(c[c.length-1]===t&&!o||s.name==="__HARPERDB_WORK_QUEUE__")continue;let _=i.split(".");_[_.length-1]=t;let l=_.join(".");Bn.trace(`Updating stream subject name from: ${i} to: ${l}`),s.subjects[0]=l,await e.streams.update(s.name,s)}}a(CX,"updateLocalStreams");function DX(e){let{config:t}=e,r=!1,n=Pt.get(De.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE);n=n===null?0:n*1e9;let s=Pt.get(De.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXBYTES);s=s===null?-1:s;let i=Pt.get(De.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(DX,"updateStreamLimits");async function LX(e){let t,r;try{t=await Er.jetstream({domain:e}),r=await Er.jetstreamManager({domain:e,checkAPI:!1})}catch(n){throw Bn.error("Unable to connect to:",e),n}return{js:t,jsm:r}}a(LX,"connectToRemoteJS")});var Su=g((Cfe,mL)=>{"use strict";var la=O_(),_a=RD(),MX=$(),UX=require("uuid").v4,wfe=require("clone"),Cd=bs(),da=L(),PX=require("util"),_i=Cn(),{handleHDBError:hr,hdb_errors:vX}=ne(),{HDB_ERROR_MSGS:wd,HTTP_STATUS_CODES:mr}=vX,{SchemaEventMsg:Dd}=Mn(),fL=it(),{getDatabases:BX}=(Re(),ie(Fe)),{transformReq:fa}=Q();mL.exports={createSchema:HX,createSchemaStructure:EL,createTable:xX,createTableStructure:hL,createAttribute:VX,dropSchema:GX,dropTable:qX,dropAttribute:FX,getBackup:$X};async function HX(e){let t=await EL(e);return Cd.signalSchemaChange(new Dd(process.pid,e.operation,e.schema)),t}a(HX,"createSchema");async function EL(e){let t=la.schema_object(e);if(t)throw hr(t,t.message,mr.BAD_REQUEST,void 0,void 0,!0);if(fa(e),!await _a.checkSchemaExists(e.schema))throw hr(new Error,wd.SCHEMA_EXISTS_ERR(e.schema),mr.BAD_REQUEST,da.LOG_LEVELS.ERROR,wd.SCHEMA_EXISTS_ERR(e.schema),!0);return await _i.createSchema(e),`database '${e.schema}' successfully created`}a(EL,"createSchemaStructure");async function xX(e){return fa(e),e.hash_attribute=e.primary_key??e.hash_attribute,await hL(e)}a(xX,"createTable");async function hL(e){let t=la.create_table_object(e);if(t)throw hr(t,t.message,mr.BAD_REQUEST,void 0,void 0,!0);if(la.validateTableResidence(e.residence),!await _a.checkSchemaTableExists(e.schema,e.table))throw hr(new Error,wd.TABLE_EXISTS_ERR(e.schema,e.table),mr.BAD_REQUEST,da.LOG_LEVELS.ERROR,wd.TABLE_EXISTS_ERR(e.schema,e.table),!0);let n={name:e.table,schema:e.schema,id:UX(),hash_attribute:e.hash_attribute};try{if(e.residence)if(global.clustering_on)n.residence=e.residence,await _i.createTable(n,e);else throw hr(new Error,"Clustering does not appear to be enabled. Cannot insert table with property 'residence'.",mr.BAD_REQUEST);else await _i.createTable(n,e);return`table '${e.schema}.${e.table}' successfully created.`}catch(s){throw s}}a(hL,"createTableStructure");async function GX(e){let t=!e.schema&&!e.database?new Error("database is required"):void 0,r=la.schema_object(e),n=t??r;if(n)throw hr(n,n.message,mr.BAD_REQUEST,void 0,void 0,!0);fa(e);let s=await _a.checkSchemaExists(e.schema);if(s)throw hr(new Error,s,mr.NOT_FOUND,da.LOG_LEVELS.ERROR,s,!0);let i=await _a.schema_describe.describeSchema({schema:e.schema}),o=Object.keys(global.hdb_schema[e.schema]);return await _i.dropSchema(e),Cd.signalSchemaChange(new Dd(process.pid,e.operation,e.schema)),await fL.purgeSchemaTableStreams(e.schema,o),`successfully deleted '${e.schema}'`}a(GX,"dropSchema");async function qX(e){let t=la.table_object(e);if(t)throw hr(t,t.message,mr.BAD_REQUEST,void 0,void 0,!0);fa(e);let r=await _a.checkSchemaTableExists(e.schema,e.table);if(r)throw hr(new Error,r,mr.NOT_FOUND,da.LOG_LEVELS.ERROR,r,!0);return await _i.dropTable(e),await fL.purgeTableStream(e.schema,e.table),`successfully deleted table '${e.schema}.${e.table}'`}a(qX,"dropTable");async function FX(e){let t=la.attribute_object(e);if(t)throw hr(t,t.message,mr.BAD_REQUEST,void 0,void 0,!0);fa(e);let r=await _a.checkSchemaTableExists(e.schema,e.table);if(r)throw hr(new Error,r,mr.NOT_FOUND,da.LOG_LEVELS.ERROR,r,!0);if(e.attribute===global.hdb_schema[e.schema][e.table].hash_attribute)throw hr(new Error,"You cannot drop a hash attribute",mr.BAD_REQUEST,void 0,void 0,!0);if(da.TIME_STAMP_NAMES.indexOf(e.attribute)>=0)throw hr(new Error,`cannot drop internal timestamp attribute: ${e.attribute}`,mr.BAD_REQUEST,void 0,void 0,!0);try{return await _i.dropAttribute(e),kX(e),Cd.signalSchemaChange(new Dd(process.pid,e.operation,e.schema,e.table,e.attribute)),`successfully deleted attribute '${e.attribute}'`}catch(n){throw MX.error(`Got an error deleting attribute ${PX.inspect(e)}.`),n}}a(FX,"dropAttribute");function kX(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(kX,"dropAttributeFromGlobal");async function VX(e){fa(e);let t=BX()[e.schema][e.table].attributes;for(let{name:r}of t)if(r===e.attribute)throw hr(new Error,`attribute '${e.attribute}' already exists in ${e.schema}.${e.table}`,mr.BAD_REQUEST,void 0,void 0,!0);return await _i.createAttribute(e),Cd.signalSchemaChange(new Dd(process.pid,e.operation,e.schema,e.table,e.attribute)),`attribute '${e.schema}.${e.table}.${e.attribute}' successfully created.`}a(VX,"createAttribute");function $X(e){return _i.getBackup(e)}a($X,"getBackup")});var SL=g((Lfe,pL)=>{"use strict";var{OPERATIONS_ENUM:YX}=L(),GS=class{static{a(this,"ReadAuditLogObject")}constructor(t,r,n=void 0,s=void 0){this.operation=YX.READ_AUDIT_LOG,this.schema=t,this.table=r,this.search_type=n,this.search_values=s}};pL.exports=GS});var qS=g((Pfe,OL)=>{"use strict";var KX=Cn(),Ufe=SL(),Ld=Q(),Md=L(),WX=ee(),{handleHDBError:TL,hdb_errors:QX}=ne(),{HDB_ERROR_MSGS:gL,HTTP_STATUS_CODES:RL}=QX,zX=Object.values(Md.READ_AUDIT_LOG_SEARCH_TYPES_ENUM),AL="To use this operation audit log must be enabled in harperdb-config.yaml";OL.exports=JX;async function JX(e){if(Ld.isEmpty(e.schema))throw new Error(gL.SCHEMA_REQUIRED_ERR);if(Ld.isEmpty(e.table))throw new Error(gL.TABLE_REQUIRED_ERR);if(!WX.get(Md.CONFIG_PARAMS.LOGGING_AUDITLOG))throw TL(new Error,AL,RL.BAD_REQUEST,Md.LOG_LEVELS.ERROR,AL,!0);let t=Ld.checkSchemaTableExist(e.schema,e.table);if(t)throw TL(new Error,t,RL.NOT_FOUND,Md.LOG_LEVELS.ERROR,t,!0);if(!Ld.isEmpty(e.search_type)&&zX.indexOf(e.search_type)<0)throw new Error(`Invalid search_type '${e.search_type}'`);return await KX.readAuditLog(e)}a(JX,"readAuditLog")});var yL=g((Bfe,bL)=>{"use strict";var{OPERATIONS_ENUM:XX}=L(),FS=class{static{a(this,"GetBackupObject")}constructor(t,r,n=void 0,s=void 0){this.operation=XX.GET_BACKUP,this.schema=t,this.table=r}};bL.exports=FS});var wL=g((qfe,IL)=>{"use strict";var jX=Cn(),xfe=yL(),kS=Q(),ZX=L(),Gfe=ee(),{handleHDBError:ej,hdb_errors:tj}=ne(),{HDB_ERROR_MSGS:NL,HTTP_STATUS_CODES:rj}=tj;IL.exports=nj;async function nj(e){if(kS.isEmpty(e.schema))throw new Error(NL.SCHEMA_REQUIRED_ERR);if(kS.isEmpty(e.table))throw new Error(NL.TABLE_REQUIRED_ERR);let t=kS.checkSchemaTableExist(e.schema,e.table);if(t)throw ej(new Error,t,rj.NOT_FOUND,ZX.LOG_LEVELS.ERROR,t,!0);return await jX.getBackup(read_audit_log_object)}a(nj,"getBackup")});var PL=g((kfe,UL)=>{var di=require("validate.js"),DL=Xe(),Ea=L(),{handleHDBError:sj,hdb_errors:ij}=ne(),{HDB_ERROR_MSGS:dt,HTTP_STATUS_CODES:oj}=ij,VS=a(()=>({role:{presence:!0,format:"[\\w\\-\\_]+"},id:{presence:!0,format:"[\\w\\-\\_]+"},permission:{presence:!0}}),"constraintsTemplate"),aj={STRUCTURE_USER:"structure_user"},CL=Object.values(Ea.ROLE_TYPES_ENUM),cj="attribute_permissions",uj="attribute_name",{PERMS_CRUD_ENUM:ha}=Ea,lj=[cj,...Object.values(ha)],LL=[ha.READ,ha.INSERT,ha.UPDATE],_j=[uj,...LL];function dj(e){let t=VS();return t.role.presence=!0,t.id.presence=!1,t.permission.presence=!0,ML(e,t)}a(dj,"addRoleValidation");function fj(e){let t=VS();return t.role.presence=!1,t.id.presence=!0,t.permission.presence=!0,ML(e,t)}a(fj,"alterRoleValidation");function Ej(e){let t=VS();return t.role.presence=!1,t.id.presence=!0,t.permission.presence=!1,DL.validateObject(e,t)}a(Ej,"dropRoleValidation");var hj=["operation","role","id","permission","hdb_user","hdb_auth_header"];function ML(e,t){let r={main_permissions:[],schema_permissions:{}},n=Object.keys(e),s=[];for(let o=0,c=n.length;o<c;o++)hj.includes(n[o])||s.push(n[o]);s.length>0&&St(dt.INVALID_ROLE_JSON_KEYS(s),r);let i=DL.validateObject(e,t);if(i&&i.message.split(",").forEach(o=>{St(o,r)}),e.permission){let o=mj(e);o&&St(o,r),CL.forEach(c=>{e.permission[c]&&!di.isBoolean(e.permission[c])&&St(dt.SU_CU_ROLE_BOOLEAN_ERROR(c),r)})}for(let o in e.permission)if(CL.indexOf(o)<0){if(o===aj.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]||St(dt.SCHEMA_NOT_FOUND(d),r)}continue}St(dt.STRUCTURE_USER_ROLE_TYPE_ERROR(o),r);continue}let c=e.permission[o];if(!o||!global.hdb_schema[o]){St(dt.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]){St(dt.TABLE_NOT_FOUND(o,u),r);continue}if(Object.keys(_).forEach(l=>{lj.includes(l)||St(dt.INVALID_PERM_KEY(l),r,o,u)}),Object.values(ha).forEach(l=>{di.isDefined(_[l])?di.isBoolean(_[l])||St(dt.TABLE_PERM_NOT_BOOLEAN(l),r,o,u):St(dt.TABLE_PERM_MISSING(l),r,o,u)}),di.isDefined(_.attribute_permissions)){if(!di.isArray(_.attribute_permissions)){St(dt.ATTR_PERMS_NOT_ARRAY,r,o,u);continue}}else{St(dt.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=>{!_j.includes(p)&&p!==ha.DELETE&&St(dt.INVALID_ATTR_PERM_KEY(p),r,o,u)}),!di.isDefined(E.attribute_name)){St(dt.ATTR_PERM_MISSING_NAME,r,o,u);continue}let h=E.attribute_name;if(!l.includes(h)){St(dt.INVALID_ATTRIBUTE_IN_PERMS(h),r,o,u);continue}LL.forEach(p=>{di.isDefined(E[p])?di.isBoolean(E[p])||St(dt.ATTR_PERM_NOT_BOOLEAN(p,h),r,o,u):St(dt.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}`;St(dt.MISMATCHED_TABLE_ATTR_PERMS(f),r,o,u)}}}}return pj(r)}a(ML,"customValidate");UL.exports={addRoleValidation:dj,alterRoleValidation:fj,dropRoleValidation:Ej};function mj(e){let{operation:t,permission:r}=e;if(t===Ea.OPERATIONS_ENUM.ADD_ROLE||t===Ea.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 dt.SU_CU_ROLE_COMBINED_ERROR;{let o=r.super_user?Ea.ROLE_TYPES_ENUM.SUPER_USER:Ea.ROLE_TYPES_ENUM.CLUSTER_USER;return dt.SU_CU_ROLE_NO_PERMS_ALLOWED(o)}}}return null}a(mj,"validateNoSUPerms");function pj(e){let{main_permissions:t,schema_permissions:r}=e;if(t.length>0||Object.keys(r).length>0){let n={error:dt.ROLE_PERMS_ERROR,...e};return sj(new Error,n,oj.BAD_REQUEST)}else return null}a(pj,"generateRolePermResponse");function St(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(St,"addPermError")});var zS=g(($fe,xL)=>{"use strict";var vL=vr(),BL=Pr(),Sj=ii(),YS=PL(),KS=bs(),Tj=require("uuid").v4,gj=require("util"),Ud=L(),Rj=Q(),WS=BL.searchByValue,Aj=BL.searchByHash,Oj=gj.promisify(Sj.delete),bj=ts(),yj=sa(),{hdb_errors:Nj,handleHDBError:lo}=ne(),{HDB_ERROR_MSGS:HL,HTTP_STATUS_CODES:Tu}=Nj,{UserEventMsg:QS}=Mn();xL.exports={addRole:Ij,alterRole:wj,dropRole:Cj,listRoles:Dj};function $S(e){try{e.hdb_auth_header&&delete e.hdb_auth_header,e.HDB_INTERNAL_PATH&&delete e.HDB_INTERNAL_PATH,e.operation&&delete e.operation,e.hdb_user&&delete e.hdb_user}catch{}return e}a($S,"scrubRoleDetails");async function Ij(e){let t=YS.addRoleValidation(e);if(t)throw t;e=$S(e);let r={schema:"system",table:"hdb_role",search_attribute:"role",search_value:e.role,hash_attribute:"id",get_attributes:["*"]},n;try{n=Array.from(await WS(r)||[])}catch(i){throw lo(i)}if(n&&n.length>0)throw lo(new Error,HL.ROLE_ALREADY_EXISTS(e.role),Tu.CONFLICT,void 0,void 0,!0);e.id||(e.id=Tj());let s={operation:"insert",schema:"system",table:"hdb_role",hash_attribute:"id",records:[e]};return await vL.insert(s),KS.signalUserChange(new QS(process.pid)),e=$S(e),e}a(Ij,"addRole");async function wj(e){let t=YS.alterRoleValidation(e);if(t)throw t;e=$S(e);let r={operation:"update",schema:"system",table:"hdb_role",records:[e]},n;try{n=await vL.update(r)}catch(s){throw lo(s)}if(n&&n?.message==="updated 0 of 1 records")throw lo(new Error,"Invalid role id",Tu.BAD_REQUEST,void 0,void 0,!0);return await KS.signalUserChange(new QS(process.pid)),e}a(wj,"alterRole");async function Cj(e){let t=YS.dropRoleValidation(e);if(t)throw lo(new Error,t,Tu.BAD_REQUEST,void 0,void 0,!0);let r=new yj(Ud.SYSTEM_SCHEMA_NAME,Ud.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME,[e.id],["role"]),n=Array.from(await Aj(r));if(n.length===0)throw lo(new Error,HL.ROLE_NOT_FOUND,Tu.NOT_FOUND,void 0,void 0,!0);let s=new bj(Ud.SYSTEM_SCHEMA_NAME,Ud.SYSTEM_TABLE_NAMES.USER_TABLE_NAME,"role",e.id,void 0,["username","active"]),i=Array.from(await WS(s)),o=!1;if(Rj.isEmptyOrZeroLength(i)===!1){for(let u=0;u<i.length;u++)if(i[u].active===!0){o=!0;break}}if(o===!0)throw lo(new Error,`Cannot drop role ${n[0].role} as it has active user(s) tied to this role`,Tu.CONFLICT,void 0,void 0,!0);let c={table:"hdb_role",schema:"system",hash_values:[e.id]};return await Oj(c),KS.signalUserChange(new QS(process.pid)),`${n[0].role} successfully deleted`}a(Cj,"dropRole");async function Dj(){return WS({table:"hdb_role",schema:"system",hash_attribute:"id",search_attribute:"id",search_value:"*",get_attributes:["*"]})}a(Dj,"listRoles")});var kL=g((Kfe,FL)=>{"use strict";var Lj=ee(),fi=require("joi"),Mj=Xe(),GL=require("moment"),Uj=require("fs-extra"),JS=require("path"),Pj=require("lodash"),gu=L(),{LOG_LEVELS:_o}=L(),vj="YYYY-MM-DD hh:mm:ss",Bj=JS.resolve(__dirname,"../logs");FL.exports=function(e){return Mj.validateBySchema(e,Hj)};var Hj=fi.object({from:fi.custom(qL),until:fi.custom(qL),level:fi.valid(_o.NOTIFY,_o.FATAL,_o.ERROR,_o.WARN,_o.INFO,_o.DEBUG,_o.TRACE),order:fi.valid("asc","desc"),limit:fi.number().min(1),start:fi.number().min(0),log_name:fi.custom(xj)});function qL(e,t){if(GL(e,GL.ISO_8601).format(vj)==="Invalid date")return t.message(`'${t.state.path[0]}' date '${e}' is invalid.`)}a(qL,"validateDatetime");function xj(e,t){if(Pj.invert(gu.LOG_NAMES)[e]===void 0)return t.message(`'log_name' '${e}' is invalid.`);let n=Lj.get(gu.HDB_SETTINGS_NAMES.LOG_PATH_KEY),s=e===void 0?gu.LOG_NAMES.HDB:e,i=s===gu.LOG_NAMES.INSTALL?JS.join(Bj,gu.LOG_NAMES.INSTALL):JS.join(n,s);return Uj.existsSync(i)?null:t.message(`'log_name' '${e}' does not exist.`)}a(xj,"validateReadLogPath")});var jS=g((Qfe,$L)=>{"use strict";var Pd=L(),Gj=$(),qj=ee(),Fj=kL(),XS=require("path"),VL=require("fs-extra"),{once:kj}=require("events"),{handleHDBError:Vj,hdb_errors:$j}=ne(),{PACKAGE_ROOT:Yj}=L(),Kj=XS.join(Yj,"logs"),Wj=1e3,Qj=200;$L.exports=zj;async function zj(e){let t=Fj(e);if(t)throw Vj(t,t.message,$j.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0);let r=qj.get(Pd.HDB_SETTINGS_NAMES.LOG_PATH_KEY),n=e.log_name===void 0?Pd.LOG_NAMES.HDB:e.log_name,s=n===Pd.LOG_NAMES.INSTALL?XS.join(Kj,Pd.LOG_NAMES.INSTALL):XS.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?Wj: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(VL.statSync(s).size-(h+5)*Qj,0));let S=VL.createReadStream(s,{start:p});S.on("error",P=>{Gj.error(P)});let T=0,A=[],R="",M;S.on("data",P=>{let k=/(?:^|\n)(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:[\d\.]+Z) \[(.+?)]: /g;P=R+P;let B=0,X;for(;(X=k.exec(P))&&!S.destroyed;){M&&(M.message=P.slice(B,X.index),x(M));let[z,J,me]=X,ce=me.split("] ["),de=ce[0],Le=ce[1];ce.splice(0,2),M={timestamp:J,thread:de,level:Le,tags:ce,message:""},B=X.index+z.length}R=P.slice(B)}),S.on("end",P=>{S.destroyed||M&&(M.message=R.trim(),x(M))}),S.resume();function x(P){let k,B,X;switch(!0){case(i&&c&&_):k=new Date(P.timestamp),B=new Date(u),X=new Date(l),P.level===o&&k>=B&&k<=X&&T<E?T++:P.level===o&&k>=B&&k<=X&&(Ei(P,f,A),T++,T===h&&S.destroy());break;case(i&&c):k=new Date(P.timestamp),B=new Date(u),P.level===o&&k>=B&&T<E?T++:P.level===o&&k>=B&&(Ei(P,f,A),T++,T===h&&S.destroy());break;case(i&&_):k=new Date(P.timestamp),X=new Date(l),P.level===o&&k<=X&&T<E?T++:P.level===o&&k<=X&&(Ei(P,f,A),T++,T===h&&S.destroy());break;case(c&&_):k=new Date(P.timestamp),B=new Date(u),X=new Date(l),k>=B&&k<=X&&T<E?T++:k>=B&&k<=X&&(Ei(P,f,A),T++,T===h&&S.destroy());break;case i:P.level===o&&T<E?T++:P.level===o&&(Ei(P,f,A),T++,T===h&&S.destroy());break;case c:k=new Date(P.timestamp),B=new Date(u),k>=B&&T<E?T++:k>=B&&T>=E&&(Ei(P,f,A),T++,T===h&&S.destroy());break;case _:k=new Date(P.timestamp),X=new Date(l),k<=X&&T<E?T++:k<=X&&T>=E&&(Ei(P,f,A),T++,T===h&&S.destroy());break;default:T<E?T++:(Ei(P,f,A),T++,T===h&&S.destroy())}}return a(x,"onLogMessage"),await kj(S,"close"),A}a(zj,"readLog");function Ei(e,t,r){t==="desc"?Jj(e,r):t==="asc"?Xj(e,r):r.push(e)}a(Ei,"pushLineToResult");function Jj(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(Jj,"insertDescending");function Xj(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(Xj,"insertAscending")});var vd=g((Zfe,QL)=>{"use strict";var ZS=require("joi"),{string:Ru,boolean:YL,date:jj}=ZS.types(),Zj=Xe(),{validateSchemaExists:Jfe,validateTableExists:Xfe,validateSchemaName:jfe}=Jn(),eZ=L(),tZ=ke(),KL=ee();KL.initSync();var rZ=Ru.invalid(KL.get(eZ.CONFIG_PARAMS.CLUSTERING_NODENAME)).pattern(tZ.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(),WL={operation:Ru.valid("add_node","update_node","set_node_replication"),node_name:rZ,subscriptions:ZS.array().items({table:Ru.optional(),schema:Ru.optional(),database:Ru.optional(),subscribe:YL.required(),publish:YL.required().custom(sZ),start_time:jj.iso()}).min(1).required()};function nZ(e){return Zj.validateBySchema(e,ZS.object(WL))}a(nZ,"addUpdateNodeValidator");function sZ(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(sZ,"checkForFalsy");QL.exports={addUpdateNodeValidator:nZ,validation_schema:WL}});var JL=g((tEe,zL)=>{var iZ=Xe(),oZ={user:{presence:!0},schema:{presence:!0},table:{presence:!0},operation:{presence:!0}};zL.exports=function(e){return iZ.validateObject(e,oZ)}});var Bd=g((rEe,XL)=>{"use strict";var aZ=L().OPERATIONS_ENUM,eT=class{static{a(this,"UpdateObject")}constructor(t,r,n,s=void 0){this.operation=aZ.UPDATE,this.schema=t,this.table=r,this.records=n,this.__origin=s}};XL.exports=eT});var ZL=g((sEe,jL)=>{"use strict";var cZ={OPERATION:"operation",REFRESH:"refresh"},tT=class{static{a(this,"JWTTokens")}constructor(t,r){this.operation_token=t,this.refresh_token=r}},rT=class{static{a(this,"JWTRSAKeys")}constructor(t,r,n){this.public_key=t,this.private_key=r,this.passphrase=n}};jL.exports={JWTTokens:tT,TOKEN_TYPE_ENUM:cZ,JWTRSAKeys:rT}});var bu=g((oEe,nM)=>{"use strict";var Ou=require("jsonwebtoken"),nT=require("fs-extra"),sT=Q(),un=L(),{handleHDBError:pr,hdb_errors:uZ}=ne(),{HTTP_STATUS_CODES:Sr,AUTHENTICATION_ERROR_MSGS:Tr}=uZ,Au=$(),eM=G_(),aT=an(),lZ=vr().update,_Z=Bd(),dZ=bs(),{UserEventMsg:fZ}=Mn(),hi=ee();hi.initSync();var iT=require("path"),{JWTTokens:EZ,JWTRSAKeys:hZ,TOKEN_TYPE_ENUM:Hd}=ZL(),mZ=hi.get(un.HDB_SETTINGS_NAMES.OPERATION_TOKEN_TIMEOUT_KEY)?hi.get(un.HDB_SETTINGS_NAMES.OPERATION_TOKEN_TIMEOUT_KEY):"1d",pZ=hi.get(un.HDB_SETTINGS_NAMES.REFRESH_TOKEN_TIMEOUT_KEY)?hi.get(un.HDB_SETTINGS_NAMES.REFRESH_TOKEN_TIMEOUT_KEY):"30d",xd="RS256",oT;nM.exports={createTokens:SZ,validateOperationToken:gZ,refreshOperationToken:TZ,validateRefreshToken:rM};async function SZ(e){if(sT.isEmpty(e)||typeof e!="object")throw pr(new Error,Tr.INVALID_AUTH_OBJECT,Sr.BAD_REQUEST,void 0,void 0,!0);if(sT.isEmpty(e.username))throw pr(new Error,Tr.USERNAME_REQUIRED,Sr.BAD_REQUEST,void 0,void 0,!0);if(sT.isEmpty(e.password))throw pr(new Error,Tr.PASSWORD_REQUIRED,Sr.BAD_REQUEST,void 0,void 0,!0);let t;try{if(t=await aT.findAndValidateUser(e.username,e.password),!t)throw pr(new Error,Tr.INVALID_CREDENTIALS,Sr.UNAUTHORIZED,void 0,void 0,!0)}catch(f){throw Au.error(f),pr(new Error,Tr.INVALID_CREDENTIALS,Sr.UNAUTHORIZED,void 0,void 0,!0)}let r=await Gd(),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 tM(i,r.private_key,r.passphrase),c=await Ou.sign(i,{key:r.private_key,passphrase:r.passphrase},{expiresIn:pZ,algorithm:xd,subject:Hd.REFRESH}),u=eM.hash(c),_=new _Z(un.SYSTEM_SCHEMA_NAME,un.SYSTEM_TABLE_NAMES.USER_TABLE_NAME,[{username:e.username,refresh_token:u}]),l,d;try{l=await lZ(_)}catch(f){Au.error(f),d=f}if(d!==void 0||l.skipped_hashes.length>0)throw pr(new Error,Tr.REFRESH_TOKEN_SAVE_FAILED,Sr.INTERNAL_SERVER_ERROR);return dZ.signalUserChange(new fZ(process.pid)),new EZ(o,c)}a(SZ,"createTokens");async function tM(e,t,r){return await Ou.sign(e,{key:t,passphrase:r},{expiresIn:mZ,algorithm:xd,subject:Hd.OPERATION})}a(tM,"signOperationToken");async function Gd(){if(oT===void 0)try{let e=iT.join(hi.getHdbBasePath(),un.LICENSE_KEY_DIR_NAME,un.JWT_ENUM.JWT_PASSPHRASE_NAME),t=iT.join(hi.getHdbBasePath(),un.LICENSE_KEY_DIR_NAME,un.JWT_ENUM.JWT_PRIVATE_KEY_NAME),r=iT.join(hi.getHdbBasePath(),un.LICENSE_KEY_DIR_NAME,un.JWT_ENUM.JWT_PUBLIC_KEY_NAME),n=(await nT.readFile(e)).toString(),s=(await nT.readFile(t)).toString(),i=(await nT.readFile(r)).toString();oT=new hZ(i,s,n)}catch(e){throw Au.error(e),pr(new Error,Tr.NO_ENCRYPTION_KEYS,Sr.INTERNAL_SERVER_ERROR)}return oT}a(Gd,"getJWTRSAKeys");async function TZ(e){if(!e)throw pr(new Error,Tr.INVALID_BODY,Sr.BAD_REQUEST,void 0,void 0,!0);if(!e.refresh_token)throw pr(new Error,Tr.REFRESH_TOKEN_REQUIRED,Sr.BAD_REQUEST,void 0,void 0,!0);await rM(e.refresh_token);let t=await Gd(),r=await Ou.decode(e.refresh_token);return{operation_token:await tM({username:r.username,super_user:r.super_user,cluster_user:r.cluster_user},t.private_key,t.passphrase)}}a(TZ,"refreshOperationToken");async function gZ(e){try{let t=await Gd(),r=await Ou.verify(e,t.public_key,{algorithms:xd,subject:Hd.OPERATION});return await aT.findAndValidateUser(r.username,void 0,!1)}catch(t){throw Au.warn(t),t.name&&t.name==="TokenExpiredError"?pr(new Error,Tr.TOKEN_EXPIRED,Sr.FORBIDDEN):pr(new Error,Tr.INVALID_TOKEN,Sr.UNAUTHORIZED)}}a(gZ,"validateOperationToken");async function rM(e){let t;try{let r=await Gd(),n=await Ou.verify(e,r.public_key,{algorithms:xd,subject:Hd.REFRESH});t=await aT.findAndValidateUser(n.username,void 0,!1)}catch(r){throw Au.warn(r),r.name&&r.name==="TokenExpiredError"?pr(new Error,Tr.TOKEN_EXPIRED,Sr.FORBIDDEN):pr(new Error,Tr.INVALID_TOKEN,Sr.UNAUTHORIZED)}if(!eM.validate(t.refresh_token,e))throw pr(new Error,Tr.INVALID_TOKEN,Sr.UNAUTHORIZED);return t}a(rM,"validateRefreshToken")});var cT=g((uEe,oM)=>{"use strict";var RZ=JL(),ma=require("passport"),AZ=require("passport-local").Strategy,OZ=require("passport-http").BasicStrategy,bZ=require("util"),yZ=an(),iM=bZ.callbackify(yZ.findAndValidateUser),cEe=Cr(),NZ=L(),sM=bu();ma.use(new AZ(function(e,t,r){iM(e,t,r)}));ma.use(new OZ(function(e,t,r){iM(e,t,r)}));ma.serializeUser(function(e,t){t(null,e)});ma.deserializeUser(function(e,t){t(null,e)});function IZ(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":ma.authenticate("basic",{session:!1},(o,c)=>{i(o,c)})(e,t,r);break;case"Bearer":e.body?.operation&&e.body.operation===NZ.OPERATIONS_ENUM.REFRESH_OPERATION_TOKEN?sM.validateRefreshToken(s).then(o=>{e.body.refresh_token=s,r(null,o)}).catch(o=>{r(o)}):sM.validateOperationToken(s).then(o=>{r(null,o)}).catch(o=>{r(o)});break;default:ma.authenticate("local",{session:!1},function(o,c){i(o,c)})(e,t,r);break}}a(IZ,"authorize");function wZ(e,t){let r=RZ(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(wZ,"checkPermissions");oM.exports={authorize:IZ,checkPermissions:wZ}});var mi=g((_Ee,aM)=>{"use strict";var uT=class{static{a(this,"Node")}constructor(t,r,n){this.name=t,this.subscriptions=r,this.system_info=n}},lT=class{static{a(this,"NodeSubscription")}constructor(t,r,n,s){this.schema=t,this.table=r,this.publish=n,this.subscribe=s}};aM.exports={Node:uT,NodeSubscription:lT}});var uM=g((fEe,cM)=>{"use strict";var CZ=L().OPERATIONS_ENUM,_T=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}};cM.exports=_T});var yu=g((hEe,lM)=>{"use strict";var dT=class{static{a(this,"RemotePayloadObject")}constructor(t,r,n,s){this.operation=t,this.node_name=r,this.subscriptions=n,this.system_info=s}},fT=class{static{a(this,"RemotePayloadSubscription")}constructor(t,r,n,s,i,o,c){this.schema=t,this.table=r,this.hash_attribute=n,this.publish=s,this.subscribe=i,this.start_time=o,c!==void 0&&(this.attributes=c)}};lM.exports={RemotePayloadObject:dT,RemotePayloadSubscription:fT}});var dM=g((pEe,_M)=>{"use strict";var ET=class{static{a(this,"TableSizeObject")}constructor(t,r,n=0,s=0,i=0,o=0){this.schema=t,this.table=r,this.table_size=n,this.record_count=s,this.transaction_log_size=i,this.transaction_log_record_count=o}};_M.exports=ET});var hM=g((AEe,EM)=>{"use strict";var DZ=dM(),TEe=ut(),fM=We(),LZ=$(),{getSchemaPath:gEe,getTransactionAuditStorePath:REe}=Je(),{getDatabases:MZ}=(Re(),ie(Fe));EM.exports=UZ;async function UZ(e){let t=new DZ;try{let r=MZ()[e.schema]?.[e.name],n=r.primaryStore.getStats(),s=r.auditStore?.getStats(),i=await fM.environmentDataSize(schema_path,e.name),o=await fM.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){LZ.warn(`unable to stat table dbi due to ${r}`)}return t}a(UZ,"lmdbGetTableSize")});var pM=g((bEe,mM)=>{"use strict";var hT=class{static{a(this,"SystemInformationObject")}constructor(t,r,n,s,i,o,c){this.system=t,this.time=r,this.cpu=n,this.memory=s,this.disk=i,this.network=o,this.harperdb_processes=c}};mM.exports=hT});var pa=g((CEe,AM)=>{"use strict";var PZ=require("fs-extra"),vZ=require("path"),Zt=require("systeminformation"),pi=$(),SM=it(),NEe=ke(),Fd=L(),BZ=hM(),HZ=As(),{getThreadInfo:TM}=Ke(),yT=ee();yT.initSync();var xZ=pM(),{openEnvironment:IEe}=We(),{getSchemaPath:wEe}=Je(),{database:GZ,databases:gM}=(Re(),ie(Fe)),qd;AM.exports={getHDBProcessInfo:TT,getNetworkInfo:RT,getDiskInfo:gT,getMemoryInfo:ST,getCPUInfo:pT,getTimeInfo:mT,getSystemInformation:AT,systemInformation:qZ,getTableSize:OT,getMetrics:bT};function mT(){return Zt.time()}a(mT,"getTimeInfo");async function pT(){try{let{family:e,model:t,stepping:r,revision:n,voltage:s,speedmin:i,speedmax:o,governor:c,socket:u,cache:_,...l}=await Zt.cpu();l.cpu_speed=await Zt.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 Zt.currentLoad();return A.cpus=[],T.forEach(R=>{let{raw_load:M,raw_load_idle:x,raw_load_irq:P,raw_load_nice:k,raw_load_system:B,raw_load_user:X,...z}=R;A.cpus.push(z)}),l.current_load=A,l}catch(e){return pi.error(`error in getCPUInfo: ${e}`),{}}}a(pT,"getCPUInfo");async function ST(){try{let{buffers:e,cached:t,slab:r,buffcache:n,...s}=await Zt.mem();return Object.assign(s,process.memoryUsage())}catch(e){return pi.error(`error in getMemoryInfo: ${e}`),{}}}a(ST,"getMemoryInfo");async function TT(){let e={core:[],clustering:[]};try{let t=await Zt.processes(),r;try{r=Number.parseInt(await PZ.readFile(vZ.join(yT.get(Fd.CONFIG_PARAMS.ROOTPATH),Fd.HDB_PID_FILE),"utf8"))}catch(n){if(n.code===Fd.NODE_ERROR_CODES.ENOENT)pi.warn("Unable to locate 'hdb.pid' file, try stopping and starting HarperDB. This could be because HarperDB is not running.");else throw n}t.list.forEach(n=>{n.pid===r?e.core.push(n):n.name==="nats-server"&&e.clustering.push(n)});for(let n of e.core)for(let s of t.list)s.pid===n.parentPid&&(s.name==="PM2"||s.command==="PM2")&&(n.parent="PM2");return e}catch(t){return pi.error(`error in getHDBProcessInfo: ${t}`),e}}a(TT,"getHDBProcessInfo");async function gT(){let e={};try{let{rIO_sec:t,wIO_sec:r,tIO_sec:n,ms:s,...i}=await Zt.disksIO();e.io=i;let{rx_sec:o,tx_sec:c,wx_sec:u,..._}=await Zt.fsStats();return e.read_write=_,e.size=await Zt.fsSize(),e}catch(t){return pi.error(`error in getDiskInfo: ${t}`),e}}a(gT,"getDiskInfo");async function RT(){let e={default_interface:null,latency:{},interfaces:[],stats:[],connections:[]};try{return e.default_interface=await Zt.networkInterfaceDefault(),e.latency=await Zt.inetChecksite("google.com"),(await Zt.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 Zt.networkStats()).forEach(n=>{let{rx_sec:s,tx_sec:i,ms:o,...c}=n;e.stats.push(c)}),e}catch(t){return pi.error(`error in getNetworkInfo: ${t}`),e}}a(RT,"getNetworkInfo");async function AT(){if(qd!==void 0)return qd;let e={};try{let{codepage:t,logofile:r,serial:n,build:s,servicepack:i,uefi:o,...c}=await Zt.osInfo();e=c;let u=await Zt.versions("node, npm");return e.node_version=u.node,e.npm_version=u.npm,qd=e,qd}catch(t){return pi.error(`error in getSystemInformation: ${t}`),e}}a(AT,"getSystemInformation");async function OT(){let e=[],t=await HZ.describeAll();for(let r of Object.values(t))for(let n of Object.values(r))e.push(await BZ(n));return e}a(OT,"getTableSize");async function bT(){let e={};for(let t in gM){let r=e[t]={};for(let n in gM[t])try{let s=GZ({database:t,table:n}),i=s.getStats();i.readers=s.readerList().split(/\n\s+/).slice(1).map(o=>{let[c,u,_]=o.trim().split(" ");return{pid:c,thread:u,txnid:_}}),r[n]=i}catch(s){pi.notify(`Error getting stats for table ${n}: ${s}`)}}return e}a(bT,"getMetrics");async function RM(){if(yT.get(Fd.CONFIG_PARAMS.CLUSTERING_ENABLED)){let{jsm:e}=await SM.getNATSReferences(),t=await SM.listStreams(),r=[];for(let n of t){let s=[],i=await e.consumers.list(n.config.name);for await(let c of i)s.push({name:c.name,created:c.created,num_ack_pending:c.num_ack_pending,num_redelivered:c.num_redelivered,num_waiting:c.num_waiting,num_pending:c.num_pending});let o={stream_name:n.config.name,database:n.config.subjects[0].split(".")[1],table:n.config.subjects[0].split(".")[2],state:n.state,consumers:s};r.push(o)}return r}}a(RM,"getNatsStreamInfo");async function qZ(e){let t=new xZ;if(!Array.isArray(e.attributes)||e.attributes.length===0)return t.system=await AT(),t.time=mT(),t.cpu=await pT(),t.memory=await ST(),t.disk=await gT(),t.network=await RT(),t.harperdb_processes=await TT(),t.table_size=await OT(),t.metrics=await bT(),t.threads=await TM(),t.replication=await RM(),t;for(let r=0;r<e.attributes.length;r++)switch(e.attributes[r]){case"system":t.system=await AT();break;case"time":t.time=mT();break;case"cpu":t.cpu=await pT();break;case"memory":t.memory=await ST();break;case"disk":t.disk=await gT();break;case"network":t.network=await RT();break;case"harperdb_processes":t.harperdb_processes=await TT();break;case"table_size":t.table_size=await OT();break;case"database_metrics":case"metrics":t.metrics=await bT();break;case"threads":t.threads=await TM();break;case"replication":t.replication=await RM();break;default:break}return t}a(qZ,"systemInformation")});var Vd=g((LEe,OM)=>{"use strict";OM.exports={version:FZ,printVersion:kZ};var kd=iu();function FZ(){if(kd)return kd.version}a(FZ,"version");function kZ(){kd&&console.log(`HarperDB Version ${kd.version}`)}a(kZ,"printVersion")});var ln=g((vEe,IM)=>{"use strict";var VZ=vr(),NT=Q(),$Z=require("util"),fo=L(),bM=ee();bM.initSync();var YZ=cT(),yM=Pr(),{Node:UEe,NodeSubscription:PEe}=mi(),KZ=sa(),WZ=uM(),{RemotePayloadObject:QZ,RemotePayloadSubscription:zZ}=yu(),{handleHDBError:JZ,hdb_errors:XZ}=ne(),{HTTP_STATUS_CODES:jZ,HDB_ERROR_MSGS:ZZ}=XZ,e5=ts(),t5=pa(),r5=Vd(),{getDatabases:n5}=(Re(),ie(Fe)),s5=$Z.promisify(YZ.authorize),i5=yM.searchByHash,o5=yM.searchByValue;IM.exports={authHeaderToUser:a5,isEmpty:c5,getNodeRecord:u5,upsertNodeRecord:l5,buildNodePayloads:_5,checkClusteringEnabled:d5,getAllNodeRecords:f5,getSystemInfo:E5,reverseSubscription:NM};async function a5(e){let t={headers:{authorization:e.hdb_auth_header}};return e.hdb_user=await s5(t,null),e}a(a5,"authHeaderToUser");function c5(e){return e==null}a(c5,"isEmpty");async function u5(e){let t=new KZ(fo.SYSTEM_SCHEMA_NAME,fo.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[e],["*"]);return i5(t)}a(u5,"getNodeRecord");async function l5(e){let t=new WZ(fo.SYSTEM_SCHEMA_NAME,fo.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[e]);return VZ.upsert(t)}a(l5,"upsertNodeRecord");function NM(e){if(NT.isEmpty(e.subscribe)||NT.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(NM,"reverseSubscription");function _5(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=NT.getTableHashAttribute(u,_),{subscribe:d,publish:f}=NM(c),E=n5()[u]?.[_],h=new zZ(u,_,l,f,d,c.start_time,E.schemaDefined?E.attributes:void 0);s.push(h)}return new QZ(r,t,s,n)}a(_5,"buildNodePayloads");function d5(){if(!bM.get(fo.CONFIG_PARAMS.CLUSTERING_ENABLED))throw JZ(new Error,ZZ.CLUSTERING_NOT_ENABLED,jZ.BAD_REQUEST,void 0,void 0,!0)}a(d5,"checkClusteringEnabled");async function f5(){let e=new e5(fo.SYSTEM_SCHEMA_NAME,fo.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,"name","*",void 0,["*"]);return Array.from(await o5(e))}a(f5,"getAllNodeRecords");async function E5(){let e=await t5.getSystemInformation();return{hdb_version:r5.version(),node_version:e.node_version,platform:e.platform}}a(E5,"getSystemInfo")});var IT=g((HEe,vM)=>{"use strict";var $d=it(),wM=Q(),CM=ke(),DM=L(),Yd=$(),LM=Su(),h5=id(),{RemotePayloadObject:m5}=yu(),{handleHDBError:MM,hdb_errors:p5}=ne(),{HTTP_STATUS_CODES:UM}=p5,{NodeSubscription:PM}=mi();vM.exports=S5;async function S5(e,t){let r;try{r=await $d.request(`${t}.${CM.REQUEST_SUFFIX}`,new m5(DM.OPERATIONS_ENUM.DESCRIBE_ALL,t,void 0,void 0)),Yd.trace("Response from remote describe all request:",r)}catch(o){Yd.error(`addNode received error from describe all request to remote node: ${o}`);let c=$d.requestErrorHandler(o,"add_node",t);throw MM(new Error,c,UM.INTERNAL_SERVER_ERROR,"error",c)}if(r.status===CM.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let o=`Error returned from remote node ${t}: ${r.message}`;throw MM(new Error,o,UM.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===DM.SYSTEM_SCHEMA_NAME){await $d.createLocalTableStream(u,c);let h=new PM(u,c,o.publish,o.subscribe);h.start_time=o.start_time,i.push(h);continue}let _=wM.doesSchemaExist(u),l=n[u]!==void 0,d=c?wM.doesTableExist(u,c):!0,f=c?n?.[u]?.[c]!==void 0:!0;if(!_&&!l||!d&&!f){s.push(o);continue}if(!_&&l&&(Yd.trace(`addNode creating schema: ${u}`),await LM.createSchema({operation:"create_schema",schema:u})),!d&&f){Yd.trace(`addNode creating table: ${c} in schema: ${u} with attributes ${JSON.stringify(n[u][c].attributes)}`);let h=new h5(u,c,n[u][c].hash_attribute);n[u][c].attributes&&(h.attributes=n[u][c].attributes),await LM.createTable(h)}await $d.createLocalTableStream(u,c);let E=new PM(u,c,o.publish,o.subscribe);E.start_time=o.start_time,i.push(E)}return{added:i,skipped:s}}a(S5,"reviewSubscriptions")});var zd=g((GEe,xM)=>{"use strict";var{handleHDBError:Kd,hdb_errors:T5}=ne(),{HTTP_STATUS_CODES:Wd}=T5,{addUpdateNodeValidator:g5}=vd(),Qd=$(),HM=L(),BM=ke(),R5=Q(),Nu=it(),Iu=ln(),A5=ee(),O5=IT(),{Node:b5,NodeSubscription:y5}=mi(),{broadcast:N5}=Ke(),I5="Unable to create subscriptions due to schema and/or tables not existing on the local or remote node",w5="Some subscriptions were unsuccessful due to schema and/or tables not existing on the local or remote node",C5=A5.get(HM.CONFIG_PARAMS.CLUSTERING_NODENAME);xM.exports=D5;async function D5(e,t=!1){Qd.trace("addNode called with:",e),Iu.checkClusteringEnabled();let r=g5(e);if(r)throw Kd(r,r.message,Wd.BAD_REQUEST,void 0,void 0,!0);let n=e.node_name;if(!t){let d=await Iu.getNodeRecord(n);if(!R5.isEmptyOrZeroLength(d))throw Kd(new Error,`Node '${n}' has already been added, perform update_node to proceed.`,Wd.BAD_REQUEST,void 0,void 0,!0)}let{added:s,skipped:i}=await O5(e.subscriptions,n),o={message:void 0,added:s,skipped:i};if(s.length===0)return o.message=I5,o;let c=Iu.buildNodePayloads(s,C5,HM.OPERATIONS_ENUM.ADD_NODE,await Iu.getSystemInfo()),u=[];for(let d=0,f=s.length;d<f;d++){let E=s[d];s[d].start_time===void 0&&delete s[d].start_time,u.push(new y5(E.schema,E.table,E.publish,E.subscribe))}Qd.trace("addNode sending remote payload:",c);let _;try{_=await Nu.request(`${n}.${BM.REQUEST_SUFFIX}`,c)}catch(d){Qd.error(`addNode received error from request: ${d}`);for(let E=0,h=s.length;E<h;E++){let p=s[E];p.publish=!1,p.subscribe=!1,await Nu.updateRemoteConsumer(p,n)}let f=Nu.requestErrorHandler(d,"add_node",n);throw Kd(new Error,f,Wd.INTERNAL_SERVER_ERROR,"error",f)}if(_.status===BM.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let d=`Error returned from remote node ${n}: ${_.message}`;throw Kd(new Error,d,Wd.INTERNAL_SERVER_ERROR,"error",d)}Qd.trace(_);for(let d=0,f=s.length;d<f;d++){let E=s[d];await Nu.updateRemoteConsumer(E,n),E.subscribe===!0&&await Nu.updateConsumerIterator(E.schema,E.table,n,"start")}let l=new b5(n,u,_.system_info);return await Iu.upsertNodeRecord(l),N5({type:"nats_update"}),i.length>0?o.message=w5:o.message=`Successfully added '${n}' to manifest`,o}a(D5,"addNode")});var DT=g((kEe,FM)=>{"use strict";var{handleHDBError:wT,hdb_errors:L5}=ne(),{HTTP_STATUS_CODES:CT}=L5,{addUpdateNodeValidator:M5}=vd(),wu=$(),qM=L(),GM=ke(),FEe=Q(),Cu=it(),Du=ln(),U5=ee(),{cloneDeep:P5}=require("lodash"),v5=IT(),{Node:B5,NodeSubscription:H5}=mi(),{broadcast:x5}=Ke(),G5="Unable to update subscriptions due to schema and/or tables not existing on the local or remote node",q5="Some subscriptions were unsuccessful due to schema and/or tables not existing on the local or remote node",F5=U5.get(qM.CONFIG_PARAMS.CLUSTERING_NODENAME);FM.exports=k5;async function k5(e){wu.trace("updateNode called with:",e),Du.checkClusteringEnabled();let t=M5(e);if(t)throw wT(t,t.message,CT.BAD_REQUEST,void 0,void 0,!0);let r=e.node_name,n,s=await Du.getNodeRecord(r);s.length>0&&(n=P5(s));let{added:i,skipped:o}=await v5(e.subscriptions,r),c={message:void 0,updated:i,skipped:o};if(i.length===0)return c.message=G5,c;let u=Du.buildNodePayloads(i,F5,qM.OPERATIONS_ENUM.UPDATE_NODE,await Du.getSystemInfo());for(let l=0,d=i.length;l<d;l++){let f=i[l];wu.trace(`updateNode updating work stream for node: ${r} subscription:`,f),i[l].start_time===void 0&&delete i[l].start_time}wu.trace("updateNode sending remote payload:",u);let _;try{_=await Cu.request(`${r}.${GM.REQUEST_SUFFIX}`,u)}catch(l){wu.error(`updateNode received error from request: ${l}`);let d=Cu.requestErrorHandler(l,"update_node",r);throw wT(new Error,d,CT.INTERNAL_SERVER_ERROR,"error",d)}if(_.status===GM.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR){let l=`Error returned from remote node ${r}: ${_.message}`;throw wT(new Error,l,CT.INTERNAL_SERVER_ERROR,"error",l)}wu.trace(_);for(let l=0,d=i.length;l<d;l++){let f=i[l];await Cu.updateRemoteConsumer(f,r),f.subscribe===!0?await Cu.updateConsumerIterator(f.schema,f.table,r,"start"):await Cu.updateConsumerIterator(f.schema,f.table,r,"stop")}return n||(n=[new B5(r,[],_.system_info)]),await V5(n[0],i,_.system_info),o.length>0?c.message=q5:c.message=`Successfully updated '${r}'`,c}a(k5,"updateNode");async function V5(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 H5(o.schema,o.table,o.publish,o.subscribe))}n.system_info=r,await Du.upsertNodeRecord(n),x5({type:"nats_update"})}a(V5,"updateNodeTable")});var KM=g(($Ee,YM)=>{"use strict";var $M=require("joi"),{string:kM}=$M.types(),$5=Xe(),VM=L(),Y5=ee(),K5=ke();YM.exports=W5;function W5(e){let t=kM.invalid(Y5.get(VM.CONFIG_PARAMS.CLUSTERING_NODENAME)).pattern(K5.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=$M.object({operation:kM.valid(VM.OPERATIONS_ENUM.REMOVE_NODE).required(),node_name:t});return $5.validateBySchema(e,r)}a(W5,"removeNodeValidator")});var Xd=g((KEe,XM)=>{"use strict";var{handleHDBError:WM,hdb_errors:Q5}=ne(),{HTTP_STATUS_CODES:QM}=Q5,z5=KM(),Lu=$(),zM=ln(),J5=Q(),Jd=L(),JM=ke(),LT=it(),X5=ee(),{RemotePayloadObject:j5}=yu(),{NodeSubscription:Z5}=mi(),e8=ia(),t8=ii(),{broadcast:r8}=Ke(),n8=X5.get(Jd.CONFIG_PARAMS.CLUSTERING_NODENAME);XM.exports=s8;async function s8(e){Lu.trace("removeNode called with:",e),zM.checkClusteringEnabled();let t=z5(e);if(t)throw WM(t,t.message,QM.BAD_REQUEST,void 0,void 0,!0);let r=e.node_name,n=await zM.getNodeRecord(r);if(J5.isEmptyOrZeroLength(n))throw WM(new Error,`Node '${r}' was not found.`,QM.BAD_REQUEST,void 0,void 0,!0);n=n[0];let s=new j5(Jd.OPERATIONS_ENUM.REMOVE_NODE,n8,[]),i,o=!1;for(let u=0,_=n.subscriptions.length;u<_;u++){let l=n.subscriptions[u];l.subscribe===!0&&await LT.updateConsumerIterator(l.schema,l.table,r,"stop");try{await LT.updateRemoteConsumer(new Z5(l.schema,l.table,!1,!1),r)}catch(d){Lu.error(d)}}try{i=await LT.request(`${r}.${JM.REQUEST_SUFFIX}`,s),Lu.trace("Remove node reply from remote node:",r,i)}catch(u){Lu.error("removeNode received error from request:",u),o=!0}let c=new e8(Jd.SYSTEM_SCHEMA_NAME,Jd.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[r]);return await t8.deleteRecord(c),r8({type:"nats_update"}),i?.status===JM.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR||o?(Lu.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(s8,"removeNode")});var eU=g((QEe,ZM)=>{"use strict";var jM=require("joi"),{string:i8,array:o8}=jM.types(),a8=Xe(),c8=vd();ZM.exports=u8;function u8(e){let t=jM.object({operation:i8.valid("configure_cluster").required(),connections:o8.items(c8.validation_schema).required()});return a8.validateBySchema(e,t)}a(u8,"configureClusterValidator")});var MT=g((JEe,iU)=>{"use strict";var l8=L(),jd=$(),_8=Q(),d8=Xd(),f8=zd(),tU=ln(),E8=eU(),{handleHDBError:rU,hdb_errors:h8}=ne(),{HTTP_STATUS_CODES:nU}=h8,m8="Configure cluster complete.",p8="Failed to configure the cluster. Check the logs for more details.",S8="Configure cluster was partially successful. Errors occurred when attempting to configure the following nodes. Check the logs for more details.";iU.exports=T8;async function T8(e){jd.trace("configure cluster called with:",e),tU.checkClusteringEnabled();let t=E8(e);if(t)throw rU(t,t.message,nU.BAD_REQUEST,void 0,void 0,!0);let r=await tU.getAllNodeRecords(),n=[];for(let l=0,d=r.length;l<d;l++){let f=await sU(d8,{operation:l8.OPERATIONS_ENUM.REMOVE_NODE,node_name:r[l].name},r[l].name);n.push(f)}jd.trace("All results from configure_cluster remove node:",n);let s=[],i=e.connections.length;for(let l=0;l<i;l++){let d=e.connections[l],f=await sU(f8,d,d.node_name);s.push(f)}jd.trace("All results from configure_cluster add node:",s);let o=[],c=[],u=!1,_=n.concat(s);for(let l=0,d=_.length;l<d;l++){let f=_[l];f.status==="rejected"&&(jd.error(f),o.includes(f.node_name)||o.push(f.node_name)),(f?.result?.message?.includes?.("Successfully")||f?.result?.includes?.("Successfully"))&&(u=!0),!(typeof f.result=="string"&&f.result.includes("Successfully removed")||f.status==="rejected")&&c.push({node_name:f?.node_name,subscriptions:f?.result})}if(_8.isEmptyOrZeroLength(o))return{message:m8,connections:c};if(u)return{message:S8,failed_nodes:o,connections:c};throw rU(new Error,p8,nU.INTERNAL_SERVER_ERROR,void 0,void 0,!0)}a(T8,"configureCluster");async function sU(e,t,r){try{return{node_name:r,result:await e(t)}}catch(n){return{node_name:r,error:n,status:"rejected"}}}a(sU,"functionWrapper")});var uU=g((jEe,cU)=>{"use strict";var Mu=require("joi"),g8=Xe(),{validateSchemaExists:oU,validateTableExists:R8,validateSchemaName:aU}=Jn(),A8=Mu.object({operation:Mu.string().valid("purge_stream"),schema:Mu.string().custom(oU).custom(aU).optional(),database:Mu.string().custom(oU).custom(aU).optional(),table:Mu.string().custom(R8).required()});function O8(e){return g8.validateBySchema(e,A8)}a(O8,"purgeStreamValidator");cU.exports=O8});var UT=g((ehe,lU)=>{"use strict";var{handleHDBError:b8,hdb_errors:y8}=ne(),{HTTP_STATUS_CODES:N8}=y8,I8=uU(),w8=it(),C8=ln();lU.exports=D8;async function D8(e){e.schema=e.schema??e.database;let t=I8(e);if(t)throw b8(t,t.message,N8.BAD_REQUEST,void 0,void 0,!0);C8.checkClusteringEnabled();let{schema:r,table:n,options:s}=e;return await w8.purgeTableStream(r,n,s),`Successfully purged table '${r}.${n}'`}a(D8,"purgeStream")});var BT=g((rhe,mU)=>{"use strict";var vT=ln(),L8=it(),fU=ee(),Zd=L(),Eo=ke(),M8=Q(),PT=$(),{RemotePayloadObject:U8}=yu(),{ErrorCode:_U}=require("nats"),dU=fU.get(Zd.CONFIG_PARAMS.CLUSTERING_ENABLED),EU=fU.get(Zd.CONFIG_PARAMS.CLUSTERING_NODENAME);mU.exports={clusterStatus:P8,buildNodeStatus:hU};async function P8(){let e={node_name:EU,is_enabled:dU,connections:[]};if(!dU)return e;let t=await vT.getAllNodeRecords();if(M8.isEmptyOrZeroLength(t))return e;let r=[];for(let n=0,s=t.length;n<s;n++)r.push(hU(t[n],e.connections));return await Promise.allSettled(r),e}a(P8,"clusterStatus");async function hU(e,t){let r=e.name,n=new U8(Zd.OPERATIONS_ENUM.CLUSTER_STATUS,EU,void 0,await vT.getSystemInfo()),s,i,o=Eo.CLUSTER_STATUS_STATUSES.OPEN;try{let u=Date.now();s=await L8.request(Eo.REQUEST_SUBJECT(r),n),i=Date.now()-u,s.status===Eo.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR&&(o=Eo.CLUSTER_STATUS_STATUSES.CLOSED,PT.error(`Error getting node status from ${r} `,s))}catch(u){PT.warn(`Error getting node status from ${r}`,u),u.code===_U.NoResponders?o=Eo.CLUSTER_STATUS_STATUSES.NO_RESPONDERS:u.code===_U.Timeout?o=Eo.CLUSTER_STATUS_STATUSES.TIMEOUT:o=Eo.CLUSTER_STATUS_STATUSES.CLOSED}let c=new v8(r,o,s?.message?.ports?.clustering,s?.message?.ports?.operations_api,i,s?.message?.uptime,e.subscriptions,s?.message?.system_info);try{let u={name:r,system_info:s?.message?.system_info};e.system_info?.hdb_version!==Zd.PRE_4_0_0_VERSION&&await vT.upsertNodeRecord(u)}catch(u){PT.error("Cluster status encountered an error updating system info for node:",r,u)}t.push(c)}a(hU,"buildNodeStatus");function v8(e,t,r,n,s,i,o,c){this.node_name=e,this.status=t,this.ports={clustering:r,operations_api:n},this.latency_ms=s,this.uptime=i,this.subscriptions=o,this.system_info=c}a(v8,"NodeStatusObject")});var xT=g((she,pU)=>{"use strict";var{handleHDBError:B8,hdb_errors:H8}=ne(),{HTTP_STATUS_CODES:x8}=H8,G8=it(),q8=ln(),HT=Q(),ef=require("joi"),F8=Xe(),k8=2e3,V8=ef.object({timeout:ef.number().min(1),connected_nodes:ef.boolean(),routes:ef.boolean()});pU.exports=$8;async function $8(e){q8.checkClusteringEnabled();let t=F8.validateBySchema(e,V8);if(t)throw B8(t,t.message,x8.BAD_REQUEST,void 0,void 0,!0);let{timeout:r,connected_nodes:n,routes:s}=e,i=n===void 0||HT.autoCastBoolean(n),o=s===void 0||HT.autoCastBoolean(s),c={nodes:[]},u=await G8.getServerList(r??k8),_={};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:HT.autoCast(p.split(":")[1])})):[]),c.nodes.push(h)}}return c}a($8,"clusterNetwork")});var RU=g((ohe,gU)=>{"use strict";var GT=require("joi"),SU=Xe(),{route_constraints:TU}=tp();gU.exports={setRoutesValidator:Y8,deleteRoutesValidator:K8};function Y8(e){let t=GT.object({server:GT.valid("hub","leaf").required(),routes:TU.required()});return SU.validateBySchema(e,t)}a(Y8,"setRoutesValidator");function K8(e){let t=GT.object({routes:TU.required()});return SU.validateBySchema(e,t)}a(K8,"deleteRoutesValidator")});var FT=g((che,yU)=>{"use strict";var ho=lr(),qT=Q(),tf=L(),AU=RU(),{handleHDBError:OU,hdb_errors:W8}=ne(),{HTTP_STATUS_CODES:bU}=W8,Q8="cluster routes successfully set",z8="cluster routes successfully deleted";yU.exports={setRoutes:J8,getRoutes:X8,deleteRoutes:j8};function J8(e){let t=AU.setRoutesValidator(e);if(t)throw OU(t,t.message,bU.BAD_REQUEST,void 0,void 0,!0);let r=ho.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=qT.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"?ho.updateConfigValue(tf.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,n):ho.updateConfigValue(tf.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,n),{message:Q8,set:o,skipped:i}}a(J8,"setRoutes");function X8(){let e=ho.getClusteringRoutes();return{hub:e.hub_routes,leaf:e.leaf_routes}}a(X8,"getRoutes");function j8(e){let t=AU.deleteRoutesValidator(e);if(t)throw OU(t,t.message,bU.BAD_REQUEST,void 0,void 0,!0);let r=ho.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=qT.isEmptyOrZeroLength(n)?null:n,ho.updateConfigValue(tf.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_ROUTES,n)),u&&(s=qT.isEmptyOrZeroLength(s)?null:s,ho.updateConfigValue(tf.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_ROUTES,s)),{message:z8,deleted:i,skipped:o}}a(j8,"deleteRoutes")});var IU=g((lhe,NU)=>{"use strict";var Uu=require("alasql"),mo=require("recursive-iterator"),xn=$(),Z8=Q(),Pu=L(),kT=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,t6(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=>Pu.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=>!Pu.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][Pu.PERMS_CRUD_ENUM.READ]){let c;t[i].tables[o].attribute_permissions.length>0?c=e6(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(_=>!Pu.SEARCH_WILDCARDS.includes(_));c.forEach(({attribute_name:_})=>{let l=new Uu.yy.Column({columnid:_});s.tableid&&(l.tableid=s.tableid),this.ast.columns.push(l),u.includes(_)||u.push(_)}),this.affected_attributes.get(i).set(o,u)}}),this.ast}};function e6(e){return e.filter(t=>t[Pu.PERMS_CRUD_ENUM.READ])}a(e6,"filterReadRestrictedAttrs");function t6(e,t,r,n,s){r6(e,t,r,n,s)}a(t6,"interpretAST");function vu(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(vu,"addSchemaTableToMap");function r6(e,t,r,n,s){if(!e){xn.info("getRecordAttributesAST: invalid SQL syntax tree");return}e instanceof Uu.yy.Insert?o6(e,t,r):e instanceof Uu.yy.Select?n6(e,t,r,n,s):e instanceof Uu.yy.Update?s6(e,t,r):e instanceof Uu.yy.Delete?i6(e,t,r):xn.error("AST in getRecordAttributesAST() is not a valid SQL type.")}a(r6,"getRecordAttributesAST");function n6(e,t,r,n,s){if(!e){xn.info("getSelectAttributes: invalid SQL syntax tree");return}if(!e.from||e.from[0]===void 0)return;let i=e.from[0].databaseid;if(Z8.isEmptyOrZeroLength(i)){xn.error("No schema specified");return}e.from.forEach(c=>{vu(c,t,r,n,s)}),e.joins&&e.joins.forEach(c=>{c.as&&(c.table.as=c.as),vu(c.table,t,r,n,s)});let o=new mo(e.columns);for(let{node:c}of o)if(c&&c.columnid){let u=c.tableid,_=n.has(u)?n.get(u):i;if(u||(u=e.from[0].tableid),!t.get(_).has(u))if(r.has(u))u=r.get(u);else{xn.info(`table specified as ${u} not found.`);return}t.get(_).get(u).indexOf(c.columnid)<0&&t.get(_).get(u).push(c.columnid)}if(e.where){let c=new mo(e.where),u=e.from[0].tableid;for(let{node:_}of c)if(_&&_.columnid){let l=_.tableid?_.tableid:u;if(!t.get(i).has(l))if(r.has(l))l=r.get(l);else{xn.info(`table specified as ${l} not found.`);continue}t.get(i).get(l).indexOf(_.columnid)<0&&t.get(i).get(l).push(_.columnid)}}if(e.joins&&e.joins.forEach(c=>{let u=new mo(c.on);for(let{node:_}of u)if(_&&_.columnid){let l=_.tableid,d=s.get(l);if(!t.get(d).has(l))if(r.has(l))l=r.get(l);else{xn.info(`table specified as ${l} not found.`);continue}t.get(d).get(l).indexOf(_.columnid)<0&&t.get(d).get(l).push(_.columnid)}}),e.order){let c=new mo(e.order);for(let{node:u}of c)if(u&&u.columnid){let _=u.tableid,l=n.has(_)?n.get(_):i;if(_||(_=e.from[0].tableid),!t.get(l).has(_))if(r.has(_))_=r.get(_);else{xn.info(`table specified as ${_} not found.`);return}t.get(l).get(_).indexOf(u.columnid)<0&&t.get(l).get(_).push(u.columnid)}}}a(n6,"getSelectAttributes");function s6(e,t,r){if(!e){xn.info("getUpdateAttributes: invalid SQL syntax tree");return}let n=new mo(e.columns),s=e.table.databaseid;vu(e.table,t,r);for(let{node:i}of n)i&&i.columnid&&VT(e.table.tableid,s,i.columnid,t,r)}a(s6,"getUpdateAttributes");function i6(e,t,r){if(!e){xn.info("getDeleteAttributes: invalid SQL syntax tree");return}let n=new mo(e.where),s=e.table.databaseid;vu(e.table,t,r);for(let{node:i}of n)i&&i.columnid&&VT(e.table.tableid,s,i.columnid,t,r)}a(i6,"getDeleteAttributes");function o6(e,t,r){if(!e){xn.info("getInsertAttributes: invalid SQL syntax tree");return}let n=new mo(e.columns),s=e.into.databaseid;vu(e.into,t,r);for(let{node:i}of n)i&&i.columnid&&VT(e.into.tableid,s,i.columnid,t,r)}a(o6,"getInsertAttributes");function VT(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(VT,"pushAttribute");NU.exports=kT});var KT=g((dhe,LU)=>{var rf=Xi(),wU=require("chalk"),Vr=$(),CU=require("prompt"),{promisify:a6}=require("util"),$T=L(),c6=require("fs-extra"),u6=require("path"),l6=Q(),_6=Vd(),DU=ee();DU.initSync();var d6=require("moment"),f6=a6(CU.get),E6=u6.join(DU.getHdbBasePath(),$T.LICENSE_KEY_DIR_NAME,$T.LICENSE_FILE_NAME,$T.LICENSE_FILE_NAME);LU.exports={getFingerprint:m6,setLicense:h6,parseLicense:YT,register:p6,getRegistrationInfo:T6};async function h6(e){if(e&&e.key&&e.company){try{Vr.info(`parsing license key: ${e.key} and `);let t=e.company.toString();await YT(e.key.trim(),t.trim())}catch(t){let r="There was an error parsing the license key.";throw Vr.error(r),Vr.error(t),new Error(r)}return"Wrote license key file. Registration successful."}throw new Error("Invalid key or company specified for license file.")}a(h6,"setLicense");async function m6(){let e={};try{e=await rf.generateFingerPrint()}catch(t){let r="Error generating fingerprint.";throw Vr.error(r),Vr.error(t),new Error(r)}return e}a(m6,"getFingerprint");async function YT(e,t){if(!e||!t)throw new Error("Invalid entries for License Key and Customer Company");Vr.info("Validating license input...");let r=rf.validateLicense(e,t);if(Vr.info("checking for valid license..."),!r.valid_license)throw new Error("Invalid license found.");if(Vr.info("checking valid license date..."),!r.valid_date)throw new Error("This License has expired.");if(Vr.info(`checking for valid machine license ${r.valid_machine}`),!r.valid_machine)throw new Error("This license is in use on another machine.");try{Vr.info("writing license to disk"),await c6.writeFile(E6,JSON.stringify({license_key:e,company:t}))}catch(n){throw Vr.error("Failed to write License"),n}return"Registration successful."}a(YT,"parseLicense");async function p6(){let e=await S6();return YT(e.HDB_LICENSE,e.CUSTOMER_COMPANY)}a(p6,"register");async function S6(){let e=await rf.generateFingerPrint(),t={properties:{CUSTOMER_COMPANY:{description:wU.magenta("[COMPANY] Please enter your company name"),required:!0},HDB_LICENSE:{description:wU.magenta(`[HDB_LICENSE] Your fingerprint is ${e} Please enter your license key`),required:!0}}};try{CU.start()}catch(n){Vr.error(n)}let r;try{r=await f6(t)}catch(n){throw console.error("There was a problem prompting for registration input. Exiting."),n}return r}a(S6,"promptForRegistration");async function T6(){let e={registered:!1,version:null,ram_allocation:null,license_expiration_date:null},t;try{t=await rf.getLicense()}catch(r){throw Vr.error(`There was an error when searching licenses due to: ${r.message}`),r}if(l6.isEmptyOrZeroLength(t))throw new Error("There were no licenses found.");if(e.registered=t.enterprise,e.version=_6.version(),e.ram_allocation=t.ram_allocation,isNaN(t.exp_date))e.license_expiration_date=t.enterprise?t.exp_date:null;else{let r=d6.utc(t.exp_date).format("YYYY-MM-DD");e.license_expiration_date=t.enterprise?r:null}return e}a(T6,"getRegistrationInfo")});var UU=g((Ehe,MU)=>{"use strict";var g6=ke(),WT=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+g6.SERVER_SUFFIX.HUB,this.pid_file=n,this.max_payload=67108864,this.reconnect_error_reports=100,this.jetstream={enabled:!1},this.tls={cert_file:s,key_file:i,ca_file:o,insecure:c,verify:u},this.leafnodes={port:_,tls:{cert_file:s,key_file:i,ca_file:o,insecure:c}},this.cluster={name:l,port:d,routes: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"}};MU.exports=WT});var BU=g((mhe,vU)=>{"use strict";var PU=ke(),QT=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+PU.SERVER_SUFFIX.LEAF,this.pid_file=n,this.max_payload=67108864,this.jetstream={enabled:!0,store_dir:s,domain:r+PU.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"}};vU.exports=QT});var xU=g((She,HU)=>{"use strict";var zT=class{static{a(this,"HdbUserObject")}constructor(t,r){this.user=t,this.password=r}};HU.exports=zT});var qU=g((ghe,GU)=>{"use strict";var R6=ke(),JT=class{static{a(this,"SysUserObject")}constructor(t,r){this.user=t+R6.SERVER_SUFFIX.ADMIN,this.password=r}};GU.exports=JT});var ZT=g((Ahe,VU)=>{"use strict";var Sa=require("path"),of=require("fs-extra"),A6=UU(),O6=BU(),b6=xU(),y6=qU(),XT=an(),ga=Q(),gr=lr(),sf=L(),Bu=ke(),{CONFIG_PARAMS:ft}=sf,Ra=$(),Hu=ee(),FU=Rs(),jT=it(),Ta="clustering",N6=1e4,kU=50;VU.exports={generateNatsConfig:w6,removeNatsConfig:C6,getHubConfigPath:I6};function I6(){let e=Hu.get(ft.ROOTPATH);return Sa.join(e,Ta,Bu.NATS_CONFIG_FILES.HUB_SERVER)}a(I6,"getHubConfigPath");async function w6(e=!1,t=void 0){Hu.initSync();let r=Hu.get(ft.ROOTPATH),n=Sa.join(r,Ta,Bu.PID_FILES.HUB),s=Sa.join(r,Ta,Bu.PID_FILES.LEAF),i=gr.getConfigFromFile(ft.CLUSTERING_LEAFSERVER_STREAMS_PATH),o=Sa.join(r,Ta,Bu.NATS_CONFIG_FILES.HUB_SERVER),c=Sa.join(r,Ta,Bu.NATS_CONFIG_FILES.LEAF_SERVER),u=gr.getConfigFromFile(ft.CLUSTERING_TLS_CERTIFICATE),_=gr.getConfigFromFile(ft.CLUSTERING_TLS_PRIVATEKEY),l=gr.getConfigFromFile(ft.CLUSTERING_TLS_CERT_AUTH),d=gr.getConfigFromFile(ft.CLUSTERING_TLS_INSECURE),f=gr.getConfigFromFile(ft.CLUSTERING_TLS_VERIFY),E=gr.getConfigFromFile(ft.CLUSTERING_NODENAME),h=gr.getConfigFromFile(ft.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT);await jT.checkNATSServerInstalled()||af("nats-server dependency is either missing or the wrong version. Run 'npm install' to fix");let p=await XT.listUsers(),S=gr.getConfigFromFile(ft.CLUSTERING_USER),T=await XT.getClusterUser();(ga.isEmpty(T)||T.active!==!0)&&af(`Invalid cluster user '${S}'. A valid user with the role 'cluster_user' must be defined under clustering.user in harperdb-config.yaml`),e||(await nf(ft.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),await nf(ft.CLUSTERING_HUBSERVER_LEAFNODES_NETWORK_PORT),await nf(ft.CLUSTERING_HUBSERVER_NETWORK_PORT),await nf(ft.CLUSTERING_LEAFSERVER_NETWORK_PORT));let A=[],R=[];for(let[z,J]of p.entries())J.role.role===sf.ROLE_TYPES_ENUM.CLUSTER_USER&&J.active&&(A.push(new y6(J.username,FU.decrypt(J.hash))),R.push(new b6(J.username,FU.decrypt(J.hash))));let M=[],{hub_routes:x}=gr.getClusteringRoutes();if(!ga.isEmptyOrZeroLength(x))for(let z of x)M.push(`tls://${T.sys_name_encoded}:${T.uri_encoded_d_hash}@${z.host}:${z.port}`);let P=new A6(gr.getConfigFromFile(ft.CLUSTERING_HUBSERVER_NETWORK_PORT),E,n,u,_,l,d,f,h,gr.getConfigFromFile(ft.CLUSTERING_HUBSERVER_CLUSTER_NAME),gr.getConfigFromFile(ft.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),M,A,R);l==null&&(delete P.tls.ca_file,delete P.leafnodes.tls.ca_file),t=ga.isEmpty(t)?void 0:t.toLowerCase(),(t===void 0||t===sf.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase())&&(await of.writeJson(o,P),Ra.trace(`Hub server config written to ${o}`));let k=`tls://${T.sys_name_encoded}:${T.uri_encoded_d_hash}@0.0.0.0:${h}`,B=`tls://${T.uri_encoded_name}:${T.uri_encoded_d_hash}@0.0.0.0:${h}`,X=new O6(gr.getConfigFromFile(ft.CLUSTERING_LEAFSERVER_NETWORK_PORT),E,s,i,[k],[B],A,R,u,_,l,d);l==null&&delete X.tls.ca_file,(t===void 0||t===sf.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())&&(await of.writeJson(c,X),Ra.trace(`Leaf server config written to ${c}`))}a(w6,"generateNatsConfig");async function nf(e){let t=Hu.get(e);return ga.isEmpty(t)&&af(`port undefined for '${e}'`),await ga.isPortTaken(t)&&af(`'${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(nf,"isPortAvailable");function af(e){let t=`Error generating clustering config: ${e}`;Ra.error(t),console.error(t),process.exit(1)}a(af,"generateNatsConfigError");async function C6(e){let{port:t,config_file:r}=jT.getServerConfig(e),{username:n,decrypt_hash:s}=await XT.getClusterUser(),i=0,o=2e3;for(;i<kU;){try{let l=await jT.createConnection(t,n,s,!1);if(l.protocol.connected===!0){l.close();break}}catch(l){Ra.trace(`removeNatsConfig waiting for ${e}. Caught and swallowed error ${l}`)}if(i++,i>=kU)throw new Error(`Operations API timed out attempting to connect to ${e}. This is commonly caused by incorrect clustering config. Check hdb.log for further details.`);let _=o*(i*2);_>3e4&&Ra.notify("Operations API waiting for Nats server connection. This could be caused by large Nats streams or incorrect clustering config."),await ga.async_set_timeout(_)}let c="0".repeat(N6),u=Sa.join(Hu.get(ft.ROOTPATH),Ta,r);await of.writeFile(u,c),await of.remove(u),Ra.notify(e,"started.")}a(C6,"removeNatsConfig")});var zU=g((bhe,QU)=>{"use strict";var $r=ee(),D6=Xi(),he=L(),xu=ke(),Cs=require("path"),{PACKAGE_ROOT:uf}=L(),$U=ee(),cf=Q(),Aa="/dev/null",L6=Cs.join(uf,"launchServiceScripts"),YU=Cs.join(uf,"utility/scripts"),M6=Cs.join(YU,he.HDB_RESTART_SCRIPT),KU=Cs.resolve(uf,"dependencies",`${process.platform}-${process.arch}`,xu.NATS_BINARY_NAME);function WU(){let t=D6.licenseSearch().ram_allocation||he.RAM_ALLOCATION_ENUM.DEFAULT,r=he.MEM_SETTING_KEY+t,n={[he.PROCESS_NAME_ENV_PROP]:he.PROCESS_DESCRIPTORS.HDB,IS_SCRIPTED_SERVICE:!0};return cf.noBootFile()&&(n[he.CONFIG_PARAMS.ROOTPATH.toUpperCase()]=cf.getEnvCliRootPath()),{name:he.PROCESS_DESCRIPTORS.HDB,script:he.LAUNCH_SERVICE_SCRIPTS.MAIN,exec_mode:"fork",env:n,node_args:r,cwd:uf}}a(WU,"generateMainServerConfig");var U6=9930;function P6(){$r.initSync(!0);let e=$r.get(he.CONFIG_PARAMS.ROOTPATH),t=Cs.join(e,"clustering",xu.NATS_CONFIG_FILES.HUB_SERVER),r=Cs.join($r.get(he.HDB_SETTINGS_NAMES.LOG_PATH_KEY),he.LOG_NAMES.HDB),n=$U.get(he.CONFIG_PARAMS.CLUSTERING_HUBSERVER_NETWORK_PORT),s=xu.LOG_LEVEL_FLAGS[$r.get(he.CONFIG_PARAMS.CLUSTERING_LOGLEVEL)]??void 0,i={name:he.PROCESS_DESCRIPTORS.CLUSTERING_HUB+(n!==U6?"-"+n:""),script:KU,args:s?`${s} -c ${t}`:`-c ${t}`,exec_mode:"fork",env:{[he.PROCESS_NAME_ENV_PROP]:he.PROCESS_DESCRIPTORS.CLUSTERING_HUB},merge_logs:!0,out_file:r,error_file:r,instances:1};return $r.get(he.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(i.out_file=Aa,i.error_file=Aa),i}a(P6,"generateNatsHubServerConfig");var v6=9940;function B6(){$r.initSync(!0);let e=$r.get(he.CONFIG_PARAMS.ROOTPATH),t=Cs.join(e,"clustering",xu.NATS_CONFIG_FILES.LEAF_SERVER),r=Cs.join($r.get(he.HDB_SETTINGS_NAMES.LOG_PATH_KEY),he.LOG_NAMES.HDB),n=$U.get(he.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_NETWORK_PORT),s=xu.LOG_LEVEL_FLAGS[$r.get(he.CONFIG_PARAMS.CLUSTERING_LOGLEVEL)]??void 0,i={name:he.PROCESS_DESCRIPTORS.CLUSTERING_LEAF+(n!==v6?"-"+n:""),script:KU,args:s?`${s} -c ${t}`:`-c ${t}`,exec_mode:"fork",env:{[he.PROCESS_NAME_ENV_PROP]:he.PROCESS_DESCRIPTORS.CLUSTERING_LEAF},merge_logs:!0,out_file:r,error_file:r,instances:1};return $r.get(he.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(i.out_file=Aa,i.error_file=Aa),i}a(B6,"generateNatsLeafServerConfig");function H6(){$r.initSync();let e=Cs.join($r.get(he.CONFIG_PARAMS.LOGGING_ROOT),he.LOG_NAMES.HDB),t={name:he.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0,script:he.LAUNCH_SERVICE_SCRIPTS.NODES_UPGRADE_4_0_0,exec_mode:"fork",env:{[he.PROCESS_NAME_ENV_PROP]:he.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0},merge_logs:!0,out_file:e,error_file:e,instances:1,cwd:L6,autorestart:!1};return $r.get(he.HDB_SETTINGS_NAMES.LOG_TO_FILE)||(t.out_file=Aa,t.error_file=Aa),t}a(H6,"generateClusteringUpgradeV4ServiceConfig");function x6(){let e={[he.PROCESS_NAME_ENV_PROP]:he.PROCESS_DESCRIPTORS.RESTART_HDB};return cf.noBootFile()&&(e[he.CONFIG_PARAMS.ROOTPATH.toUpperCase()]=cf.getEnvCliRootPath()),{...{name:he.PROCESS_DESCRIPTORS.RESTART_HDB,exec_mode:"fork",env:e,instances:1,autorestart:!1,cwd:YU},script:M6}}a(x6,"generateRestart");function G6(){return{apps:[WU()]}}a(G6,"generateAllServiceConfigs");QU.exports={generateAllServiceConfigs:G6,generateMainServerConfig:WU,generateRestart:x6,generateNatsHubServerConfig:P6,generateNatsLeafServerConfig:B6,generateClusteringUpgradeV4ServiceConfig:H6}});var uP=g((Ihe,cP)=>{"use strict";var ve=L(),q6=Q(),Ls=ZT(),lf=it(),Ds=ke(),Si=zU(),_f=ee(),Ti=$(),F6=ln(),{startWorker:JU,onMessageFromWorkers:k6}=Ke(),V6=pa(),Nhe=require("util"),$6=require("child_process"),Y6=require("fs"),{execFile:K6}=$6,Ne;cP.exports={enterPM2Mode:W6,start:gi,stop:eg,reload:jU,restart:ZU,list:tg,describe:tP,connect:Ms,kill:j6,startAllServices:Z6,startService:rg,getUniqueServicesList:rP,restartAllServices:e9,isServiceRegistered:nP,reloadStopStart:sP,restartHdb:eP,deleteProcess:J6,startClusteringProcesses:oP,startClusteringThreads:aP,isHdbRestartRunning:X6,isClusteringRunning:r9,stopClustering:t9,reloadClustering:n9};var Gu=!1;k6(e=>{e.type==="restart"&&_f.initSync(!0)});function W6(){Gu=!0}a(W6,"enterPM2Mode");function Ms(){return Ne||(Ne=require("pm2")),new Promise((e,t)=>{Ne.connect((r,n)=>{Ti.setupConsoleLogging(),r&&t(r),e(n)})})}a(Ms,"connect");var Rr,Q6=10,XU;function gi(e,t=!1){if(Gu)return z6(e);let r=K6(e.script,e.args.split(" "),e);r.name=e.name,r.on("exit",async i=>{let o=Rr.indexOf(r);o>-1&&Rr.splice(o,1),!XU&&i!==0&&(e.restarts=(e.restarts||0)+1,e.restarts<Q6&&(Y6.existsSync(Ls.getHubConfigPath())?gi(e):(await Ls.generateNatsConfig(!0),gi(e),await new Promise(c=>setTimeout(c,3e3)),await Ls.removeNatsConfig(ve.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await Ls.removeNatsConfig(ve.PROCESS_DESCRIPTORS.CLUSTERING_LEAF))))});let n={serviceName:e.name.replace(/ /g,"-")};function s(i){let o=_f.get(ve.CONFIG_PARAMS.CLUSTERING_LOGLEVEL),c=/\[\d+][^\[]+\[(\w+)]/g,u,_=0,l;for(;u=c.exec(i);){if(u.index&&Ds.LOG_LEVEL_HIERARCHY[o]>=Ds.LOG_LEVEL_HIERARCHY[l||"info"]){let E=l===Ds.LOG_LEVELS.ERR||l===Ds.LOG_LEVELS.WRN?Ti.OUTPUTS.STDERR:Ti.OUTPUTS.STDOUT;Ti.logCustomLevel(l||"info",E,n,i.slice(_,u.index).trim())}let[d,f]=u;_=u.index+d.length,l=Ds.LOG_LEVELS[f]}if(Ds.LOG_LEVEL_HIERARCHY[o]>=Ds.LOG_LEVEL_HIERARCHY[l||"info"]){let d=l===Ds.LOG_LEVELS.ERR||l===Ds.LOG_LEVELS.WRN?Ti.OUTPUTS.STDERR:Ti.OUTPUTS.STDOUT;Ti.logCustomLevel(l||"info",d,n,i.slice(_).trim())}}if(a(s,"extractMessages"),r.stdout.on("data",s),r.stderr.on("data",s),r.unref(),Rr=[],!Rr&&!t){let i=a(()=>{XU=!0,Rr&&(Rr.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)}Rr.push(r)}a(gi,"start");function z6(e){return new Promise(async(t,r)=>{try{await Ms()}catch(n){r(n)}Ne.start(e,(n,s)=>{n&&(Ne.disconnect(),r(n)),Ne.disconnect(),t(s)})})}a(z6,"startWithPM2");function eg(e){if(!Gu){for(let t of Rr||[])t.name===e&&(Rr.splice(Rr.indexOf(t),1),t.kill());return}return new Promise(async(t,r)=>{try{await Ms()}catch(n){r(n)}Ne.stop(e,async(n,s)=>{n&&(Ne.disconnect(),r(n)),Ne.delete(e,(i,o)=>{i&&(Ne.disconnect(),r(n)),Ne.disconnect(),t(o)})})})}a(eg,"stop");function jU(e){return new Promise(async(t,r)=>{try{await Ms()}catch(n){r(n)}Ne.reload(e,(n,s)=>{n&&(Ne.disconnect(),r(n)),Ne.disconnect(),t(s)})})}a(jU,"reload");function ZU(e){if(!Gu)for(let t of Rr||[])t.name===e&&t.kill();return new Promise(async(t,r)=>{try{await Ms()}catch(n){r(n)}Ne.restart(e,(n,s)=>{Ne.disconnect(),t(s)})})}a(ZU,"restart");function J6(e){return new Promise(async(t,r)=>{try{await Ms()}catch(n){r(n)}Ne.delete(e,(n,s)=>{n&&(Ne.disconnect(),r(n)),Ne.disconnect(),t(s)})})}a(J6,"deleteProcess");async function eP(){await gi(Si.generateRestart())}a(eP,"restartHdb");async function X6(){let e=await tg();for(let t in e)if(e[t].name===ve.PROCESS_DESCRIPTORS.RESTART_HDB)return!0;return!1}a(X6,"isHdbRestartRunning");function tg(){return new Promise(async(e,t)=>{try{await Ms()}catch(r){t(r)}Ne.list((r,n)=>{r&&(Ne.disconnect(),t(r)),Ne.disconnect(),e(n)})})}a(tg,"list");function tP(e){return new Promise(async(t,r)=>{try{await Ms()}catch(n){r(n)}Ne.describe(e,(n,s)=>{n&&(Ne.disconnect(),r(n)),Ne.disconnect(),t(s)})})}a(tP,"describe");function j6(){if(!Gu){for(let e of Rr||[])e.kill();Rr=[];return}return new Promise(async(e,t)=>{try{await Ms()}catch(r){t(r)}Ne.killDaemon((r,n)=>{r&&(Ne.disconnect(),t(r)),Ne.disconnect(),e(n)})})}a(j6,"kill");async function Z6(){try{await oP(),await aP(),await gi(Si.generateAllServiceConfigs())}catch(e){throw Ne?.disconnect(),e}}a(Z6,"startAllServices");async function rg(e,t=!1){try{let r;switch(e=e.toLowerCase(),e){case ve.PROCESS_DESCRIPTORS.HDB.toLowerCase():r=Si.generateMainServerConfig();break;case ve.PROCESS_DESCRIPTORS.CLUSTERING_INGEST_SERVICE.toLowerCase():r=Si.generateNatsIngestServiceConfig();break;case ve.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE.toLowerCase():r=Si.generateNatsReplyServiceConfig();break;case ve.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase():r=Si.generateNatsHubServerConfig(),await gi(r,t),await Ls.removeNatsConfig(e);return;case ve.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase():r=Si.generateNatsLeafServerConfig(),await gi(r,t),await Ls.removeNatsConfig(e);return;case ve.PROCESS_DESCRIPTORS.CLUSTERING_UPGRADE_4_0_0.toLowerCase():r=Si.generateClusteringUpgradeV4ServiceConfig();break;default:throw new Error(`Start service called with unknown service config: ${e}`)}await gi(r)}catch(r){throw Ne?.disconnect(),r}}a(rg,"startService");async function rP(){try{let e=await tg(),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 Ne?.disconnect(),e}}a(rP,"getUniqueServicesList");async function e9(e=[]){try{let t=!1,r=await rP();for(let n=0,s=Object.values(r).length;n<s;n++){let o=Object.values(r)[n].name;e.includes(o)||(o===ve.PROCESS_DESCRIPTORS.HDB?t=!0:await ZU(o))}t&&await sP(ve.PROCESS_DESCRIPTORS.HDB)}catch(t){throw Ne?.disconnect(),t}}a(e9,"restartAllServices");async function nP(e){if(Rr?.find(r=>r.name===e))return!0;let t=await V6.getHDBProcessInfo();return t.core.length&&t.core[0]?.parent==="PM2"}a(nP,"isServiceRegistered");async function sP(e){let t=_f.get(ve.CONFIG_PARAMS.THREADS_COUNT)??_f.get(ve.CONFIG_PARAMS.THREADS),r=await tP(e),n=q6.isEmptyOrZeroLength(r)?0:r.length;t!==n?(await eg(e),await rg(e)):e===ve.PROCESS_DESCRIPTORS.HDB?await eP():await jU(e)}a(sP,"reloadStopStart");var iP;async function oP(e=!1){for(let t in ve.CLUSTERING_PROCESSES){let r=ve.CLUSTERING_PROCESSES[t];await rg(r,e)}}a(oP,"startClusteringProcesses");async function aP(){iP=JU(ve.LAUNCH_SERVICE_SCRIPTS.NATS_REPLY_SERVICE,{name:ve.PROCESS_DESCRIPTORS.CLUSTERING_REPLY_SERVICE});try{await lf.deleteLocalStream("__HARPERDB_WORK_QUEUE__")}catch{}await lf.updateLocalStreams();let e=await F6.getAllNodeRecords();for(let t=0,r=e.length;t<r;t++)if(e[t].system_info?.hdb_version===ve.PRE_4_0_0_VERSION){Ti.info("Starting clustering upgrade 4.0.0 process"),JU(ve.LAUNCH_SERVICE_SCRIPTS.NODES_UPGRADE_4_0_0,{name:"Upgrade-4-0-0"});break}}a(aP,"startClusteringThreads");async function t9(){for(let e in ve.CLUSTERING_PROCESSES)if(e!==ve.CLUSTERING_PROCESSES.CLUSTERING_INGEST_PROC_DESCRIPTOR)if(e===ve.CLUSTERING_PROCESSES.CLUSTERING_REPLY_SERVICE_DESCRIPTOR)await iP.terminate();else{let t=ve.CLUSTERING_PROCESSES[e];await eg(t)}}a(t9,"stopClustering");async function r9(){for(let e in ve.CLUSTERING_PROCESSES){let t=ve.CLUSTERING_PROCESSES[e];if(await nP(t)===!1)return!1}return!0}a(r9,"isClusteringRunning");async function n9(){await Ls.generateNatsConfig(!0),await lf.reloadNATSHub(),await lf.reloadNATSLeaf(),await Ls.removeNatsConfig(ve.PROCESS_DESCRIPTORS.CLUSTERING_HUB.toLowerCase()),await Ls.removeNatsConfig(ve.PROCESS_DESCRIPTORS.CLUSTERING_LEAF.toLowerCase())}a(n9,"reloadClustering")});var mP={};qe(mP,{compactOnStart:()=>s9,copyDb:()=>hP});async function s9(){Fu.notify("Running compact on start"),console.log("Running compact on start");let e=(0,ng.get)(Ri.CONFIG_PARAMS.ROOTPATH),t=new Map,r=dr();try{for(let n in r){if(n==="system")continue;let s;for(let u in r[n]){s=r[n][u].primaryStore.path;break}let i=(0,df.join)(e,"backup",n+".mdb"),o=(0,df.join)(e,Ri.DATABASES_DIR_NAME,n+"-copy.mdb"),c=await lP(n);console.log("Database",n,"before compact has a total record count of",c),t.set(n,{db_path:s,copy_dest:o,backup_dest:i,record_count:c}),await hP(n,o),console.log("Backing up",n,"to",i),await(0,po.move)(s,i,{overwrite:!0})}qu();for(let[n,{db_path:s,copy_dest:i}]of t)console.log("Moving copy compacted",n,"to",s),await(0,po.move)(i,s,{overwrite:!0}),await(0,po.remove)((0,df.join)(e,Ri.DATABASES_DIR_NAME,`${n}-copy.mdb-lock`));qu()}catch(n){Fu.error("Error compacting database, rolling back operation",n),console.error("Error compacting database, rolling back operation",n),(0,sg.updateConfigValue)(Ri.CONFIG_PARAMS.STORAGE_COMPACTONSTART,!1);for(let[s,{db_path:i,backup_dest:o}]of t){console.error("Moving backup database",o,"back to",i);try{await(0,po.move)(o,i,{overwrite:!0})}catch(c){console.error(c)}}throw qu(),n}for(let[n,{backup_dest:s,record_count:i}]of t){let o=!0,c=await lP(n);if(console.log("Database",n,"after compact has a total record count of",c),i!==c){o=!1;let u=`There is a discrepancy between pre and post compact record count for database ${n}.
|
|
11
|
+
Total record count before compaction: ${i}, total after: ${c}.
|
|
12
|
+
Database backup has not been removed and can be found here: ${s}`;Fu.error(u),console.error(u)}(0,ng.get)(Ri.CONFIG_PARAMS.STORAGE_COMPACTONSTARTKEEPBACKUP)===!0||o===!1||(console.log("Removing backup",s),await(0,po.remove)(s))}(0,sg.updateConfigValue)(Ri.CONFIG_PARAMS.STORAGE_COMPACTONSTART,!1)}async function lP(e){let t=await(0,EP.describeSchema)({database:e}),r=0;for(let n in t)r+=t[n].record_count;return r}async function hP(e,t){console.log("copyDb start");let r=dr()[e],n;for(let f in r){n=r[f].primaryStore.rootStore;break}let s=n.dbisDb,i=n.auditStore,o=(0,_P.open)(new dP.default(t)),c=o.openDB(ff.INTERNAL_DBIS_NAME),u,_=0;for(let{key:f,value:E}of s.getRange({})){let h=E.is_hash_attribute||E.isPrimaryKey,p,S;if(h&&(p=E.compression,S=hf(),S?E.compression=S:delete E.compression,p?.dictionary?.toString()===S?.dictionary?.toString()&&(p=null,S=null)),c.put(f,E),!(h||E.indexed))continue;let T=new fP.default(!h,h);T.encoding="binary",T.compression=p;let A=n.openDB(f,T);A.decoder=null,T.compression=S;let R=o.openDB(f,T);R.encoder=null,console.log("copying",f,"from",e,"to",t),await d(A,R,h)}let l=n.openDB(ff.AUDIT_STORE_NAME,Ef);console.log("copying audit log"),d(i,l,!1);async function d(f,E,h){let p=0,S=0;for(let{key:T,value:A,version:R}of f.getRange({start:null,versions:h}))u=E.put(T,A,R),p++,S+=(T.length||10)+A.length,_++>5e3&&(await u,console.log("copied",p,"entries",S,"bytes"),_=0);console.log("finish copying, copied",p,"entries",S,"bytes")}a(d,"copyDbi"),await u,o.close(),console.log("copied database "+e+" to "+t)}var _P,df,po,ng,dP,fP,ff,Ri,EP,sg,Fu,pP=ge(()=>{Re();_P=require("lmdb"),df=require("path"),po=require("fs-extra"),ng=v(ee()),dP=v(Cc()),fP=v(wc()),ff=v(ut()),Ri=v(L());ei();EP=v(As()),sg=v(lr()),Fu=v($());a(s9,"compactOnStart");a(lP,"getTotalDBRecordCount");a(hP,"copyDb")});var Tf=g((Uhe,bP)=>{"use strict";var i9=require("minimist"),{isMainThread:og,parentPort:gP}=require("worker_threads"),et=L(),{PROCESS_DESCRIPTORS_VALIDATE:ku}=et,is=$(),ag=Q(),pf=ZT(),mf=it(),Mhe=ke(),RP=lr(),os=uP(),SP=pa(),{compactOnStart:o9}=(pP(),ie(mP)),a9=Uh(),{restartWorkers:Sf,onMessageByType:c9}=Ke(),{handleHDBError:u9,hdb_errors:l9}=ne(),{HTTP_STATUS_CODES:_9}=l9,$u=ee();$u.initSync();var Vu=`Restarting HarperDB. This may take up to ${et.RESTART_TIMEOUT_MS/1e3} seconds.`,d9="Restart is not available from the CLI when running in non-pm2 mode. Either call restart from the API or stop and start HarperDB.",TP="Clustering is not enabled so cannot be restarted",f9="Invalid service",Oa,_n;bP.exports={restart:AP,restartService:cg};og&&c9(et.ITC_EVENT_TYPES.RESTART,e=>{e.workerType?cg({service:e.workerType}):AP({operation:"restart"})});async function AP(e){_n=Object.keys(e).length===0,Oa=await os.isServiceRegistered(et.HDB_PROC_DESCRIPTOR);let t=i9(process.argv);if(t.service){await cg(t);return}if(_n&&!Oa){console.error(d9);return}if(_n&&console.log(Vu),Oa){os.enterPM2Mode(),is.notify(Vu);let r=a9(Object.keys(et.CONFIG_PARAM_MAP),!0);return ag.isEmptyOrZeroLength(Object.keys(r))||RP.updateConfigValue(void 0,void 0,r,!0,!0),E9(),Vu}return og?(is.notify(Vu),$u.get(et.CONFIG_PARAMS.STORAGE_COMPACTONSTART)&&await o9(),setTimeout(()=>{Sf()},50)):gP.postMessage({type:et.ITC_EVENT_TYPES.RESTART}),Vu}a(AP,"restart");async function cg(e){let{service:t}=e;if(et.PROCESS_DESCRIPTORS_VALIDATE[t]===void 0)throw u9(new Error,f9,_9.BAD_REQUEST,void 0,void 0,!0);if(Oa=await os.isServiceRegistered(et.HDB_PROC_DESCRIPTOR),!og)return gP.postMessage({type:et.ITC_EVENT_TYPES.RESTART,workerType:t}),t==="custom_functions"&&(t="Custom Functions"),`Restarting ${t}`;let r;switch(t){case ku.clustering:if(!$u.get(et.CONFIG_PARAMS.CLUSTERING_ENABLED)){r=TP;break}_n&&console.log("Restarting clustering"),is.notify("Restarting clustering"),await OP();break;case ku.clustering_config:case ku["clustering config"]:if(!$u.get(et.CONFIG_PARAMS.CLUSTERING_ENABLED)){r=TP;break}_n&&console.log("Restarting clustering_config"),is.notify("Restarting clustering_config"),await os.reloadClustering();break;case"custom_functions":case"custom functions":case ku.harperdb:case ku.http_workers:if(_n&&!Oa){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}_n&&console.log("Restarting http_workers"),is.notify("Restarting http_workers"),_n?await os.restart(et.HDB_PROC_DESCRIPTOR):setTimeout(()=>{Sf("http")},200);break;default:r=`Unrecognized service: ${t}`;break}return r?(is.error(r),_n&&console.error(r),r):(t==="custom_functions"&&(t="Custom Functions"),`Restarting ${t}`)}a(cg,"restartService");async function E9(){await OP(),await os.restart(et.HDB_PROC_DESCRIPTOR),await ag.async_set_timeout(2e3),$u.get(et.CONFIG_PARAMS.CLUSTERING_ENABLED)&&await ig(),_n&&(await mf.closeConnection(),process.exit(0))}a(E9,"restartPM2Mode");async function OP(){if(!RP.getConfigFromFile(et.CONFIG_PARAMS.CLUSTERING_ENABLED))return;if((await SP.getHDBProcessInfo()).clustering.length===0)is.trace("Clustering not running, restart will start clustering services"),await pf.generateNatsConfig(!0),await os.startClusteringProcesses(),await os.startClusteringThreads(),await ig(),_n&&await mf.closeConnection();else{await pf.generateNatsConfig(!0),Oa?(is.trace("Restart clustering restarting PM2 managed Hub and Leaf servers"),await os.restart(et.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await os.restart(et.PROCESS_DESCRIPTORS.CLUSTERING_LEAF)):(await SP.getHDBProcessInfo()).clustering.forEach(s=>{is.trace("Restart clustering killing process pid",s.pid),process.kill(s.pid)}),await ag.async_set_timeout(3e3),await ig(),await mf.updateLocalStreams(),_n&&await mf.closeConnection(),is.trace("Restart clustering restarting ingest and reply service threads");let t=Sf(et.LAUNCH_SERVICE_SCRIPTS.NATS_INGEST_SERVICE),r=Sf(et.LAUNCH_SERVICE_SCRIPTS.NATS_REPLY_SERVICE);await t,await r}}a(OP,"restartClustering");async function ig(){await pf.removeNatsConfig(et.PROCESS_DESCRIPTORS.CLUSTERING_HUB),await pf.removeNatsConfig(et.PROCESS_DESCRIPTORS.CLUSTERING_LEAF)}a(ig,"removeNatsConfig")});var vP=g((Bhe,PP)=>{"use strict";var vhe=require("lodash"),Ar=L(),{handleHDBError:yP,hdb_errors:h9}=ne(),{HDB_ERROR_MSGS:m9,HTTP_STATUS_CODES:p9}=h9,ug=$();PP.exports={getRolePermissions:T9};var So=Object.create(null),S9=a(e=>({key:e,perms:{}}),"perms_template_obj"),CP=a((e=!1)=>({describe:e,tables:{}}),"schema_perms_template"),DP=a((e=!1,t=!1,r=!1,n=!1)=>({[Ar.PERMS_CRUD_ENUM.READ]:e,[Ar.PERMS_CRUD_ENUM.INSERT]:t,[Ar.PERMS_CRUD_ENUM.UPDATE]:r,[Ar.PERMS_CRUD_ENUM.DELETE]:n}),"permissions_template"),lg=a((e=!1,t=!1,r=!1,n=!1,s=!1)=>({attribute_permissions:[],describe:e,...DP(t,r,n,s)}),"table_perms_template"),NP=a((e,t=DP())=>({attribute_name:e,describe:UP(t),[Yu]:t[Yu],[_g]:t[_g],[dg]:t[dg]}),"attr_perms_template"),IP=a((e,t=!1)=>({attribute_name:e,describe:t,[Yu]:t}),"timestamp_attr_perms_template"),{READ:Yu,INSERT:_g,UPDATE:dg}=Ar.PERMS_CRUD_ENUM,LP=Object.values(Ar.PERMS_CRUD_ENUM),MP=[Yu,_g,dg];function T9(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[Ar.SYSTEM_SCHEMA_NAME],t=e.role;let n=JSON.stringify([e.__updatedtime__,r]);if(So[t]&&So[t].key===n)return So[t].perms;let s=g9(e,r);return So[t]?So[t].key=n:So[t]=S9(n),So[t].perms=s,s}catch(r){if(!e[Ar.TIME_STAMP_NAMES_ENUM.UPDATED_TIME]||e[Ar.TIME_STAMP_NAMES_ENUM.UPDATED_TIME]<Ar.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 ug.error(n),ug.debug(r),yP(new Error,m9.OUTDATED_PERMS_TRANSLATION_ERROR,p9.BAD_REQUEST)}else{let n=`There was an error while translating role permissions for role: ${t}.
|
|
13
|
+
${r.stack}`;throw ug.error(n),yP(new Error)}}}a(T9,"getRolePermissions");function g9(e,t){let r=Object.create(null);r.super_user=!1;let n=e.permission;r[Ar.SYSTEM_SCHEMA_NAME]=n[Ar.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]=R9(t[i]);return}r[i]=CP(),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],_=A9(c,u);r[i].describe||LP.forEach(l=>{_[l]&&(r[i].describe=!0)}),r[i].tables[o]=_}else r[i].tables[o]=lg()})):Object.keys(t[i]).forEach(o=>{r[i].tables[o]=lg()})}),r}a(g9,"translateRolePermissions");function R9(e){let t=CP(!0);return Object.keys(e).forEach(r=>{t.tables[r]=lg(!0,!0,!0,!0,!0)}),t}a(R9,"createStructureUserPermissions");function A9(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 Ar.TIME_STAMP_NAMES.includes(d)&&(f=IP(d,l[Yu])),_[d]=f,_},{}),o=t.primaryKey||t.hash_attribute,c=!!i[o],u=NP(o);return t.attributes.forEach(({attribute:_})=>{if(i[_]){let l=i[_];l.describe=UP(l),s.attribute_permissions.push(l),c||O9(l,u)}else if(_!==o){let l;Ar.TIME_STAMP_NAMES.includes(_)?l=IP(_):l=NP(_),s.attribute_permissions.push(l)}}),c||s.attribute_permissions.push(u),s.describe=wP(s),s}else return e.describe=wP(e),e}a(A9,"getTableAttrPerms");function wP(e){return LP.filter(t=>e[t]).length>0}a(wP,"getSchemaTableDescribePerm");function UP(e){return MP.filter(t=>e[t]).length>0}a(UP,"getAttributeDescribePerm");function O9(e,t){MP.forEach(r=>{e[r]&&!t[r]&&(t[r]=!0,t.describe=!0)})}a(O9,"checkForHashPerms")});var BP={};qe(BP,{Resources:()=>gf,keyArrayToString:()=>ba,resetResources:()=>b9,resources:()=>Ai});function b9(){return Ai=new gf}function ba(e){return Array.isArray(e)?e[e.length-1]===null?e.slice(0,-1).join("/")+"/":e.join("/"):e}var gf,Ai,Ku=ge(()=>{no();gf=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 je(r,async()=>{let s=this.getMatch(t);if(s)return t=s.relativeURL,n(s.Resource,s.path,t)})}setRepresentation(t,r,n){}};a(b9,"resetResources");a(ba,"keyArrayToString")});var HP={};qe(HP,{Headers:()=>Oi,appendHeader:()=>fg});function fg(e,t,r,n){if(e.append)e.append(t,r,n);else if(e.set){let s=e.get(t);if(s)if(n)r=(typeof s=="string"?s:s.join(", "))+", "+r;else if(typeof s=="string")r=[s,r];else{s.push(r);return}return e.set(t,r)}else e[t]=(e[t]?e[t]+", ":"")+r}var Oi,Wu=ge(()=>{Oi=class extends Map{static{a(this,"Headers")}set(t,r){return typeof t!="string"&&(t=""+t),typeof r!="string"&&(r=""+r),super.set(t.toLowerCase(),[t,r])}get(t){return typeof t!="string"&&(t=""+t),super.get(t.toLowerCase())?.[1]}has(t){return typeof t!="string"&&(t=""+t),super.has(t.toLowerCase())}setIfNone(t,r){typeof t!="string"&&(t=""+t),typeof r!="string"&&(r=""+r);let n=t.toLowerCase();if(!super.has(n))return super.set(n,[t,r])}append(t,r,n){typeof t!="string"&&(t=""+t),typeof r!="string"&&(r=""+r);let s=t.toLowerCase(),i=super.get(s);if(i){let o=i[1];if(n)r=(typeof o=="string"?o:o.join(", "))+", "+r;else if(typeof o=="string")r=[o,r];else{o.push(r);return}}return super.set(s,[t,r])}[Symbol.iterator](){return super.values()[Symbol.iterator]()}};a(fg,"appendHeader")});var Qu={};qe(Qu,{authentication:()=>YP,bypassAuth:()=>L9,login:()=>U9,logout:()=>P9,start:()=>M9});function L9(){$P=!0}async function YP(e,t){let r=e.headers.asObject,n=r.authorization,s=r.cookie,i=r.origin,o=[];try{if(i){let E=e.isOperationsServer?w9?I9:[]:N9?y9:[];if(E.includes(i)||E.includes("*")){if(e.method==="OPTIONS"){let h=new Oi([["Access-Control-Allow-Methods","POST, GET, PUT, DELETE, PATCH, OPTIONS"],["Access-Control-Allow-Headers","Accept, Content-Type, Authorization"],["Access-Control-Allow-Origin",i]]);return Rf&&h.set("Access-Control-Allow-Credentials","true"),{status:200,headers:h}}o.push("Access-Control-Allow-Origin",i),Rf&&o.push("Access-Control-Allow-Credentials","true")}}let u,_;if(Rf){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 GP.get(u)}e.session=_||(_={})}e.user=null;let l=a((E,h,p)=>{let S=new ya.AuthAuditLog(E,h,vt.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===vt.AUTH_AUDIT_STATUS.SUCCESS?xP.notify(S):xP.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 nt.getUser(E,null,null),l(E,vt.AUTH_AUDIT_STATUS.SUCCESS,"mTLS")):(0,ya.debug)("HTTPS/WSS mTLS authorized connection (mTLS did not authorize a user)","from",e.ip)}let d;if(!e.user)if(n){if(d=To.get(n),!d){let[E,h]=n.split(" "),p,S;try{switch(E){case"Basic":[p,S]=atob(h).split(":"),d=p||S?await nt.getUser(p,S,e):null;break;case"Bearer":try{d=await(0,Af.validateOperationToken)(h)}catch(T){if(T.message==="invalid token")try{return await(0,Af.validateRefreshToken)(h),c({status:-1})}catch{throw T}}break}}catch(T){return D9&&(To.get(h)||(To.set(h,h),l(p,vt.AUTH_AUDIT_STATUS.FAILURE,E))),c({status:401,body:bi({error:T.message},e)})}To.set(n,d),C9&&l(d.username,vt.AUTH_AUDIT_STATUS.SUCCESS,E)}e.user=d}else _?.user?e.user=await nt.getUser(_.user,null,e):($P&&(e.ip?.includes("127.0.0.1")||e.ip=="::1")||e?._nodeRequest?.socket?.server?._pipeName&&e.ip===void 0)&&(e.user=await(0,FP.getSuperUser)());Rf&&(e.session.update=function(E){if(!u){u=(0,kP.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,GP.put(E)},e.login=async function(E,h){e.user=await nt.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")&&Ai.loginPath?(f.status=302,f.headers.set("Location",Ai.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 Oi);for(let d=0;d<_;){let f=o[d++];l.set(f,o[d++])}}return o=null,u}a(c,"applyResponseHeaders")}function M9({server:e,port:t}){e.request(YP,{port:t||"all"}),qP||(qP=!0,setInterval(()=>{To=new Map},dn.get(vt.CONFIG_PARAMS.AUTHENTICATION_CACHETTL)).unref(),VP.user.addListener(()=>{To=new Map}))}async function U9(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 P9(e){if(!e.baseRequest.session)throw new Error("No session for logout");return await e.baseRequest.session.update({user:null}),"Logout successful"}var FP,Af,kP,dn,vt,ya,VP,xP,y9,N9,I9,w9,GP,Rf,$P,C9,D9,To,qP,Of=ge(()=>{FP=v(an());or();Ku();Af=v(bu());Re();kP=require("uuid"),dn=v(ee()),vt=v(L()),ya=v($()),VP=v(kc());Wu();Na();xP=(0,ya.loggerWithTag)("auth-event");dn.initSync();y9=dn.get(vt.CONFIG_PARAMS.HTTP_CORSACCESSLIST),N9=dn.get(vt.CONFIG_PARAMS.HTTP_CORS),I9=dn.get(vt.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_CORSACCESSLIST),w9=dn.get(vt.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_CORS),GP=lt({table:"hdb_session",database:"system",attributes:[{name:"id",isPrimaryKey:!0},{name:"user"}]}),Rf=dn.get(vt.CONFIG_PARAMS.AUTHENTICATION_ENABLESESSIONS)??!0,$P=dn.get(vt.CONFIG_PARAMS.AUTHENTICATION_AUTHORIZELOCAL)??process.env.DEV_MODE,C9=dn.get(vt.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)??!1,D9=dn.get(vt.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGFAILED)??!1,To=new Map;nt.onInvalidatedUser(()=>{To=new Map});a(L9,"bypassAuth");a(YP,"authentication");a(M9,"start");a(U9,"login");a(P9,"logout")});var jP=g((Whe,XP)=>{"use strict";var Ie=require("joi"),KP=require("fs-extra"),WP=require("path"),Ps=Xe(),QP=ee(),zP=L(),JP=$(),{hdb_errors:v9}=ne(),{HDB_ERROR_MSGS:er}=v9,Us=/^[a-zA-Z0-9-_]+$/;XP.exports={getDropCustomFunctionValidator:H9,setCustomFunctionValidator:x9,addComponentValidator:k9,dropCustomFunctionProjectValidator:V9,packageComponentValidator:$9,deployComponentValidator:Y9,setComponentFileValidator:G9,getComponentFileValidator:F9,dropComponentFileValidator:q9};function bf(e,t,r){try{let n=QP.get(zP.CONFIG_PARAMS.COMPONENTSROOT),s=WP.join(n,t);return KP.existsSync(s)?e?t:r.message(er.PROJECT_EXISTS):e?r.message(er.NO_PROJECT):t}catch(n){return JP.error(n),r.message(er.VALIDATION_ERR)}}a(bf,"checkProjectExists");function zu(e,t){return e.includes("..")?t.message("Invalid file path"):e}a(zu,"checkFilePath");function B9(e,t,r,n){try{let s=QP.get(zP.CONFIG_PARAMS.COMPONENTSROOT),i=WP.join(s,e,t,r+".js");return KP.existsSync(i)?r:n.message(er.NO_FILE)}catch(s){return JP.error(s),n.message(er.VALIDATION_ERR)}}a(B9,"checkFileExists");function H9(e){let t=Ie.object({project:Ie.string().pattern(Us).custom(bf.bind(null,!0)).required().messages({"string.pattern.base":er.BAD_PROJECT_NAME}),type:Ie.string().valid("helpers","routes").required(),file:Ie.string().pattern(Us).custom(B9.bind(null,e.project,e.type)).custom(zu).required().messages({"string.pattern.base":er.BAD_FILE_NAME})});return Ps.validateBySchema(e,t)}a(H9,"getDropCustomFunctionValidator");function x9(e){let t=Ie.object({project:Ie.string().pattern(Us).custom(bf.bind(null,!0)).required().messages({"string.pattern.base":er.BAD_PROJECT_NAME}),type:Ie.string().valid("helpers","routes").required(),file:Ie.string().custom(zu).required(),function_content:Ie.string().required()});return Ps.validateBySchema(e,t)}a(x9,"setCustomFunctionValidator");function G9(e){let t=Ie.object({project:Ie.string().pattern(Us).required().messages({"string.pattern.base":er.BAD_PROJECT_NAME}),file:Ie.string().custom(zu).required(),payload:Ie.string().allow("").optional(),encoding:Ie.string().valid("utf8","ASCII","binary","hex","base64","utf16le","latin1","ucs2").optional()});return Ps.validateBySchema(e,t)}a(G9,"setComponentFileValidator");function q9(e){let t=Ie.object({project:Ie.string().pattern(Us).required().messages({"string.pattern.base":er.BAD_PROJECT_NAME}),file:Ie.string().custom(zu).optional()});return Ps.validateBySchema(e,t)}a(q9,"dropComponentFileValidator");function F9(e){let t=Ie.object({project:Ie.string().required(),file:Ie.string().custom(zu).required(),encoding:Ie.string().valid("utf8","ASCII","binary","hex","base64","utf16le","latin1","ucs2").optional()});return Ps.validateBySchema(e,t)}a(F9,"getComponentFileValidator");function k9(e){let t=Ie.object({project:Ie.string().pattern(Us).custom(bf.bind(null,!1)).required().messages({"string.pattern.base":er.BAD_PROJECT_NAME})});return Ps.validateBySchema(e,t)}a(k9,"addComponentValidator");function V9(e){let t=Ie.object({project:Ie.string().pattern(Us).custom(bf.bind(null,!0)).required().messages({"string.pattern.base":er.BAD_PROJECT_NAME})});return Ps.validateBySchema(e,t)}a(V9,"dropCustomFunctionProjectValidator");function $9(e){let t=Ie.object({project:Ie.string().pattern(Us).required().messages({"string.pattern.base":er.BAD_PROJECT_NAME}),skip_node_modules:Ie.boolean()});return Ps.validateBySchema(e,t)}a($9,"packageComponentValidator");function Y9(e){let t=Ie.object({project:Ie.string().pattern(Us).required().messages({"string.pattern.base":er.BAD_PROJECT_NAME}),payload:Ie.string().optional().messages({"string.pattern.base":er.BAD_PACKAGE}),package:Ie.string().optional()});return Ps.validateBySchema(e,t)}a(Y9,"deployComponentValidator")});var wf=g((zhe,iv)=>{"use strict";var yf=require("joi"),Nf=require("path"),ZP=require("fs-extra"),{exec:K9}=require("child_process"),W9=require("util"),ev=W9.promisify(K9),Ju=L(),{handleHDBError:Ia,hdb_errors:Q9}=ne(),{HTTP_STATUS_CODES:wa}=Q9,Xu=ee(),z9=Xe(),Ca=$();Xu.initSync();var Eg=Xu.get(Ju.CONFIG_PARAMS.COMPONENTSROOT),tv="npm install --omit=dev --json",J9=`${tv} --dry-run`;iv.exports={installModules:e7,auditModules:t7,installAllRootModules:X9,uninstallRootModule:j9,linkHarperdb:Z9};async function X9(e=!1){await If(),await ju(e?"npm install --ignore-scripts":"npm install",Xu.get(Ju.CONFIG_PARAMS.ROOTPATH))}a(X9,"installAllRootModules");async function j9(e){await ju(`npm uninstall ${e}`,Xu.get(Ju.CONFIG_PARAMS.ROOTPATH))}a(j9,"uninstallRootModule");async function Z9(){await If(),await ju(`npm link ${Ju.PACKAGE_ROOT}`,Xu.get(Ju.CONFIG_PARAMS.ROOTPATH))}a(Z9,"linkHarperdb");async function ju(e,t=void 0){let r,n;try{({stdout:r,stderr:n}=await ev(e,{cwd:t}))}catch(s){throw new Error(s.stderr.replace(`
|
|
14
|
+
`,""))}return n&&!n.includes("Debugger listening")&&Ca.error("Error running NPM command:",e,n),Ca.trace(r,n),r?.replace(`
|
|
15
|
+
`,"")}a(ju,"runCommand");async function e7(e){Ca.info(`starting installModules for request: ${e}`);let t=sv(e);if(t)throw Ia(t,t.message,wa.BAD_REQUEST);let{projects:r,dry_run:n}=e,s=n===!0?J9:tv;await If(),await nv(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 _=Nf.join(Eg,u),l,d=null;try{let{stdout:f,stderr:E}=await ev(s,{cwd:_});l=f?f.replace(`
|
|
14
16
|
`,""):null,d=E?E.replace(`
|
|
15
|
-
`,""):null}catch(f){f.stderr?i[u].npm_error=
|
|
16
|
-
`);return r>-1&&s>-1?JSON.parse(e.substring(r+t.length-1,s+1)):e}a(PP,"parseNPMStdErr");async function P9(e){ya.info(`starting auditModules for request: ${e}`);let t=BP(e);if(t)throw ba(t,t.message,Na.BAD_REQUEST);let{projects:r}=e;await Tf(),await vP(r);let s={};for(let n=0,i=r.length;n<i;n++){let o=r[n],c=Sf.join(sg,o);s[o]={npm_output:null,npm_error:null};try{let u=await $u("npm audit --json",c);s[o].npm_output=JSON.parse(u)}catch(u){s[o].npm_error=PP(u.stderr)}}return ya.info(`finished auditModules with response ${s}`),s}a(P9,"auditModules");async function Tf(){try{return await $u("npm -v"),!0}catch{throw ba(new Error,"Unable to install project dependencies: npm is not installed on this instance of HarperDB.",Na.BAD_REQUEST,void 0,void 0,!0)}}a(Tf,"checkNPMInstalled");async function vP(e){if(!Array.isArray(e)||e.length===0)throw ba(new Error,"projects argument must be an array with at least 1 element",Na.BAD_REQUEST,void 0,void 0,!0);let t=[],r=[];for(let s=0,n=e.length;s<n;s++){let i=e[s],o=Sf.join(sg,i.toString());if(!await LP.pathExists(o)){t.push(i);continue}let u=Sf.join(o,"package.json");await LP.pathExists(u)||r.push(i)}if(t.length>0)throw ba(new Error,`Unable to install project dependencies: custom function projects '${t.join(",")}' does not exist.`,Na.BAD_REQUEST,void 0,void 0,!0);if(r.length>0)throw ba(new Error,`Unable to install project dependencies: custom function projects '${r.join(",")}' do not have a package.json file.`,Na.BAD_REQUEST,void 0,void 0,!0)}a(vP,"checkProjectPaths");function BP(e){let t=pf.object({projects:pf.array().min(1).items(pf.string()).required(),dry_run:pf.boolean().default(!1)});return w9.validateBySchema(e,t)}a(BP,"modulesValidator")});var ig=g((whe,kP)=>{"use strict";var Ia=require("fs-extra"),ng=require("path"),Rf=$(),xP=Q(),Af=M(),FP=ee(),v9=Br();kP.exports=B9;async function B9(){let e=H9(),t=FP.get(Af.CONFIG_PARAMS.ROOTPATH),r=ng.join(t,"package.json"),s={dependencies:{harperdb:"file:"+Af.PACKAGE_ROOT}},n=ng.join(t,"node_modules");await Ia.ensureDir(n);let i,o=!0,c=!1;try{i=await Ia.readJson(r)}catch(u){if(xP.isEmptyOrZeroLength(e))return;if(u.code!==Af.NODE_ERROR_CODES.ENOENT)throw u;o=!1}if(!xP.isEmptyOrZeroLength(e)){for(let{name:u,package:_}of e){let l=await qP(_);s.dependencies[u]=l+_}if(!o){Rf.notify("Installing components"),await GP(r,s,null);return}for(let{name:u,package:_}of e){let l=i.dependencies[u],d=await qP(_);if(l===void 0||l!==d+_){c=!0;break}}}for(let u in i.dependencies)s.dependencies[u]===void 0&&(Rf.notify("Removing component",u),c=!0);c&&(Rf.notify("Updating components."),await GP(r,s,i))}a(B9,"installComponents");function H9(){let e=v9.getConfiguration(),t=[];for(let r in e)e[r]?.package&&t.push(Object.assign(e[r],{name:r}));return t}a(H9,"getComponentsConfig");async function qP(e){return e.includes(":")?"":e.startsWith("@")||!e.startsWith("@")&&!e.includes("/")?"npm:":ng.extname(e)||await Ia.pathExists(e)?"file:":"github:"}a(qP,"getPkgPrefix");async function GP(e,t,r){Rf.trace("npm installing components package.json",t),await Ia.writeFile(e,JSON.stringify(t,null," "));try{await gf().installAllRootModules(FP.get(Af.CONFIG_PARAMS.IGNORE_SCRIPTS)===!0)}catch(s){throw r?await Ia.writeFile(e,JSON.stringify(r,null," ")):await Ia.unlink(e),s}}a(GP,"installPackages")});var cg=g((Lhe,KP)=>{"use strict";var ke=require("fs-extra"),og=require("fast-glob"),Se=require("path"),$P=require("tar-fs"),Dhe=require("uuid").v4,ag=require("normalize-path"),cn=DP(),yt=$(),Qe=M(),St=ee(),Yu=Br(),x9=Q(),{PACKAGE_ROOT:q9}=M(),{handleHDBError:vt,hdb_errors:G9}=se(),{basename:F9}=require("path"),k9=ig(),YP=ee(),V9=M(),{Readable:$9}=require("stream"),{isMainThread:Y9}=require("worker_threads"),{HDB_ERROR_MSGS:So,HTTP_STATUS_CODES:Bt}=G9,K9=Se.join(q9,"application-template"),VP=Se.join(St.get(Qe.HDB_SETTINGS_NAMES.HDB_ROOT_KEY),"tmp");function W9(){yt.trace("getting custom api status");let e={};try{e={port:St.get(Qe.CONFIG_PARAMS.HTTP_PORT),directory:St.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),is_enabled:!0}}catch(t){throw vt(new Error,So.FUNCTION_STATUS,Bt.INTERNAL_SERVER_ERROR,yt.ERR,t)}return e}a(W9,"customFunctionsStatus");function Q9(){yt.trace("getting custom api endpoints");let e={},t=St.get(Qe.CONFIG_PARAMS.COMPONENTSROOT);try{og.sync(ag(`${t}/*`),{onlyDirectories:!0}).forEach(s=>{let n=s.split("/").pop();e[n]={routes:og.sync(ag(`${s}/routes/*.js`)).map(i=>i.split("/").pop().split(".js")[0]),helpers:og.sync(ag(`${s}/helpers/*.js`)).map(i=>i.split("/").pop().split(".js")[0])}})}catch(r){throw vt(new Error,So.GET_FUNCTIONS,Bt.INTERNAL_SERVER_ERROR,yt.ERR,r)}return e}a(Q9,"getCustomFunctions");function z9(e){e.project&&(e.project=Se.parse(e.project).name),e.file&&(e.file=Se.parse(e.file).name);let t=cn.getDropCustomFunctionValidator(e);if(t)throw vt(t,t.message,Bt.BAD_REQUEST);yt.trace("getting custom api endpoint file content");let r=St.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),{project:s,type:n,file:i}=e,o=Se.join(r,s,n,i+".js");try{return ke.readFileSync(o,{encoding:"utf8"})}catch(c){throw vt(new Error,So.GET_FUNCTION,Bt.INTERNAL_SERVER_ERROR,yt.ERR,c)}}a(z9,"getCustomFunction");function J9(e){e.project&&(e.project=Se.parse(e.project).name),e.file&&(e.file=Se.parse(e.file).name);let t=cn.setCustomFunctionValidator(e);if(t)throw vt(t,t.message,Bt.BAD_REQUEST);yt.trace("setting custom function file content");let r=St.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),{project:s,type:n,file:i,function_content:o}=e;try{return ke.outputFileSync(Se.join(r,s,n,i+".js"),o),`Successfully updated custom function: ${i}.js`}catch(c){throw vt(new Error,So.SET_FUNCTION,Bt.INTERNAL_SERVER_ERROR,yt.ERR,c)}}a(J9,"setCustomFunction");function X9(e){e.project&&(e.project=Se.parse(e.project).name),e.file&&(e.file=Se.parse(e.file).name);let t=cn.getDropCustomFunctionValidator(e);if(t)throw vt(t,t.message,Bt.BAD_REQUEST);yt.trace("dropping custom function file");let r=St.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),{project:s,type:n,file:i}=e;try{return ke.unlinkSync(Se.join(r,s,n,i+".js")),`Successfully deleted custom function: ${i}.js`}catch(o){throw vt(new Error,So.DROP_FUNCTION,Bt.INTERNAL_SERVER_ERROR,yt.ERR,o)}}a(X9,"dropCustomFunction");function j9(e){e.project&&(e.project=Se.parse(e.project).name);let t=cn.addComponentValidator(e);if(t)throw vt(t,t.message,Bt.BAD_REQUEST);yt.trace("adding component");let r=St.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),{project:s}=e;try{let n=Se.join(r,s);return ke.mkdirSync(n,{recursive:!0}),ke.copySync(K9,n),`Successfully added project: ${s}`}catch(n){throw vt(new Error,So.ADD_FUNCTION,Bt.INTERNAL_SERVER_ERROR,yt.ERR,n)}}a(j9,"addComponent");function Z9(e){e.project&&(e.project=Se.parse(e.project).name);let t=cn.dropCustomFunctionProjectValidator(e);if(t)throw vt(t,t.message,Bt.BAD_REQUEST);yt.trace("dropping custom function project");let r=St.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),{project:s}=e,n=St.get(Qe.CONFIG_PARAMS.APPS);if(!x9.isEmptyOrZeroLength(n)){let i=!1;for(let[o,c]of n.entries())if(c.name===s){n.splice(o,1),i=!0;break}if(i)return Yu.updateConfigValue(Qe.CONFIG_PARAMS.APPS,n),`Successfully deleted project: ${s}`}try{let i=Se.join(r,s);return ke.rmSync(i,{recursive:!0}),`Successfully deleted project: ${s}`}catch(i){throw vt(new Error,So.DROP_FUNCTION_PROJECT,Bt.INTERNAL_SERVER_ERROR,yt.ERR,i)}}a(Z9,"dropCustomFunctionProject");async function e7(e){e.project&&(e.project=Se.parse(e.project).name);let t=cn.packageComponentValidator(e);if(t)throw vt(t,t.message,Bt.BAD_REQUEST);let r=St.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),{project:s}=e;yt.trace("packaging component",s);let n;try{n=await ke.realpath(Se.join(r,s))}catch(u){if(u.code!==Qe.NODE_ERROR_CODES.ENOENT)throw u;try{n=await ke.realpath(Se.join(St.get(Qe.CONFIG_PARAMS.ROOTPATH),"node_modules",s))}catch(_){if(_.code===Qe.NODE_ERROR_CODES.ENOENT)throw new Error(`Unable to locate project '${s}'`)}}await ke.ensureDir(VP);let i=Se.join(VP,`${s}.tar`),o={};(e.skip_node_modules===!0||e.skip_node_modules==="true")&&(o={ignore:u=>u.includes(Se.join(n,"node_modules"))}),$P.pack(n,o).pipe(ke.createWriteStream(i,{overwrite:!0})),await new Promise(u=>setTimeout(u,2e3));let c=ke.readFileSync(i,{encoding:"base64"});return await ke.remove(i),{project:s,payload:c}}a(e7,"packageComponent");async function t7(e){e.project&&(e.project=Se.parse(e.project).name);let t=cn.deployComponentValidator(e);if(t)throw vt(t,t.message,Bt.BAD_REQUEST);let r=St.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),{project:s,payload:n,package:i}=e;if(yt.trace("deploying component",s),!n&&!i)throw new Error("'payload' or 'package' must be provided");let o;if(n){o=Se.join(r,s),i="file:"+o,await ke.ensureDir(o);let f=$9.from(Buffer.from(n,"base64"));await new Promise((h,p)=>{f.pipe($P.extract(o,{finish:h})).on("error",p)});let E=await ke.readdir(o);E.length===1&&E[0]==="package"&&(await ke.copy(Se.join(o,"package"),o),await ke.remove(Se.join(o,"package")))}if(await Yu.addConfig(s,{package:i}),!n){await k9();let f=YP.get(V9.CONFIG_PARAMS.ROOTPATH);o=Se.join(f,"node_modules",s)}if(Y9)return;let c=new Map;c.isWorker=!0;let u=(bf(),ne(Of)),_;u.setErrorReporter(f=>_=f);let l=F9(o),d=u.component_errors.get(l);try{await u.loadComponent(o,c)}finally{u.component_errors.set(l,d)}if(_)throw _;return yt.info("Installed component"),`Successfully deployed: ${s}`}a(t7,"deployComponent");async function r7(){let e=Yu.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 ke.readdir(o,{withFileTypes:!0});for(let _ of u){let l=_.name;if(l.startsWith(".")||l==="node_modules")continue;let d=Se.join(o,l);if(_.isDirectory()||_.isSymbolicLink()){let f={name:l,entries:[]};c.entries.push(f),await r(d,f)}else{let f=await ke.stat(d),E={name:Se.basename(l),mtime:f.mtime,size:f.size};c.entries.push(E)}}return c}catch(u){return yt.warn("Error loading package",u),{error:u.toString(),entries:[]}}},"walk_dir"),s=await r(St.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),{name:St.get(Qe.CONFIG_PARAMS.COMPONENTSROOT).split(Se.sep).slice(-1).pop(),entries:t});for(let o of s.entries)if(o.package){let c=await r(Se.join(St.get(Qe.CONFIG_PARAMS.ROOTPATH),"node_modules",o.name),{name:o.name,entries:[]});Object.assign(o,c)}let i=(bf(),ne(Of)).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 s}a(r7,"getComponents");async function s7(e){let t=cn.getComponentFileValidator(e);if(t)throw vt(t,t.message,Bt.BAD_REQUEST);let s=Yu.getConfigObj()[e.project]||e.project==="harperdb"?Se.join(YP.get(Qe.CONFIG_PARAMS.ROOTPATH),"node_modules"):St.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),n=e.encoding?{encoding:e.encoding}:{encoding:"utf8"};try{let i=await ke.stat(Se.join(s,e.project,e.file));return{message:await ke.readFile(Se.join(s,e.project,e.file),n),size:i.size,birthtime:i.birthtime,mtime:i.mtime}}catch(i){throw i.code===Qe.NODE_ERROR_CODES.ENOENT?new Error(`Component file not found '${Se.join(e.project,e.file)}'`):i}}a(s7,"getComponentFile");async function n7(e){let t=cn.setComponentFileValidator(e);if(t)throw vt(t,t.message,Bt.BAD_REQUEST);let r=e.encoding?{encoding:e.encoding}:{encoding:"utf8"},s=Se.join(St.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),e.project,e.file);return e.payload!==void 0?(await ke.ensureFile(s),await ke.outputFile(s,e.payload,r)):await ke.ensureDir(s),"Successfully set component: "+e.file}a(n7,"setComponentFile");async function i7(e){let t=cn.dropComponentFileValidator(e);if(t)throw vt(t,t.message,Bt.BAD_REQUEST);let r=e.file?Se.join(e.project,e.file):e.project,s=Se.join(St.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),r);return await ke.pathExists(s)&&await ke.remove(s),Yu.deleteConfigFromFile([e.project]),"Successfully dropped: "+r}a(i7,"dropComponent");KP.exports={customFunctionsStatus:W9,getCustomFunctions:Q9,getCustomFunction:z9,setCustomFunction:J9,dropCustomFunction:X9,addComponent:j9,dropCustomFunctionProject:Z9,packageComponent:e7,deployComponent:t7,getComponents:r7,getComponentFile:s7,setComponentFile:n7,dropComponent:i7}});var ug=g((Uhe,QP)=>{"use strict";var un=require("joi"),WP=Xe();QP.exports={readTransactionLogValidator:o7,deleteTransactionLogsBeforeValidator:a7};function o7(e){let t=un.object({schema:un.string().required(),table:un.string().required(),from:un.date().timestamp(),to:un.date().timestamp(),limit:un.number().min(1)});return WP.validateBySchema(e,t)}a(o7,"readTransactionLogValidator");function a7(e){let t=un.object({schema:un.string().required(),table:un.string().required(),timestamp:un.date().timestamp().required()});return WP.validateBySchema(e,t)}a(a7,"deleteTransactionLogsBeforeValidator")});var yf=g((vhe,ZP)=>{"use strict";var lg=M(),Nf=nt(),zP=Q(),JP=ee(),XP=Rn(),{handleHDBError:wa,hdb_errors:c7}=se(),{HTTP_STATUS_CODES:Ca}=c7,{readTransactionLogValidator:u7,deleteTransactionLogsBeforeValidator:l7}=ug(),jP="This operation relies on clustering and cannot run with it disable.",_7="Logs successfully deleted from transaction log.",d7="All logs successfully deleted from transaction log.";ZP.exports={readTransactionLog:f7,deleteTransactionLogsBefore:E7};async function*f7(e){let t=u7(e);if(t)throw wa(t,t.message,Ca.BAD_REQUEST,void 0,void 0,!0);if(!JP.get(lg.CONFIG_PARAMS.CLUSTERING_ENABLED))throw wa(new Error,jP,Ca.NOT_FOUND,void 0,void 0,!0);let{schema:r,table:s}=e,n=zP.checkSchemaTableExist(r,s);if(n)throw wa(new Error,n,Ca.NOT_FOUND,void 0,void 0,!0);let i=XP.createNatsTableStreamName(r,s),o=await Nf.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===lg.OPERATIONS_ENUM.DELETE&&(_.hash_values=c?.entry?.hash_values),yield _}}a(f7,"readTransactionLog");async function E7(e){let t=l7(e);if(t)throw wa(t,t.message,Ca.BAD_REQUEST,void 0,void 0,!0);if(!JP.get(lg.CONFIG_PARAMS.CLUSTERING_ENABLED))throw wa(new Error,jP,Ca.NOT_FOUND,void 0,void 0,!0);let{schema:r,table:s,timestamp:n}=e,i=zP.checkSchemaTableExist(r,s);if(i)throw wa(new Error,i,Ca.NOT_FOUND,void 0,void 0,!0);let o=XP.createNatsTableStreamName(r,s),{jsm:c}=await Nf.getNATSReferences(),u=await Nf.getStreamInfo(o),_=new Date(u.state.first_ts).getTime();if(n<=_)return`No transactions exist before: ${n}`;let l=_7,d,f=new Date(u.state.last_ts).getTime();return n>f?(d=u.state.last_seq+1,l=d7):d=(await Nf.viewStream(o,parseInt(n),1))[0].nats_sequence,await c.streams.purge(o,{seq:d}),l}a(E7,"deleteTransactionLogsBefore")});var tv=g((Hhe,ev)=>{"use strict";var _g=class{static{a(this,"PermissionTableResponseObject")}constructor(t,r,s=[],n=[]){this.schema=t,this.table=r,this.required_table_permissions=s,this.required_attribute_permissions=n}};ev.exports=_g});var sv=g((qhe,rv)=>{"use strict";var dg=class{static{a(this,"PermissionAttributeResponseObject")}constructor(t,r=[]){this.attribute_name=t,this.required_permissions=r}};rv.exports=dg});var Eg=g((Fhe,iv)=>{"use strict";var nv=tv(),h7=sv(),{HDB_ERROR_MSGS:m7}=Ir(),fg=class{static{a(this,"PermissionResponseObject")}constructor(){this.error=m7.OP_AUTH_PERMS_ERROR,this.unauthorized_access={},this.invalid_schema_items=[]}handleUnauthorizedItem(t){return this.invalid_schema_items=[],this.unauthorized_access=[t],this}handleInvalidItem(t){return this.invalid_schema_items=[t],this.unauthorized_access=[],this}addInvalidItem(t,r,s){if(r&&s){let n=`${r}_${s}`;if(this.unauthorized_access[n])return}this.invalid_schema_items.push(t)}addUnauthorizedTable(t,r,s){let n=new nv(t,r,s),i=`${t}_${r}`;this.unauthorized_access[i]=n}addUnauthorizedAttributes(t,r,s,n){let i=[];t.forEach(c=>{let u=new h7(c,n[c]);i.push(u)});let o=`${r}_${s}`;if(this.unauthorized_access[o])this.unauthorized_access[o].required_attribute_permissions=i;else{let c=new nv(r,s,[],i);this.unauthorized_access[o]=c}}getPermsResponse(){let t=Object.values(this.unauthorized_access);return t.length>0||this.invalid_schema_items.length>0?(this.unauthorized_access=t,this):null}};iv.exports=fg});var Df=g((Vhe,Rv)=>{"use strict";var hg=Ur(),If=Mr(),ds=fu(),Qu=ti(),mg=ni(),p7=LS(),S7=mL(),zu=is(),wf=GS(),It=$(),T7=VS(),g7=Vd(),R7=RT(),A7=Yd(),O7=OT(),b7=bT(),N7=IT(),y7=CT(),pg=MT(),Pn=Q(),I7=fU(),Sg=HT(),cv=_f(),_s=M(),uv=fP(),w7=ha(),lv=Tu(),_v=(hf(),ne(Gu)),dv=Br(),$r=cg(),C7=require("alasql"),fv=yf(),Ev=gf(),hv=Eg(),{handleHDBError:Rr,hdb_errors:mv}=se(),{HDB_ERROR_MSGS:$t,HTTP_STATUS_CODES:Ku}=mv,V=new Map,pv="delete",Oi="insert",vn="read",To="update",Wu="describe",ov=Qu.describeSchema.name,av=Qu.describeTable.name,Sv={delete:!0,deleteRecord:!0,update:!0,updateData:!0,dropAttribute:!0,dropTable:!0,dropSchema:!0,upsert:!0,upsertData:!0},D7="catchup",L7="handleGetJob",M7="handleGetJobsByStartDate",Cf={CSV_DATA_LOAD:"csvDataLoad",CSV_URL_LOAD:"csvURLLoad",CSV_FILE_LOAD:"csvFileLoad",IMPORT_FROM_S3:"importFromS3"},U7=[ds.createTable.name,ds.createAttribute.name,ds.dropTable.name,ds.dropAttribute.name],Tv={EXPORT_TO_S3:"export_to_s3",EXPORT_LOCAL:"export_local"},W=class{static{a(this,"permission")}constructor(t,r){this.requires_su=t,this.perms=r}};V.set(hg.insert.name,new W(!1,[Oi]));V.set(hg.update.name,new W(!1,[To]));V.set(hg.upsert.name,new W(!1,[Oi,To]));V.set(If.searchByConditions.name,new W(!1,[vn]));V.set(If.searchByHash.name,new W(!1,[vn]));V.set(If.searchByValue.name,new W(!1,[vn]));V.set(If.search.name,new W(!1,[vn]));V.set(ds.createSchema.name,new W(!0,[]));V.set(ds.createTable.name,new W(!0,[]));V.set(ds.createAttribute.name,new W(!1,[Oi]));V.set(ds.dropSchema.name,new W(!0,[]));V.set(ds.dropTable.name,new W(!0,[]));V.set(ds.dropAttribute.name,new W(!0,[]));V.set(Qu.describeSchema.name,new W(!1,[vn]));V.set(Qu.describeTable.name,new W(!1,[vn]));V.set(mg.deleteRecord.name,new W(!1,[pv]));V.set(zu.addUser.name,new W(!0,[]));V.set(zu.alterUser.name,new W(!0,[]));V.set(zu.dropUser.name,new W(!0,[]));V.set(zu.listUsersExternal.name,new W(!0,[]));V.set(wf.listRoles.name,new W(!0,[]));V.set(wf.addRole.name,new W(!0,[]));V.set(wf.alterRole.name,new W(!0,[]));V.set(wf.dropRole.name,new W(!0,[]));V.set(T7.name,new W(!0,[]));V.set(g7.name,new W(!0,[]));V.set(R7.name,new W(!0,[]));V.set(A7.name,new W(!0,[]));V.set(O7.name,new W(!0,[]));V.set(b7.name,new W(!0,[]));V.set(pg.setRoutes.name,new W(!0,[]));V.set(pg.getRoutes.name,new W(!0,[]));V.set(pg.deleteRoutes.name,new W(!0,[]));V.set(dv.setConfiguration.name,new W(!0,[]));V.set(N7.clusterStatus.name,new W(!0,[]));V.set(y7.name,new W(!0,[]));V.set(Sg.getFingerprint.name,new W(!0,[]));V.set(Sg.setLicense.name,new W(!0,[]));V.set(mg.deleteFilesBefore.name,new W(!0,[]));V.set(mg.deleteAuditLogsBefore.name,new W(!0,[]));V.set(cv.restart.name,new W(!0,[]));V.set(cv.restartService.name,new W(!0,[]));V.set(p7.name,new W(!0,[]));V.set(S7.name,new W(!0,[vn]));V.set(w7.systemInformation.name,new W(!0,[]));V.set(dv.getConfiguration.name,new W(!0,[]));V.set(fv.readTransactionLog.name,new W(!0,[]));V.set(fv.deleteTransactionLogsBefore.name,new W(!0,[]));V.set(Ev.installModules.name,new W(!0,[]));V.set(Ev.auditModules.name,new W(!0,[]));V.set(lv.createTokens.name,new W(!1,[]));V.set(lv.refreshOperationToken.name,new W(!1,[]));V.set(_v.login.name,new W(!1,[]));V.set(_v.logout.name,new W(!1,[]));V.set($r.customFunctionsStatus.name,new W(!0,[]));V.set($r.getCustomFunctions.name,new W(!0,[]));V.set($r.getComponents.name,new W(!0,[]));V.set($r.getComponentFile.name,new W(!0,[]));V.set($r.setComponentFile.name,new W(!0,[]));V.set($r.dropComponent.name,new W(!0,[]));V.set($r.getCustomFunction.name,new W(!0,[]));V.set($r.setCustomFunction.name,new W(!0,[]));V.set($r.dropCustomFunction.name,new W(!0,[]));V.set($r.addComponent.name,new W(!0,[]));V.set($r.dropCustomFunctionProject.name,new W(!0,[]));V.set($r.packageComponent.name,new W(!0,[]));V.set($r.deployComponent.name,new W(!0,[]));V.set(Sg.getRegistrationInfo.name,new W(!1,[]));V.set(zu.userInfo.name,new W(!1,[]));V.set(Qu.describeAll.name,new W(!1,[]));V.set(L7,new W(!1,[]));V.set(M7,new W(!0,[]));V.set(D7,new W(!0,[]));V.set(Cf.CSV_DATA_LOAD,new W(!1,[Oi,To]));V.set(Cf.CSV_URL_LOAD,new W(!1,[Oi,To]));V.set(Cf.CSV_FILE_LOAD,new W(!1,[Oi,To]));V.set(Cf.IMPORT_FROM_S3,new W(!1,[Oi,To]));V.set(Tv.EXPORT_TO_S3,new W(!0,[]));V.set(Tv.EXPORT_LOCAL,new W(!0,[]));V.set(_s.VALID_SQL_OPS_ENUM.DELETE,new W(!1,[pv]));V.set(_s.VALID_SQL_OPS_ENUM.SELECT,new W(!1,[vn]));V.set(_s.VALID_SQL_OPS_ENUM.INSERT,new W(!1,[Oi]));V.set(_s.VALID_SQL_OPS_ENUM.UPDATE,new W(!1,[To]));Rv.exports={verifyPerms:v7,verifyPermsAst:P7,verifyBulkLoadAttributePerms:H7};function P7(e,t,r){if(Pn.isEmptyOrZeroLength(e))throw It.info("verify_perms_ast has an empty user parameter"),Rr(new Error);if(Pn.isEmptyOrZeroLength(t))throw It.info("verify_perms_ast has an empty user parameter"),Rr(new Error);if(Pn.isEmptyOrZeroLength(r))throw It.info("verify_perms_ast has a null operation parameter"),Rr(new Error);try{let s=new hv,n=new I7(e),i=n.getSchemas(),o=new Map;if((!i||i.length===0)&&n.affected_attributes&&n.affected_attributes.size>0)throw It.info("No schemas defined in verifyPermsAst(), will not continue."),Rr(new Error);let c=!!t.role.permission.super_user,u=i.includes("system");if(u&&Sv[r])throw Rr(new Error,$t.DROP_SYSTEM,Ku.FORBIDDEN);if(c&&!u)return null;let _=uv.getRolePermissions(t.role);t.role.permission=_,!c&&e instanceof C7.yy.Select&&(e=n.updateAttributeWildcardsForRolePerms(_));for(let d=0;d<i.length;d++){let f=n.getTablesBySchemaName(i[d]);f&&o.set(i[d],f)}let l=gv(t,r,o,s);return l||(o.forEach((d,f)=>{for(let E=0;E<d.length;E++){let h=n.getAttributesBySchemaTableName(f,d[E]),p=gg(t.role.permission,f,d[E]);Tg(h,p,r,d[E],f,s)}}),s.getPermsResponse())}catch(s){throw Rr(s)}}a(P7,"verifyPermsAst");function v7(e,t){if(e===null||t===null||e.hdb_user===void 0||e.hdb_user===null)throw It.info("null required parameter in verifyPerms"),Rr(new Error,$t.DEFAULT_INVALID_REQUEST,Ku.BAD_REQUEST);let r;t instanceof Function?r=t.name:r=t;let s=e.action,n=e.schema??e.database,i=e.table,o=new Map;n&&i&&o.set(n,[i]);let c=new hv;if(Pn.isEmptyOrZeroLength(e.hdb_user.role)||Pn.isEmptyOrZeroLength(e.hdb_user.role.permission))return It.info(`User ${e.hdb_user.username} has no role or permissions. Please assign the user a valid role.`),c.handleUnauthorizedItem($t.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(_s.SYSTEM_SCHEMA_NAME)||n===_s.SYSTEM_SCHEMA_NAME;if(l&&Sv[r])throw Rr(new Error,$t.DROP_SYSTEM,Ku.FORBIDDEN);if(u&&!l||_===!0&&(r===ds.createSchema.name||r===ds.dropSchema.name))return null;if(U7.indexOf(r)>=0&&(_===!0||Array.isArray(_)))return _===!0||_.indexOf(n)>=0?null:c.handleUnauthorizedItem(`User does not have access to perform '${e.operation}' against schema '${n}'`);let d=uv.getRolePermissions(e.hdb_user.role);if(e.hdb_user.role.permission=d,r===ov||r===av){if(n===_s.SYSTEM_SCHEMA_NAME)return c.handleUnauthorizedItem($t.SCHEMA_PERM_ERROR(n));if(!d.super_user){if(r===ov&&(!d[n]||!d[n][Wu]))return c.handleInvalidItem($t.SCHEMA_NOT_FOUND(n));if(r===av&&(!d[n]||!d[n].tables[i]||!d[n].tables[i][Wu]))return c.handleInvalidItem($t.TABLE_NOT_FOUND(n,i))}}let f=gv(e.hdb_user,r,o,c,s);if(f)return f;if(V.get(r)&&V.get(r).perms.length===0)return null;if(!u&&e.get_attributes&&_s.SEARCH_WILDCARDS.includes(e.get_attributes[0])){let p=[],S=d[n].tables[i];S[_s.PERMS_CRUD_ENUM.READ]&&(S.attribute_permissions.length>0?S.attribute_permissions.filter(b=>b[_s.PERMS_CRUD_ENUM.READ]).forEach(b=>{p.push(b.attribute_name)}):p=global.hdb_schema[n][i].attributes.map(T=>T.attribute),e.get_attributes=p)}let E=B7(e),h=gg(e.hdb_user.role.permission,n,i);return Tg(E,h,r,i,n,c,s),c.getPermsResponse()}a(v7,"verifyPerms");function gv(e,t,r,s,n){if(Pn.arrayHasEmptyValues([e,t,r]))throw It.info("hasPermissions has an invalid parameter"),Rr(new Error);let i=r.has("system"),o=e.role.permission;if(o.super_user&&(!i||V.get(t).requires_su))return null;if(!V.get(t))throw It.info(`operation ${t} not found.`),Rr(new Error,$t.OP_NOT_FOUND(t),Ku.BAD_REQUEST);if(V.get(t)&&V.get(t).requires_su)return It.info(`operation ${t} requires SU permissions.`),s.handleUnauthorizedItem($t.OP_IS_SU_ONLY(t));let c=r.keys();for(let u of c){try{if(u&&!o[u]||o[u][Wu]===!1){s.addInvalidItem($t.SCHEMA_NOT_FOUND(u));continue}}catch{s.addInvalidItem($t.SCHEMA_NOT_FOUND(u));continue}let _=r.get(u);for(let l of _){let d=o[u].tables[l];if(!d||d[Wu]===!1)s.addInvalidItem($t.TABLE_NOT_FOUND(u,l));else try{let f=[],E=V.get(t).perms;!Pn.isEmpty(n)&&E.includes(n)&&(E=[n]);for(let h=0;h<E.length;h++){let p=E[h],S=d[p];(S==null||S===!1)&&(It.info(`Required ${p} permission not found for ${t} ${n?`${n} `:""}operation in role ${e.role.id}`),f.push(p))}f.length>0&&s.addUnauthorizedTable(u,l,f)}catch(f){let E=$t.UNKNOWN_OP_AUTH_ERROR(t,u,l);throw It.error(E),It.error(f),Rr(mv.CHECK_LOGS_WRAPPER(E))}}}return r.size<2?s.getPermsResponse():null}a(gv,"hasPermissions");function Tg(e,t,r,s,n,i,o){if(!e||!t)throw It.info("no attributes specified in checkAttributePerms."),Rr(new Error);let c=V.get(r).perms;if(!c||c==="")throw It.info(`no permissions found for ${r} in checkAttributePerms().`),Rr(new Error);if(Pn.isEmptyOrZeroLength(t))return It.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[Wu]===!1){i.addInvalidItem($t.ATTR_NOT_FOUND(n,s,l),n,s);continue}if(c)for(let f of c){if(_s.TIME_STAMP_NAMES.includes(d.attribute_name)&&f!==vn)throw Rr(new Error,$t.SYSTEM_TIMESTAMP_PERMS_ERR,Ku.FORBIDDEN);d[f]===!1&&(u[d.attribute_name]?u[d.attribute_name].push(f):u[d.attribute_name]=[f])}}else i.addInvalidItem($t.ATTR_NOT_FOUND(n,s,l),n,s)}let _=Object.keys(u);_.length>0&&i.addUnauthorizedAttributes(_,n,s,u)}a(Tg,"checkAttributePerms");function B7(e){let t=new Set;try{if(e.action)return t;if(e.operation===_s.OPERATIONS_ENUM.SEARCH_BY_CONDITIONS&&e.conditions.forEach(r=>{t.add(r.search_attribute)}),e&&e.search_attribute&&t.add(e.search_attribute),!e.records||e.records.length===0){if(!e.get_attributes||!e.get_attributes.length===0)return t;for(let r=0;r<e.get_attributes.length;r++)t.add(e.get_attributes[r])}else for(let r=0;r<e.records.length;r++){let s=Object.keys(e.records[r]);for(let n=0;n<s.length;n++)t.add(s[n])}}catch(r){It.info(r)}return t}a(B7,"getRecordAttributes");function gg(e,t,r){let s=new Map;if(Pn.isEmpty(e))return It.info("no hdb_user specified in getAttributePermissions"),s;if(e.super_user||!t||!r)return s;try{e[t].tables[r].attribute_permissions.forEach(n=>{s.has(n.attribute_name)||s.set(n.attribute_name,n)})}catch{It.info(`No attribute permissions found for schema ${t} and table ${r}.`)}return s}a(gg,"getAttributePermissions");function H7(e,t,r,s,n,i,o){let c=new Set(i),u=gg(e,s,n);Tg(c,u,t,n,s,o,r)}a(H7,"verifyBulkLoadAttributePerms")});var Mf=g((Yhe,yv)=>{"use strict";yv.exports={evaluateSQL:J7,processAST:Nv,convertSQLToAST:bv,checkASTPermissions:Ov};var x7=Ur(),Av=require("util"),q7=Av.callbackify(x7.insert),G7=Mr().search,F7=sD().update,k7=Av.callbackify(F7),V7=iD().convertDelete,bi=require("alasql"),$7=Df(),Lf=$(),Y7=ad(),K7=Q(),Ju=M(),{hdb_errors:W7,handleHDBError:Rg}=se(),{HTTP_STATUS_CODES:Ag}=W7;Y7(bi);var Q7=403,z7="There was a problem performing this insert. Please check the logs and try again.",Og=class{static{a(this,"ParsedSQLObject")}constructor(){this.ast=void 0,this.variant=void 0,this.permissions_checked=!1}};function J7(e,t){let r=e.parsed_sql_object;if(!r){r=bv(e.sql);let s,n=r.ast.statements[0];if(n instanceof bi.yy.Insert?s=n.into.databaseid:n instanceof bi.yy.Select?s=n.from?n.from[0].databaseid:null:n instanceof bi.yy.Update||n instanceof bi.yy.Delete?s=n.table.databaseid:Lf.error("AST in evaluateSQL is not a valid SQL type."),!(n instanceof bi.yy.Select)&&K7.isEmptyOrZeroLength(s))return t("No schema specified",null)}Nv(e,r,(s,n)=>{if(s)return t(s);t(null,n)})}a(J7,"evaluateSQL");function Ov(e,t){let r;try{r=$7.verifyPermsAst(t.ast.statements[0],e.hdb_user,t.variant),t.permissions_checked=!0}catch(s){throw s}return r||null}a(Ov,"checkASTPermissions");function bv(e){let t=new Og;if(!e)throw Rg(new Error,"The 'sql' parameter is missing from the request body",Ag.BAD_REQUEST);try{let r=e.trim(),s=bi.parse(r),n=r.split(" ")[0].toLowerCase();t.ast=s,t.variant=n}catch(r){let s=r.message.split(`
|
|
17
|
-
`);throw s[1]?Rg(r,`Invalid SQL at: ${s[1]}. Please ensure your SQL is valid. Try adding backticks to reserved words and schema table references.`,Ag.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.",Ag.BAD_REQUEST)}return t}a(bv,"convertSQLToAST");function Nv(e,t,r){try{let s=X7;if(!e.bypass_auth&&!t.permissions_checked){let i=Ov(e,t);if(i&&i.length>0)return r(Q7,i)}let n={statement:t.ast.statements[0],hdb_user:e.hdb_user};switch(t.variant){case Ju.VALID_SQL_OPS_ENUM.SELECT:s=G7,n=t.ast.statements[0];break;case Ju.VALID_SQL_OPS_ENUM.INSERT:s=j7;break;case Ju.VALID_SQL_OPS_ENUM.UPDATE:s=k7;break;case Ju.VALID_SQL_OPS_ENUM.DELETE:s=V7;break;default:throw new Error(`unsupported SQL type ${t.variant} in SQL: ${e}`)}s(n,(i,o)=>{if(i){r(i);return}r(null,o)})}catch(s){return r(s)}}a(Nv,"processAST");function X7(e,t){Lf.info(e),t("unknown sql statement")}a(X7,"nullFunction");function j7({statement:e,hdb_user:t},r){let s=e.into,n={schema:s.databaseid,table:s.tableid,operation:"insert",hdb_user:t},i=e.columns.map(o=>o.columnid);try{n.records=Z7(i,e.values)}catch(o){return r(o)}q7(n,(o,c)=>{if(o)return r(o);try{delete c.new_attributes,delete c.txn_time}catch(u){Lf.error(`Error delete new_attributes from insert response: ${u}`)}r(null,c)})}a(j7,"convertInsert");function Z7(e,t){try{return t.map(r=>{if(e.length!==r.length)throw"number of values do not match number of columns in insert";let s={};return r.forEach((n,i)=>{if(n.columnid)throw"cannot use a column in insert value";"value"in n?s[e[i]]=n.value:s[e[i]]=bi.compile(`SELECT ${n.toString()} AS [${Ju.FUNC_VAL}] FROM ?`)}),s})}catch(r){throw Lf.error(r),new Error(z7)}}a(Z7,"createDataObjects")});var bg=g((Whe,wv)=>{"use strict";var{S3:eee,GetObjectCommand:tee}=require("@aws-sdk/client-s3");wv.exports={getFileStreamFromS3:ree,getS3AuthObj:Iv};async function ree(e){let{s3:t}=e,r={Bucket:t.bucket,Key:t.key};return(await Iv(t.aws_access_key_id,t.aws_secret_access_key,t.region).send(new tee(r))).Body}a(ree,"getFileStreamFromS3");function Iv(e,t,r){return new eee({credentials:{accessKeyId:e,secretAccessKey:t},region:r})}a(Iv,"getS3AuthObj")});var Uf=g((zhe,Hv)=>{"use strict";var yg=Mr(),see=Mf(),nee=bg(),{AsyncParser:iee,Transform:oee}=require("json2csv"),ju=require("stream"),Yr=Q(),Ng=require("fs-extra"),aee=require("path"),Es=$(),{promisify:Lv}=require("util"),Xu=Q(),{handleHDBError:Tt,hdb_errors:cee}=se(),{HDB_ERROR_MSGS:Ar,HTTP_STATUS_CODES:gt}=cee,{streamAsJSON:uee}=(Yh(),ne(Tb)),{Upload:lee}=require("@aws-sdk/lib-storage"),Cv=["search_by_value","search_by_hash","sql","search_by_conditions"],Dv=["json","csv"],Mv="json",Uv="csv",_ee="Successfully exported JSON locally.",dee="Successfully exported CSV locally.",fee=1e3,Eee=yg.searchByHash,hee=yg.searchByValue,mee=Lv(see.evaluateSQL),pee=Lv(ju.finished);Hv.exports={export_to_s3:Ree,export_local:See,toCsvStream:Pv};async function See(e){Es.trace(`export_local request to path: ${e.path}, filename: ${e.filename}, format: ${e.format}`);let t=vv(e);if(!Yr.isEmpty(t))throw Es.error(t),Tt(new Error,t,gt.BAD_REQUEST,void 0,void 0,!0);if(Yr.isEmpty(e.path))throw Es.error(Ar.MISSING_VALUE("path")),Tt(new Error,Ar.MISSING_VALUE("path"),gt.BAD_REQUEST,void 0,void 0,!0);let r=(Yr.isEmpty(e.filename)?new Date().getTime():e.filename)+"."+e.format;e.path.endsWith(aee.sep)&&(e.path=e.path.substring(0,e.path.length-1));let s=Yr.buildFolderPath(e.path,r);await Tee(e.path);let n=await Bv(e);return await gee(s,e.format,n)}a(See,"export_local");async function Tee(e){if(Es.trace("in confirmPath"),Yr.isEmptyOrZeroLength(e))throw Tt(new Error,`Invalid path: ${e}`,gt.BAD_REQUEST,void 0,void 0,!0);let t;try{t=await Ng.stat(e)}catch(r){let s;throw r.code==="ENOENT"?s=`path '${e}' does not exist`:r.code==="EACCES"?s=`access to path '${e}' is denied`:s=r.message,Es.error(s),Tt(new Error,s,gt.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 Es.error(r),Tt(new Error,r,gt.BAD_REQUEST,void 0,void 0,!0)}return!0}a(Tee,"confirmPath");async function gee(e,t,r){if(Es.trace("in saveToLocal"),Xu.isEmptyOrZeroLength(e))throw Tt(new Error,Ar.INVALID_VALUE("file_path"),gt.BAD_REQUEST,void 0,void 0,!0);if(Xu.isEmptyOrZeroLength(t))throw Tt(new Error,Ar.INVALID_VALUE("Source format"),gt.BAD_REQUEST,void 0,void 0,!0);if(Xu.isEmpty(r))throw Tt(new Error,Ar.NOT_FOUND("Data"),gt.BAD_REQUEST,void 0,void 0,!0);if(t===Mv){let s=Ng.createWriteStream(e);return uee(r).pipe(s),await pee(s),{message:_ee,path:e}}else if(t===Uv){let s=Ng.createWriteStream(e),n=ju.Readable.from(r),i={},o=r.getColumns?.();o&&(i.fields=o.map(l=>({label:l,value:l})));let c={objectMode:!0};return await new iee(i,c).fromInput(n).toOutput(s).promise(!1),{message:dee,path:e}}throw Tt(new Error,Ar.INVALID_VALUE("format"),gt.BAD_REQUEST)}a(gee,"saveToLocal");async function Ree(e){if(!e.s3||Object.keys(e.s3).length===0)throw Tt(new Error,Ar.MISSING_VALUE("S3 object"),gt.BAD_REQUEST);if(Yr.isEmptyOrZeroLength(e.s3.aws_access_key_id))throw Tt(new Error,Ar.MISSING_VALUE("aws_access_key_id"),gt.BAD_REQUEST);if(Yr.isEmptyOrZeroLength(e.s3.aws_secret_access_key))throw Tt(new Error,Ar.MISSING_VALUE("aws_secret_access_key"),gt.BAD_REQUEST);if(Yr.isEmptyOrZeroLength(e.s3.bucket))throw Tt(new Error,Ar.MISSING_VALUE("bucket"),gt.BAD_REQUEST);if(Yr.isEmptyOrZeroLength(e.s3.key))throw Tt(new Error,Ar.MISSING_VALUE("key"),gt.BAD_REQUEST);if(Yr.isEmptyOrZeroLength(e.s3.region))throw Tt(new Error,Ar.MISSING_VALUE("region"),gt.BAD_REQUEST);let t=vv(e);if(!Yr.isEmpty(t))throw Tt(new Error,t,gt.BAD_REQUEST);Es.trace(`called export_to_s3 to bucket: ${e.s3.bucket} and query ${e.search_operation.sql}`);let r;try{r=await Bv(e)}catch(u){throw Es.error(u),u}let s,n=await nee.getS3AuthObj(e.s3.aws_access_key_id,e.s3.aws_secret_access_key,e.s3.region),i,o=new ju.PassThrough;if(e.format===Uv){i=e.s3.key+".csv";let u=Pv(r,r.getColumns?.());u.on("error",_=>{throw _}),u.pipe(o)}else if(e.format===Mv){i=e.s3.key+".json";let u=new ju.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%fee===0&&(u.push(l),l="")}l.length!==0&&u.push(l),u.push("]"),u.push(null)}else throw Tt(new Error,Ar.INVALID_VALUE("format"),gt.BAD_REQUEST);return new lee({client:n,params:{Bucket:e.s3.bucket,Key:i,Body:o}}).done()}a(Ree,"export_to_s3");function Pv(e,t){let r=ju.Readable.from(e?.[Symbol.iterator]||e?.[Symbol.asyncIterator]?e:[e]),s={};t&&(s.fields=t.map(o=>({label:o,value:o})));let n={objectMode:!0},i=new oee(s,n);return r.pipe(i)}a(Pv,"toCsvStream");function vv(e){if(Es.trace("in exportCoreValidation"),Yr.isEmpty(e.format))return"format missing";if(Dv.indexOf(e.format)<0)return`format invalid. must be one of the following values: ${Dv.join(", ")}`;let t=e.search_operation.operation;if(Yr.isEmpty(t))return"search_operation.operation missing";if(Cv.indexOf(t)<0)return`search_operation.operation must be one of the following values: ${Cv.join(", ")}`}a(vv,"exportCoreValidation");async function Bv(e){Es.trace("in getRecords");let t,r;if(Xu.isEmpty(e.search_operation)||Xu.isEmptyOrZeroLength(e.search_operation.operation))throw Tt(new Error,Ar.INVALID_VALUE("Search operation"),gt.BAD_REQUEST);switch(e.search_operation.operation){case"search_by_value":t=hee;break;case"search_by_hash":t=Eee;break;case"search_by_conditions":t=yg.searchByConditions;break;case"sql":t=mee;break;default:throw r=`Operation ${e.search_operation.operation} is not support by export.`,Es.error(r),Tt(new Error,r,gt.BAD_REQUEST)}return e.search_operation.hdb_user=e.hdb_user,t(e.search_operation)}a(Bv,"getRecords")});var Yv={};Ye(Yv,{contentTypes:()=>Lg,findBestSerializer:()=>vf,getDeserializer:()=>Ro,registerContentHandlers:()=>Mg,serialize:()=>Bf,serializeMessage:()=>Ai});function Aee(e){try{return e?.[0]===123?Dg(e):e}catch{return e}}function Mg(e){e.register(bee,{serializers:[{regex:/^application\/json$/,serializer:Tc},{regex:/^application\/cbor$/,serializer:function(t){return new go.EncoderStream(el).end(t)}},{regex:/^application\/(x-)?msgpack$/,serializer:function(t){return(t?.[Symbol.iterator]||t?.[Symbol.asyncIterator])&&!Array.isArray(t)?Pf.Readable.from((0,ln.encodeIter)(t,el)):(0,ln.pack)(t)}},{regex:/^text\/csv$/,serializer:function(t){return this.header("Content-Disposition",'attachment; filename="data.csv"'),(0,Ig.toCsvStream)(t)}}]}),e.addContentTypeParser("application/x-msgpack",{parseAs:"buffer"},(t,r,s)=>{try{s(null,(0,ln.unpack)(r))}catch(n){n.statusCode=400,s(n)}}),e.addContentTypeParser("application/cbor",{parseAs:"buffer"},(t,r,s)=>{try{s(null,(0,go.decode)(r))}catch(n){n.statusCode=400,s(n)}})}function vf(e){let r=(e.headers.asObject||e.headers).accept,s,n=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=Ht.get(_);if(E){let h=(E.q||1)*d;h>n&&(s=E,i=E.type||_,n=h,o=f)}}if(!s){if(r)return{serializer(){this.code(406).send("No supported content types found in Accept header, supported types include: "+Array.from(Ht.keys()).join(", "))}};s=Ht.get("application/json"),i="application/json"}return{serializer:s,type:i,parameters:o}}function Bf(e,t,r){let s=qv&&t.headers.asObject?.["accept-encoding"]?.includes("br"),n;if(e?.contentType!=null&&e.data!=null)r.headers.set("Content-Type",e.contentType),r.headers.set("Vary","Accept-Encoding"),n=e.data;else if(e instanceof Uint8Array)r.headers.set("Content-Type","application/octet-stream"),r.headers.set("Vary","Accept-Encoding"),n=e;else{let i=vf(t);if(i.serializer.compressible===!1&&(s=!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 s&&(r.headers.set("Content-Encoding","br"),o=o.pipe((0,Bn.createBrotliCompress)({params:{[Bn.constants.BROTLI_PARAM_MODE]:i.type.includes("json")||i.type.includes("text")?Bn.constants.BROTLI_MODE_TEXT:Bn.constants.BROTLI_MODE_GENERIC,[Bn.constants.BROTLI_PARAM_QUALITY]:2}}))),o}n=i.serializer.serialize(e,r)}return s&&n?.length>qv?(r.headers.set("Content-Encoding","br"),new Promise((i,o)=>(0,Bn.brotliCompress)(n,(c,u)=>{c?o(c):i(u)}))):n}function Ai(e,t){if(e?.contentType!=null&&e.data!=null)return e.data;if(!t)return Zu(e);let r=t.serialize;if(r)return r(e);let s=vf(t);return r=t.serialize=s.serializer.serialize,r(e)}function Nee(e){return new Promise((t,r)=>{let s=[];e.on("data",n=>s.push(n)),e.on("end",()=>t(Buffer.concat(s))),e.on("error",r)})}function Ro(e,t){e||(e="");let r=e.indexOf(";"),s;r>-1&&(s=e.slice(r+1),e=e.slice(0,r));let n=Ht.get(e);if(t){if(n?.deserializeStream)return n.deserializeStream;let i=Ht.get(e)?.deserialize||Gv(e,s);return o=>Nee(o).then(i)}return e&&Ht.get(e)?.deserialize||Gv(e,s)}function Gv(e,t){if(e.startsWith("text/")){let r=t?.match(/charset=(.+)/)?.[1]||"utf-8";return s=>({contentType:e,data:s.toString(r)})}else return e==="application/octet-stream"?r=>r:r=>{if(!e)try{if(r?.[0]===123)return Dg(r)}catch{}return{contentType:e||"application/octet-stream",data:r}}}function yee(e,t){return{[Symbol.asyncIterator](){let r=e[Symbol.asyncIterator]?e[Symbol.asyncIterator]():e[Symbol.iterator]();return{next(){let s=r.next();return s.then?s.then(n=>({value:t(n.value),done:n.done})):{value:t(s.value),done:s.done}},return(s){return r.return(s)},throw(s){return r.throw(s)}}}}}var Ig,ln,go,Bn,Pf,Fv,wg,Cg,kv,Vv,Zu,Dg,el,Ht,Lg,xv,$v,Oee,bee,qv,Oa=Re(()=>{Yh();Ig=x(Uf()),ln=require("msgpackr"),go=require("cbor-x"),Bn=require("zlib"),Pf=require("stream");or();Fv=require("../index"),wg=x(ee()),Cg=x(M()),kv=x(require("yaml")),Vv=wg.default.get(Cg.CONFIG_PARAMS.SERIALIZATION_BIGINT)!==!1,Zu=Vv?Hi:JSON.stringify,Dg=Vv?$h:JSON.parse,el={useRecords:!1,useToJSON:!0},Ht=new Map,Lg=Ht;rt.contentTypes=Lg;(0,Fv._assignPackageExport)("contentTypes",Lg);Ht.set("application/json",{serializeStream:Tc,serialize:Zu,deserialize:Dg,q:.8});xv=new go.Encoder(el);Ht.set("application/cbor",{serializeStream(e){return e[Symbol.asyncIterator]&&(e[Symbol.iterator]=null),new go.EncoderStream(el).end(e)},serialize:xv.encode,deserialize:xv.decode,q:1});Ht.set("application/x-msgpack",{serializeStream(e){return(e?.[Symbol.iterator]||e?.[Symbol.asyncIterator])&&!Array.isArray(e)?Pf.Readable.from((0,ln.encodeIter)(e,el)):(0,ln.pack)(e)},serialize:ln.pack,deserialize:ln.unpack,q:.9});Ht.set("text/csv",{serializeStream(e,t){return t.headers.set("Content-Disposition",'attachment; filename="data.csv"'),(0,Ig.toCsvStream)(e,e?.getColumns?.())},q:.1});Ht.set("text/plain",{serialize(e){return e.toString()},deserialize(e){return e.toString()},q:.01});Ht.set("text/yaml",{serialize(e){return kv.stringify(e,{aliasDuplicateObjects:!1})},q:.7});Ht.set("text/event-stream",{serializeStream:function(e){return Pf.Readable.from(yee(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=
|
|
17
|
+
`,""):null}catch(f){f.stderr?i[u].npm_error=rv(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 Ca.info(`finished installModules with response ${i}`),i}a(e7,"installModules");function rv(e){let t='"error": {',r=e.indexOf('"error": {'),n=e.indexOf(`}
|
|
18
|
+
`);return r>-1&&n>-1?JSON.parse(e.substring(r+t.length-1,n+1)):e}a(rv,"parseNPMStdErr");async function t7(e){Ca.info(`starting auditModules for request: ${e}`);let t=sv(e);if(t)throw Ia(t,t.message,wa.BAD_REQUEST);let{projects:r}=e;await If(),await nv(r);let n={};for(let s=0,i=r.length;s<i;s++){let o=r[s],c=Nf.join(Eg,o);n[o]={npm_output:null,npm_error:null};try{let u=await ju("npm audit --json",c);n[o].npm_output=JSON.parse(u)}catch(u){n[o].npm_error=rv(u.stderr)}}return Ca.info(`finished auditModules with response ${n}`),n}a(t7,"auditModules");async function If(){try{return await ju("npm -v"),!0}catch{throw Ia(new Error,"Unable to install project dependencies: npm is not installed on this instance of HarperDB.",wa.BAD_REQUEST,void 0,void 0,!0)}}a(If,"checkNPMInstalled");async function nv(e){if(!Array.isArray(e)||e.length===0)throw Ia(new Error,"projects argument must be an array with at least 1 element",wa.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=Nf.join(Eg,i.toString());if(!await ZP.pathExists(o)){t.push(i);continue}let u=Nf.join(o,"package.json");await ZP.pathExists(u)||r.push(i)}if(t.length>0)throw Ia(new Error,`Unable to install project dependencies: custom function projects '${t.join(",")}' does not exist.`,wa.BAD_REQUEST,void 0,void 0,!0);if(r.length>0)throw Ia(new Error,`Unable to install project dependencies: custom function projects '${r.join(",")}' do not have a package.json file.`,wa.BAD_REQUEST,void 0,void 0,!0)}a(nv,"checkProjectPaths");function sv(e){let t=yf.object({projects:yf.array().min(1).items(yf.string()).required(),dry_run:yf.boolean().default(!1)});return z9.validateBySchema(e,t)}a(sv,"modulesValidator")});var mg=g((Xhe,lv)=>{"use strict";var Da=require("fs-extra"),hg=require("path"),Cf=$(),ov=Q(),Df=L(),uv=ee(),r7=lr();lv.exports=n7;async function n7(){let e=s7(),t=uv.get(Df.CONFIG_PARAMS.ROOTPATH),r=hg.join(t,"package.json"),n={dependencies:{harperdb:"file:"+Df.PACKAGE_ROOT}},s=hg.join(t,"node_modules");await Da.ensureDir(s);let i,o=!0,c=!1;try{i=await Da.readJson(r)}catch(u){if(ov.isEmptyOrZeroLength(e))return;if(u.code!==Df.NODE_ERROR_CODES.ENOENT)throw u;o=!1}if(!ov.isEmptyOrZeroLength(e)){for(let{name:u,package:_}of e){let l=await av(_);n.dependencies[u]=l+_}if(!o){Cf.notify("Installing components"),await cv(r,n,null);return}for(let{name:u,package:_}of e){let l=i.dependencies[u],d=await av(_);if(l===void 0||l!==d+_){c=!0;break}}}for(let u in i.dependencies)n.dependencies[u]===void 0&&(Cf.notify("Removing component",u),c=!0);c&&(Cf.notify("Updating components."),await cv(r,n,i))}a(n7,"installComponents");function s7(){let e=r7.getConfiguration(),t=[];for(let r in e)e[r]?.package&&t.push(Object.assign(e[r],{name:r}));return t}a(s7,"getComponentsConfig");async function av(e){return e.includes(":")?"":e.startsWith("@")||!e.startsWith("@")&&!e.includes("/")?"npm:":hg.extname(e)||await Da.pathExists(e)?"file:":"github:"}a(av,"getPkgPrefix");async function cv(e,t,r){Cf.trace("npm installing components package.json",t),await Da.writeFile(e,JSON.stringify(t,null," "));try{await wf().installAllRootModules(uv.get(Df.CONFIG_PARAMS.IGNORE_SCRIPTS)===!0)}catch(n){throw r?await Da.writeFile(e,JSON.stringify(r,null," ")):await Da.unlink(e),n}}a(cv,"installPackages")});var Tg=g((eme,Ev)=>{"use strict";var Ve=require("fs-extra"),pg=require("fast-glob"),Te=require("path"),dv=require("tar-fs"),Zhe=require("uuid").v4,Sg=require("normalize-path"),as=jP(),Nt=$(),Qe=L(),Tt=ee(),Zu=lr(),i7=Q(),{PACKAGE_ROOT:o7}=L(),{handleHDBError:Bt,hdb_errors:a7}=ne(),{basename:c7}=require("path"),u7=mg(),fv=ee(),l7=L(),{Readable:_7}=require("stream"),{isMainThread:d7}=require("worker_threads"),{HDB_ERROR_MSGS:go,HTTP_STATUS_CODES:Ht}=a7,f7=Te.join(o7,"application-template"),_v=Te.join(Tt.get(Qe.HDB_SETTINGS_NAMES.HDB_ROOT_KEY),"tmp");function E7(){Nt.trace("getting custom api status");let e={};try{e={port:Tt.get(Qe.CONFIG_PARAMS.HTTP_PORT),directory:Tt.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),is_enabled:!0}}catch(t){throw Bt(new Error,go.FUNCTION_STATUS,Ht.INTERNAL_SERVER_ERROR,Nt.ERR,t)}return e}a(E7,"customFunctionsStatus");function h7(){Nt.trace("getting custom api endpoints");let e={},t=Tt.get(Qe.CONFIG_PARAMS.COMPONENTSROOT);try{pg.sync(Sg(`${t}/*`),{onlyDirectories:!0}).forEach(n=>{let s=n.split("/").pop();e[s]={routes:pg.sync(Sg(`${n}/routes/*.js`)).map(i=>i.split("/").pop().split(".js")[0]),helpers:pg.sync(Sg(`${n}/helpers/*.js`)).map(i=>i.split("/").pop().split(".js")[0])}})}catch(r){throw Bt(new Error,go.GET_FUNCTIONS,Ht.INTERNAL_SERVER_ERROR,Nt.ERR,r)}return e}a(h7,"getCustomFunctions");function m7(e){e.project&&(e.project=Te.parse(e.project).name),e.file&&(e.file=Te.parse(e.file).name);let t=as.getDropCustomFunctionValidator(e);if(t)throw Bt(t,t.message,Ht.BAD_REQUEST);Nt.trace("getting custom api endpoint file content");let r=Tt.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),{project:n,type:s,file:i}=e,o=Te.join(r,n,s,i+".js");try{return Ve.readFileSync(o,{encoding:"utf8"})}catch(c){throw Bt(new Error,go.GET_FUNCTION,Ht.INTERNAL_SERVER_ERROR,Nt.ERR,c)}}a(m7,"getCustomFunction");function p7(e){e.project&&(e.project=Te.parse(e.project).name),e.file&&(e.file=Te.parse(e.file).name);let t=as.setCustomFunctionValidator(e);if(t)throw Bt(t,t.message,Ht.BAD_REQUEST);Nt.trace("setting custom function file content");let r=Tt.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),{project:n,type:s,file:i,function_content:o}=e;try{return Ve.outputFileSync(Te.join(r,n,s,i+".js"),o),`Successfully updated custom function: ${i}.js`}catch(c){throw Bt(new Error,go.SET_FUNCTION,Ht.INTERNAL_SERVER_ERROR,Nt.ERR,c)}}a(p7,"setCustomFunction");function S7(e){e.project&&(e.project=Te.parse(e.project).name),e.file&&(e.file=Te.parse(e.file).name);let t=as.getDropCustomFunctionValidator(e);if(t)throw Bt(t,t.message,Ht.BAD_REQUEST);Nt.trace("dropping custom function file");let r=Tt.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),{project:n,type:s,file:i}=e;try{return Ve.unlinkSync(Te.join(r,n,s,i+".js")),`Successfully deleted custom function: ${i}.js`}catch(o){throw Bt(new Error,go.DROP_FUNCTION,Ht.INTERNAL_SERVER_ERROR,Nt.ERR,o)}}a(S7,"dropCustomFunction");function T7(e){e.project&&(e.project=Te.parse(e.project).name);let t=as.addComponentValidator(e);if(t)throw Bt(t,t.message,Ht.BAD_REQUEST);Nt.trace("adding component");let r=Tt.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),{project:n}=e;try{let s=Te.join(r,n);return Ve.mkdirSync(s,{recursive:!0}),Ve.copySync(f7,s),`Successfully added project: ${n}`}catch(s){throw Bt(new Error,go.ADD_FUNCTION,Ht.INTERNAL_SERVER_ERROR,Nt.ERR,s)}}a(T7,"addComponent");function g7(e){e.project&&(e.project=Te.parse(e.project).name);let t=as.dropCustomFunctionProjectValidator(e);if(t)throw Bt(t,t.message,Ht.BAD_REQUEST);Nt.trace("dropping custom function project");let r=Tt.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),{project:n}=e,s=Tt.get(Qe.CONFIG_PARAMS.APPS);if(!i7.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 Zu.updateConfigValue(Qe.CONFIG_PARAMS.APPS,s),`Successfully deleted project: ${n}`}try{let i=Te.join(r,n);return Ve.rmSync(i,{recursive:!0}),`Successfully deleted project: ${n}`}catch(i){throw Bt(new Error,go.DROP_FUNCTION_PROJECT,Ht.INTERNAL_SERVER_ERROR,Nt.ERR,i)}}a(g7,"dropCustomFunctionProject");async function R7(e){e.project&&(e.project=Te.parse(e.project).name);let t=as.packageComponentValidator(e);if(t)throw Bt(t,t.message,Ht.BAD_REQUEST);let r=Tt.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),{project:n}=e;Nt.trace("packaging component",n);let s;try{s=await Ve.realpath(Te.join(r,n))}catch(u){if(u.code!==Qe.NODE_ERROR_CODES.ENOENT)throw u;try{s=await Ve.realpath(Te.join(Tt.get(Qe.CONFIG_PARAMS.ROOTPATH),"node_modules",n))}catch(_){if(_.code===Qe.NODE_ERROR_CODES.ENOENT)throw new Error(`Unable to locate project '${n}'`)}}await Ve.ensureDir(_v);let i=Te.join(_v,`${n}.tar`),o={};(e.skip_node_modules===!0||e.skip_node_modules==="true")&&(o={ignore:u=>u.includes(Te.join(s,"node_modules"))}),dv.pack(s,o).pipe(Ve.createWriteStream(i,{overwrite:!0})),await new Promise(u=>setTimeout(u,2e3));let c=Ve.readFileSync(i,{encoding:"base64"});return await Ve.remove(i),{project:n,payload:c}}a(R7,"packageComponent");async function A7(e){e.project&&(e.project=Te.parse(e.project).name);let t=as.deployComponentValidator(e);if(t)throw Bt(t,t.message,Ht.BAD_REQUEST);let r=Tt.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),{project:n,payload:s,package:i}=e;if(Nt.trace("deploying component",n),!s&&!i)throw new Error("'payload' or 'package' must be provided");let o;if(s){o=Te.join(r,n),i="file:"+o,await Ve.ensureDir(o);let f=_7.from(Buffer.from(s,"base64"));await new Promise((h,p)=>{f.pipe(dv.extract(o,{finish:h})).on("error",p)});let E=await Ve.readdir(o);E.length===1&&E[0]==="package"&&(await Ve.copy(Te.join(o,"package"),o),await Ve.remove(Te.join(o,"package")))}if(await Zu.addConfig(n,{package:i}),!s){await u7();let f=fv.get(l7.CONFIG_PARAMS.ROOTPATH);o=Te.join(f,"node_modules",n)}if(d7)return;let c=new Map;c.isWorker=!0;let u=(Mf(),ie(Lf)),_;u.setErrorReporter(f=>_=f);let l=c7(o),d=u.component_errors.get(l);try{await u.loadComponent(o,c)}finally{u.component_errors.set(l,d)}if(_)throw _;return Nt.info("Installed component"),`Successfully deployed: ${n}`}a(A7,"deployComponent");async function O7(){let e=Zu.getConfiguration(),t=[];for(let o in e)if(e[o]?.package){if(e[o].package.startsWith("file:"))continue;t.push(Object.assign({},e[o],{name:o}))}let r=a(async(o,c)=>{try{let u=await Ve.readdir(o,{withFileTypes:!0});for(let _ of u){let l=_.name;if(l.startsWith(".")||l==="node_modules")continue;let d=Te.join(o,l);if(_.isDirectory()||_.isSymbolicLink()){let f={name:l,entries:[]};c.entries.push(f),await r(d,f)}else{let f=await Ve.stat(d),E={name:Te.basename(l),mtime:f.mtime,size:f.size};c.entries.push(E)}}return c}catch(u){return Nt.warn("Error loading package",u),{error:u.toString(),entries:[]}}},"walk_dir"),n=await r(Tt.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),{name:Tt.get(Qe.CONFIG_PARAMS.COMPONENTSROOT).split(Te.sep).slice(-1).pop(),entries:t});for(let o of n.entries)if(o.package){let c=await r(Te.join(Tt.get(Qe.CONFIG_PARAMS.ROOTPATH),"node_modules",o.name),{name:o.name,entries:[]});Object.assign(o,c)}let i=(Mf(),ie(Lf)).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(O7,"getComponents");async function b7(e){let t=as.getComponentFileValidator(e);if(t)throw Bt(t,t.message,Ht.BAD_REQUEST);let n=Zu.getConfigObj()[e.project]||e.project==="harperdb"?Te.join(fv.get(Qe.CONFIG_PARAMS.ROOTPATH),"node_modules"):Tt.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),s=e.encoding?{encoding:e.encoding}:{encoding:"utf8"};try{let i=await Ve.stat(Te.join(n,e.project,e.file));return{message:await Ve.readFile(Te.join(n,e.project,e.file),s),size:i.size,birthtime:i.birthtime,mtime:i.mtime}}catch(i){throw i.code===Qe.NODE_ERROR_CODES.ENOENT?new Error(`Component file not found '${Te.join(e.project,e.file)}'`):i}}a(b7,"getComponentFile");async function y7(e){let t=as.setComponentFileValidator(e);if(t)throw Bt(t,t.message,Ht.BAD_REQUEST);let r=e.encoding?{encoding:e.encoding}:{encoding:"utf8"},n=Te.join(Tt.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),e.project,e.file);return e.payload!==void 0?(await Ve.ensureFile(n),await Ve.outputFile(n,e.payload,r)):await Ve.ensureDir(n),"Successfully set component: "+e.file}a(y7,"setComponentFile");async function N7(e){let t=as.dropComponentFileValidator(e);if(t)throw Bt(t,t.message,Ht.BAD_REQUEST);let r=e.file?Te.join(e.project,e.file):e.project,n=Te.join(Tt.get(Qe.CONFIG_PARAMS.COMPONENTSROOT),r);return await Ve.pathExists(n)&&await Ve.remove(n),Zu.deleteConfigFromFile([e.project]),"Successfully dropped: "+r}a(N7,"dropComponent");Ev.exports={customFunctionsStatus:E7,getCustomFunctions:h7,getCustomFunction:m7,setCustomFunction:p7,dropCustomFunction:S7,addComponent:T7,dropCustomFunctionProject:g7,packageComponent:R7,deployComponent:A7,getComponents:O7,getComponentFile:b7,setComponentFile:y7,dropComponent:N7}});var gg=g((rme,mv)=>{"use strict";var cs=require("joi"),hv=Xe();mv.exports={readTransactionLogValidator:I7,deleteTransactionLogsBeforeValidator:w7};function I7(e){let t=cs.object({schema:cs.string().required(),table:cs.string().required(),from:cs.date().timestamp(),to:cs.date().timestamp(),limit:cs.number().min(1)});return hv.validateBySchema(e,t)}a(I7,"readTransactionLogValidator");function w7(e){let t=cs.object({schema:cs.string().required(),table:cs.string().required(),timestamp:cs.date().timestamp().required()});return hv.validateBySchema(e,t)}a(w7,"deleteTransactionLogsBeforeValidator")});var Pf=g((sme,Rv)=>{"use strict";var Rg=L(),Uf=it(),pv=Q(),Sv=ee(),Tv=Rs(),{handleHDBError:La,hdb_errors:C7}=ne(),{HTTP_STATUS_CODES:Ma}=C7,{readTransactionLogValidator:D7,deleteTransactionLogsBeforeValidator:L7}=gg(),gv="This operation relies on clustering and cannot run with it disable.",M7="Logs successfully deleted from transaction log.",U7="All logs successfully deleted from transaction log.";Rv.exports={readTransactionLog:P7,deleteTransactionLogsBefore:v7};async function*P7(e){let t=D7(e);if(t)throw La(t,t.message,Ma.BAD_REQUEST,void 0,void 0,!0);if(!Sv.get(Rg.CONFIG_PARAMS.CLUSTERING_ENABLED))throw La(new Error,gv,Ma.NOT_FOUND,void 0,void 0,!0);let{schema:r,table:n}=e,s=pv.checkSchemaTableExist(r,n);if(s)throw La(new Error,s,Ma.NOT_FOUND,void 0,void 0,!0);let i=Tv.createNatsTableStreamName(r,n),o=await Uf.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===Rg.OPERATIONS_ENUM.DELETE&&(_.hash_values=c?.entry?.hash_values),yield _}}a(P7,"readTransactionLog");async function v7(e){let t=L7(e);if(t)throw La(t,t.message,Ma.BAD_REQUEST,void 0,void 0,!0);if(!Sv.get(Rg.CONFIG_PARAMS.CLUSTERING_ENABLED))throw La(new Error,gv,Ma.NOT_FOUND,void 0,void 0,!0);let{schema:r,table:n,timestamp:s}=e,i=pv.checkSchemaTableExist(r,n);if(i)throw La(new Error,i,Ma.NOT_FOUND,void 0,void 0,!0);let o=Tv.createNatsTableStreamName(r,n),{jsm:c}=await Uf.getNATSReferences(),u=await Uf.getStreamInfo(o),_=new Date(u.state.first_ts).getTime();if(s<=_)return`No transactions exist before: ${s}`;let l=M7,d,f=new Date(u.state.last_ts).getTime();return s>f?(d=u.state.last_seq+1,l=U7):d=(await Uf.viewStream(o,parseInt(s),1))[0].nats_sequence,await c.streams.purge(o,{seq:d}),l}a(v7,"deleteTransactionLogsBefore")});var Ov=g((ome,Av)=>{"use strict";var Ag=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}};Av.exports=Ag});var yv=g((cme,bv)=>{"use strict";var Og=class{static{a(this,"PermissionAttributeResponseObject")}constructor(t,r=[]){this.attribute_name=t,this.required_permissions=r}};bv.exports=Og});var yg=g((lme,Iv)=>{"use strict";var Nv=Ov(),B7=yv(),{HDB_ERROR_MSGS:H7}=Cr(),bg=class{static{a(this,"PermissionResponseObject")}constructor(){this.error=H7.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 Nv(t,r,n),i=`${t}_${r}`;this.unauthorized_access[i]=s}addUnauthorizedAttributes(t,r,n,s){let i=[];t.forEach(c=>{let u=new B7(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 Nv(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}};Iv.exports=bg});var xf=g((dme,Vv)=>{"use strict";var Ng=vr(),vf=Pr(),En=Su(),rl=As(),Ig=ii(),x7=qS(),G7=wL(),nl=an(),Bf=zS(),It=$(),q7=jS(),F7=zd(),k7=DT(),V7=Xd(),$7=MT(),Y7=UT(),K7=BT(),W7=xT(),wg=FT(),vs=Q(),Q7=IU(),Cg=KT(),Dv=Tf(),fn=L(),Lv=vP(),z7=pa(),Mv=bu(),Uv=(Of(),ie(Qu)),Pv=lr(),Yr=Tg(),J7=require("alasql"),vv=Pf(),Bv=wf(),Hv=yg(),{handleHDBError:Or,hdb_errors:xv}=ne(),{HDB_ERROR_MSGS:$t,HTTP_STATUS_CODES:el}=xv,V=new Map,Gv="delete",yi="insert",Bs="read",Ro="update",tl="describe",wv=rl.describeSchema.name,Cv=rl.describeTable.name,qv={delete:!0,deleteRecord:!0,update:!0,updateData:!0,dropAttribute:!0,dropTable:!0,dropSchema:!0,upsert:!0,upsertData:!0},X7="catchup",j7="handleGetJob",Z7="handleGetJobsByStartDate",Hf={CSV_DATA_LOAD:"csvDataLoad",CSV_URL_LOAD:"csvURLLoad",CSV_FILE_LOAD:"csvFileLoad",IMPORT_FROM_S3:"importFromS3"},eee=[En.createTable.name,En.createAttribute.name,En.dropTable.name,En.dropAttribute.name],Fv={EXPORT_TO_S3:"export_to_s3",EXPORT_LOCAL:"export_local"},W=class{static{a(this,"permission")}constructor(t,r){this.requires_su=t,this.perms=r}};V.set(Ng.insert.name,new W(!1,[yi]));V.set(Ng.update.name,new W(!1,[Ro]));V.set(Ng.upsert.name,new W(!1,[yi,Ro]));V.set(vf.searchByConditions.name,new W(!1,[Bs]));V.set(vf.searchByHash.name,new W(!1,[Bs]));V.set(vf.searchByValue.name,new W(!1,[Bs]));V.set(vf.search.name,new W(!1,[Bs]));V.set(En.createSchema.name,new W(!0,[]));V.set(En.createTable.name,new W(!0,[]));V.set(En.createAttribute.name,new W(!1,[yi]));V.set(En.dropSchema.name,new W(!0,[]));V.set(En.dropTable.name,new W(!0,[]));V.set(En.dropAttribute.name,new W(!0,[]));V.set(rl.describeSchema.name,new W(!1,[Bs]));V.set(rl.describeTable.name,new W(!1,[Bs]));V.set(Ig.deleteRecord.name,new W(!1,[Gv]));V.set(nl.addUser.name,new W(!0,[]));V.set(nl.alterUser.name,new W(!0,[]));V.set(nl.dropUser.name,new W(!0,[]));V.set(nl.listUsersExternal.name,new W(!0,[]));V.set(Bf.listRoles.name,new W(!0,[]));V.set(Bf.addRole.name,new W(!0,[]));V.set(Bf.alterRole.name,new W(!0,[]));V.set(Bf.dropRole.name,new W(!0,[]));V.set(q7.name,new W(!0,[]));V.set(F7.name,new W(!0,[]));V.set(k7.name,new W(!0,[]));V.set(V7.name,new W(!0,[]));V.set($7.name,new W(!0,[]));V.set(Y7.name,new W(!0,[]));V.set(wg.setRoutes.name,new W(!0,[]));V.set(wg.getRoutes.name,new W(!0,[]));V.set(wg.deleteRoutes.name,new W(!0,[]));V.set(Pv.setConfiguration.name,new W(!0,[]));V.set(K7.clusterStatus.name,new W(!0,[]));V.set(W7.name,new W(!0,[]));V.set(Cg.getFingerprint.name,new W(!0,[]));V.set(Cg.setLicense.name,new W(!0,[]));V.set(Ig.deleteFilesBefore.name,new W(!0,[]));V.set(Ig.deleteAuditLogsBefore.name,new W(!0,[]));V.set(Dv.restart.name,new W(!0,[]));V.set(Dv.restartService.name,new W(!0,[]));V.set(x7.name,new W(!0,[]));V.set(G7.name,new W(!0,[Bs]));V.set(z7.systemInformation.name,new W(!0,[]));V.set(Pv.getConfiguration.name,new W(!0,[]));V.set(vv.readTransactionLog.name,new W(!0,[]));V.set(vv.deleteTransactionLogsBefore.name,new W(!0,[]));V.set(Bv.installModules.name,new W(!0,[]));V.set(Bv.auditModules.name,new W(!0,[]));V.set(Mv.createTokens.name,new W(!1,[]));V.set(Mv.refreshOperationToken.name,new W(!1,[]));V.set(Uv.login.name,new W(!1,[]));V.set(Uv.logout.name,new W(!1,[]));V.set(Yr.customFunctionsStatus.name,new W(!0,[]));V.set(Yr.getCustomFunctions.name,new W(!0,[]));V.set(Yr.getComponents.name,new W(!0,[]));V.set(Yr.getComponentFile.name,new W(!0,[]));V.set(Yr.setComponentFile.name,new W(!0,[]));V.set(Yr.dropComponent.name,new W(!0,[]));V.set(Yr.getCustomFunction.name,new W(!0,[]));V.set(Yr.setCustomFunction.name,new W(!0,[]));V.set(Yr.dropCustomFunction.name,new W(!0,[]));V.set(Yr.addComponent.name,new W(!0,[]));V.set(Yr.dropCustomFunctionProject.name,new W(!0,[]));V.set(Yr.packageComponent.name,new W(!0,[]));V.set(Yr.deployComponent.name,new W(!0,[]));V.set(Cg.getRegistrationInfo.name,new W(!1,[]));V.set(nl.userInfo.name,new W(!1,[]));V.set(rl.describeAll.name,new W(!1,[]));V.set(j7,new W(!1,[]));V.set(Z7,new W(!0,[]));V.set(X7,new W(!0,[]));V.set(Hf.CSV_DATA_LOAD,new W(!1,[yi,Ro]));V.set(Hf.CSV_URL_LOAD,new W(!1,[yi,Ro]));V.set(Hf.CSV_FILE_LOAD,new W(!1,[yi,Ro]));V.set(Hf.IMPORT_FROM_S3,new W(!1,[yi,Ro]));V.set(Fv.EXPORT_TO_S3,new W(!0,[]));V.set(Fv.EXPORT_LOCAL,new W(!0,[]));V.set(fn.VALID_SQL_OPS_ENUM.DELETE,new W(!1,[Gv]));V.set(fn.VALID_SQL_OPS_ENUM.SELECT,new W(!1,[Bs]));V.set(fn.VALID_SQL_OPS_ENUM.INSERT,new W(!1,[yi]));V.set(fn.VALID_SQL_OPS_ENUM.UPDATE,new W(!1,[Ro]));Vv.exports={verifyPerms:ree,verifyPermsAst:tee,verifyBulkLoadAttributePerms:see};function tee(e,t,r){if(vs.isEmptyOrZeroLength(e))throw It.info("verify_perms_ast has an empty user parameter"),Or(new Error);if(vs.isEmptyOrZeroLength(t))throw It.info("verify_perms_ast has an empty user parameter"),Or(new Error);if(vs.isEmptyOrZeroLength(r))throw It.info("verify_perms_ast has a null operation parameter"),Or(new Error);try{let n=new Hv,s=new Q7(e),i=s.getSchemas(),o=new Map;if((!i||i.length===0)&&s.affected_attributes&&s.affected_attributes.size>0)throw It.info("No schemas defined in verifyPermsAst(), will not continue."),Or(new Error);let c=!!t.role.permission.super_user,u=i.includes("system");if(u&&qv[r])throw Or(new Error,$t.DROP_SYSTEM,el.FORBIDDEN);if(c&&!u)return null;let _=Lv.getRolePermissions(t.role);t.role.permission=_,!c&&e instanceof J7.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=kv(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=Lg(t.role.permission,f,d[E]);Dg(h,p,r,d[E],f,n)}}),n.getPermsResponse())}catch(n){throw Or(n)}}a(tee,"verifyPermsAst");function ree(e,t){if(e===null||t===null||e.hdb_user===void 0||e.hdb_user===null)throw It.info("null required parameter in verifyPerms"),Or(new Error,$t.DEFAULT_INVALID_REQUEST,el.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 Hv;if(vs.isEmptyOrZeroLength(e.hdb_user.role)||vs.isEmptyOrZeroLength(e.hdb_user.role.permission))return It.info(`User ${e.hdb_user.username} has no role or permissions. Please assign the user a valid role.`),c.handleUnauthorizedItem($t.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(fn.SYSTEM_SCHEMA_NAME)||s===fn.SYSTEM_SCHEMA_NAME;if(l&&qv[r])throw Or(new Error,$t.DROP_SYSTEM,el.FORBIDDEN);if(u&&!l||_===!0&&(r===En.createSchema.name||r===En.dropSchema.name))return null;if(eee.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=Lv.getRolePermissions(e.hdb_user.role);if(e.hdb_user.role.permission=d,r===wv||r===Cv){if(s===fn.SYSTEM_SCHEMA_NAME)return c.handleUnauthorizedItem($t.SCHEMA_PERM_ERROR(s));if(!d.super_user){if(r===wv&&(!d[s]||!d[s][tl]))return c.handleInvalidItem($t.SCHEMA_NOT_FOUND(s));if(r===Cv&&(!d[s]||!d[s].tables[i]||!d[s].tables[i][tl]))return c.handleInvalidItem($t.TABLE_NOT_FOUND(s,i))}}let f=kv(e.hdb_user,r,o,c,n);if(f)return f;if(V.get(r)&&V.get(r).perms.length===0)return null;if(!u&&e.get_attributes&&fn.SEARCH_WILDCARDS.includes(e.get_attributes[0])){let p=[],S=d[s].tables[i];S[fn.PERMS_CRUD_ENUM.READ]&&(S.attribute_permissions.length>0?S.attribute_permissions.filter(A=>A[fn.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=nee(e),h=Lg(e.hdb_user.role.permission,s,i);return Dg(E,h,r,i,s,c,n),c.getPermsResponse()}a(ree,"verifyPerms");function kv(e,t,r,n,s){if(vs.arrayHasEmptyValues([e,t,r]))throw It.info("hasPermissions has an invalid parameter"),Or(new Error);let i=r.has("system"),o=e.role.permission;if(o.super_user&&(!i||V.get(t).requires_su))return null;if(!V.get(t))throw It.info(`operation ${t} not found.`),Or(new Error,$t.OP_NOT_FOUND(t),el.BAD_REQUEST);if(V.get(t)&&V.get(t).requires_su)return It.info(`operation ${t} requires SU permissions.`),n.handleUnauthorizedItem($t.OP_IS_SU_ONLY(t));let c=r.keys();for(let u of c){try{if(u&&!o[u]||o[u][tl]===!1){n.addInvalidItem($t.SCHEMA_NOT_FOUND(u));continue}}catch{n.addInvalidItem($t.SCHEMA_NOT_FOUND(u));continue}let _=r.get(u);for(let l of _){let d=o[u].tables[l];if(!d||d[tl]===!1)n.addInvalidItem($t.TABLE_NOT_FOUND(u,l));else try{let f=[],E=V.get(t).perms;!vs.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)&&(It.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=$t.UNKNOWN_OP_AUTH_ERROR(t,u,l);throw It.error(E),It.error(f),Or(xv.CHECK_LOGS_WRAPPER(E))}}}return r.size<2?n.getPermsResponse():null}a(kv,"hasPermissions");function Dg(e,t,r,n,s,i,o){if(!e||!t)throw It.info("no attributes specified in checkAttributePerms."),Or(new Error);let c=V.get(r).perms;if(!c||c==="")throw It.info(`no permissions found for ${r} in checkAttributePerms().`),Or(new Error);if(vs.isEmptyOrZeroLength(t))return It.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[tl]===!1){i.addInvalidItem($t.ATTR_NOT_FOUND(s,n,l),s,n);continue}if(c)for(let f of c){if(fn.TIME_STAMP_NAMES.includes(d.attribute_name)&&f!==Bs)throw Or(new Error,$t.SYSTEM_TIMESTAMP_PERMS_ERR,el.FORBIDDEN);d[f]===!1&&(u[d.attribute_name]?u[d.attribute_name].push(f):u[d.attribute_name]=[f])}}else i.addInvalidItem($t.ATTR_NOT_FOUND(s,n,l),s,n)}let _=Object.keys(u);_.length>0&&i.addUnauthorizedAttributes(_,s,n,u)}a(Dg,"checkAttributePerms");function nee(e){let t=new Set;try{if(e.action)return t;if(e.operation===fn.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){It.info(r)}return t}a(nee,"getRecordAttributes");function Lg(e,t,r){let n=new Map;if(vs.isEmpty(e))return It.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{It.info(`No attribute permissions found for schema ${t} and table ${r}.`)}return n}a(Lg,"getAttributePermissions");function see(e,t,r,n,s,i,o){let c=new Set(i),u=Lg(e,n,s);Dg(c,u,t,s,n,o,r)}a(see,"verifyBulkLoadAttributePerms")});var qf=g((Eme,Qv)=>{"use strict";Qv.exports={evaluateSQL:pee,processAST:Wv,convertSQLToAST:Kv,checkASTPermissions:Yv};var iee=vr(),$v=require("util"),oee=$v.callbackify(iee.insert),aee=Pr().search,cee=ED().update,uee=$v.callbackify(cee),lee=mD().convertDelete,Ni=require("alasql"),_ee=xf(),Gf=$(),dee=fd(),fee=Q(),sl=L(),{hdb_errors:Eee,handleHDBError:Mg}=ne(),{HTTP_STATUS_CODES:Ug}=Eee;dee(Ni);var hee=403,mee="There was a problem performing this insert. Please check the logs and try again.",Pg=class{static{a(this,"ParsedSQLObject")}constructor(){this.ast=void 0,this.variant=void 0,this.permissions_checked=!1}};function pee(e,t){let r=e.parsed_sql_object;if(!r){r=Kv(e.sql);let n,s=r.ast.statements[0];if(s instanceof Ni.yy.Insert?n=s.into.databaseid:s instanceof Ni.yy.Select?n=s.from?s.from[0].databaseid:null:s instanceof Ni.yy.Update||s instanceof Ni.yy.Delete?n=s.table.databaseid:Gf.error("AST in evaluateSQL is not a valid SQL type."),!(s instanceof Ni.yy.Select)&&fee.isEmptyOrZeroLength(n))return t("No schema specified",null)}Wv(e,r,(n,s)=>{if(n)return t(n);t(null,s)})}a(pee,"evaluateSQL");function Yv(e,t){let r;try{r=_ee.verifyPermsAst(t.ast.statements[0],e.hdb_user,t.variant),t.permissions_checked=!0}catch(n){throw n}return r||null}a(Yv,"checkASTPermissions");function Kv(e){let t=new Pg;if(!e)throw Mg(new Error,"The 'sql' parameter is missing from the request body",Ug.BAD_REQUEST);try{let r=e.trim(),n=Ni.parse(r),s=r.split(" ")[0].toLowerCase();t.ast=n,t.variant=s}catch(r){let n=r.message.split(`
|
|
19
|
+
`);throw n[1]?Mg(r,`Invalid SQL at: ${n[1]}. Please ensure your SQL is valid. Try adding backticks to reserved words and schema table references.`,Ug.BAD_REQUEST):Mg(r,"We had trouble parsing your request. Please ensure your SQL is valid. Try adding backticks to reserved words and schema table references.",Ug.BAD_REQUEST)}return t}a(Kv,"convertSQLToAST");function Wv(e,t,r){try{let n=See;if(!e.bypass_auth&&!t.permissions_checked){let i=Yv(e,t);if(i&&i.length>0)return r(hee,i)}let s={statement:t.ast.statements[0],hdb_user:e.hdb_user};switch(t.variant){case sl.VALID_SQL_OPS_ENUM.SELECT:n=aee,s=t.ast.statements[0];break;case sl.VALID_SQL_OPS_ENUM.INSERT:n=Tee;break;case sl.VALID_SQL_OPS_ENUM.UPDATE:n=uee;break;case sl.VALID_SQL_OPS_ENUM.DELETE:n=lee;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(Wv,"processAST");function See(e,t){Gf.info(e),t("unknown sql statement")}a(See,"nullFunction");function Tee({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=gee(i,e.values)}catch(o){return r(o)}oee(s,(o,c)=>{if(o)return r(o);try{delete c.new_attributes,delete c.txn_time}catch(u){Gf.error(`Error delete new_attributes from insert response: ${u}`)}r(null,c)})}a(Tee,"convertInsert");function gee(e,t){try{return t.map(r=>{if(e.length!==r.length)throw"number of values do not match number of columns in insert";let n={};return r.forEach((s,i)=>{if(s.columnid)throw"cannot use a column in insert value";"value"in s?n[e[i]]=s.value:n[e[i]]=Ni.compile(`SELECT ${s.toString()} AS [${sl.FUNC_VAL}] FROM ?`)}),n})}catch(r){throw Gf.error(r),new Error(mee)}}a(gee,"createDataObjects")});var vg=g((mme,Jv)=>{"use strict";var{S3:Ree,GetObjectCommand:Aee}=require("@aws-sdk/client-s3");Jv.exports={getFileStreamFromS3:Oee,getS3AuthObj:zv};async function Oee(e){let{s3:t}=e,r={Bucket:t.bucket,Key:t.key};return(await zv(t.aws_access_key_id,t.aws_secret_access_key,t.region).send(new Aee(r))).Body}a(Oee,"getFileStreamFromS3");function zv(e,t,r){return new Ree({credentials:{accessKeyId:e,secretAccessKey:t},region:r})}a(zv,"getS3AuthObj")});var Ff=g((Sme,i0)=>{"use strict";var Hg=Pr(),bee=qf(),yee=vg(),{AsyncParser:Nee,Transform:Iee}=require("json2csv"),ol=require("stream"),Kr=Q(),Bg=require("fs-extra"),wee=require("path"),hn=$(),{promisify:Zv}=require("util"),il=Q(),{handleHDBError:gt,hdb_errors:Cee}=ne(),{HDB_ERROR_MSGS:br,HTTP_STATUS_CODES:Rt}=Cee,{streamAsJSON:Dee}=(em(),ie(Db)),{Upload:Lee}=require("@aws-sdk/lib-storage"),Xv=["search_by_value","search_by_hash","sql","search_by_conditions"],jv=["json","csv"],e0="json",t0="csv",Mee="Successfully exported JSON locally.",Uee="Successfully exported CSV locally.",Pee=1e3,vee=Hg.searchByHash,Bee=Hg.searchByValue,Hee=Zv(bee.evaluateSQL),xee=Zv(ol.finished);i0.exports={export_to_s3:kee,export_local:Gee,toCsvStream:r0};async function Gee(e){hn.trace(`export_local request to path: ${e.path}, filename: ${e.filename}, format: ${e.format}`);let t=n0(e);if(!Kr.isEmpty(t))throw hn.error(t),gt(new Error,t,Rt.BAD_REQUEST,void 0,void 0,!0);if(Kr.isEmpty(e.path))throw hn.error(br.MISSING_VALUE("path")),gt(new Error,br.MISSING_VALUE("path"),Rt.BAD_REQUEST,void 0,void 0,!0);let r=(Kr.isEmpty(e.filename)?new Date().getTime():e.filename)+"."+e.format;e.path.endsWith(wee.sep)&&(e.path=e.path.substring(0,e.path.length-1));let n=Kr.buildFolderPath(e.path,r);await qee(e.path);let s=await s0(e);return await Fee(n,e.format,s)}a(Gee,"export_local");async function qee(e){if(hn.trace("in confirmPath"),Kr.isEmptyOrZeroLength(e))throw gt(new Error,`Invalid path: ${e}`,Rt.BAD_REQUEST,void 0,void 0,!0);let t;try{t=await Bg.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,hn.error(n),gt(new Error,n,Rt.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 hn.error(r),gt(new Error,r,Rt.BAD_REQUEST,void 0,void 0,!0)}return!0}a(qee,"confirmPath");async function Fee(e,t,r){if(hn.trace("in saveToLocal"),il.isEmptyOrZeroLength(e))throw gt(new Error,br.INVALID_VALUE("file_path"),Rt.BAD_REQUEST,void 0,void 0,!0);if(il.isEmptyOrZeroLength(t))throw gt(new Error,br.INVALID_VALUE("Source format"),Rt.BAD_REQUEST,void 0,void 0,!0);if(il.isEmpty(r))throw gt(new Error,br.NOT_FOUND("Data"),Rt.BAD_REQUEST,void 0,void 0,!0);if(t===e0){let n=Bg.createWriteStream(e);return Dee(r).pipe(n),await xee(n),{message:Mee,path:e}}else if(t===t0){let n=Bg.createWriteStream(e),s=ol.Readable.from(r),i={},o=r.getColumns?.();o&&(i.fields=o.map(l=>({label:l,value:l})));let c={objectMode:!0};return await new Nee(i,c).fromInput(s).toOutput(n).promise(!1),{message:Uee,path:e}}throw gt(new Error,br.INVALID_VALUE("format"),Rt.BAD_REQUEST)}a(Fee,"saveToLocal");async function kee(e){if(!e.s3||Object.keys(e.s3).length===0)throw gt(new Error,br.MISSING_VALUE("S3 object"),Rt.BAD_REQUEST);if(Kr.isEmptyOrZeroLength(e.s3.aws_access_key_id))throw gt(new Error,br.MISSING_VALUE("aws_access_key_id"),Rt.BAD_REQUEST);if(Kr.isEmptyOrZeroLength(e.s3.aws_secret_access_key))throw gt(new Error,br.MISSING_VALUE("aws_secret_access_key"),Rt.BAD_REQUEST);if(Kr.isEmptyOrZeroLength(e.s3.bucket))throw gt(new Error,br.MISSING_VALUE("bucket"),Rt.BAD_REQUEST);if(Kr.isEmptyOrZeroLength(e.s3.key))throw gt(new Error,br.MISSING_VALUE("key"),Rt.BAD_REQUEST);if(Kr.isEmptyOrZeroLength(e.s3.region))throw gt(new Error,br.MISSING_VALUE("region"),Rt.BAD_REQUEST);let t=n0(e);if(!Kr.isEmpty(t))throw gt(new Error,t,Rt.BAD_REQUEST);hn.trace(`called export_to_s3 to bucket: ${e.s3.bucket} and query ${e.search_operation.sql}`);let r;try{r=await s0(e)}catch(u){throw hn.error(u),u}let n,s=await yee.getS3AuthObj(e.s3.aws_access_key_id,e.s3.aws_secret_access_key,e.s3.region),i,o=new ol.PassThrough;if(e.format===t0){i=e.s3.key+".csv";let u=r0(r,r.getColumns?.());u.on("error",_=>{throw _}),u.pipe(o)}else if(e.format===e0){i=e.s3.key+".json";let u=new ol.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%Pee===0&&(u.push(l),l="")}l.length!==0&&u.push(l),u.push("]"),u.push(null)}else throw gt(new Error,br.INVALID_VALUE("format"),Rt.BAD_REQUEST);return new Lee({client:s,params:{Bucket:e.s3.bucket,Key:i,Body:o}}).done()}a(kee,"export_to_s3");function r0(e,t){let r=ol.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 Iee(n,s);return r.pipe(i)}a(r0,"toCsvStream");function n0(e){if(hn.trace("in exportCoreValidation"),Kr.isEmpty(e.format))return"format missing";if(jv.indexOf(e.format)<0)return`format invalid. must be one of the following values: ${jv.join(", ")}`;let t=e.search_operation.operation;if(Kr.isEmpty(t))return"search_operation.operation missing";if(Xv.indexOf(t)<0)return`search_operation.operation must be one of the following values: ${Xv.join(", ")}`}a(n0,"exportCoreValidation");async function s0(e){hn.trace("in getRecords");let t,r;if(il.isEmpty(e.search_operation)||il.isEmptyOrZeroLength(e.search_operation.operation))throw gt(new Error,br.INVALID_VALUE("Search operation"),Rt.BAD_REQUEST);switch(e.search_operation.operation){case"search_by_value":t=Bee;break;case"search_by_hash":t=vee;break;case"search_by_conditions":t=Hg.searchByConditions;break;case"sql":t=Hee;break;default:throw r=`Operation ${e.search_operation.operation} is not support by export.`,hn.error(r),gt(new Error,r,Rt.BAD_REQUEST)}return e.search_operation.hdb_user=e.hdb_user,t(e.search_operation)}a(s0,"getRecords")});var f0={};qe(f0,{contentTypes:()=>kg,findBestSerializer:()=>Vf,getDeserializer:()=>Oo,registerContentHandlers:()=>Vg,serialize:()=>$f,serializeMessage:()=>bi});function Vee(e){try{return e?.[0]===123?Fg(e):e}catch{return e}}function Vg(e){e.register(Yee,{serializers:[{regex:/^application\/json$/,serializer:Ac},{regex:/^application\/cbor$/,serializer:function(t){return new Ao.EncoderStream(cl).end(t)}},{regex:/^application\/(x-)?msgpack$/,serializer:function(t){return(t?.[Symbol.iterator]||t?.[Symbol.asyncIterator])&&!Array.isArray(t)?kf.Readable.from((0,us.encodeIter)(t,cl)):(0,us.pack)(t)}},{regex:/^text\/csv$/,serializer:function(t){return this.header("Content-Disposition",'attachment; filename="data.csv"'),(0,xg.toCsvStream)(t)}}]}),e.addContentTypeParser("application/x-msgpack",{parseAs:"buffer"},(t,r,n)=>{try{n(null,(0,us.unpack)(r))}catch(s){s.statusCode=400,n(s)}}),e.addContentTypeParser("application/cbor",{parseAs:"buffer"},(t,r,n)=>{try{n(null,(0,Ao.decode)(r))}catch(s){s.statusCode=400,n(s)}})}function Vf(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=xt.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(xt.keys()).join(", "))}};n=xt.get("application/json"),i="application/json"}return{serializer:n,type:i,parameters:o}}function $f(e,t,r){let n=a0&&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=Vf(t);if(i.serializer.compressible===!1&&(n=!1),r.headers.set("Vary","Accept, Accept-Encoding"),r.headers.set("Content-Type",i.type),typeof e=="object"&&(e[Symbol.iterator]||e[Symbol.asyncIterator])&&i.serializer.serializeStream){let o=i.serializer.serializeStream(e,r);return n&&(r.headers.set("Content-Encoding","br"),o=o.pipe((0,Hs.createBrotliCompress)({params:{[Hs.constants.BROTLI_PARAM_MODE]:i.type.includes("json")||i.type.includes("text")?Hs.constants.BROTLI_MODE_TEXT:Hs.constants.BROTLI_MODE_GENERIC,[Hs.constants.BROTLI_PARAM_QUALITY]:2}}))),o}s=i.serializer.serialize(e,r)}return n&&s?.length>a0?(r.headers.set("Content-Encoding","br"),new Promise((i,o)=>(0,Hs.brotliCompress)(s,(c,u)=>{c?o(c):i(u)}))):s}function bi(e,t){if(e?.contentType!=null&&e.data!=null)return e.data;if(!t)return al(e);let r=t.serialize;if(r)return r(e);let n=Vf(t);return r=t.serialize=n.serializer.serialize,r(e)}function Kee(e){return new Promise((t,r)=>{let n=[];e.on("data",s=>n.push(s)),e.on("end",()=>t(Buffer.concat(n))),e.on("error",r)})}function Oo(e,t){e||(e="");let r=e.indexOf(";"),n;r>-1&&(n=e.slice(r+1),e=e.slice(0,r));let s=xt.get(e);if(t){if(s?.deserializeStream)return s.deserializeStream;let i=xt.get(e)?.deserialize||c0(e,n);return o=>Kee(o).then(i)}return e&&xt.get(e)?.deserialize||c0(e,n)}function c0(e,t){if(e.startsWith("text/")){let r=t?.match(/charset=(.+)/)?.[1]||"utf-8";return n=>({contentType:e,data:n.toString(r)})}else return e==="application/octet-stream"?r=>r:r=>{if(!e)try{if(r?.[0]===123)return Fg(r)}catch{}return{contentType:e||"application/octet-stream",data:r}}}function Wee(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 xg,us,Ao,Hs,kf,u0,Gg,qg,l0,_0,al,Fg,cl,xt,kg,o0,d0,$ee,Yee,a0,Na=ge(()=>{em();xg=v(Ff()),us=require("msgpackr"),Ao=require("cbor-x"),Hs=require("zlib"),kf=require("stream");or();u0=require("../index"),Gg=v(ee()),qg=v(L()),l0=v(require("yaml")),_0=Gg.default.get(qg.CONFIG_PARAMS.SERIALIZATION_BIGINT)!==!1,al=_0?Gi:JSON.stringify,Fg=_0?Zh:JSON.parse,cl={useRecords:!1,useToJSON:!0},xt=new Map,kg=xt;nt.contentTypes=kg;(0,u0._assignPackageExport)("contentTypes",kg);xt.set("application/json",{serializeStream:Ac,serialize:al,deserialize:Fg,q:.8});o0=new Ao.Encoder(cl);xt.set("application/cbor",{serializeStream(e){return e[Symbol.asyncIterator]&&(e[Symbol.iterator]=null),new Ao.EncoderStream(cl).end(e)},serialize:o0.encode,deserialize:o0.decode,q:1});xt.set("application/x-msgpack",{serializeStream(e){return(e?.[Symbol.iterator]||e?.[Symbol.asyncIterator])&&!Array.isArray(e)?kf.Readable.from((0,us.encodeIter)(e,cl)):(0,us.pack)(e)},serialize:us.pack,deserialize:us.unpack,q:.9});xt.set("text/csv",{serializeStream(e,t){return t.headers.set("Content-Disposition",'attachment; filename="data.csv"'),(0,xg.toCsvStream)(e,e?.getColumns?.())},q:.1});xt.set("text/plain",{serialize(e){return e.toString()},deserialize(e){return e.toString()},q:.01});xt.set("text/yaml",{serialize(e){return l0.stringify(e,{aliasDuplicateObjects:!1})},q:.7});xt.set("text/event-stream",{serializeStream:function(e){return kf.Readable.from(Wee(e,this.serialize))},serialize:function(e){if(e.acknowledge&&e.acknowledge(),typeof e=="object"&&"value"in e&&e.timestamp&&(e={data:e.value,event:e.type,id:e.timestamp}),e.data||e.event){let t="";if(e.event&&(t+="event: "+e.event+`
|
|
20
|
+
`),e.data){let r=e.data;typeof r=="object"&&(r=al(r)),t+="data: "+r+`
|
|
19
21
|
`}return e.id&&(t+="id: "+e.id+`
|
|
20
22
|
`),e.retry&&(t+="retry: "+e.retry+`
|
|
21
23
|
`),t+`
|
|
22
|
-
`}else return typeof e=="object"?`data: ${
|
|
24
|
+
`}else return typeof e=="object"?`data: ${al(e)}
|
|
23
25
|
|
|
24
26
|
`:`data: ${e}
|
|
25
27
|
|
|
26
|
-
`},compressible:!1,q:.8});Ht.set("application/x-www-form-urlencoded",{deserialize(e){let t={};for(let[r,s]of new URLSearchParams(e))if(t.hasOwnProperty(r)){let n=t[r];Array.isArray(n)?n.push(s):t.key=[n,s]}else t[r]=s},serialize(e){let t=new URLSearchParams;for(let r in e)t.set(r,e);return t.toString()}});$v={type:"application/json",serializeStream:Tc,serialize:Zu,deserialize:Aee,q:.8};Ht.set("*/*",$v);Ht.set("",$v);a(Aee,"tryJSONParse");a(Mg,"registerContentHandlers");Oee=require("fastify-plugin"),bee=Oee(function(e,t,r){e.addHook("preSerialization",async(s,n)=>{if(n.raw.getHeader("content-type"))return;let{serializer:o,type:c}=vf(s.raw);n.type(c),n.serializer(function(u){return(o.serializeStream||o.serialize)(u,{headers:{set:(_,l)=>{n.header(_,l)}}})})}),r()},{name:"content-type-negotiation"});a(vf,"findBestSerializer");qv=wg.default.get(Cg.CONFIG_PARAMS.HTTP_COMPRESSIONTHRESHOLD);a(Bf,"serialize");a(Ai,"serializeMessage");a(Nee,"streamToBuffer");a(Ro,"getDeserializer");a(Gv,"deserializerUnknownType");a(yee,"transformIterable")});function vg(e,t,r,s,n,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?vg(d.conditions,d.operator,r,s,n,i,o,c):Ma(d,s,d.descending||n.reverse===!0,r,n.allowFullScan,c)}a(_,"executeCondition");function l(d,f,E){return d.map((h,p)=>{if(h.conditions){let b=h.operator==="or",R=l(h.conditions,!b,E);return b?(L,H)=>R.some(P=>P(L,H)):(L,H)=>R.every(P=>P(L,H))}let S=(h.attribute||h[0])===r.primaryKey,T=Hg(h,r,i,c,S,E);return f&&p<d.length-1&&E&&(E=vee(r.primaryStore,h.estimated_count,E)),T}).filter(Boolean)}a(l,"mapConditionsToFilters")}function Ma(e,t,r,s,n,i){let o=e[0]??e.attribute,c=e[1]??e.value,u=e.comparator;if(Array.isArray(o)){let b=o[0],R=xn(s.attributes,b);if(R.relationship){if(o.length<2)throw new Kr.ClientError("Can not directly query a relational attribute, must query an attribute within the target table");let L=R.definition?.tableClass||R.elements?.definition?.tableClass,H=new Map,P=Ma({attribute:o.length>2?o.slice(1):o[1],value:c,comparator:u},t,r,L,n,H);if(R.relationship.to){i[o[0]]=H;let k=!!xn(L.attributes,R.relationship.to)?.elements;P=Lee(P,R,L.primaryStore,k,H)}if(R.relationship.from){let k=a(B=>Ma({attribute:R.relationship.from,value:B},t,r,s,n,H),"searchEntry");R.elements?(i[o[0]]=H,P=Mee(P,R,L.primaryStore,H,k)):P=P.flatMap(k)}return P}else if(o.length===1)o=o[0];else throw new Kr.ClientError("Unable to query by attribute "+JSON.stringify(o))}let _,l,d,f;c instanceof Date&&(c=c.getTime());let E;switch(Bg[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]=_n.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 Kr.ClientError(`Unknown query comparator "${u}"`)}if(r){let b=_;_=l,l=b,b=!f,f=!d,d=b}let h=o===s.primaryKey||o==null,p=h?s.primaryStore:s.indices[o],S;if(!p||p.isIndexing||E||c===null&&!p.indexNulls){if(n===!1&&!p)throw new Kr.ClientError(`"${o}" is not indexed, can not search for this attribute`,404);if(n===!1&&E)throw new Kr.ClientError(`Can not use ${u||"equal"} operator without combining with a condition that uses an index, can not search for attribute ${o}`,403);if(p?.isIndexing)throw new Kr.ServerError(`"${o}" is not indexed yet, can not search for this attribute`,503);if(c===null&&!p.indexNulls)throw new Kr.ClientError(`"${o}" is not indexed for nulls, index needs to be rebuilt to search for nulls, can not search for this attribute`,400);if(S=Hg(e),!S)throw new Kr.ClientError(`Unknown search operator ${e.comparator}`)}let T={start:_,end:l,inclusiveEnd:d,exclusiveStart:f,values:!0,versions:h,transaction:t,reverse:r};if(h){let b=p.getRange(T).map(S?function({key:R,value:L}){return this.isSync?L&&S(L)?R:Ni.SKIP:new Promise((H,P)=>setImmediate(()=>{try{H(L&&S(L)?R:Ni.SKIP)}catch(k){P(k)}}))}:R=>R.value==null?Ni.SKIP:R);return b.hasEntries=!0,b}else return p?p.getRange(T).map(S?function({key:b,value:R}){return this.isSync?S({[o]:b})?R:Ni.SKIP:new Promise((L,H)=>setImmediate(()=>{try{L(S({[o]:b})?R:Ni.SKIP)}catch(P){H(P)}}))}:({value:b})=>b):s.primaryStore.getRange(r?{end:!0,transaction:t,reverse:!0}:{start:!0,transaction:t}).map(function({key:b,value:R}){return this.isSync?R&&S(R)?b:Ni.SKIP:new Promise((L,H)=>setImmediate(()=>{try{L(R&&S(R)?b:Ni.SKIP)}catch(P){H(P)}}))})}function xn(e,t){if(Array.isArray(t))if(t.length>1){let r=xn(e,t[0]),s=(r?.definition?.tableClass||r?.elements.definition?.tableClass)?.attributes;return s?xn(s,t.slice(1)):void 0}else t=t.toString();else typeof t!="string"&&(t=t.toString());return e.find(r=>r.name===t)}function Lee(e,t,r,s,n){return new e.constructor({[Symbol.iterator](){let i;n.hasMappings=!0;let o;return{next(){if(!i){let u=t.relationship.to,_=a((l,d)=>{let f=l;Array.isArray(l)&&(f=qs(l),o=!0);let E=n.get(f);E?E.push(d):n.set(f,E=[d]),l!==f&&(E.key=l)},"add_entry");for(let l of e){let d=l.value??r.get(l.key??l),f=d?.[u];if(f!=null&&!n.filters?.some(E=>!E(d)))if(s)for(let E=0;E<f.length;E++)_(f[E],l);else _(f,l)}return i=(o?n:n.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 Mee(e,t,r,s,n){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 _=qs(u.value);if(!c.has(_))return c.add(_),u}if(!i){let _=new Map;s.fromRecord=l=>l[t.relationship.from]?.filter?.(d=>_.has(qs(d)));for(let l of e){if(s.filters){let d=r.get(l);if(s.filters.some(f=>!f(d)))continue}_.set(qs(l),l)}return i=_.values()[Symbol.iterator](),this.next()}do{let _=i.next();return _.done?_:(o=n(_.value)[Symbol.iterator](),this.next())}while(!0)},return(){return o?.return?.()},throw(){return o?.throw?.()}}}})}function Hg(e,t,r,s,n,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=xn(t.attributes,l),f=d.definition?.tableClass||d.elements.definition?.tableClass,E=s?.[l],h=Hg({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((b,R)=>{let L,H;if(p){if(p.from&&h.idFilter){if(!S)if(h.idFilter.idSet?.size===1){for(let k of h.idFilter.idSet)e={attribute:p.from,value:k};S=_(p.from,h.idFilter,!0,!0)}else S=_(p.from,h.idFilter,!1,!0);let P=S(b);return S.idFilter&&(T.idFilter=S.idFilter),P}H=p(b,r,R),L=H?.value}else L=b[l];return L?Array.isArray(L)?L.some(h):h(L,H):!1},"recordFilter");return T}}switch(u instanceof Date&&(u=u.getTime()),Bg[o]||o){case Ug.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,_n.compareKeys)(l,u[0])>=0&&(0,_n.compareKeys)(l,u[1])<=0,!0);case"gt":return _(c,l=>(0,_n.compareKeys)(l,u)>0);case"ge":return _(c,l=>(0,_n.compareKeys)(l,u)>=0);case"lt":return _(c,l=>(0,_n.compareKeys)(l,u)<0);case"le":return _(c,l=>(0,_n.compareKeys)(l,u)<=0);case"ne":return _(c,l=>(0,_n.compareKeys)(l,u)!==0);case"sort":return()=>!0;default:throw new Kr.ClientError(`Unknown query comparator "${o}"`)}function _(l,d,f,E){let h;f=f&&!n&&t?.indices[l]&&i>3,f&&(e.estimated_count==null&&xf(t)(e),h=e.estimated_count>>4,(isNaN(h)||h>=i)&&(f=!1));let p=0,S=3;function T(b){let R=b[l],L;if(typeof R!="object"||!R||E?L=d(R):Array.isArray(R)?L=R.some(d):R instanceof Date&&(L=d(R.getTime())),f&&(S++,!L&&!T.idFilter&&++p/S*(i-S)>h)){let H=Ma(e,r.transaction.getReadTxn(),!1,t).map(qs),P=new Set(H);T.idFilter=k=>P.has(qs(k)),T.idFilter.idSet=P}return L}return a(T,"recordFilter"),n&&(T.idFilter=d),T}a(_,"attributeComparator")}function xf(e){function t(r){if(r.estimated_count===void 0){if(r.conditions){let n;if(r.operator==="or"){n=0;for(let i of r.conditions)t(i),n+=i.estimated_count}else{n=1/0;for(let i of r.conditions)t(i),n=isFinite(n)?n*i.estimated_count/Hn(e.primaryStore):i.estimated_count}return r.estimated_count=n,r.estimated_count}let s=r.comparator||r.search_type;if(s=Bg[s]||s,s===Ug.SEARCH_TYPES.EQUALS||!s){let n=r[0]??r.attribute;if(n==null||n===e.primaryKey)r.estimated_count=1;else if(Array.isArray(n)&&n.length>1){let i=xn(e.attributes,n[0]),o=i.definition?.tableClass||i.elements.definition?.tableClass,c=xf(o)({value:r.value,attribute:n.length>2?n.slice(1):n[1],comparator:"equals"}),u=e.indices[i.relationship.from];r.estimated_count=c+(u?c*Hn(e.indices[i.relationship.from])/(Hn(o.primaryStore)||1):c)}else{let i=e.indices[n];r.estimated_count=i?i.getValuesCount(r[1]??r.value):1/0}}else if(s==="contains"||s==="ends_with"||s==="ne"){let n=r[0]??r.attribute,i=e.indices[n];r.value===null&&s==="ne"?r.estimated_count=Hn(e.primaryStore)-(i?i.getValuesCount(null):0):r.estimated_count=1/0}else s==="starts_with"||s==="prefix"?r.estimated_count=Cee*Hn(e.primaryStore)+1:s==="between"?r.estimated_count=wee*Hn(e.primaryStore)+1:s==="sort"?r.estimated_count=Hn(e.primaryStore)+1:r.estimated_count=Iee*Hn(e.primaryStore)+1;typeof r.descending=="boolean"&&(r.estimated_count/=2)}return r.estimated_count}return a(t,"estimateConditionForTable"),t}function qf(e){if(e)if(yi=e,Da.lastIndex=0,Uee.test(e))try{let t=tl(new La,"");if(Or!==yi.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 ${Or} in '${yi}'`,t}else{let t=new URLSearchParams(e);return t.conditions=t,t}}function tl(e,t){let r=Da,s,n,i,o,c,u=decodeURIComponent,_;for(;s=r.exec(yi);){Or=r.lastIndex;let[,l,d]=s;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(n){if(l.length<=2)i=l;else throw new SyntaxError(`invalid FIQL operator ${l}`);u=Kv}else{if(u=decodeURIComponent,i="equals",!l)throw new SyntaxError("attribute must be specified before equality comparator");n=rl(l)}break;case"==":case"!=":case"<":case"<=":case">":case">=":case"===":case"!==":if(i=Dee[d],u=Pg[i]?Kv:decodeURIComponent,!l)throw new SyntaxError(`attribute must be specified before comparator ${d}`);n=rl(l);break;case"|":case"&":case"":case void 0:if(n==null){if(n===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:n,value:u(l)};i==="eq"&&Wv(h,l),Hf(e,_),e.conditions.push(h)}d==="&"&&(_="and"),d==="|"&&(_="or"),n=void 0;break;case",":if(e.conditions)throw new SyntaxError("conditions/comparisons are not allowed in a property list");e.push(rl(l)),n=void 0;break;case"(":Da.lastIndex=Or;let E=tl(l?[]:new La,")");switch(l){case"":Hf(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=Qv(E);break;default:throw new SyntaxError(`unknown query function call ${l}`)}yi[Or]===","?r.lastIndex=++Or:o=!0,n=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");Da.lastIndex=Or,f=tl([],"}"),f.name=l,e.push(f),yi[Or]===","?r.lastIndex=++Or:o=!0;break;case"[":Da.lastIndex=Or,l?(f=tl(new La,"]"),f.name=l):f=tl(e.conditions?new La:[],"]"),e.conditions?(Hf(e,_),e.conditions.push(f),n=null):e.push(f),yi[Or]===","?r.lastIndex=++Or:o=!0;break;case")":case"]":case"}":if(t===d[0]){if(e.conditions){if(n){let h={comparator:i||"equals",attribute:n,value:u(l)};i==="eq"&&Wv(h,l),Hf(e,_),e.conditions.push(h)}else if(l)throw new SyntaxError("no attribute or comparison specified")}else(l||e.length>0&&c)&&e.push(rl(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=n?Pee:Da,r.lastIndex=Or),Or===yi.length)return e}if(t)throw new SyntaxError(`expected '${t}', but encountered end of string`)}function Hf(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 rl(e){return e.indexOf(".")>-1?e.split(".").map(rl):decodeURIComponent(e)}function Kv(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 Kr.ClientError(`Unknown type ${t}`)}return decodeURIComponent(e)}function Wv(e,t){if(t.indexOf("*")>-1)if(t.endsWith("*"))e.comparator="starts_with",e.value=decodeURIComponent(t.slice(0,-1));else throw new Kr.ClientError("wildcard can only be used at the end of a string")}function Qv(e){let t=zv(e[0]);return e.length>1&&(t.next=Qv(e.slice(1))),t}function zv(e){if(Array.isArray(e)){let t=zv(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 qs(e){return Array.isArray(e)?e.join("\0"):e}function Hn(e){let t=Date.now();return(e.estimatedEntryCountExpires||0)<t&&(e.estimatedEntryCount=e.getStats().entryCount,e.estimatedEntryCountExpires=t+1e4),e.estimatedEntryCount}function vee(e,t,r){return t*r/Hn(e)}var Kr,Ug,_n,Ni,Iee,wee,Cee,Dee,Pg,Bg,Uee,Da,Pee,Or,yi,La,Gf=Re(()=>{Kr=x(se()),Ug=x(Et()),_n=require("ordered-binary"),Ni=require("lmdb"),Iee=.3,wee=.1,Cee=.05,Dee={"<":"lt","<=":"le",">":"gt",">=":"ge","!=":"ne","==":"eq","===":"equals","!==":"not_equal"},Pg={lt:!0,le:!0,gt:!0,ge:!0,ne:!0,eq:!0};a(vg,"executeConditions");a(Ma,"searchByIndex");a(xn,"findAttribute");a(Lee,"joinTo");a(Mee,"joinFrom");Bg={eq:"equals",greater_than:"gt",greaterThan:"gt",greater_than_equal:"ge",greaterThanEqual:"ge",less_than:"lt",lessThan:"lt",less_than_equal:"le",lessThanEqual:"le",not_equal:"ne",notEqual:"ne",equal:"equals",sw:"starts_with",startsWith:"starts_with",ew:"ends_with",endsWith:"ends_with",ct:"contains",">":"gt",">=":"ge","<":"lt","<=":"le","...":"between"};a(Hg,"filterByType");a(xf,"estimateCondition");Uee=/[()[\]|!<>.]|(=\w*=)/,Da=/([^?&|=<>!([{}\]),]*)([([{}\])|,&]|[=<>!]*)/g,Pee=/([^&|=[\]{}]+)([[\]{}]|[&|=]*)/g;a(qf,"parseQuery");a(tl,"parseBlock");a(Hf,"assignOperator");a(rl,"decodeProperty");a(Kv,"typedDecoding");a(Wv,"wildcardDecoding");a(Qv,"toSortObject");a(zv,"toSortEntry");La=class{static{a(this,"Query")}constructor(){this.conditions=[]}[Symbol.iterator](){return this.conditions[Symbol.iterator]()}get(t){for(let r=0;r<this.conditions.length;r++){let s=this.conditions[r];if(s.attribute===t)return s.value}}};a(qs,"flattenKey");a(Hn,"estimatedEntryCount");a(vee,"intersectionEstimate")});function e0(e){let t={openapi:Bee,info:{title:"HarperDB HTTP REST interface",version:(0,Zv.version)()},paths:{},components:{schemas:{},securitySchemes:{basicAuth:{type:"http",scheme:"basic"},bearerAuth:{type:"http",scheme:"bearer",bearerFormat:"JWT"}}}},r=[{basicAuth:[],bearerAuth:[]}];for(let[,s]of e){if(!s.path)continue;let{path:n}=s,i=n.split("/").slice(-1),{attributes:o,primaryKey:c,prototype:u}=s.Resource;if(c=c??"id",!c)continue;let _={},l=[];if(o)for(let{type:R,name:L,elements:H,relationship:P,definition:k}of o){if(P)R==="array"?_[L]={type:"array",items:{$ref:Ii+H.type}}:_[L]={$ref:Ii+R};else{let B=k??H?.definition;if(B){if(!t.components.schemas[B.type]){let X={};B.properties.forEach(z=>{X[z.name]=new Fg(xg[z.type],z.type)}),t.components.schemas[B.type]=new jv(X)}R==="array"?_[L]={type:"array",items:{$ref:Ii+B.type}}:_[L]={$ref:Ii+B.type}}else R==="array"?H.type==="Any"||H.type=="ID"?_[L]={type:"array",items:{format:H.type}}:_[L]={type:"array",items:new Fg(xg[H.type],H.type)}:R==="Any"||R=="ID"?_[L]={format:R}:_[L]=new Fg(xg[R],R)}l.push(new kg(L,"query",_[L]))}let d=Object.keys(_),f=new kg(c,"path",{format:"ID"});f.required=!0,f.description="primary key of record";let E=new kg("property","path",{enum:d});E.required=!0,t.components.schemas[i]=new jv(_);let h=u.post!==Resource.prototype.post||u.update,p=typeof u.put=="function",S=typeof u.get=="function",T=typeof u.delete=="function",b="/"+n+"/";h&&(t.paths[b]={},t.paths[b].post=new Hee(i,r,"create a new record auto-assigning a primary key")),S&&(t.paths[b]||(t.paths[b]={}),t.paths[b].get=new qg(l,r,{200:new Gg({$ref:Ii+i})},"search for records by the specified property name and value pairs")),T&&(t.paths[b]||(t.paths[b]={}),t.paths[b].delete=new Xv(l,r,"delete all the records that match the provided query",{204:new Jv})),b="/"+n+"/{"+c+"}",S&&(t.paths[b]={},t.paths[b].get=new qg([f],r,{200:new Gg({$ref:Ii+i})},"retrieve a record by its primary key")),p&&(t.paths[b]||(t.paths[b]={}),t.paths[b].put=new xee([f],r,i,"create or update the record with the URL path that maps to the record's primary key")),T&&(t.paths[b]||(t.paths[b]={}),t.paths[b].delete=new Xv([f],r,"delete a record with the given primary key",{204:new Jv})),S&&E.schema.enum.length>0&&(b="/"+n+"/{"+c+"}.{property}",t.paths[b]={},t.paths[b].get=new qg([f,E],r,{200:new Gg({enum:d})},"used to retrieve the specified property of the specified record"))}return t}function Hee(e,t,r){this.description=r,this.requestBody={content:{"application/json":{schema:{$ref:Ii+e}}}},this.security=t,this.responses={200:{description:Vg,headers:{Location:{description:"primary key of new record",schema:{type:"string",format:"ID"}}},content:{"application/json":{schema:{type:"string",format:"ID"}}}}}}function qg(e,t,r,s){this.description=s,this.parameters=e,this.security=t,this.responses=r}function Gg(e){this.description=Vg,this.content={"application/json":{schema:e}}}function Jv(){this.description="successfully processed request, no content returned to client"}function xee(e,t,r,s){this.description=s,this.parameters=e,this.security=t,this.requestBody={content:{"application/json":{schema:{$ref:Ii+r}}}},this.responses={200:{description:Vg}}}function Xv(e,t,r,s){this.description=r,this.parameters=e,this.security=t,this.responses=s}function jv(e){this.type="object",this.properties=e}function Fg(e,t){this.type=e,this.format=t}function kg(e,t,r){this.name=e,this.in=t,this.schema=r}var Zv,Bee,xg,Ii,Vg,t0=Re(()=>{Zv=x(Hd()),Bee="3.0.3",xg={Int:"integer",Float:"number",Long:"integer",String:"string",Boolean:"boolean",Date:"string",Bytes:"string",BigInt:"integer",array:"array"},Ii="#/components/schemas/",Vg="successful operation";a(e0,"generateJsonApi");a(Hee,"Post");a(qg,"Get");a(Gg,"Response200");a(Jv,"Response204");a(xee,"Put");a(Xv,"Delete");a(jv,"ResourceSchema");a(Fg,"Type");a(kg,"Parameter")});var kf={};Ye(kf,{start:()=>Fee});async function Gee(e,t){let r=e.headers.asObject,s=r.accept==="text/event-stream"?"CONNECT":e.method;e.search&&qf(e);let n=new Ri;try{e.responseHeaders=n;let i=e.url.slice(1),o,c;if(i!==r0){let h=Ff.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 je(e,()=>{if(s==="POST"||s==="PUT"||s==="PATCH"||s==="QUERY")try{e.data=Ro(r["content-type"],!0)(e.body)}catch(h){throw new Ua.ClientError(h,400)}if(e.authorize=!0,i===r0&&s==="GET"){if(e?.user?.role?.permission?.super_user)return e0(Ff);throw new Ua.ServerError("Forbidden",403)}switch(s){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":n.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 Ua.ClientError("HarperDB is short and stout and can't brew coffee",418);default:throw new Ua.ServerError(`Method ${s} is not recognized`,501)}}),l=200,d;if(_==null)l=s==="GET"||s==="HEAD"?404:204,$g.lastModified&&e.lastModified&&n.setIfNone("Last-Modified",new Date(e.lastModified).toUTCString());else if(d=e.lastModified){qee[0]=d;let h=String.fromCharCode(34,(Yt[0]&63)+62,(Yt[0]>>6)+(Yt[1]<<2&63)+62,(Yt[1]>>4)+(Yt[2]<<4&63)+62,(Yt[2]>>2)+62,(Yt[3]&63)+62,(Yt[3]>>6)+(Yt[4]<<2&63)+62,(Yt[4]>>4)+(Yt[5]<<4&63)+62,(Yt[5]>>2)+62,(Yt[6]&63)+62,(Yt[6]>>6)+(Yt[7]<<2&63)+62,34),p=r["if-none-match"];p&&h==p?(_?.onDone&&_.onDone(),l=304,_=void 0):n.setIfNone("ETag",h),$g.lastModified&&n.setIfNone("Last-Modified",new Date(d).toUTCString())}e.createdResource&&(l=201),e.newLocation&&n.setIfNone("Location",e.newLocation);let f={status:l,headers:n,body:void 0},E=_?.wasLoadedFromSource?.();return E!==void 0&&(f.wasCacheMiss=E,!E&&d&&n.setIfNone("Age",Math.round((Date.now()-(e.lastRefreshed||d))/1e3))),_!==void 0&&(f.body=Bf(_,e,f),s==="HEAD"&&(f.body=void 0)),f}catch(i){i.statusCode?i.statusCode===500?Ao.warn(i):Ao.info(i):Ao.error(i),i.statusCode===405&&(i.method&&(i.message+=` to handle HTTP method ${i.method.toUpperCase()||""}`),i.allow&&(i.allow.push("trace","head","options"),n.setIfNone("Allow",i.allow.map(c=>c.toUpperCase()).join(", "))));let o={status:i.statusCode||500,headers:n,body:void 0};return o.body=Bf(i.contentType?i:i.toString(),e,o),o}}function Fee(e){$g=e,!s0&&(s0=!0,Ff=e.resources,e.server.http(async(t,r)=>{if(!t.isWebSocket)return Gee(t,r)}),e.server.ws(async(t,r,s)=>{sl++;let n=new bs;n0||(n0=!0,nu(l=>{sl>0&&l.push({metric:"ws-connections",connections:sl,byThread:!0})}));let i;t.on("error",l=>{i=!0,Ao.warn(l)});let o;t.on("message",a(function(d){o||(o=Ro(r.headers.asObject["content-type"]));let f=o(d);n.push(f)},"message"));let c;t.on("close",()=>{sl--,os(!i,"connection","ws","disconnect"),n.emit("close"),c&&c.return()}),await s;let u=r.url.slice(1),_=Ff.getMatch(u);if(os(!!_,"connection","ws","connect"),!_)t.send(Ai(`No resource was found to handle ${r.pathname}`,r));else{r.handlerPath=_.path,Fr(h=>({count:h.count,total:sl}),"connections",r.handlerPath,"connect","ws");let l={url:_.relativeURL,async:!0},d=_.Resource;c=(await je(r,()=>d.connect(l,n,r)))[Symbol.asyncIterator]();let E;for(;!(E=await c.next()).done;){let h=Ai(E.value,r);t.send(h),Fr(h.length,"bytes-sent",r.handlerPath,"message","ws")}}t.close()}))}var Ao,Ua,Yt,qee,$g,r0,s0,Ff,n0,sl,i0=Re(()=>{Oa();In();Ao=x($()),Ua=x(se());Gf();pc();ro();qu();t0();Yt=new Uint8Array(8),qee=new Float64Array(Yt.buffer,0,1),$g={},r0="openapi";a(Gee,"http");sl=0;a(Fee,"start")});var Yg=g((fme,o0)=>{var{recordAction:Vf,recordActionBinary:kee}=(In(),ne(iu)),Vee=require("fastify-plugin"),$ee=200;o0.exports=Vee(function(e,t,r){e.addHook("onResponse",async(s,n)=>{n.getResponseTime()}),e.addHook("onSend",async(s,n,i)=>{let o=n.getResponseTime(),c=performance.now(),u=n.request.routeOptions,_,l,d;u.config?.isOperation?(_=s.body?.operation,l="operation"):(_=u.url,l="fastify-route",d=u.method),Vf(o,"duration",_,d,l),kee(n.raw.statusCode<400,"success",_,d,l);let f=$ee;i?.pipe?(i.on("data",h=>{f+=h.length}),i.on("end",()=>{Vf(performance.now()-c,"transfer",_,d,l),Vf(f,"bytes-sent",_,d,l)})):(f+=i?.length||0,Vf(f,"bytes-sent",_,d,l));let E=o.toFixed(3);n.header("Server-Timing",`db;dur=${E}`)}),r()},{name:"hdb-request-time"})});var Xg=g((mme,l0)=>{var Wf=require("clone"),Qf=Xe(),Yee=Q(),Yf=M(),Eme=$(),Kg=require("fs"),Qg=require("joi"),{string:Kf}=Qg.types(),{hdb_errors:Kee,handleHDBError:$f}=se(),{HDB_ERROR_MSGS:hme,HTTP_STATUS_CODES:Wg}=Kee,{common_validators:Pa}=Js(),a0=" is required",Wee=["insert","update","upsert"],zg={database:{presence:!1,format:Pa.schema_format,length:Pa.schema_length},schema:{presence:!1,format:Pa.schema_format,length:Pa.schema_length},table:{presence:!0,format:Pa.schema_format,length:Pa.schema_length},action:{inclusion:{within:Wee,message:"is required and must be either insert, update, or upsert"}},file_path:{},csv_url:{url:{allowLocal:!0}},data:{},passthrough_headers:{}},Qee={schema:Kf.required(),table:Kf.required(),action:Kf.valid("insert","update","upsert")},{AWS_ACCESS_KEY:zee,AWS_SECRET:Jee,AWS_BUCKET:Xee,AWS_FILE_KEY:jee,REGION:Zee}=Yf.S3_BUCKET_AUTH_KEYS,ete={s3:{presence:!0},[`s3.${zee}`]:{presence:!0,type:"String"},[`s3.${Jee}`]:{presence:!0,type:"String"},[`s3.${Xee}`]:{presence:!0,type:"String"},[`s3.${jee}`]:{presence:!0,type:"String",hasValidFileExt:[".csv",".json"]},[`s3.${Zee}`]:{presence:!0,type:"String"}},c0=Wf(zg);c0.data.presence={message:a0};var u0=Wf(zg);u0.file_path.presence={message:a0};var tte=Object.assign(Wf(zg),ete),Jg=Wf(Qee);Jg.csv_url=Kf.uri().messages({"string.uri":"'csv_url' must be a valid url"}).required();Jg.passthrough_headers=Qg.object();function rte(e){let t=Qf.validateObject(e,c0);return zf(e,t)}a(rte,"dataObject");function ste(e){let t=Qf.validateBySchema(e,Qg.object(Jg));return zf(e,t)}a(ste,"urlObject");function nte(e){let t=Qf.validateObject(e,u0);return zf(e,t)}a(nte,"fileObject");function ite(e){let t=Qf.validateObject(e,tte);return zf(e,t)}a(ite,"s3FileObject");function zf(e,t){if(!t){let r=Yee.checkGlobalSchemaTable(e.schema,e.table);if(r)return $f(new Error,r,Wg.BAD_REQUEST);if(e.operation===Yf.OPERATIONS_ENUM.CSV_FILE_LOAD)try{Kg.accessSync(e.file_path,Kg.constants.R_OK|Kg.constants.F_OK)}catch(s){return s.code===Yf.NODE_ERROR_CODES.ENOENT?$f(s,`No such file or directory ${s.path}`,Wg.BAD_REQUEST):s.code===Yf.NODE_ERROR_CODES.EACCES?$f(s,`Permission denied ${s.path}`,Wg.BAD_REQUEST):$f(s)}}return t}a(zf,"postValidateChecks");l0.exports={dataObject:rte,urlObject:ste,fileObject:nte,s3FileObject:ite}});var jg=g((Sme,_0)=>{"use strict";var nl=$(),Jf=M();async function ote(e,t,r,s=void 0){if(!e||typeof e!="function")throw new Error("Invalid function parameter");let n;try{return n=await e(t),r&&await r(t,n,s),t.operation===Jf.OPERATIONS_ENUM.INSERT||t.operation===Jf.OPERATIONS_ENUM.UPDATE||t.operation===Jf.OPERATIONS_ENUM.UPSERT?(delete n.new_attributes,delete n.txn_time):t.operation===Jf.OPERATIONS_ENUM.DELETE&&delete n.txn_time,n}catch(i){throw i.message&&typeof i.message=="string"&&i.message.includes("already exists")?(nl.info(i.message),i):i.http_resp_msg?(nl.error(`Error calling operation: ${e.name}`),nl.error(i.http_resp_msg),i):(nl.error(`Error calling operation: ${e.name}`),nl.error(i),i)}}a(ote,"callOperationFunctionAsAwait");_0.exports={callOperationFunctionAsAwait:ote}});var f0=g((gme,d0)=>{"use strict";var Zg=class{static{a(this,"BulkLoadFileObject")}constructor(t,r,s,n,i,o,c=null){this.op=t,this.action=r,this.schema=s,this.table=n,this.file_path=i,this.file_type=o,this.role_perms=c}},eR=class{static{a(this,"BulkLoadDataObject")}constructor(t,r,s,n){this.action=t,this.schema=r,this.table=s,this.data=n}};d0.exports={BulkLoadFileObject:Zg,BulkLoadDataObject:eR}});var h0=g((Ame,E0)=>{"use strict";var tR=class{static{a(this,"ClusteringOriginObject")}constructor(t,r,s){this.timestamp=t,this.user=r,this.node_name=s}};E0.exports=tR});var aR=g((wme,M0)=>{"use strict";var Xf=Ur(),Zf=Xg(),ate=require("needle"),Gs=M(),bme=Fe(),va=Q(),{handleHDBError:ot,hdb_errors:b0}=se(),{HTTP_STATUS_CODES:Kt,HDB_ERROR_MSGS:wt,CHECK_LOGS_WRAPPER:bo}=b0,Ba=$(),rR=require("papaparse");va.promisifyPapaParse();var Fs=require("fs-extra"),cte=require("path"),{chain:m0}=require("stream-chain"),p0=require("stream-json/streamers/StreamArray"),S0=require("stream-json/utils/Batch"),T0=require("stream-chain/utils/comp"),{finished:g0}=require("stream"),ute=ee(),N0=jg(),lte=bg(),{BulkLoadFileObject:nR,BulkLoadDataObject:_te}=f0(),iR=Eg(),{verifyBulkLoadAttributePerms:y0}=Df(),Nme=h0(),yme=nt(),Ime=Rn(),{databases:dte}=(Ae(),ne(Ge)),{coerceType:fte}=(eE(),ne(cR)),R0="No records parsed from csv file.",Oo=`${ute.get("HDB_ROOT")}/tmp`,{schema_regex:Ete}=Js(),A0=1024*1024*2,O0=5e3,hte={"text/csv":!0,"application/octet-stream":!0,"text/plain":!0,"application/vnd.ms-excel":!0};M0.exports={csvDataLoad:mte,csvURLLoad:pte,csvFileLoad:Ste,importFromS3:Tte};async function mte(e,t){let r=Zf.dataObject(e);if(r)throw ot(r,r.message,Kt.BAD_REQUEST,void 0,void 0,!0);let s={};try{let n=C0(e.schema,e.table),i=rR.parse(e.data,{header:!0,skipEmptyLines:!0,transform:sR.bind(null,n),dynamicTyping:!1}),o=new iR;e.hdb_user&&e.hdb_user.role&&e.hdb_user.role.permission&&e.hdb_user.role.permission.super_user!==!0&&y0(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 ot(new Error,c,Kt.BAD_REQUEST,void 0,void 0,!0);let u=new _te(e.action,e.schema,e.table,i.data);return s=await N0.callOperationFunctionAsAwait(D0,u,null),s.message===R0?R0:L0(s.records,s.number_written)}catch(n){throw No(n)}}a(mte,"csvDataLoad");async function pte(e){let t=Zf.urlObject(e);if(t)throw ot(t,t.message,Kt.BAD_REQUEST,void 0,void 0,!0);let r=`${Date.now()}.csv`,s=`${Oo}/${r}`;try{await gte(e,r)}catch(n){throw Ba.error(wt.DOWNLOAD_FILE_ERR(r)+" - "+n),ot(n,bo(wt.DOWNLOAD_FILE_ERR(r)))}try{let n=new nR(this.job_operation_function.name,e.action,e.schema,e.table,s,Gs.VALID_S3_FILE_TYPES.CSV,e.hdb_user.role.permission),i=await oR(n);return await jf(s),i}catch(n){throw await jf(s),No(n)}}a(pte,"csvURLLoad");async function Ste(e){let t=Zf.fileObject(e);if(t)throw ot(t,t.message,Kt.BAD_REQUEST,void 0,void 0,!0);let r=new nR(this.job_operation_function.name,e.action,e.schema,e.table,e.file_path,Gs.VALID_S3_FILE_TYPES.CSV,e.hdb_user.role.permission);try{return await oR(r)}catch(s){throw No(s)}}a(Ste,"csvFileLoad");async function Tte(e){let t=Zf.s3FileObject(e);if(t)throw ot(t,t.message,Kt.BAD_REQUEST,void 0,void 0,!0);let r;try{let s=cte.extname(e.s3.key),n=`${Date.now()}${s}`;r=`${Oo}/${n}`;let i=new nR(this.job_operation_function.name,e.action,e.schema,e.table,r,s,e.hdb_user.role.permission);await Rte(n,e);let o=await oR(i);return await jf(r),o}catch(s){throw await jf(r),No(s)}}a(Tte,"importFromS3");async function gte(e,t){let r;try{let s=e.passthrough_headers?{headers:e.passthrough_headers}:void 0;r=await ate("get",e.csv_url,s)}catch(s){let n=`Error downloading CSV file from ${e.csv_url}, status code: ${s.statusCode}. Check the log for more information.`;throw ot(s,n,s.statusCode,Gs.LOG_LEVELS.ERROR,"Error downloading CSV file - "+s)}Ote(r,e.csv_url),await Ate(t,r.raw)}a(gte,"downloadCSVFile");async function Rte(e,t){try{let r=`${Oo}/${e}`;await Fs.mkdirp(Oo),await Fs.writeFile(`${Oo}/${e}`,"",{flag:"a+"});let s=await Fs.createWriteStream(r),n=await lte.getFileStreamFromS3(t);await new Promise((i,o)=>{n.on("error",function(c){o(c)}),n.pipe(s).on("error",function(c){o(c)}).on("close",function(){Ba.info(`${t.s3.key} successfully downloaded to ${r}`),i()})})}catch(r){throw Ba.error(wt.S3_DOWNLOAD_ERR+" - "+r),ot(r,bo(wt.S3_DOWNLOAD_ERR))}}a(Rte,"downloadFileFromS3");async function Ate(e,t){try{await Fs.mkdirp(Oo),await Fs.writeFile(`${Oo}/${e}`,t)}catch(r){throw Ba.error(wt.WRITE_TEMP_FILE_ERR),ot(r,bo(wt.DEFAULT_BULK_LOAD_ERR))}}a(Ate,"writeFileToTempFolder");async function jf(e){if(e)try{await Fs.access(e),await Fs.unlink(e)}catch{Ba.warn(`could not delete temp csv file at ${e}, file does not exist`)}}a(jf,"deleteTempFile");function Ote(e,t){if(e.statusCode!==b0.HTTP_STATUS_CODES.OK)throw ot(new Error,`CSV Load failed from URL: ${t}, status code: ${e.statusCode}, message: ${e.statusMessage}`,Kt.BAD_REQUEST);if(!hte[e.headers["content-type"]])throw ot(new Error,`CSV Load failed from URL: ${t}, unsupported content type: ${e.headers["content-type"]}`,Kt.BAD_REQUEST);if(!e.raw)throw ot(new Error,`CSV Load failed from URL: ${t}, no csv found at url`,Kt.BAD_REQUEST)}a(Ote,"validateURLResponse");async function oR(e){try{let t;switch(e.file_type){case Gs.VALID_S3_FILE_TYPES.CSV:t=await bte(e);break;case Gs.VALID_S3_FILE_TYPES.JSON:t=await Nte(e);break;default:throw ot(new Error,wt.DEFAULT_BULK_LOAD_ERR,Kt.BAD_REQUEST,Gs.LOG_LEVELS.ERROR,wt.INVALID_FILE_EXT_ERR(e))}return L0(t.records,t.number_written)}catch(t){throw No(t)}}a(oR,"fileLoad");async function I0(e,t,r,s,n){let i=s.data?s.data:s;if(i.length===0)return;n&&n.pause();let o={operation:e.action,schema:e.schema,table:e.table,records:i};try{let{attributes:c}=await Xf.validation(o);e.role_perms&&e.role_perms.super_user!==!0&&y0(e.role_perms,e.op,e.action,e.schema,e.table,c,t),n&&n.resume()}catch(c){let u=ot(c);r(u)}}a(I0,"validateChunk");async function w0(e,t,r,s,n){let i=s.data?s.data:s;if(i.length===0)return;va.autoCastJSONDeep(i),n&&n.pause();let o=s.meta?s.meta.fields:null;if(o)i.forEach(c=>{!va.isEmpty(c)&&!va.isEmpty(c.__parsed_extra)&&delete c.__parsed_extra});else{let c=new Set;i.forEach(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 N0.callOperationFunctionAsAwait(D0,c,null);t.records+=u.records,t.number_written+=u.number_written,n&&n.resume()}catch(c){let u=ot(c,bo(wt.INSERT_CSV_ERR),Kt.INTERNAL_SERVER_ERROR,Gs.LOG_LEVELS.ERROR,wt.INSERT_CSV_ERR+" - "+c);r(u)}}a(w0,"insertChunk");async function bte(e){let t={records:0,number_written:0},r=C0(e.schema,e.table);try{let s=new iR,n=Fs.createReadStream(e.file_path,{highWaterMark:A0});n.setEncoding("utf8"),await rR.parsePromise(n,I0.bind(null,e,s),sR.bind(null,r));let i=s.getPermsResponse();if(i)throw ot(new Error,i,Kt.BAD_REQUEST);return n=Fs.createReadStream(e.file_path,{highWaterMark:A0}),n.setEncoding("utf8"),await rR.parsePromise(n,w0.bind(null,e,t),sR.bind(null,r)),n.destroy(),t}catch(s){throw ot(s,bo(wt.PAPA_PARSE_ERR),Kt.INTERNAL_SERVER_ERROR,Gs.LOG_LEVELS.ERROR,wt.PAPA_PARSE_ERR+s)}}a(bte,"callPapaParse");function C0(e,t){let r=dte[e][t].attributes,s=new Map;for(let n of r)n.type&&s.set(n.name,i=>fte(i,n));return s}a(C0,"createTransformMap");function sR(e,t,r){let s=e.get(r);return s?s(t):va.autoCast(t)}a(sR,"typeFunction");async function Nte(e){let t={records:0,number_written:0},r=a(s=>{throw s},"throwErr");try{let s=new iR,n=m0([Fs.createReadStream(e.file_path,{encoding:"utf-8"}),p0.withParser(),c=>c.value,new S0({batchSize:O0}),T0(async c=>{await I0(e,s,r,c)})]);await new Promise((c,u)=>{g0(n,_=>{_?u(_):c()}),n.resume()});let i=s.getPermsResponse();if(i)throw ot(new Error,i,Kt.BAD_REQUEST);let o=m0([Fs.createReadStream(e.file_path,{encoding:"utf-8"}),p0.withParser(),c=>c.value,new S0({batchSize:O0}),T0(async c=>{await w0(e,t,r,c)})]);return await new Promise((c,u)=>{g0(o,_=>{_?u(_):c()}),o.resume()}),t}catch(s){throw ot(s,bo(wt.INSERT_JSON_ERR),Kt.INTERNAL_SERVER_ERROR,Gs.LOG_LEVELS.ERROR,wt.INSERT_JSON_ERR+s)}}a(Nte,"insertJson");async function D0(e){let t={};try{e.data&&e.data.length>0&&yte(e.data[0])?t=await Ite(e.data,e.schema,e.table,e.action):(t.message="No records parsed from csv file.",Ba.info(t.message))}catch(r){throw No(r)}return t}a(D0,"callBulkFileLoad");function yte(e){let t=Object.keys(e);for(let r of t)if(!Ete.test(r))throw new Error(`Invalid column name '${r}', cancelling load operation`);return!0}a(yte,"validateColumnNames");async function Ite(e,t,r,s){s||(s="insert");let n={operation:s,schema:t,table:r,records:e},i;switch(s){case"insert":i=Xf.insert;break;case"update":i=Xf.update;break;case"upsert":i=Xf.upsert;break;default:throw ot(new Error,wt.INVALID_ACTION_PARAM_ERR(s),Kt.BAD_REQUEST,Gs.LOG_LEVELS.ERROR,wt.INVALID_ACTION_PARAM_ERR(s))}try{let o=await i(n),c;switch(s){case"insert":c=o.inserted_hashes;break;case"update":c=o.update_hashes;break;case"upsert":c=o.upserted_hashes;break;default:break}if(Array.isArray(o.skipped_hashes)&&o.skipped_hashes.length>0){let l=global.hdb_schema[t][r].hash_attribute,d=e.length;for(;d--;)o.skipped_hashes.indexOf(e[d][l])>=0&&e.splice(d,1)}let u=va.isEmptyOrZeroLength(c)?0:c.length;return{records:e.length,number_written:u,new_attributes:o.new_attributes}}catch(o){throw No(o)}}a(Ite,"bulkFileLoad");function L0(e,t){return`successfully loaded ${t} of ${e} records`}a(L0,"buildResponseMsg");function No(e){return ot(e,bo(wt.DEFAULT_BULK_LOAD_ERR),Kt.INTERNAL_SERVER_ERROR,Gs.LOG_LEVELS.ERROR,wt.DEFAULT_BULK_LOAD_ERR+" - "+e)}a(No,"buildTopLevelErrMsg")});var P0=g((Dme,U0)=>{"use strict";var uR=class{static{a(this,"SqlSearchObject")}constructor(t,r){this.operation="sql",this.sql=t,this.hdb_user=r}};U0.exports=uR});var H0=g((Mme,B0)=>{"use strict";var wte=M(),v0=require("moment"),Cte=require("uuid").v4,lR=class{static{a(this,"JobObject")}constructor(){this.id=Cte(),this.type=void 0,this.start_datetime=v0().valueOf(),this.created_datetime=v0().valueOf(),this.end_datetime=void 0,this.status=wte.JOB_STATUS_ENUM.CREATED,this.message=void 0,this.user=void 0,this.request=void 0}};B0.exports=lR});var _R=g((Pme,V0)=>{"use strict";var Dte=require("uuid").v4,G0=Ur(),F0=Mr(),Lte=tn(),Mte=ra(),Ute=P0(),at=M(),Pte=H0(),vte=Dd(),hs=$(),Bte=Lc(),Ha=Q(),{promisify:Hte}=require("util"),yo=require("moment"),xte=Mf(),tE=Xg(),x0=Bm(),{deleteTransactionLogsBeforeValidator:qte}=ug(),{handleHDBError:Gte,hdb_errors:Fte}=se(),{HTTP_STATUS_CODES:kte}=Fte,q0=F0.searchByValue,Vte=F0.searchByHash,$te=G0.insert,Yte=Hte(xte.evaluateSQL),Kte=G0.update;V0.exports={addJob:zte,updateJob:Xte,handleGetJob:Wte,handleGetJobsByStartDate:Qte,getJobById:k0};async function Wte(e){try{let t=await k0(e.id);return Ha.isEmptyOrZeroLength(t)||(t[0]={...t[0]},t[0].request!==void 0&&delete t[0].request,delete t[0].__createdtime__,delete t[0].__updatedtime__),t}catch(t){let r=`There was an error getting job: ${t}`;throw hs.error("There was an error getting job",t),new Error(r)}}a(Wte,"handleGetJob");async function Qte(e){try{let t=await Jte(e);if(hs.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=yo(r.start_datetime)),r.end_datetime&&(r.end_datetime_converted=yo(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 hs.error(r),new Error(r)}}a(Qte,"handleGetJobsByStartDate");async function zte(e){let t={message:"",error:"",success:!1,createdJob:void 0};if(!e||Object.keys(e).length===0||Ha.isEmptyOrZeroLength(e.operation)){let l="job parameter is invalid";return hs.info(l),t.error=l,t}if(!at.JOB_TYPE_ENUM[e.operation])return hs.info(`invalid job type specified: ${e.operation}.`),t;let r=e.operation,s;switch(r){case at.OPERATIONS_ENUM.CSV_FILE_LOAD:s=tE.fileObject(e);break;case at.OPERATIONS_ENUM.CSV_URL_LOAD:s=tE.urlObject(e);break;case at.OPERATIONS_ENUM.CSV_DATA_LOAD:s=tE.dataObject(e);break;case at.OPERATIONS_ENUM.IMPORT_FROM_S3:s=tE.s3FileObject(e);break;case at.OPERATIONS_ENUM.DELETE_FILES_BEFORE:case at.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE:s=x0(e,"date");break;case at.OPERATIONS_ENUM.DELETE_AUDIT_LOGS_BEFORE:s=x0(e,"timestamp");break;case at.OPERATIONS_ENUM.DELETE_TRANSACTION_LOGS_BEFORE:s=qte(e);break;default:break}if(s)throw Gte(s,s.message,kte.BAD_REQUEST,void 0,void 0,!0);let n=new Pte;n.type=e.operation===at.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE?at.OPERATIONS_ENUM.DELETE_FILES_BEFORE:e.operation,n.type=e.operation,n.user=e.hdb_user.username;let i=new Lte(at.SYSTEM_SCHEMA_NAME,at.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,"id",n.id,"id",["id"]),o;try{o=Array.from(await q0(i))}catch(l){let d=`There was an error inserting a new job: ${l}`;return hs.error(d),t}let c=Array.isArray(o)?o:Object.keys(o);if(c&&c.length>0){n.id=Dte();try{o=await q0(i)}catch(l){let d=`There was an error inserting a new job: ${l}`;return hs.error(d),t}if(c=Array.isArray(o)?o:Object.keys(o),c&&c.length>0)return hs.error("Error creating a job, could not find a unique job id."),t}n.request=e;let u=new Bte(at.SYSTEM_SCHEMA_NAME,at.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,"id",[n]),_;try{_=await $te(u)}catch(l){return hs.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 ${n.operation} and id ${n.id}`;else{let l=`Created a job with type ${n.type} and id ${n.id}`;t.message=l,t.createdJob=n,t.success=!0,hs.trace(l)}return t}a(zte,"addJob");async function Jte(e){let t=yo(e.from_date,yo.ISO_8601),r=yo(e.to_date,yo.ISO_8601);if(!t.isValid())throw new Error("Invalid 'from' date, must be in ISO-8601 format (YYYY-MM-DD).");if(!r.isValid())throw new Error("Invalid 'to' date, must be in ISO-8601 format (YYYY-MM-DD)");let s=`select * from system.hdb_job where start_datetime > '${t.valueOf()}' and start_datetime < '${r.valueOf()}'`,n=new Ute(s,e.hdb_user);try{return await Yte(n)}catch(i){throw hs.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(Jte,"getJobsInDateRange");async function k0(e){if(Ha.isEmptyOrZeroLength(e))return Ha.errorizeMessage("Invalid job ID specified.");let t=new Mte(at.SYSTEM_SCHEMA_NAME,at.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,[e],["*"]);try{return await Vte(t)}catch(r){let s=`There was an error searching for a job by id: ${e} ${r}`;return hs.error(s),Ha.errorizeMessage("there was an error searching for jobs. Please check the log for details.")}}a(k0,"getJobById");async function Xte(e){if(Object.keys(e).length===0)throw new Error("invalid job object passed to updateJob");if(Ha.isEmptyOrZeroLength(e.id))throw new Error("invalid ID passed to updateJob");(e.status===at.JOB_STATUS_ENUM.COMPLETE||e.status===at.JOB_STATUS_ENUM.ERROR)&&(e.end_datetime=yo().valueOf());let t=new vte(at.SYSTEM_SCHEMA_NAME,at.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,[e]),r;return r=await Kte(t),r}a(Xte,"updateJob")});var z0=g((Bme,Q0)=>{"use strict";var $0=Q(),br=M(),jte=require("moment"),rE=aR(),sE=$(),Y0=_R(),K0=Uf(),W0=ni(),Zte=Ke(),ere=yf(),dR=class{static{a(this,"RunnerMessage")}constructor(t,r){this.job=t,this.json=r}};async function tre(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($0.isEmptyOrZeroLength(e.json.operation))throw new Error("Invalid operation");if($0.isEmptyOrZeroLength(e.job.id))throw new Error("Empty job id specified");switch(e.json.operation){case br.JOB_TYPE_ENUM.csv_file_load:await qn(e,rE.csvFileLoad);break;case br.JOB_TYPE_ENUM.csv_url_load:await qn(e,rE.csvURLLoad);break;case br.JOB_TYPE_ENUM.csv_data_load:await qn(e,rE.csvDataLoad);break;case br.JOB_TYPE_ENUM.import_from_s3:await qn(e,rE.importFromS3);break;case br.JOB_TYPE_ENUM.empty_trash:break;case br.JOB_TYPE_ENUM.export_local:await qn(e,K0.export_local);break;case br.JOB_TYPE_ENUM.export_to_s3:await qn(e,K0.export_to_s3);break;case br.JOB_TYPE_ENUM.delete_files_before:case br.JOB_TYPE_ENUM.delete_records_before:await qn(e,W0.deleteFilesBefore);break;case br.JOB_TYPE_ENUM.delete_audit_logs_before:await qn(e,W0.deleteAuditLogsBefore);break;case br.JOB_TYPE_ENUM.delete_transaction_logs_before:await qn(e,ere.deleteTransactionLogsBefore);break;default:return`Invalid operation ${e.json.operation} specified`}}a(tre,"parseMessage");async function qn(e,t){try{e.job.status=br.JOB_STATUS_ENUM.IN_PROGRESS,e.job.start_datetime=jte().valueOf(),await Y0.updateJob(e.job),await rre(e.job.id)}catch(r){let s=r.message!==void 0?r.message:r;typeof s=="string"?(s=`There was an error running ${t.name} job with id ${e.job.id} - ${s}`,r.message=s):sE.error(`There was an error running ${t.name} job with id ${e.job.id}`),sE.error(s),e.job.message=s,e.job.status=br.JOB_STATUS_ENUM.ERROR;try{await Y0.updateJob(e.job)}catch(n){throw sE.error(`Unable to update job with id ${e.job.id}`),n}throw r}}a(qn,"runJob");async function rre(e){sE.trace("launching job thread:",e),Zte.startWorker("server/jobs/jobProcess.js",{autoRestart:!1,name:"job",env:Object.assign({},process.env,{[br.PROCESS_NAME_ENV_PROP]:`JOB-${e}`})})}a(rre,"launchJobThread");Q0.exports={parseMessage:tre,RunnerMessage:dR}});var X0=g((xme,J0)=>{"use strict";var fR=class{static{a(this,"OperationFunctionObject")}constructor(t,r=void 0){this.operation_function=t,this.job_operation_function=r}};J0.exports=fR});var EB=g((Gme,TR)=>{"use strict";var cE=Mr(),mR=Mf(),nE=aR(),Gn=fu(),iE=ti(),ol=ni(),sre=LS(),il=is(),oE=GS(),Wt=cg(),aE=$(),nre=VS(),ire=Vd(),j0=RT(),ore=Yd(),are=OT(),cre=bT(),ure=IT(),lre=CT(),ER=MT(),Z0=Uf(),_re=Df(),pR=_R(),q=M(),{hdb_errors:cl,handleHDBError:al}=se(),{HTTP_STATUS_CODES:eB}=cl,hR=HT(),tB=_f(),lB=require("util"),xa=Ur(),dre=An(),fre=ha(),rB=z0(),sB=Tu(),nB=(hf(),ne(Gu)),iB=Br(),oB=yf(),aB=gf(),{setServerUtilities:Ere}=(eE(),ne(cR)),{CONTEXT:hre}=(Ns(),ne(Dp)),{_assignPackageExport:mre}=require("../index"),{transformReq:pre}=Q(),{server:Sre}=(or(),ne(Bi)),tr=aE.loggerWithTag("operation"),Tre=jg(),cB=cE.searchByHash,gre=cE.searchByValue,Rre=lB.promisify(cE.search),Are=lB.promisify(mR.evaluateSQL),Ore={[q.OPERATIONS_ENUM.CREATE_ATTRIBUTE]:!0,[q.OPERATIONS_ENUM.CREATE_TABLE]:!0,[q.OPERATIONS_ENUM.CREATE_SCHEMA]:!0,[q.OPERATIONS_ENUM.DROP_ATTRIBUTE]:!0,[q.OPERATIONS_ENUM.DROP_TABLE]:!0,[q.OPERATIONS_ENUM.DROP_SCHEMA]:!0},Y=X0();async function _B(e,t){try{if(e.body.operation!=="read_log"&&(aE.log_level===q.LOG_LEVELS.INFO||aE.log_level===q.LOG_LEVELS.DEBUG||aE.log_level===q.LOG_LEVELS.TRACE)){let{hdb_user:s,hdb_auth_header:n,password:i,...o}=e.body;tr.info(o)}}catch(s){tr.error(s)}let r=await Tre.callOperationFunctionAsAwait(t,e.body,null);if(typeof r!="object"&&(r={message:r}),r instanceof Error)throw r;return Ore[e.body.operation]&&dre.setSchemaDataToGlobal(s=>{s&&tr.error(s)}),r}a(_B,"processLocalTransaction");var uB=Nre();TR.exports={chooseOperation:dB,getOperationFunction:fB,operation:SR,processLocalTransaction:_B};Ere(TR.exports);Sre.operation=SR;function dB(e){let t;try{t=fB(e)}catch(n){throw tr.error(`Error when selecting operation function - ${n}`),n}let{operation_function:r,job_operation_function:s}=t;try{if(e.operation==="sql"||e.search_operation&&e.search_operation.operation==="sql"){let n=e.operation==="sql"?e.sql:e.search_operation.sql,i=mR.convertSQLToAST(n);if(e.parsed_sql_object=i,!e.bypass_auth){let o=mR.checkASTPermissions(e,i);if(o)throw tr.error(`${eB.FORBIDDEN} from operation ${e.operation}`),tr.warn(`User '${e.hdb_user.username}' is not permitted to ${e.operation}`),al(new Error,o,cl.HTTP_STATUS_CODES.FORBIDDEN,void 0,void 0,!0)}}else if(!e.bypass_auth&&e.operation!==q.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS&&e.operation!==q.OPERATIONS_ENUM.LOGIN&&e.operation!==q.OPERATIONS_ENUM.LOGOUT){let n=s===void 0?r:s,i=e.search_operation?e.search_operation:e;i.hdb_user||(i.hdb_user=e.hdb_user);let o=_re.verifyPerms(i,n);if(o)throw tr.error(`${eB.FORBIDDEN} from operation ${e.operation}`),tr.warn(`User '${i.hdb_user.username}' is not permitted to ${i.operation}`),al(new Error,o,cl.HTTP_STATUS_CODES.FORBIDDEN,void 0,!1,!0)}}catch(n){throw al(n,"There was an error when trying to choose an operation path")}return r}a(dB,"chooseOperation");function fB(e){if(tr.trace(`getOperationFunction with operation: ${e.operation}`),uB.has(e.operation))return uB.get(e.operation);throw al(new Error,cl.HDB_ERROR_MSGS.OP_NOT_FOUND(e.operation),cl.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0)}a(fB,"getOperationFunction");mre("operation",SR);function SR(e,t){e.hdb_user=this[hre]?.user,e.bypass_auth=!t;let r=dB(e);return _B({body:e},r)}a(SR,"operation");async function bre(e){tr.trace("In serverUtils.catchup");let t=e.transaction,r=t.channel.split(":"),s=r[0],n=r[1];for(let i of t.transactions)try{i.schema=s,i.table=n,i[q.CLUSTERING_FLAG]=!0;let o;switch(i.operation){case q.OPERATIONS_ENUM.INSERT:o=await xa.insert(i);break;case q.OPERATIONS_ENUM.UPDATE:o=await xa.update(i);break;case q.OPERATIONS_ENUM.UPSERT:o=await xa.upsert(i);break;case q.OPERATIONS_ENUM.DELETE:o=await ol.deleteRecord(i);break;default:tr.warn("invalid operation in catchup");break}await transact_to_clustering_utils.postOperationHandler(i,o,e)}catch(o){tr.info("Invalid operation in transaction"),tr.error(o)}}a(bre,"catchup");async function dn(e){pre(e);let t,r;try{r=await pR.addJob(e),t=r.createdJob,tr.info("addJob result",r);let s=new rB.RunnerMessage(t,e);return await rB.parseMessage(s),{message:`Starting job with id ${t.id}`,job_id:t.id}}catch(s){let n=`There was an error executing job: ${s.http_resp_msg?s.http_resp_msg:s}`;throw tr.error(n),al(s,n)}}a(dn,"executeJob");function Nre(){let e=new Map;return e.set(q.OPERATIONS_ENUM.INSERT,new Y(xa.insert)),e.set(q.OPERATIONS_ENUM.UPDATE,new Y(xa.update)),e.set(q.OPERATIONS_ENUM.UPSERT,new Y(xa.upsert)),e.set(q.OPERATIONS_ENUM.SEARCH_BY_CONDITIONS,new Y(cE.searchByConditions)),e.set(q.OPERATIONS_ENUM.SEARCH_BY_HASH,new Y(cB)),e.set(q.OPERATIONS_ENUM.SEARCH_BY_ID,new Y(cB)),e.set(q.OPERATIONS_ENUM.SEARCH_BY_VALUE,new Y(gre)),e.set(q.OPERATIONS_ENUM.SEARCH,new Y(Rre)),e.set(q.OPERATIONS_ENUM.SQL,new Y(Are)),e.set(q.OPERATIONS_ENUM.CSV_DATA_LOAD,new Y(dn,nE.csvDataLoad)),e.set(q.OPERATIONS_ENUM.CSV_FILE_LOAD,new Y(dn,nE.csvFileLoad)),e.set(q.OPERATIONS_ENUM.CSV_URL_LOAD,new Y(dn,nE.csvURLLoad)),e.set(q.OPERATIONS_ENUM.IMPORT_FROM_S3,new Y(dn,nE.importFromS3)),e.set(q.OPERATIONS_ENUM.CREATE_SCHEMA,new Y(Gn.createSchema)),e.set(q.OPERATIONS_ENUM.CREATE_DATABASE,new Y(Gn.createSchema)),e.set(q.OPERATIONS_ENUM.CREATE_TABLE,new Y(Gn.createTable)),e.set(q.OPERATIONS_ENUM.CREATE_ATTRIBUTE,new Y(Gn.createAttribute)),e.set(q.OPERATIONS_ENUM.DROP_SCHEMA,new Y(Gn.dropSchema)),e.set(q.OPERATIONS_ENUM.DROP_DATABASE,new Y(Gn.dropSchema)),e.set(q.OPERATIONS_ENUM.DROP_TABLE,new Y(Gn.dropTable)),e.set(q.OPERATIONS_ENUM.DROP_ATTRIBUTE,new Y(Gn.dropAttribute)),e.set(q.OPERATIONS_ENUM.DESCRIBE_SCHEMA,new Y(iE.describeSchema)),e.set(q.OPERATIONS_ENUM.DESCRIBE_DATABASE,new Y(iE.describeSchema)),e.set(q.OPERATIONS_ENUM.DESCRIBE_TABLE,new Y(iE.describeTable)),e.set(q.OPERATIONS_ENUM.DESCRIBE_ALL,new Y(iE.describeAll)),e.set(q.OPERATIONS_ENUM.DELETE,new Y(ol.deleteRecord)),e.set(q.OPERATIONS_ENUM.ADD_USER,new Y(il.addUser)),e.set(q.OPERATIONS_ENUM.ALTER_USER,new Y(il.alterUser)),e.set(q.OPERATIONS_ENUM.DROP_USER,new Y(il.dropUser)),e.set(q.OPERATIONS_ENUM.LIST_USERS,new Y(il.listUsersExternal)),e.set(q.OPERATIONS_ENUM.LIST_ROLES,new Y(oE.listRoles)),e.set(q.OPERATIONS_ENUM.ADD_ROLE,new Y(oE.addRole)),e.set(q.OPERATIONS_ENUM.ALTER_ROLE,new Y(oE.alterRole)),e.set(q.OPERATIONS_ENUM.DROP_ROLE,new Y(oE.dropRole)),e.set(q.OPERATIONS_ENUM.USER_INFO,new Y(il.userInfo)),e.set(q.OPERATIONS_ENUM.READ_LOG,new Y(nre)),e.set(q.OPERATIONS_ENUM.ADD_NODE,new Y(ire)),e.set(q.OPERATIONS_ENUM.UPDATE_NODE,new Y(j0)),e.set(q.OPERATIONS_ENUM.SET_NODE_REPLICATION,new Y(j0)),e.set(q.OPERATIONS_ENUM.REMOVE_NODE,new Y(ore)),e.set(q.OPERATIONS_ENUM.CONFIGURE_CLUSTER,new Y(are)),e.set(q.OPERATIONS_ENUM.PURGE_STREAM,new Y(cre)),e.set(q.OPERATIONS_ENUM.SET_CONFIGURATION,new Y(iB.setConfiguration)),e.set(q.OPERATIONS_ENUM.CLUSTER_STATUS,new Y(ure.clusterStatus)),e.set(q.OPERATIONS_ENUM.CLUSTER_NETWORK,new Y(lre)),e.set(q.OPERATIONS_ENUM.CLUSTER_SET_ROUTES,new Y(ER.setRoutes)),e.set(q.OPERATIONS_ENUM.CLUSTER_GET_ROUTES,new Y(ER.getRoutes)),e.set(q.OPERATIONS_ENUM.CLUSTER_DELETE_ROUTES,new Y(ER.deleteRoutes)),e.set(q.OPERATIONS_ENUM.EXPORT_TO_S3,new Y(dn,Z0.export_to_s3)),e.set(q.OPERATIONS_ENUM.DELETE_FILES_BEFORE,new Y(dn,ol.deleteFilesBefore)),e.set(q.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE,new Y(dn,ol.deleteFilesBefore)),e.set(q.OPERATIONS_ENUM.EXPORT_LOCAL,new Y(dn,Z0.export_local)),e.set(q.OPERATIONS_ENUM.SEARCH_JOBS_BY_START_DATE,new Y(pR.handleGetJobsByStartDate)),e.set(q.OPERATIONS_ENUM.GET_JOB,new Y(pR.handleGetJob)),e.set(q.OPERATIONS_ENUM.GET_FINGERPRINT,new Y(hR.getFingerprint)),e.set(q.OPERATIONS_ENUM.SET_LICENSE,new Y(hR.setLicense)),e.set(q.OPERATIONS_ENUM.GET_REGISTRATION_INFO,new Y(hR.getRegistrationInfo)),e.set(q.OPERATIONS_ENUM.RESTART,new Y(tB.restart)),e.set(q.OPERATIONS_ENUM.RESTART_SERVICE,new Y(tB.restartService)),e.set(q.OPERATIONS_ENUM.CATCHUP,new Y(bre)),e.set(q.OPERATIONS_ENUM.SYSTEM_INFORMATION,new Y(fre.systemInformation)),e.set(q.OPERATIONS_ENUM.DELETE_AUDIT_LOGS_BEFORE,new Y(dn,ol.deleteAuditLogsBefore)),e.set(q.OPERATIONS_ENUM.READ_AUDIT_LOG,new Y(sre)),e.set(q.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS,new Y(sB.createTokens)),e.set(q.OPERATIONS_ENUM.REFRESH_OPERATION_TOKEN,new Y(sB.refreshOperationToken)),e.set(q.OPERATIONS_ENUM.LOGIN,new Y(nB.login)),e.set(q.OPERATIONS_ENUM.LOGOUT,new Y(nB.logout)),e.set(q.OPERATIONS_ENUM.GET_CONFIGURATION,new Y(iB.getConfiguration)),e.set(q.OPERATIONS_ENUM.CUSTOM_FUNCTIONS_STATUS,new Y(Wt.customFunctionsStatus)),e.set(q.OPERATIONS_ENUM.GET_CUSTOM_FUNCTIONS,new Y(Wt.getCustomFunctions)),e.set(q.OPERATIONS_ENUM.GET_COMPONENT_FILE,new Y(Wt.getComponentFile)),e.set(q.OPERATIONS_ENUM.GET_COMPONENTS,new Y(Wt.getComponents)),e.set(q.OPERATIONS_ENUM.SET_COMPONENT_FILE,new Y(Wt.setComponentFile)),e.set(q.OPERATIONS_ENUM.DROP_COMPONENT,new Y(Wt.dropComponent)),e.set(q.OPERATIONS_ENUM.GET_CUSTOM_FUNCTION,new Y(Wt.getCustomFunction)),e.set(q.OPERATIONS_ENUM.SET_CUSTOM_FUNCTION,new Y(Wt.setCustomFunction)),e.set(q.OPERATIONS_ENUM.DROP_CUSTOM_FUNCTION,new Y(Wt.dropCustomFunction)),e.set(q.OPERATIONS_ENUM.ADD_CUSTOM_FUNCTION_PROJECT,new Y(Wt.addComponent)),e.set(q.OPERATIONS_ENUM.ADD_COMPONENT,new Y(Wt.addComponent)),e.set(q.OPERATIONS_ENUM.DROP_CUSTOM_FUNCTION_PROJECT,new Y(Wt.dropCustomFunctionProject)),e.set(q.OPERATIONS_ENUM.PACKAGE_CUSTOM_FUNCTION_PROJECT,new Y(Wt.packageComponent)),e.set(q.OPERATIONS_ENUM.PACKAGE_COMPONENT,new Y(Wt.packageComponent)),e.set(q.OPERATIONS_ENUM.DEPLOY_CUSTOM_FUNCTION_PROJECT,new Y(Wt.deployComponent)),e.set(q.OPERATIONS_ENUM.DEPLOY_COMPONENT,new Y(Wt.deployComponent)),e.set(q.OPERATIONS_ENUM.READ_TRANSACTION_LOG,new Y(oB.readTransactionLog)),e.set(q.OPERATIONS_ENUM.DELETE_TRANSACTION_LOGS_BEFORE,new Y(dn,oB.deleteTransactionLogsBefore)),e.set(q.OPERATIONS_ENUM.INSTALL_NODE_MODULES,new Y(aB.installModules)),e.set(q.OPERATIONS_ENUM.AUDIT_NODE_MODULES,new Y(aB.auditModules)),e.set(q.OPERATIONS_ENUM.GET_BACKUP,new Y(Gn.getBackup)),e}a(Nre,"initializeOperationFunctionMap")});var lE=g((kme,pB)=>{"use strict";var gR=M(),yre=Q(),ul=$(),{handleHDBError:RR,hdb_errors:uE}=se(),{isMainThread:Ire}=require("worker_threads"),{Readable:wre}=require("stream"),hB=require("os"),Cre=require("util"),Dre=ZS(),Lre=Cre.promisify(Dre.authorize),mB=EB(),{createGzip:Mre,constants:Ure}=require("zlib");function Pre(e){let t=`Found an uncaught exception with message: ${e.message}. ${hB.EOL}Stack: ${e.stack} ${hB.EOL}Terminating ${Ire?"HDB":"thread"}.`;console.error(t),ul.fatal(t),process.exit(1)}a(Pre,"handleServerUncaughtException");function vre(e,t,r){if(ul[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 s=e.statusCode?e.statusCode:uE.HTTP_STATUS_CODES.INTERNAL_SERVER_ERROR;return typeof e=="string"?r.code(s).send({error:e}):r.code(s).send(e.message?{error:e.message}:e)}a(vre,"serverErrorHandler");function Bre(e,t,r){if(!e.body||Object.keys(e.body).length===0||typeof e.body!="object"){let s=RR(new Error,"Invalid JSON.",uE.HTTP_STATUS_CODES.BAD_REQUEST);r(s,null)}if(yre.isEmpty(e.body.operation)){let s=RR(new Error,"Request body must include an 'operation' property.",uE.HTTP_STATUS_CODES.BAD_REQUEST);r(s,null)}r()}a(Bre,"reqBodyValidationHandler");function Hre(e,t,r){let s;e.body.operation!==gR.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS&&e.body.operation!==gR.OPERATIONS_ENUM.LOGIN&&e.body.operation!==gR.OPERATIONS_ENUM.LOGOUT?Lre(e,t).then(n=>{s=n,e.body.hdb_user=s,e.body.hdb_auth_header=e.headers.authorization,r()}).catch(n=>{ul.warn(n),ul.warn(`{"ip":"${e.socket.remoteAddress}", "error":"${n.stack}"`);let i=typeof n=="string"?{error:n}:{error:n.message};r(RR(n,i,uE.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(Hre,"authHandler");async function xre(e,t,r=!1){let s;try{r&&(e.body.operation!=="configure_cluster"||e.body.operation!=="set_configuration")&&(e.body.bypass_auth=r),s=mB.chooseOperation(e.body);let n=await mB.processLocalTransaction(e,s);if(n instanceof wre&&n.headers){for(let[i,o]of n.headers)t.header(i,o);e.headers["accept-encoding"]?.includes("gzip")&&(t.header("content-encoding","gzip"),n=n.pipe(Mre({level:Ure.Z_BEST_SPEED})))}return n}catch(n){throw ul.error(n),n}}a(xre,"handlePostRequest");pB.exports={authHandler:Hre,handlePostRequest:xre,handleServerUncaughtException:Pre,serverErrorHandler:vre,reqBodyValidationHandler:Bre}});var RB=g(($me,gB)=>{"use strict";var qre=require("fastify-plugin"),{handlePostRequest:SB,authHandler:Gre,reqBodyValidationHandler:Fre}=lE();async function kre(e){e.decorate("hdbCore",{preValidation:[Fre,Gre],request:t=>TB(SB(t,response)),requestWithoutAuthentication:(t,r)=>TB(SB(t,r,!0))})}a(kre,"hdbCore");async function TB(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(TB,"convertAsyncIterators");gB.exports=qre(kre)});var bB=g((Wme,OB)=>{"use strict";var Kme=require("fs"),AR=ee();AR.initSync();var{CONFIG_PARAMS:AB}=M(),Vre=1024*1024*1024;function $re(e){let t=AR.get(AB.HTTP_TIMEOUT),r=AR.get(AB.HTTP_KEEPALIVETIMEOUT);return{bodyLimit:Vre,connectionTimeout:t,keepAliveTimeout:r,return503OnClosing:!1,forceCloseConnections:!0,ignoreTrailingSlash:!0,https:e}}a($re,"getServerOptions");OB.exports=$re});var IB=g((zme,yB)=>{"use strict";var OR=ee();OR.initSync();var{CONFIG_PARAMS:NB}=M();function Yre(){let e=OR.get(NB.HTTP_CORSACCESSLIST),t=OR.get(NB.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=(s,n)=>n(null,e.indexOf(s)!==-1))),r}a(Yre,"getCORSOptions");yB.exports=Yre});var DB=g((Xme,CB)=>{"use strict";var wB=ee();wB.initSync();var Kre=M();function Wre(){return wB.get(Kre.CONFIG_PARAMS.HTTP_HEADERSTIMEOUT)??6e4}a(Wre,"getHeaderTimeoutConfig");CB.exports=Wre});var NR={};Ye(NR,{customFunctionsServer:()=>Jre,ready:()=>YB,start:()=>zre});function zre(e){let t=e.securePort>0;return{async handleFile(r,s,n,i){Fn||(Fn=$B(t),rt.http((await Fn).server));let o=await Fn,c=(0,bR.dirname)(n),u=(0,bR.dirname)(s);if(u.startsWith("/")&&(u=u.slice(1)),!LB.has(c)){LB.add(c);try{o.register(jre(c,u))}catch(_){if(_.message==="Root plugin has already booted")Ve.warn(`Could not load root fastify route for ${n}, this may require a restart to install properly`);else throw _}}},ready:YB}}async function Jre(){try{Ve.info("In Custom Functions Fastify server"+process.cwd()),Ve.info(`Custom Functions Running with NODE_ENV set as: ${process.env.NODE_ENV}`),Ve.debug(`Custom Functions server process ${process.pid} starting up.`),await Xre();let e=HB.get(xB.CONFIG_PARAMS.HTTP_SECUREPORT)>0,t;try{t=Fn=await $B(e)}catch(r){throw Ve.error(`Custom Functions buildServer error: ${r}`),r}try{await t.ready()}catch(r){throw Ve.error(`Custom Functions server.ready() error: ${r}`),r}t.server.cantCleanupProperly=!0}catch(e){Ve.error(`Custom Functions ${process.pid} Error: ${e}`),Ve.error(e),process.exit(1)}}async function Xre(){try{Ve.info("Custom Functions starting configuration."),await qB.setUsersToGlobal(),Ve.info("Custom Functions completed configuration.")}catch(e){Ve.error(e)}}function jre(e,t){return async function(r){try{Ve.info("Custom Functions starting buildRoutes"),Ve.trace("Loading fastify routes folder "+e),(0,MB.existsSync)(e)&&r.register(BB.default,n=>({dir:e,dirNameRoutePrefix:!1,options:{hdbCore:n.hdbCore,logger:Ve.loggerWithTag("custom-function"),prefix:`/${t}`}})).after((n,i,o)=>{n?.message?Ve.error(n.message):n&&Ve.error(n),o()})}catch(s){Ve.error(`Custom Functions errored buildRoutes: ${s}`)}}}async function $B(e){Ve.info("Custom Functions starting buildServer.");let t=(0,GB.default)(e),r=(0,UB.default)(t);r.server.headersTimeout=(0,kB.default)(),r.setErrorHandler(VB.serverErrorHandler);let s=(0,FB.default)();return s&&r.register(PB.default,s),r.register(function(n,i,o){n.setNotFoundHandler(function(c,u){r.server.emit("unhandled",c.raw,u.raw)}),o()}),r.register(vB.default),await r.register(Qre),await r.after(),Mg(r),Ve.info("Custom Functions completed buildServer."),r}function YB(){if(Fn)return Fn.then?Fn.then(e=>e.ready()):Fn.ready()}var bR,MB,UB,PB,vB,BB,HB,xB,Ve,Qre,qB,GB,FB,kB,VB,Fn,LB,KB=Re(()=>{bR=require("path"),MB=require("fs"),UB=x(require("fastify")),PB=x(require("@fastify/cors")),vB=x(Yg()),BB=x(require("@fastify/autoload")),HB=x(ee()),xB=x(M()),Ve=x($()),Qre=x(RB()),qB=x(is()),GB=x(bB()),FB=x(IB()),kB=x(DB()),VB=x(lE());Oa();or();LB=new Set;a(zre,"start");a(Jre,"customFunctionsServer");a(Xre,"setUp");a(jre,"buildRouteFolder");a($B,"buildServer");a(YB,"ready")});var yR={};Ye(yR,{start:()=>Zre});function Zre(e){return{handleDirectory(t,r){if(t==="/"){let s=(0,XB.default)(r,e);return e.server.http(async(n,i)=>{if(!n.isWebSocket)return new Promise(o=>s(n._nodeRequest,n._nodeResponse,()=>{o(i(n))}))}),!0}},handleFile(t,r,s){QB||(QB=!0,e.server.http(async(n,i)=>{if(!n.isWebSocket){let o=WB.get(n.pathname);if(o)return{handlesHeaders:!0,body:(0,zB.default)(n,(0,JB.realpathSync)(o))}}return i(n)},{runFirst:!0})),WB.set(r,s)}}}var zB,JB,XB,WB,QB,jB=Re(()=>{zB=x(require("send")),JB=require("fs"),XB=x(require("serve-static")),WB=new Map;a(Zre,"start")});function rse(e,t=1,r){if(IR++,(0,Io.startWorker)("server/threads/threadServer.js",{name:fE.THREAD_TYPES.HTTP,workerIndex:e,threadCount:t,async onStarted(s){let n=new Promise((o,c)=>{function u(_){_.type===fE.CLUSTER_MESSAGE_TYPE_ENUM.CHILD_STARTED&&(s.removeListener("message",u),o(s))}a(u,"onMessage"),s.on("message",u),s.on("error",c)});tse.push(n),await n,qa.push(s),s.expectedIdle=1,s.lastIdle=0,s.requests=1,s.on("message",o=>{if(o.requestId){let c=dE.get(o.requestId);c&&c(o)}}),s.on("exit",i),s.on("shutdown",i);function i(){let o=qa.indexOf(s);o>-1&&qa.splice(o,1)}if(a(i,"removeWorker"),Ga){let o=Ga;Ga=[];for(let c of o)rH[c.localPort](null,c)}}}),r){let s=setInterval(()=>{wR?wR=!1:(clearInterval(s),console.log("shut down dynamic thread due to inactivity"),(0,Io.shutdownWorkers)(),IR=0,setTimeout(()=>{global.gc?.()},5e3))},1e4)}}function sH(e=0,t){if(typeof e=="string")try{(0,EE.existsSync)(e)&&(0,EE.unlinkSync)(e)}catch{}let r;t?t==="ip"?r=sse:r=nse(t):r=DR;let s=(0,Fa.createServer)({allowHalfOpen:!0,pauseOnConnect:!r.readsData}).listen(e);if(s._handle){s._handle.onconnection=rH[e]=function(i,o){r.readsData||(o.reading=!1,o.readStop()),wR=!0,r(o,(c,u)=>{if(!c){if(ZB){let l=o._socket||new Fa.Socket({handle:o,writable:!0,readable:!0});ZB.deliverSocket(l,e,u),l.resume()}else IR>0?(Ga.length===0&&setTimeout(()=>{Ga.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,Ga.push(o)):(console.log("start up a dynamic thread to handle request"),rse(0));Fr(!1,"socket-routed");return}c.requests++;let _=o.fd;if(_>=0)c.postMessage({port:e,fd:_,data:u});else{let l=o._socket||new Fa.Socket({handle:o,writable:!0,readable:!0});cse(l,c,e)}Fr(!0,"socket-routed")})};let n=eu();CR.info(`HarperDB ${n.version} Server running on port ${e}`)}return s.on("error",n=>{console.error("Error in socket server",n)}),process.env._UNREF_SERVER&&s.unref(),s}function DR(e,t){let r,s=0;for(let n of qa){if(n.threadId===-1)continue;let i=n.expectedIdle/n.requests;if(i>s)r=n;else if(s>=_E)return _E=i,t(r);s=i}_E=0,t(r)}function sse(e,t){let r={};e.getpeername(r);let s=r.address,n=ka.get(s),i=Date.now();if(n&&n.worker.threadId!==-1)return n.lastUsed=i,t(n.worker);DR(e,o=>{ka.set(s,{worker:o,lastUsed:i}),t(o)})}function nse(e){let t=new RegExp(`${e}:\\s*(.+)`,"i");return r.readsData=!0,r;function r(s,n){let i=new Fa.Socket({handle:s,readable:!0,writable:!0});s._socket=i,i.on("data",o=>{s.readStop();let u=o.toString("latin1").match(t)?.[1],_=ka.get(u),l=Date.now();if(_&&_.worker.threadId!==-1)return _.lastUsed=l,n(_.worker);DR(s,d=>{ka.set(u,{worker:d,lastUsed:l}),n(d,o)})})}a(r,"findByHeaderAffinity")}function ose(){_E=0;for(let e of qa)e.expectedIdle=e.recentELU.idle+ise,e.requests=1;qa.sort((e,t)=>e.expectedIdle>t.expectedIdle?-1:1)}function cse(e,t,r){let s=ase++;t.postMessage({port:r,requestId:s,event:"connection"}),e.on("data",n=>{let i=n.toString("latin1");t.postMessage({port:r,requestId:s,data:i,event:"data"})}).on("close",n=>{t.postMessage({port:r,requestId:s,event:"close",hadError:n})}).on("error",n=>{t.postMessage({port:r,requestId:s,event:"error",error:n})}).on("drain",n=>{t.postMessage({port:r,requestId:s,event:"drain",error:n})}).on("end",()=>{t.postMessage({port:r,requestId:s,event:"end"})}).resume(),dE.set(s,n=>{n.event=="data"&&e.write(Buffer.from(n.data,"latin1")),n.event=="end"&&(e.end(n.data&&Buffer.from(n.data,"latin1")),dE.delete(s)),n.event=="destroy"&&(e.destroy(),dE.delete(s))})}var Io,Fa,fE,CR,EE,tH,ese,qa,Ga,rH,ZB,IR,tse,wR,_E,eH,ka,ise,dE,ase,nH=Re(()=>{Io=x(Ke()),Fa=require("net"),fE=x(M()),CR=x($()),EE=require("fs");In();tH=require("worker_threads"),ese=x(Ji()),qa=[],Ga=[],rH=[],IR=0,tse=[];tH.isMainThread&&process.on("uncaughtException",e=>{e.code!=="ECONNRESET"&&e.message!=="write EIO"&&console.error("uncaughtException",e)});a(rse,"startHTTPWorker");a(sH,"startSocketServer");_E=0;a(DR,"findMostIdleWorker");eH=36e5,ka=new Map;a(sse,"findByRemoteAddressAffinity");a(nse,"makeFindByHeaderAffinity");setInterval(()=>{let e=Date.now();for(let[t,r]of ka)r.lastUsed+eH<e&&ka.delete(t)},eH).unref();ise=1e3;a(ose,"updateWorkerIdleness");(0,Io.setMonitorListener)(ose);dE=new Map,ase=1;a(cse,"proxySocket")});var PR={};Ye(PR,{Request:()=>LR,createReuseportFd:()=>hE});var iH,LR,MR,UR,hE,mE=Re(()=>{iH=require("os"),LR=class{static{a(this,"Request")}#e;constructor(t,r){this.method=t.method;let s=t.url;this._nodeRequest=t,this._nodeResponse=r,this.url=s,this.headers=new UR(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 MR(this._nodeRequest))}get host(){return this._nodeRequest.authority||this._nodeRequest.headers.host}get isAborted(){return!1}},MR=class{static{a(this,"RequestBody")}#e;constructor(t){this.#e=t}on(t,r){return this.#e.on(t,r),this}},UR=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,s]of this)t(s,r,this)}};(0,iH.platform)()!="win32"&&(hE=require("node-unix-socket").createReuseportFd)});var uH=g((dpe,cH)=>{"use strict";var use=require("cluster"),wo=ee();wo.initSync();var aH=M(),ape=require("util"),kn=$(),cpe=require("fs"),lse=require("fastify"),upe=eu(),_se=require("@fastify/cors"),dse=require("@fastify/compress"),fse=require("@fastify/static"),Ese=Yg(),hse=require("path"),{PACKAGE_ROOT:mse}=M(),pse=An(),Sse=Q(),Tse=is(),gse=Ji(),{server:Rse}=(or(),ne(Bi)),{node_request_key:lpe}=(mE(),ne(PR)),{authHandler:Ase,handlePostRequest:Ose,serverErrorHandler:bse,reqBodyValidationHandler:Nse}=lE(),_pe=require("net"),{registerContentHandlers:yse}=(Oa(),ne(Yv)),Ise=6e4,wse=1024*1024*1024,Cse="TRUE",{CONFIG_PARAMS:ll}=aH,Va;cH.exports={hdbServer:oH,start:oH};async function oH(e){try{kn.info("In Fastify server"+process.cwd()),kn.info(`Running with NODE_ENV set as: ${process.env.NODE_ENV}`),kn.debug(`HarperDB server process ${process.pid} starting up.`),global.clustering_on=!1,global.isMaster=use.isMaster,await Dse();let t=e.securePort>0;Va=Lse(t),await Va.ready(),e||(e={}),e.isOperationsServer=!0;try{Rse.http(Va.server,e),Va.server.closeIdleConnections||await Va.listen({port:0,host:"::"})}catch(r){throw Va.close(),kn.error(r),kn.error("Error configuring operations server"),r}}catch(t){console.error(`Failed to build server on ${process.pid}`,t),kn.fatal(t),process.exit(1)}}a(oH,"operationsServer");async function Dse(){kn.trace("Configuring HarperDB process."),pse.setSchemaDataToGlobal(),await Tse.setUsersToGlobal(),await gse.getLicense()}a(Dse,"setUp");function Lse(e){kn.debug(`HarperDB process starting to build ${e?"HTTPS":"HTTP"} server.`);let t=Mse(e),r=lse(t);r.server.headersTimeout=Pse(),r.setErrorHandler(bse);let s=Use();s&&r.register(_se,s),r.register(function(i,o,c){i.setNotFoundHandler(function(u,_){r.server.emit("unhandled",u.raw,_.raw)}),c()}),r.register(Ese),r.register(dse),r.register(fse,{root:hse.join(mse,"studio/build-local")}),yse(r);let n=wo.get(aH.HDB_SETTINGS_NAMES.LOCAL_STUDIO_ON);return r.get("/",function(i,o){return!Sse.isEmpty(n)&&n.toString().toLowerCase()==="true"?o.sendFile("index.html"):o.sendFile("running.html")}),r.post("/",{preValidation:[Nse,Ase],config:{isOperation:!0}},async function(i,o){return i.body?.operation?.startsWith("restart")&&o.header("Connection","close"),Ose(i,o)}),r.get("/health",()=>"HarperDB is running."),kn.debug(`HarperDB process starting up ${e?"HTTPS":"HTTP"} server listener.`),r}a(Lse,"buildServer");function Mse(e){let t=wo.get(ll.OPERATIONSAPI_NETWORK_TIMEOUT),r=wo.get(ll.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT);return{bodyLimit:wse,connectionTimeout:t,keepAliveTimeout:r,forceCloseConnections:!0,return503OnClosing:!1,https:e}}a(Mse,"getServerOptions");function Use(){let e=wo.get(ll.OPERATIONSAPI_NETWORK_CORS),t=wo.get(ll.OPERATIONSAPI_NETWORK_CORSACCESSLIST),r;return e&&(e===!0||e.toUpperCase()===Cse)&&(r={origin:!0,allowedHeaders:["Content-Type","Authorization","Accept"],credentials:!1},t&&t.length>0&&t[0]!==null&&t[0]!=="*"&&(r.origin=(s,n)=>n(null,t.indexOf(s)!==-1))),r}a(Use,"getCORSOpts");function Pse(){return wo.get(ll.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT)??Ise}a(Pse,"getHeaderTimeoutConfig")});var GR={};Ye(GR,{disableNATS:()=>Bse,publishToStream:()=>TE,setNATSReplicator:()=>vR,setPublishToStream:()=>Hse,setSubscription:()=>qR,start:()=>vse});function vse(){_l.default.get(dl.default.CONFIG_PARAMS.CLUSTERING_ENABLED)&&qse()}function Bse(e=!0){EH=e}function Hse(e,t){TE=e,qR=t}function qse(){if(EH||process.env._DISABLE_NATS)return;let e=Us(),t=Object.keys(e);t.push("system");for(let r of t){let s=e[r];for(let n in s){let i=s[n];vR(n,r,i)}}FR((r,s)=>{vR(r.tableName,r.databaseName,r),s&&mH(r)}),!lH&&(lH=!0)}function vR(e,t,r){if(!r)return console.error(`Attempt to replicate non-existent table ${e} from database ${t}`);if(r.sources.some(n=>n?.isNATSReplicator))return;r.sourcedFrom(class extends Ft{static{a(this,"NATSReplicator")}put(i){return s(this.getContext()).addWrite(t,{operation:"put",table:e,id:this[Me],record:i})}delete(){return s(this.getContext()).addWrite(t,{operation:"delete",table:e,id:this[Me]})}publish(i){return s(this.getContext()).addWrite(t,{operation:"publish",table:e,id:this[Me],record:i})}patch(i){return s(this.getContext()).addWrite(t,{operation:"patch",table:e,id:this[Me],record:i})}invalidate(){s(this.getContext()).addWrite(t,{operation:"invalidate",table:e,id:this[Me]})}static defineSchema(i){mH(i)}static subscribe(){let i=new bs;return qR(t,e,i),i}static subscribeOnThisThread(i){return i<(_l.default.get(dl.default.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXINGESTTHREADS)??xse)}static isEqual(i){return i.isNATSReplicator}static isNATSReplicator=!0;static shouldReceiveInvalidations=!0},{intermediateSource:!0});function s(n){let i=n?.transaction?.nats;if(!i)if(n?.transaction){n.transaction.nats=i=new pE(n.transaction,n);let o=n.transaction;for(;o.next;)o=o.next;o.next=n.transaction.nats,i.user=n.user,i.context=n}else i=hH;return i}a(s,"getNATSTransaction")}function mH(e){let t=_l.default.get(dl.default.CONFIG_PARAMS.CLUSTERING_NODENAME);TE(`${HR.SUBJECT_PREFIXES.TXN}.${e.databaseName}.${e.tableName}`,(0,xR.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 _H,HR,xR,dH,fH,_l,dl,SE,EH,TE,qR,xse,hH,lH,pE,BR,pH=Re(()=>{Ae();Ns();_H=x(nt()),HR=x(Fe()),xR=x(Rn());pc();dH=x(TS()),fH=x(wr()),_l=x(ee()),dl=x(M()),SE=x($());a(vse,"start");a(Bse,"disableNATS");TE=_H.publishToStream,qR=dH.setSubscription;a(Hse,"setPublishToStream");xse=2;a(qse,"assignReplicationSource");a(vR,"setNATSReplicator");a(mH,"publishSchema");pE=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 s=this.writes_by_db.get(t);s||this.writes_by_db.set(t,s=[]),s.push(r)}commit({timestamp:t}){let r=_l.default.get(dl.default.CONFIG_PARAMS.CLUSTERING_NODENAME),s=[];for(let[n,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:n,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&&s.push(TE(`${HR.SUBJECT_PREFIXES.TXN}.${n}.${u.table}`,(0,xR.createNatsTableStreamName)(n,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(s)}},BR=class extends pE{static{a(this,"ImmmediateNATSTransaction")}constructor(){super({get timestamp(){return(0,fH.getNextMonotonicTime)()}})}addWrite(t,r){super.addWrite(t,r),this.commit({})}};hH=new BR});var MH=g(Co=>{"use strict";var{isMainThread:OH,parentPort:El,threadId:gE}=require("worker_threads"),{Socket:Gse,createServer:Fse}=require("net"),{createServer:kse,IncomingMessage:Vse}=require("http"),{createServer:$se}=require("https"),{readFileSync:$a,unlinkSync:SH,existsSync:Yse}=require("fs"),rr=$(),we=ee(),ft=M(),{server:bE}=(or(),ne(Bi)),{WebSocketServer:Kse}=require("ws"),{createServer:Wse}=require("tls"),{getTicketKeys:Qse,restartNumber:zse,getWorkerIndex:AE}=Ke(),{Headers:bH,appendHeader:Jse}=(qu(),ne(hP)),{recordAction:fl,recordActionBinary:Xse}=(In(),ne(iu)),{Request:NH,createReuseportFd:TH}=(mE(),ne(PR)),{checkMemoryLimit:jse}=Ji(),yH=require("tls"),gH=yH.createSecureContext;yH.createSecureContext=function(e){if(!e.cert||!e.key)return gH(e);let t={...e};delete t.key,delete t.cert;let r=gH(t);return r.context.setCert(e.cert),r.context.setKey(e.key,void 0),r};var IH=we.get(ft.CONFIG_PARAMS.THREADS_DEBUG);if(IH){let e;if(OH)e=we.get(ft.CONFIG_PARAMS.THREADS_DEBUG_PORT)??9229,process.on(["SIGINT","SIGTERM","SIGQUIT","exit"],()=>{try{require("inspector").close()}catch(t){rr.info("Could not close debugger",t)}});else{let t=we.get(ft.CONFIG_PARAMS.THREADS_DEBUG_STARTINGPORT);t&&AE()>=0&&(e=t+AE())}if(e){let t=we.get(ft.CONFIG_PARAMS.THREADS_DEBUG_HOST),r=we.get(ft.CONFIG_PARAMS.THREADS_DEBUG_WAITFORDEBUGGER);try{require("inspector").open(e,t,r)}catch(s){rr.trace(`Could not start debugging on port ${e}, you may already be debugging:`,s.message)}}}else if(process.env.DEV_MODE)try{require("inspector").open(9229)}catch(e){zse<=1&&rr.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:Tpe,CONFIG_PARAMS:Zse}=ft;we.initSync();var ene=we.get(Zse.HTTP_SESSIONAFFINITY),fn={};Co.registerServer=KR;Co.httpServer=WR;Co.deliverSocket=YR;Co.startServers=wH;Co.when_components_loaded=null;bE.http=WR;bE.request=nne;bE.socket=ine;bE.ws=one;var kR={},RE={},tne,wi={},OE={},rne=[],VR=[];function wH(){return Co.when_components_loaded=QR().loadRootComponents(!0).then(()=>{El?.on("message",t=>{let{port:r,fd:s,data:n}=t;if(s)YR(s,r,n);else if(t.requestId)sne(t);else if(t.type===ft.ITC_EVENT_TYPES.SHUTDOWN){rr.trace("received shutdown request",gE);for(let i in fn){let o=fn[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?rr.info(`Closing ${E.length} idle connections`):f&&rr.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
|
|
28
|
+
`},compressible:!1,q:.8});xt.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()}});d0={type:"application/json",serializeStream:Ac,serialize:al,deserialize:Vee,q:.8};xt.set("*/*",d0);xt.set("",d0);a(Vee,"tryJSONParse");a(Vg,"registerContentHandlers");$ee=require("fastify-plugin"),Yee=$ee(function(e,t,r){e.addHook("preSerialization",async(n,s)=>{if(s.raw.getHeader("content-type"))return;let{serializer:o,type:c}=Vf(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(Vf,"findBestSerializer");a0=Gg.default.get(qg.CONFIG_PARAMS.HTTP_COMPRESSIONTHRESHOLD);a($f,"serialize");a(bi,"serializeMessage");a(Kee,"streamToBuffer");a(Oo,"getDeserializer");a(c0,"deserializerUnknownType");a(Wee,"transformIterable")});function Kg(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?Kg(d.conditions,d.operator,r,n,s,i,o,c):va(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",R=l(h.conditions,!A,E);return A?(M,x)=>R.some(P=>P(M,x)):(M,x)=>R.every(P=>P(M,x))}let S=(h.attribute||h[0])===r.primaryKey,T=Qg(h,r,i,c,S,E);return f&&p<d.length-1&&E&&(E=rte(r.primaryStore,h.estimated_count,E)),T}).filter(Boolean)}a(l,"mapConditionsToFilters")}function va(e,t,r,n,s,i){let o=e[0]??e.attribute,c=e[1]??e.value,u=e.comparator;if(Array.isArray(o)){let A=o[0],R=Gs(n.attributes,A);if(R.relationship){if(o.length<2)throw new Wr.ClientError("Can not directly query a relational attribute, must query an attribute within the target table");let M=R.definition?.tableClass||R.elements?.definition?.tableClass,x=new Map,P=va({attribute:o.length>2?o.slice(1):o[1],value:c,comparator:u},t,r,M,s,x);if(R.relationship.to){i[o[0]]=x;let k=!!Gs(M.attributes,R.relationship.to)?.elements;P=jee(P,R,M.primaryStore,k,x)}if(R.relationship.from){let k=a(B=>va({attribute:R.relationship.from,value:B},t,r,n,s,x),"searchEntry");R.elements?(i[o[0]]=x,P=Zee(P,R,M.primaryStore,x,k)):P=P.flatMap(k)}return P}else if(o.length===1)o=o[0];else throw new Wr.ClientError("Unable to query by attribute "+JSON.stringify(o))}let _,l,d,f;c instanceof Date&&(c=c.getTime());let E;switch(Wg[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]=ls.MAXIMUM_KEY;break;case"starts_with":_=c.toString(),l=c+"\uFFFF";break;case"between":_=c[0],_ instanceof Date&&(_=_.getTime()),l=c[1],l instanceof Date&&(l=l.getTime()),d=!0;break;case"equals":case void 0:_=c,l=c,d=!0;break;case"ne":if(c===null){_=c,f=!0;break}case"sort":case"contains":case"ends_with":_=!0,E=!0;break;default:throw new Wr.ClientError(`Unknown query comparator "${u}"`)}if(r){let A=_;_=l,l=A,A=!f,f=!d,d=A}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===!1&&!p)throw new Wr.ClientError(`"${o}" is not indexed, can not search for this attribute`,404);if(s===!1&&E)throw new Wr.ClientError(`Can not use ${u||"equal"} operator without combining with a condition that uses an index, can not search for attribute ${o}`,403);if(p?.isIndexing)throw new Wr.ServerError(`"${o}" is not indexed yet, can not search for this attribute`,503);if(c===null&&!p.indexNulls)throw new Wr.ClientError(`"${o}" is not indexed for nulls, index needs to be rebuilt to search for nulls, can not search for this attribute`,400);if(S=Qg(e),!S)throw new Wr.ClientError(`Unknown search operator ${e.comparator}`)}let T={start:_,end:l,inclusiveEnd:d,exclusiveStart:f,values:!0,versions:h,transaction:t,reverse:r};if(h){let A=p.getRange(T).map(S?function({key:R,value:M}){return this.isSync?M&&S(M)?R:Ii.SKIP:new Promise((x,P)=>setImmediate(()=>{try{x(M&&S(M)?R:Ii.SKIP)}catch(k){P(k)}}))}:R=>R.value==null?Ii.SKIP:R);return A.hasEntries=!0,A}else return p?p.getRange(T).map(S?function({key:A,value:R}){return this.isSync?S({[o]:A})?R:Ii.SKIP:new Promise((M,x)=>setImmediate(()=>{try{M(S({[o]:A})?R:Ii.SKIP)}catch(P){x(P)}}))}:({value:A})=>A):n.primaryStore.getRange(r?{end:!0,transaction:t,reverse:!0}:{start:!0,transaction:t}).map(function({key:A,value:R}){return this.isSync?R&&S(R)?A:Ii.SKIP:new Promise((M,x)=>setImmediate(()=>{try{M(R&&S(R)?A:Ii.SKIP)}catch(P){x(P)}}))})}function Gs(e,t){if(Array.isArray(t))if(t.length>1){let r=Gs(e,t[0]),n=(r?.definition?.tableClass||r?.elements.definition?.tableClass)?.attributes;return n?Gs(n,t.slice(1)):void 0}else t=t.toString();else typeof t!="string"&&(t=t.toString());return e.find(r=>r.name===t)}function jee(e,t,r,n,s){return new e.constructor({[Symbol.iterator](){let i;s.hasMappings=!0;let o;return{next(){if(!i){let u=t.relationship.to,_=a((l,d)=>{let f=l;Array.isArray(l)&&(f=Gn(l),o=!0);let E=s.get(f);E?E.push(d):s.set(f,E=[d]),l!==f&&(E.key=l)},"add_entry");for(let l of e){let d=l.value??r.get(l.key??l),f=d?.[u];if(f!=null&&!s.filters?.some(E=>!E(d)))if(n)for(let E=0;E<f.length;E++)_(f[E],l);else _(f,l)}return i=(o?s:s.keys())[Symbol.iterator](),this.next()}let c=i.next();return c.done?c:{value:o?c.value[1].key||c.value[0]:c.value}}}}})}function Zee(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 _=Gn(u.value);if(!c.has(_))return c.add(_),u}if(!i){let _=new Map;n.fromRecord=l=>l[t.relationship.from]?.filter?.(d=>_.has(Gn(d)));for(let l of e){if(n.filters){let d=r.get(l);if(n.filters.some(f=>!f(d)))continue}_.set(Gn(l),l)}return i=_.values()[Symbol.iterator](),this.next()}do{let _=i.next();return _.done?_:(o=s(_.value)[Symbol.iterator](),this.next())}while(!0)},return(){return o?.return?.()},throw(){return o?.throw?.()}}}})}function Qg(e,t,r,n,s,i){let o=e.comparator,c=e[0]??e.attribute,u=e[1]??e.value;if(Array.isArray(c)){if(c.length===0)return()=>!0;if(c.length===1)c=c[0];else if(c.length>1){let l=c[0],d=Gs(t.attributes,l),f=d.definition?.tableClass||d.elements.definition?.tableClass,E=n?.[l],h=Qg({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,R)=>{let M,x;if(p){if(p.from&&h.idFilter){if(!S)if(h.idFilter.idSet?.size===1){for(let k of h.idFilter.idSet)e={attribute:p.from,value:k};S=_(p.from,h.idFilter,!0,!0)}else S=_(p.from,h.idFilter,!1,!0);let P=S(A);return S.idFilter&&(T.idFilter=S.idFilter),P}x=p(A,r,R),M=x?.value}else M=A[l];return M?Array.isArray(M)?M.some(h):h(M,x):!1},"recordFilter");return T}}switch(u instanceof Date&&(u=u.getTime()),Wg[o]||o){case $g.SEARCH_TYPES.EQUALS:case void 0:return _(c,l=>l===u,!0);case"contains":return _(c,l=>l?.toString().includes(u));case"ends_with":return _(c,l=>l?.toString().endsWith(u));case"starts_with":return _(c,l=>typeof l=="string"&&l.startsWith(u),!0);case"prefix":return Array.isArray(u)?u[u.length-1]==null&&(u=u.slice(0,-1)):u=[u],_(c,l=>{if(!Array.isArray(l))return!1;for(let d=0,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,ls.compareKeys)(l,u[0])>=0&&(0,ls.compareKeys)(l,u[1])<=0,!0);case"gt":return _(c,l=>(0,ls.compareKeys)(l,u)>0);case"ge":return _(c,l=>(0,ls.compareKeys)(l,u)>=0);case"lt":return _(c,l=>(0,ls.compareKeys)(l,u)<0);case"le":return _(c,l=>(0,ls.compareKeys)(l,u)<=0);case"ne":return _(c,l=>(0,ls.compareKeys)(l,u)!==0);case"sort":return()=>!0;default:throw new Wr.ClientError(`Unknown query comparator "${o}"`)}function _(l,d,f,E){let h;f=f&&!s&&t?.indices[l]&&i>3,f&&(e.estimated_count==null&&Kf(t)(e),h=e.estimated_count>>4,(isNaN(h)||h>=i)&&(f=!1));let p=0,S=3;function T(A){let R=A[l],M;if(typeof R!="object"||!R||E?M=d(R):Array.isArray(R)?M=R.some(d):R instanceof Date&&(M=d(R.getTime())),f&&(S++,!M&&!T.idFilter&&++p/S*(i-S)>h)){let x=va(e,r.transaction.getReadTxn(),!1,t).map(Gn),P=new Set(x);T.idFilter=k=>P.has(Gn(k)),T.idFilter.idSet=P}return M}return a(T,"recordFilter"),s&&(T.idFilter=d),T}a(_,"attributeComparator")}function Kf(e){function t(r){if(r.estimated_count===void 0){if(r.conditions){let s;if(r.operator==="or"){s=0;for(let i of r.conditions)t(i),s+=i.estimated_count}else{s=1/0;for(let i of r.conditions)t(i),s=isFinite(s)?s*i.estimated_count/xs(e.primaryStore):i.estimated_count}return r.estimated_count=s,r.estimated_count}let n=r.comparator||r.search_type;if(n=Wg[n]||n,n===$g.SEARCH_TYPES.EQUALS||!n){let s=r[0]??r.attribute;if(s==null||s===e.primaryKey)r.estimated_count=1;else if(Array.isArray(s)&&s.length>1){let i=Gs(e.attributes,s[0]),o=i.definition?.tableClass||i.elements.definition?.tableClass,c=Kf(o)({value:r.value,attribute:s.length>2?s.slice(1):s[1],comparator:"equals"}),u=e.indices[i.relationship.from];r.estimated_count=c+(u?c*xs(e.indices[i.relationship.from])/(xs(o.primaryStore)||1):c)}else{let i=e.indices[s];r.estimated_count=i?i.getValuesCount(r[1]??r.value):1/0}}else if(n==="contains"||n==="ends_with"||n==="ne"){let s=r[0]??r.attribute,i=e.indices[s];r.value===null&&n==="ne"?r.estimated_count=xs(e.primaryStore)-(i?i.getValuesCount(null):0):r.estimated_count=1/0}else n==="starts_with"||n==="prefix"?r.estimated_count=Jee*xs(e.primaryStore)+1:n==="between"?r.estimated_count=zee*xs(e.primaryStore)+1:n==="sort"?r.estimated_count=xs(e.primaryStore)+1:r.estimated_count=Qee*xs(e.primaryStore)+1;typeof r.descending=="boolean"&&(r.estimated_count/=2)}return r.estimated_count}return a(t,"estimateConditionForTable"),t}function Wf(e){if(e)if(wi=e,Ua.lastIndex=0,ete.test(e))try{let t=ul(new Pa,"");if(yr!==wi.length)throw new SyntaxError("Unable to parse query, unexpected end of query");return t}catch(t){throw t.statusCode=400,t.message=`Unable to parse query, ${t.message} at position ${yr} in '${wi}'`,t}else{let t=new URLSearchParams(e);return t.conditions=t,t}}function ul(e,t){let r=Ua,n,s,i,o,c,u=decodeURIComponent,_;for(;n=r.exec(wi);){yr=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=E0}else{if(u=decodeURIComponent,i="equals",!l)throw new SyntaxError("attribute must be specified before equality comparator");s=ll(l)}break;case"==":case"!=":case"<":case"<=":case">":case">=":case"===":case"!==":if(i=Xee[d],u=Yg[i]?E0:decodeURIComponent,!l)throw new SyntaxError(`attribute must be specified before comparator ${d}`);s=ll(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"&&h0(h,l),Yf(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(ll(l)),s=void 0;break;case"(":Ua.lastIndex=yr;let E=ul(l?[]:new Pa,")");switch(l){case"":Yf(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=m0(E);break;default:throw new SyntaxError(`unknown query function call ${l}`)}wi[yr]===","?r.lastIndex=++yr: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");Ua.lastIndex=yr,f=ul([],"}"),f.name=l,e.push(f),wi[yr]===","?r.lastIndex=++yr:o=!0;break;case"[":Ua.lastIndex=yr,l?(f=ul(new Pa,"]"),f.name=l):f=ul(e.conditions?new Pa:[],"]"),e.conditions?(Yf(e,_),e.conditions.push(f),s=null):e.push(f),wi[yr]===","?r.lastIndex=++yr: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"&&h0(h,l),Yf(e,_),e.conditions.push(h)}else if(l)throw new SyntaxError("no attribute or comparison specified")}else(l||e.length>0&&c)&&e.push(ll(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?tte:Ua,r.lastIndex=yr),yr===wi.length)return e}if(t)throw new SyntaxError(`expected '${t}', but encountered end of string`)}function Yf(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 ll(e){return e.indexOf(".")>-1?e.split(".").map(ll):decodeURIComponent(e)}function E0(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 Wr.ClientError(`Unknown type ${t}`)}return decodeURIComponent(e)}function h0(e,t){if(t.indexOf("*")>-1)if(t.endsWith("*"))e.comparator="starts_with",e.value=decodeURIComponent(t.slice(0,-1));else throw new Wr.ClientError("wildcard can only be used at the end of a string")}function m0(e){let t=p0(e[0]);return e.length>1&&(t.next=m0(e.slice(1))),t}function p0(e){if(Array.isArray(e)){let t=p0(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 Gn(e){return Array.isArray(e)?e.join("\0"):e}function xs(e){let t=Date.now();return(e.estimatedEntryCountExpires||0)<t&&(e.estimatedEntryCount=e.getStats().entryCount,e.estimatedEntryCountExpires=t+1e4),e.estimatedEntryCount}function rte(e,t,r){return t*r/xs(e)}var Wr,$g,ls,Ii,Qee,zee,Jee,Xee,Yg,Wg,ete,Ua,tte,yr,wi,Pa,Qf=ge(()=>{Wr=v(ne()),$g=v(ut()),ls=require("ordered-binary"),Ii=require("lmdb"),Qee=.3,zee=.1,Jee=.05,Xee={"<":"lt","<=":"le",">":"gt",">=":"ge","!=":"ne","==":"eq","===":"equals","!==":"not_equal"},Yg={lt:!0,le:!0,gt:!0,ge:!0,ne:!0,eq:!0};a(Kg,"executeConditions");a(va,"searchByIndex");a(Gs,"findAttribute");a(jee,"joinTo");a(Zee,"joinFrom");Wg={eq:"equals",greater_than:"gt",greaterThan:"gt",greater_than_equal:"ge",greaterThanEqual:"ge",less_than:"lt",lessThan:"lt",less_than_equal:"le",lessThanEqual:"le",not_equal:"ne",notEqual:"ne",equal:"equals",sw:"starts_with",startsWith:"starts_with",ew:"ends_with",endsWith:"ends_with",ct:"contains",">":"gt",">=":"ge","<":"lt","<=":"le","...":"between"};a(Qg,"filterByType");a(Kf,"estimateCondition");ete=/[()[\]|!<>.]|(=\w*=)/,Ua=/([^?&|=<>!([{}\]),]*)([([{}\])|,&]|[=<>!]*)/g,tte=/([^&|=[\]{}]+)([[\]{}]|[&|=]*)/g;a(Wf,"parseQuery");a(ul,"parseBlock");a(Yf,"assignOperator");a(ll,"decodeProperty");a(E0,"typedDecoding");a(h0,"wildcardDecoding");a(m0,"toSortObject");a(p0,"toSortEntry");Pa=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(Gn,"flattenKey");a(xs,"estimatedEntryCount");a(rte,"intersectionEstimate")});function A0(e){let t={openapi:nte,info:{title:"HarperDB HTTP REST interface",version:(0,R0.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:M,elements:x,relationship:P,definition:k}of o){if(P)R==="array"?_[M]={type:"array",items:{$ref:Ci+x.type}}:_[M]={$ref:Ci+R};else{let B=k??x?.definition;if(B){if(!t.components.schemas[B.type]){let X={};B.properties.forEach(z=>{X[z.name]=new jg(zg[z.type],z.type)}),t.components.schemas[B.type]=new g0(X)}R==="array"?_[M]={type:"array",items:{$ref:Ci+B.type}}:_[M]={$ref:Ci+B.type}}else R==="array"?x.type==="Any"||x.type=="ID"?_[M]={type:"array",items:{format:x.type}}:_[M]={type:"array",items:new jg(zg[x.type],x.type)}:R==="Any"||R=="ID"?_[M]={format:R}:_[M]=new jg(zg[R],R)}l.push(new Zg(M,"query",_[M]))}let d=Object.keys(_),f=new Zg(c,"path",{format:"ID"});f.required=!0,f.description="primary key of record";let E=new Zg("property","path",{enum:d});E.required=!0,t.components.schemas[i]=new g0(_);let h=u.post!==Resource.prototype.post||u.update,p=typeof u.put=="function",S=typeof u.get=="function",T=typeof u.delete=="function",A="/"+s+"/";h&&(t.paths[A]={},t.paths[A].post=new ste(i,r,"create a new record auto-assigning a primary key")),S&&(t.paths[A]||(t.paths[A]={}),t.paths[A].get=new Jg(l,r,{200:new Xg({$ref:Ci+i})},"search for records by the specified property name and value pairs")),T&&(t.paths[A]||(t.paths[A]={}),t.paths[A].delete=new T0(l,r,"delete all the records that match the provided query",{204:new S0})),A="/"+s+"/{"+c+"}",S&&(t.paths[A]={},t.paths[A].get=new Jg([f],r,{200:new Xg({$ref:Ci+i})},"retrieve a record by its primary key")),p&&(t.paths[A]||(t.paths[A]={}),t.paths[A].put=new ite([f],r,i,"create or update the record with the URL path that maps to the record's primary key")),T&&(t.paths[A]||(t.paths[A]={}),t.paths[A].delete=new T0([f],r,"delete a record with the given primary key",{204:new S0})),S&&E.schema.enum.length>0&&(A="/"+s+"/{"+c+"}.{property}",t.paths[A]={},t.paths[A].get=new Jg([f,E],r,{200:new Xg({enum:d})},"used to retrieve the specified property of the specified record"))}return t}function ste(e,t,r){this.description=r,this.requestBody={content:{"application/json":{schema:{$ref:Ci+e}}}},this.security=t,this.responses={200:{description:eR,headers:{Location:{description:"primary key of new record",schema:{type:"string",format:"ID"}}},content:{"application/json":{schema:{type:"string",format:"ID"}}}}}}function Jg(e,t,r,n){this.description=n,this.parameters=e,this.security=t,this.responses=r}function Xg(e){this.description=eR,this.content={"application/json":{schema:e}}}function S0(){this.description="successfully processed request, no content returned to client"}function ite(e,t,r,n){this.description=n,this.parameters=e,this.security=t,this.requestBody={content:{"application/json":{schema:{$ref:Ci+r}}}},this.responses={200:{description:eR}}}function T0(e,t,r,n){this.description=r,this.parameters=e,this.security=t,this.responses=n}function g0(e){this.type="object",this.properties=e}function jg(e,t){this.type=e,this.format=t}function Zg(e,t,r){this.name=e,this.in=t,this.schema=r}var R0,nte,zg,Ci,eR,O0=ge(()=>{R0=v(Vd()),nte="3.0.3",zg={Int:"integer",Float:"number",Long:"integer",String:"string",Boolean:"boolean",Date:"string",Bytes:"string",BigInt:"integer",array:"array"},Ci="#/components/schemas/",eR="successful operation";a(A0,"generateJsonApi");a(ste,"Post");a(Jg,"Get");a(Xg,"Response200");a(S0,"Response204");a(ite,"Put");a(T0,"Delete");a(g0,"ResourceSchema");a(jg,"Type");a(Zg,"Parameter")});var Jf={};qe(Jf,{start:()=>cte});async function ate(e,t){let r=e.headers.asObject,n=r.accept==="text/event-stream"?"CONNECT":e.method;e.search&&Wf(e);let s=new Oi;try{e.responseHeaders=s;let i=e.url.slice(1),o,c;if(i!==b0){let h=zf.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 je(e,()=>{if(n==="POST"||n==="PUT"||n==="PATCH"||n==="QUERY")try{e.data=Oo(r["content-type"],!0)(e.body,e.headers)}catch(h){throw new Ba.ClientError(h,400)}if(e.authorize=!0,i===b0&&n==="GET"){if(e?.user?.role?.permission?.super_user)return A0(zf);throw new Ba.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 Ba.ClientError("HarperDB is short and stout and can't brew coffee",418);default:throw new Ba.ServerError(`Method ${n} is not recognized`,501)}}),l=200,d;if(_==null)l=n==="GET"||n==="HEAD"?404:204,tR.lastModified&&e.lastModified&&s.setIfNone("Last-Modified",new Date(e.lastModified).toUTCString());else if(d=e.lastModified){ote[0]=d;let h=String.fromCharCode(34,(Yt[0]&63)+62,(Yt[0]>>6)+(Yt[1]<<2&63)+62,(Yt[1]>>4)+(Yt[2]<<4&63)+62,(Yt[2]>>2)+62,(Yt[3]&63)+62,(Yt[3]>>6)+(Yt[4]<<2&63)+62,(Yt[4]>>4)+(Yt[5]<<4&63)+62,(Yt[5]>>2)+62,(Yt[6]&63)+62,(Yt[6]>>6)+(Yt[7]<<2&63)+62,34),p=r["if-none-match"];p&&h==p?(_?.onDone&&_.onDone(),l=304,_=void 0):s.setIfNone("ETag",h),tR.lastModified&&s.setIfNone("Last-Modified",new Date(d).toUTCString())}e.createdResource&&(l=201),e.newLocation&&s.setIfNone("Location",e.newLocation);let 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=$f(_,e,f),n==="HEAD"&&(f.body=void 0)),f}catch(i){i.statusCode?i.statusCode===500?bo.warn(i):bo.info(i):bo.error(i),i.statusCode===405&&(i.method&&(i.message+=` to handle HTTP method ${i.method.toUpperCase()||""}`),i.allow&&(i.allow.push("trace","head","options"),s.setIfNone("Allow",i.allow.map(c=>c.toUpperCase()).join(", "))));let o={status:i.statusCode||500,headers:s,body:void 0};return o.body=$f(i.contentType?i:i.toString(),e,o),o}}function cte(e){tR=e,!y0&&(y0=!0,zf=e.resources,e.server.http(async(t,r)=>{if(!t.isWebSocket)return ate(t,r)}),e.server.ws(async(t,r,n)=>{_l++;let s=new yn;N0||(N0=!0,uu(l=>{_l>0&&l.push({metric:"ws-connections",connections:_l,byThread:!0})}));let i;t.on("error",l=>{i=!0,bo.warn(l)});let o;t.on("message",a(function(d){o||(o=Oo(r.headers.asObject["content-type"]));let f=o(d);s.push(f)},"message"));let c;t.on("close",()=>{_l--,cn(!i,"connection","ws","disconnect"),s.emit("close"),c&&c.return()}),await n;let u=r.url.slice(1),_=zf.getMatch(u);if(cn(!!_,"connection","ws","connect"),!_)t.send(bi(`No resource was found to handle ${r.pathname}`,r));else{r.handlerPath=_.path,kr(h=>({count:h.count,total:_l}),"connections",r.handlerPath,"connect","ws");let l={url:_.relativeURL,async:!0},d=_.Resource;c=(await je(r,()=>d.connect(l,s,r)))[Symbol.asyncIterator]();let E;for(;!(E=await c.next()).done;){let h=bi(E.value,r);t.send(h),kr(h.length,"bytes-sent",r.handlerPath,"message","ws")}}t.close()}))}var bo,Ba,Yt,ote,tR,b0,y0,zf,N0,_l,I0=ge(()=>{Na();ws();bo=v($()),Ba=v(ne());Qf();gc();no();Wu();O0();Yt=new Uint8Array(8),ote=new Float64Array(Yt.buffer,0,1),tR={},b0="openapi";a(ate,"http");_l=0;a(cte,"start")});var rR=g((Bme,w0)=>{var{recordAction:Xf,recordActionBinary:ute}=(ws(),ie(lu)),lte=require("fastify-plugin"),_te=200;w0.exports=lte(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),Xf(o,"duration",_,d,l),ute(s.raw.statusCode<400,"success",_,d,l);let f=_te;i?.pipe?(i.on("data",h=>{f+=h.length}),i.on("end",()=>{Xf(performance.now()-c,"transfer",_,d,l),Xf(f,"bytes-sent",_,d,l)})):(f+=i?.length||0,Xf(f,"bytes-sent",_,d,l));let E=o.toFixed(3);s.header("Server-Timing",`db;dur=${E}`)}),r()},{name:"hdb-request-time"})});var cR=g((Gme,M0)=>{var tE=require("clone"),rE=Xe(),dte=Q(),Zf=L(),Hme=$(),nR=require("fs"),iR=require("joi"),{string:eE}=iR.types(),{hdb_errors:fte,handleHDBError:jf}=ne(),{HDB_ERROR_MSGS:xme,HTTP_STATUS_CODES:sR}=fte,{common_validators:Ha}=Jn(),C0=" is required",Ete=["insert","update","upsert"],oR={database:{presence:!1,format:Ha.schema_format,length:Ha.schema_length},schema:{presence:!1,format:Ha.schema_format,length:Ha.schema_length},table:{presence:!0,format:Ha.schema_format,length:Ha.schema_length},action:{inclusion:{within:Ete,message:"is required and must be either insert, update, or upsert"}},file_path:{},csv_url:{url:{allowLocal:!0}},data:{},passthrough_headers:{}},hte={schema:eE.required(),table:eE.required(),action:eE.valid("insert","update","upsert")},{AWS_ACCESS_KEY:mte,AWS_SECRET:pte,AWS_BUCKET:Ste,AWS_FILE_KEY:Tte,REGION:gte}=Zf.S3_BUCKET_AUTH_KEYS,Rte={s3:{presence:!0},[`s3.${mte}`]:{presence:!0,type:"String"},[`s3.${pte}`]:{presence:!0,type:"String"},[`s3.${Ste}`]:{presence:!0,type:"String"},[`s3.${Tte}`]:{presence:!0,type:"String",hasValidFileExt:[".csv",".json"]},[`s3.${gte}`]:{presence:!0,type:"String"}},D0=tE(oR);D0.data.presence={message:C0};var L0=tE(oR);L0.file_path.presence={message:C0};var Ate=Object.assign(tE(oR),Rte),aR=tE(hte);aR.csv_url=eE.uri().messages({"string.uri":"'csv_url' must be a valid url"}).required();aR.passthrough_headers=iR.object();function Ote(e){let t=rE.validateObject(e,D0);return nE(e,t)}a(Ote,"dataObject");function bte(e){let t=rE.validateBySchema(e,iR.object(aR));return nE(e,t)}a(bte,"urlObject");function yte(e){let t=rE.validateObject(e,L0);return nE(e,t)}a(yte,"fileObject");function Nte(e){let t=rE.validateObject(e,Ate);return nE(e,t)}a(Nte,"s3FileObject");function nE(e,t){if(!t){let r=dte.checkGlobalSchemaTable(e.schema,e.table);if(r)return jf(new Error,r,sR.BAD_REQUEST);if(e.operation===Zf.OPERATIONS_ENUM.CSV_FILE_LOAD)try{nR.accessSync(e.file_path,nR.constants.R_OK|nR.constants.F_OK)}catch(n){return n.code===Zf.NODE_ERROR_CODES.ENOENT?jf(n,`No such file or directory ${n.path}`,sR.BAD_REQUEST):n.code===Zf.NODE_ERROR_CODES.EACCES?jf(n,`Permission denied ${n.path}`,sR.BAD_REQUEST):jf(n)}}return t}a(nE,"postValidateChecks");M0.exports={dataObject:Ote,urlObject:bte,fileObject:yte,s3FileObject:Nte}});var uR=g((Fme,U0)=>{"use strict";var dl=$(),sE=L();async function Ite(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===sE.OPERATIONS_ENUM.INSERT||t.operation===sE.OPERATIONS_ENUM.UPDATE||t.operation===sE.OPERATIONS_ENUM.UPSERT?(delete s.new_attributes,delete s.txn_time):t.operation===sE.OPERATIONS_ENUM.DELETE&&delete s.txn_time,s}catch(i){throw i.message&&typeof i.message=="string"&&i.message.includes("already exists")?(dl.info(i.message),i):i.http_resp_msg?(dl.error(`Error calling operation: ${e.name}`),dl.error(i.http_resp_msg),i):(dl.error(`Error calling operation: ${e.name}`),dl.error(i),i)}}a(Ite,"callOperationFunctionAsAwait");U0.exports={callOperationFunctionAsAwait:Ite}});var v0=g((Vme,P0)=>{"use strict";var lR=class{static{a(this,"BulkLoadFileObject")}constructor(t,r,n,s,i,o,c=null){this.op=t,this.action=r,this.schema=n,this.table=s,this.file_path=i,this.file_type=o,this.role_perms=c}},_R=class{static{a(this,"BulkLoadDataObject")}constructor(t,r,n,s){this.action=t,this.schema=r,this.table=n,this.data=s}};P0.exports={BulkLoadFileObject:lR,BulkLoadDataObject:_R}});var H0=g((Yme,B0)=>{"use strict";var dR=class{static{a(this,"ClusteringOriginObject")}constructor(t,r,n){this.timestamp=t,this.user=r,this.node_name=n}};B0.exports=dR});var SR=g((Xme,eB)=>{"use strict";var iE=vr(),aE=cR(),wte=require("needle"),qn=L(),Wme=ke(),xa=Q(),{handleHDBError:ot,hdb_errors:K0}=ne(),{HTTP_STATUS_CODES:Kt,HDB_ERROR_MSGS:wt,CHECK_LOGS_WRAPPER:No}=K0,Ga=$(),fR=require("papaparse");xa.promisifyPapaParse();var Fn=require("fs-extra"),Cte=require("path"),{chain:x0}=require("stream-chain"),G0=require("stream-json/streamers/StreamArray"),q0=require("stream-json/utils/Batch"),F0=require("stream-chain/utils/comp"),{finished:k0}=require("stream"),Dte=ee(),W0=uR(),Lte=vg(),{BulkLoadFileObject:hR,BulkLoadDataObject:Mte}=v0(),mR=yg(),{verifyBulkLoadAttributePerms:Q0}=xf(),Qme=H0(),zme=it(),Jme=Rs(),{databases:Ute}=(Re(),ie(Fe)),{coerceType:Pte}=(cE(),ie(TR)),V0="No records parsed from csv file.",yo=`${Dte.get("HDB_ROOT")}/tmp`,{schema_regex:vte}=Jn(),$0=1024*1024*2,Y0=5e3,Bte={"text/csv":!0,"application/octet-stream":!0,"text/plain":!0,"application/vnd.ms-excel":!0};eB.exports={csvDataLoad:Hte,csvURLLoad:xte,csvFileLoad:Gte,importFromS3:qte};async function Hte(e,t){let r=aE.dataObject(e);if(r)throw ot(r,r.message,Kt.BAD_REQUEST,void 0,void 0,!0);let n={};try{let s=X0(e.schema,e.table),i=fR.parse(e.data,{header:!0,skipEmptyLines:!0,transform:ER.bind(null,s),dynamicTyping:!1}),o=new mR;e.hdb_user&&e.hdb_user.role&&e.hdb_user.role.permission&&e.hdb_user.role.permission.super_user!==!0&&Q0(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 ot(new Error,c,Kt.BAD_REQUEST,void 0,void 0,!0);let u=new Mte(e.action,e.schema,e.table,i.data);return n=await W0.callOperationFunctionAsAwait(j0,u,null),n.message===V0?V0:Z0(n.records,n.number_written)}catch(s){throw Io(s)}}a(Hte,"csvDataLoad");async function xte(e){let t=aE.urlObject(e);if(t)throw ot(t,t.message,Kt.BAD_REQUEST,void 0,void 0,!0);let r=`${Date.now()}.csv`,n=`${yo}/${r}`;try{await Fte(e,r)}catch(s){throw Ga.error(wt.DOWNLOAD_FILE_ERR(r)+" - "+s),ot(s,No(wt.DOWNLOAD_FILE_ERR(r)))}try{let s=new hR(this.job_operation_function.name,e.action,e.schema,e.table,n,qn.VALID_S3_FILE_TYPES.CSV,e.hdb_user.role.permission),i=await pR(s);return await oE(n),i}catch(s){throw await oE(n),Io(s)}}a(xte,"csvURLLoad");async function Gte(e){let t=aE.fileObject(e);if(t)throw ot(t,t.message,Kt.BAD_REQUEST,void 0,void 0,!0);let r=new hR(this.job_operation_function.name,e.action,e.schema,e.table,e.file_path,qn.VALID_S3_FILE_TYPES.CSV,e.hdb_user.role.permission);try{return await pR(r)}catch(n){throw Io(n)}}a(Gte,"csvFileLoad");async function qte(e){let t=aE.s3FileObject(e);if(t)throw ot(t,t.message,Kt.BAD_REQUEST,void 0,void 0,!0);let r;try{let n=Cte.extname(e.s3.key),s=`${Date.now()}${n}`;r=`${yo}/${s}`;let i=new hR(this.job_operation_function.name,e.action,e.schema,e.table,r,n,e.hdb_user.role.permission);await kte(s,e);let o=await pR(i);return await oE(r),o}catch(n){throw await oE(r),Io(n)}}a(qte,"importFromS3");async function Fte(e,t){let r;try{let n=e.passthrough_headers?{headers:e.passthrough_headers}:void 0;r=await wte("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 ot(n,s,n.statusCode,qn.LOG_LEVELS.ERROR,"Error downloading CSV file - "+n)}$te(r,e.csv_url),await Vte(t,r.raw)}a(Fte,"downloadCSVFile");async function kte(e,t){try{let r=`${yo}/${e}`;await Fn.mkdirp(yo),await Fn.writeFile(`${yo}/${e}`,"",{flag:"a+"});let n=await Fn.createWriteStream(r),s=await Lte.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(){Ga.info(`${t.s3.key} successfully downloaded to ${r}`),i()})})}catch(r){throw Ga.error(wt.S3_DOWNLOAD_ERR+" - "+r),ot(r,No(wt.S3_DOWNLOAD_ERR))}}a(kte,"downloadFileFromS3");async function Vte(e,t){try{await Fn.mkdirp(yo),await Fn.writeFile(`${yo}/${e}`,t)}catch(r){throw Ga.error(wt.WRITE_TEMP_FILE_ERR),ot(r,No(wt.DEFAULT_BULK_LOAD_ERR))}}a(Vte,"writeFileToTempFolder");async function oE(e){if(e)try{await Fn.access(e),await Fn.unlink(e)}catch{Ga.warn(`could not delete temp csv file at ${e}, file does not exist`)}}a(oE,"deleteTempFile");function $te(e,t){if(e.statusCode!==K0.HTTP_STATUS_CODES.OK)throw ot(new Error,`CSV Load failed from URL: ${t}, status code: ${e.statusCode}, message: ${e.statusMessage}`,Kt.BAD_REQUEST);if(!Bte[e.headers["content-type"]])throw ot(new Error,`CSV Load failed from URL: ${t}, unsupported content type: ${e.headers["content-type"]}`,Kt.BAD_REQUEST);if(!e.raw)throw ot(new Error,`CSV Load failed from URL: ${t}, no csv found at url`,Kt.BAD_REQUEST)}a($te,"validateURLResponse");async function pR(e){try{let t;switch(e.file_type){case qn.VALID_S3_FILE_TYPES.CSV:t=await Yte(e);break;case qn.VALID_S3_FILE_TYPES.JSON:t=await Kte(e);break;default:throw ot(new Error,wt.DEFAULT_BULK_LOAD_ERR,Kt.BAD_REQUEST,qn.LOG_LEVELS.ERROR,wt.INVALID_FILE_EXT_ERR(e))}return Z0(t.records,t.number_written)}catch(t){throw Io(t)}}a(pR,"fileLoad");async function z0(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 iE.validation(o);e.role_perms&&e.role_perms.super_user!==!0&&Q0(e.role_perms,e.op,e.action,e.schema,e.table,c,t),s&&s.resume()}catch(c){let u=ot(c);r(u)}}a(z0,"validateChunk");async function J0(e,t,r,n,s){let i=n.data?n.data:n;if(i.length===0)return;xa.autoCastJSONDeep(i),s&&s.pause();let o=n.meta?n.meta.fields:null;if(o)i.forEach(c=>{!xa.isEmpty(c)&&!xa.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 W0.callOperationFunctionAsAwait(j0,c,null);t.records+=u.records,t.number_written+=u.number_written,s&&s.resume()}catch(c){let u=ot(c,No(wt.INSERT_CSV_ERR),Kt.INTERNAL_SERVER_ERROR,qn.LOG_LEVELS.ERROR,wt.INSERT_CSV_ERR+" - "+c);r(u)}}a(J0,"insertChunk");async function Yte(e){let t={records:0,number_written:0},r=X0(e.schema,e.table);try{let n=new mR,s=Fn.createReadStream(e.file_path,{highWaterMark:$0});s.setEncoding("utf8"),await fR.parsePromise(s,z0.bind(null,e,n),ER.bind(null,r));let i=n.getPermsResponse();if(i)throw ot(new Error,i,Kt.BAD_REQUEST);return s=Fn.createReadStream(e.file_path,{highWaterMark:$0}),s.setEncoding("utf8"),await fR.parsePromise(s,J0.bind(null,e,t),ER.bind(null,r)),s.destroy(),t}catch(n){throw ot(n,No(wt.PAPA_PARSE_ERR),Kt.INTERNAL_SERVER_ERROR,qn.LOG_LEVELS.ERROR,wt.PAPA_PARSE_ERR+n)}}a(Yte,"callPapaParse");function X0(e,t){let r=Ute[e][t].attributes,n=new Map;for(let s of r)s.type&&n.set(s.name,i=>Pte(i,s));return n}a(X0,"createTransformMap");function ER(e,t,r){let n=e.get(r);return n?n(t):xa.autoCast(t)}a(ER,"typeFunction");async function Kte(e){let t={records:0,number_written:0},r=a(n=>{throw n},"throwErr");try{let n=new mR,s=x0([Fn.createReadStream(e.file_path,{encoding:"utf-8"}),G0.withParser(),c=>c.value,new q0({batchSize:Y0}),F0(async c=>{await z0(e,n,r,c)})]);await new Promise((c,u)=>{k0(s,_=>{_?u(_):c()}),s.resume()});let i=n.getPermsResponse();if(i)throw ot(new Error,i,Kt.BAD_REQUEST);let o=x0([Fn.createReadStream(e.file_path,{encoding:"utf-8"}),G0.withParser(),c=>c.value,new q0({batchSize:Y0}),F0(async c=>{await J0(e,t,r,c)})]);return await new Promise((c,u)=>{k0(o,_=>{_?u(_):c()}),o.resume()}),t}catch(n){throw ot(n,No(wt.INSERT_JSON_ERR),Kt.INTERNAL_SERVER_ERROR,qn.LOG_LEVELS.ERROR,wt.INSERT_JSON_ERR+n)}}a(Kte,"insertJson");async function j0(e){let t={};try{e.data&&e.data.length>0&&Wte(e.data[0])?t=await Qte(e.data,e.schema,e.table,e.action):(t.message="No records parsed from csv file.",Ga.info(t.message))}catch(r){throw Io(r)}return t}a(j0,"callBulkFileLoad");function Wte(e){let t=Object.keys(e);for(let r of t)if(!vte.test(r))throw new Error(`Invalid column name '${r}', cancelling load operation`);return!0}a(Wte,"validateColumnNames");async function Qte(e,t,r,n){n||(n="insert");let s={operation:n,schema:t,table:r,records:e},i;switch(n){case"insert":i=iE.insert;break;case"update":i=iE.update;break;case"upsert":i=iE.upsert;break;default:throw ot(new Error,wt.INVALID_ACTION_PARAM_ERR(n),Kt.BAD_REQUEST,qn.LOG_LEVELS.ERROR,wt.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=xa.isEmptyOrZeroLength(c)?0:c.length;return{records:e.length,number_written:u,new_attributes:o.new_attributes}}catch(o){throw Io(o)}}a(Qte,"bulkFileLoad");function Z0(e,t){return`successfully loaded ${t} of ${e} records`}a(Z0,"buildResponseMsg");function Io(e){return ot(e,No(wt.DEFAULT_BULK_LOAD_ERR),Kt.INTERNAL_SERVER_ERROR,qn.LOG_LEVELS.ERROR,wt.DEFAULT_BULK_LOAD_ERR+" - "+e)}a(Io,"buildTopLevelErrMsg")});var rB=g((Zme,tB)=>{"use strict";var gR=class{static{a(this,"SqlSearchObject")}constructor(t,r){this.operation="sql",this.sql=t,this.hdb_user=r}};tB.exports=gR});var iB=g((tpe,sB)=>{"use strict";var zte=L(),nB=require("moment"),Jte=require("uuid").v4,RR=class{static{a(this,"JobObject")}constructor(){this.id=Jte(),this.type=void 0,this.start_datetime=nB().valueOf(),this.created_datetime=nB().valueOf(),this.end_datetime=void 0,this.status=zte.JOB_STATUS_ENUM.CREATED,this.message=void 0,this.user=void 0,this.request=void 0}};sB.exports=RR});var AR=g((npe,_B)=>{"use strict";var Xte=require("uuid").v4,cB=vr(),uB=Pr(),jte=ts(),Zte=sa(),ere=rB(),at=L(),tre=iB(),rre=Bd(),mn=$(),nre=Bc(),qa=Q(),{promisify:sre}=require("util"),wo=require("moment"),ire=qf(),uE=cR(),oB=Ym(),{deleteTransactionLogsBeforeValidator:ore}=gg(),{handleHDBError:are,hdb_errors:cre}=ne(),{HTTP_STATUS_CODES:ure}=cre,aB=uB.searchByValue,lre=uB.searchByHash,_re=cB.insert,dre=sre(ire.evaluateSQL),fre=cB.update;_B.exports={addJob:mre,updateJob:Sre,handleGetJob:Ere,handleGetJobsByStartDate:hre,getJobById:lB};async function Ere(e){try{let t=await lB(e.id);return qa.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 mn.error("There was an error getting job",t),new Error(r)}}a(Ere,"handleGetJob");async function hre(e){try{let t=await pre(e);if(mn.trace(`Searching for jobs from ${e.from_date} to ${e.to_date}`),t&&t.length>0)for(let r of t)r.start_datetime&&(r.start_datetime_converted=wo(r.start_datetime)),r.end_datetime&&(r.end_datetime_converted=wo(r.end_datetime)),r.request!==void 0&&delete r.request,delete r.__createdtime__,delete r.__updatedtime__;return t}catch(t){let r=`There was an error searching jobs by date: ${t}`;throw mn.error(r),new Error(r)}}a(hre,"handleGetJobsByStartDate");async function mre(e){let t={message:"",error:"",success:!1,createdJob:void 0};if(!e||Object.keys(e).length===0||qa.isEmptyOrZeroLength(e.operation)){let l="job parameter is invalid";return mn.info(l),t.error=l,t}if(!at.JOB_TYPE_ENUM[e.operation])return mn.info(`invalid job type specified: ${e.operation}.`),t;let r=e.operation,n;switch(r){case at.OPERATIONS_ENUM.CSV_FILE_LOAD:n=uE.fileObject(e);break;case at.OPERATIONS_ENUM.CSV_URL_LOAD:n=uE.urlObject(e);break;case at.OPERATIONS_ENUM.CSV_DATA_LOAD:n=uE.dataObject(e);break;case at.OPERATIONS_ENUM.IMPORT_FROM_S3:n=uE.s3FileObject(e);break;case at.OPERATIONS_ENUM.DELETE_FILES_BEFORE:case at.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE:n=oB(e,"date");break;case at.OPERATIONS_ENUM.DELETE_AUDIT_LOGS_BEFORE:n=oB(e,"timestamp");break;case at.OPERATIONS_ENUM.DELETE_TRANSACTION_LOGS_BEFORE:n=ore(e);break;default:break}if(n)throw are(n,n.message,ure.BAD_REQUEST,void 0,void 0,!0);let s=new tre;s.type=e.operation===at.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE?at.OPERATIONS_ENUM.DELETE_FILES_BEFORE:e.operation,s.type=e.operation,s.user=e.hdb_user.username;let i=new jte(at.SYSTEM_SCHEMA_NAME,at.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,"id",s.id,"id",["id"]),o;try{o=Array.from(await aB(i))}catch(l){let d=`There was an error inserting a new job: ${l}`;return mn.error(d),t}let c=Array.isArray(o)?o:Object.keys(o);if(c&&c.length>0){s.id=Xte();try{o=await aB(i)}catch(l){let d=`There was an error inserting a new job: ${l}`;return mn.error(d),t}if(c=Array.isArray(o)?o:Object.keys(o),c&&c.length>0)return mn.error("Error creating a job, could not find a unique job id."),t}s.request=e;let u=new nre(at.SYSTEM_SCHEMA_NAME,at.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,"id",[s]),_;try{_=await _re(u)}catch(l){return mn.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,mn.trace(l)}return t}a(mre,"addJob");async function pre(e){let t=wo(e.from_date,wo.ISO_8601),r=wo(e.to_date,wo.ISO_8601);if(!t.isValid())throw new Error("Invalid 'from' date, must be in ISO-8601 format (YYYY-MM-DD).");if(!r.isValid())throw new Error("Invalid 'to' date, must be in ISO-8601 format (YYYY-MM-DD)");let n=`select * from system.hdb_job where start_datetime > '${t.valueOf()}' and start_datetime < '${r.valueOf()}'`,s=new ere(n,e.hdb_user);try{return await dre(s)}catch(i){throw mn.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(pre,"getJobsInDateRange");async function lB(e){if(qa.isEmptyOrZeroLength(e))return qa.errorizeMessage("Invalid job ID specified.");let t=new Zte(at.SYSTEM_SCHEMA_NAME,at.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,[e],["*"]);try{return await lre(t)}catch(r){let n=`There was an error searching for a job by id: ${e} ${r}`;return mn.error(n),qa.errorizeMessage("there was an error searching for jobs. Please check the log for details.")}}a(lB,"getJobById");async function Sre(e){if(Object.keys(e).length===0)throw new Error("invalid job object passed to updateJob");if(qa.isEmptyOrZeroLength(e.id))throw new Error("invalid ID passed to updateJob");(e.status===at.JOB_STATUS_ENUM.COMPLETE||e.status===at.JOB_STATUS_ENUM.ERROR)&&(e.end_datetime=wo().valueOf());let t=new rre(at.SYSTEM_SCHEMA_NAME,at.SYSTEM_TABLE_NAMES.JOB_TABLE_NAME,[e]),r;return r=await fre(t),r}a(Sre,"updateJob")});var pB=g((ipe,mB)=>{"use strict";var dB=Q(),Nr=L(),Tre=require("moment"),lE=SR(),_E=$(),fB=AR(),EB=Ff(),hB=ii(),gre=Ke(),Rre=Pf(),OR=class{static{a(this,"RunnerMessage")}constructor(t,r){this.job=t,this.json=r}};async function Are(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(dB.isEmptyOrZeroLength(e.json.operation))throw new Error("Invalid operation");if(dB.isEmptyOrZeroLength(e.job.id))throw new Error("Empty job id specified");switch(e.json.operation){case Nr.JOB_TYPE_ENUM.csv_file_load:await qs(e,lE.csvFileLoad);break;case Nr.JOB_TYPE_ENUM.csv_url_load:await qs(e,lE.csvURLLoad);break;case Nr.JOB_TYPE_ENUM.csv_data_load:await qs(e,lE.csvDataLoad);break;case Nr.JOB_TYPE_ENUM.import_from_s3:await qs(e,lE.importFromS3);break;case Nr.JOB_TYPE_ENUM.empty_trash:break;case Nr.JOB_TYPE_ENUM.export_local:await qs(e,EB.export_local);break;case Nr.JOB_TYPE_ENUM.export_to_s3:await qs(e,EB.export_to_s3);break;case Nr.JOB_TYPE_ENUM.delete_files_before:case Nr.JOB_TYPE_ENUM.delete_records_before:await qs(e,hB.deleteFilesBefore);break;case Nr.JOB_TYPE_ENUM.delete_audit_logs_before:await qs(e,hB.deleteAuditLogsBefore);break;case Nr.JOB_TYPE_ENUM.delete_transaction_logs_before:await qs(e,Rre.deleteTransactionLogsBefore);break;default:return`Invalid operation ${e.json.operation} specified`}}a(Are,"parseMessage");async function qs(e,t){try{e.job.status=Nr.JOB_STATUS_ENUM.IN_PROGRESS,e.job.start_datetime=Tre().valueOf(),await fB.updateJob(e.job),await Ore(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):_E.error(`There was an error running ${t.name} job with id ${e.job.id}`),_E.error(n),e.job.message=n,e.job.status=Nr.JOB_STATUS_ENUM.ERROR;try{await fB.updateJob(e.job)}catch(s){throw _E.error(`Unable to update job with id ${e.job.id}`),s}throw r}}a(qs,"runJob");async function Ore(e){_E.trace("launching job thread:",e),gre.startWorker("server/jobs/jobProcess.js",{autoRestart:!1,name:"job",env:Object.assign({},process.env,{[Nr.PROCESS_NAME_ENV_PROP]:`JOB-${e}`})})}a(Ore,"launchJobThread");mB.exports={parseMessage:Are,RunnerMessage:OR}});var TB=g((ape,SB)=>{"use strict";var bR=class{static{a(this,"OperationFunctionObject")}constructor(t,r=void 0){this.operation_function=t,this.job_operation_function=r}};SB.exports=bR});var BB=g((upe,DR)=>{"use strict";var mE=Pr(),IR=qf(),dE=SR(),Fs=Su(),fE=As(),El=ii(),bre=qS(),fl=an(),EE=zS(),Wt=Tg(),hE=$(),yre=jS(),Nre=zd(),gB=DT(),Ire=Xd(),wre=MT(),Cre=UT(),Dre=BT(),Lre=xT(),yR=FT(),RB=Ff(),Mre=xf(),wR=AR(),q=L(),{hdb_errors:ml,handleHDBError:hl}=ne(),{HTTP_STATUS_CODES:AB}=ml,NR=KT(),OB=Tf(),MB=require("util"),Fa=vr(),Ure=Os(),Pre=pa(),bB=pB(),yB=bu(),NB=(Of(),ie(Qu)),IB=lr(),wB=Pf(),CB=wf(),{setServerUtilities:vre}=(cE(),ie(TR)),{CONTEXT:Bre}=(Nn(),ie(Gp)),{_assignPackageExport:Hre}=require("../index"),{transformReq:xre}=Q(),{server:Gre}=(or(),ie(xi)),tr=hE.loggerWithTag("operation"),qre=uR(),DB=mE.searchByHash,Fre=mE.searchByValue,kre=MB.promisify(mE.search),Vre=MB.promisify(IR.evaluateSQL),$re={[q.OPERATIONS_ENUM.CREATE_ATTRIBUTE]:!0,[q.OPERATIONS_ENUM.CREATE_TABLE]:!0,[q.OPERATIONS_ENUM.CREATE_SCHEMA]:!0,[q.OPERATIONS_ENUM.DROP_ATTRIBUTE]:!0,[q.OPERATIONS_ENUM.DROP_TABLE]:!0,[q.OPERATIONS_ENUM.DROP_SCHEMA]:!0},Y=TB();async function UB(e,t){try{if(e.body.operation!=="read_log"&&(hE.log_level===q.LOG_LEVELS.INFO||hE.log_level===q.LOG_LEVELS.DEBUG||hE.log_level===q.LOG_LEVELS.TRACE)){let{hdb_user:n,hdb_auth_header:s,password:i,...o}=e.body;tr.info(o)}}catch(n){tr.error(n)}let r=await qre.callOperationFunctionAsAwait(t,e.body,null);if(typeof r!="object"&&(r={message:r}),r instanceof Error)throw r;return $re[e.body.operation]&&Ure.setSchemaDataToGlobal(n=>{n&&tr.error(n)}),r}a(UB,"processLocalTransaction");var LB=Kre();DR.exports={chooseOperation:PB,getOperationFunction:vB,operation:CR,processLocalTransaction:UB};vre(DR.exports);Gre.operation=CR;function PB(e){let t;try{t=vB(e)}catch(s){throw tr.error(`Error when selecting operation function - ${s}`),s}let{operation_function:r,job_operation_function:n}=t;try{if(e.operation==="sql"||e.search_operation&&e.search_operation.operation==="sql"){let s=e.operation==="sql"?e.sql:e.search_operation.sql,i=IR.convertSQLToAST(s);if(e.parsed_sql_object=i,!e.bypass_auth){let o=IR.checkASTPermissions(e,i);if(o)throw tr.error(`${AB.FORBIDDEN} from operation ${e.operation}`),tr.warn(`User '${e.hdb_user.username}' is not permitted to ${e.operation}`),hl(new Error,o,ml.HTTP_STATUS_CODES.FORBIDDEN,void 0,void 0,!0)}}else if(!e.bypass_auth&&e.operation!==q.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS&&e.operation!==q.OPERATIONS_ENUM.LOGIN&&e.operation!==q.OPERATIONS_ENUM.LOGOUT){let s=n===void 0?r:n,i=e.search_operation?e.search_operation:e;i.hdb_user||(i.hdb_user=e.hdb_user);let o=Mre.verifyPerms(i,s);if(o)throw tr.error(`${AB.FORBIDDEN} from operation ${e.operation}`),tr.warn(`User '${i.hdb_user.username}' is not permitted to ${i.operation}`),hl(new Error,o,ml.HTTP_STATUS_CODES.FORBIDDEN,void 0,!1,!0)}}catch(s){throw hl(s,"There was an error when trying to choose an operation path")}return r}a(PB,"chooseOperation");function vB(e){if(tr.trace(`getOperationFunction with operation: ${e.operation}`),LB.has(e.operation))return LB.get(e.operation);throw hl(new Error,ml.HDB_ERROR_MSGS.OP_NOT_FOUND(e.operation),ml.HTTP_STATUS_CODES.BAD_REQUEST,void 0,void 0,!0)}a(vB,"getOperationFunction");Hre("operation",CR);function CR(e,t){e.hdb_user=this[Bre]?.user,e.bypass_auth=!t;let r=PB(e);return UB({body:e},r)}a(CR,"operation");async function Yre(e){tr.trace("In serverUtils.catchup");let t=e.transaction,r=t.channel.split(":"),n=r[0],s=r[1];for(let i of t.transactions)try{i.schema=n,i.table=s,i[q.CLUSTERING_FLAG]=!0;let o;switch(i.operation){case q.OPERATIONS_ENUM.INSERT:o=await Fa.insert(i);break;case q.OPERATIONS_ENUM.UPDATE:o=await Fa.update(i);break;case q.OPERATIONS_ENUM.UPSERT:o=await Fa.upsert(i);break;case q.OPERATIONS_ENUM.DELETE:o=await El.deleteRecord(i);break;default:tr.warn("invalid operation in catchup");break}await transact_to_clustering_utils.postOperationHandler(i,o,e)}catch(o){tr.info("Invalid operation in transaction"),tr.error(o)}}a(Yre,"catchup");async function _s(e){xre(e);let t,r;try{r=await wR.addJob(e),t=r.createdJob,tr.info("addJob result",r);let n=new bB.RunnerMessage(t,e);return await bB.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 tr.error(s),hl(n,s)}}a(_s,"executeJob");function Kre(){let e=new Map;return e.set(q.OPERATIONS_ENUM.INSERT,new Y(Fa.insert)),e.set(q.OPERATIONS_ENUM.UPDATE,new Y(Fa.update)),e.set(q.OPERATIONS_ENUM.UPSERT,new Y(Fa.upsert)),e.set(q.OPERATIONS_ENUM.SEARCH_BY_CONDITIONS,new Y(mE.searchByConditions)),e.set(q.OPERATIONS_ENUM.SEARCH_BY_HASH,new Y(DB)),e.set(q.OPERATIONS_ENUM.SEARCH_BY_ID,new Y(DB)),e.set(q.OPERATIONS_ENUM.SEARCH_BY_VALUE,new Y(Fre)),e.set(q.OPERATIONS_ENUM.SEARCH,new Y(kre)),e.set(q.OPERATIONS_ENUM.SQL,new Y(Vre)),e.set(q.OPERATIONS_ENUM.CSV_DATA_LOAD,new Y(_s,dE.csvDataLoad)),e.set(q.OPERATIONS_ENUM.CSV_FILE_LOAD,new Y(_s,dE.csvFileLoad)),e.set(q.OPERATIONS_ENUM.CSV_URL_LOAD,new Y(_s,dE.csvURLLoad)),e.set(q.OPERATIONS_ENUM.IMPORT_FROM_S3,new Y(_s,dE.importFromS3)),e.set(q.OPERATIONS_ENUM.CREATE_SCHEMA,new Y(Fs.createSchema)),e.set(q.OPERATIONS_ENUM.CREATE_DATABASE,new Y(Fs.createSchema)),e.set(q.OPERATIONS_ENUM.CREATE_TABLE,new Y(Fs.createTable)),e.set(q.OPERATIONS_ENUM.CREATE_ATTRIBUTE,new Y(Fs.createAttribute)),e.set(q.OPERATIONS_ENUM.DROP_SCHEMA,new Y(Fs.dropSchema)),e.set(q.OPERATIONS_ENUM.DROP_DATABASE,new Y(Fs.dropSchema)),e.set(q.OPERATIONS_ENUM.DROP_TABLE,new Y(Fs.dropTable)),e.set(q.OPERATIONS_ENUM.DROP_ATTRIBUTE,new Y(Fs.dropAttribute)),e.set(q.OPERATIONS_ENUM.DESCRIBE_SCHEMA,new Y(fE.describeSchema)),e.set(q.OPERATIONS_ENUM.DESCRIBE_DATABASE,new Y(fE.describeSchema)),e.set(q.OPERATIONS_ENUM.DESCRIBE_TABLE,new Y(fE.describeTable)),e.set(q.OPERATIONS_ENUM.DESCRIBE_ALL,new Y(fE.describeAll)),e.set(q.OPERATIONS_ENUM.DELETE,new Y(El.deleteRecord)),e.set(q.OPERATIONS_ENUM.ADD_USER,new Y(fl.addUser)),e.set(q.OPERATIONS_ENUM.ALTER_USER,new Y(fl.alterUser)),e.set(q.OPERATIONS_ENUM.DROP_USER,new Y(fl.dropUser)),e.set(q.OPERATIONS_ENUM.LIST_USERS,new Y(fl.listUsersExternal)),e.set(q.OPERATIONS_ENUM.LIST_ROLES,new Y(EE.listRoles)),e.set(q.OPERATIONS_ENUM.ADD_ROLE,new Y(EE.addRole)),e.set(q.OPERATIONS_ENUM.ALTER_ROLE,new Y(EE.alterRole)),e.set(q.OPERATIONS_ENUM.DROP_ROLE,new Y(EE.dropRole)),e.set(q.OPERATIONS_ENUM.USER_INFO,new Y(fl.userInfo)),e.set(q.OPERATIONS_ENUM.READ_LOG,new Y(yre)),e.set(q.OPERATIONS_ENUM.ADD_NODE,new Y(Nre)),e.set(q.OPERATIONS_ENUM.UPDATE_NODE,new Y(gB)),e.set(q.OPERATIONS_ENUM.SET_NODE_REPLICATION,new Y(gB)),e.set(q.OPERATIONS_ENUM.REMOVE_NODE,new Y(Ire)),e.set(q.OPERATIONS_ENUM.CONFIGURE_CLUSTER,new Y(wre)),e.set(q.OPERATIONS_ENUM.PURGE_STREAM,new Y(Cre)),e.set(q.OPERATIONS_ENUM.SET_CONFIGURATION,new Y(IB.setConfiguration)),e.set(q.OPERATIONS_ENUM.CLUSTER_STATUS,new Y(Dre.clusterStatus)),e.set(q.OPERATIONS_ENUM.CLUSTER_NETWORK,new Y(Lre)),e.set(q.OPERATIONS_ENUM.CLUSTER_SET_ROUTES,new Y(yR.setRoutes)),e.set(q.OPERATIONS_ENUM.CLUSTER_GET_ROUTES,new Y(yR.getRoutes)),e.set(q.OPERATIONS_ENUM.CLUSTER_DELETE_ROUTES,new Y(yR.deleteRoutes)),e.set(q.OPERATIONS_ENUM.EXPORT_TO_S3,new Y(_s,RB.export_to_s3)),e.set(q.OPERATIONS_ENUM.DELETE_FILES_BEFORE,new Y(_s,El.deleteFilesBefore)),e.set(q.OPERATIONS_ENUM.DELETE_RECORDS_BEFORE,new Y(_s,El.deleteFilesBefore)),e.set(q.OPERATIONS_ENUM.EXPORT_LOCAL,new Y(_s,RB.export_local)),e.set(q.OPERATIONS_ENUM.SEARCH_JOBS_BY_START_DATE,new Y(wR.handleGetJobsByStartDate)),e.set(q.OPERATIONS_ENUM.GET_JOB,new Y(wR.handleGetJob)),e.set(q.OPERATIONS_ENUM.GET_FINGERPRINT,new Y(NR.getFingerprint)),e.set(q.OPERATIONS_ENUM.SET_LICENSE,new Y(NR.setLicense)),e.set(q.OPERATIONS_ENUM.GET_REGISTRATION_INFO,new Y(NR.getRegistrationInfo)),e.set(q.OPERATIONS_ENUM.RESTART,new Y(OB.restart)),e.set(q.OPERATIONS_ENUM.RESTART_SERVICE,new Y(OB.restartService)),e.set(q.OPERATIONS_ENUM.CATCHUP,new Y(Yre)),e.set(q.OPERATIONS_ENUM.SYSTEM_INFORMATION,new Y(Pre.systemInformation)),e.set(q.OPERATIONS_ENUM.DELETE_AUDIT_LOGS_BEFORE,new Y(_s,El.deleteAuditLogsBefore)),e.set(q.OPERATIONS_ENUM.READ_AUDIT_LOG,new Y(bre)),e.set(q.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS,new Y(yB.createTokens)),e.set(q.OPERATIONS_ENUM.REFRESH_OPERATION_TOKEN,new Y(yB.refreshOperationToken)),e.set(q.OPERATIONS_ENUM.LOGIN,new Y(NB.login)),e.set(q.OPERATIONS_ENUM.LOGOUT,new Y(NB.logout)),e.set(q.OPERATIONS_ENUM.GET_CONFIGURATION,new Y(IB.getConfiguration)),e.set(q.OPERATIONS_ENUM.CUSTOM_FUNCTIONS_STATUS,new Y(Wt.customFunctionsStatus)),e.set(q.OPERATIONS_ENUM.GET_CUSTOM_FUNCTIONS,new Y(Wt.getCustomFunctions)),e.set(q.OPERATIONS_ENUM.GET_COMPONENT_FILE,new Y(Wt.getComponentFile)),e.set(q.OPERATIONS_ENUM.GET_COMPONENTS,new Y(Wt.getComponents)),e.set(q.OPERATIONS_ENUM.SET_COMPONENT_FILE,new Y(Wt.setComponentFile)),e.set(q.OPERATIONS_ENUM.DROP_COMPONENT,new Y(Wt.dropComponent)),e.set(q.OPERATIONS_ENUM.GET_CUSTOM_FUNCTION,new Y(Wt.getCustomFunction)),e.set(q.OPERATIONS_ENUM.SET_CUSTOM_FUNCTION,new Y(Wt.setCustomFunction)),e.set(q.OPERATIONS_ENUM.DROP_CUSTOM_FUNCTION,new Y(Wt.dropCustomFunction)),e.set(q.OPERATIONS_ENUM.ADD_CUSTOM_FUNCTION_PROJECT,new Y(Wt.addComponent)),e.set(q.OPERATIONS_ENUM.ADD_COMPONENT,new Y(Wt.addComponent)),e.set(q.OPERATIONS_ENUM.DROP_CUSTOM_FUNCTION_PROJECT,new Y(Wt.dropCustomFunctionProject)),e.set(q.OPERATIONS_ENUM.PACKAGE_CUSTOM_FUNCTION_PROJECT,new Y(Wt.packageComponent)),e.set(q.OPERATIONS_ENUM.PACKAGE_COMPONENT,new Y(Wt.packageComponent)),e.set(q.OPERATIONS_ENUM.DEPLOY_CUSTOM_FUNCTION_PROJECT,new Y(Wt.deployComponent)),e.set(q.OPERATIONS_ENUM.DEPLOY_COMPONENT,new Y(Wt.deployComponent)),e.set(q.OPERATIONS_ENUM.READ_TRANSACTION_LOG,new Y(wB.readTransactionLog)),e.set(q.OPERATIONS_ENUM.DELETE_TRANSACTION_LOGS_BEFORE,new Y(_s,wB.deleteTransactionLogsBefore)),e.set(q.OPERATIONS_ENUM.INSTALL_NODE_MODULES,new Y(CB.installModules)),e.set(q.OPERATIONS_ENUM.AUDIT_NODE_MODULES,new Y(CB.auditModules)),e.set(q.OPERATIONS_ENUM.GET_BACKUP,new Y(Fs.getBackup)),e}a(Kre,"initializeOperationFunctionMap")});var SE=g((_pe,GB)=>{"use strict";var LR=L(),Wre=Q(),pl=$(),{handleHDBError:MR,hdb_errors:pE}=ne(),{isMainThread:Qre}=require("worker_threads"),{Readable:zre}=require("stream"),HB=require("os"),Jre=require("util"),Xre=cT(),jre=Jre.promisify(Xre.authorize),xB=BB(),{createGzip:Zre,constants:ene}=require("zlib");function tne(e){let t=`Found an uncaught exception with message: ${e.message}. ${HB.EOL}Stack: ${e.stack} ${HB.EOL}Terminating ${Qre?"HDB":"thread"}.`;console.error(t),pl.fatal(t),process.exit(1)}a(tne,"handleServerUncaughtException");function rne(e,t,r){if(pl[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:pE.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(rne,"serverErrorHandler");function nne(e,t,r){if(!e.body||Object.keys(e.body).length===0||typeof e.body!="object"){let n=MR(new Error,"Invalid JSON.",pE.HTTP_STATUS_CODES.BAD_REQUEST);r(n,null)}if(Wre.isEmpty(e.body.operation)){let n=MR(new Error,"Request body must include an 'operation' property.",pE.HTTP_STATUS_CODES.BAD_REQUEST);r(n,null)}r()}a(nne,"reqBodyValidationHandler");function sne(e,t,r){let n;e.body.operation!==LR.OPERATIONS_ENUM.CREATE_AUTHENTICATION_TOKENS&&e.body.operation!==LR.OPERATIONS_ENUM.LOGIN&&e.body.operation!==LR.OPERATIONS_ENUM.LOGOUT?jre(e,t).then(s=>{n=s,e.body.hdb_user=n,e.body.hdb_auth_header=e.headers.authorization,r()}).catch(s=>{pl.warn(s),pl.warn(`{"ip":"${e.socket.remoteAddress}", "error":"${s.stack}"`);let i=typeof s=="string"?{error:s}:{error:s.message};r(MR(s,i,pE.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(sne,"authHandler");async function ine(e,t,r=!1){let n;try{r&&(e.body.operation!=="configure_cluster"||e.body.operation!=="set_configuration")&&(e.body.bypass_auth=r),n=xB.chooseOperation(e.body);let s=await xB.processLocalTransaction(e,n);if(s instanceof zre&&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(Zre({level:ene.Z_BEST_SPEED})))}return s}catch(s){throw pl.error(s),s}}a(ine,"handlePostRequest");GB.exports={authHandler:sne,handlePostRequest:ine,handleServerUncaughtException:tne,serverErrorHandler:rne,reqBodyValidationHandler:nne}});var VB=g((fpe,kB)=>{"use strict";var one=require("fastify-plugin"),{handlePostRequest:qB,authHandler:ane,reqBodyValidationHandler:cne}=SE();async function une(e){e.decorate("hdbCore",{preValidation:[cne,ane],request:t=>FB(qB(t,response)),requestWithoutAuthentication:(t,r)=>FB(qB(t,r,!0))})}a(une,"hdbCore");async function FB(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(FB,"convertAsyncIterators");kB.exports=one(une)});var KB=g((mpe,YB)=>{"use strict";var hpe=require("fs"),UR=ee();UR.initSync();var{CONFIG_PARAMS:$B}=L(),lne=1024*1024*1024;function _ne(e){let t=UR.get($B.HTTP_TIMEOUT),r=UR.get($B.HTTP_KEEPALIVETIMEOUT);return{bodyLimit:lne,connectionTimeout:t,keepAliveTimeout:r,return503OnClosing:!1,forceCloseConnections:!0,ignoreTrailingSlash:!0,https:e}}a(_ne,"getServerOptions");YB.exports=_ne});var zB=g((Spe,QB)=>{"use strict";var PR=ee();PR.initSync();var{CONFIG_PARAMS:WB}=L();function dne(){let e=PR.get(WB.HTTP_CORSACCESSLIST),t=PR.get(WB.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(dne,"getCORSOptions");QB.exports=dne});var jB=g((gpe,XB)=>{"use strict";var JB=ee();JB.initSync();var fne=L();function Ene(){return JB.get(fne.CONFIG_PARAMS.HTTP_HEADERSTIMEOUT)??6e4}a(Ene,"getHeaderTimeoutConfig");XB.exports=Ene});var BR={};qe(BR,{customFunctionsServer:()=>pne,ready:()=>fH,start:()=>mne});function mne(e){let t=e.securePort>0;return{async handleFile(r,n,s,i){ks||(ks=dH(t),nt.http((await ks).server));let o=await ks,c=(0,vR.dirname)(s),u=(0,vR.dirname)(n);if(u.startsWith("/")&&(u=u.slice(1)),!ZB.has(c)){ZB.add(c);try{o.register(Tne(c,u))}catch(_){if(_.message==="Root plugin has already booted")$e.warn(`Could not load root fastify route for ${s}, this may require a restart to install properly`);else throw _}}},ready:fH}}async function pne(){try{$e.info("In Custom Functions Fastify server"+process.cwd()),$e.info(`Custom Functions Running with NODE_ENV set as: ${process.env.NODE_ENV}`),$e.debug(`Custom Functions server process ${process.pid} starting up.`),await Sne();let e=iH.get(oH.CONFIG_PARAMS.HTTP_SECUREPORT)>0,t;try{t=ks=await dH(e)}catch(r){throw $e.error(`Custom Functions buildServer error: ${r}`),r}try{await t.ready()}catch(r){throw $e.error(`Custom Functions server.ready() error: ${r}`),r}t.server.cantCleanupProperly=!0}catch(e){$e.error(`Custom Functions ${process.pid} Error: ${e}`),$e.error(e),process.exit(1)}}async function Sne(){try{$e.info("Custom Functions starting configuration."),await aH.setUsersToGlobal(),$e.info("Custom Functions completed configuration.")}catch(e){$e.error(e)}}function Tne(e,t){return async function(r){try{$e.info("Custom Functions starting buildRoutes"),$e.trace("Loading fastify routes folder "+e),(0,eH.existsSync)(e)&&r.register(sH.default,s=>({dir:e,dirNameRoutePrefix:!1,options:{hdbCore:s.hdbCore,logger:$e.loggerWithTag("custom-function"),prefix:`/${t}`}})).after((s,i,o)=>{s?.message?$e.error(s.message):s&&$e.error(s),o()})}catch(n){$e.error(`Custom Functions errored buildRoutes: ${n}`)}}}async function dH(e){$e.info("Custom Functions starting buildServer.");let t=(0,cH.default)(e),r=(0,tH.default)(t);r.server.headersTimeout=(0,lH.default)(),r.setErrorHandler(_H.serverErrorHandler);let n=(0,uH.default)();return n&&r.register(rH.default,n),r.register(function(s,i,o){s.setNotFoundHandler(function(c,u){r.server.emit("unhandled",c.raw,u.raw)}),o()}),r.register(nH.default),await r.register(hne),await r.after(),Vg(r),$e.info("Custom Functions completed buildServer."),r}function fH(){if(ks)return ks.then?ks.then(e=>e.ready()):ks.ready()}var vR,eH,tH,rH,nH,sH,iH,oH,$e,hne,aH,cH,uH,lH,_H,ks,ZB,EH=ge(()=>{vR=require("path"),eH=require("fs"),tH=v(require("fastify")),rH=v(require("@fastify/cors")),nH=v(rR()),sH=v(require("@fastify/autoload")),iH=v(ee()),oH=v(L()),$e=v($()),hne=v(VB()),aH=v(an()),cH=v(KB()),uH=v(zB()),lH=v(jB()),_H=v(SE());Na();or();ZB=new Set;a(mne,"start");a(pne,"customFunctionsServer");a(Sne,"setUp");a(Tne,"buildRouteFolder");a(dH,"buildServer");a(fH,"ready")});var HR={};qe(HR,{start:()=>gne});function gne(e){return{handleDirectory(t,r){if(t==="/"){let n=(0,TH.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){mH||(mH=!0,e.server.http(async(s,i)=>{if(!s.isWebSocket){let o=hH.get(s.pathname);if(o)return{handlesHeaders:!0,body:(0,pH.default)(s,(0,SH.realpathSync)(o))}}return i(s)},{runFirst:!0})),hH.set(r,n)}}}var pH,SH,TH,hH,mH,gH=ge(()=>{pH=v(require("send")),SH=require("fs"),TH=v(require("serve-static")),hH=new Map;a(gne,"start")});function One(e,t=1,r){if(xR++,(0,Co.startWorker)("server/threads/threadServer.js",{name:RE.THREAD_TYPES.HTTP,workerIndex:e,threadCount:t,async onStarted(n){let s=new Promise((o,c)=>{function u(_){_.type===RE.CLUSTER_MESSAGE_TYPE_ENUM.CHILD_STARTED&&(n.removeListener("message",u),o(n))}a(u,"onMessage"),n.on("message",u),n.on("error",c)});Ane.push(s),await s,ka.push(n),n.expectedIdle=1,n.lastIdle=0,n.requests=1,n.on("message",o=>{if(o.requestId){let c=gE.get(o.requestId);c&&c(o)}}),n.on("exit",i),n.on("shutdown",i);function i(){let o=ka.indexOf(n);o>-1&&ka.splice(o,1)}if(a(i,"removeWorker"),Va){let o=Va;Va=[];for(let c of o)bH[c.localPort](null,c)}}}),r){let n=setInterval(()=>{GR?GR=!1:(clearInterval(n),console.log("shut down dynamic thread due to inactivity"),(0,Co.shutdownWorkers)(),xR=0,setTimeout(()=>{global.gc?.()},5e3))},1e4)}}function yH(e=0,t){if(typeof e=="string")try{(0,AE.existsSync)(e)&&(0,AE.unlinkSync)(e)}catch{}let r;t?t==="ip"?r=bne:r=yne(t):r=FR;let n=(0,$a.createServer)({allowHalfOpen:!0,pauseOnConnect:!r.readsData}).listen(e);if(n._handle){n._handle.onconnection=bH[e]=function(i,o){r.readsData||(o.reading=!1,o.readStop()),GR=!0,r(o,(c,u)=>{if(!c){if(RH){let l=o._socket||new $a.Socket({handle:o,writable:!0,readable:!0});RH.deliverSocket(l,e,u),l.resume()}else xR>0?(Va.length===0&&setTimeout(()=>{Va.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,Va.push(o)):(console.log("start up a dynamic thread to handle request"),One(0));kr(!1,"socket-routed");return}c.requests++;let _=o.fd;if(_>=0)c.postMessage({port:e,fd:_,data:u});else{let l=o._socket||new $a.Socket({handle:o,writable:!0,readable:!0});Cne(l,c,e)}kr(!0,"socket-routed")})};let s=iu();qR.info(`HarperDB ${s.version} Server running on port ${e}`)}return n.on("error",s=>{console.error("Error in socket server",s)}),process.env._UNREF_SERVER&&n.unref(),n}function FR(e,t){let r,n=0;for(let s of ka){if(s.threadId===-1)continue;let i=s.expectedIdle/s.requests;if(i>n)r=s;else if(n>=TE)return TE=i,t(r);n=i}TE=0,t(r)}function bne(e,t){let r={};e.getpeername(r);let n=r.address,s=Ya.get(n),i=Date.now();if(s&&s.worker.threadId!==-1)return s.lastUsed=i,t(s.worker);FR(e,o=>{Ya.set(n,{worker:o,lastUsed:i}),t(o)})}function yne(e){let t=new RegExp(`${e}:\\s*(.+)`,"i");return r.readsData=!0,r;function r(n,s){let i=new $a.Socket({handle:n,readable:!0,writable:!0});n._socket=i,i.on("data",o=>{n.readStop();let u=o.toString("latin1").match(t)?.[1],_=Ya.get(u),l=Date.now();if(_&&_.worker.threadId!==-1)return _.lastUsed=l,s(_.worker);FR(n,d=>{Ya.set(u,{worker:d,lastUsed:l}),s(d,o)})})}a(r,"findByHeaderAffinity")}function Ine(){TE=0;for(let e of ka)e.expectedIdle=e.recentELU.idle+Nne,e.requests=1;ka.sort((e,t)=>e.expectedIdle>t.expectedIdle?-1:1)}function Cne(e,t,r){let n=wne++;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(),gE.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")),gE.delete(n)),s.event=="destroy"&&(e.destroy(),gE.delete(n))})}var Co,$a,RE,qR,AE,OH,Rne,ka,Va,bH,RH,xR,Ane,GR,TE,AH,Ya,Nne,gE,wne,NH=ge(()=>{Co=v(Ke()),$a=require("net"),RE=v(L()),qR=v($()),AE=require("fs");ws();OH=require("worker_threads"),Rne=v(Xi()),ka=[],Va=[],bH=[],xR=0,Ane=[];OH.isMainThread&&process.on("uncaughtException",e=>{e.code!=="ECONNRESET"&&e.message!=="write EIO"&&console.error("uncaughtException",e)});a(One,"startHTTPWorker");a(yH,"startSocketServer");TE=0;a(FR,"findMostIdleWorker");AH=36e5,Ya=new Map;a(bne,"findByRemoteAddressAffinity");a(yne,"makeFindByHeaderAffinity");setInterval(()=>{let e=Date.now();for(let[t,r]of Ya)r.lastUsed+AH<e&&Ya.delete(t)},AH).unref();Nne=1e3;a(Ine,"updateWorkerIdleness");(0,Co.setMonitorListener)(Ine);gE=new Map,wne=1;a(Cne,"proxySocket")});var YR={};qe(YR,{Request:()=>kR,createReuseportFd:()=>OE});var IH,kR,VR,$R,OE,bE=ge(()=>{IH=require("os"),kR=class{static{a(this,"Request")}#e;constructor(t,r){this.method=t.method;let n=t.url;this._nodeRequest=t,this._nodeResponse=r,this.url=n,this.headers=new $R(t.headers)}get absoluteURL(){return this.protocol+"://"+this.host+this.url}get pathname(){let t=this.url.indexOf("?");return t>-1?this.url.slice(0,t):this.url}set pathname(t){let r=this.url.indexOf("?");r>-1?this.url=t+this.url.slice(r):this.url=t}get protocol(){return this._nodeRequest.socket.encrypted?"https":"http"}get ip(){return this._nodeRequest.socket.remoteAddress}get authorized(){return this._nodeRequest.socket.authorized}get peerCertificate(){return this._nodeRequest.socket.getPeerCertificate()}get mtlsConfig(){return this._nodeRequest.socket.server.mtlsConfig}get body(){return this.#e||(this.#e=new VR(this._nodeRequest))}get host(){return this._nodeRequest.authority||this._nodeRequest.headers.host}get isAborted(){return!1}},VR=class{static{a(this,"RequestBody")}#e;constructor(t){this.#e=t}on(t,r){return this.#e.on(t,r),this}pipe(t,r){return this.#e.pipe(t,r)}},$R=class{constructor(t){this.asObject=t}static{a(this,"Headers")}set(t,r){this.asObject[t.toLowerCase()]=r}get(t){return this.asObject[t.toLowerCase()]}has(t){return this.asObject.hasOwnProperty(t.toLowerCase())}[Symbol.iterator](){return Object.entries(this.asObject)[Symbol.iterator]()}keys(){return Object.keys(this.asObject)}values(){return Object.values(this.asObject)}forEach(t){for(let[r,n]of this)t(n,r,this)}};(0,IH.platform)()!="win32"&&(OE=require("node-unix-socket").createReuseportFd)});var LH=g((vpe,DH)=>{"use strict";var Dne=require("cluster"),Do=ee();Do.initSync();var CH=L(),Dpe=require("util"),Vs=$(),Lpe=require("fs"),Lne=require("fastify"),Mpe=iu(),Mne=require("@fastify/cors"),Une=require("@fastify/compress"),Pne=require("@fastify/static"),vne=rR(),Bne=require("path"),{PACKAGE_ROOT:Hne}=L(),xne=Os(),Gne=Q(),qne=an(),Fne=Xi(),{server:kne}=(or(),ie(xi)),{node_request_key:Upe}=(bE(),ie(YR)),{authHandler:Vne,handlePostRequest:$ne,serverErrorHandler:Yne,reqBodyValidationHandler:Kne}=SE(),Ppe=require("net"),{registerContentHandlers:Wne}=(Na(),ie(f0)),Qne=6e4,zne=1024*1024*1024,Jne="TRUE",{CONFIG_PARAMS:Sl}=CH,Ka;DH.exports={hdbServer:wH,start:wH};async function wH(e){try{Vs.info("In Fastify server"+process.cwd()),Vs.info(`Running with NODE_ENV set as: ${process.env.NODE_ENV}`),Vs.debug(`HarperDB server process ${process.pid} starting up.`),global.clustering_on=!1,global.isMaster=Dne.isMaster,await Xne();let t=e.securePort>0;Ka=jne(t),await Ka.ready(),e||(e={}),e.isOperationsServer=!0;try{kne.http(Ka.server,e),Ka.server.closeIdleConnections||await Ka.listen({port:0,host:"::"})}catch(r){throw Ka.close(),Vs.error(r),Vs.error("Error configuring operations server"),r}}catch(t){console.error(`Failed to build server on ${process.pid}`,t),Vs.fatal(t),process.exit(1)}}a(wH,"operationsServer");async function Xne(){Vs.trace("Configuring HarperDB process."),xne.setSchemaDataToGlobal(),await qne.setUsersToGlobal(),await Fne.getLicense()}a(Xne,"setUp");function jne(e){Vs.debug(`HarperDB process starting to build ${e?"HTTPS":"HTTP"} server.`);let t=Zne(e),r=Lne(t);r.server.headersTimeout=tse(),r.setErrorHandler(Yne);let n=ese();n&&r.register(Mne,n),r.register(function(i,o,c){i.setNotFoundHandler(function(u,_){r.server.emit("unhandled",u.raw,_.raw)}),c()}),r.register(vne),r.register(Une),r.register(Pne,{root:Bne.join(Hne,"studio/build-local")}),Wne(r);let s=Do.get(CH.HDB_SETTINGS_NAMES.LOCAL_STUDIO_ON);return r.get("/",function(i,o){return!Gne.isEmpty(s)&&s.toString().toLowerCase()==="true"?o.sendFile("index.html"):o.sendFile("running.html")}),r.post("/",{preValidation:[Kne,Vne],config:{isOperation:!0}},async function(i,o){return i.body?.operation?.startsWith("restart")&&o.header("Connection","close"),$ne(i,o)}),r.get("/health",()=>"HarperDB is running."),Vs.debug(`HarperDB process starting up ${e?"HTTPS":"HTTP"} server listener.`),r}a(jne,"buildServer");function Zne(e){let t=Do.get(Sl.OPERATIONSAPI_NETWORK_TIMEOUT),r=Do.get(Sl.OPERATIONSAPI_NETWORK_KEEPALIVETIMEOUT);return{bodyLimit:zne,connectionTimeout:t,keepAliveTimeout:r,forceCloseConnections:!0,return503OnClosing:!1,https:e}}a(Zne,"getServerOptions");function ese(){let e=Do.get(Sl.OPERATIONSAPI_NETWORK_CORS),t=Do.get(Sl.OPERATIONSAPI_NETWORK_CORSACCESSLIST),r;return e&&(e===!0||e.toUpperCase()===Jne)&&(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(ese,"getCORSOpts");function tse(){return Do.get(Sl.OPERATIONSAPI_NETWORK_HEADERSTIMEOUT)??Qne}a(tse,"getHeaderTimeoutConfig")});var XR={};qe(XR,{disableNATS:()=>nse,publishToStream:()=>IE,setNATSReplicator:()=>KR,setPublishToStream:()=>sse,setSubscription:()=>JR,start:()=>rse});function rse(){Tl.default.get(gl.default.CONFIG_PARAMS.CLUSTERING_ENABLED)&&ose()}function nse(e=!0){BH=e}function sse(e,t){IE=e,JR=t}function ose(){if(BH||process.env._DISABLE_NATS)return;let e=dr(),t=Object.keys(e);t.push("system");for(let r of t){let n=e[r];for(let s in n){let i=n[s];KR(s,r,i)}}jR((r,n)=>{KR(r.tableName,r.databaseName,r),n&&xH(r)}),!MH&&(MH=!0)}function KR(e,t,r){if(!r)return console.error(`Attempt to replicate non-existent table ${e} from database ${t}`);if(r.sources.some(s=>s?.isNATSReplicator))return;r.sourcedFrom(class extends Ft{static{a(this,"NATSReplicator")}put(i){return n(this.getContext()).addWrite(t,{operation:"put",table:e,id:this[Me],record:i})}delete(){return n(this.getContext()).addWrite(t,{operation:"delete",table:e,id:this[Me]})}publish(i){return n(this.getContext()).addWrite(t,{operation:"publish",table:e,id:this[Me],record:i})}patch(i){return n(this.getContext()).addWrite(t,{operation:"patch",table:e,id:this[Me],record:i})}invalidate(){n(this.getContext()).addWrite(t,{operation:"invalidate",table:e,id:this[Me]})}static defineSchema(i){xH(i)}static subscribe(){let i=new yn;return JR(t,e,i),i}static subscribeOnThisThread(i){return i<(Tl.default.get(gl.default.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXINGESTTHREADS)??ise)}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 yE(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=HH;return i}a(n,"getNATSTransaction")}function xH(e){let t=Tl.default.get(gl.default.CONFIG_PARAMS.CLUSTERING_NODENAME);IE(`${QR.SUBJECT_PREFIXES.TXN}.${e.databaseName}.${e.tableName}`,(0,zR.createNatsTableStreamName)(e.databaseName,e.tableName),void 0,{operation:"define_schema",schema:e.databaseName,table:e.tableName,attributes:e.attributes,__origin:{timestamp:Date.now(),node_name:t}})}var UH,QR,zR,PH,vH,Tl,gl,NE,BH,IE,JR,ise,HH,MH,yE,WR,GH=ge(()=>{Re();Nn();UH=v(it()),QR=v(ke()),zR=v(Rs());gc();PH=v(wS()),vH=v(Dr()),Tl=v(ee()),gl=v(L()),NE=v($());a(rse,"start");a(nse,"disableNATS");IE=UH.publishToStream,JR=PH.setSubscription;a(sse,"setPublishToStream");ise=2;a(ose,"assignReplicationSource");a(KR,"setNATSReplicator");a(xH,"publishSchema");yE=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=Tl.default.get(gl.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||(NE.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(`${QR.SUBJECT_PREFIXES.TXN}.${s}.${u.table}`,(0,zR.createNatsTableStreamName)(s,u.table),void 0,u)?.catch(l=>{throw NE.error("An error has occurred trying to replicate transaction",u,l),l.statusCode=504,l}))}return Promise.all(n)}},WR=class extends yE{static{a(this,"ImmmediateNATSTransaction")}constructor(){super({get timestamp(){return(0,vH.getNextMonotonicTime)()}})}addWrite(t,r){super.addWrite(t,r),this.commit({})}};HH=new WR});var ex=g(Lo=>{"use strict";var{isMainThread:YH,parentPort:Al,threadId:wE}=require("worker_threads"),{Socket:ase,createServer:cse}=require("net"),{createServer:use,IncomingMessage:lse}=require("http"),{createServer:_se}=require("https"),{readFileSync:Wa,unlinkSync:qH,existsSync:dse}=require("fs"),rr=$(),we=ee(),Et=L(),{server:ME}=(or(),ie(xi)),{WebSocketServer:fse}=require("ws"),{createServer:Ese}=require("tls"),{getTicketKeys:hse,restartNumber:mse,getWorkerIndex:DE}=Ke(),{Headers:KH,appendHeader:pse}=(Wu(),ie(HP)),{recordAction:Rl,recordActionBinary:Sse}=(ws(),ie(lu)),{Request:WH,createReuseportFd:FH}=(bE(),ie(YR)),{checkMemoryLimit:Tse}=Xi(),QH=require("tls"),kH=QH.createSecureContext;QH.createSecureContext=function(e){if(!e.cert||!e.key)return kH(e);let t={...e};delete t.key,delete t.cert;let r=kH(t);return r.context.setCert(e.cert),r.context.setKey(e.key,void 0),r};var zH=we.get(Et.CONFIG_PARAMS.THREADS_DEBUG);if(zH){let e;if(YH)e=we.get(Et.CONFIG_PARAMS.THREADS_DEBUG_PORT)??9229,process.on(["SIGINT","SIGTERM","SIGQUIT","exit"],()=>{try{require("inspector").close()}catch(t){rr.info("Could not close debugger",t)}});else{let t=we.get(Et.CONFIG_PARAMS.THREADS_DEBUG_STARTINGPORT);t&&DE()>=0&&(e=t+DE())}if(e){let t=we.get(Et.CONFIG_PARAMS.THREADS_DEBUG_HOST),r=we.get(Et.CONFIG_PARAMS.THREADS_DEBUG_WAITFORDEBUGGER);try{require("inspector").open(e,t,r)}catch(n){rr.trace(`Could not start debugging on port ${e}, you may already be debugging:`,n.message)}}}else if(process.env.DEV_MODE)try{require("inspector").open(9229)}catch(e){mse<=1&&rr.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:kpe,CONFIG_PARAMS:gse}=Et;we.initSync();var Rse=we.get(gse.HTTP_SESSIONAFFINITY),ds={};Lo.registerServer=nA;Lo.httpServer=sA;Lo.deliverSocket=rA;Lo.startServers=JH;Lo.when_components_loaded=null;ME.http=sA;ME.request=yse;ME.socket=Nse;ME.ws=Ise;var ZR={},CE={},Ase,Di={},LE={},Ose=[],eA=[];function JH(){return Lo.when_components_loaded=iA().loadRootComponents(!0).then(()=>{Al?.on("message",t=>{let{port:r,fd:n,data:s}=t;if(n)rA(n,r,s);else if(t.requestId)bse(t);else if(t.type===Et.ITC_EVENT_TYPES.SHUTDOWN){rr.trace("received shutdown request",wE);for(let i in ds){let o=ds[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?rr.info(`Closing ${E.length} idle connections`):f&&rr.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
29
|
Connection: close\r
|
|
28
30
|
\r
|
|
29
|
-
`))}},25).unref()}o.close?.(()=>{if(we.get(
|
|
30
|
-
`)}a(AH,"defaultNotFound")});async function BH({clientId:e,user:t,clean:r,will:s}){let n;if(e&&!r){let i=await zR.get(e,{returnNonexistent:!0});n=new jR(e,t,i),i&&(n.sessionWasPresent=!0)}else{if(e){let i=await zR.get(e);i&&i.delete()}n=new yE(e,t)}return s&&(s.id=e,s.user={username:t?.username},hl.put(s)),n}function JR(){return NE++,NE>65500&&(NE=1),NE}function XR(e,t,r=e){let{topic:s,retain:n}=e;e.data=t,e.async=!0,e.authorize=!0;let i=gi.getMatch(s);if(!i)throw new Error(`Can not publish to topic ${s} as it does not exist, no resource has been defined to handle this topic`);e.url=i.relativeURL;let o=i.Resource;return je(r,()=>n?t===void 0?o.delete(e,r):o.put(e,e.data,r):o.publish(e,e.data,r))}var UH,Ci,PH,vH,zR,hl,NE,yE,jR,HH=Re(()=>{Ae();xu();UH=x(wr()),Ci=x($());ro();PH=x(Ke()),vH=x(MH());or();zR=ut({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"}]}}]}),hl=ut({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,PH.getWorkerIndex)()===0&&(async()=>{await vH.when_components_loaded,await new Promise(e=>setTimeout(e,2e3));for await(let e of hl.search({})){let t=e.data,r=Object.assign({},e);r.user?.username&&(r.user=await rt.getUser(r.user.username)),je(r,()=>{try{XR(r,t)}catch{(0,Ci.warn)("Failed to publish will",t)}hl.delete(e.id,r)})}})();a(BH,"getSession");NE=1;a(JR,"getNextMessageId");yE=class{static{a(this,"SubscriptionsSession")}listener;sessionId;user;subscriptions=[];awaitingAcks;sessionWasPresent;constructor(t,r){this.sessionId=t,this.user=r}async addSubscription(t,r,s){let{topic:n,rh:i,startTime:o}=t,c=n.indexOf("?"),u,_;if(c>-1?(u=n.slice(c),_=n.slice(0,c)):_=n,!_)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===n),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,Ci.trace)("Resuming subscription from",n,"from",o);let E=gi.getMatch(_);if(!E){let T=new Error(`The topic ${n} 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 b=T.split("/"),R;for(let P=0;P<b.length;P++)if(b[P].indexOf("+")>-1)if(b[P]==="+")R=!0;else throw new Error("Single-level wildcards can only be used as a topic level (between or after slashes)");if(s&&R)throw new Error("Filters can not be combined");let L=!0;b[b.length-1]==="#"&&(b.length--,L=!1),R&&(s=a(P=>{let k=P.id;if(!Array.isArray(k)||L&&k.length!==b.length)return!1;for(let B=0;B<b.length;B++)if(b[B]!=="+"&&b[B]!==k[B])return!1;return!0},"filter"));let H=b.indexOf("+");f.url="/"+(H>-1?b.slice(0,H):b).concat("").join("/")}}let h=E.path,p=E.Resource,S=await je(f,async()=>{let T=await p.subscribe(f);if(!T)throw new Error(`No subscription was returned from subscribe for topic ${n}`);if(!T[Symbol.asyncIterator])throw new Error(`Subscription is not (async) iterable for topic ${n}`);return(async()=>{for await(let b of T)try{let R;if(b.type&&b.type!=="put"&&b.type!=="delete"&&b.type!=="message"&&b.type!=="patch"||s&&!s(b))continue;r?(b.topic=n,R=this.needsAcknowledge(b)):(b.acknowledge?.(),R=JR());let L=b.id;Array.isArray(L)&&(L=Ra(L)),L==null&&(L=""),this.listener(h+"/"+L,b.value,R,t)}catch(R){(0,Ci.warn)(R)}})(),T});return S.topic=n,S.qos=t.qos,this.subscriptions.push(S),S}resume(){}needsAcknowledge(t){let r=JR();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(s=>s.topic===t);if(r)return r.end(),!0}async publish(t,r){return t.user=this.user,XR(t,r)}setListener(t){this.listener=t}disconnect(t){let r={};je(r,async()=>{if(!t){let s=await hl.get(this.sessionId,r);s?.doesExist()&&await XR(s,s.data,r)}await hl.delete(this.sessionId,r)}).catch(s=>{(0,Ci.warn)(`Error publishing MQTT will for ${this.sessionId}`,s)});for(let s of this.subscriptions)s.end();this.subscriptions=[]}};a(XR,"publish");jR=class extends yE{static{a(this,"DurableSubscriptionsSession")}sessionRecord;constructor(t,r,s){super(t,r),this.sessionRecord=s||{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,s){return super.addSubscription(t,r,s)}needsAcknowledge(t){this.awaitingAcks||(this.awaitingAcks=new Map);let r=JR(),s={topic:t.topic,timestamp:t.timestamp};return t.acknowledge&&(s.acknowledge=t.acknowledge),this.awaitingAcks.set(r,s),r}acknowledge(t){let r=this.awaitingAcks.get(t);this.awaitingAcks.delete(t),r.acknowledge?.();let s=r.topic;for(let[,n]of this.awaitingAcks)if(n.topic===s&&n.timestamp<r.timestamp){for(let i of this.sessionRecord.subscriptions)if(i.topic===s){i.acks||(i.acks=[]),i.acks.push(r.timestamp),(0,Ci.trace)("Received ack",s,r.timestamp),this.sessionRecord.update();return}}for(let n of this.sessionRecord.subscriptions)n.topic===s&&(n.startTime=r.timestamp);this.sessionRecord.update()}async addSubscription(t,r){await this.resumeSubscription(t,r);let{qos:s,startTime:n}=t;return s>0&&!n&&(this.sessionRecord.subscriptions=this.subscriptions.map(i=>{let o=i.startTime;return o||(o=i.startTime=(0,UH.getNextMonotonicTime)()),(0,Ci.trace)("Added durable subscription",i.topic,o),{qos:i.qos,topic:i.topic,startTime:o}}),zR.put(this.sessionRecord)),t.qos}}});var tA={};Ye(tA,{bypassAuth:()=>ane,start:()=>cne});function ane(){FH=!0}function cne({server:e,port:t,network:r,webSocket:s,securePort:n,requireAuthentication:i}){let o=e.mqtt={requireAuthentication:i,sessions:new Set},c,u=r?.mtls;return s&&(c=e.ws((_,l,d)=>{if(_.protocol==="mqtt"){Wr.debug("Received WSS connection for MQTT from",_._socket.remoteAddress);let{onMessage:f,onClose:E}=qH(_,(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=>{Wr.info("WebSocket error",h)})}},Object.assign({subProtocol:"mqtt"},s))),(t||n)&&(c=e.socket(async _=>{let l;if(Wr.debug("Received connection for MQTT from",_.remoteAddress),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),(0,ml.get)(Qr.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)&&ZR.notify({username:l.username,status:Qr.AUTH_AUDIT_STATUS.SUCCESS,type:Qr.AUTH_AUDIT_TYPES.AUTHENTICATION,auth_strategy:"MQTT mTLS",remote_address:_.remoteAddress})):Wr.debug("MQTT mTLS authorized connection (mTLS did not authorize a user)","from",_.remoteAddress)}catch(E){Wr.error(E)}else if(u.required)return Wr.info(`Unauthorized connection attempt, no authorized client certificate provided, error: ${_.authorizationError}`),_.end()}!l&&FH&&_.remoteAddress.includes("127.0.0.1")&&(l=await(0,GH.getSuperUser)(),Wr.debug("Auto-authorizing local connection",l?.username));let{onMessage:d,onClose:f}=qH(_,E=>_.write(E),null,l,o);_.on("data",d),_.on("close",f),_.on("error",E=>{Wr.info("Socket error",E)})},{port:t,securePort:n,mtls:u})),c}function qH(e,t,r,s,n){xH||(xH=!0,nu(d=>{IE>0&&d.push({metric:"mqtt-connections",connections:IE,byThread:!0})}));let i;IE++;let o,c={protocolVersion:4},u=(0,wE.parser)({protocolVersion:5});function _(d){u.parse(d)}a(_,"onMessage");function l(){IE--,i||(i=!0,o?.disconnect(),n.sessions.delete(o),os(!1,"connection","mqtt","disconnect"))}return a(l,"onClose"),u.on("packet",async d=>{s?.then&&(s=await s),o?.then&&await o;try{switch(d.cmd){case"connect":if(c.protocolVersion=d.protocolVersion,d.username)try{s=await rt.getUser(d.username,d.password.toString(),r),(0,ml.get)(Qr.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)&&ZR.notify({username:s.username,status:Qr.AUTH_AUDIT_STATUS.SUCCESS,type:Qr.AUTH_AUDIT_TYPES.AUTHENTICATION,auth_strategy:"MQTT",remote_address:e.remoteAddress})}catch{return(0,ml.get)(Qr.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGFAILED)&&ZR.error({username:s.username,status:Qr.AUTH_AUDIT_STATUS.FAILURE,type:Qr.AUTH_AUDIT_TYPES.AUTHENTICATION,auth_strategy:"mqtt",remote_address:e.remoteAddress}),f({cmd:"connack",reasonCode:4,returnCode:134})}if(!s&&n.requireAuthentication)return os(!1,"connection","mqtt","connect"),f({cmd:"connack",reasonCode:4,returnCode:134});try{if(n.authorizeClient?.(d,s),d.will){let R=e.deserialize||(e.deserialize=Ro(r?.headers.get?.("content-type")));d.will.data=d.will.payload?.length>0?R(d.will.payload):void 0,delete d.will.payload}o=BH({user:s,...d}),o=await o,n.sessions.add(o)}catch(R){return Wr.error(R),os(!1,"connection","mqtt","connect"),f({cmd:"connack",reasonCode:R.code||5,returnCode:R.code||128})}os(!0,"connection","mqtt","connect"),f({cmd:"connack",sessionPresent:o.sessionWasPresent,reasonCode:0,returnCode:0}),o.setListener((R,L,H,P)=>{try{let k=R.indexOf("/",1),B=k>0?R.slice(0,k):R;f({cmd:"publish",topic:R,payload:E(L),messageId:H||Math.floor(Math.random()*1e8),qos:P.qos},B)}catch(k){Wr.error(k),o?.disconnect(),n.sessions.delete(o)}}),o.sessionWasPresent&&await o.resume();break;case"subscribe":let h=[];for(let R of d.subscriptions){let L;try{L=(await o.addSubscription(R,R.qos>=1)).qos||0}catch(H){Wr.error(H),L=c.protocolVersion<5?128:H.statusCode===403?135:H.statusCode===404?143:128}h.push(L)}await o.committed,f({cmd:"suback",granted:h,messageId:d.messageId});break;case"unsubscribe":{let R=[];for(let L of d.unsubscriptions)R.push(o.removeSubscription(L)?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=Ro(r?.headers.get?.("content-type"))),T=d.payload?.length>0?S(d.payload):void 0,b;try{b=await o.publish(d,T)}catch(R){Wr.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:b===!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),n.sessions.delete(o),os(!0,"connection","mqtt","disconnect"),e.close?e.close():e.end();break}}catch(h){Wr.error(h),f({cmd:"disconnect"})}function f(h,p){let S=(0,wE.generate)(h,c);t(S),Fr(S.length,"bytes-sent",p,h.cmd,"mqtt")}a(f,"sendPacket");function E(h){return Ai(h,r)}a(E,"serialize")}),{onMessage:_,onClose:l}}var wE,GH,ml,Qr,eA,ZR,Wr,FH,xH,IE,kH=Re(()=>{wE=require("mqtt-packet");HH();GH=x(is());Oa();In();or();ml=x(ee()),Qr=x(M()),eA=x($()),ZR=(0,eA.loggerWithTag)("auth-event"),Wr=(0,eA.loggerWithTag)("mqtt"),FH=(0,ml.get)(Qr.CONFIG_PARAMS.AUTHENTICATION_AUTHORIZELOCAL)??process.env.DEV_MODE;a(ane,"bypassAuth");a(cne,"start");IE=0;a(qH,"onSocket")});var Of={};Ye(Of,{component_errors:()=>Ka,loadComponent:()=>CE,loadComponentDirectories:()=>XH,setErrorReporter:()=>dne});function XH(e,t){t&&(sA=t),e&&(nA=e);let r=[];if((0,ks.existsSync)(rA)){let n=(0,ks.readdirSync)(rA,{withFileTypes:!0});for(let i of n){if(!i.isDirectory()&&!i.isSymbolicLink())continue;let o=i.name,c=(0,Rt.join)(rA,o);r.push(CE(c,sA,"hdb",!1))}}let s=process.env.RUN_HDB_APP;return s&&r.push(CE(s,sA,s,!1,null,process.env.DEV_MODE)),Promise.all(r).then(()=>{JH=!0})}function dne(e){Sl=e}async function CE(e,t,r,s,n,i){if(!$H.has(e)){$H.set(e,!0),n&&(nA=n);try{let o;s&&(Ka=new Map);let c=(0,Rt.join)(e,s?"harperdb-config.yaml":"config.yaml");(0,ks.existsSync)(c)?o=s?(0,zH.getConfigObj)():(0,YH.parseDocument)((0,ks.readFileSync)(c,"utf8"),{simpleKeys:!0}).toJSON():o=iA;let u=[],_=s;for(let l in o){let d=o[l];if(Ka.set(s?l:(0,Rt.basename)(e),!1),!d)continue;let f,E=d.package;try{if(E){let b=e,R;for(;!(0,ks.existsSync)(R=(0,Rt.join)(b,"node_modules",l));)if(b=(0,Rt.dirname)(b),b.length<(0,QH.getHdbBasePath)().length){R=null;break}if(R)f=await CE(R,t,r,!1),_=!0;else throw new Error(`Unable to find package ${l}:${E}`)}else f=_ne[l];if(!f)continue;u.push(f);let h=a(b=>(b.origin=r,ut(b)),"ensureTable"),p=d.network||(d.port||d.securePort)&&d,S=p?.securePort||p?.https&&p.port,T=!p?.https&&p?.port;if(Ya.isMainThread&&(f=await f.startOnMainThread?.({server:rt,ensureTable:h,port:T,securePort:S,resources:t,...d})||f,s&&p))for(let b of[T,S])try{if(+b&&!VH.includes(b)){let R=oA.get(aA.CONFIG_PARAMS.HTTP_SESSIONAFFINITY);R&&pl.default.warn("Session affinity is not recommended and may cause memory leaks"),(R||!hE)&&(VH.push(b),sH(b,R))}}catch(R){console.error("Error listening on socket",b,R,l)}if(t.isWorker&&(f=await f.start?.({server:rt,ensureTable:h,port:T,securePort:S,resources:t,...d})||f),nA.set(f,!0),(f.handleFile||f.handleDirectory)&&d.files){if(d.files.includes(".."))throw(0,WH.handleHDBError)("Can not reference parent directories");let b=(0,Rt.join)(e,d.files).replace(/\\/g,"/"),R=b.indexOf("/*");if(R>-1&&d.files!==iA[l]?.files&&!(0,ks.existsSync)(b.slice(0,R)))throw new Error(`The path '${b.slice(0,R)}' does not exist and cannot be used as the base of the resolved 'files' path value '${d.files}'`);let L=(0,Rt.basename)(e),H=d.path||"/";H=H.startsWith("/")?H:H.startsWith("./")?"/"+L+H.slice(2):H==="."?"/"+L:"/"+L+"/"+H;let P,k,B;if(d.root){let z=d.root;z.startsWith("/")&&(z=z.slice(1)),z.endsWith("/")&&(z=z.slice(0,-1)),z+="/",k=(0,Rt.join)(e,z)}else(B=b.indexOf("/*"))>-1&&(k=b.slice(0,B+1),P=(0,Rt.relative)(e,k));let X=!1;if(Ya.isMainThread&&f.setupDirectory&&(X=await f.setupDirectory?.(H,k,t)),t.isWorker&&f.handleDirectory&&(X=await f.handleDirectory?.(H,k,t)),X)continue;for(let z of await(0,KH.default)(b,{onlyFiles:!1,objectMode:!0})){let{path:J,dirent:de}=z;_=!0;let ce=(0,Rt.relative)(e,J).replace(/\\/g,"/");if(P)if(ce.startsWith(P))ce=ce.slice(P.length+1);else throw new Error(`The root path '${d.root}' does not reference a valid part of the file path '${ce}'.The root path should be used to indicate the relative path/part of the file path for determining the exported web path.`);let fe=H+(H.endsWith("/")?"":"/")+ce;try{if(de.isFile()){let Le=await lne(J);Ya.isMainThread&&await f.setupFile?.(Le,fe,J,t),t.isWorker&&await f.handleFile?.(Le,fe,J,t)}else Ya.isMainThread&&await f.setupDirectory?.(fe,J,t),t.isWorker&&await f.handleDirectory?.(fe,J,t)}catch(Le){Le.message=`Could not load ${de.isFile()?"file":"directory"} '${J}'${d.module?" using '"+d.module+"'":""} for application '${e}' due to: ${Le.message}`,Sl?.(Le),((0,Wa.getWorkerIndex)()===0?console:pl.default).error(Le),t.set(d.path||"/",new Tl(Le)),Ka.set(s?l:(0,Rt.basename)(e),Le.message)}}}}catch(h){h.message=`Could not load component '${l}' for application '${(0,Rt.basename)(e)}' due to: ${h.message}`,Sl?.(h),((0,Wa.getWorkerIndex)()===0?console:pl.default).error(h),t.set(d.path||"/",new Tl(h),null,!0),Ka.set(s?l:(0,Rt.basename)(e),h.message)}}if(Ya.isMainThread&&!JH&&i&&(0,Wa.watchDir)(e,async()=>XH()),o.extensionModule)return await t_((0,Rt.join)(e,o.extensionModule));if(!_&&t.isWorker){let l=`${e} did not load any modules, resources, or files, is this a valid component?`;Sl?.(new Error(l)),((0,Wa.getWorkerIndex)()===0?console:pl.default).error(l),Ka.set((0,Rt.basename)(e),l)}}catch(o){console.error(`Could not load application directory ${e}`,o),o.message=`Could not load application due to ${o.message}`,Sl?.(o),t.set("",new Tl(o))}}}var ks,Rt,Ya,YH,oA,aA,KH,Wa,pl,WH,QH,une,zH,lne,rA,nA,JH,sA,Ka,_ne,iA,VH,$H,Sl,Tl,bf=Re(()=>{ks=require("fs"),Rt=require("path"),Ya=require("worker_threads"),YH=require("yaml"),oA=x(ee()),aA=x(M());ab();_b();db();i0();KB();jB();KH=x(require("fast-glob")),Wa=x(Ke()),pl=x($());xh();or();WH=x(se());Ns();Ae();nH();QH=x(ee()),une=x(uH());hf();pH();kH();zH=x(Br());mE();({readFile:lne}=ks.promises),rA=oA.get(aA.CONFIG_PARAMS.COMPONENTSROOT),nA=new Map,Ka=new Map;a(XH,"loadComponentDirectories");_ne={REST:kf,rest:kf,graphqlSchema:Hh,jsResource:Gh,fastifyRoutes:NR,login:kh,static:yR,operationsApi:une,customFunctions:{},http:{},clustering:GR,authentication:Gu,mqtt:tA},iA={rest:!0,graphqlSchema:{files:"*.graphql"},jsResource:{files:"resources.js"},fastifyRoutes:{files:"routes/*.js",path:"."}};Object.defineProperty(iA,"static",{value:{files:"web/**"}});VH=[],$H=new Map;a(dne,"setErrorReporter");a(CE,"loadComponent");Tl=class extends Ft{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 QR=g((Ype,ZH)=>{var{isMainThread:jH}=require("worker_threads"),{getTables:fne}=(Ae(),ne(Ge)),{loadComponentDirectories:Ene,loadComponent:hne}=(bf(),ne(Of)),{resetResources:mne}=(xu(),ne(EP)),pne=ig(),Sne=Br(),{dirname:Tne}=require("path"),{getConnection:gne}=nt(),Rne=ee(),Ane=M(),cA=new Map;async function One(e=!1){!jH&&Rne.get(Ane.CONFIG_PARAMS.CLUSTERING_ENABLED)&&gne();try{jH&&await pne()}catch(s){console.error(s)}let t=mne();fne(),t.isWorker=e,await hne(Tne(Sne.getConfigFilePath()),t,"hdb",!0,cA),await Ene(cA,t);let r=[];for(let[s]of cA)s.ready&&r.push(s.ready());r.length>0&&await Promise.all(r)}a(One,"loadRootComponents");ZH.exports.loadRootComponents=One});var Ke=g((Wpe,Li)=>{"use strict";var{Worker:bne,MessageChannel:Nne,parentPort:En,isMainThread:fA,threadId:yne,workerData:Vn}=require("worker_threads"),{PACKAGE_ROOT:Ine}=M(),{join:sx,isAbsolute:wne,extname:Cne}=require("path"),{server:nx}=(or(),ne(Bi)),{watch:Dne,readdir:Lne}=require("fs/promises"),{totalmem:ex}=require("os"),gl=M(),ix=ee(),$n=$(),{randomBytes:Mne}=require("crypto"),{_assignPackageExport:Une}=require("../index"),Pne=M(),tx=1024*1024,Di=[],ms=[],vne=50,EA=1e4,Bne="restart",ox="request_thread_info",ax="resource_report",cx="thread_info",ux="added-port",Hne="ack",uA;Une("threads",ms);Li.exports={startWorker:lA,restartWorkers:mA,shutdownWorkers:kne,workers:Di,setMonitorListener:Jne,onMessageFromWorkers:Vne,onMessageByType:mx,broadcast:Yne,broadcastWithAcknowledgement:Wne,setChildListenerByType:Fne,getWorkerIndex:lx,getWorkerCount:_x,getTicketKeys:fx,setMainIsWorker:qne,setTerminateTimeout:xne,restartNumber:Vn?.restartNumber||1};ms.onMessageByType=mx;ms.sendToThread=function(e,t){if(!t?.type)throw new Error("A message with a type must be provided");let r=ms.find(s=>s.threadId===e);if(r)return r.postMessage(t),!0};var hA;function xne(e){EA=e}a(xne,"setTerminateTimeout");function lx(){return Vn?Vn.workerIndex:hA?0:void 0}a(lx,"getWorkerIndex");function _x(){return Vn?Vn.workerCount:hA?1:void 0}a(_x,"getWorkerCount");function qne(e){hA=e}a(qne,"setMainIsWorker");var dx=1,DE;function fx(){return DE||(DE=fA?Mne(48):Vn.ticketKeys,DE)}a(fx,"getTicketKeys");Object.defineProperty(nx,"workerIndex",{get(){return lx()}});Object.defineProperty(nx,"workerCount",{get(){return _x()}});var Ex={[ox](e,t){Qne(t)},[ax](e,t){zne(t,e)}};function lA(e,t={}){let r=process.constrainedMemory?.()||ex();r=Math.min(r,ex(),2e4*tx);let s=ix.get(gl.CONFIG_PARAMS.THREADS_MAXHEAPMEMORY)??Math.max(Math.floor(r/tx/(10+(t.threadCount||1)/4)),512),n=Math.min(Math.max(s>>6,16),64),i=[],o=[];for(let u of ms){let _=new Nne;_.existingPort=u,i.push(_),o.push(_.port2)}Cne(e)||(e+=".js");let c=new bne(wne(e)?e:sx(Ine,e),Object.assign({resourceLimits:{maxOldGenerationSizeMb:s,maxYoungGenerationSizeMb:n},execArgv:["--enable-source-maps"],argv:process.argv.slice(2),workerData:{addPorts:o,addThreadIds:i.map(u=>u.existingPort.threadId),workerIndex:t.workerIndex,workerCount:dx=t.threadCount,name:t.name,restartNumber:Li.exports.restartNumber,ticketKeys:fx()},transferList:o},t));for(let{port1:u,existingPort:_}of i)_.postMessage({type:ux,port:u,threadId:c.threadId},[u]);return ME(c,!0),c.unexpectedRestarts=t.unexpectedRestarts||0,c.startCopy=()=>lA(e,t),c.on("error",u=>{console.error("Worker error:",u),$n.error("Worker error:",u)}),c.on("exit",u=>{Di.splice(Di.indexOf(c),1),!c.wasShutdown&&t.autoRestart!==!1&&(c.unexpectedRestarts<vne?(t.unexpectedRestarts=c.unexpectedRestarts+1,lA(e,t)):$n.error(`Thread has been restarted ${c.restarts} times and will not be restarted`))}),c.on("message",u=>{Ex[u.type]?.(u,c)}),Di.push(c),jne(),t.onStarted&&t.onStarted(c),c.name=t.name,c}a(lA,"startWorker");var Gne=[gl.THREAD_TYPES.HTTP];async function mA(e=null,t=Math.max(dx>3,1),r=!0){if(fA){if(r){let{loadRootComponents:o}=QR();await o()}Li.exports.restartNumber++,t<1&&(t=t*Di.length);let s=[],n=[];for(let o of Di.slice(0)){if(e&&o.name!==e||o.wasShutdown)continue;$n.trace("sending shutdown request to ",o.threadId),o.postMessage({restartNumber:Li.exports.restartNumber,type:gl.ITC_EVENT_TYPES.SHUTDOWN}),o.wasShutdown=!0,o.emit("shutdown",{});let c=Gne.indexOf(o.name)>-1,u=new Promise(_=>{let l=setTimeout(()=>o.terminate(),EA*2).unref();o.on("exit",()=>{clearTimeout(l),s.splice(s.indexOf(u)),!c&&r&&o.startCopy(),_()})});if(s.push(u),c&&r){let _=o.startCopy(),l=new Promise(d=>{let f=a(E=>{E.type===Pne.ITC_EVENT_TYPES.CHILD_STARTED&&($n.trace("Worker has started",_.threadId),d(),n.splice(n.indexOf(l)),_.off("message",f))},"startListener");$n.trace("Waiting for worker to start",_.threadId),_.on("message",f)});n.push(l),s.length>=t&&await Promise.race(s),n.length>=t&&await Promise.race(n)}}await Promise.all(s),await Promise.all(n);let{restartService:i}=_f();r&&(e==="http"||!e)&&ix.get(gl.CONFIG_PARAMS.CLUSTERING_ENABLED)&&await i({service:"clustering"})}else En.postMessage({type:Bne,workerType:e})}a(mA,"restartWorkers");function Fne(e,t){Ex[e]=t}a(Fne,"setChildListenerByType");function kne(e){return mA(e,1/0,!1)}a(kne,"shutdownWorkers");var hx=[];function Vne(e){hx.push(e)}a(Vne,"onMessageFromWorkers");var _A=new Map;function mx(e,t){let r=_A.get(e);r||_A.set(e,r=[]),r.push(t)}a(mx,"onMessageByType");var $ne=10;async function Yne(e){let t=0;for(let r of ms)try{r.postMessage(e),t++>$ne&&(t=0,await new Promise(setImmediate))}catch(s){$n.error("Unable to send message to worker",s)}}a(Yne,"broadcast");var LE=new Map,Kne=1;function Wne(e){return new Promise(t=>{let r=0;for(let s of ms)try{let n=Kne++,i=a(()=>{LE.delete(n),--r===0&&t(),s!==En&&--s.refCount===0&&s.unref()},"ack_handler");i.port=s,s.ref(),s.refCount=(s.refCount||0)+1,LE.set(e.requestId=n,i),s.hasAckCloseListener||(s.hasAckCloseListener=!0,s.on(s.close?"close":"exit",()=>{for(let[,o]of LE)o.port===s&&o()})),s.postMessage(e),r++}catch(n){$n.error("Unable to send message to worker",n)}r===0&&t()})}a(Wne,"broadcastWithAcknowledgement");function Qne(e){e.postMessage({type:cx,workers:px()})}a(Qne,"sendThreadInfo");function px(){let e=Date.now();return Di.map(t=>({threadId:t.threadId,name:t.name,heapTotal:t.resources?.heapTotal,heapUsed:t.resources?.heapUsed,externalMemory:t.resources?.external,arrayBuffers:t.resources?.arrayBuffers,sinceLastUpdate:e-t.resources?.updated,...t.recentELU}))}a(px,"getChildWorkerInfo");function zne(e,t){e.resources=t,e.resources.updated=Date.now()}a(zne,"recordResourceReport");var dA;function Jne(e){dA=e}a(Jne,"setMonitorListener");var Xne=1e3,rx=!1;function jne(){rx||(rx=!0,setInterval(()=>{for(let e of Di){let t=e.performance.eventLoopUtilization(),r;e.lastTotalELU?r=e.performance.eventLoopUtilization(t,e.lastTotalELU):r=t,e.lastTotalELU=t,e.recentELU=r}dA&&dA()},Xne).unref())}a(jne,"startMonitoring");var Zne=1e3;if(En){ME(En);for(let e=0,t=Vn.addPorts.length;e<t;e++){let r=Vn.addPorts[e];r.threadId=Vn.addThreadIds[e],ME(r)}setInterval(()=>{let e=process.memoryUsage();En.postMessage({type:ax,heapTotal:e.heapTotal,heapUsed:e.heapUsed,external:e.external,arrayBuffers:e.arrayBuffers})},Zne).unref(),uA=a(()=>new Promise((e,t)=>{En.on("message",r),En.postMessage({type:ox});function r(s){s.type===cx&&(En.off("message",r),e(s.workers))}a(r,"receiveThreadInfo")}),"getThreadInfo")}else uA=px;Li.exports.getThreadInfo=uA;function ME(e,t){ms.push(e),e.on("message",r=>{if(r.type===ux)r.port.threadId=r.threadId,ME(r.port);else if(r.type===Hne){let s=LE.get(r.id);s&&s()}else{for(let n of hx)n(r,e);let s=_A.get(r.type);if(s)for(let n of s)try{n(r,e)}catch(i){$n.error(i)}}}).on("close",()=>{ms.splice(ms.indexOf(e),1)}).on("exit",()=>{ms.splice(ms.indexOf(e),1)}),t?e.refCount=100:e.unref()}a(ME,"addPort");if(fA){let e,t,r=a(async(s,n)=>{n&&(e=n);for(let i of await Lne(s,{withFileTypes:!0}))i.isDirectory()&&i.name!=="node_modules"&&r(sx(s,i.name));try{for await(let{filename:i}of Dne(s,{persistent:!1}))t&&clearTimeout(t),t=setTimeout(async()=>{e&&await e(),await mA(),console.log("Reloaded HarperDB components")},100)}catch(i){console.warn("Error trying to watch component directory",s,i)}},"watch_dir");Li.exports.watchDir=r,process.env.WATCH_DIR&&r(process.env.WATCH_DIR)}else En.on("message",async e=>{let{type:t}=e;t===gl.ITC_EVENT_TYPES.SHUTDOWN&&(Li.exports.restartNumber=e.restartNumber,En.unref(),setTimeout(()=>{$n.warn("Thread did not voluntarily terminate",yne),process.exit(0)},EA).unref())})});var SC={};Ye(SC,{AUDIT_STORE_OPTIONS:()=>Ix,createAuditEntry:()=>o_,openAuditStore:()=>BE,readAuditEntry:()=>Lt,setAuditRetention:()=>tie,transactionKeyEncoder:()=>yx});function BE(e){let t=e.auditStore=e.openDB(Ox.AUDIT_STORE_NAME,Ix);t.rootStore=e;let r=[];t.addDeleteRemovalCallback=function(i,o){return r[i]=o,{remove(){delete r[i]}}};let s=null;function n(i=UE){clearTimeout(s),s=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()-pA})){if((_[0]&15)===gA){let l=Lt(_),d=l.tableId;r[d]?.(l.recordId)}if(c=t.remove(u),await new Promise(setImmediate),++o>=eie){i=10;break}}await c}finally{o===0&&(i=Math.min(i<<1,pA/10)),n(i)}},i).unref()}return a(n,"scheduleAuditCleanup"),t.scheduleAuditCleanup=n,(0,vE.getWorkerIndex)()===(0,vE.getWorkerCount)()-1&&n(UE),t}function tie(e,t=UE){pA=e,UE=t}function o_(e,t,r,s,n,i,o){let c=wx[i];if(!c)throw new Error(`Invalid audit entry type ${i}`);let u=1;s&&(s>1?Qa.setFloat64(0,s):ps.set(nm),u=9),f(0),f(t),d(r),Qa.setFloat64(u,e),u+=8,n?d(n):ps[u++]=0,ps[s?8:0]=c;let l=ps.subarray(0,u);if(o)return Buffer.concat([l,o]);return l;function d(E){let h=u;u+=1,u=(0,za.writeKey)(E,ps,u);let p=u-h-1;p>127?p>16383?(AA.error("Key or username was too large for audit entry",E),u=h+1,ps[h]=0):(ps.copyWithin(h+2,h+1,u),Qa.setUint16(h,p|32768),u++):ps[h]=p}function f(E){E<128?ps[u++]=E:E<16384?(Qa.setUint16(u,E|32768),u+=2):E<1056964608?(Qa.setUint32(u,E|3221225472),u+=4):(ps[u]=255,Qa.setUint32(u+1,E),u+=5)}}function Lt(e){try{let t=e.dataView||(e.dataView=new RA(e.buffer,e.byteOffset,e.byteLength)),r;e[0]==66&&(r=t.readFloat64());let s=t.readInt(),n=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:wx[s&7],tableId:i,get recordId(){return Ax(e,c,u)},version:_,previousLocalTime:r,get user(){return d>l?Ax(e,l,d):void 0},getValue(f,E,h){if(s&SA||s&TA&&!E)return f.decoder.decode(e.subarray(t.position));if(s&TA&&h)return OA(f.getEntry(this.recordId),h,f)}}}catch(t){return AA.error("Reading audit entry error",t,e),{}}}function Ax(e,t,r){let s=e.subarray(t,r);return(0,za.readKey)(s,0,r-t)}var za,PE,Ox,bx,vE,Nx,AA,ps,Qa,yx,Ix,pA,eie,UE,SA,TA,Sx,gA,Tx,gx,Rx,wx,RA,qi=Re(()=>{za=require("ordered-binary"),PE=x(ee()),Ox=x(Et()),bx=x(M()),vE=x(Ke()),Nx=x(Q());bc();AA=x($());HE();(0,PE.initSync)();ps=Buffer.alloc(1024),Qa=new DataView(ps.buffer,ps.byteOffset,1024),yx={writeKey(e,t,r){return e===Oc?(t.set(Oc,r),r+8):typeof e=="number"?((t.dataView||(t.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength))).setFloat64(r,e),r+8):(0,za.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,za.readKey)(e,t,r)}},Ix={encoding:"binary",keyEncoder:yx},pA=(0,Nx.convertToMS)((0,PE.get)(bx.CONFIG_PARAMS.LOGGING_AUDITRETENTION))||86400*3,eie=1e3,UE=1e4;a(BE,"openAuditStore");a(tie,"setAuditRetention");SA=16,TA=32,Sx=1,gA=2,Tx=3,gx=4,Rx=5,wx={put:Sx|SA,[Sx]:"put",delete:gA,[gA]:"delete",message:Tx|SA,[Tx]:"message",invalidate:gx,[gx]:"invalidate",patch:Rx|TA,[Rx]:"patch"};a(o_,"createAuditEntry");a(Lt,"readAuditEntry");RA=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(Ax,"readKeySafely")});var bA={};Ye(bA,{add:()=>xE,applyReverse:()=>Cx,getRecordAtTime:()=>OA,rebuildUpdateBefore:()=>qE});function xE(e,t,r){isNaN(e[t])?e[t]=r.value:e[t]+=r.value}function qE(e,t){let r=null;for(let s in e)if(s in t){let n=t[s];if(n?.__op__){let i=e[s];if(i?.__op__)if(i.__op__===n.__op__)r||(r={}),r[s]=i;else throw new Error("Can not merge updates with different operations");else r||(r={}),r[s]=i,xE(r,s,n)}}else r||(r={}),r[s]=e[s];return r}function Cx(e,t){for(let r in t){let s=t[r];if(s?.__op__){let n=rie[s.__op__]?.reverse;if(n)n(e,r,{value:s.value});else throw new Error(`Unsupported operation ${s.__op__}`)}else e[r]=Dx}}function OA(e,t,r){let s=r.rootStore.auditStore,n=Object.assign({},e.value),i=e.localTime;for(;i>t;){let u=s.get(i),_=Lt(u);switch(_.type){case"put":n=_.getValue(r);break;case"patch":Cx(n,_.getValue(r));break;case"delete":n=null}i=_.previousLocalTime}let o={},c=0;for(let u in n)n[u]===Dx&&(o[u]=!0,c++);for(;c>0&&i>0;){let u=s.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]&&(n[d]=l[d],o[d]=!1,c--);i=_.previousLocalTime}if(c>0)for(let u in o)n[u]=null;return n}var rie,Dx,HE=Re(()=>{qi();a(xE,"add");xE.reverse=function(e,t,r){isNaN(e[t])||(e[t]-=r.value)};rie={add:xE};a(qE,"rebuildUpdateBefore");a(Cx,"applyReverse");Dx={};a(OA,"getRecordAtTime")});function zr(e){return e[Ct]||(e[Ct]=Object.create(null))}function $E(e,t){let r=e.prototype,s={},n=t.attributes||t.properties||[];for(let o of n){let c=o.name,u,_;if(o.resolve)_={get(){return o.resolve(this,this[Oe])},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 Ss.ClientError(`${c} must be a string, attempt to assign ${l}`);zr(this)[c]=l},"set");break;case"ID":u=a(function(l){if(!(typeof l=="string"||l?.length>0&&l.every?.(d=>typeof d=="string")||l==null&&o.nullable!==!1))throw new Ss.ClientError(`${c} must be a string, attempt to assign ${l}`);zr(this)[c]=l},"set");break;case"Float":case"Number":u=a(function(l){if(!(typeof l=="number"||l==null&&o.nullable!==!1))throw new Ss.ClientError(`${c} must be a number, attempt to assign ${l}`);zr(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 Ss.ClientError(`${c} must be an integer between -2147483648 and 2147483647, attempt to assign ${l}`);zr(this)[c]=l},"set");break;case"Long":u=a(function(l){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 Ss.ClientError(`${c} must be an integer between -9007199254740992 and 9007199254740992, attempt to assign ${l}`);zr(this)[c]=l},"set");break;case"BigInt":u=a(function(l){if(!(typeof l=="bigint"||l==null&&o.nullable!==!1))if(typeof l=="string"||typeof l=="number")l=BigInt(l);else throw new Ss.ClientError(`${c} must be a number, attempt to assign ${l}`);zr(this)[c]=l},"set");break;case"Boolean":u=a(function(l){if(!(typeof l=="boolean"||l==null&&o.nullable!==!1))throw new Ss.ClientError(`${c} must be a boolean, attempt to assign ${l}`);zr(this)[c]=l},"set");break;case"Date":u=a(function(l){if(!(l instanceof Date||l==null&&o.nullable!==!1))if(typeof l=="string"||typeof l=="number")l=new Date(l);else throw new Ss.ClientError(`${c} must be a Date, attempt to assign ${l}`);zr(this)[c]=l},"set");break;case"Bytes":u=a(function(l){if(!(l instanceof Uint8Array||l==null&&o.nullable!==!1))throw new Ss.ClientError(`${c} must be a Buffer or Uint8Array, attempt to assign ${l}`);zr(this)[c]=l},"set");break;case"Any":case void 0:u=a(function(l){zr(this)[c]=l},"set");break;default:u=a(function(l){if(!(typeof l=="object"||l==null&&o.nullable!==!1))throw new Ss.ClientError(`${c} must be an object, attempt to assign ${l}`);zr(this)[c]=l},"set")}_={get(){let l=this[Ct];if(l&&c in l){let f=l[c];if(f?.__op__){let E=this[_e]?.[c];return f.update(E)}return f}let d=this[_e]?.[c];if(d&&typeof d=="object"){let f=Mx(d,o);if(f)return l||(l=this[Ct]=Object.create(null)),l[c]=f}return d},set:u,enumerable:!0,configurable:!0}}_.get.isAttribute=!0,s[c]=_,(!(c in r)||Object.getOwnPropertyDescriptor(r,c)?.get?.isAttribute)&&Object.defineProperty(r,c,_)}i("getProperty",function(o){let c=s[o];if(c)return c.get.call(this);let u=this[Ct];return u?.[o]!==void 0?u[o]:this[_e]?.[o]}),i("set",function(o,c){let u=s[o];if(u)return u.set.call(this,c);if(t.sealed)throw new Ss.ClientError("Can not add a property to a sealed table schema");zr(this)[o]=c}),i("deleteProperty",function(o){zr(this)[o]=void 0}),i("toJSON",function(){let o=this[Ct],c;for(let _ in o){c||(c=Object.assign({},this[_e]));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[_e])),Object.assign(c,this)),c||this[_e]}),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 Mx(e,t){let r;switch(e.constructor){case Object:return t?((r=t.TrackedObject)||(t.TrackedObject=r=class{static{a(this,"TrackedObject")}constructor(n){if(n?.[_e])throw new Error("Can not track an already tracked object, check for circular references");this[_e]=n}},$E(r,t)),new r(e)):new GE(e);case Array:let s=new kE(e.length);s[_e]=e;for(let n=0,i=e.length;n<i;n++){let o=e[n];o&&typeof o=="object"&&(o=Mx(o,t?.elements)),s[n]=o}return s;default:return e}}function nd(e){let t=e[Ct],r;for(let n in t){r||(r=Object.assign({},e[_e]));let i=t[n];if(i&&typeof i=="object")if(i.__op__){let o=r[n];i=i.update(o)}else i=nd(i);r[n]=i}return Object.keys(e).length>0&&(r||(r=Object.assign({},e[_e])),Object.assign(r,e)),r||e[_e]}function Lo(e,t=e[Ct]){let r;if(Lx.call(e,_e)&&e.constructor===Array&&!Object.isFrozen(e)){r=e;for(let s=0,n=e.length;s<n;s++){let i=e[s];if(i&&typeof i=="object"){let o=Lo(i);o!==i&&r===e&&(r=e.slice(0)),i=o}r[s]=i}return Object.freeze(r)}for(let s in t){r||(r=Object.assign({},e[_e]));let n=t[s];if(n&&typeof n=="object")if(n.__op__){let i=bA[n?.__op__];if(i)i(r,s,n);else throw new Error("Invalid CRDT operation "+n.__op__);continue}else n=Lo(n);r[s]=n}return r?Object.freeze(r):Lx.call(e,_e)?e[_e]:e}function FE(e){let t=e[_e];if(t===void 0)return!0;if(e.constructor===Array){if(!t||e[Do]||e.length!==t.length)return!0;for(let r=0,s=e.length;r<s;r++){let n=t[r],i=e[r];if(n&&i?.[_e]===n){if(FE(i))return!0}else return!0}}else{let r=e[Ct];if(r&&!t)return!0;for(let s in r){let n=r[s];if(n&&typeof n=="object"){let i=t[s];if(i&&n[_e]===i){if(FE(n))return!0}else return!0}else return!0}}return!1}var Ss,Ct,GE,Lx,Do,kE,VE,id=Re(()=>{Ns();Ss=x(se());HE();Ct=Symbol("own-data");a(zr,"getChanges");a($E,"assignTrackedAccessors");a(Mx,"trackObject");GE=class{static{a(this,"GenericTrackedObject")}constructor(t){if(t?.[_e])throw new Error("Can not track an already tracked object, check for circular references");this[_e]=t}};$E(GE,{});a(nd,"collapseData");Lx=Object.prototype.hasOwnProperty;a(Lo,"deepFreeze");a(FE,"hasChanges");Do=Symbol.for("has-array-changes"),kE=class extends Array{static{a(this,"TrackedArray")}[Do];constructor(t){super(t)}splice(...t){return this[Do]=!0,super.splice(...t)}push(...t){return this[Do]=!0,super.push(...t)}pop(){return this[Do]=!0,super.pop()}unshift(...t){return this[Do]=!0,super.unshift(...t)}shift(){return this[Do]=!0,super.shift()}};kE.prototype.constructor=Array;VE=class{constructor(t){this.value=t}static{a(this,"Addition")}__op__="add";update(t){return(+t||0)+this.value}}});var Dp={};Ye(Dp,{CONTEXT:()=>Oe,ID_PROPERTY:()=>Me,IS_COLLECTION:()=>Ts,RECORD_PROPERTY:()=>_e,Resource:()=>Ft,snake_case:()=>nie,transformForSelect:()=>KE});function nie(e){return e[0].toLowerCase()+e.slice(1).replace(/[a-z][A-Z][a-z]/g,t=>t[0]+"_"+t.slice(1))}function Ux(e,t){if(Rl=!1,e==="")return null;if(e=e.slice(1),e.indexOf("/")===-1)return e===""?(Rl=!0,null):(e.startsWith("$")&&(e=parseInt(e,36)),t.coerceId(decodeURIComponent(e)));let r=e.split("/"),s=new yA;for(let n=0;n<r.length;n++){let i=r[n];if(!i&&n===r.length-1){Rl=!0;break}s[n]=t.coerceId(decodeURIComponent(i))}return s}function Jr(e,t){s.reliesOnPrototype=!0;let r=t.hasContent;return s;function s(n,i,o){let c,u,_,l;if(r?(o?(l=i,o=o[Oe]||o):i?typeof n=="object"&&n&&(!Array.isArray(n)||typeof n[0]=="object")?(l=n,c=l[this.primaryKey]??null,o=i[Oe]||i):l=i:(l=n,c=l[Me]??l[this.primaryKey]??null),c==null&&(_=!0)):i?o=i[Oe]||i:n&&typeof n=="object"&&!Array.isArray(n)&&(o=n),c===void 0)if(typeof n=="string")c=n;else if(typeof n=="object"&&n)if(u=n,n[Symbol.iterator]){c=[],_=!0;for(let E of n){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=n.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=n.id??null,c==null&&(_=!0))}else c=n??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 je(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 YE(o.user);return typeof l?.then=="function"?l.then(S=>e(E,u,o,S)):e(E,u,o,l)});if(!h)throw new YE(o.user)}return typeof l?.then=="function"?l.then(h=>e(E,u,o,h)):e(E,u,o,l)}a(f,"authorizeActionOnResource")}}function Xr(e,t){let r=new Bx.ClientError(`The ${e.constructor.name} does not have a ${t} method implemented`,405);r.allow=[],r.method=t;for(let s of["get","put","post","delete","query","move","copy"])typeof e[s]=="function"&&r.allow.push(s);throw r}function NA(e,t,r){let s=e[_e];if(s){let n=e[Ct];return i=>{let o,c;return e.hasOwnProperty(i)&&typeof(o=e[i])!="function"?o:n&&i in n?n[i]:(c=t?.[i])?c(e,r):s[i]}}else return t?n=>{let i=t[n];return i?i(e,r):e[n]}:n=>e[n]}function KE(e,t){let r=t?.propertyResolvers,s=t[Oe],n;if(typeof e=="string")return a(function o(c){return c.then?c.then(o):Array.isArray(c)?c.map(o):NA(c,r,s)(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(NA(u,r,s));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(NA(u,r,s)),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){n||(n={});let u=n[c.name];if(!u){let l=r[c.name]?.definition?.tableClass;u=n[c.name]=KE(c.select||c,l)}let _=o(c.name);return u(_)}else return o(c);else return c}}a(i,"handleProperty")}var Px,vx,Bx,Oe,Me,Ts,_e,sie,Ft,YE,Rl,yA,Ns=Re(()=>{Px=require("crypto");pc();vx=require("../index"),Bx=x(se());id();ro();Gf();Oe=Symbol.for("context"),Me=Symbol.for("primary-key"),Ts=Symbol("is-collection"),_e=Symbol("stored-record"),sie={json:"application/json",cbor:"application/cbor",msgpack:"application/x-msgpack",csv:"text/csv"},Ft=class{static{a(this,"Resource")}static transactions;constructor(t,r){this[Me]=t;let s=r?.[Oe];this[Oe]=s!==void 0?s:r||null}static get=Jr(function(t,r,s,n){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 _=KE(u,t.constructor);return typeof c?.map=="function"?c.map(_):_(c)}return c}},{type:"read",letItLinger:!0,ensureLoaded:!0,async:!0});static put=Jr(function(t,r,s,n){if(Array.isArray(n)&&t[Ts]){let i=[],o=s.authorize;for(let c of n){let u=t.constructor,_=u.getResource(c[u.primaryKey],s,{async:!0});_.then?i.push(_.then(l=>l.put(c,s))):i.push(_.put(c,s))}return Promise.all(i)}return t.put?t.put(n,r):Xr(t,"put")},{hasContent:!0,type:"update"});static patch=Jr(function(t,r,s,n){return t.patch?t.patch(n,r):Xr(t,"patch")},{hasContent:!0,type:"update"});static delete=Jr(function(t,r,s,n){return t.delete?t.delete(r):Xr(t,"delete")},{hasContent:!1,type:"delete"});static getNewId(){return(0,Px.randomUUID)()}static create(t,r,s){let n;return t==null?n=this.getNewId():Array.isArray(t)&&typeof t[0]!="object"?n=[...t,this.getNewId()]:typeof t!="object"?n=[t,this.getNewId()]:(n=this.getNewId(),s=r,r=t),je(s,()=>{let i=new this(n,s),o=i.update?i.update(r):Xr(i,"update");return s.newLocation=n,s.createdResource=!0,o?.then?o.then(()=>n):n})}static invalidate=Jr(function(t,r,s,n){return t.invalidate?t.invalidate(r):Xr(t,"delete")},{hasContent:!1,type:"update"});static post=Jr(function(t,r,s,n){return t[Me]!=null&&t.update?.(),t.post(n,r)},{hasContent:!0,type:"create"});static connect=Jr(function(t,r,s,n){return t.connect?t.connect(n,r):Xr(t,"connect")},{hasContent:!0,type:"read"});static subscribe=Jr(function(t,r,s,n){return t.subscribe?t.subscribe(r):Xr(t,"subscribe")},{type:"read"});static publish=Jr(function(t,r,s,n){return t[Me]!=null&&t.update?.(),t.publish?t.publish(n,r):Xr(t,"publish")},{hasContent:!0,type:"create"});static search=Jr(function(t,r,s,n){let i=t.search?t.search(r):Xr(t,"search"),o=s.select;if(o&&s.hasOwnProperty("select")&&i!=null&&!i.selectApplied){let c=KE(o,t.constructor);return i.map(c)}return i},{type:"read"});static query=Jr(function(t,r,s,n){return t.search?t.search(n,r):Xr(t,"search")},{hasContent:!0,type:"read"});static copy=Jr(function(t,r,s,n){return t.copy?t.copy(n,r):Xr(t,"copy")},{type:"create"});static move=Jr(function(t,r,s,n){return t.move?t.move(n,r):Xr(t,"move")},{type:"delete"});post(t){if(this[Ts])return this.constructor.create(this[Me],t,this[Oe]);Xr(this,"post")}static isCollection(t){return t?.[Ts]}static coerceId(t){return t}static parseQuery(t){return qf(t)}static parsePath(t,r,s){let n=t.indexOf(".");if(n>-1){let o=t.slice(n+1);t=t.slice(0,n);let c=r?.headers&&sie[o];if(c)r.headers.set("accept",c);else if(s)s.property=o;else return{query:{property:o},id:Ux(t,this),isCollection:Rl}}let i=Ux(t,this);return Rl?{id:i,isCollection:!0}:i}static getResource(t,r,s){let n,i=r[Oe],o;typeof r.isCollection=="boolean"&&r.hasOwnProperty("isCollection")?o=r.isCollection:o=s?.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(n=_?.find(l=>l.constructor===c),n)return n;_||u.asMap.set(t,_=[]),_.push(n=new c(t,i))}else{if(n=u.find(_=>_[Me]===t&&_.constructor===c),n)return n;if(u.push(n=new c(t,i)),u.length>10){let _=new Map;for(let l of u){let d=l[Me],f=_.get(d);f?f.push(l):_.set(d,[l])}i.resourceCache.length=0,i.resourceCache.asMap=_}}}else n=new c(t,i);return o&&(n[Ts]=!0),n}subscribe(t){return new bs}connect(t){return t?.subscribe!==!1?this.subscribe?.(t):new bs}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[Me]}getContext(){return this[Oe]}};Ft.prototype[Oe]=null;(0,vx._assignPackageExport)("Resource",Ft);a(nie,"snake_case");YE=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(Ux,"pathToId");yA=class extends Array{static{a(this,"MulitPartId")}toString(){return this.join("/")}};a(Jr,"transactional");a(Xr,"missingMethod");a(NA,"selectFromObject");a(KE,"transformForSelect")});function xx(e,t,r,s){let n=e.primaryStore.env.path,i=e.primaryStore.tableId;Ja||((0,WE.onMessageByType)(Hx,l=>{qx(l.path)}),Ja=Object.create(null));let o=Ja[n]||(Ja[n]=[]);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=Ra(t);let u=new wA(r);u.startTime=s;let _=c.get(t);return _?_.push(u):(c.set(t,_=[u]),_.tables=c,_.key=t),u.subscriptions=_,u}function qx(e,t){if(!Ja)return;let r=Ja[e];if(!r)return;try{r.auditStore.resetReadTxn()}catch(n){throw n.message+=" in "+e,n}let s;for(let{key:n,value:i}of r.auditStore.getRange({start:r.lastTxnTime,exclusiveStart:!0})){r.lastTxnTime=n;let o=Lt(i),c=r[o.tableId];if(!c)continue;let u=o.recordId,_,l=Ra(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>=n){(0,IA.info)("omitting",u,h.startTime,n);continue}try{if(h.crossThreads===!1&&!t)continue;let p;h.supportsTransactions&&h.txnInProgress!==o.version&&(p=!0,h.txnInProgress||(s?s.push(h):s=[h]),h.txnInProgress=o.version),h.listener(u,o,n,p)}catch(p){console.error(p),(0,IA.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(s)for(let n of s)n.txnInProgress=null,n.listener(null,{type:"end_txn"},r.lastTxnTime,!0)}function Gx(e,t){let r=t||e,s=r.env;if(t&&!t.cache&&(t.cache=new Map),!s.hasBroadcastListener){s.hasBroadcastListener=!0;let n=s.path;r.on("aftercommit",()=>{(0,WE.broadcast)({type:Hx,path:n}),qx(n,!0)})}}var IA,WE,Hx,Ja,hSe,wA,Fx=Re(()=>{IA=x($()),WE=x(Ke());pc();xu();qi();Hx="transaction",hSe=Buffer.alloc(4096);a(xx,"addSubscription");wA=class extends bs{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 s=t.envs,n=t.dbi;delete s[n]}}this.subscriptions=null}}toJSON(){return{name:"subscription"}}};a(qx,"notifyFromTransactionData");a(Gx,"listenToCommits")});var cR={};Ye(cR,{coerceType:()=>QE,makeTable:()=>XE,setServerUtilities:()=>fie,updateResource:()=>zE});function XE(e){let{primaryKey:t,indices:r,tableId:s,tableName:n,primaryStore:i,databasePath:o,databaseName:c,auditStore:u,schemaDefined:_,dbisDB:l,sealed:d}=e,{expirationMS:f,evictionMS:E,audit:h,trackDeletes:p}=e,{attributes:S}=e;S||(S=[]),Gx(i,u);let T=am(i,s,u),b=0,R,L,H={},P=Promise.resolve(),k,B,X;for(let K of S)(K.assignCreatedTime||K.name==="__createdtime__")&&(k=K),(K.assignUpdatedTime||K.name==="__updatedtime__")&&(B=K),K.expiresAt&&(X=K),K.isPrimaryKey&&(H=K);let z,J=[],de=[],ce=1,fe=2,Le={},Be={},Dt=864e5,ql,Gl,Wn,zA=!1,Eh,Yq=i.getRange({start:!1,end:!1}).constructor,Kq=10,Wq=6;h&&jA();class ze extends Ft{static name=n;static primaryStore=i;static auditStore=u;static primaryKey=t;static tableName=n;static indices=r;static audit=h;static databasePath=o;static databaseName=c;static attributes=S;static expirationTimer;static createdTimeProperty=k;static updatedTimeProperty=B;static propertyResolvers;static sources=[];static get expirationMS(){return f}static dbisDB=l;static schemaDefined=_;static sourcedFrom(m,O){O&&(this.sourceOptions=O,(O.expiration||O.eviction||O.scanInterval)&&this.setTTLExpiration(O)),O?.intermediateSource?(m.intermediateSource=!0,this.sources.unshift(m)):this.sources.push(m),L=m.get&&(!m.get.reliesOnPrototype||m.prototype.get);let I=a(D=>{let y=this.sources.slice(0,-1);if(y=y.filter(U=>U[D]&&(!U[D].reliesOnPrototype||U.prototype[D])),y.length>0)if(y.length===1){let U=y[0];return(G,C,v)=>{if(G?.source!==U)return U[D](C,v,G)}}else return(U,G,C)=>{let v=[];for(let F of y){if(U?.source===F)break;v.push(F[D](G,C,U))}return Promise.all(v)}},"getApplyToIntermediateSource"),N=this.sources[this.sources.length-1],A=a(D=>{if(N[D]&&(!N[D].reliesOnPrototype||N.prototype[D]))return(y,U,G)=>{if(!y?.source)return N[D](U,G,y)}},"getApplyToCanonicalSource");return Le={put:A("put"),patch:A("patch"),delete:A("delete"),publish:A("publish")},Be={put:I("put"),patch:I("patch"),delete:I("delete"),publish:I("publish"),invalidate:I("invalidate")},(async()=>{let D=!1,y=a(async(U,G)=>{let C=U.value,v=U.table?st[c][U.table]:ze;if(c===$s.SYSTEM_SCHEMA_NAME&&(U.table===$s.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME||U.table===$s.SYSTEM_TABLE_NAMES.USER_TABLE_NAME)&&(D=!0),U.id===void 0&&(U.id=C[v.primaryKey],U.id===void 0))throw new Error("Replication message without an id "+JSON.stringify(U));U.source=m;let F=await v.getResource(U.id,G,Xa);switch(U.type){case"put":return F._writeUpdate(C,!0,Xa);case"patch":return F._writeUpdate(C,!1,Xa);case"delete":return F._writeDelete(Xa);case"publish":return F._writePublish(C,Xa);case"invalidate":return F.invalidate(Xa);default:et.error("Unknown operation",U.type,U.id)}},"writeUpdate");try{let U=m.subscribe;U&&p==null&&(p=!0);let G=m.subscribeOnThisThread?m.subscribeOnThisThread((0,Uo.getWorkerIndex)()):(0,Uo.getWorkerIndex)()===0,C=U&&G&&await m.subscribe?.({crossThreads:!1,inTransactionUpdates:!0,supportsTransactions:!0,omitCurrent:!0});if(C){let v;for await(let F of C)try{if(!(F.type==="transaction"?F.writes[0]:F)){et.error("Bad subscription event",F);continue}if(F.source=m,v)if(F.beginTxn)v.resolve();else{y(F,v);continue}if(F.type==="end_txn")continue;let be=je(F,()=>{if(F.type==="transaction"){let te=[];for(let Pe of F.writes)try{te.push(y(Pe,F))}catch(ae){throw ae.message+=" writing "+JSON.stringify(Pe)+" of event "+JSON.stringify(F),ae}return Promise.all(te)}else if(F.type==="define_schema"){let te=this.attributes.slice(0),Pe;for(let ae of F.attributes)te.find(qe=>qe.name===ae.name)||(te.push(ae),Pe=!0);Pe&&(ut({table:n,database:c,attributes:te,origin:"cluster"}),wl.signalSchemaChange(new Cl.SchemaEventMsg(process.pid,$s.OPERATIONS_ENUM.CREATE_TABLE,c,n)))}else return F.beginTxn?(v=F,y(F,F),new Promise(te=>{v.resolve=te})):y(F,F)});D&&(await be,wl.signalUserChange(new Cl.UserEventMsg(process.pid))),F.onCommit&&(be?.then?be.then(F.onCommit):F.onCommit())}catch(oe){et.error("error in subscription handler",oe)}}}catch(U){et.error(U)}})(),this}static getResource(m,O,I){let N=super.getResource(m,O,I);if(m!=null){rc(m);try{if(N.hasOwnProperty(_e))return N;if(typeof m=="object"&&m&&!Array.isArray(m))throw new Error(`Invalid id ${JSON.stringify(m)}`);let A=!I?.async||i.cache?.get(m),D=As(O),y=D.getReadTxn();if(y?.isDone)throw new Error("You can not read from a transaction that has already been committed/aborted");return hh(m,O,{transaction:y},A,U=>{if(U?zE(N,U):N[_e]=null,O.onlyIfCached&&O.noCacheStore){if(!N.doesExist())throw new gs.ServerError("Entry is not cached",504)}else if(I?.ensureLoaded){let G=mh(m,U,O,N);if(G)return D?.disregardReadTxn(),N[CA]=!0,LA(G,C=>(zE(N,C),N))}return N})}catch(A){throw A.message.includes("Unable to serialize object")&&(A.message+=": "+JSON.stringify(m)),A}}return N}ensureLoaded(){let m=mh(this[Me],this[jr],this[Oe]);if(m)return this[CA]=!0,LA(m,O=>{this[jr]=O,this[_e]=O.value,this[yl]=O.version})}static setTTLExpiration(m){if(typeof m=="number")f=m*1e3,E||(E=0);else if(m&&typeof m=="object")f=m.expiration*1e3,E=(m.eviction||0)*1e3,Dt=m.scanInterval*1e3;else throw new Error("Invalid expiration value type");if(f<0)throw new Error("Expiration can not be negative");Dt=Dt||(f+E)/4,Sh()}static enableAuditing(m=!0){h=m,m&&jA(),ze.audit=m}static coerceId(m){return m===""?null:QE(m,H)}static async dropTable(){if(delete st[c][n],c===o){for(let m of S)l.remove(ze.tableName+"/"+m.name),r[m.name]?.drop();l.remove(ze.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));wl.signalSchemaChange(new Cl.SchemaEventMsg(process.pid,$s.OPERATIONS_ENUM.DROP_TABLE,c,n))}get(m){if(typeof m=="string")return this.getProperty(m);if(this[Ts])return this.search(m);if(this[Me]===null){if(m?.conditions)return this.search(m);let O=ze.getRecordCount();return{recordCount:O.recordCount,estimatedRecordRange:O.estimatedRange,records:"./",name:n,database:c,attributes:S}}if(m?.property)return this.getProperty(m.property);if(this.doesExist()||m?.ensureLoaded===!1||this[Oe]?.returnNonexistent)return this}allowRead(m,O){let I=kl(m);if(I?.read){if(I.isSuperUser)return!0;let N=I.attribute_permissions,A=O?.select;if(N?.length>0||zA&&A){if(O||(O={}),A){let D=N?.length>0&&DA(N,"read");O.select=A.map(y=>{let U=y.name||y;if(!D||D[U]){let G=Wn[U]?.definition?.tableClass;if(G){if(y.name||(y={name:y}),!G.prototype.allowRead.call(null,m,y))return!1;if(!y.select)return y.name}return y}}).filter(Boolean)}else O.select=N.filter(D=>D.read&&!Wn[D.attribute_name]).map(D=>D.attribute_name);return O}else return!0}}allowUpdate(m,O){let I=kl(m);if(I?.update){let N=I.attribute_permissions;if(N?.length>0){let A=DA(N,"update");for(let D in O)if(!A[D])return!1;for(let D of N){let y=D.attribute_name;!D.update&&!(y in O)&&(O[y]=this.getProperty(y))}}return!0}}allowCreate(m,O){if(this[Ts]){let I=kl(m);if(I?.insert){let N=I.attribute_permissions;if(N?.length>0){let A=DA(N,"insert");for(let D in O)if(!A[D])return!1}else return!0}}else return this.allowUpdate(m,{})}allowDelete(m){return kl(m)?.delete}update(m,O){if(!As(this[Oe]))throw new Error("Can not update a table resource outside of a transaction");if(m===!1)return this;let N;return typeof m=="object"&&m&&(O?(Object.isFrozen(m)&&(m=Object.assign({},m)),this[_e]={},this[Ct]=m):(N=this[Ct],N&&(m=Object.assign(N,m)),this[Ct]=N=m)),this._writeUpdate(this[Ct],O),this}addTo(m,O){if(typeof O=="number")this[Al]===Vx?this.set(m,(+this.getProperty(m)||0)+O):(this[Al]||this.update(),this.set(m,new VE(O)));else throw new Error("Can not add a non-numeric value")}subtractFrom(m,O){if(typeof O=="number")return this.addTo(m,-O);throw new Error("Can not subtract a non-numeric value")}invalidate(m){let O=this[Oe],I=this[Me];rc(I),As(this[Oe]).addWrite({key:I,store:i,invalidated:!0,entry:this[jr],nodeName:this[Oe]?.nodeName,before:Le.invalidate?.bind(this,O,I),beforeIntermediate:Be.invalidate?.bind(this,O,I),commit:(A,D)=>{if(D?.version>A)return;let y=null;for(let U in r)y||(y={}),y[U]=this.getProperty(U);T(I,y,this[jr],A,Ol,h,this[Oe],0,"invalidate")}})}static evict(m,O,I){let N=this.Source,A;if(!((L||h)&&(!O||(A=i.getEntry(m),!A||!O)||A.version!==I))){if(L){if(i.hasLock(m,A.version))return;let D;for(let y in r)D||(D={}),D[y]=O[y];if(D)return T(m,D,A,I,bl,null,null,0,null,!0)}return i.ifVersion(m,I,()=>{Fl(m,O,null)}),h?T(m,null,A,I,bl,null,null,0,null,!0):i.remove(m,I)}}lock(){throw new Error("Not yet implemented")}static operation(m,O){return m.table||=n,m.schema||=c,zx.operation(m,O)}put(m){this.update(m,!0)}patch(m){this.update(m,!1)}_writeUpdate(m,O,I){let N=this[Oe],A=As(N),D=this[Me];rc(D);let y=this[jr];this[Al]=O?Vx:lie;let U={key:D,store:i,entry:y,nodeName:N?.nodeName,validate:G=>{m||(m=this[Ct]),O||m&&FE(m)?N?.source||(A.checkOverloaded(),this.validate(m,!O),B&&(m[B.name]=B.type==="Date"?new Date(G):B.type==="String"?new Date(G).toISOString():G),O&&(t&&m[t]!==D&&(m[t]=D),k&&(y?.value?m[k.name]=y?.value[k.name]:m[k.name]=k.type==="Date"?new Date(G):k.type==="String"?new Date(G).toISOString():G),m=Lo(m))):A.removeWrite(U)},before:O?Le.put?()=>Le.put(N,D,m):null:Le.patch?()=>Le.patch(N,D,m):Le.put?()=>Le.put(N,D,Lo(this)):null,beforeIntermediate:O?Be.put?()=>Be.put(N,D,m):null:Be.patch?()=>Be.patch(N,D,m):Be.put?()=>Be.put(N,D,Lo(this)):null,commit:(G,C,v)=>{if(v){if(N&&C?.version>(N.lastModified||0)&&(N.lastModified=C.version),this[jr]=C,C?.value?.[_e])throw new Error("Can not assign a record to a record, check for circular references");O||(this[_e]=C?.value??null)}this[Ct]=m,this[yl]=G;let F=C?.value,oe=m;if(this[Al]=0,C?.version>=G)if(h){let ae=C.localTime,qe=C.version;for(;oe&&(ae>G||qe>=G&&ae>0);){let re=u.get(ae);if(!re)break;let j=Lt(re);if(qe=j.version,qe>G){if(j.type==="patch"){let ge=j.getValue(i);oe=qE(oe,ge)}else if(j.type==="put"||j.type==="delete")return}else if(qe===G)return;ae=j.previousLocalTime}}else{if(O)return;oe=qE(oe,F)}let be;if(O?be=oe:(this[_e]=F,be=O?oe:Lo(this,oe)),this[_e]=be,be?.[_e])throw new Error("Can not assign a record to a record, check for circular references");let te;O||(te=m),Fl(D,F,be);let Pe=O?"put":"patch";T(D,be,C,G,0,h,N,N.expiresAt||(f?f+Date.now():0),Pe,!1,te)}};A.addWrite(U)}async delete(m){if(typeof m=="string")return this.deleteProperty(m);if(this[Ts]){for await(let O of this.search(m))(await ze.getResource(O[t],this.getContext(),{ensureLoaded:!1}))._writeDelete(m);return}return this[_e]?this._writeDelete(m):!1}_writeDelete(m){let O=As(this[Oe]),I=this[Me];rc(I);let N=this[Oe];return O.addWrite({key:I,store:i,resource:this,nodeName:N?.nodeName,before:Le.delete?.bind(this,N,I),beforeIntermediate:Be.delete?.bind(this,N,I),commit:(A,D,y)=>{let U=D?.value;y&&(N&&D?.version>(N.lastModified||0)&&(N.lastModified=D.version),zE(this,D)),!(D?.version>A)&&(Fl(this[Me],U),et.trace("Write delete entry",I,A),h||p?(T(I,null,this[jr],A,0,h,this[Oe],0,"delete"),h||Sh()):i.remove(this[Me]))}}),!0}search(m){let O=this[Oe],I=As(O);if(!m)throw new Error("No query provided");let N=m.conditions;N?N.length===void 0&&(N=N[Symbol.iterator]?Array.from(N):[N]):N=Array.isArray(m)?m:m[Symbol.iterator]?Array.from(m):[],this[Me]&&(N=[{attribute:null,comparator:"prefix",value:this[Me]}].concat(N));let A,D={};function y(j,ge){let He;switch(ge){case"and":case void 0:if(j.length<1)throw new Error('An "and" operator requires at least one condition');He=!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 "+ge)}let Ys=He&&{},Qn;for(let $e of j){if($e.conditions){$e.conditions=y($e.conditions,$e.operator);continue}let qt=$e[0]??$e.attribute,ts=qt==null?H:xn(S,qt);if(ts){if(He){let Ks=qs(qt),Gt=Ys[Ks];Gt?(Gt.push($e),Qn=!0):Ys[Ks]=[$e]}(ts.type||Pg[$e.comparator])&&($e[1]===void 0?$e.value=G($e.value,ts):$e[1]=G($e[1],ts))}else if(qt!=null)throw(0,gs.handleHDBError)(new Error,`${qt} is not a defined attribute`,404)}if(m.enforceExecutionOrder)return j;if(Qn)for(let $e in Ys){let qt=Ys[$e],ts=qt.length;if(ts>1)for(let Ks=0;Ks<ts;Ks++){let Gt=qt[Ks];if(Gt.comparator==="ge"||Gt.comparator==="greater_than_equal")for(let zn=0;zn<ts;zn++){let Ho=qt[zn];(Ho.comparator==="le"||Ho.comparator==="less_than_equal")&&(Gt.comparator="between",Gt.value=[Gt.value,Ho.value],j.splice(j.indexOf(Ho),1))}if(Gt.comparator==="equals"||!Gt.comparator){for(let zn=0;zn<ts;zn++)if(zn!==Ks){let Ho=qt[zn];j.splice(j.indexOf(Ho),1)}break}}}return j}a(y,"prepareConditions");function U(j,ge){if(m.enforceExecutionOrder)return j;for(let He of j)He.conditions&&(He.conditions=U(He.conditions,He.operator));return j.length>1&&ge!=="or"?(0,Qx.sortBy)(j,xf(ze)):j}a(U,"orderConditions");function G(j,ge){return Array.isArray(j)?j.map(He=>QE(He,ge)):QE(j,ge)}a(G,"coerceTypedValues");let C=m.operator;(N.length>0||C)&&(N=y(N,C));let v=typeof m.sort=="object"&&m.sort,F;if(v&&C!=="or"){let j=v.attribute;if(A=N.find(ge=>qs(ge.attribute)===qs(j)),!A){if(!xn(S,j))throw(0,gs.handleHDBError)(new Error,`${Array.isArray(j)?j.join("."):j} is not a defined attribute`,404);A={attribute:j,comparator:"sort"},N.push(A)}A.descending=!!v.descending}N=U(N,C),v&&(N[0]===A?v.next&&(F={dbOrderedAttribute:v.attribute,attribute:v.next.attribute,descending:v.next.descending,next:v.next.next}):(A&&N.splice(N.indexOf(A),1),F=v));let oe=m.select;if(N.length===0&&(N=[{attribute:t,comparator:"greater_than",value:!0}]),m.explain)return{conditions:N,operator:C,postOrdering:F,selectApplied:!!oe};let be=I.useReadTxn(),te=vg(N,C,ze,be,m,O,(j,ge)=>JA(j,oe,O,be,ge),D),Pe=m.ensureLoaded!==!1;F||(te=re(te));let ae=ze.transformEntryForSelect(oe,O,be,D,Pe,!0),qe=ze.transformToOrderedSelect(te,oe,F,be,O,ae);function re(j){return m.offset||m.limit!==void 0?j.slice(m.offset,m.limit!==void 0?(m.offset||0)+m.limit:void 0):j}return a(re,"applyOffset"),F&&(qe=re(qe)),qe.onDone=()=>{qe.onDone=null,I.doneReadTxn()},qe.selectApplied=!0,qe.getColumns=()=>{if(oe){let j=[];for(let ge of oe)ge==="*"?j.push(...S.map(He=>He.name)):j.push(ge.name||ge);return j}return S.map(j=>j.name)},qe}static transformToOrderedSelect(m,O,I,N,A,D){let y=new Yq;if(I){m=JA(m,O,N,A,null);let U;y.iterate=function(){let C,v=m[Symbol.asyncIterator]?m[Symbol.asyncIterator]():m[Symbol.iterator](),F,oe=I.dbOrderedAttribute,be,te,Pe=!0;function ae(re){let j=re.next&&ae(re.next),ge=re.descending;return(He,Ys)=>{let Qn=ph(He,re.attribute,N),$e=ph(Ys,re.attribute,N),qt=ge?(0,Po.compareKeys)($e,Qn):(0,Po.compareKeys)(Qn,$e);return qt===0?j?.(He,Ys)||0:qt}}a(ae,"createComparator");let qe=ae(I);return{async next(){let re;if(C)if(re=C.next(),re.done){if(F)return y.onDone&&y.onDone(),re}else return{value:await D.call(this,re.value)};U=[],be&&U.push(be);do if(re=await v.next(),re.done){if(F=!0,U.length)break;return y.onDone&&y.onDone(),re}else{let j=re.value;if(j?.then&&(j=await j),oe){let ge=ph(j,oe,N);if(Pe)Pe=!1,te=ge;else if(ge!==te){te=ge,be=j;break}}U.push(j)}while(!0);return I.isGrouped,U.sort(qe),C=U[Symbol.iterator](),re=C.next(),re.done?(y.onDone&&y.onDone(),re):{value:await D.call(this,re.value)}},return(){y.onDone&&y.onDone(),v.return()},throw(){y.onDone&&y.onDone(),v.throw()}}};let G=a(C=>{if(typeof O=="object"&&Array.isArray(C.attribute))for(let v=0;v<O.length;v++){let F=O[v],oe;if(F.name===C.attribute[0]){for(oe=F.sort||(F.sort={});oe.next;)oe=oe.next;oe.attribute=C.attribute.slice(1),oe.descending=C.descending}else F===C.attribute[0]&&(O[v]=oe={name:F,sort:{attribute:C.attribute.slice(1),descending:C.descending}})}C.next&&G(C.next)},"applySortingOnSelect");G(I)}else y.iterate=(m[Symbol.asyncIterator]||m[Symbol.iterator]).bind(m),y=y.map(D);return y}static transformEntryForSelect(m,O,I,N,A,D){if(m&&(m===t||m?.length===1&&m[0]===t)){let C=a(v=>v?.key??v,"transform");return m===t?C:m.asArray?v=>[C(v)]:v=>({[t]:C(v)})}let y;A&&L&&!m?.every(C=>{let v;return typeof C=="object"?v=C.name:v=C,r[v]||v===t})&&(y=!0);let U,G=a(function(C){let v;if(C!=null){if(Eh=C,v=C.value||C.deref?.(),!v&&(C.key===void 0||C.deref)){if(C=hh(C.key??C,O,{transaction:I,lazy:m?.length<4},this.isSync,F=>F),C?.then)return C.then(G.bind(this));v=C?.value}if(y&&(C.metadataFlags&(Ol|bl)||C.expiresAt&&C.expiresAt<Date.now())){let F=mh(C.key??C,C,O);if(F?.then)return F.then(G)}}if(v==null)return D?Mo.SKIP:v;if(m&&!(m[0]==="*"&&m.length===1)){let F,oe=a((te,Pe)=>{let ae;typeof te=="object"?ae=te.name:ae=te;let qe=Wn?.[ae],re;if(qe){let j=N?.[ae];if(j)if(j.hasMappings){let He=qe.from?v[qe.from]:qs(C.key);re=j.get(He),re||(re=[])}else re=j.fromRecord?.(v);else re=qe(v,O,C);let ge=a(He=>{if(He&&typeof He=="object"){let Ys=qe.definition?.tableClass||ze;U||(U={});let Qn=U[ae]||(U[ae]=Ys.transformEntryForSelect(ae===te?null:te.select||(Array.isArray(te)?te:null),O,I,j,A));if(Array.isArray(He)){let $e=[],qt=Ys.transformToOrderedSelect(He,te.select,typeof te.sort=="object"&&te.sort,O,I,Qn)[this.isSync?Symbol.iterator:Symbol.asyncIterator](),ts=a(Gt=>{for(;!Gt.done;){if(Gt?.then)return Gt.then(ts);$e.push(Gt.value),Gt=qt.next()}Pe($e,ae)},"nextValue"),Ks=ts(qt.next());Ks&&(F||(F=[]),F.push(Ks));return}else if(He=Qn.call(this,He),He?.then){F||(F=[]),F.push(He.then($e=>Pe($e,ae)));return}}Pe(He,ae)},"handleResolvedValue");re?.then?(F||(F=[]),F.push(re.then(ge))):ge(re);return}else re=v[ae],re&&typeof re=="object"&&ae!==te&&(re=ze.transformEntryForSelect(te.select||te,O,I,null)({value:re}));Pe(re,ae)},"selectAttribute"),be;if(typeof m=="string")oe(m,te=>{be=te});else if(Array.isArray(m))if(m.asArray)be=[],m.forEach((te,Pe)=>{te==="*"?m[Pe]=v:oe(te,ae=>be[Pe]=ae)});else{be={};let te=m.forceNulls;for(let Pe of m)if(Pe==="*")for(let ae in v)be[ae]=v[ae];else oe(Pe,(ae,qe)=>{ae===void 0&&te&&(ae=null),be[qe]=ae})}else throw new gs.ClientError("Invalid select"+m);return F?Promise.all(F).then(()=>be):be}return v},"transform");return G}async subscribe(m){if(!u)throw new Error("Can not subscribe to a table without an audit log");h||ut({table:n,database:c,schemaDefined:_,attributes:S,audit:!0}),m||(m={});let O=!m.rawEvents,I=xx(ze,this[Me]??null,function(y,U,G,C){try{let v=U.getValue?.(i,O);if(!v&&U.type==="patch"&&O){let F=i.getEntry(y);F?.version===U.version?v=F.value:v=U.getValue?.(i,!0,G),U.type="put"}this.send({id:y,timestamp:G,value:v,version:U.version,type:U.type,beginTxn:C})}catch(v){et.error(v)}},m.startTime||0,this[Ts]);this[Ts]&&(I.includeDescendants=!0,m.onlyChildren&&(I.onlyChildren=!0)),m.crossThreads===!1&&(I.crossThreads=!1),m.supportsTransactions&&(I.supportsTransactions=!0);let N=this[Me],A=m.previousCount;A>1e3&&(A=1e3);let D=m.startTime;if(this[Ts]){if(D){if(A)throw new gs.ClientError("startTime and previousCount can not be combined for a table level subscription");for(let{key:y,value:U}of u.getRange({start:D,exclusiveStart:!0})){let G=Lt(U);if(G.tableId!==s)continue;let C=G.recordId;if(N==null||Kx(N,C)){let v=G.getValue(i,O,y);I.send({id:C,timestamp:y,value:v,version:G.version,type:G.type})}I.startTime=y}}else if(A){let y=[];for(let{key:U,value:G}of u.getRange({start:"z",end:!1,reverse:!0}))try{let C=Lt(G);if(C.tableId!==s)continue;let v=C.recordId;if(N==null||Kx(N,v)){let F=C.getValue(i,O,U);if(y.push({id:v,timestamp:U,value:F,version:C.version,type:C.type}),--A<=0)break}}catch(C){et.error("Error getting history entry",U,C)}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:G,localTime:C}of i.getRange({start:N??!1,end:N==null?void 0:[N,Po.MAXIMUM_KEY],versions:!0}))U&&I.send({id:y,timestamp:C,value:U,version:G,type:"put"})}else{A&&!D&&(D=0);let y=this[jr]?.localTime;if(y===om&&(i.cache?.delete(N),this[jr]=i.getEntry(N),et.trace("re-retrieved record",y,this[jr]?.localTime),y=this[jr]?.localTime),et.trace("Subscription from",D,"from",N,y),D<y){let U=[],G=y;do{let C=u.get(G);if(C){m.omitCurrent=!0;let v=Lt(C),F=v.getValue(i,O,G);O&&(v.type="put"),U.push({id:N,value:F,timestamp:G,...v}),G=v.previousLocalTime}else break;A&&A--}while(G>D&&A!==0);for(let C=U.length;C>0;)I.send(U[--C]);I.startTime=y}!m.omitCurrent&&this.doesExist()&&I.send({id:N,timestamp:y,value:this,version:this[yl],type:"put"})}return m.listener&&I.on("data",m.listener),I}doesExist(){return!!(this[_e]||this[Al])}publish(m,O){this._writePublish(m,O)}_writePublish(m,O){let I=As(this[Oe]),N=this[Me]||null;rc(N);let A=this[Oe];I.addWrite({key:N,store:i,entry:this[jr],nodeName:A?.nodeName,validate:()=>{A?.source||(I.checkOverloaded(),this.validate(m))},before:Le.publish?.bind(this,A,N,m),beforeIntermediate:Be.publish?.bind(this,A,N,m),commit:(D,y,U)=>{y===void 0&&p&&!h&&Sh(),T(N,y?.value??null,y,y?.version||D,0,!0,A,y?.expiresAt,"message",!1,m)}})}validate(m,O){let I,N=a((A,D,y)=>{if(D.type&&A!=null)if(O&&A.__op__&&(A=A.value),D.properties){typeof A!="object"&&(I||(I=[])).push(`Value ${Vs(A)} in property ${y} must be an object${D.type?" ("+D.type+")":""}`);let U=D.properties;for(let G=0,C=U.length;G<C;G++){let v=U[G],F=N(A[v.name],v,y+"."+v.name);F&&(A[v.name]=F)}if(D.sealed&&A!=null&&typeof A=="object")for(let G in A)U.find(C=>C.name===G)||(I||(I=[])).push(`Property ${G} is not allowed within object in property ${y}`)}else switch(D.type){case"Int":(typeof A!="number"||A>>0!==A)&&(I||(I=[])).push(`Value ${Vs(A)} in property ${y} must be an integer (from -2147483648 to 2147483647)`);break;case"Long":(typeof A!="number"||!(Math.floor(A)===A&&Math.abs(A)<=9007199254740992))&&(I||(I=[])).push(`Value ${Vs(A)} in property ${y} must be an integer (from -9007199254740992 to 9007199254740992)`);break;case"Float":typeof A!="number"&&(I||(I=[])).push(`Value ${Vs(A)} in property ${y} must be a number`);break;case"ID":typeof A=="string"||A?.length>0&&A.every?.(U=>typeof U=="string")||(I||(I=[])).push(`Value ${Vs(A)} in property ${y} must be a string, or an array of strings`);break;case"String":typeof A!="string"&&(I||(I=[])).push(`Value ${Vs(A)} in property ${y} must be a string`);break;case"Boolean":typeof A!="boolean"&&(I||(I=[])).push(`Value ${Vs(A)} in property ${y} must be a boolean`);break;case"Date":if(!(A instanceof Date)){if(typeof A=="string"||typeof A=="number")return new Date(A);(I||(I=[])).push(`Value ${Vs(A)} in property ${y} must be a Date`)}break;case"BigInt":if(typeof A!="bigint"){if(typeof A=="string"||typeof A=="number")return BigInt(A);(I||(I=[])).push(`Value ${Vs(A)} in property ${y} must be a bigint`)}break;case"Bytes":A instanceof Uint8Array||(I||(I=[])).push(`Value ${Vs(A)} in property ${y} must be a Buffer or Uint8Array`);break;case"array":if(Array.isArray(A)){if(D.elements)for(let U=0,G=A.length;U<G;U++){let C=A[U],v=N(C,D.elements,y+"[*]");v&&(A[U]=v)}}else(I||(I=[])).push(`Value ${Vs(A)} in property ${y} must be a Buffer or Uint8Array`);break}D.nullable===!1&&A==null&&(I||(I=[])).push(`Property ${y} is required (and not does not allow null values)`)},"validateValue");for(let A=0,D=S.length;A<D;A++){let y=S[A];if(!y.relationship&&(!O||y.name in m)){let U=N(m[y.name],y,y.name);U&&(m[y.name]=U)}}if(d)for(let A in m)S.find(D=>D.name===A)||(I||(I=[])).push(`Property ${A} is not allowed`);if(I)throw new gs.ClientError(I.join(". "))}getUpdatedTime(){return this[yl]}wasLoadedFromSource(){return L?!!this[CA]:void 0}static async addAttributes(m){let O=S.slice(0);for(let I of m){if(!I.name)throw new gs.ClientError("Attribute name is required");if(I.name.match(/[`/]/))throw new gs.ClientError("Attribute names cannot include backticks or forward slashes");O.push(I)}return ut({table:n,database:c,schemaDefined:_,attributes:O}),ze.indexingOperation}static async removeAttributes(m){let O=S.filter(I=>!m.includes(I.name));return ut({table:n,database:c,schemaDefined:_,attributes:O}),ze.indexingOperation}static getRecordCount(m){let O=i.getStats().entryCount,I=5e3,N=1e3,A;O>I&&!m?.exactCount&&(A=N);let D=0;for(let{value:y}of i.getRange({start:!0,lazy:!0,limit:A}))y!=null&&D++;if(A){let y=D;D=0;for(let{value:Pe}of i.getRange({start:"\uFFFF",reverse:!0,lazy:!0,limit:A}))Pe!=null&&D++;let U=A*2,G=(D+y)/U,C=Math.pow((D-y+1)/A/2,2)+G*(1-G)/U,v=Math.max(Math.sqrt(C)*O,1),F=Math.round(G*O),oe=Math.max(F-1.96*v,0),be=Math.min(F+1.96*v,O),te=Math.pow(10,Math.round(Math.log10(v)));return te>F&&(te=te/10),D=Math.round(F/te)*te,{recordCount:D,estimatedRange:[Math.round(oe),Math.round(be)]}}return{recordCount:D}}static updatedAttributes(){Wn=this.propertyResolvers={$id:(m,O,I)=>({value:I.key}),$updatedtime:(m,O,I)=>I.version,$record:(m,O,I)=>I?{value:m}:m};for(let m of this.attributes){m.resolve=null;let O=m.relationship;if(O)if(m.indexed&&console.error("A relationship property can not be directly indexed, (but you may want to index the foreign key attribute)"),zA=!0,O.to)m.elements?.definition?(Wn[m.name]=m.resolve=(I,N,A)=>{let D=I[O.from?O.from:t],y=m.elements.definition.tableClass;return A?Ma({attribute:O.to,value:D},As(N).getReadTxn(),!1,y,!1).asArray:y.search([{attribute:O.to,value:D}],N).asArray},m.set=()=>{throw new Error("Setting a one-to-many relationship property is not supported")},m.resolve.definition=m.elements.definition,O.from&&(m.resolve.from=O.from)):console.error(`The one-to-many/many-to-many relationship property "${m.name}" in table "${n}" must have an array type referencing a table as the elements`);else if(O.from){let I=m.definition||m.elements?.definition;I?(Wn[m.name]=m.resolve=(N,A,D)=>{let y=N[O.from];if(y!==void 0){if(m.elements){let U,G=y.map(C=>{let v=D?I.tableClass.primaryStore.getEntry(C,{transaction:As(A).getReadTxn()}):I.tableClass.get(C,A);return v?.then&&(U=!0),v});return O.filterMissing?U?Promise.all(G).then(C=>C.filter(Wx)):G.filter(Wx):U?Promise.all(G):G}return D?I.tableClass.primaryStore.getEntry(y,{transaction:As(A).getReadTxn()}):I.tableClass.get(y,A)}},m.set=(N,A)=>{if(Array.isArray(A)){let D=A.map(y=>y[Me]||y[I.tableClass.primaryKey]);N[O.from]=D}else{let D=A[Me]||A[I.tableClass.primaryKey];N[O.from]=D}},m.resolve.definition=m.definition||m.elements?.definition,m.resolve.from=O.from):console.error(`The relationship property "${m.name}" in table "${n}" must be a type that references a table`)}else console.error(`The relationship directive on "${m.name}" in table "${n}" must use either "from" or "to" arguments`)}$E(this,this)}static async deleteHistory(m=0){let O;for(let{key:I,value:N}of u.getRange({start:0,end:m}))await Nl(),Lt(N).tableId===s&&(O=u.remove(I));await O}static async*getHistory(m=0,O=1/0){for(let{key:I,value:N}of u.getRange({start:m,end:O})){await Nl();let A=Lt(N);A.tableId===s&&(yield{id:A.recordId,localTime:I,version:A.version,type:A.type,value:A.getValue(i,!0,I),user:A.user})}}static async getHistoryOfRecord(m){let O=[];if(m==null)throw new Error("An id is required");let I=i.getEntry(m);if(!I)return O;let N=I.localTime;if(!N)throw new Error("The entry does not have a local audit time");let A=0;do{await Nl();let D=u.get(N);if(D){let y=Lt(D);O.push({id:y.recordId,localTime:N,version:y.version,type:y.type,value:y.getValue(i,!0,N),user:y.user}),N=y.previousLocalTime}else break}while(A<1e3&&N);return O.reverse()}static cleanup(){z?.remove()}}ze.updatedAttributes();let Qq=ze.prototype;return Qq[uie]=!0,f&&ze.setTTLExpiration(f/1e3),X&&zq(),ze;function Fl(K,m,O){let I;for(let N in r){let A=r[N],D=A.isIndexing,y=O?.[N],U=m?.[N];if(y===U&&!D)continue;I=!0;let G=A.indexNulls,C=(0,Il.getIndexedValues)(U,G);if(C){kx&&A.prefetch(C.map(v=>({key:v,value:K})),Yx);for(let v=0,F=C.length;v<F;v++)A.remove(C[v],K)}if(C=(0,Il.getIndexedValues)(y,G),C){kx&&A.prefetch(C.map(v=>({key:v,value:K})),Yx);for(let v=0,F=C.length;v<F;v++)A.put(C[v],K)}}return I}a(Fl,"updateIndices");function rc(K){switch(typeof K){case"number":return!0;case"string":if(K.length<659)return!0;if(K.length>$x)throw new Error("Primary key size is too large: "+K.length);break;case"object":if(K===null)return!0;break;case"bigint":if(K<2n**64n&&K>-(2n**64n))return!0;break;default:throw new Error("Invalid primary key type: "+typeof K)}if((0,Po.writeKey)(K,_ie,0)>$x)throw new Error("Primary key size is too large: "+K.length);return!0}a(rc,"checkValidId");function hh(K,m,O,I,N){let A=a(()=>{if(m?.transaction?.stale&&(m.transaction.stale=!1),O.transaction?.isDone)return N(null,K);let D=i.getEntry(K,O);return D&&m&&(D?.version>(m.lastModified||0)&&(m.lastModified=D.version),D?.localTime&&!m.lastRefreshed&&(m.lastRefreshed=D.localTime)),N(D,K)},"whenPrefetched");return I?A():ce>0?(ce--,A()):new Promise((D,y)=>{ce===0?(ce--,i.prefetch([K],()=>{U(),G()})):(J.push(K),de.push(G),J.length>Wq&&(ce--,U()));function U(){if(J.length>0){let C=de;i.prefetch(J,()=>{ce===-1?U():ce++;for(let v of C)v()}),J=[],de=[],fe>2&&fe--}else ce=fe,fe<Kq&&fe++}a(U,"prefetch");function G(){try{D(A())}catch(C){y(C)}}a(G,"load")})}a(hh,"loadLocalRecord");function kl(K){if(!K?.role)return;let m=K.role.permission;if(m.super_user)return die;let O=m[c],I,N=O?.tables;if(N)return N[n];if(c==="data"&&(I=m[n])&&!I.tables)return I}a(kl,"getTablePermissions");function mh(K,m,O,I){if(L){let N;if(O.noCache?N=!0:(m?(!m.value||m.metadataFlags&(Ol|bl)||m.expiresAt&&m.expiresAt<Date.now())&&(N=!0):N=!0,os(!N,"cache-hit",n)),N){let A=XA(K,m,O).then(D=>(D?.value?.[_e]&&et.error("Can not assign a record with a record property"),O&&(D?.version>(O.lastModified||0)&&(O.lastModified=D.version),O.lastRefreshed=Date.now()),D));if(O?.onlyIfCached||m?.value&&I?.allowStaleWhileRevalidate?.(m,K)){if(A.catch(D=>et.warn(D)),O?.onlyIfCached&&!I.doesExist())throw new gs.ServerError("Entry is not cached",504);return}else return A}}}a(mh,"ensureLoadedFromSource");function As(K){let m=K?.transaction;if(m){if(!m.lmdbDb)return m.lmdbDb=i,m;do{if(m.lmdbDb?.path===i.path)return m;let O=m.next;if(!O)return m=m.next=new to,m.lmdbDb=i,m;m=O}while(!0)}else return new rd}a(As,"txnForContext");function ph(K,m,O){if(!K)return;Eh=K;let I=K.value||K.deref?.()||(Eh=i.getEntry(K.key))?.value;if(typeof m=="object"){let A=Wn,D=I;for(let y=0,U=m.length;y<U;y++){let G=m[y],C=A?.[G];D=C&&D?C(D,O,!0)?.value:D?.[G],A=C?.definition?.tableClass?.propertyResolvers}return D}let N=Wn[m];return N?N(I,O):I[m]}a(ph,"getAttributeValue");function JA(K,m,O,I,N){let A=N?.length,D={transaction:I,lazy:A>0||typeof m=="string"||m?.length<4,alwaysPrefetch:!0},y;function U(G,C){let v=G?.value;if(!v)return Mo.SKIP;for(let F=0;F<A;F++)if(!y?.includes(F)&&!N[F](v,G))return Mo.SKIP;return C!==void 0&&(G.key=C),G}if(a(U,"processEntry"),A>0||!K.hasEntries){let G=K.map(C=>{if(y=null,typeof C=="object"&&C.key!==void 0)return A>0?U(C):C;if(C==null)return Mo.SKIP;for(let v=0;v<A;v++){let oe=N[v].idFilter;if(oe){if(!oe(C))return Mo.SKIP;y||(y=[]),y.push(v)}}return hh(C,O,D,!1,U)});return Array.isArray(K)&&(G=G.filter(C=>C!==Mo.SKIP)),G.hasEntries=!0,G}return K}a(JA,"transformToEntries");async function XA(K,m,O){let I=m?.metadataFlags,N=m?.version,A,D;if(!i.attemptLock(K,N,()=>{clearTimeout(D);let C=i.getEntry(K);!C||!C.value||C.metadataFlags&(Ol|bl)?A(XA(K,i.getEntry(K),O)):A(C)}))return new Promise(C=>{A=C,D=setTimeout(()=>{i.unlock(K,N)},cie)});let y=m?.value,U={requestContext:O,replacingRecord:y,replacingVersion:N,source:null,resourceCache:O?.resourceCache},G=O?.responseHeaders;return new Promise((C,v)=>{let F;LA(je(U,async oe=>{let be=performance.now(),te,Pe,ae;try{for(let ge of ze.sources)if(ge.get&&(!ge.get.reliesOnPrototype||ge.prototype.get)&&(U.source=ge,te=await ge.get(K,U),te))break;ae=I&Ol;let re=U.lastModified||ae&&N;Pe=ae||re>N||!y,re||(re=(0,Il.getNextMonotonicTime)());let j=performance.now()-be;if(Fr(j,"cache-resolution",n),G&&rg(G,"Server-Timing",`cache-resolve;dur=${j.toFixed(2)}`,!0),oe.timestamp=re,f&&!U.expiresAt&&(U.expiresAt=Date.now()+f),te){if(typeof te!="object")throw new Error("Only objects can be cached and stored in tables");typeof te.toJSON=="function"&&(te=te.toJSON()),t&&te[t]!==K&&(te[t]=K)}F=!0,C({version:re,value:te})}catch(re){re.message+=` while resolving record ${K} for ${n}`,y&&((re.code==="ECONNRESET"||re.code==="ECONNREFUSED"||re.code==="EAI_AGAIN")&&!O?.mustRevalidate||O?.staleIfError&&(re.statusCode===500||re.statusCode===502||re.statusCode===503||re.statusCode===504))?(C({version:N,value:y}),et.trace(re.message,"(returned stale record)")):v(re),U.transaction.abort();return}if(O?.noCacheStore){U.transaction.abort();return}As(U).addWrite({key:K,store:i,entry:m,nodeName:"source",commit:(re,j)=>{if(j?.version!==N)return;let ge=Fl(K,y,te);te?(Be.put?.(U,K,te),T(K,te,j,re,0,h&&Pe||null,U,U.expiresAt,"put",!!ae)):(Be.delete?.(U,K),h||p?T(K,null,j,re,0,h&&Pe||null,U,0,"delete",!!ae):i.remove(K,N))}})}),()=>{i.unlock(K,N)},oe=>{i.unlock(K,N),F&&et.error("Error committing cache update",oe)})})}a(XA,"getFromSource");function Sh(){if(Dt!==ql&&(ql=Dt,(0,Uo.getWorkerIndex)()===(0,Uo.getWorkerCount)()-1)){if(Gl&&clearTimeout(Gl),!Dt)return;let K=new Date;K.setMonth(0),K.setDate(1),K.setHours(0),K.setMinutes(0),K.setSeconds(0);let m=Math.ceil((Date.now()-K.getTime())/Dt)*Dt+K.getTime(),O=a(I=>{et.trace(`Scheduled next cleanup scan at ${new Date(I)}ms`),Gl=setTimeout(()=>P=P.then(async()=>{if(O(Math.max(I+Dt,Date.now())),i.rootStore.status!=="open"){clearTimeout(Gl);return}let N=50,A=new Array(N),D=0;et.trace(`Starting cleanup scan for ${n}`);try{let y=0;for(let{key:U,value:G,version:C,expiresAt:v}of i.getRange({start:!1,snapshot:!1,versions:!0,lazy:!0})){let F;G===null&&!h&&C+aie<Date.now()?F=i.remove(U,C):v&&v+E<Date.now()&&(F=ze.evict(U,G,C),y++),F&&(await A[D],A[D]=F.catch(oe=>{et.error("Cleanup error",oe)}),++D>=N&&(D=0)),await Nl()}et.trace(`Finished cleanup scan for ${n}, evicted ${y} entries`)}catch(y){et.trace(`Error in cleanup scan for ${n}:`,y)}}),Math.min(I-Date.now(),2147483647)).unref()},"startNextTimer");O(m)}}a(Sh,"scheduleCleanup");function jA(){z=u?.addDeleteRemovalCallback(s,K=>{let m=i.getEntry(K);m?.value===null&&i.remove(K,m.version)})}a(jA,"addDeleteRemoval");function zq(){(0,Uo.getWorkerIndex)()===0&&setInterval(async()=>{try{let K=X.name,m=r[K];if(!m)throw new Error(`expiresAt attribute ${X} must be indexed`);for(let{key:O,value:I}of m.getRange({start:!0,end:Date.now(),versions:!0,snapshot:!1})){let N=i.getEntry(I);N?.value?N.value[K]<Date.now()&&ze.evict(I,N.value,N.version):i.ifVersion(I,N?.version,()=>m.remove(O,I)),await Nl()}}catch(K){et.error("Error in evicting old records",K)}},oie).unref()}a(zq,"runRecordExpirationEviction")}function DA(e,t){let r=e.attr_object||(e.attr_object={}),s=r[t];if(s)return s;s=r[t]=Object.create(null);for(let n of e)s[n.attribute_name]=n[t];return s}function Yx(){}function fie(e){zx=e}function QE(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"&&!Eie.test(e)&&(e+="Z"),e==="null"?null:new Date(e)):!r||r==="Any"?(0,JE.autoCast)(e):e}function Kx(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 s=0;s<r;s++)if(t[s]!==e[s])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 zE(e,t){e[jr]=t,e[_e]=t?.value??null,e[yl]=t?.version}function Wx(e){return e!=null}function Vs(e){try{return JSON.stringify(e)}catch{return e}}var $s,Mo,Il,Qx,Dl,gs,wl,Cl,et,Po,Uo,JE,iie,zx,oie,aie,kx,cie,yl,uie,jr,Al,Vx,lie,CA,Xa,Ol,bl,_ie,$x,die,USe,Eie,Nl,eE=Re(()=>{$s=x(M()),Mo=require("lmdb"),Il=x(wr()),Qx=require("lodash");Ns();Xp();Dl=x(ee());Fx();gs=x(se()),wl=x(On()),Cl=x(Ls());Ae();Gf();et=x($());id();ro();Po=require("ordered-binary"),Uo=x(Ke());qi();JE=x(Q());bc();In();HE();qu();iie=new Uint8Array(9);iie[8]=192;oie=6e4,aie=864e5;Dl.initSync();kx=Dl.get($s.CONFIG_PARAMS.STORAGE_PREFETCHWRITES),cie=1e4,yl=Symbol.for("version"),uie=Symbol.for("incremental-update"),jr=Symbol("entry"),Al=Symbol("is-saving"),Vx=1,lie=2,CA=Symbol("loaded-from-source"),Xa={isNotification:!0,ensureLoaded:!1},Ol=1,bl=8,_ie=Buffer.allocUnsafeSlow(8192),$x=1978,die={read:!0,insert:!0,update:!0,delete:!0,isSuperUser:!0},USe=(0,JE.convertToMS)(Dl.get($s.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE))||864e5;a(XE,"makeTable");a(DA,"attributesAsObject");a(Yx,"noop");a(fie,"setServerUtilities");Eie=/[+-][0-9]{2}:[0-9]{2}|[a-zA-Z]$/;a(QE,"coerceType");a(Kx,"isDescendantId");Nl=a(()=>new Promise(setImmediate),"rest");a(LA,"when");a(zE,"updateResource");a(Wx,"exists");a(Vs,"stringify")});var Ge={};Ye(Ge,{database:()=>Jc,databases:()=>st,dropDatabase:()=>rS,dropTableMeta:()=>gie,getDatabases:()=>Us,getDefaultCompression:()=>eq,getTables:()=>hie,onUpdatedTable:()=>FR,readMetaDb:()=>Ll,resetDatabases:()=>mie,table:()=>ut,tables:()=>Cr});function hie(){return rh||Us(),Cr||{}}function Us(){if(rh)return st;rh=!0,ec=new Map;let e=(0,At.getHdbBasePath)()&&(0,tt.join)((0,At.getHdbBasePath)(),xt.DATABASES_DIR_NAME),t=(0,At.get)(xt.CONFIG_PARAMS.DATABASES)||{};if(process.env.SCHEMAS_DATA_PATH&&(t.data={path:process.env.SCHEMAS_DATA_PATH}),e=process.env.STORAGE_PATH||(0,At.get)(xt.CONFIG_PARAMS.STORAGE_PATH)||e&&((0,Zr.existsSync)(e)?e:(0,tt.join)((0,At.getHdbBasePath)(),xt.LEGACY_DATABASES_DIR_NAME)),!!e){if((0,Zr.existsSync)(e))for(let r of(0,Zr.readdirSync)(e,{withFileTypes:!0})){let s=(0,tt.basename)(r.name,".mdb");r.isFile()&&(0,tt.extname)(r.name).toLowerCase()===".mdb"&&!t[s]?.path&&Ll((0,tt.join)(e,r.name),null,s)}if((0,Zr.existsSync)((0,Za.getBaseSchemaPath)())){for(let r of(0,Zr.readdirSync)((0,Za.getBaseSchemaPath)(),{withFileTypes:!0}))if(!r.isFile()){let s=(0,tt.join)((0,Za.getBaseSchemaPath)(),r.name),n=(0,tt.join)((0,Za.getTransactionAuditStoreBasePath)(),r.name);for(let i of(0,Zr.readdirSync)(s,{withFileTypes:!0}))if(i.isFile()&&(0,tt.extname)(i.name).toLowerCase()===".mdb"){let o=(0,tt.join)(n,i.name);Ll((0,tt.join)(s,i.name),(0,tt.basename)(i.name,".mdb"),r.name,o,!0)}}}if(t)for(let r in t){let s=t[r],n=s.path;if((0,Zr.existsSync)(n))for(let o of(0,Zr.readdirSync)(n,{withFileTypes:!0}))o.isFile()&&(0,tt.extname)(o.name).toLowerCase()===".mdb"&&Ll((0,tt.join)(n,o.name),(0,tt.basename)(o.name,".mdb"),r);let i=s.tables;if(i)for(let o in i){let c=i[o],u=(0,tt.join)(c.path,(0,tt.basename)(o+".mdb"));(0,Zr.existsSync)(u)&&Ll(u,o,r,null,!0)}}for(let r in st){let s=ec.get(r);if(s){let n=st[r];r.includes("delete")&&Rs.trace(`defined tables ${Array.from(s.keys())}`);for(let i in n)s.has(i)||(Rs.trace(`delete table class ${i}`),delete n[i])}else if(delete st[r],r==="data"){for(let n in Cr)delete Cr[n];delete Cr[nh]}}return ec=null,st}}function mie(){rh=!1;for(let[,e]of Mi)e.needsDeletion=!0;Us();for(let[e,t]of Mi)t.needsDeletion&&!e.endsWith("system.mdb")&&(t.close(),Mi.delete(e));return st}function Ll(e,t,r=PA,s,n){let i=new MA.default(e,!1);try{let o=Mi.get(e);o?o.needsDeletion=!1:(o=(0,ZE.open)(i),Mi.set(e,o));let c=new vo.default(!1),u=o.dbisDb||(o.dbisDb=o.openDB(jE.INTERNAL_DBIS_NAME,c)),_=o.auditStore;_||(s?(0,Zr.existsSync)(s)&&(i.path=s,_=(0,ZE.open)(i),_.isLegacy=!0):_=BE(o));let l=jx(r),d=l[nh],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 J of p)if(J.is_hash_attribute||J.isPrimaryKey){S=J;break}if(!S){Rs.fatal(`Unable to find a primary key attribute on table ${E}, with attributes: ${JSON.stringify(p)}`);continue}}let T=l[E],b={},R=[],L,H,P=typeof S.audit=="boolean"?S.audit:(0,At.get)(xt.CONFIG_PARAMS.LOGGING_AUDITLOG),k=S.trackDeletes,B=S.expiration,X=S.eviction,z=S.sealed;if(T)b=T.indices,R=T.attributes,T.schemaVersion++;else{L=S.tableId,L?L>=(u.get(ja)||0)&&u.putSync(ja,L+1):(S.tableId=L=u.get(ja),L||(L=1),u.putSync(ja,L+1),u.putSync(S.key,S));let J=new vo.default(!S.is_hash_attribute,S.is_hash_attribute);J.compression=S.compression;let de=(0,At.get)(xt.CONFIG_PARAMS.STORAGE_COMPRESSION_THRESHOLD);J.compression&&de&&(J.compression.threshold=de),H=a_(o.openDB(S.key,J)),H.rootStore=o,H.tableId=L}for(let J of p){J.attribute=J.name;try{if(!J.is_hash_attribute&&(J.indexed||J.attribute&&!J.name)){if(!b[J.name]){let ce=new vo.default(!J.is_hash_attribute,J.is_hash_attribute);b[J.name]=o.openDB(J.key,ce),b[J.name].indexNulls=J.indexNulls}let de=R.find(ce=>ce.name===J.name);de?R.splice(R.indexOf(de),1,J):R.push(J)}}catch(de){Rs.error("Error trying to update attribute",J,R,b,de)}}if(!T){T=Zx(l,E,XE({primaryStore:H,auditStore:_,audit:P,sealed:z,expirationMS:B&&B*1e3,evictionMS:X&&X*1e3,trackDeletes:k,tableName:E,tableId:L,primaryKey:S.name,databasePath:n?r+"/"+E:r,databaseName:r,indices:b,attributes:p,schemaDefined:S.schemaDefined,dbisDB:u})),T.schemaVersion=1;for(let J of vA)J(T)}}return o}catch(o){throw o.message+=` opening database ${e}`,o}}function jx(e){let t=st[e];if(t||(e==="data"?t=st[e]=Cr:e==="system"?Object.defineProperty(st,"system",{value:t=Object.create(null),configurable:!0}):t=st[e]=Object.create(null)),ec&&!ec.has(e)){let r=new Set;t[nh]=r,ec.set(e,r)}return t}function Zx(e,t,r){return e[t]=r,r}function Jc({database:e,table:t}){e||(e=PA),Us();let r=jx(e),s=(0,tt.join)((0,At.getHdbBasePath)(),xt.DATABASES_DIR_NAME),n=(0,At.get)(xt.CONFIG_PARAMS.DATABASES)||{};process.env.SCHEMAS_DATA_PATH&&(n.data={path:process.env.SCHEMAS_DATA_PATH});let i=t&&n[e]?.tables?.[t]?.path;s=i||n[e]?.path||process.env.STORAGE_PATH||(0,At.get)(xt.CONFIG_PARAMS.STORAGE_PATH)||((0,Zr.existsSync)(s)?s:(0,tt.join)((0,At.getHdbBasePath)(),xt.LEGACY_DATABASES_DIR_NAME));let o=(0,tt.join)(s,(i?t:e)+".mdb"),c=Mi.get(o);if(!c){let u=new MA.default(o,!1);c=(0,ZE.open)(u),Mi.set(o,c)}return c}async function rS(e){if(!st[e])throw new Error("Schema does not exist");let t=st[e];for(let r in t){let n=t[r].primaryStore.rootStore;Mi.delete(n.path),n.status==="open"&&(await n.close(),await sh.remove(n.path))}if(e==="data"){for(let r in Cr)delete Cr[r];delete Cr[nh]}delete st[e]}function ut({table:e,database:t,expiration:r,eviction:s,scanInterval:n,attributes:i,audit:o,sealed:c,trackDeletes:u,schemaDefined:_,origin:l}){t||(t=PA);let d=Jc({database:t,table:e}),f=st[t],E=f?.[e];if(d.status==="closed")throw new Error(`Can not use a closed data store for ${e}`);let h,p,S,T;_==null&&(_=!0);let b=new vo.default(!1);for(let B of i)B.attribute?(B.name=B.attribute,B.indexed=!0):B.attribute=B.name,B.expiresAt&&(B.indexed=!0);let R,L;if(E){if(h=E.primaryKey,E.primaryStore.rootStore.status==="closed")throw new Error(`Can not use a closed data store from ${e} class`);E.attributes.splice(0,E.attributes.length,...i)}else{let B=d.auditStore;B||(B=BE(d)),p=i.find(de=>de.isPrimaryKey)||{},h=p.name,p.is_hash_attribute=!0,p.schemaDefined=_,p.compression=eq(),u&&(p.trackDeletes=!0),o=p.audit=typeof o=="boolean"?o:(0,At.get)(xt.CONFIG_PARAMS.LOGGING_AUDITLOG),r&&(p.expiration=r),s&&(p.eviction=s),typeof c=="boolean"&&(p.sealed=c),l&&(p.origins?p.origins.includes(l)||p.origins.push(l):p.origins=[l]),Rs.trace(`${e} table loading, opening primary store`);let X=new vo.default(!1,!0);X.compression=p.compression;let z=e+"/",J=a_(d.openDB(z,X));J.rootStore=d,T=d.dbisDb=d.openDB(jE.INTERNAL_DBIS_NAME,b),J.tableId=T.get(ja),J.tableId||(J.tableId=1),T.putSync(ja,J.tableId+1),p.tableId=J.tableId,E=Zx(f,e,XE({primaryStore:J,auditStore:B,audit:o,sealed:c,trackDeletes:u,expirationMS:r&&r*1e3,evictionMS:s&&s*1e3,primaryKey:h,tableName:e,tableId:J.tableId,databasePath:t,databaseName:t,indices:{},attributes:i,schemaDefined:_,dbisDB:T})),E.schemaVersion=1,R=!0,k(),T.put(z,p)}S=E.indices,T=T||(d.dbisDb=d.openDB(jE.INTERNAL_DBIS_NAME,b)),E.dbisDB=T;let H=[];for(let{key:B,value:X}of T.getRange({start:!0})){let[z,J]=B.toString().split("/");if(J===""&&(J=X.name),J){if(z!==e)continue}else J=z;if(!i.find(ce=>ce.name===J)?.indexed&&X.indexed&&!X.isPrimaryKey){k(),R=!0,T.remove(B);let ce=E.indices[z];ce&&H.push(ce)}}let P=[];try{for(let B of i||[]){if(B.relationship)continue;let X=e+"/"+(B.name||"");Object.defineProperty(B,"key",{value:X,configurable:!0});let z=T.get(X);if(B.isPrimaryKey){if(z=z||T.get(X=e+"/")||{},o!==E.audit||c!==c||(+r||void 0)!==(+z.expiration||void 0)||(+s||void 0)!==(+z.eviction||void 0)){let de=Object.assign({},z);typeof o=="boolean"&&(o&&E.enableAuditing(o),de.audit=o),r&&(de.expiration=+r),s&&(de.eviction=+s),c!==void 0&&(de.sealed=c),R=!0,k(),T.put(X,de)}continue}z?.attribute&&!z.name&&(z.indexed=!0);let J=!z||z.type!==B.type||z.indexed!==B.indexed||z.nullable!==B.nullable||JSON.stringify(z.attributes)!==JSON.stringify(B.attributes)||JSON.stringify(z.elements)!==JSON.stringify(B.elements);if(B.indexed){let de=new vo.default(!0,!1),ce=d.openDB(X,de);(J||z.indexingPID&&z.indexingPID!==process.pid||z.restartNumber<Ml.workerData?.restartNumber)&&(R=!0,k(),z=T.get(X),(J||z.indexingPID&&z.indexingPID!==process.pid||z.restartNumber<Ml.workerData?.restartNumber)&&(R=!0,B.indexNulls===void 0&&(B.indexNulls=!0),E.primaryStore.getStats().entryCount>0&&(B.lastIndexedKey=z?.lastIndexedKey||!1,B.indexingPID=process.pid,ce.isIndexing=!0,Object.defineProperty(B,"dbi",{value:ce}),P.push(B))),T.put(X,B)),z?.indexNulls&&B.indexNulls===void 0&&(B.indexNulls=!0),ce.indexNulls=B.indexNulls,S[B.name]=ce}else J&&(R=!0,k(),T.put(X,B))}}finally{L&&L()}if(R&&(E.schemaVersion++,E.updatedAttributes()),Rs.trace(`${e} table loading, running index`),P.length>0||H.length>0?E.indexingOperation=Tie(E,P,H):R&&eh.signalSchemaChange(new th.SchemaEventMsg(process.pid,"schema-change",E.databaseName,E.tableName)),E.origin=l,R)for(let B of vA)B(E,l!=="cluster");return(r||s||n)&&E.setTTLExpiration({expiration:r,eviction:s,scanInterval:n}),Rs.trace(`${e} table loaded`),E;function k(){L||d.transactionSync(()=>({then(B){L=B}}))}a(k,"startTxn")}async function Tie(e,t,r){try{let s=e.schemaVersion;await eh.signalSchemaChange(new th.SchemaEventMsg(process.pid,"schema-change",e.databaseName,e.tableName));let n;for(let u of r)n=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++,n=e.primaryStore.ifVersion(_,d,()=>{for(let f=0;f<c;f++){let E=t[f],h=E.name,p=(0,Jx.getIndexedValues)(l[h]);if(p)for(let S=0,T=p.length;S<T;S++)E.dbi.put(p[S],_)}}),n.then(()=>u--,f=>{u--,Rs.error(f)}),Ml.workerData&&Ml.workerData.restartNumber!==Xx.restartNumber&&(i=!0),++o%100===0||i){for(let f of t)f.lastIndexedKey=_,e.dbisDB.put(f.key,f);if(i)return}u>pie?await n:u>Sie&&await new Promise(f=>setImmediate(f))}for(let _ of t)delete _.lastIndexedKey,delete _.indexingPID,_.dbi.isIndexing=!1,n=e.dbisDB.put(_.key,_)}await n,await eh.signalSchemaChange(new th.SchemaEventMsg(process.pid,"indexing-finished",e.databaseName,e.tableName))}catch(s){Rs.error("Error in indexing",s)}}function gie({table:e,database:t}){let r=Jc({database:t,table:e}),s=[],n=r.dbisDb;for(let i of n.getKeys({start:e+"/",end:e+"0"}))s.push(n.remove(i));return Promise.all(s)}function FR(e){vA.push(e)}function eq(){let e=(0,At.get)(xt.CONFIG_PARAMS.STORAGE_COMPRESSION),t=(0,At.get)(xt.CONFIG_PARAMS.STORAGE_COMPRESSION_DICTIONARY),r=(0,At.get)(xt.CONFIG_PARAMS.STORAGE_COMPRESSION_THRESHOLD),s={startingOffset:32};return t&&(s.dictionary=sh.readFileSync(t)),r&&(s.threshold=r),e&&s}var At,jE,ZE,tt,Zr,Za,vo,MA,xt,sh,UA,Jx,eh,th,Ml,Rs,Xx,PA,nh,Cr,st,ja,vA,rh,Mi,ec,pie,Sie,Ae=Re(()=>{At=x(ee()),jE=x(Et()),ZE=require("lmdb"),tt=require("path"),Zr=require("fs"),Za=x(Je());eE();vo=x(c_()),MA=x(l_()),xt=x(M()),sh=x(require("fs-extra")),UA=require("../index"),Jx=x(wr()),eh=x(On()),th=x(Ls()),Ml=require("worker_threads"),Rs=x($()),Xx=x(Ke());qi();bc();PA="data",nh=Symbol("defined-tables");(0,At.initSync)();Cr=Object.create(null),st=Object.create(null);(0,UA._assignPackageExport)("databases",st);(0,UA._assignPackageExport)("tables",Cr);ja=Symbol.for("next-table-id"),vA=[],Mi=new Map;a(hie,"getTables");a(Us,"getDatabases");a(mie,"resetDatabases");a(Ll,"readMetaDb");a(jx,"ensureDB");a(Zx,"setTable");a(Jc,"database");a(rS,"dropDatabase");a(ut,"table");pie=1e3,Sie=10;a(Tie,"runIndexing");a(gie,"dropTableMeta");a(FR,"onUpdatedTable");a(eq,"getDefaultCompression")});var Q=g((kSe,Eq)=>{"use strict";var Ui=require("path"),iq=require("fs-extra"),Nr=$(),tq=require("fs-extra"),ih=require("os"),Rie=require("net"),Aie=require("recursive-iterator"),ct=M(),Oie=LO(),rq=require("papaparse"),oh=require("moment"),{inspect:bie}=require("util"),sq=require("is-number"),FSe=require("lodash"),Nie=require("minimist"),yie=require("https"),Iie=require("http"),{hdb_errors:ah}=se(),wie=/^((\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)))$/,oq=require("util").promisify(setTimeout),Cie=100,Die=5,Lie="",Mie=4,nq={true:!0,TRUE:!0,FALSE:!1,false:!1,undefined:null,null:null,NULL:null,NaN:NaN};Eq.exports={isEmpty:es,isEmptyOrZeroLength:hn,arrayHasEmptyValues:vie,arrayHasEmptyOrZeroLengthValues:Bie,buildFolderPath:Hie,isBoolean:aq,errorizeMessage:Uie,stripFileExtension:qie,autoCast:Gie,autoCastJSON:cq,autoCastJSONDeep:HA,removeDir:Fie,compareVersions:kie,isCompatibleDataVersion:Vie,escapeRawValue:$ie,unescapeValue:Yie,stringifyProps:Kie,timeoutPromise:Qie,isClusterOperation:Jie,getClusterUser:jie,checkGlobalSchemaTable:Xie,getHomeDir:lq,getPropsFilePath:Wie,promisifyPapaParse:Zie,removeBOM:_q,createEventPromise:eoe,checkProcessRunning:toe,checkSchemaTableExist:roe,checkSchemaExists:dq,checkTableExists:fq,getStartOfTomorrowInSeconds:soe,getLimitKey:noe,isObject:xie,isNotEmptyAndHasValue:Pie,autoCasterIsNumberCheck:uq,backtickASTSchemaItems:ioe,isPortTaken:zie,createForkArgs:ooe,autoCastBoolean:aoe,async_set_timeout:oq,getTableHashAttribute:coe,doesSchemaExist:uoe,doesTableExist:loe,stringifyObj:_oe,ms_to_time:doe,changeExtension:foe,getEnvCliRootPath:xA,noBootFile:Eoe,httpRequest:hoe,transformReq:moe,convertToMS:poe,PACKAGE_ROOT:ct.PACKAGE_ROOT};function Uie(e){return e instanceof Error?e:new Error(e)}a(Uie,"errorizeMessage");function es(e){return e==null}a(es,"isEmpty");function Pie(e){return!es(e)&&(e||e===0||e===""||aq(e))}a(Pie,"isNotEmptyAndHasValue");function hn(e){return es(e)||e.length===0||e.size===0}a(hn,"isEmptyOrZeroLength");function vie(e){if(es(e))return!0;for(let t=0;t<e.length;t++)if(es(e[t]))return!0;return!1}a(vie,"arrayHasEmptyValues");function Bie(e){if(hn(e))return!0;for(let t=0;t<e.length;t++)if(hn(e[t]))return!0;return!1}a(Bie,"arrayHasEmptyOrZeroLengthValues");function Hie(...e){try{return e.join(Ui.sep)}catch{console.error(e)}}a(Hie,"buildFolderPath");function aq(e){return es(e)?!1:e===!0||e===!1}a(aq,"isBoolean");function xie(e){return es(e)?!1:typeof e=="object"}a(xie,"isObject");function qie(e){return hn(e)?Lie:e.slice(0,-Mie)}a(qie,"stripFileExtension");function Gie(e){return es(e)||e===""||typeof e!="string"?e:nq[e]!==void 0?nq[e]:uq(e)===!0?Number(e):wie.test(e)?new Date(e):e}a(Gie,"autoCast");function cq(e){if(typeof e=="string"&&(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")))try{return JSON.parse(e)}catch{}return e}a(cq,"autoCastJSON");function HA(e){if(e&&typeof e=="object"){if(Array.isArray(e))for(let t=0,r=e.length;t<r;t++){let s=e[t],n=HA(s);n!==s&&(e[t]=n)}else for(let t in e){let r=e[t],s=HA(r);s!==r&&(e[t]=s)}return e}else return cq(e)}a(HA,"autoCastJSONDeep");function uq(e){if(e.startsWith("0.")&&sq(e))return!0;let t=e.toUpperCase().includes("E");return!!((e!=="0"&&e.startsWith("0"))===!1&&t===!1&&sq(e))}a(uq,"autoCasterIsNumberCheck");async function Fie(e){if(hn(e))throw new Error(`Directory path: ${e} does not exist`);try{await tq.emptyDir(e),await tq.remove(e)}catch(t){throw Nr.error(`Error removing files in ${e} -- ${t}`),t}}a(Fie,"removeDir");function kie(e,t){if(hn(e)){Nr.info("Invalid current version sent as parameter.");return}if(hn(t)){Nr.info("Invalid upgrade version sent as parameter.");return}let r,s=/(\.0+)+$/,n=e.version?e.version:e,i=t.version?t.version:t,o=n.replace(s,"").split("."),c=i.replace(s,"").split("."),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(kie,"compareVersions");function Vie(e,t,r=!1){let s=e.toString().split("."),n=t.toString().split(".");return s[0]===n[0]&&(!r||s[1]===n[1])}a(Vie,"isCompatibleDataVersion");function $ie(e){if(es(e))return e;let t=String(e);return t==="."?ct.UNICODE_PERIOD:t===".."?ct.UNICODE_PERIOD+ct.UNICODE_PERIOD:t.replace(ct.FORWARD_SLASH_REGEX,ct.UNICODE_FORWARD_SLASH)}a($ie,"escapeRawValue");function Yie(e){if(es(e))return e;let t=String(e);return t===ct.UNICODE_PERIOD?".":t===ct.UNICODE_PERIOD+ct.UNICODE_PERIOD?"..":String(e).replace(ct.ESCAPED_FORWARD_SLASH_REGEX,"/")}a(Yie,"unescapeValue");function Kie(e,t){if(es(e))return Nr.info("Properties object is null"),"";let r="";return e.each(function(s,n){try{if(t&&t[s]){let i=t[s];for(let o of i)r+=";"+o+ih.EOL}!hn(s)&&s[0]===";"?r+=" "+s+n+ih.EOL:hn(s)||(r+=s+"="+n+ih.EOL)}catch{Nr.error(`Found bad property during upgrade with key ${s} and value: ${n}`)}}),r}a(Kie,"stringifyProps");function lq(){let e;try{e=ih.homedir()}catch{e=process.env.HOME}return e||(e="~/"),e}a(lq,"getHomeDir");function Wie(){let e=Ui.join(lq(),ct.HDB_HOME_DIR_NAME,ct.BOOT_PROPS_FILE_NAME);return iq.existsSync(e)||(e=Ui.join(__dirname,"../","hdb_boot_properties.file")),e}a(Wie,"getPropsFilePath");function Qie(e,t){let r,s;return s=new Promise(function(n){r=setTimeout(function(){n(t)},e)}),{promise:s,cancel:function(){clearTimeout(r)}}}a(Qie,"timeoutPromise");async function zie(e){if(!e)throw new Error("Invalid port passed as parameter");return new Promise((t,r)=>{let s=Rie.createServer().once("error",n=>{n.code==="EADDRINUSE"?t(!0):r(n)}).once("listening",()=>s.once("close",()=>t(!1)).close()).listen(e)})}a(zie,"isPortTaken");function Jie(e){try{return ct.CLUSTER_OPERATIONS[e.toLowerCase()]!==void 0}catch(t){Nr.error(`Error checking operation against cluster ops ${t}`)}return!1}a(Jie,"isClusterOperation");function Xie(e,t){let r=(Ae(),ne(Ge)).getDatabases();if(!r[e])return ah.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e);if(!r[e][t])return ah.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(Xie,"checkGlobalSchemaTable");function jie(e,t){if(es(t)){Nr.warn("No CLUSTERING_USER defined, clustering disabled");return}if(es(e)||hn(e)){Nr.warn("No users to search.");return}let r;try{let s=e.get(t);s&&s.role.permission.cluster_user===!0&&s.active===!0&&(r=s)}catch(s){Nr.error(`unable to find cluster_user due to: ${s.message}`);return}if(r===void 0){Nr.warn(`CLUSTERING_USER: ${t} not found or is not active.`);return}return r}a(jie,"getClusterUser");function Zie(){rq.parsePromise=function(e,t,r){return new Promise(function(s,n){rq.parse(e,{header:!0,transformHeader:_q,chunk:t.bind(null,n),skipEmptyLines:!0,transform:r,dynamicTyping:!1,error:n,complete:s})})}}a(Zie,"promisifyPapaParse");function _q(e){if(typeof e!="string")throw new TypeError(`Expected a string, got ${typeof e}`);return e.charCodeAt(0)===65279?e.slice(1):e}a(_q,"removeBOM");function eoe(e,t,r){return new Promise(s=>{t.once(e,n=>{let i=r;Nr.info(`Got cluster status event response: ${bie(n)}`);try{i.cancel()}catch{Nr.error("Error trying to cancel timeout.")}s(n)})})}a(eoe,"createEventPromise");async function toe(e){let t=!0,r=0;do await oq(Cie*r++),(await Oie.findPs(e)).length>0&&(t=!1);while(t&&r<Die);if(t)throw new Error(`process ${e} was not started`)}a(toe,"checkProcessRunning");function roe(e,t){let r=dq(e);if(r)return r;let s=fq(e,t);if(s)return s}a(roe,"checkSchemaTableExist");function dq(e){let{getDatabases:t}=(Ae(),ne(Ge));if(!t()[e])return ah.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}a(dq,"checkSchemaExists");function fq(e,t){let{getDatabases:r}=(Ae(),ne(Ge));if(!r()[e][t])return ah.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(fq,"checkTableExists");function soe(){let e=oh().utc().add(1,ct.MOMENT_DAYS_TAG).startOf(ct.MOMENT_DAYS_TAG).unix(),t=oh().utc().unix();return e-t}a(soe,"getStartOfTomorrowInSeconds");function noe(){return oh().utc().format("DD-MM-YYYY")}a(noe,"getLimitKey");function ioe(e){try{let t=new Aie(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){Nr.error("Got an error back ticking items."),Nr.error(t)}}a(ioe,"backtickASTSchemaItems");function ooe(e){return[e]}a(ooe,"createForkArgs");function aoe(e){return e===!0||typeof e=="string"&&e.toLowerCase()==="true"}a(aoe,"autoCastBoolean");function coe(e,t){let{getDatabases:r}=(Ae(),ne(Ge)),s=r()[e]?.[t];return s?.primaryKey||s?.hash_attribute}a(coe,"getTableHashAttribute");function uoe(e){let{getDatabases:t}=(Ae(),ne(Ge));return t()[e]!==void 0}a(uoe,"doesSchemaExist");function loe(e,t){let{getDatabases:r}=(Ae(),ne(Ge));return r()[e]?.[t]!==void 0}a(loe,"doesTableExist");function _oe(e){try{return JSON.stringify(e)}catch{return e}}a(_oe,"stringifyObj");function doe(e){let t=oh.duration(e),r=t.seconds()>0?t.seconds()+"s":"",s=t.minutes()>0?t.minutes()+"m ":"",n=t.hours()>0?t.hours()+"h ":"",i=t.days()>0?t.days()+"d ":"";return(t.years()>0?t.years()+"y ":"")+i+n+s+r}a(doe,"ms_to_time");function foe(e,t){let r=Ui.basename(e,Ui.extname(e));return Ui.join(Ui.dirname(e),r+t)}a(foe,"changeExtension");function xA(){if(process.env[ct.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return process.env[ct.CONFIG_PARAMS.ROOTPATH.toUpperCase()];let e=Nie(process.argv);if(e[ct.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return e[ct.CONFIG_PARAMS.ROOTPATH.toUpperCase()]}a(xA,"getEnvCliRootPath");var BA;function Eoe(){if(BA)return BA;let e=xA();xA()&&iq.pathExistsSync(Ui.join(e,ct.HDB_CONFIG_FILE))&&(BA=!0)}a(Eoe,"noBootFile");function hoe(e,t){let r;return e.protocol==="http:"?r=Iie:r=yie,new Promise((s,n)=>{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",()=>{s(c)})});i.on("error",o=>{n(o)}),i.write(JSON.stringify(t)),i.end()})}a(hoe,"httpRequest");function moe(e){if(!e.schema&&!e.database){e.schema=ct.DEFAULT_DATABASE_NAME;return}e.database&&(e.schema=e.database)}a(moe,"transformReq");function poe(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(poe,"convertToMS")});var ee=g(($Se,Sq)=>{"use strict";var qA=require("fs-extra"),Bo=require("path"),hq=require("os"),Soe=require("properties-reader"),Pl=$(),Ul=Q(),ue=M(),ch=Br(),Toe="Error initializing environment manager",uh="BOOT_PROPS_FILE_PATH",mq=!1,goe={[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},Yn={};Sq.exports={BOOT_PROPS_FILE_PATH:uh,getHdbBasePath:Roe,setHdbBasePath:Aoe,get:pq,initSync:boe,setProperty:Ue,initTestEnvironment:Noe};function Roe(){return Yn[ue.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]}a(Roe,"getHdbBasePath");function Aoe(e){Yn[ue.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=e}a(Aoe,"setHdbBasePath");function pq(e){let t=ch.getConfigValue(e);return t===void 0?Yn[e]:t}a(pq,"get");function Ue(e,t){goe[e]&&(Yn[e]=t),ch.updateConfigObject(e,t)}a(Ue,"setProperty");function Ooe(){let e;try{e=Ul.getPropsFilePath(),qA.accessSync(e,qA.constants.F_OK|qA.constants.R_OK),mq=!0;let t=Soe(e);return Yn[ue.HDB_SETTINGS_NAMES.INSTALL_USER]=t.get(ue.HDB_SETTINGS_NAMES.INSTALL_USER),Yn[ue.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY]=t.get(ue.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY),Yn[uh]=e,!0}catch{return Pl.trace(`Environment manager found no properties file at ${e}`),!1}}a(Ooe,"doesPropFileExist");function boe(e=!1){try{(mq||Ooe()||Ul.noBootFile())&&(ch.initConfig(e),Yn[ue.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=ch.getConfigValue(ue.HDB_SETTINGS_NAMES.HDB_ROOT_KEY))}catch(t){Pl.error(Toe),Pl.error(t),console.error(t),process.exit(1)}}a(boe,"initSync");function Noe(e={}){try{let{keep_alive_timeout:t,headers_timeout:r,server_timeout:s,https_enabled:n,cors_enabled:i,cors_accesslist:o,local_studio_on:c}=e,u=Bo.join(__dirname,"../../","unitTests");Yn[uh]=Bo.join(u,"hdb_boot_properties.file"),Ue(ue.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY,Bo.join(u,"settings.test")),Ue(ue.HDB_SETTINGS_NAMES.INSTALL_USER,hq.userInfo()?hq.userInfo().username:void 0),Ue(ue.HDB_SETTINGS_NAMES.LOG_LEVEL_KEY,"debug"),Ue(ue.HDB_SETTINGS_NAMES.LOG_PATH_KEY,Bo.join(u,"envDir","log")),Ue(ue.HDB_SETTINGS_NAMES.LOG_DAILY_ROTATE_KEY,!1),Ue(ue.HDB_SETTINGS_NAMES.CLUSTERING_ENABLED_KEY,!0),Ue(ue.HDB_SETTINGS_NAMES.CLUSTERING_NODE_NAME_KEY,"1231412de213"),Ue(ue.HDB_SETTINGS_NAMES.HDB_ROOT_KEY,Bo.join(u,"envDir")),Ue(ue.CONFIG_PARAMS.STORAGE_PATH,Bo.join(u,"envDir")),n&&(Ue(ue.CONFIG_PARAMS.HTTP_SECUREPORT,pq(ue.CONFIG_PARAMS.HTTP_PORT)),Ue(ue.CONFIG_PARAMS.HTTP_PORT,null)),Ue(ue.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HTTPS,!!n),Ue(ue.HDB_SETTINGS_NAMES.SERVER_PORT_KEY,9925),Ue(ue.HDB_SETTINGS_NAMES.CORS_ENABLED_KEY,Ul.isEmpty(i)?!1:i),Ue(ue.CONFIG_PARAMS.HTTP_CORS,Ul.isEmpty(i)?!1:i),Ue(ue.HDB_SETTINGS_NAMES.MAX_CUSTOM_FUNCTION_PROCESSES,2),Ue(ue.HDB_SETTINGS_NAMES.MAX_HDB_PROCESSES,4),Ue(ue.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_PORT_KEY,9926),Ue(ue.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_ENABLED_KEY,!0),Ue(ue.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY,Bo.resolve(__dirname,"../../unitTests/server/fastifyRoutes/custom_functions")),Ue(ue.HDB_SETTINGS_NAMES.LOCAL_STUDIO_ON,Ul.isEmpty(c)?!1:c),o&&(Ue("CORS_ACCESSLIST",o),Ue(ue.CONFIG_PARAMS.HTTP_CORSACCESSLIST,o)),s&&(Ue(ue.HDB_SETTINGS_NAMES.SERVER_TIMEOUT_KEY,s),Ue(ue.CONFIG_PARAMS.HTTP_TIMEOUT,s)),t&&(Ue(ue.HDB_SETTINGS_NAMES.SERVER_KEEP_ALIVE_TIMEOUT_KEY,t),Ue(ue.CONFIG_PARAMS.HTTP_KEEPALIVETIMEOUT,t)),r&&(Ue(ue.HDB_SETTINGS_NAMES.SERVER_HEADERS_TIMEOUT_KEY,r),Ue(ue.CONFIG_PARAMS.HTTP_HEADERSTIMEOUT,r))}catch(t){let r=`Error reading in HDB environment variables from path ${uh}. Please check your boot props and settings files`;Pl.fatal(r),Pl.error(t)}}a(Noe,"initTestEnvironment")});var Oq=g((KSe,Aq)=>{"use strict";var Rq=require("joi"),{string:vl,boolean:Tq,array:yoe}=Rq.types(),gq=M(),Ioe=Xe();Aq.exports=woe;function woe(e){let t=Rq.object({operation:vl.valid(gq.OPERATIONS_ENUM.ADD_NODE,gq.OPERATIONS_ENUM.UPDATE_NODE).required(),node_name:vl.required(),subscriptions:yoe.items({schema:vl.required(),table:vl.optional(),hash_attribute:vl.optional(),subscribe:Tq.required(),publish:Tq.required()}).min(1).required()});return Ioe.validateBySchema(e,t)}a(woe,"updateRemoteSourceValidator")});var Bl=g((QSe,bq)=>{"use strict";var GA=class{static{a(this,"UpdateRemoteResponseObject")}constructor(t,r,s=void 0){this.status=t,this.message=r,this.system_info=s}};bq.exports=GA});var Cq=g((JSe,wq)=>{"use strict";var Coe=Oq(),Kn=$(),FA=Fe(),Nq=M(),kA=cs(),Pi=nt(),yq=fu(),Doe=Z_(),{Node:Loe,NodeSubscription:Iq}=hi(),VA=Bl(),$A=Q(),Moe=ee(),{cloneDeep:Uoe}=require("lodash"),{broadcast:Poe}=Ke();wq.exports=voe;async function voe(e){try{let t=Coe(e);if(t)return Kn.error(`Validation error in updateRemoteSource: ${t.message}`),new VA(FA.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,t.message);let{subscriptions:r,node_name:s,system_info:n}=e,i=[],o=Uoe(await kA.getNodeRecord(s)),c=!$A.isEmptyOrZeroLength(o);o=c?o[0]:o,c&&Kn.trace(`Existing record found for ${s}, updating records subscriptions`);for(let _=0,l=r.length;_<l;_++){let d=r[_],f=d.schema,E=d.table;if(!$A.doesSchemaExist(f)){Kn.trace(`updateRemoteSource creating schema: ${f}`);try{await yq.createSchema({operation:"create_schema",schema:f})}catch(h){Kn.error(h)}}if(E&&!$A.doesTableExist(f,E)){let h=new Doe(f,E,d.hash_attribute);d.attributes&&(h.attributes=d.attributes),Kn.trace(`updateRemoteSource creating table: ${E} in schema: ${f} with attributes: ${JSON.stringify(d.attributes)}`);try{await yq.createTable(h)}catch(p){Kn.error(p)}Kn.trace(`Creating local stream for ${f}.${E}`),await Pi.createLocalTableStream(f,E)}if(f===Nq.SYSTEM_SCHEMA_NAME&&await Pi.createLocalTableStream(f,E),c?(await Pi.updateConsumerIterator(f,E,s,"stop"),await Pi.updateRemoteConsumer(d,s),d.subscribe===!0&&await Pi.updateConsumerIterator(f,E,s,"start")):(await Pi.updateRemoteConsumer(d,s),d.subscribe===!0?await Pi.updateConsumerIterator(f,E,s,"start"):await Pi.updateConsumerIterator(f,E,s,"stop")),c){let h=!1;for(let p=0,S=o.subscriptions.length;p<S;p++){let T=o.subscriptions[p];if(T.schema===f&&T.table===E){T.publish=d.publish,T.subscribe=d.subscribe,h=!0;break}}h||o.subscriptions.push(new Iq(f,E,d.publish,d.subscribe))}else i.push(new Iq(f,E,d.publish,d.subscribe))}c||(o=new Loe(s,i,void 0),Kn.trace(`No record found for ${s}, creating a new one`));let u=Object.create({});return Object.assign(u,o),u.system_info=n,await kA.upsertNodeRecord(u),Poe({type:"nats_update"}),new VA(FA.UPDATE_REMOTE_RESPONSE_STATUSES.SUCCESS,`Node ${Moe.get(Nq.CONFIG_PARAMS.CLUSTERING_NODENAME)} successfully updated remote source`,await kA.getSystemInfo())}catch(t){Kn.error(t);let r=t.message?t.message:t;return new VA(FA.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,r)}}a(voe,"updateRemoteSource")});var Uq=g((jSe,Mq)=>{"use strict";var Lq=require("joi"),{string:Dq}=Lq.types(),Boe=M(),Hoe=Xe();Mq.exports=xoe;function xoe(e){let t=Lq.object({operation:Dq.valid(Boe.OPERATIONS_ENUM.REMOVE_NODE).required(),node_name:Dq.required()});return Hoe.validateBySchema(e,t)}a(xoe,"removeRemoteSourceValidator")});var Bq=g((eTe,vq)=>{"use strict";var qoe=Uq(),lh=$(),_h=Fe(),YA=M(),Goe=cs(),Foe=Q(),Pq=nt(),koe=ee(),dh=Bl(),{NodeSubscription:Voe}=hi(),$oe=sa(),Yoe=ni(),{broadcast:Koe}=Ke(),Woe=koe.get(YA.CONFIG_PARAMS.CLUSTERING_NODENAME);vq.exports=Qoe;async function Qoe(e){try{let t=qoe(e);if(t)return lh.error(`Validation error in removeRemoteSource: ${t.message}`),new dh(_h.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,t.message);let r=e.node_name,s=await Goe.getNodeRecord(r);if(Foe.isEmptyOrZeroLength(s)){let i=`No record found for node '${r}'`;return lh.error(i),new dh(_h.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,i)}s=s[0];for(let i=0,o=s.subscriptions.length;i<o;i++){let c=s.subscriptions[i];lh.trace(`remove remote source removing subscription: ${c.schema}.${c.table} for node: ${r}`);let u=new Voe(c.schema,c.table,!1,!1);await Pq.updateConsumerIterator(c.schema,c.table,r,"stop"),await Pq.updateRemoteConsumer(u,r)}let n=new $oe(YA.SYSTEM_SCHEMA_NAME,YA.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[r]);return await Yoe.deleteRecord(n),Koe({type:"nats_update"}),new dh(_h.UPDATE_REMOTE_RESPONSE_STATUSES.SUCCESS,`Node ${Woe} successfully removed node '${r}'.`)}catch(t){lh.error(t);let r=t.message?t.message:t;return new dh(_h.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,r)}}a(Qoe,"removeRemoteSource")});var Gq=g((rTe,qq)=>{"use strict";var fh=$(),Hl=M(),Hq=Fe(),KA=ee(),zoe=Q(),xq=Bl(),Joe=cs(),Xoe=Dd(),joe=Ur();qq.exports=Zoe;async function Zoe(e){try{fh.trace("getRemoteSourceConfig called");let t=process.uptime()*1e3,r=zoe.ms_to_time(t),s=new eae(KA.get(Hl.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),KA.get(Hl.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_PORT)??KA.get(Hl.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_SECUREPORT),r,await Joe.getSystemInfo());try{let n={name:e.node_name,system_info:e.system_info},i=new Xoe(Hl.SYSTEM_SCHEMA_NAME,Hl.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[n]);await joe.update(i)}catch(n){fh.error("Get remote config encountered an error updating system info for node:",e.node_name,n)}return fh.trace("getRemoteSourceConfig response:",s),new xq(Hq.UPDATE_REMOTE_RESPONSE_STATUSES.SUCCESS,s)}catch(t){fh.error(t);let r=t.message?t.message:t;return new xq(Hq.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,r)}}a(Zoe,"getRemoteSourceConfig");function eae(e,t,r,s){this.uptime=r,this.ports={clustering:e,operations_api:t},this.system_info=s}a(eae,"ConfigResponseObject")});var $q=g((nTe,Vq)=>{"use strict";var Fq=ee();Fq.initSync();var kq=nt(),xl=$(),tc=M(),WA=Fe(),tae=Cq(),rae=Bq(),sae=Gq(),nae=Bl(),{encode:iae,decode:oae}=require("msgpackr"),aae=An(),cae=ti(),uae=require("util"),lae=M(),{isMainThread:_ae,parentPort:dae}=require("worker_threads");Ke();var fae=uae.promisify(aae.setSchemaDataToGlobal),QA=Fq.get(tc.CONFIG_PARAMS.CLUSTERING_NODENAME);Vq.exports=Eae;async function Eae(){try{xl.notify("Starting reply service."),await fae();let e=await kq.getConnection(),t=`${QA}.__request__`,r=e.subscribe(t,{queue:QA});await hae(r)}catch(e){xl.error(e)}}a(Eae,"initialize");async function hae(e){for await(let t of e){let r=oae(t.data),s;switch(r.operation){case tc.OPERATIONS_ENUM.ADD_NODE:case tc.OPERATIONS_ENUM.UPDATE_NODE:s=await tae(r);break;case tc.OPERATIONS_ENUM.REMOVE_NODE:s=await rae(r);break;case tc.OPERATIONS_ENUM.CLUSTER_STATUS:s=await sae(r);break;case tc.OPERATIONS_ENUM.DESCRIBE_ALL:s=await mae();break;default:let n=`node '${QA}' reply service received unrecognized request operation`;xl.error(n),s=new nae(WA.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,n)}xl.trace(s),t.respond(iae(s))}}a(hae,"handleRequest");async function mae(){try{return{status:WA.UPDATE_REMOTE_RESPONSE_STATUSES.SUCCESS,message:await cae.describeAll()}}catch(e){return xl.error(e),{status:WA.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,message:e.message}}}a(mae,"getRemoteDescribeAll");_ae||dae.on("message",async e=>{let{type:t}=e;t===lae.ITC_EVENT_TYPES.SHUTDOWN&&kq.closeConnection()})});var pae=$q();(async()=>{try{await pae()}catch(e){console.error("Error launching Nats reply service."),console.error(e)}})();
|
|
31
|
+
`))}},25).unref()}o.close?.(()=>{if(we.get(Et.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET)&&DE()==0)try{qH(we.get(Et.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET))}catch{}clearInterval(c),setTimeout(()=>{console.log("forced close server",i,wE),o.cantCleanupProperly||rr.warn("Had to forcefully exit the thread",wE),process.exit(0)},5e3).unref()})}if(zH||process.env.DEV_MODE)try{require("inspector").close()}catch(i){rr.info("Could not close debugger",i)}}}).ref();let e=[];if(FH&&!Rse)for(let t in ds){let r=ds[t];if(isNaN(t)&&DE()==0){dse(t)&&qH(t),e.push(new Promise((s,i)=>{r.listen({path:t},()=>{s(),rr.info("Domain socket listening on "+t)}).on("error",i)}));continue}let n;try{n=FH(+t,"::")}catch(s){console.error(`Unable to bind to port ${t}`,s);continue}e.push(new Promise((s,i)=>{r.listen({fd:n},()=>{s(),rr.trace("Listening on port "+t,wE)}).on("error",i)}))}Promise.all(e).then(()=>{Al?.postMessage({type:Et.ITC_EVENT_TYPES.CHILD_STARTED})})})}a(JH,"startServers");YH||JH();function rA(e,t,r){let n=e?.read?e:new ase({fd:e,readable:!0,writable:!0,allowHalfOpen:!0}),s=ds[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=ds[t];c?(typeof c=="function"?c(n):c.emit("connection",n),r&&n.emit("data",r)):o<5?i(o+1):(rr.error(`Server on port ${t} was not registered`),n.destroy())},1e3)},"retry");i(1)}return n}a(rA,"deliverSocket");var VH=new Map;function bse(e){let{port:t,event:r,data:n,requestId:s}=e,i;switch(i=VH.get(s),r){case"connection":i=rA(void 0,t),VH.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(bse,"proxyRequest");function nA(e,t,r=!0){!+t&&t!==we.get(Et.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET)&&(t=parseInt(we.get(Et.CONFIG_PARAMS.HTTP_PORT),10));let n=ds[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",$H),s.on("unhandled",(i,o)=>{e.cantCleanupProperly&&(n.cantCleanupProperly=!0),e.emit("request",i,o)}),n.lastServer=e}else ds[t]=e;e.on("unhandled",$H)}a(nA,"registerServer");function XH(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=[],we.get(Et.CONFIG_PARAMS.HTTP_PORT)!=null&&t.push({port:we.get(Et.CONFIG_PARAMS.HTTP_PORT),secure:we.get(Et.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HTTPS)}),we.get(Et.CONFIG_PARAMS.HTTP_SECUREPORT)!=null&&t.push({port:we.get(Et.CONFIG_PARAMS.HTTP_SECUREPORT),secure:!0})),e?.isOperationsServer&&we.get(Et.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET)&&t.push({port:we.get(Et.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_DOMAINSOCKET),secure:!1}),t}a(XH,"getPorts");function sA(e,t){for(let{port:r,secure:n}of XH(t))jH(r,n,t?.isOperationsServer),typeof e=="function"?eA[t?.runFirst?"unshift":"push"]({listener:e,port:t?.port||r}):(e.isSecure=n,nA(e,r,!1)),LE[r]=tA(eA,r),Ase=tA(Ose,r)}a(sA,"httpServer");function jH(e,t,r){if(!Di[e]){let n=r?"operationsApi_network":"http",s={keepAliveTimeout:we.get(n+"_keepAliveTimeout"),headersTimeout:we.get(n+"_headersTimeout"),requestTimeout:we.get(n+"_timeout")},i=we.get(n+"_mtls"),o=we.get(n+"_mtls_required");if(t){n=r?"operationsApi_":"";let u=we.get(n+"tls_privateKey"),_=we.get(n+"tls_certificate"),l=we.get(n+"tls_certificateAuthority");Object.assign(s,{allowHTTP1:!0,key:Wa(u),ciphers:we.get("tls_ciphers"),cert:Wa(_),ca:l&&Wa(l),rejectUnauthorized:!!o,requestCert:!!i,ticketKeys:hse(),maxHeaderSize:we.get(Et.CONFIG_PARAMS.HTTP_MAXHEADERSIZE)})}let c=Tse();Di[e]=(t?_se:use)(s,async(u,_)=>{try{let d=performance.now(),f=new WH(u,_);r&&(f.isOperationsServer=!0);let E=await LE[e](f);if(!E){if(f._nodeResponse.statusCode)return;E=ZH(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 x of E.headers||[])_.setHeader(x[0],x[1]);return u.baseRequest=f,_.baseResponse=E,Di[e].emit("unhandled",u,_)}let h=E.status||200,p=performance.now(),S=p-d,T=E.body,A;if(!E.handlesHeaders){let x=E.headers||new KH;T?T.length>=0&&(typeof T=="string"?x.set("Content-Length",Buffer.byteLength(T)):x.set("Content-Length",T.length),A=!0):(x.set("Content-Length","0"),A=!0);let P=`hdb;dur=${S.toFixed(2)}`;E.wasCacheMiss&&(P+=", miss"),pse(x,"Server-Timing",P,!0),_.writeHead(h,x&&(x[Symbol.iterator]?Array.from(x):x)),A&&_.end(T)}let R=f.handlerPath,M=f.method;if(Rl(S,"duration",R,M,E.wasCacheMiss==null?void 0:E.wasCacheMiss?"cache-miss":"cache-hit"),Sse(h<400,"success",R,M),!A)if(T?.pipe){T.pipe(_),T.destroy&&_.on("close",()=>{T.destroy()});let x=0;T.on("data",P=>{x+=P.length}),T.on("end",()=>{Rl(performance.now()-p,"transfer",R,M),Rl(x,"bytes-sent",R,M)})}else T?.then?T.then(x=>{_.end(x)},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?rr.warn(d):rr.info(d):rr.error(d)}a(l,"onError")}),i&&(Di[e].mtlsConfig=i),t&&(Di[e].on("secureConnection",u=>{u._parent.startTime&&Rl(performance.now()-u._parent.startTime,"tls-handshake",e),Rl(u.isSessionReused(),"tls-reused",e)}),Di[e].isSecure=!0),nA(Di[e],e)}return Di[e]}a(jH,"getHTTPServer");function tA(e,t){let r=ZH;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(tA,"makeCallbackChain");function ZH(e){return e.user&&(e._nodeRequest.user=e.user),{status:-1,body:"Not found",headers:new KH}}a(ZH,"unhandled");function yse(e,t){sA(e,{requestOnly:!0,...t})}a(yse,"onRequest");function Nse(e,t){let r;if(t.securePort){let n=we.get("tls_privateKey"),s=we.get("tls_certificate"),i=t.mtls?.certificateAuthority||we.get("tls_certificateAuthority");r=Ese({ciphers:we.get("tls_ciphers"),key:Wa(n),cert:Wa(s),ca:i&&Wa(i),rejectUnauthorized:!!t.mtls?.required,requestCert:!!t.mtls},e),ds[t.securePort]=r}return t.port&&(r=cse(e),ds[t.port]=r),r}a(Nse,"onSocket");Object.defineProperty(lse.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 Ise(e,t){let r;for(let{port:n,secure:s}of XH(t)){CE[n]||(CE[n]=new fse({server:r=jH(n,s)}),CE[n].on("connection",async(c,u)=>{try{let _=new WH(u);_.isWebSocket=!0;let l=LE[n](_),d=u.headers["sec-websocket-protocol"]||"",f=ZR[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(_){rr.warn("Error handling WebSocket connection",_)}}),CE[n].on("error",c=>{console.log("Error in setting up WebSocket server",c)}));let i=t?.subProtocol||"",o=ZR[n];o||(o=ZR[n]=[]),o.push({listener:e,protocol:i}),LE[n]=tA(eA,n)}return r}a(Ise,"onWebSocket");function $H(e,t){t.writeHead(404),t.end(`Not found
|
|
32
|
+
`)}a($H,"defaultNotFound")});async function sx({clientId:e,user:t,clean:r,will:n}){let s;if(e&&!r){let i=await oA.get(e,{returnNonexistent:!0});s=new uA(e,t,i),i&&(s.sessionWasPresent=!0)}else{if(e){let i=await oA.get(e);i&&i.delete()}s=new PE(e,t)}return n&&(n.id=e,n.user={username:t?.username},Ol.put(n)),s}function aA(){return UE++,UE>65500&&(UE=1),UE}function cA(e,t,r=e){let{topic:n,retain:s}=e;e.data=t,e.async=!0,e.authorize=!0;let i=Ai.getMatch(n);if(!i)throw new Error(`Can not publish to topic ${n} as it does not exist, no resource has been defined to handle this topic`);e.url=i.relativeURL;let o=i.Resource;return je(r,()=>s?t===void 0?o.delete(e,r):o.put(e,e.data,r):o.publish(e,e.data,r))}var tx,Li,rx,nx,oA,Ol,UE,PE,uA,ix=ge(()=>{Re();Ku();tx=v(Dr()),Li=v($());no();rx=v(Ke()),nx=v(ex());or();oA=lt({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"}]}}]}),Ol=lt({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,rx.getWorkerIndex)()===0&&(async()=>{await nx.when_components_loaded,await new Promise(e=>setTimeout(e,2e3));for await(let e of Ol.search({})){let t=e.data,r=Object.assign({},e);r.user?.username&&(r.user=await nt.getUser(r.user.username)),je(r,()=>{try{cA(r,t)}catch{(0,Li.warn)("Failed to publish will",t)}Ol.delete(e.id,r)})}})();a(sx,"getSession");UE=1;a(aA,"getNextMessageId");PE=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,Li.trace)("Resuming subscription from",s,"from",o);let E=Ai.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("/"),R;for(let P=0;P<A.length;P++)if(A[P].indexOf("+")>-1)if(A[P]==="+")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 M=!0;A[A.length-1]==="#"&&(A.length--,M=!1),R&&(n=a(P=>{let k=P.id;if(!Array.isArray(k)||M&&k.length!==A.length)return!1;for(let B=0;B<A.length;B++)if(A[B]!=="+"&&A[B]!==k[B])return!1;return!0},"filter"));let x=A.indexOf("+");f.url="/"+(x>-1?A.slice(0,x):A).concat("").join("/")}}let h=E.path,p=E.Resource,S=await je(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 R;if(A.type&&A.type!=="put"&&A.type!=="delete"&&A.type!=="message"&&A.type!=="patch"||n&&!n(A))continue;r?(A.topic=s,R=this.needsAcknowledge(A)):(A.acknowledge?.(),R=aA());let M=A.id;Array.isArray(M)&&(M=ba(M)),M==null&&(M=""),this.listener(h+"/"+M,A.value,R,t)}catch(R){(0,Li.warn)(R)}})(),T});return S.topic=s,S.qos=t.qos,this.subscriptions.push(S),S}resume(){}needsAcknowledge(t){let r=aA();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,cA(t,r)}setListener(t){this.listener=t}disconnect(t){let r={};je(r,async()=>{if(!t){let n=await Ol.get(this.sessionId,r);n?.doesExist()&&await cA(n,n.data,r)}await Ol.delete(this.sessionId,r)}).catch(n=>{(0,Li.warn)(`Error publishing MQTT will for ${this.sessionId}`,n)});for(let n of this.subscriptions)n.end();this.subscriptions=[]}};a(cA,"publish");uA=class extends PE{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=aA(),n={topic:t.topic,timestamp:t.timestamp};return t.acknowledge&&(n.acknowledge=t.acknowledge),this.awaitingAcks.set(r,n),r}acknowledge(t){let r=this.awaitingAcks.get(t);this.awaitingAcks.delete(t),r.acknowledge?.();let n=r.topic;for(let[,s]of this.awaitingAcks)if(s.topic===n&&s.timestamp<r.timestamp){for(let i of this.sessionRecord.subscriptions)if(i.topic===n){i.acks||(i.acks=[]),i.acks.push(r.timestamp),(0,Li.trace)("Received ack",n,r.timestamp),this.sessionRecord.update();return}}for(let s of this.sessionRecord.subscriptions)s.topic===n&&(s.startTime=r.timestamp);this.sessionRecord.update()}async addSubscription(t,r){await this.resumeSubscription(t,r);let{qos:n,startTime:s}=t;return n>0&&!s&&(this.sessionRecord.subscriptions=this.subscriptions.map(i=>{let o=i.startTime;return o||(o=i.startTime=(0,tx.getNextMonotonicTime)()),(0,Li.trace)("Added durable subscription",i.topic,o),{qos:i.qos,topic:i.topic,startTime:o}}),oA.put(this.sessionRecord)),t.qos}}});var dA={};qe(dA,{bypassAuth:()=>wse,start:()=>Cse});function wse(){ux=!0}function Cse({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"){Qr.debug("Received WSS connection for MQTT from",_._socket.remoteAddress);let{onMessage:f,onClose:E}=ax(_,(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=>{Qr.info("WebSocket error",h)})}},Object.assign({subProtocol:"mqtt"},n))),(t||s)&&(c=e.socket(async _=>{let l;if(Qr.debug("Received connection for MQTT from",_.remoteAddress),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),(0,bl.get)(zr.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)&&lA.notify({username:l.username,status:zr.AUTH_AUDIT_STATUS.SUCCESS,type:zr.AUTH_AUDIT_TYPES.AUTHENTICATION,auth_strategy:"MQTT mTLS",remote_address:_.remoteAddress})):Qr.debug("MQTT mTLS authorized connection (mTLS did not authorize a user)","from",_.remoteAddress)}catch(E){Qr.error(E)}else if(u.required)return Qr.info(`Unauthorized connection attempt, no authorized client certificate provided, error: ${_.authorizationError}`),_.end()}!l&&ux&&_.remoteAddress.includes("127.0.0.1")&&(l=await(0,cx.getSuperUser)(),Qr.debug("Auto-authorizing local connection",l?.username));let{onMessage:d,onClose:f}=ax(_,E=>_.write(E),null,l,o);_.on("data",d),_.on("close",f),_.on("error",E=>{Qr.info("Socket error",E)})},{port:t,securePort:s,mtls:u})),c}function ax(e,t,r,n,s){ox||(ox=!0,uu(d=>{vE>0&&d.push({metric:"mqtt-connections",connections:vE,byThread:!0})}));let i;vE++;let o,c={protocolVersion:4},u=(0,BE.parser)({protocolVersion:5});function _(d){u.parse(d)}a(_,"onMessage");function l(){vE--,i||(i=!0,o?.disconnect(),s.sessions.delete(o),cn(!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 nt.getUser(d.username,d.password.toString(),r),(0,bl.get)(zr.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGSUCCESSFUL)&&lA.notify({username:n.username,status:zr.AUTH_AUDIT_STATUS.SUCCESS,type:zr.AUTH_AUDIT_TYPES.AUTHENTICATION,auth_strategy:"MQTT",remote_address:e.remoteAddress})}catch{return(0,bl.get)(zr.CONFIG_PARAMS.LOGGING_AUDITAUTHEVENTS_LOGFAILED)&&lA.error({username:n.username,status:zr.AUTH_AUDIT_STATUS.FAILURE,type:zr.AUTH_AUDIT_TYPES.AUTHENTICATION,auth_strategy:"mqtt",remote_address:e.remoteAddress}),f({cmd:"connack",reasonCode:4,returnCode:134})}if(!n&&s.requireAuthentication)return cn(!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=Oo(r?.headers.get?.("content-type")));d.will.data=d.will.payload?.length>0?R(d.will.payload):void 0,delete d.will.payload}o=sx({user:n,...d}),o=await o,s.sessions.add(o)}catch(R){return Qr.error(R),cn(!1,"connection","mqtt","connect"),f({cmd:"connack",reasonCode:R.code||5,returnCode:R.code||128})}cn(!0,"connection","mqtt","connect"),f({cmd:"connack",sessionPresent:o.sessionWasPresent,reasonCode:0,returnCode:0}),o.setListener((R,M,x,P)=>{try{let k=R.indexOf("/",1),B=k>0?R.slice(0,k):R;f({cmd:"publish",topic:R,payload:E(M),messageId:x||Math.floor(Math.random()*1e8),qos:P.qos},B)}catch(k){Qr.error(k),o?.disconnect(),s.sessions.delete(o)}}),o.sessionWasPresent&&await o.resume();break;case"subscribe":let h=[];for(let R of d.subscriptions){let M;try{M=(await o.addSubscription(R,R.qos>=1)).qos||0}catch(x){Qr.error(x),M=c.protocolVersion<5?128:x.statusCode===403?135:x.statusCode===404?143:128}h.push(M)}await o.committed,f({cmd:"suback",granted:h,messageId:d.messageId});break;case"unsubscribe":{let R=[];for(let M of d.unsubscriptions)R.push(o.removeSubscription(M)?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=Oo(r?.headers.get?.("content-type"))),T=d.payload?.length>0?S(d.payload):void 0,A;try{A=await o.publish(d,T)}catch(R){Qr.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: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),cn(!0,"connection","mqtt","disconnect"),e.close?e.close():e.end();break}}catch(h){Qr.error(h),f({cmd:"disconnect"})}function f(h,p){let S=(0,BE.generate)(h,c);t(S),kr(S.length,"bytes-sent",p,h.cmd,"mqtt")}a(f,"sendPacket");function E(h){return bi(h,r)}a(E,"serialize")}),{onMessage:_,onClose:l}}var BE,cx,bl,zr,_A,lA,Qr,ux,ox,vE,lx=ge(()=>{BE=require("mqtt-packet");ix();cx=v(an());Na();ws();or();bl=v(ee()),zr=v(L()),_A=v($()),lA=(0,_A.loggerWithTag)("auth-event"),Qr=(0,_A.loggerWithTag)("mqtt"),ux=(0,bl.get)(zr.CONFIG_PARAMS.AUTHENTICATION_AUTHORIZELOCAL)??process.env.DEV_MODE;a(wse,"bypassAuth");a(Cse,"start");vE=0;a(ax,"onSocket")});var Lf={};qe(Lf,{component_errors:()=>za,loadComponent:()=>HE,loadComponentDirectories:()=>Tx,setErrorReporter:()=>Use});function Tx(e,t){t&&(EA=t),e&&(hA=e);let r=[];if((0,kn.existsSync)(fA)){let s=(0,kn.readdirSync)(fA,{withFileTypes:!0});for(let i of s){if(!i.isDirectory()&&!i.isSymbolicLink())continue;let o=i.name,c=(0,At.join)(fA,o);r.push(HE(c,EA,"hdb",!1))}}let n=process.env.RUN_HDB_APP;return n&&r.push(HE(n,EA,n,!1,null,process.env.DEV_MODE)),Promise.all(r).then(()=>{Sx=!0})}function Use(e){Nl=e}async function HE(e,t,r,n,s,i){if(!dx.has(e)){dx.set(e,!0),s&&(hA=s);try{let o;n&&(za=new Map);let c=(0,At.join)(e,n?"harperdb-config.yaml":"config.yaml");(0,kn.existsSync)(c)?o=n?(0,px.getConfigObj)():(0,fx.parseDocument)((0,kn.readFileSync)(c,"utf8"),{simpleKeys:!0}).toJSON():o=mA;let u=[],_=n;for(let l in o){let d=o[l];if(za.set(n?l:(0,At.basename)(e),!1),!d)continue;let f,E=d.package;try{if(E){let A=e,R;for(;!(0,kn.existsSync)(R=(0,At.join)(A,"node_modules",l));)if(A=(0,At.dirname)(A),A.length<(0,mx.getHdbBasePath)().length){R=null;break}if(R)f=await HE(R,t,r,!1),_=!0;else throw new Error(`Unable to find package ${l}:${E}`)}else f=Mse[l];if(!f)continue;u.push(f);let h=a(A=>(A.origin=r,lt(A)),"ensureTable"),p=d.network||(d.port||d.securePort)&&d,S=p?.securePort||p?.https&&p.port,T=!p?.https&&p?.port;if(Qa.isMainThread&&(f=await f.startOnMainThread?.({server:nt,ensureTable:h,port:T,securePort:S,resources:t,...d})||f,n&&p))for(let A of[T,S])try{if(+A&&!_x.includes(A)){let R=pA.get(SA.CONFIG_PARAMS.HTTP_SESSIONAFFINITY);R&&yl.default.warn("Session affinity is not recommended and may cause memory leaks"),(R||!OE)&&(_x.push(A),yH(A,R))}}catch(R){console.error("Error listening on socket",A,R,l)}if(t.isWorker&&(f=await f.start?.({server:nt,ensureTable:h,port:T,securePort:S,resources:t,...d})||f),hA.set(f,!0),(f.handleFile||f.handleDirectory)&&d.files){if(d.files.includes(".."))throw(0,hx.handleHDBError)("Can not reference parent directories");let A=(0,At.join)(e,d.files).replace(/\\/g,"/"),R=A.indexOf("/*");if(R>-1&&d.files!==mA[l]?.files&&!(0,kn.existsSync)(A.slice(0,R)))throw new Error(`The path '${A.slice(0,R)}' does not exist and cannot be used as the base of the resolved 'files' path value '${d.files}'`);let M=(0,At.basename)(e),x=d.path||"/";x=x.startsWith("/")?x:x.startsWith("./")?"/"+M+x.slice(2):x==="."?"/"+M:"/"+M+"/"+x;let P,k,B;if(d.root){let z=d.root;z.startsWith("/")&&(z=z.slice(1)),z.endsWith("/")&&(z=z.slice(0,-1)),z+="/",k=(0,At.join)(e,z)}else(B=A.indexOf("/*"))>-1&&(k=A.slice(0,B+1),P=(0,At.relative)(e,k));let X=!1;if(Qa.isMainThread&&f.setupDirectory&&(X=await f.setupDirectory?.(x,k,t)),t.isWorker&&f.handleDirectory&&(X=await f.handleDirectory?.(x,k,t)),X)continue;for(let z of await(0,Ex.default)(A,{onlyFiles:!1,objectMode:!0})){let{path:J,dirent:me}=z;_=!0;let ce=(0,At.relative)(e,J).replace(/\\/g,"/");if(P)if(ce.startsWith(P))ce=ce.slice(P.length+1);else throw new Error(`The root path '${d.root}' does not reference a valid part of the file path '${ce}'.The root path should be used to indicate the relative path/part of the file path for determining the exported web path.`);let de=x+(x.endsWith("/")?"":"/")+ce;try{if(me.isFile()){let Le=await Lse(J);Qa.isMainThread&&await f.setupFile?.(Le,de,J,t),t.isWorker&&await f.handleFile?.(Le,de,J,t)}else Qa.isMainThread&&await f.setupDirectory?.(de,J,t),t.isWorker&&await f.handleDirectory?.(de,J,t)}catch(Le){Le.message=`Could not load ${me.isFile()?"file":"directory"} '${J}'${d.module?" using '"+d.module+"'":""} for application '${e}' due to: ${Le.message}`,Nl?.(Le),((0,Ja.getWorkerIndex)()===0?console:yl.default).error(Le),t.set(d.path||"/",new Il(Le)),za.set(n?l:(0,At.basename)(e),Le.message)}}}}catch(h){h.message=`Could not load component '${l}' for application '${(0,At.basename)(e)}' due to: ${h.message}`,Nl?.(h),((0,Ja.getWorkerIndex)()===0?console:yl.default).error(h),t.set(d.path||"/",new Il(h),null,!0),za.set(n?l:(0,At.basename)(e),h.message)}}if(Qa.isMainThread&&!Sx&&i&&(0,Ja.watchDir)(e,async()=>Tx()),o.extensionModule)return await u_((0,At.join)(e,o.extensionModule));if(!_&&t.isWorker){let l=`${e} did not load any modules, resources, or files, is this a valid component?`;Nl?.(new Error(l)),((0,Ja.getWorkerIndex)()===0?console:yl.default).error(l),za.set((0,At.basename)(e),l)}}catch(o){console.error(`Could not load application directory ${e}`,o),o.message=`Could not load application due to ${o.message}`,Nl?.(o),t.set("",new Il(o))}}}var kn,At,Qa,fx,pA,SA,Ex,Ja,yl,hx,mx,Dse,px,Lse,fA,hA,Sx,EA,za,Mse,mA,_x,dx,Nl,Il,Mf=ge(()=>{kn=require("fs"),At=require("path"),Qa=require("worker_threads"),fx=require("yaml"),pA=v(ee()),SA=v(L());Sb();Ab();Ob();I0();EH();gH();Ex=v(require("fast-glob")),Ja=v(Ke()),yl=v($());Wh();or();hx=v(ne());Nn();Re();NH();mx=v(ee()),Dse=v(LH());Of();GH();lx();px=v(lr());bE();({readFile:Lse}=kn.promises),fA=pA.get(SA.CONFIG_PARAMS.COMPONENTSROOT),hA=new Map,za=new Map;a(Tx,"loadComponentDirectories");Mse={REST:Jf,rest:Jf,graphqlSchema:Kh,jsResource:zh,fastifyRoutes:BR,login:Xh,static:HR,operationsApi:Dse,customFunctions:{},http:{},clustering:XR,authentication:Qu,mqtt:dA},mA={rest:!0,graphqlSchema:{files:"*.graphql"},jsResource:{files:"resources.js"},fastifyRoutes:{files:"routes/*.js",path:"."}};Object.defineProperty(mA,"static",{value:{files:"web/**"}});_x=[],dx=new Map;a(Use,"setErrorReporter");a(HE,"loadComponent");Il=class extends Ft{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 iA=g((ESe,Rx)=>{var{isMainThread:gx}=require("worker_threads"),{getTables:Pse}=(Re(),ie(Fe)),{loadComponentDirectories:vse,loadComponent:Bse}=(Mf(),ie(Lf)),{resetResources:Hse}=(Ku(),ie(BP)),xse=mg(),Gse=lr(),{dirname:qse}=require("path"),{getConnection:Fse}=it(),kse=ee(),Vse=L(),TA=new Map;async function $se(e=!1){!gx&&kse.get(Vse.CONFIG_PARAMS.CLUSTERING_ENABLED)&&Fse();try{gx&&await xse()}catch(n){console.error(n)}let t=Hse();Pse(),t.isWorker=e,await Bse(qse(Gse.getConfigFilePath()),t,"hdb",!0,TA),await vse(TA,t);let r=[];for(let[n]of TA)n.ready&&r.push(n.ready());r.length>0&&await Promise.all(r)}a($se,"loadRootComponents");Rx.exports.loadRootComponents=$se});var Ke=g((mSe,Ui)=>{"use strict";var{Worker:Yse,MessageChannel:Kse,parentPort:Es,isMainThread:bA,threadId:Wse,workerData:$s}=require("worker_threads"),{PACKAGE_ROOT:Qse}=L(),{join:yx,isAbsolute:zse,extname:Jse}=require("path"),{server:Nx}=(or(),ie(xi)),{watch:Xse,readdir:jse}=require("fs/promises"),{totalmem:Ax}=require("os"),wl=L(),Ix=ee(),Ys=$(),{randomBytes:Zse}=require("crypto"),{_assignPackageExport:eie}=require("../index"),tie=L(),Ox=1024*1024,Mi=[],pn=[],rie=50,yA=1e4,nie="restart",wx="request_thread_info",Cx="resource_report",Dx="thread_info",Lx="added-port",sie="ack",gA;eie("threads",pn);Ui.exports={startWorker:RA,restartWorkers:IA,shutdownWorkers:uie,workers:Mi,setMonitorListener:pie,onMessageFromWorkers:lie,onMessageByType:xx,broadcast:die,broadcastWithAcknowledgement:Eie,setChildListenerByType:cie,getWorkerIndex:Mx,getWorkerCount:Ux,getTicketKeys:vx,setMainIsWorker:oie,setTerminateTimeout:iie,restartNumber:$s?.restartNumber||1};pn.onMessageByType=xx;pn.sendToThread=function(e,t){if(!t?.type)throw new Error("A message with a type must be provided");let r=pn.find(n=>n.threadId===e);if(r)return r.postMessage(t),!0};var NA;function iie(e){yA=e}a(iie,"setTerminateTimeout");function Mx(){return $s?$s.workerIndex:NA?0:void 0}a(Mx,"getWorkerIndex");function Ux(){return $s?$s.workerCount:NA?1:void 0}a(Ux,"getWorkerCount");function oie(e){NA=e}a(oie,"setMainIsWorker");var Px=1,xE;function vx(){return xE||(xE=bA?Zse(48):$s.ticketKeys,xE)}a(vx,"getTicketKeys");Object.defineProperty(Nx,"workerIndex",{get(){return Mx()}});Object.defineProperty(Nx,"workerCount",{get(){return Ux()}});var Bx={[wx](e,t){hie(t)},[Cx](e,t){mie(t,e)}};function RA(e,t={}){let r=process.constrainedMemory?.()||Ax();r=Math.min(r,Ax(),2e4*Ox);let n=Ix.get(wl.CONFIG_PARAMS.THREADS_MAXHEAPMEMORY)??Math.max(Math.floor(r/Ox/(10+(t.threadCount||1)/4)),512),s=Math.min(Math.max(n>>6,16),64),i=[],o=[];for(let u of pn){let _=new Kse;_.existingPort=u,i.push(_),o.push(_.port2)}Jse(e)||(e+=".js");let c=new Yse(zse(e)?e:yx(Qse,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:Px=t.threadCount,name:t.name,restartNumber:Ui.exports.restartNumber,ticketKeys:vx()},transferList:o},t));for(let{port1:u,existingPort:_}of i)_.postMessage({type:Lx,port:u,threadId:c.threadId},[u]);return qE(c,!0),c.unexpectedRestarts=t.unexpectedRestarts||0,c.startCopy=()=>RA(e,t),c.on("error",u=>{console.error("Worker error:",u),Ys.error("Worker error:",u)}),c.on("exit",u=>{Mi.splice(Mi.indexOf(c),1),!c.wasShutdown&&t.autoRestart!==!1&&(c.unexpectedRestarts<rie?(t.unexpectedRestarts=c.unexpectedRestarts+1,RA(e,t)):Ys.error(`Thread has been restarted ${c.restarts} times and will not be restarted`))}),c.on("message",u=>{Bx[u.type]?.(u,c)}),Mi.push(c),Tie(),t.onStarted&&t.onStarted(c),c.name=t.name,c}a(RA,"startWorker");var aie=[wl.THREAD_TYPES.HTTP];async function IA(e=null,t=Math.max(Px>3,1),r=!0){if(bA){if(r){let{loadRootComponents:o}=iA();await o()}Ui.exports.restartNumber++,t<1&&(t=t*Mi.length);let n=[],s=[];for(let o of Mi.slice(0)){if(e&&o.name!==e||o.wasShutdown)continue;Ys.trace("sending shutdown request to ",o.threadId),o.postMessage({restartNumber:Ui.exports.restartNumber,type:wl.ITC_EVENT_TYPES.SHUTDOWN}),o.wasShutdown=!0,o.emit("shutdown",{});let c=aie.indexOf(o.name)>-1,u=new Promise(_=>{let l=setTimeout(()=>o.terminate(),yA*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===tie.ITC_EVENT_TYPES.CHILD_STARTED&&(Ys.trace("Worker has started",_.threadId),d(),s.splice(s.indexOf(l)),_.off("message",f))},"startListener");Ys.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}=Tf();r&&(e==="http"||!e)&&Ix.get(wl.CONFIG_PARAMS.CLUSTERING_ENABLED)&&await i({service:"clustering"})}else Es.postMessage({type:nie,workerType:e})}a(IA,"restartWorkers");function cie(e,t){Bx[e]=t}a(cie,"setChildListenerByType");function uie(e){return IA(e,1/0,!1)}a(uie,"shutdownWorkers");var Hx=[];function lie(e){Hx.push(e)}a(lie,"onMessageFromWorkers");var AA=new Map;function xx(e,t){let r=AA.get(e);r||AA.set(e,r=[]),r.push(t)}a(xx,"onMessageByType");var _ie=10;async function die(e){let t=0;for(let r of pn)try{r.postMessage(e),t++>_ie&&(t=0,await new Promise(setImmediate))}catch(n){Ys.error("Unable to send message to worker",n)}}a(die,"broadcast");var GE=new Map,fie=1;function Eie(e){return new Promise(t=>{let r=0;for(let n of pn)try{let s=fie++,i=a(()=>{GE.delete(s),--r===0&&t(),n!==Es&&--n.refCount===0&&n.unref()},"ack_handler");i.port=n,n.ref(),n.refCount=(n.refCount||0)+1,GE.set(e.requestId=s,i),n.hasAckCloseListener||(n.hasAckCloseListener=!0,n.on(n.close?"close":"exit",()=>{for(let[,o]of GE)o.port===n&&o()})),n.postMessage(e),r++}catch(s){Ys.error("Unable to send message to worker",s)}r===0&&t()})}a(Eie,"broadcastWithAcknowledgement");function hie(e){e.postMessage({type:Dx,workers:Gx()})}a(hie,"sendThreadInfo");function Gx(){let e=Date.now();return Mi.map(t=>({threadId:t.threadId,name:t.name,heapTotal:t.resources?.heapTotal,heapUsed:t.resources?.heapUsed,externalMemory:t.resources?.external,arrayBuffers:t.resources?.arrayBuffers,sinceLastUpdate:e-t.resources?.updated,...t.recentELU}))}a(Gx,"getChildWorkerInfo");function mie(e,t){e.resources=t,e.resources.updated=Date.now()}a(mie,"recordResourceReport");var OA;function pie(e){OA=e}a(pie,"setMonitorListener");var Sie=1e3,bx=!1;function Tie(){bx||(bx=!0,setInterval(()=>{for(let e of Mi){let t=e.performance.eventLoopUtilization(),r;e.lastTotalELU?r=e.performance.eventLoopUtilization(t,e.lastTotalELU):r=t,e.lastTotalELU=t,e.recentELU=r}OA&&OA()},Sie).unref())}a(Tie,"startMonitoring");var gie=1e3;if(Es){qE(Es);for(let e=0,t=$s.addPorts.length;e<t;e++){let r=$s.addPorts[e];r.threadId=$s.addThreadIds[e],qE(r)}setInterval(()=>{let e=process.memoryUsage();Es.postMessage({type:Cx,heapTotal:e.heapTotal,heapUsed:e.heapUsed,external:e.external,arrayBuffers:e.arrayBuffers})},gie).unref(),gA=a(()=>new Promise((e,t)=>{Es.on("message",r),Es.postMessage({type:wx});function r(n){n.type===Dx&&(Es.off("message",r),e(n.workers))}a(r,"receiveThreadInfo")}),"getThreadInfo")}else gA=Gx;Ui.exports.getThreadInfo=gA;function qE(e,t){pn.push(e),e.on("message",r=>{if(r.type===Lx)r.port.threadId=r.threadId,qE(r.port);else if(r.type===sie){let n=GE.get(r.id);n&&n()}else{for(let s of Hx)s(r,e);let n=AA.get(r.type);if(n)for(let s of n)try{s(r,e)}catch(i){Ys.error(i)}}}).on("close",()=>{pn.splice(pn.indexOf(e),1)}).on("exit",()=>{pn.splice(pn.indexOf(e),1)}),t?e.refCount=100:e.unref()}a(qE,"addPort");if(bA){let e,t,r=a(async(n,s)=>{s&&(e=s);for(let i of await jse(n,{withFileTypes:!0}))i.isDirectory()&&i.name!=="node_modules"&&r(yx(n,i.name));try{for await(let{filename:i}of Xse(n,{persistent:!1}))t&&clearTimeout(t),t=setTimeout(async()=>{e&&await e(),await IA(),console.log("Reloaded HarperDB components")},100)}catch(i){console.warn("Error trying to watch component directory",n,i)}},"watch_dir");Ui.exports.watchDir=r,process.env.WATCH_DIR&&r(process.env.WATCH_DIR)}else Es.on("message",async e=>{let{type:t}=e;t===wl.ITC_EVENT_TYPES.SHUTDOWN&&(Ui.exports.restartNumber=e.restartNumber,Es.unref(),setTimeout(()=>{Ys.warn("Thread did not voluntarily terminate",Wse),process.exit(0)},yA).unref())})});var CC={};qe(CC,{AUDIT_STORE_OPTIONS:()=>Ef,createAuditEntry:()=>E_,openAuditStore:()=>$E,readAuditEntry:()=>Mt,setAuditRetention:()=>Aie,transactionKeyEncoder:()=>Qx});function $E(e){let t=e.auditStore=e.openDB(Yx.AUDIT_STORE_NAME,Ef);t.rootStore=e;let r=[];t.addDeleteRemovalCallback=function(i,o){return r[i]=o,{remove(){delete r[i]}}};let n=null;function s(i=FE){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()-wA})){if((_[0]&15)===LA){let l=Mt(_),d=l.tableId;r[d]?.(l.recordId)}if(c=t.remove(u),await new Promise(setImmediate),++o>=Rie){i=10;break}}await c}finally{o===0&&(i=Math.min(i<<1,wA/10)),s(i)}},i).unref()}return a(s,"scheduleAuditCleanup"),t.scheduleAuditCleanup=s,(0,VE.getWorkerIndex)()===(0,VE.getWorkerCount)()-1&&s(FE),t}function Aie(e,t=FE){wA=e,FE=t}function E_(e,t,r,n,s,i,o){let c=zx[i];if(!c)throw new Error(`Invalid audit entry type ${i}`);let u=1;n&&(n>1?Xa.setFloat64(0,n):Sn.set(fm),u=9),f(0),f(t),d(r),Xa.setFloat64(u,e),u+=8,s?d(s):Sn[u++]=0,Sn[n?8:0]=c;let l=Sn.subarray(0,u);if(o)return Buffer.concat([l,o]);return l;function d(E){let h=u;u+=1,u=(0,ja.writeKey)(E,Sn,u);let p=u-h-1;p>127?p>16383?(UA.error("Key or username was too large for audit entry",E),u=h+1,Sn[h]=0):(Sn.copyWithin(h+2,h+1,u),Xa.setUint16(h,p|32768),u++):Sn[h]=p}function f(E){E<128?Sn[u++]=E:E<16384?(Xa.setUint16(u,E|32768),u+=2):E<1056964608?(Xa.setUint32(u,E|3221225472),u+=4):(Sn[u]=255,Xa.setUint32(u+1,E),u+=5)}}function Mt(e){try{let t=e.dataView||(e.dataView=new MA(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:zx[n&7],tableId:i,get recordId(){return $x(e,c,u)},version:_,previousLocalTime:r,get user(){return d>l?$x(e,l,d):void 0},getValue(f,E,h){if(n&CA||n&DA&&!E)return f.decoder.decode(e.subarray(t.position));if(n&DA&&h)return PA(f.getEntry(this.recordId),h,f)}}}catch(t){return UA.error("Reading audit entry error",t,e),{}}}function $x(e,t,r){let n=e.subarray(t,r);return(0,ja.readKey)(n,0,r-t)}var ja,kE,Yx,Kx,VE,Wx,UA,Sn,Xa,Qx,Ef,wA,Rie,FE,CA,DA,qx,LA,Fx,kx,Vx,zx,MA,ei=ge(()=>{ja=require("ordered-binary"),kE=v(ee()),Yx=v(ut()),Kx=v(L()),VE=v(Ke()),Wx=v(Q());Ic();UA=v($());YE();(0,kE.initSync)();Sn=Buffer.alloc(1024),Xa=new DataView(Sn.buffer,Sn.byteOffset,1024),Qx={writeKey(e,t,r){return e===Nc?(t.set(Nc,r),r+8):typeof e=="number"?((t.dataView||(t.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength))).setFloat64(r,e),r+8):(0,ja.writeKey)(e,t,r)},readKey(e,t,r){return e[t]===66?(e.dataView||(e.dataView=new DataView(e.buffer,e.byteOffset,e.byteLength))).getFloat64(t):(0,ja.readKey)(e,t,r)}},Ef={encoding:"binary",keyEncoder:Qx},wA=(0,Wx.convertToMS)((0,kE.get)(Kx.CONFIG_PARAMS.LOGGING_AUDITRETENTION))||86400*3,Rie=1e3,FE=1e4;a($E,"openAuditStore");a(Aie,"setAuditRetention");CA=16,DA=32,qx=1,LA=2,Fx=3,kx=4,Vx=5,zx={put:qx|CA,[qx]:"put",delete:LA,[LA]:"delete",message:Fx|CA,[Fx]:"message",invalidate:kx,[kx]:"invalidate",patch:Vx|DA,[Vx]:"patch"};a(E_,"createAuditEntry");a(Mt,"readAuditEntry");MA=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($x,"readKeySafely")});var vA={};qe(vA,{add:()=>KE,applyReverse:()=>Jx,getRecordAtTime:()=>PA,rebuildUpdateBefore:()=>WE});function KE(e,t,r){isNaN(e[t])?e[t]=r.value:e[t]+=r.value}function WE(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,KE(r,n,s)}}else r||(r={}),r[n]=e[n];return r}function Jx(e,t){for(let r in t){let n=t[r];if(n?.__op__){let s=Oie[n.__op__]?.reverse;if(s)s(e,r,{value:n.value});else throw new Error(`Unsupported operation ${n.__op__}`)}else e[r]=Xx}}function PA(e,t,r){let n=r.rootStore.auditStore,s=Object.assign({},e.value),i=e.localTime;for(;i>t;){let u=n.get(i),_=Mt(u);switch(_.type){case"put":s=_.getValue(r);break;case"patch":Jx(s,_.getValue(r));break;case"delete":s=null}i=_.previousLocalTime}let o={},c=0;for(let u in s)s[u]===Xx&&(o[u]=!0,c++);for(;c>0&&i>0;){let u=n.get(i),_=Mt(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 Oie,Xx,YE=ge(()=>{ei();a(KE,"add");KE.reverse=function(e,t,r){isNaN(e[t])||(e[t]-=r.value)};Oie={add:KE};a(WE,"rebuildUpdateBefore");a(Jx,"applyReverse");Xx={};a(PA,"getRecordAtTime")});function Jr(e){return e[Ct]||(e[Ct]=Object.create(null))}function jE(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 Tn.ClientError(`${c} must be a string, attempt to assign ${l}`);Jr(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 Tn.ClientError(`${c} must be a string, attempt to assign ${l}`);Jr(this)[c]=l},"set");break;case"Float":case"Number":u=a(function(l){if(!(typeof l=="number"||l==null&&o.nullable!==!1))throw new Tn.ClientError(`${c} must be a number, attempt to assign ${l}`);Jr(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 Tn.ClientError(`${c} must be an integer between -2147483648 and 2147483647, attempt to assign ${l}`);Jr(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 Tn.ClientError(`${c} must be an integer between -9007199254740992 and 9007199254740992, attempt to assign ${l}`);Jr(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 Tn.ClientError(`${c} must be a number, attempt to assign ${l}`);Jr(this)[c]=l},"set");break;case"Boolean":u=a(function(l){if(!(typeof l=="boolean"||l==null&&o.nullable!==!1))throw new Tn.ClientError(`${c} must be a boolean, attempt to assign ${l}`);Jr(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 Tn.ClientError(`${c} must be a Date, attempt to assign ${l}`);Jr(this)[c]=l},"set");break;case"Bytes":u=a(function(l){if(!(l instanceof Uint8Array||l==null&&o.nullable!==!1))throw new Tn.ClientError(`${c} must be a Buffer or Uint8Array, attempt to assign ${l}`);Jr(this)[c]=l},"set");break;case"Any":case void 0:u=a(function(l){Jr(this)[c]=l},"set");break;default:u=a(function(l){if(!(typeof l=="object"||l==null&&o.nullable!==!1))throw new Tn.ClientError(`${c} must be an object, attempt to assign ${l}`);Jr(this)[c]=l},"set")}_={get(){let l=this[Ct];if(l&&c in l){let f=l[c];if(f?.__op__){let E=this[_e]?.[c];return f.update(E)}return f}let d=this[_e]?.[c];if(d&&typeof d=="object"){let f=Zx(d,o);if(f)return l||(l=this[Ct]=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[Ct];return u?.[o]!==void 0?u[o]:this[_e]?.[o]}),i("set",function(o,c){let u=n[o];if(u)return u.set.call(this,c);if(t.sealed)throw new Tn.ClientError("Can not add a property to a sealed table schema");Jr(this)[o]=c}),i("deleteProperty",function(o){Jr(this)[o]=void 0}),i("toJSON",function(){let o=this[Ct],c;for(let _ in o){c||(c=Object.assign({},this[_e]));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[_e])),Object.assign(c,this)),c||this[_e]}),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 Zx(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?.[_e])throw new Error("Can not track an already tracked object, check for circular references");this[_e]=s}},jE(r,t)),new r(e)):new QE(e);case Array:let n=new JE(e.length);n[_e]=e;for(let s=0,i=e.length;s<i;s++){let o=e[s];o&&typeof o=="object"&&(o=Zx(o,t?.elements)),n[s]=o}return n;default:return e}}function ld(e){let t=e[Ct],r;for(let s in t){r||(r=Object.assign({},e[_e]));let i=t[s];if(i&&typeof i=="object")if(i.__op__){let o=r[s];i=i.update(o)}else i=ld(i);r[s]=i}return Object.keys(e).length>0&&(r||(r=Object.assign({},e[_e])),Object.assign(r,e)),r||e[_e]}function Uo(e,t=e[Ct]){let r;if(jx.call(e,_e)&&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=Uo(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[_e]));let s=t[n];if(s&&typeof s=="object")if(s.__op__){let i=vA[s?.__op__];if(i)i(r,n,s);else throw new Error("Invalid CRDT operation "+s.__op__);continue}else s=Uo(s);r[n]=s}return r?Object.freeze(r):jx.call(e,_e)?e[_e]:e}function zE(e){let t=e[_e];if(t===void 0)return!0;if(e.constructor===Array){if(!t||e[Mo]||e.length!==t.length)return!0;for(let r=0,n=e.length;r<n;r++){let s=t[r],i=e[r];if(s&&i?.[_e]===s){if(zE(i))return!0}else return!0}}else{let r=e[Ct];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[_e]===i){if(zE(s))return!0}else return!0}else return!0}}return!1}var Tn,Ct,QE,jx,Mo,JE,XE,_d=ge(()=>{Nn();Tn=v(ne());YE();Ct=Symbol("own-data");a(Jr,"getChanges");a(jE,"assignTrackedAccessors");a(Zx,"trackObject");QE=class{static{a(this,"GenericTrackedObject")}constructor(t){if(t?.[_e])throw new Error("Can not track an already tracked object, check for circular references");this[_e]=t}};jE(QE,{});a(ld,"collapseData");jx=Object.prototype.hasOwnProperty;a(Uo,"deepFreeze");a(zE,"hasChanges");Mo=Symbol.for("has-array-changes"),JE=class extends Array{static{a(this,"TrackedArray")}[Mo];constructor(t){super(t)}splice(...t){return this[Mo]=!0,super.splice(...t)}push(...t){return this[Mo]=!0,super.push(...t)}pop(){return this[Mo]=!0,super.pop()}unshift(...t){return this[Mo]=!0,super.unshift(...t)}shift(){return this[Mo]=!0,super.shift()}};JE.prototype.constructor=Array;XE=class{constructor(t){this.value=t}static{a(this,"Addition")}__op__="add";update(t){return(+t||0)+this.value}}});var Gp={};qe(Gp,{CONTEXT:()=>ye,ID_PROPERTY:()=>Me,IS_COLLECTION:()=>gn,RECORD_PROPERTY:()=>_e,Resource:()=>Ft,snake_case:()=>yie,transformForSelect:()=>eh});function yie(e){return e[0].toLowerCase()+e.slice(1).replace(/[a-z][A-Z][a-z]/g,t=>t[0]+"_"+t.slice(1))}function eG(e,t){if(Cl=!1,e==="")return null;if(e=e.slice(1),e.indexOf("/")===-1)return e===""?(Cl=!0,null):(e.startsWith("$")&&(e=parseInt(e,36)),t.coerceId(decodeURIComponent(e)));let r=e.split("/"),n=new HA;for(let s=0;s<r.length;s++){let i=r[s];if(!i&&s===r.length-1){Cl=!0;break}n[s]=t.coerceId(decodeURIComponent(i))}return n}function Xr(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[Me]??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 je(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 ZE(o.user);return typeof l?.then=="function"?l.then(S=>e(E,u,o,S)):e(E,u,o,l)});if(!h)throw new ZE(o.user)}return typeof l?.then=="function"?l.then(h=>e(E,u,o,h)):e(E,u,o,l)}a(f,"authorizeActionOnResource")}}function jr(e,t){let r=new nG.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 BA(e,t,r){let n=e[_e];if(n){let s=e[Ct];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 eh(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):BA(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(BA(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(BA(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]=eh(c.select||c,l)}let _=o(c.name);return u(_)}else return o(c);else return c}}a(i,"handleProperty")}var tG,rG,nG,ye,Me,gn,_e,bie,Ft,ZE,Cl,HA,Nn=ge(()=>{tG=require("crypto");gc();rG=require("../index"),nG=v(ne());_d();no();Qf();ye=Symbol.for("context"),Me=Symbol.for("primary-key"),gn=Symbol("is-collection"),_e=Symbol("stored-record"),bie={json:"application/json",cbor:"application/cbor",msgpack:"application/x-msgpack",csv:"text/csv"},Ft=class{static{a(this,"Resource")}static transactions;constructor(t,r){this[Me]=t;let n=r?.[ye];this[ye]=n!==void 0?n:r||null}static get=Xr(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 _=eh(u,t.constructor);return typeof c?.map=="function"?c.map(_):_(c)}return c}},{type:"read",letItLinger:!0,ensureLoaded:!0,async:!0});static put=Xr(function(t,r,n,s){if(Array.isArray(s)&&t[gn]){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):jr(t,"put")},{hasContent:!0,type:"update"});static patch=Xr(function(t,r,n,s){return t.patch?t.patch(s,r):jr(t,"patch")},{hasContent:!0,type:"update"});static delete=Xr(function(t,r,n,s){return t.delete?t.delete(r):jr(t,"delete")},{hasContent:!1,type:"delete"});static getNewId(){return(0,tG.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),je(n,()=>{let i=new this(s,n),o=i.update?i.update(r,!0):jr(i,"update");return n.newLocation=s,n.createdResource=!0,o?.then?o.then(()=>s):s})}static invalidate=Xr(function(t,r,n,s){return t.invalidate?t.invalidate(r):jr(t,"delete")},{hasContent:!1,type:"update"});static post=Xr(function(t,r,n,s){return t[Me]!=null&&t.update?.(),t.post(s,r)},{hasContent:!0,type:"create"});static connect=Xr(function(t,r,n,s){return t.connect?t.connect(s,r):jr(t,"connect")},{hasContent:!0,type:"read"});static subscribe=Xr(function(t,r,n,s){return t.subscribe?t.subscribe(r):jr(t,"subscribe")},{type:"read"});static publish=Xr(function(t,r,n,s){return t[Me]!=null&&t.update?.(),t.publish?t.publish(s,r):jr(t,"publish")},{hasContent:!0,type:"create"});static search=Xr(function(t,r,n,s){let i=t.search?t.search(r):jr(t,"search"),o=n.select;if(o&&n.hasOwnProperty("select")&&i!=null&&!i.selectApplied){let c=eh(o,t.constructor);return i.map(c)}return i},{type:"read"});static query=Xr(function(t,r,n,s){return t.search?t.search(s,r):jr(t,"search")},{hasContent:!0,type:"read"});static copy=Xr(function(t,r,n,s){return t.copy?t.copy(s,r):jr(t,"copy")},{type:"create"});static move=Xr(function(t,r,n,s){return t.move?t.move(s,r):jr(t,"move")},{type:"delete"});post(t){if(this[gn])return this.constructor.create(this[Me],t,this[ye]);jr(this,"post")}static isCollection(t){return t?.[gn]}static coerceId(t){return t}static parseQuery(t){return Wf(t)}static parsePath(t,r,n){let s=t.indexOf(".");if(s>-1){let o=t.slice(s+1);t=t.slice(0,s);let c=r?.headers&&bie[o];if(c)r.headers.set("accept",c);else if(n)n.property=o;else return{query:{property:o},id:eG(t,this),isCollection:Cl}}let i=eG(t,this);return Cl?{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(_=>_[Me]===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[Me],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[gn]=!0),s}subscribe(t){return new yn}connect(t){return t?.subscribe!==!1?this.subscribe?.(t):new yn}allowRead(t){return t?.role.permission.super_user}allowUpdate(t){return t?.role.permission.super_user}allowCreate(t){return t?.role.permission.super_user}allowDelete(t){return t?.role.permission.super_user}getId(){return this[Me]}getContext(){return this[ye]}};Ft.prototype[ye]=null;(0,rG._assignPackageExport)("Resource",Ft);a(yie,"snake_case");ZE=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(eG,"pathToId");HA=class extends Array{static{a(this,"MulitPartId")}toString(){return this.join("/")}};a(Xr,"transactional");a(jr,"missingMethod");a(BA,"selectFromObject");a(eh,"transformForSelect")});function iG(e,t,r,n){let s=e.primaryStore.env.path,i=e.primaryStore.tableId;Za||((0,th.onMessageByType)(sG,l=>{oG(l.path)}),Za=Object.create(null));let o=Za[s]||(Za[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=ba(t);let u=new GA(r);u.startTime=n;let _=c.get(t);return _?_.push(u):(c.set(t,_=[u]),_.tables=c,_.key=t),u.subscriptions=_,u}function oG(e,t){if(!Za)return;let r=Za[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=Mt(i),c=r[o.tableId];if(!c)continue;let u=o.recordId,_,l=ba(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,xA.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,xA.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 aG(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,th.broadcast)({type:sG,path:s}),oG(s,!0)})}}var xA,th,sG,Za,xSe,GA,cG=ge(()=>{xA=v($()),th=v(Ke());gc();Ku();ei();sG="transaction",xSe=Buffer.alloc(4096);a(iG,"addSubscription");GA=class extends yn{static{a(this,"Subscription")}listener;subscriptions;startTime;constructor(t){super(),this.listener=t,this.on("close",()=>this.end())}end(){if(this.subscriptions){if(this.subscriptions.splice(this.subscriptions.indexOf(this),1),this.subscriptions.length===0){let t=this.subscriptions.tables,r=this.subscriptions.key;if(t.delete(r),t.size===0){let n=t.envs,s=t.dbi;delete n[s]}}this.subscriptions=null}}toJSON(){return{name:"subscription"}}};a(oG,"notifyFromTransactionData");a(aG,"listenToCommits")});var TR={};qe(TR,{coerceType:()=>rh,makeTable:()=>ih,setServerUtilities:()=>Pie,updateResource:()=>nh});function ih(e){let{primaryKey:t,indices:r,tableId:n,tableName:s,primaryStore:i,databasePath:o,databaseName:c,auditStore:u,schemaDefined:_,dbisDB:l,sealed:d}=e,{expirationMS:f,evictionMS:E,audit:h,trackDeletes:p}=e,{attributes:S}=e;S||(S=[]),aG(i,u);let T=mm(i,n,u),A=0,R,M,x={},P=Promise.resolve(),k,B,X;for(let K of S)(K.assignCreatedTime||K.name==="__createdtime__")&&(k=K),(K.assignUpdatedTime||K.name==="__updatedtime__")&&(B=K),K.expiresAt&&(X=K),K.isPrimaryKey&&(x=K);let z,J=[],me=[],ce=1,de=2,Le={},Be={},Lt=864e5,Wl,Ql,Qs,oO=!1,Ah,Oh,dq=i.getRange({start:!1,end:!1}).constructor,fq=10,Eq=6;h&&uO();class ze extends Ft{static name=s;static primaryStore=i;static auditStore=u;static primaryKey=t;static tableName=s;static indices=r;static audit=h;static databasePath=o;static databaseName=c;static attributes=S;static expirationTimer;static createdTimeProperty=k;static updatedTimeProperty=B;static propertyResolvers;static sources=[];static get expirationMS(){return f}static dbisDB=l;static schemaDefined=_;static sourcedFrom(m,O){O&&(this.sourceOptions=O,(O.expiration||O.eviction||O.scanInterval)&&this.setTTLExpiration(O)),O?.intermediateSource?(m.intermediateSource=!0,this.sources.unshift(m)):this.sources.push(m),M=m.get&&(!m.get.reliesOnPrototype||m.prototype.get);let I=a(D=>{let N=this.sources.slice(0,-1);if(N=N.filter(U=>U[D]&&(!U[D].reliesOnPrototype||U.prototype[D])),N.length>0)if(N.length===1){let U=N[0];return(F,C,H)=>{if(F?.source!==U)return U[D](C,H,F)}}else return(U,F,C)=>{let H=[];for(let G of N){if(U?.source===G)break;H.push(G[D](F,C,U))}return Promise.all(H)}},"getApplyToIntermediateSource"),y=this.sources[this.sources.length-1],b=a(D=>{if(y[D]&&(!y[D].reliesOnPrototype||y.prototype[D]))return(N,U,F)=>{if(!N?.source)return y[D](U,F,N)}},"getApplyToCanonicalSource");return Le={put:b("put"),patch:b("patch"),delete:b("delete"),publish:b("publish")},Be={put:I("put"),patch:I("patch"),delete:I("delete"),publish:I("publish"),invalidate:I("invalidate")},(async()=>{let D=!1,N=a(async(U,F)=>{let C=U.value,H=U.table?st[c][U.table]:ze;if(c===$n.SYSTEM_SCHEMA_NAME&&(U.table===$n.SYSTEM_TABLE_NAMES.ROLE_TABLE_NAME||U.table===$n.SYSTEM_TABLE_NAMES.USER_TABLE_NAME)&&(D=!0),U.id===void 0&&(U.id=C[H.primaryKey],U.id===void 0))throw new Error("Replication message without an id "+JSON.stringify(U));U.source=m;let G=await H.getResource(U.id,F,ec);switch(U.type){case"put":return G._writeUpdate(C,!0,ec);case"patch":return G._writeUpdate(C,!1,ec);case"delete":return G._writeDelete(ec);case"publish":return G._writePublish(C,ec);case"invalidate":return G.invalidate(ec);default:tt.error("Unknown operation",U.type,U.id)}},"writeUpdate");try{let U=m.subscribe;U&&p==null&&(p=!0);let F=m.subscribeOnThisThread?m.subscribeOnThisThread((0,vo.getWorkerIndex)()):(0,vo.getWorkerIndex)()===0,C=U&&F&&await m.subscribe?.({crossThreads:!1,inTransactionUpdates:!0,supportsTransactions:!0,omitCurrent:!0});if(C){let H;for await(let G of C)try{if(!(G.type==="transaction"?G.writes[0]:G)){tt.error("Bad subscription event",G);continue}if(G.source=m,H)if(G.beginTxn)H.resolve();else{N(G,H);continue}if(G.type==="end_txn")continue;let pe=je(G,()=>{if(G.type==="transaction"){let te=[];for(let Pe of G.writes)try{te.push(N(Pe,G))}catch(ae){throw ae.message+=" writing "+JSON.stringify(Pe)+" of event "+JSON.stringify(G),ae}return Promise.all(te)}else if(G.type==="define_schema"){let te=this.attributes.slice(0),Pe;for(let ae of G.attributes)te.find(Ge=>Ge.name===ae.name)||(te.push(ae),Pe=!0);Pe&&(lt({table:s,database:c,attributes:te,origin:"cluster"}),Bl.signalSchemaChange(new Hl.SchemaEventMsg(process.pid,$n.OPERATIONS_ENUM.CREATE_TABLE,c,s)))}else return G.beginTxn?(H=G,N(G,G),new Promise(te=>{H.resolve=te})):N(G,G)});D&&(await pe,Bl.signalUserChange(new Hl.UserEventMsg(process.pid))),G.onCommit&&(pe?.then?pe.then(G.onCommit):G.onCommit())}catch(se){tt.error("error in subscription handler",se)}}}catch(U){tt.error(U)}})(),this}static getResource(m,O,I){let y=super.getResource(m,O,I);if(m!=null){ic(m);try{if(y.hasOwnProperty(_e))return y;if(typeof m=="object"&&m&&!Array.isArray(m))throw new Error(`Invalid id ${JSON.stringify(m)}`);let b=!I?.async||i.cache?.get(m),D=On(O),N=D.getReadTxn();if(N?.isDone)throw new Error("You can not read from a transaction that has already been committed/aborted");return bh(m,O,{transaction:N},b,U=>{if(U?nh(y,U):y[_e]=null,O.onlyIfCached&&O.noCacheStore){if(!y.doesExist())throw new Rn.ServerError("Entry is not cached",504)}else if(I?.ensureLoaded){let F=yh(m,U,O,y);if(F)return D?.disregardReadTxn(),y[qA]=!0,kA(F,C=>(nh(y,C),y))}return y})}catch(b){throw b.message.includes("Unable to serialize object")&&(b.message+=": "+JSON.stringify(m)),b}}return y}ensureLoaded(){let m=yh(this[Me],this[Zr],this[ye]);if(m)return this[qA]=!0,kA(m,O=>{this[Zr]=O,this[_e]=O.value,this[Pl]=O.version})}static setTTLExpiration(m){if(typeof m=="number")f=m*1e3,E||(E=0);else if(m&&typeof m=="object")f=m.expiration*1e3,E=(m.eviction||0)*1e3,Lt=m.scanInterval*1e3;else throw new Error("Invalid expiration value type");if(f<0)throw new Error("Expiration can not be negative");Lt=Lt||(f+E)/4,Ih()}static enableAuditing(m=!0){h=m,m&&uO(),ze.audit=m}static coerceId(m){return m===""?null:rh(m,x)}static async dropTable(){if(delete st[c][s],c===o){for(let m of S)l.remove(ze.tableName+"/"+m.name),r[m.name]?.drop();l.remove(ze.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));Bl.signalSchemaChange(new Hl.SchemaEventMsg(process.pid,$n.OPERATIONS_ENUM.DROP_TABLE,c,s))}get(m){if(typeof m=="string")return this.getProperty(m);if(this[gn])return this.search(m);if(this[Me]===null){if(m?.conditions)return this.search(m);let O=ze.getRecordCount();return{recordCount:O.recordCount,estimatedRecordRange:O.estimatedRange,records:"./",name:s,database:c,attributes:S}}if(m?.property)return this.getProperty(m.property);if(this.doesExist()||m?.ensureLoaded===!1||this[ye]?.returnNonexistent)return this}allowRead(m,O){let I=Jl(m);if(I?.read){if(I.isSuperUser)return!0;let y=I.attribute_permissions,b=O?.select;if(y?.length>0||oO&&b){if(O||(O={}),b){let D=y?.length>0&&FA(y,"read");O.select=b.map(N=>{let U=N.name||N;if(!D||D[U]){let F=Qs[U]?.definition?.tableClass;if(F){if(N.name||(N={name:N}),!F.prototype.allowRead.call(null,m,N))return!1;if(!N.select)return N.name}return N}}).filter(Boolean)}else O.select=y.filter(D=>D.read&&!Qs[D.attribute_name]).map(D=>D.attribute_name);return O}else return!0}}allowUpdate(m,O){let I=Jl(m);if(I?.update){let y=I.attribute_permissions;if(y?.length>0){let b=FA(y,"update");for(let D in O)if(!b[D])return!1;for(let D of y){let N=D.attribute_name;!D.update&&!(N in O)&&(O[N]=this.getProperty(N))}}return!0}}allowCreate(m,O){if(this[gn]){let I=Jl(m);if(I?.insert){let y=I.attribute_permissions;if(y?.length>0){let b=FA(y,"insert");for(let D in O)if(!b[D])return!1}else return!0}}else return this.allowUpdate(m,{})}allowDelete(m){return Jl(m)?.delete}update(m,O){if(!On(this[ye]))throw new Error("Can not update a table resource outside of a transaction");if(m===!1)return this;let y;return typeof m=="object"&&m&&(O?(Object.isFrozen(m)&&(m=Object.assign({},m)),this[_e]={},this[Ct]=m):(y=this[Ct],y&&(m=Object.assign(y,m)),this[Ct]=y=m)),this._writeUpdate(this[Ct],O),this}addTo(m,O){if(typeof O=="number")this[Dl]===lG?this.set(m,(+this.getProperty(m)||0)+O):(this[Dl]||this.update(),this.set(m,new XE(O)));else throw new Error("Can not add a non-numeric value")}subtractFrom(m,O){if(typeof O=="number")return this.addTo(m,-O);throw new Error("Can not subtract a non-numeric value")}invalidate(m){let O=this[ye],I=this[Me];ic(I),On(this[ye]).addWrite({key:I,store:i,invalidated:!0,entry:this[Zr],nodeName:this[ye]?.nodeName,before:Le.invalidate?.bind(this,O,I),beforeIntermediate:Be.invalidate?.bind(this,O,I),commit:(b,D)=>{if(D?.version>b)return;let N=null;for(let U in r)N||(N={}),N[U]=this.getProperty(U);T(I,N,this[Zr],b,Ll,h,this[ye],0,"invalidate")}})}static evict(m,O,I){let y=this.Source,b;if(!((M||h)&&(!O||(b=i.getEntry(m),!b||!O)||b.version!==I))){if(M){if(i.hasLock(m,b.version))return;let D;for(let N in r)D||(D={}),D[N]=O[N];if(D)return T(m,D,b,I,Ml,null,null,0,null,!0)}return i.ifVersion(m,I,()=>{zl(m,O,null)}),h?T(m,null,b,I,Ml,null,null,0,null,!0):i.remove(m,I)}}lock(){throw new Error("Not yet implemented")}static operation(m,O){return m.table||=s,m.schema||=c,mG.operation(m,O)}put(m){this.update(m,!0)}patch(m){this.update(m,!1)}_writeUpdate(m,O,I){let y=this[ye],b=On(y),D=this[Me];ic(D);let N=this[Zr];this[Dl]=O?lG:Lie;let U={key:D,store:i,entry:N,nodeName:y?.nodeName,validate:F=>{m||(m=this[Ct]),O||m&&zE(m)?y?.source||(b.checkOverloaded(),this.validate(m,!O),B&&(m[B.name]=B.type==="Date"?new Date(F):B.type==="String"?new Date(F).toISOString():F),O&&(t&&m[t]!==D&&(m[t]=D),k&&(N?.value?m[k.name]=N?.value[k.name]:m[k.name]=k.type==="Date"?new Date(F):k.type==="String"?new Date(F).toISOString():F),m=Uo(m))):b.removeWrite(U)},before:O?Le.put?()=>Le.put(y,D,m):null:Le.patch?()=>Le.patch(y,D,m):Le.put?()=>Le.put(y,D,Uo(this)):null,beforeIntermediate:O?Be.put?()=>Be.put(y,D,m):null:Be.patch?()=>Be.patch(y,D,m):Be.put?()=>Be.put(y,D,Uo(this)):null,commit:(F,C,H)=>{if(H){if(y&&C?.version>(y.lastModified||0)&&(y.lastModified=C.version),this[Zr]=C,C?.value?.[_e])throw new Error("Can not assign a record to a record, check for circular references");O||(this[_e]=C?.value??null)}this[Ct]=m,this[Pl]=F;let G=C?.value,se=m;if(this[Dl]=0,C?.version>=F)if(h){let ae=C.localTime,Ge=C.version;for(;se&&(ae>F||Ge>=F&&ae>0);){let re=u.get(ae);if(!re)break;let j=Mt(re);if(Ge=j.version,Ge>F){if(j.type==="patch"){let Oe=j.getValue(i);se=WE(se,Oe)}else if(j.type==="put"||j.type==="delete")return}else if(Ge===F)return;ae=j.previousLocalTime}}else{if(O)return;se=WE(se,G)}let pe;if(O?pe=se:(this[_e]=G,pe=O?se:Uo(this,se)),this[_e]=pe,pe?.[_e])throw new Error("Can not assign a record to a record, check for circular references");let te;O||(te=m),zl(D,G,pe);let Pe=O?"put":"patch";T(D,pe,C,F,0,h,y,y.expiresAt||(f?f+Date.now():0),Pe,!1,te)}};b.addWrite(U)}async delete(m){if(typeof m=="string")return this.deleteProperty(m);if(this[gn]){for await(let O of this.search(m))(await ze.getResource(O[t],this.getContext(),{ensureLoaded:!1}))._writeDelete(m);return}return this[_e]?this._writeDelete(m):!1}_writeDelete(m){let O=On(this[ye]),I=this[Me];ic(I);let y=this[ye];return O.addWrite({key:I,store:i,resource:this,nodeName:y?.nodeName,before:Le.delete?.bind(this,y,I),beforeIntermediate:Be.delete?.bind(this,y,I),commit:(b,D,N)=>{let U=D?.value;N&&(y&&D?.version>(y.lastModified||0)&&(y.lastModified=D.version),nh(this,D)),!(D?.version>b)&&(zl(this[Me],U),tt.trace("Write delete entry",I,b),h||p?(T(I,null,this[Zr],b,0,h,this[ye],0,"delete"),h||Ih()):i.remove(this[Me]))}}),!0}search(m){let O=this[ye],I=On(O);if(!m)throw new Error("No query provided");let y=m.conditions;y?y.length===void 0&&(y=y[Symbol.iterator]?Array.from(y):[y]):y=Array.isArray(m)?m:m[Symbol.iterator]?Array.from(m):[],this[Me]&&(y=[{attribute:null,comparator:"prefix",value:this[Me]}].concat(y));let b,D={};function N(j,Oe){let He;switch(Oe){case"and":case void 0:if(j.length<1)throw new Error('An "and" operator requires at least one condition');He=!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 "+Oe)}let Yn=He&&{},zs;for(let Ye of j){if(Ye.conditions){Ye.conditions=N(Ye.conditions,Ye.operator);continue}let Gt=Ye[0]??Ye.attribute,rn=Gt==null?x:Gs(S,Gt);if(rn){if(He){let Kn=Gn(Gt),qt=Yn[Kn];qt?(qt.push(Ye),zs=!0):Yn[Kn]=[Ye]}(rn.type||Yg[Ye.comparator])&&(Ye[1]===void 0?Ye.value=F(Ye.value,rn):Ye[1]=F(Ye[1],rn))}else if(Gt!=null)throw(0,Rn.handleHDBError)(new Error,`${Gt} is not a defined attribute`,404)}if(m.enforceExecutionOrder)return j;if(zs)for(let Ye in Yn){let Gt=Yn[Ye],rn=Gt.length;if(rn>1)for(let Kn=0;Kn<rn;Kn++){let qt=Gt[Kn];if(qt.comparator==="ge"||qt.comparator==="greater_than_equal")for(let Js=0;Js<rn;Js++){let Go=Gt[Js];(Go.comparator==="le"||Go.comparator==="less_than_equal")&&(qt.comparator="between",qt.value=[qt.value,Go.value],j.splice(j.indexOf(Go),1))}if(qt.comparator==="equals"||!qt.comparator){for(let Js=0;Js<rn;Js++)if(Js!==Kn){let Go=Gt[Js];j.splice(j.indexOf(Go),1)}break}}}return j}a(N,"prepareConditions");function U(j,Oe){if(m.enforceExecutionOrder)return j;for(let He of j)He.conditions&&(He.conditions=U(He.conditions,He.operator));return j.length>1&&Oe!=="or"?(0,hG.sortBy)(j,Kf(ze)):j}a(U,"orderConditions");function F(j,Oe){return Array.isArray(j)?j.map(He=>rh(He,Oe)):rh(j,Oe)}a(F,"coerceTypedValues");let C=m.operator;(y.length>0||C)&&(y=N(y,C));let H=typeof m.sort=="object"&&m.sort,G;if(H&&C!=="or"){let j=H.attribute;if(b=y.find(Oe=>Gn(Oe.attribute)===Gn(j)),!b){if(!Gs(S,j))throw(0,Rn.handleHDBError)(new Error,`${Array.isArray(j)?j.join("."):j} is not a defined attribute`,404);b={attribute:j,comparator:"sort"},y.push(b)}b.descending=!!H.descending}y=U(y,C),H&&(y[0]===b?H.next&&(G={dbOrderedAttribute:H.attribute,attribute:H.next.attribute,descending:H.next.descending,next:H.next.next}):(b&&y.splice(y.indexOf(b),1),G=H));let se=m.select;if(y.length===0&&(y=[{attribute:t,comparator:"greater_than",value:!0}]),m.explain)return{conditions:y,operator:C,postOrdering:G,selectApplied:!!se};let pe=I.useReadTxn(),te=Kg(y,C,ze,pe,m,O,(j,Oe)=>aO(j,se,O,pe,Oe),D),Pe=m.ensureLoaded!==!1;G||(te=re(te));let ae=ze.transformEntryForSelect(se,O,pe,D,Pe,!0),Ge=ze.transformToOrderedSelect(te,se,G,pe,O,ae);function re(j){return m.offset||m.limit!==void 0?j.slice(m.offset,m.limit!==void 0?(m.offset||0)+m.limit:void 0):j}return a(re,"applyOffset"),G&&(Ge=re(Ge)),Ge.onDone=()=>{Ge.onDone=null,I.doneReadTxn()},Ge.selectApplied=!0,Ge.getColumns=()=>{if(se){let j=[];for(let Oe of se)Oe==="*"?j.push(...S.map(He=>He.name)):j.push(Oe.name||Oe);return j}return S.map(j=>j.name)},Ge}static transformToOrderedSelect(m,O,I,y,b,D){let N=new dq;if(I){m=aO(m,O,y,b,null);let U;N.iterate=function(){let C,H=m[Symbol.asyncIterator]?m[Symbol.asyncIterator]():m[Symbol.iterator](),G,se=I.dbOrderedAttribute,pe,te,Pe=!0;function ae(re){let j=re.next&&ae(re.next),Oe=re.descending;return(He,Yn)=>{let zs=Nh(He,re.attribute,y),Ye=Nh(Yn,re.attribute,y),Gt=Oe?(0,Bo.compareKeys)(Ye,zs):(0,Bo.compareKeys)(zs,Ye);return Gt===0?j?.(He,Yn)||0:Gt}}a(ae,"createComparator");let Ge=ae(I);return{async next(){let re;if(C)if(re=C.next(),re.done){if(G)return N.onDone&&N.onDone(),re}else return{value:await D.call(this,re.value)};U=[],pe&&U.push(pe);do if(re=await H.next(),re.done){if(G=!0,U.length)break;return N.onDone&&N.onDone(),re}else{let j=re.value;if(j?.then&&(j=await j),se){let Oe=Nh(j,se,y);if(Pe)Pe=!1,te=Oe;else if(Oe!==te){te=Oe,pe=j;break}}U.push(j)}while(!0);return I.isGrouped,U.sort(Ge),C=U[Symbol.iterator](),re=C.next(),re.done?(N.onDone&&N.onDone(),re):{value:await D.call(this,re.value)}},return(){N.onDone&&N.onDone(),H.return()},throw(){N.onDone&&N.onDone(),H.throw()}}};let F=a(C=>{if(typeof O=="object"&&Array.isArray(C.attribute))for(let H=0;H<O.length;H++){let G=O[H],se;if(G.name===C.attribute[0]){for(se=G.sort||(G.sort={});se.next;)se=se.next;se.attribute=C.attribute.slice(1),se.descending=C.descending}else G===C.attribute[0]&&(O[H]=se={name:G,sort:{attribute:C.attribute.slice(1),descending:C.descending}})}C.next&&F(C.next)},"applySortingOnSelect");F(I)}else N.iterate=(m[Symbol.asyncIterator]||m[Symbol.iterator]).bind(m),N=N.map(D);return N}static transformEntryForSelect(m,O,I,y,b,D){if(m&&(m===t||m?.length===1&&m[0]===t)){let C=a(H=>H?.key??H,"transform");return m===t?C:m.asArray?H=>[C(H)]:H=>({[t]:C(H)})}let N;b&&M&&!m?.every(C=>{let H;return typeof C=="object"?H=C.name:H=C,r[H]||H===t})&&(N=!0);let U,F=a(function(C){let H;if(C!=null){if(Ah=C,H=C.value||C.deref?.(),!H&&(C.key===void 0||C.deref)){if(C=bh(C.key??C,O,{transaction:I,lazy:m?.length<4},this.isSync,G=>G),C?.then)return C.then(F.bind(this));H=C?.value}if(N&&(C.metadataFlags&(Ll|Ml)||C.expiresAt&&C.expiresAt<Date.now())){let G=yh(C.key??C,C,O);if(G?.then)return G.then(F)}}if(H==null)return D?Po.SKIP:H;if(m&&!(m[0]==="*"&&m.length===1)){let G,se=a((te,Pe)=>{let ae;typeof te=="object"?ae=te.name:ae=te;let Ge=Qs?.[ae],re;if(Ge){let j=y?.[ae];if(j)if(j.hasMappings){let He=Ge.from?H[Ge.from]:Gn(C.key);re=j.get(He),re||(re=[])}else re=j.fromRecord?.(H);else re=Ge(H,O,C);let Oe=a(He=>{if(He&&typeof He=="object"){let Yn=Ge.definition?.tableClass||ze;U||(U={});let zs=U[ae]||(U[ae]=Yn.transformEntryForSelect(ae===te?null:te.select||(Array.isArray(te)?te:null),O,I,j,b));if(Array.isArray(He)){let Ye=[],Gt=Yn.transformToOrderedSelect(He,te.select,typeof te.sort=="object"&&te.sort,O,I,zs)[this.isSync?Symbol.iterator:Symbol.asyncIterator](),rn=a(qt=>{for(;!qt.done;){if(qt?.then)return qt.then(rn);Ye.push(qt.value),qt=Gt.next()}Pe(Ye,ae)},"nextValue"),Kn=rn(Gt.next());Kn&&(G||(G=[]),G.push(Kn));return}else if(He=zs.call(this,He),He?.then){G||(G=[]),G.push(He.then(Ye=>Pe(Ye,ae)));return}}Pe(He,ae)},"handleResolvedValue");re?.then?(G||(G=[]),G.push(re.then(Oe))):Oe(re);return}else re=H[ae],re&&typeof re=="object"&&ae!==te&&(re=ze.transformEntryForSelect(te.select||te,O,I,null)({value:re}));Pe(re,ae)},"selectAttribute"),pe;if(typeof m=="string")se(m,te=>{pe=te});else if(Array.isArray(m))if(m.asArray)pe=[],m.forEach((te,Pe)=>{te==="*"?m[Pe]=H:se(te,ae=>pe[Pe]=ae)});else{pe={};let te=m.forceNulls;for(let Pe of m)if(Pe==="*")for(let ae in H)pe[ae]=H[ae];else se(Pe,(ae,Ge)=>{ae===void 0&&te&&(ae=null),pe[Ge]=ae})}else throw new Rn.ClientError("Invalid select"+m);return G?Promise.all(G).then(()=>pe):pe}return H},"transform");return F}async subscribe(m){if(!u)throw new Error("Can not subscribe to a table without an audit log");h||lt({table:s,database:c,schemaDefined:_,attributes:S,audit:!0}),m||(m={});let O=!m.rawEvents,I=iG(ze,this[Me]??null,function(N,U,F,C){try{let H=U.getValue?.(i,O);if(!H&&U.type==="patch"&&O){let G=i.getEntry(N);G?.version===U.version?H=G.value:H=U.getValue?.(i,!0,F),U.type="put"}this.send({id:N,timestamp:F,value:H,version:U.version,type:U.type,beginTxn:C})}catch(H){tt.error(H)}},m.startTime||0,this[gn]);this[gn]&&(I.includeDescendants=!0,m.onlyChildren&&(I.onlyChildren=!0)),m.crossThreads===!1&&(I.crossThreads=!1),m.supportsTransactions&&(I.supportsTransactions=!0);let y=this[Me],b=m.previousCount;b>1e3&&(b=1e3);let D=m.startTime;if(this[gn]){if(D){if(b)throw new Rn.ClientError("startTime and previousCount can not be combined for a table level subscription");for(let{key:N,value:U}of u.getRange({start:D,exclusiveStart:!0})){let F=Mt(U);if(F.tableId!==n)continue;let C=F.recordId;if(y==null||fG(y,C)){let H=F.getValue(i,O,N);I.send({id:C,timestamp:N,value:H,version:F.version,type:F.type})}I.startTime=N}}else if(b){let N=[];for(let{key:U,value:F}of u.getRange({start:"z",end:!1,reverse:!0}))try{let C=Mt(F);if(C.tableId!==n)continue;let H=C.recordId;if(y==null||fG(y,H)){let G=C.getValue(i,O,U);if(N.push({id:H,timestamp:U,value:G,version:C.version,type:C.type}),--b<=0)break}}catch(C){tt.error("Error getting history entry",U,C)}for(let U=N.length;U>0;)I.send(N[--U]);N[0]&&(I.startTime=N[0].timestamp)}else if(!m.omitCurrent)for(let{key:N,value:U,version:F,localTime:C}of i.getRange({start:y??!1,end:y==null?void 0:[y,Bo.MAXIMUM_KEY],versions:!0}))U&&I.send({id:N,timestamp:C,value:U,version:F,type:"put"})}else{b&&!D&&(D=0);let N=this[Zr]?.localTime;if(N===hm&&(i.cache?.delete(y),this[Zr]=i.getEntry(y),tt.trace("re-retrieved record",N,this[Zr]?.localTime),N=this[Zr]?.localTime),tt.trace("Subscription from",D,"from",y,N),D<N){let U=[],F=N;do{let C=u.get(F);if(C){m.omitCurrent=!0;let H=Mt(C),G=H.getValue(i,O,F);O&&(H.type="put"),U.push({id:y,value:G,timestamp:F,...H}),F=H.previousLocalTime}else break;b&&b--}while(F>D&&b!==0);for(let C=U.length;C>0;)I.send(U[--C]);I.startTime=N}!m.omitCurrent&&this.doesExist()&&I.send({id:y,timestamp:N,value:this,version:this[Pl],type:"put"})}return m.listener&&I.on("data",m.listener),I}doesExist(){return!!(this[_e]||this[Dl])}publish(m,O){this._writePublish(m,O)}_writePublish(m,O){let I=On(this[ye]),y=this[Me]||null;ic(y);let b=this[ye];I.addWrite({key:y,store:i,entry:this[Zr],nodeName:b?.nodeName,validate:()=>{b?.source||(I.checkOverloaded(),this.validate(m))},before:Le.publish?.bind(this,b,y,m),beforeIntermediate:Be.publish?.bind(this,b,y,m),commit:(D,N,U)=>{N===void 0&&p&&!h&&Ih(),T(y,N?.value??null,N,N?.version||D,0,!0,b,N?.expiresAt,"message",!1,m)}})}validate(m,O){let I,y=a((b,D,N)=>{if(D.type&&b!=null)if(O&&b.__op__&&(b=b.value),D.properties){typeof b!="object"&&(I||(I=[])).push(`Value ${Vn(b)} in property ${N} must be an object${D.type?" ("+D.type+")":""}`);let U=D.properties;for(let F=0,C=U.length;F<C;F++){let H=U[F],G=y(b[H.name],H,N+"."+H.name);G&&(b[H.name]=G)}if(D.sealed&&b!=null&&typeof b=="object")for(let F in b)U.find(C=>C.name===F)||(I||(I=[])).push(`Property ${F} is not allowed within object in property ${N}`)}else switch(D.type){case"Int":(typeof b!="number"||b>>0!==b)&&(I||(I=[])).push(`Value ${Vn(b)} in property ${N} must be an integer (from -2147483648 to 2147483647)`);break;case"Long":(typeof b!="number"||!(Math.floor(b)===b&&Math.abs(b)<=9007199254740992))&&(I||(I=[])).push(`Value ${Vn(b)} in property ${N} must be an integer (from -9007199254740992 to 9007199254740992)`);break;case"Float":typeof b!="number"&&(I||(I=[])).push(`Value ${Vn(b)} in property ${N} must be a number`);break;case"ID":typeof b=="string"||b?.length>0&&b.every?.(U=>typeof U=="string")||(I||(I=[])).push(`Value ${Vn(b)} in property ${N} must be a string, or an array of strings`);break;case"String":typeof b!="string"&&(I||(I=[])).push(`Value ${Vn(b)} in property ${N} must be a string`);break;case"Boolean":typeof b!="boolean"&&(I||(I=[])).push(`Value ${Vn(b)} in property ${N} must be a boolean`);break;case"Date":if(!(b instanceof Date)){if(typeof b=="string"||typeof b=="number")return new Date(b);(I||(I=[])).push(`Value ${Vn(b)} in property ${N} must be a Date`)}break;case"BigInt":if(typeof b!="bigint"){if(typeof b=="string"||typeof b=="number")return BigInt(b);(I||(I=[])).push(`Value ${Vn(b)} in property ${N} must be a bigint`)}break;case"Bytes":b instanceof Uint8Array||(I||(I=[])).push(`Value ${Vn(b)} in property ${N} must be a Buffer or Uint8Array`);break;case"array":if(Array.isArray(b)){if(D.elements)for(let U=0,F=b.length;U<F;U++){let C=b[U],H=y(C,D.elements,N+"[*]");H&&(b[U]=H)}}else(I||(I=[])).push(`Value ${Vn(b)} in property ${N} must be a Buffer or Uint8Array`);break}D.nullable===!1&&b==null&&(I||(I=[])).push(`Property ${N} is required (and not does not allow null values)`)},"validateValue");for(let b=0,D=S.length;b<D;b++){let N=S[b];if(!N.relationship&&(!O||N.name in m)){let U=y(m[N.name],N,N.name);U&&(m[N.name]=U)}}if(d)for(let b in m)S.find(D=>D.name===b)||(I||(I=[])).push(`Property ${b} is not allowed`);if(I)throw new Rn.ClientError(I.join(". "))}getUpdatedTime(){return this[Pl]}wasLoadedFromSource(){return M?!!this[qA]:void 0}static async addAttributes(m){let O=S.slice(0);for(let I of m){if(!I.name)throw new Rn.ClientError("Attribute name is required");if(I.name.match(/[`/]/))throw new Rn.ClientError("Attribute names cannot include backticks or forward slashes");O.push(I)}return lt({table:s,database:c,schemaDefined:_,attributes:O}),ze.indexingOperation}static async removeAttributes(m){let O=S.filter(I=>!m.includes(I.name));return lt({table:s,database:c,schemaDefined:_,attributes:O}),ze.indexingOperation}static getRecordCount(m){let O=i.getStats().entryCount,I=5e3,y=1e3,b;O>I&&!m?.exactCount&&(b=y);let D=0;for(let{value:N}of i.getRange({start:!0,lazy:!0,limit:b}))N!=null&&D++;if(b){let N=D;D=0;for(let{value:Pe}of i.getRange({start:"\uFFFF",reverse:!0,lazy:!0,limit:b}))Pe!=null&&D++;let U=b*2,F=(D+N)/U,C=Math.pow((D-N+1)/b/2,2)+F*(1-F)/U,H=Math.max(Math.sqrt(C)*O,1),G=Math.round(F*O),se=Math.max(G-1.96*H,0),pe=Math.min(G+1.96*H,O),te=Math.pow(10,Math.round(Math.log10(H)));return te>G&&(te=te/10),D=Math.round(G/te)*te,{recordCount:D,estimatedRange:[Math.round(se),Math.round(pe)]}}return{recordCount:D}}static updatedAttributes(){Qs=this.propertyResolvers={$id:(m,O,I)=>({value:I.key}),$updatedtime:(m,O,I)=>I.version,$record:(m,O,I)=>I?{value:m}:m};for(let m of this.attributes){m.resolve=null;let O=m.relationship;if(O)if(m.indexed&&console.error("A relationship property can not be directly indexed, (but you may want to index the foreign key attribute)"),oO=!0,O.to)m.elements?.definition?(Qs[m.name]=m.resolve=(I,y,b)=>{let D=I[O.from?O.from:t],N=m.elements.definition.tableClass;return b?va({attribute:O.to,value:D},On(y).getReadTxn(),!1,N,!1).asArray:N.search([{attribute:O.to,value:D}],y).asArray},m.set=()=>{throw new Error("Setting a one-to-many relationship property is not supported")},m.resolve.definition=m.elements.definition,O.from&&(m.resolve.from=O.from)):console.error(`The one-to-many/many-to-many relationship property "${m.name}" in table "${s}" must have an array type referencing a table as the elements`);else if(O.from){let I=m.definition||m.elements?.definition;I?(Qs[m.name]=m.resolve=(y,b,D)=>{let N=y[O.from];if(N!==void 0){if(m.elements){let U,F=N.map(C=>{let H=D?I.tableClass.primaryStore.getEntry(C,{transaction:On(b).getReadTxn()}):I.tableClass.get(C,b);return H?.then&&(U=!0),H});return O.filterMissing?U?Promise.all(F).then(C=>C.filter(EG)):F.filter(EG):U?Promise.all(F):F}return D?I.tableClass.primaryStore.getEntry(N,{transaction:On(b).getReadTxn()}):I.tableClass.get(N,b)}},m.set=(y,b)=>{if(Array.isArray(b)){let D=b.map(N=>N[Me]||N[I.tableClass.primaryKey]);y[O.from]=D}else{let D=b[Me]||b[I.tableClass.primaryKey];y[O.from]=D}},m.resolve.definition=m.definition||m.elements?.definition,m.resolve.from=O.from):console.error(`The relationship property "${m.name}" in table "${s}" must be a type that references a table`)}else console.error(`The relationship directive on "${m.name}" in table "${s}" must use either "from" or "to" arguments`)}jE(this,this)}static async deleteHistory(m=0){let O;for(let{key:I,value:y}of u.getRange({start:0,end:m}))await Ul(),Mt(y).tableId===n&&(O=u.remove(I));await O}static async*getHistory(m=0,O=1/0){for(let{key:I,value:y}of u.getRange({start:m,end:O})){await Ul();let b=Mt(y);b.tableId===n&&(yield{id:b.recordId,localTime:I,version:b.version,type:b.type,value:b.getValue(i,!0,I),user:b.user})}}static async getHistoryOfRecord(m){let O=[];if(m==null)throw new Error("An id is required");let I=i.getEntry(m);if(!I)return O;let y=I.localTime;if(!y)throw new Error("The entry does not have a local audit time");let b=0;do{await Ul();let D=u.get(y);if(D){let N=Mt(D);O.push({id:N.recordId,localTime:y,version:N.version,type:N.type,value:N.getValue(i,!0,y),user:N.user}),y=N.previousLocalTime}else break}while(b<1e3&&y);return O.reverse()}static cleanup(){z?.remove()}}ze.updatedAttributes();let hq=ze.prototype;return hq[Die]=!0,f&&ze.setTTLExpiration(f/1e3),X&&mq(),ze;function zl(K,m,O){let I;for(let y in r){let b=r[y],D=b.isIndexing,N=O?.[y],U=m?.[y];if(N===U&&!D)continue;I=!0;let F=b.indexNulls,C=(0,vl.getIndexedValues)(N,F),H=(0,vl.getIndexedValues)(U,F);if(H?.length>0){let G=new Set(H);if(C=C?C.filter(se=>{if(G.has(se))G.delete(se);else return!0}):[],H=Array.from(G),(H.length>0||C.length>0)&&uG){let se=H.concat(C).map(pe=>({key:pe,value:K}));b.prefetch(se,dG)}for(let se=0,pe=H.length;se<pe;se++)b.remove(H[se],K)}else C?.length>0&&uG&&b.prefetch(C.map(G=>({key:G,value:K})),dG);if(C)for(let G=0,se=C.length;G<se;G++)b.put(C[G],K)}return I}a(zl,"updateIndices");function ic(K){switch(typeof K){case"number":return!0;case"string":if(K.length<659)return!0;if(K.length>_G)throw new Error("Primary key size is too large: "+K.length);break;case"object":if(K===null)return!0;break;case"bigint":if(K<2n**64n&&K>-(2n**64n))return!0;break;default:throw new Error("Invalid primary key type: "+typeof K)}if((0,Bo.writeKey)(K,Mie,0)>_G)throw new Error("Primary key size is too large: "+K.length);return!0}a(ic,"checkValidId");function bh(K,m,O,I,y){let b=a(()=>{if(m?.transaction?.stale&&(m.transaction.stale=!1),O.transaction?.isDone)return y(null,K);let D=i.getEntry(K,O);return D&&m&&(D?.version>(m.lastModified||0)&&(m.lastModified=D.version),D?.localTime&&!m.lastRefreshed&&(m.lastRefreshed=D.localTime)),y(D,K)},"whenPrefetched");return I?b():ce>0?(ce--,b()):new Promise((D,N)=>{ce===0?(ce--,i.prefetch([K],()=>{U(),F()})):(J.push(K),me.push(F),J.length>Eq&&(ce--,U()));function U(){if(J.length>0){let C=me;i.prefetch(J,()=>{ce===-1?U():ce++;for(let H of C)H()}),J=[],me=[],de>2&&de--}else ce=de,de<fq&&de++}a(U,"prefetch");function F(){try{D(b())}catch(C){N(C)}}a(F,"load")})}a(bh,"loadLocalRecord");function Jl(K){if(!K?.role)return;let m=K.role.permission;if(m.super_user)return Uie;let O=m[c],I,y=O?.tables;if(y)return y[s];if(c==="data"&&(I=m[s])&&!I.tables)return I}a(Jl,"getTablePermissions");function yh(K,m,O,I){if(M){let y;if(O.noCache?y=!0:(m?(!m.value||m.metadataFlags&(Ll|Ml)||m.expiresAt&&m.expiresAt<Date.now())&&(y=!0):y=!0,cn(!y,"cache-hit",s)),y){let b=cO(K,m,O).then(D=>(D?.value?.[_e]&&tt.error("Can not assign a record with a record property"),O&&(D?.version>(O.lastModified||0)&&(O.lastModified=D.version),O.lastRefreshed=Date.now()),D));if(O?.onlyIfCached||m?.value&&I?.allowStaleWhileRevalidate?.(m,K)){if(b.catch(D=>tt.warn(D)),O?.onlyIfCached&&!I.doesExist())throw new Rn.ServerError("Entry is not cached",504);return}else return b}}}a(yh,"ensureLoadedFromSource");function On(K){let m=K?.transaction;if(m){if(!m.lmdbDb)return m.lmdbDb=i,m;do{if(m.lmdbDb?.path===i.path)return m;let O=m.next;if(!O)return m=m.next=new ro,m.lmdbDb=i,m;m=O}while(!0)}else return new cd}a(On,"txnForContext");function Nh(K,m,O){if(!K)return;Ah=K;let I=K.value||K.deref?.()||(Ah=i.getEntry(K.key))?.value;if(typeof m=="object"){let b=Qs,D=I;for(let N=0,U=m.length;N<U;N++){let F=m[N],C=b?.[F];D=C&&D?C(D,O,!0)?.value:D?.[F],b=C?.definition?.tableClass?.propertyResolvers}return D}let y=Qs[m];return y?y(I,O):I[m]}a(Nh,"getAttributeValue");function aO(K,m,O,I,y){let b=y?.length,D={transaction:I,lazy:b>0||typeof m=="string"||m?.length<4,alwaysPrefetch:!0},N;function U(F,C){let H=F?.value;if(!H)return Po.SKIP;for(let G=0;G<b;G++)if(!N?.includes(G)&&!y[G](H,F))return Po.SKIP;return C!==void 0&&(F.key=C),F}if(a(U,"processEntry"),b>0||!K.hasEntries){let F=K.map(C=>{if(N=null,typeof C=="object"&&C.key!==void 0)return b>0?U(C):C;if(C==null)return Po.SKIP;for(let H=0;H<b;H++){let se=y[H].idFilter;if(se){if(!se(C))return Po.SKIP;N||(N=[]),N.push(H)}}return bh(C,O,D,!1,U)});return Array.isArray(K)&&(F=F.filter(C=>C!==Po.SKIP)),F.hasEntries=!0,F}return K}a(aO,"transformToEntries");async function cO(K,m,O){let I=m?.metadataFlags,y=m?.version,b,D;if(!i.attemptLock(K,y,()=>{clearTimeout(D);let C=i.getEntry(K);!C||!C.value||C.metadataFlags&(Ll|Ml)?b(cO(K,i.getEntry(K),O)):b(C)}))return new Promise(C=>{b=C,D=setTimeout(()=>{i.unlock(K,y)},Cie)});let N=m?.value,U={requestContext:O,replacingRecord:N,replacingVersion:y,source:null,resourceCache:O?.resourceCache},F=O?.responseHeaders;return new Promise((C,H)=>{let G;kA(je(U,async se=>{let pe=performance.now(),te,Pe,ae;try{for(let Oe of ze.sources)if(Oe.get&&(!Oe.get.reliesOnPrototype||Oe.prototype.get)&&(U.source=Oe,te=await Oe.get(K,U),te))break;ae=I⋘let re=U.lastModified||ae&&y;Pe=ae||re>y||!N,re||(re=(0,vl.getNextMonotonicTime)());let j=performance.now()-pe;if(kr(j,"cache-resolution",s),F&&fg(F,"Server-Timing",`cache-resolve;dur=${j.toFixed(2)}`,!0),se.timestamp=re,f&&!U.expiresAt&&(U.expiresAt=Date.now()+f),te){if(typeof te!="object")throw new Error("Only objects can be cached and stored in tables");typeof te.toJSON=="function"&&(te=te.toJSON()),t&&te[t]!==K&&(te[t]=K)}G=!0,C({version:re,value:te})}catch(re){re.message+=` while resolving record ${K} for ${s}`,N&&((re.code==="ECONNRESET"||re.code==="ECONNREFUSED"||re.code==="EAI_AGAIN")&&!O?.mustRevalidate||O?.staleIfError&&(re.statusCode===500||re.statusCode===502||re.statusCode===503||re.statusCode===504))?(C({version:y,value:N}),tt.trace(re.message,"(returned stale record)")):H(re),U.transaction.abort();return}if(O?.noCacheStore){U.transaction.abort();return}On(U).addWrite({key:K,store:i,entry:m,nodeName:"source",commit:(re,j)=>{if(j?.version!==y)return;let Oe=zl(K,N,te);te?(Be.put?.(U,K,te),T(K,te,j,re,0,h&&Pe||null,U,U.expiresAt,"put",!!ae)):(Be.delete?.(U,K),h||p?T(K,null,j,re,0,h&&Pe||null,U,0,"delete",!!ae):i.remove(K,y))}})}),()=>{i.unlock(K,y)},se=>{i.unlock(K,y),G&&tt.error("Error committing cache update",se)})})}a(cO,"getFromSource");function Ih(){if(Lt!==Wl&&(Wl=Lt,(0,vo.getWorkerIndex)()===(0,vo.getWorkerCount)()-1)){if(Ql&&clearTimeout(Ql),!Lt)return;let K=new Date;K.setMonth(0),K.setDate(1),K.setHours(0),K.setMinutes(0),K.setSeconds(0);let m=Math.ceil((Date.now()-K.getTime())/Lt)*Lt+K.getTime(),O=a(I=>{tt.trace(`Scheduled next cleanup scan at ${new Date(I)}ms`),Ql=setTimeout(()=>P=P.then(async()=>{if(O(Math.max(I+Lt,Date.now())),i.rootStore.status!=="open"){clearTimeout(Ql);return}let y=50,b=new Array(y),D=0;tt.trace(`Starting cleanup scan for ${s}`);try{let N=0;for(let{key:U,value:F,version:C,expiresAt:H}of i.getRange({start:!1,snapshot:!1,versions:!0,lazy:!0})){let G;F===null&&!h&&C+wie<Date.now()?G=i.remove(U,C):H&&H+E<Date.now()&&(G=ze.evict(U,F,C),N++),G&&(await b[D],b[D]=G.catch(se=>{tt.error("Cleanup error",se)}),++D>=y&&(D=0)),await Ul()}tt.trace(`Finished cleanup scan for ${s}, evicted ${N} entries`)}catch(N){tt.trace(`Error in cleanup scan for ${s}:`,N)}}),Math.min(I-Date.now(),2147483647)).unref()},"startNextTimer");O(m)}}a(Ih,"scheduleCleanup");function uO(){z=u?.addDeleteRemovalCallback(n,K=>{let m=i.getEntry(K);m?.value===null&&i.remove(K,m.version)})}a(uO,"addDeleteRemoval");function mq(){(0,vo.getWorkerIndex)()===0&&setInterval(async()=>{if(!Oh){Oh=!0;try{let K=X.name,m=r[K];if(!m)throw new Error(`expiresAt attribute ${X} must be indexed`);for(let O of m.getRange({start:!0,values:!1,end:Date.now(),snapshot:!1})){for(let I of m.getValues(O)){let y=i.getEntry(I);y?.value?y.value[K]<Date.now()&&ze.evict(I,y.value,y.version):i.ifVersion(I,y?.version,()=>m.remove(O,I))}await Ul()}}catch(K){tt.error("Error in evicting old records",K)}finally{Oh=!1}}},Iie).unref()}a(mq,"runRecordExpirationEviction")}function FA(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 dG(){}function Pie(e){mG=e}function rh(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"&&!vie.test(e)&&(e+="Z"),e==="null"?null:new Date(e)):!r||r==="Any"?(0,sh.autoCast)(e):e}function fG(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 kA(e,t,r){return e?.then?e.then(t,r):t(e)}function nh(e,t){e[Zr]=t,e[_e]=t?.value??null,e[Pl]=t?.version}function EG(e){return e!=null}function Vn(e){try{return JSON.stringify(e)}catch{return e}}var $n,Po,vl,hG,xl,Rn,Bl,Hl,tt,Bo,vo,sh,Nie,mG,Iie,wie,uG,Cie,Pl,Die,Zr,Dl,lG,Lie,qA,ec,Ll,Ml,Mie,_G,Uie,rTe,vie,Ul,cE=ge(()=>{$n=v(L()),Po=require("lmdb"),vl=v(Dr()),hG=require("lodash");Nn();oS();xl=v(ee());cG();Rn=v(ne()),Bl=v(bs()),Hl=v(Mn());Re();Qf();tt=v($());_d();no();Bo=require("ordered-binary"),vo=v(Ke());ei();sh=v(Q());Ic();ws();YE();Wu();Nie=new Uint8Array(9);Nie[8]=192;Iie=6e4,wie=864e5;xl.initSync();uG=xl.get($n.CONFIG_PARAMS.STORAGE_PREFETCHWRITES),Cie=1e4,Pl=Symbol.for("version"),Die=Symbol.for("incremental-update"),Zr=Symbol("entry"),Dl=Symbol("is-saving"),lG=1,Lie=2,qA=Symbol("loaded-from-source"),ec={isNotification:!0,ensureLoaded:!1},Ll=1,Ml=8,Mie=Buffer.allocUnsafeSlow(8192),_G=1978,Uie={read:!0,insert:!0,update:!0,delete:!0,isSuperUser:!0},rTe=(0,sh.convertToMS)(xl.get($n.CONFIG_PARAMS.CLUSTERING_LEAFSERVER_STREAMS_MAXAGE))||864e5;a(ih,"makeTable");a(FA,"attributesAsObject");a(dG,"noop");a(Pie,"setServerUtilities");vie=/[+-][0-9]{2}:[0-9]{2}|[a-zA-Z]$/;a(rh,"coerceType");a(fG,"isDescendantId");Ul=a(()=>new Promise(setImmediate),"rest");a(kA,"when");a(nh,"updateResource");a(EG,"exists");a(Vn,"stringify")});var Fe={};qe(Fe,{database:()=>tu,databases:()=>st,dropDatabase:()=>_S,dropTableMeta:()=>qie,getDatabases:()=>dr,getDefaultCompression:()=>hf,getTables:()=>Bie,onUpdatedTable:()=>jR,readMetaDb:()=>Gl,resetDatabases:()=>qu,table:()=>lt,tables:()=>Lr});function Bie(){return lh||dr(),Lr||{}}function dr(){if(lh)return st;lh=!0,nc=new Map;let e=(0,ht.getHdbBasePath)()&&(0,rt.join)((0,ht.getHdbBasePath)(),Dt.DATABASES_DIR_NAME),t=(0,ht.get)(Dt.CONFIG_PARAMS.DATABASES)||{};if(process.env.SCHEMAS_DATA_PATH&&(t.data={path:process.env.SCHEMAS_DATA_PATH}),e=process.env.STORAGE_PATH||(0,ht.get)(Dt.CONFIG_PARAMS.STORAGE_PATH)||e&&((0,en.existsSync)(e)?e:(0,rt.join)((0,ht.getHdbBasePath)(),Dt.LEGACY_DATABASES_DIR_NAME)),!!e){if((0,en.existsSync)(e))for(let r of(0,en.readdirSync)(e,{withFileTypes:!0})){let n=(0,rt.basename)(r.name,".mdb");r.isFile()&&(0,rt.extname)(r.name).toLowerCase()===".mdb"&&!t[n]?.path&&Gl((0,rt.join)(e,r.name),null,n)}if((0,en.existsSync)((0,rc.getBaseSchemaPath)())){for(let r of(0,en.readdirSync)((0,rc.getBaseSchemaPath)(),{withFileTypes:!0}))if(!r.isFile()){let n=(0,rt.join)((0,rc.getBaseSchemaPath)(),r.name),s=(0,rt.join)((0,rc.getTransactionAuditStoreBasePath)(),r.name);for(let i of(0,en.readdirSync)(n,{withFileTypes:!0}))if(i.isFile()&&(0,rt.extname)(i.name).toLowerCase()===".mdb"){let o=(0,rt.join)(s,i.name);Gl((0,rt.join)(n,i.name),(0,rt.basename)(i.name,".mdb"),r.name,o,!0)}}}if(t)for(let r in t){let n=t[r],s=n.path;if((0,en.existsSync)(s))for(let o of(0,en.readdirSync)(s,{withFileTypes:!0}))o.isFile()&&(0,rt.extname)(o.name).toLowerCase()===".mdb"&&Gl((0,rt.join)(s,o.name),(0,rt.basename)(o.name,".mdb"),r);let i=n.tables;if(i)for(let o in i){let c=i[o],u=(0,rt.join)(c.path,(0,rt.basename)(o+".mdb"));(0,en.existsSync)(u)&&Gl(u,o,r,null,!0)}}for(let r in st){let n=nc.get(r);if(n){let s=st[r];r.includes("delete")&&An.trace(`defined tables ${Array.from(n.keys())}`);for(let i in s)n.has(i)||(An.trace(`delete table class ${i}`),delete s[i])}else if(delete st[r],r==="data"){for(let s in Lr)delete Lr[s];delete Lr[dh]}}return nc=null,st}}function qu(){lh=!1;for(let[,e]of Pi)e.needsDeletion=!0;dr();for(let[e,t]of Pi)t.needsDeletion&&!e.endsWith("system.mdb")&&(t.close(),Pi.delete(e));return st}function Gl(e,t,r=YA,n,s){let i=new VA.default(e,!1);try{let o=Pi.get(e);o?o.needsDeletion=!1:(o=(0,ah.open)(i),Pi.set(e,o));let c=new Ho.default(!1),u=o.dbisDb||(o.dbisDb=o.openDB(oh.INTERNAL_DBIS_NAME,c)),_=o.auditStore;_||(n?(0,en.existsSync)(n)&&(i.path=n,_=(0,ah.open)(i),_.isLegacy=!0):_=$E(o));let l=gG(r),d=l[dh],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 J of p)if(J.is_hash_attribute||J.isPrimaryKey){S=J;break}if(!S){An.fatal(`Unable to find a primary key attribute on table ${E}, with attributes: ${JSON.stringify(p)}`);continue}}let T=l[E],A={},R=[],M,x,P=typeof S.audit=="boolean"?S.audit:(0,ht.get)(Dt.CONFIG_PARAMS.LOGGING_AUDITLOG),k=S.trackDeletes,B=S.expiration,X=S.eviction,z=S.sealed;if(T)A=T.indices,R=T.attributes,T.schemaVersion++;else{M=S.tableId,M?M>=(u.get(tc)||0)&&u.putSync(tc,M+1):(S.tableId=M=u.get(tc),M||(M=1),u.putSync(tc,M+1),u.putSync(S.key,S));let J=new Ho.default(!S.is_hash_attribute,S.is_hash_attribute);if(J.compression=S.compression,J.compression){let me=(0,ht.get)(Dt.CONFIG_PARAMS.STORAGE_COMPRESSION_THRESHOLD)||TG;J.compression.threshold=me}x=h_(o.openDB(S.key,J)),x.rootStore=o,x.tableId=M}for(let J of p){J.attribute=J.name;try{if(!J.is_hash_attribute&&(J.indexed||J.attribute&&!J.name)){if(!A[J.name]){let ce=new Ho.default(!J.is_hash_attribute,J.is_hash_attribute);A[J.name]=o.openDB(J.key,ce),A[J.name].indexNulls=J.indexNulls}let me=R.find(ce=>ce.name===J.name);me?R.splice(R.indexOf(me),1,J):R.push(J)}}catch(me){An.error("Error trying to update attribute",J,R,A,me)}}if(!T){T=RG(l,E,ih({primaryStore:x,auditStore:_,audit:P,sealed:z,expirationMS:B&&B*1e3,evictionMS:X&&X*1e3,trackDeletes:k,tableName:E,tableId:M,primaryKey:S.name,databasePath:s?r+"/"+E:r,databaseName:r,indices:A,attributes:p,schemaDefined:S.schemaDefined,dbisDB:u})),T.schemaVersion=1;for(let J of KA)J(T)}}return o}catch(o){throw o.message+=` opening database ${e}`,o}}function gG(e){let t=st[e];if(t||(e==="data"?t=st[e]=Lr:e==="system"?Object.defineProperty(st,"system",{value:t=Object.create(null),configurable:!0}):t=st[e]=Object.create(null)),nc&&!nc.has(e)){let r=new Set;t[dh]=r,nc.set(e,r)}return t}function RG(e,t,r){return e[t]=r,r}function tu({database:e,table:t}){e||(e=YA),dr();let r=gG(e),n=(0,rt.join)((0,ht.getHdbBasePath)(),Dt.DATABASES_DIR_NAME),s=(0,ht.get)(Dt.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,ht.get)(Dt.CONFIG_PARAMS.STORAGE_PATH)||((0,en.existsSync)(n)?n:(0,rt.join)((0,ht.getHdbBasePath)(),Dt.LEGACY_DATABASES_DIR_NAME));let o=(0,rt.join)(n,(i?t:e)+".mdb"),c=Pi.get(o);if(!c){let u=new VA.default(o,!1);c=(0,ah.open)(u),Pi.set(o,c)}return c}async function _S(e){if(!st[e])throw new Error("Schema does not exist");let t=st[e];for(let r in t){let s=t[r].primaryStore.rootStore;Pi.delete(s.path),s.status==="open"&&(await s.close(),await _h.remove(s.path))}if(e==="data"){for(let r in Lr)delete Lr[r];delete Lr[dh]}delete st[e]}function lt({table:e,database:t,expiration:r,eviction:n,scanInterval:s,attributes:i,audit:o,sealed:c,trackDeletes:u,schemaDefined:_,origin:l}){t||(t=YA);let d=tu({database:t,table:e}),f=st[t],E=f?.[e];if(d.status==="closed")throw new Error(`Can not use a closed data store for ${e}`);let h,p,S,T;_==null&&(_=!0);let A=new Ho.default(!1);for(let B of i)B.attribute?(B.name=B.attribute,B.indexed=!0):B.attribute=B.name,B.expiresAt&&(B.indexed=!0);let R,M;if(E){if(h=E.primaryKey,E.primaryStore.rootStore.status==="closed")throw new Error(`Can not use a closed data store from ${e} class`);E.attributes.splice(0,E.attributes.length,...i)}else{let B=d.auditStore;B||(B=$E(d)),p=i.find(me=>me.isPrimaryKey)||{},h=p.name,p.is_hash_attribute=!0,p.schemaDefined=_,p.compression=hf(),u&&(p.trackDeletes=!0),o=p.audit=typeof o=="boolean"?o:(0,ht.get)(Dt.CONFIG_PARAMS.LOGGING_AUDITLOG),r&&(p.expiration=r),n&&(p.eviction=n),typeof c=="boolean"&&(p.sealed=c),l&&(p.origins?p.origins.includes(l)||p.origins.push(l):p.origins=[l]),An.trace(`${e} table loading, opening primary store`);let X=new Ho.default(!1,!0);X.compression=p.compression;let z=e+"/",J=h_(d.openDB(z,X));J.rootStore=d,T=d.dbisDb=d.openDB(oh.INTERNAL_DBIS_NAME,A),J.tableId=T.get(tc),J.tableId||(J.tableId=1),T.putSync(tc,J.tableId+1),p.tableId=J.tableId,E=RG(f,e,ih({primaryStore:J,auditStore:B,audit:o,sealed:c,trackDeletes:u,expirationMS:r&&r*1e3,evictionMS:n&&n*1e3,primaryKey:h,tableName:e,tableId:J.tableId,databasePath:t,databaseName:t,indices:{},attributes:i,schemaDefined:_,dbisDB:T})),E.schemaVersion=1,R=!0,k(),T.put(z,p)}S=E.indices,T=T||(d.dbisDb=d.openDB(oh.INTERNAL_DBIS_NAME,A)),E.dbisDB=T;let x=[];for(let{key:B,value:X}of T.getRange({start:!0})){let[z,J]=B.toString().split("/");if(J===""&&(J=X.name),J){if(z!==e)continue}else J=z;if(!i.find(ce=>ce.name===J)?.indexed&&X.indexed&&!X.isPrimaryKey){k(),R=!0,T.remove(B);let ce=E.indices[z];ce&&x.push(ce)}}let P=[];try{for(let B of i||[]){if(B.relationship)continue;let X=e+"/"+(B.name||"");Object.defineProperty(B,"key",{value:X,configurable:!0});let z=T.get(X);if(B.isPrimaryKey){if(z=z||T.get(X=e+"/")||{},o!==E.audit||c!==c||(+r||void 0)!==(+z.expiration||void 0)||(+n||void 0)!==(+z.eviction||void 0)){let me=Object.assign({},z);typeof o=="boolean"&&(o&&E.enableAuditing(o),me.audit=o),r&&(me.expiration=+r),n&&(me.eviction=+n),c!==void 0&&(me.sealed=c),R=!0,k(),T.put(X,me)}continue}z?.attribute&&!z.name&&(z.indexed=!0);let J=!z||z.type!==B.type||z.indexed!==B.indexed||z.nullable!==B.nullable||JSON.stringify(z.attributes)!==JSON.stringify(B.attributes)||JSON.stringify(z.elements)!==JSON.stringify(B.elements);if(B.indexed){let me=new Ho.default(!0,!1),ce=d.openDB(X,me);(J||z.indexingPID&&z.indexingPID!==process.pid||z.restartNumber<ql.workerData?.restartNumber)&&(R=!0,k(),z=T.get(X),(J||z.indexingPID&&z.indexingPID!==process.pid||z.restartNumber<ql.workerData?.restartNumber)&&(R=!0,B.indexNulls===void 0&&(B.indexNulls=!0),E.primaryStore.getStats().entryCount>0&&(B.lastIndexedKey=z?.lastIndexedKey||!1,B.indexingPID=process.pid,ce.isIndexing=!0,Object.defineProperty(B,"dbi",{value:ce}),P.push(B))),T.put(X,B)),z?.indexNulls&&B.indexNulls===void 0&&(B.indexNulls=!0),ce.indexNulls=B.indexNulls,S[B.name]=ce}else J&&(R=!0,k(),T.put(X,B))}}finally{M&&M()}if(R&&(E.schemaVersion++,E.updatedAttributes()),An.trace(`${e} table loading, running index`),P.length>0||x.length>0?E.indexingOperation=Gie(E,P,x):R&&ch.signalSchemaChange(new uh.SchemaEventMsg(process.pid,"schema-change",E.databaseName,E.tableName)),E.origin=l,R)for(let B of KA)B(E,l!=="cluster");return(r||n||s)&&E.setTTLExpiration({expiration:r,eviction:n,scanInterval:s}),An.trace(`${e} table loaded`),E;function k(){M||d.transactionSync(()=>({then(B){M=B}}))}a(k,"startTxn")}async function Gie(e,t,r){try{let n=e.schemaVersion;await ch.signalSchemaChange(new uh.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,pG.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--,An.error(f)}),ql.workerData&&ql.workerData.restartNumber!==SG.restartNumber&&(i=!0),++o%100===0||i){for(let f of t)f.lastIndexedKey=_,e.dbisDB.put(f.key,f);if(i)return}u>Hie?await s:u>xie&&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 ch.signalSchemaChange(new uh.SchemaEventMsg(process.pid,"indexing-finished",e.databaseName,e.tableName))}catch(n){An.error("Error in indexing",n)}}function qie({table:e,database:t}){let r=tu({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 jR(e){KA.push(e)}function hf(){let e=(0,ht.get)(Dt.CONFIG_PARAMS.STORAGE_COMPRESSION),t=(0,ht.get)(Dt.CONFIG_PARAMS.STORAGE_COMPRESSION_DICTIONARY),r=(0,ht.get)(Dt.CONFIG_PARAMS.STORAGE_COMPRESSION_THRESHOLD)||TG,n={startingOffset:32};return t&&(n.dictionary=_h.readFileSync(t)),r&&(n.threshold=r),e&&n}var ht,oh,ah,rt,en,rc,Ho,VA,Dt,_h,$A,pG,ch,uh,ql,An,SG,YA,dh,TG,Lr,st,tc,KA,lh,Pi,nc,Hie,xie,Re=ge(()=>{ht=v(ee()),oh=v(ut()),ah=require("lmdb"),rt=require("path"),en=require("fs"),rc=v(Je());cE();Ho=v(wc()),VA=v(Cc()),Dt=v(L()),_h=v(require("fs-extra")),$A=require("../index"),pG=v(Dr()),ch=v(bs()),uh=v(Mn()),ql=require("worker_threads"),An=v($()),SG=v(Ke());ei();Ic();YA="data",dh=Symbol("defined-tables"),TG=((0,ht.get)(Dt.CONFIG_PARAMS.STORAGE_PAGESIZE)||4096)-60;(0,ht.initSync)();Lr=Object.create(null),st=Object.create(null);(0,$A._assignPackageExport)("databases",st);(0,$A._assignPackageExport)("tables",Lr);tc=Symbol.for("next-table-id"),KA=[],Pi=new Map;a(Bie,"getTables");a(dr,"getDatabases");a(qu,"resetDatabases");a(Gl,"readMetaDb");a(gG,"ensureDB");a(RG,"setTable");a(tu,"database");a(_S,"dropDatabase");a(lt,"table");Hie=1e3,xie=10;a(Gie,"runIndexing");a(qie,"dropTableMeta");a(jR,"onUpdatedTable");a(hf,"getDefaultCompression")});var Q=g((_Te,vG)=>{"use strict";var vi=require("path"),NG=require("fs-extra"),Ir=$(),AG=require("fs-extra"),fh=require("os"),Fie=require("net"),kie=require("recursive-iterator"),ct=L(),Vie=kO(),OG=require("papaparse"),Eh=require("moment"),{inspect:$ie}=require("util"),bG=require("is-number"),lTe=require("lodash"),Yie=require("minimist"),Kie=require("https"),Wie=require("http"),{hdb_errors:hh}=ne(),Qie=/^((\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)))$/,IG=require("util").promisify(setTimeout),zie=100,Jie=5,Xie="",jie=4,yG={true:!0,TRUE:!0,FALSE:!1,false:!1,undefined:null,null:null,NULL:null,NaN:NaN};vG.exports={isEmpty:tn,isEmptyOrZeroLength:hs,arrayHasEmptyValues:toe,arrayHasEmptyOrZeroLengthValues:roe,buildFolderPath:noe,isBoolean:wG,errorizeMessage:Zie,stripFileExtension:ioe,autoCast:ooe,autoCastJSON:CG,autoCastJSONDeep:QA,removeDir:aoe,compareVersions:coe,isCompatibleDataVersion:uoe,escapeRawValue:loe,unescapeValue:_oe,stringifyProps:doe,timeoutPromise:Eoe,isClusterOperation:moe,getClusterUser:Soe,checkGlobalSchemaTable:poe,getHomeDir:LG,getPropsFilePath:foe,promisifyPapaParse:Toe,removeBOM:MG,createEventPromise:goe,checkProcessRunning:Roe,checkSchemaTableExist:Aoe,checkSchemaExists:UG,checkTableExists:PG,getStartOfTomorrowInSeconds:Ooe,getLimitKey:boe,isObject:soe,isNotEmptyAndHasValue:eoe,autoCasterIsNumberCheck:DG,backtickASTSchemaItems:yoe,isPortTaken:hoe,createForkArgs:Noe,autoCastBoolean:Ioe,async_set_timeout:IG,getTableHashAttribute:woe,doesSchemaExist:Coe,doesTableExist:Doe,stringifyObj:Loe,ms_to_time:Moe,changeExtension:Uoe,getEnvCliRootPath:zA,noBootFile:Poe,httpRequest:voe,transformReq:Boe,convertToMS:Hoe,PACKAGE_ROOT:ct.PACKAGE_ROOT};function Zie(e){return e instanceof Error?e:new Error(e)}a(Zie,"errorizeMessage");function tn(e){return e==null}a(tn,"isEmpty");function eoe(e){return!tn(e)&&(e||e===0||e===""||wG(e))}a(eoe,"isNotEmptyAndHasValue");function hs(e){return tn(e)||e.length===0||e.size===0}a(hs,"isEmptyOrZeroLength");function toe(e){if(tn(e))return!0;for(let t=0;t<e.length;t++)if(tn(e[t]))return!0;return!1}a(toe,"arrayHasEmptyValues");function roe(e){if(hs(e))return!0;for(let t=0;t<e.length;t++)if(hs(e[t]))return!0;return!1}a(roe,"arrayHasEmptyOrZeroLengthValues");function noe(...e){try{return e.join(vi.sep)}catch{console.error(e)}}a(noe,"buildFolderPath");function wG(e){return tn(e)?!1:e===!0||e===!1}a(wG,"isBoolean");function soe(e){return tn(e)?!1:typeof e=="object"}a(soe,"isObject");function ioe(e){return hs(e)?Xie:e.slice(0,-jie)}a(ioe,"stripFileExtension");function ooe(e){return tn(e)||e===""||typeof e!="string"?e:yG[e]!==void 0?yG[e]:DG(e)===!0?Number(e):Qie.test(e)?new Date(e):e}a(ooe,"autoCast");function CG(e){if(typeof e=="string"&&(e.startsWith("{")&&e.endsWith("}")||e.startsWith("[")&&e.endsWith("]")))try{return JSON.parse(e)}catch{}return e}a(CG,"autoCastJSON");function QA(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=QA(n);s!==n&&(e[t]=s)}else for(let t in e){let r=e[t],n=QA(r);n!==r&&(e[t]=n)}return e}else return CG(e)}a(QA,"autoCastJSONDeep");function DG(e){if(e.startsWith("0.")&&bG(e))return!0;let t=e.toUpperCase().includes("E");return!!((e!=="0"&&e.startsWith("0"))===!1&&t===!1&&bG(e))}a(DG,"autoCasterIsNumberCheck");async function aoe(e){if(hs(e))throw new Error(`Directory path: ${e} does not exist`);try{await AG.emptyDir(e),await AG.remove(e)}catch(t){throw Ir.error(`Error removing files in ${e} -- ${t}`),t}}a(aoe,"removeDir");function coe(e,t){if(hs(e)){Ir.info("Invalid current version sent as parameter.");return}if(hs(t)){Ir.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(coe,"compareVersions");function uoe(e,t,r=!1){let n=e.toString().split("."),s=t.toString().split(".");return n[0]===s[0]&&(!r||n[1]===s[1])}a(uoe,"isCompatibleDataVersion");function loe(e){if(tn(e))return e;let t=String(e);return t==="."?ct.UNICODE_PERIOD:t===".."?ct.UNICODE_PERIOD+ct.UNICODE_PERIOD:t.replace(ct.FORWARD_SLASH_REGEX,ct.UNICODE_FORWARD_SLASH)}a(loe,"escapeRawValue");function _oe(e){if(tn(e))return e;let t=String(e);return t===ct.UNICODE_PERIOD?".":t===ct.UNICODE_PERIOD+ct.UNICODE_PERIOD?"..":String(e).replace(ct.ESCAPED_FORWARD_SLASH_REGEX,"/")}a(_oe,"unescapeValue");function doe(e,t){if(tn(e))return Ir.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+fh.EOL}!hs(n)&&n[0]===";"?r+=" "+n+s+fh.EOL:hs(n)||(r+=n+"="+s+fh.EOL)}catch{Ir.error(`Found bad property during upgrade with key ${n} and value: ${s}`)}}),r}a(doe,"stringifyProps");function LG(){let e;try{e=fh.homedir()}catch{e=process.env.HOME}return e||(e="~/"),e}a(LG,"getHomeDir");function foe(){let e=vi.join(LG(),ct.HDB_HOME_DIR_NAME,ct.BOOT_PROPS_FILE_NAME);return NG.existsSync(e)||(e=vi.join(__dirname,"../","hdb_boot_properties.file")),e}a(foe,"getPropsFilePath");function Eoe(e,t){let r,n;return n=new Promise(function(s){r=setTimeout(function(){s(t)},e)}),{promise:n,cancel:function(){clearTimeout(r)}}}a(Eoe,"timeoutPromise");async function hoe(e){if(!e)throw new Error("Invalid port passed as parameter");return new Promise((t,r)=>{let n=Fie.createServer().once("error",s=>{s.code==="EADDRINUSE"?t(!0):r(s)}).once("listening",()=>n.once("close",()=>t(!1)).close()).listen(e)})}a(hoe,"isPortTaken");function moe(e){try{return ct.CLUSTER_OPERATIONS[e.toLowerCase()]!==void 0}catch(t){Ir.error(`Error checking operation against cluster ops ${t}`)}return!1}a(moe,"isClusterOperation");function poe(e,t){let r=(Re(),ie(Fe)).getDatabases();if(!r[e])return hh.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e);if(!r[e][t])return hh.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(poe,"checkGlobalSchemaTable");function Soe(e,t){if(tn(t)){Ir.warn("No CLUSTERING_USER defined, clustering disabled");return}if(tn(e)||hs(e)){Ir.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){Ir.error(`unable to find cluster_user due to: ${n.message}`);return}if(r===void 0){Ir.warn(`CLUSTERING_USER: ${t} not found or is not active.`);return}return r}a(Soe,"getClusterUser");function Toe(){OG.parsePromise=function(e,t,r){return new Promise(function(n,s){OG.parse(e,{header:!0,transformHeader:MG,chunk:t.bind(null,s),skipEmptyLines:!0,transform:r,dynamicTyping:!1,error:s,complete:n})})}}a(Toe,"promisifyPapaParse");function MG(e){if(typeof e!="string")throw new TypeError(`Expected a string, got ${typeof e}`);return e.charCodeAt(0)===65279?e.slice(1):e}a(MG,"removeBOM");function goe(e,t,r){return new Promise(n=>{t.once(e,s=>{let i=r;Ir.info(`Got cluster status event response: ${$ie(s)}`);try{i.cancel()}catch{Ir.error("Error trying to cancel timeout.")}n(s)})})}a(goe,"createEventPromise");async function Roe(e){let t=!0,r=0;do await IG(zie*r++),(await Vie.findPs(e)).length>0&&(t=!1);while(t&&r<Jie);if(t)throw new Error(`process ${e} was not started`)}a(Roe,"checkProcessRunning");function Aoe(e,t){let r=UG(e);if(r)return r;let n=PG(e,t);if(n)return n}a(Aoe,"checkSchemaTableExist");function UG(e){let{getDatabases:t}=(Re(),ie(Fe));if(!t()[e])return hh.HDB_ERROR_MSGS.SCHEMA_NOT_FOUND(e)}a(UG,"checkSchemaExists");function PG(e,t){let{getDatabases:r}=(Re(),ie(Fe));if(!r()[e][t])return hh.HDB_ERROR_MSGS.TABLE_NOT_FOUND(e,t)}a(PG,"checkTableExists");function Ooe(){let e=Eh().utc().add(1,ct.MOMENT_DAYS_TAG).startOf(ct.MOMENT_DAYS_TAG).unix(),t=Eh().utc().unix();return e-t}a(Ooe,"getStartOfTomorrowInSeconds");function boe(){return Eh().utc().format("DD-MM-YYYY")}a(boe,"getLimitKey");function yoe(e){try{let t=new kie(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){Ir.error("Got an error back ticking items."),Ir.error(t)}}a(yoe,"backtickASTSchemaItems");function Noe(e){return[e]}a(Noe,"createForkArgs");function Ioe(e){return e===!0||typeof e=="string"&&e.toLowerCase()==="true"}a(Ioe,"autoCastBoolean");function woe(e,t){let{getDatabases:r}=(Re(),ie(Fe)),n=r()[e]?.[t];return n?.primaryKey||n?.hash_attribute}a(woe,"getTableHashAttribute");function Coe(e){let{getDatabases:t}=(Re(),ie(Fe));return t()[e]!==void 0}a(Coe,"doesSchemaExist");function Doe(e,t){let{getDatabases:r}=(Re(),ie(Fe));return r()[e]?.[t]!==void 0}a(Doe,"doesTableExist");function Loe(e){try{return JSON.stringify(e)}catch{return e}}a(Loe,"stringifyObj");function Moe(e){let t=Eh.duration(e),r=t.seconds()>0?t.seconds()+"s":"",n=t.minutes()>0?t.minutes()+"m ":"",s=t.hours()>0?t.hours()+"h ":"",i=t.days()>0?t.days()+"d ":"";return(t.years()>0?t.years()+"y ":"")+i+s+n+r}a(Moe,"ms_to_time");function Uoe(e,t){let r=vi.basename(e,vi.extname(e));return vi.join(vi.dirname(e),r+t)}a(Uoe,"changeExtension");function zA(){if(process.env[ct.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return process.env[ct.CONFIG_PARAMS.ROOTPATH.toUpperCase()];let e=Yie(process.argv);if(e[ct.CONFIG_PARAMS.ROOTPATH.toUpperCase()])return e[ct.CONFIG_PARAMS.ROOTPATH.toUpperCase()]}a(zA,"getEnvCliRootPath");var WA;function Poe(){if(WA)return WA;let e=zA();zA()&&NG.pathExistsSync(vi.join(e,ct.HDB_CONFIG_FILE))&&(WA=!0)}a(Poe,"noBootFile");function voe(e,t){let r;return e.protocol==="http:"?r=Wie:r=Kie,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(voe,"httpRequest");function Boe(e){if(!e.schema&&!e.database){e.schema=ct.DEFAULT_DATABASE_NAME;return}e.database&&(e.schema=e.database)}a(Boe,"transformReq");function Hoe(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(Hoe,"convertToMS")});var ee=g((fTe,GG)=>{"use strict";var JA=require("fs-extra"),xo=require("path"),BG=require("os"),xoe=require("properties-reader"),kl=$(),Fl=Q(),ue=L(),mh=lr(),Goe="Error initializing environment manager",ph="BOOT_PROPS_FILE_PATH",HG=!1,qoe={[ue.HDB_SETTINGS_NAMES.INSTALL_USER]:!0,[ue.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY]:!0,[ue.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]:!0,BOOT_PROPS_FILE_PATH:!0},Ks={};GG.exports={BOOT_PROPS_FILE_PATH:ph,getHdbBasePath:Foe,setHdbBasePath:koe,get:xG,initSync:$oe,setProperty:Ue,initTestEnvironment:Yoe};function Foe(){return Ks[ue.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]}a(Foe,"getHdbBasePath");function koe(e){Ks[ue.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=e}a(koe,"setHdbBasePath");function xG(e){let t=mh.getConfigValue(e);return t===void 0?Ks[e]:t}a(xG,"get");function Ue(e,t){qoe[e]&&(Ks[e]=t),mh.updateConfigObject(e,t)}a(Ue,"setProperty");function Voe(){let e;try{e=Fl.getPropsFilePath(),JA.accessSync(e,JA.constants.F_OK|JA.constants.R_OK),HG=!0;let t=xoe(e);return Ks[ue.HDB_SETTINGS_NAMES.INSTALL_USER]=t.get(ue.HDB_SETTINGS_NAMES.INSTALL_USER),Ks[ue.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY]=t.get(ue.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY),Ks[ph]=e,!0}catch{return kl.trace(`Environment manager found no properties file at ${e}`),!1}}a(Voe,"doesPropFileExist");function $oe(e=!1){try{(HG||Voe()||Fl.noBootFile())&&(mh.initConfig(e),Ks[ue.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]=mh.getConfigValue(ue.HDB_SETTINGS_NAMES.HDB_ROOT_KEY))}catch(t){kl.error(Goe),kl.error(t),console.error(t),process.exit(1)}}a($oe,"initSync");function Yoe(e={}){try{let{keep_alive_timeout:t,headers_timeout:r,server_timeout:n,https_enabled:s,cors_enabled:i,cors_accesslist:o,local_studio_on:c}=e,u=xo.join(__dirname,"../../","unitTests");Ks[ph]=xo.join(u,"hdb_boot_properties.file"),Ue(ue.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY,xo.join(u,"settings.test")),Ue(ue.HDB_SETTINGS_NAMES.INSTALL_USER,BG.userInfo()?BG.userInfo().username:void 0),Ue(ue.HDB_SETTINGS_NAMES.LOG_LEVEL_KEY,"debug"),Ue(ue.HDB_SETTINGS_NAMES.LOG_PATH_KEY,xo.join(u,"envDir","log")),Ue(ue.HDB_SETTINGS_NAMES.LOG_DAILY_ROTATE_KEY,!1),Ue(ue.HDB_SETTINGS_NAMES.CLUSTERING_ENABLED_KEY,!0),Ue(ue.HDB_SETTINGS_NAMES.CLUSTERING_NODE_NAME_KEY,"1231412de213"),Ue(ue.HDB_SETTINGS_NAMES.HDB_ROOT_KEY,xo.join(u,"envDir")),Ue(ue.CONFIG_PARAMS.STORAGE_PATH,xo.join(u,"envDir")),s&&(Ue(ue.CONFIG_PARAMS.HTTP_SECUREPORT,xG(ue.CONFIG_PARAMS.HTTP_PORT)),Ue(ue.CONFIG_PARAMS.HTTP_PORT,null)),Ue(ue.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HTTPS,!!s),Ue(ue.HDB_SETTINGS_NAMES.SERVER_PORT_KEY,9925),Ue(ue.HDB_SETTINGS_NAMES.CORS_ENABLED_KEY,Fl.isEmpty(i)?!1:i),Ue(ue.CONFIG_PARAMS.HTTP_CORS,Fl.isEmpty(i)?!1:i),Ue(ue.HDB_SETTINGS_NAMES.MAX_CUSTOM_FUNCTION_PROCESSES,2),Ue(ue.HDB_SETTINGS_NAMES.MAX_HDB_PROCESSES,4),Ue(ue.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_PORT_KEY,9926),Ue(ue.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_ENABLED_KEY,!0),Ue(ue.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY,xo.resolve(__dirname,"../../unitTests/server/fastifyRoutes/custom_functions")),Ue(ue.HDB_SETTINGS_NAMES.LOCAL_STUDIO_ON,Fl.isEmpty(c)?!1:c),o&&(Ue("CORS_ACCESSLIST",o),Ue(ue.CONFIG_PARAMS.HTTP_CORSACCESSLIST,o)),n&&(Ue(ue.HDB_SETTINGS_NAMES.SERVER_TIMEOUT_KEY,n),Ue(ue.CONFIG_PARAMS.HTTP_TIMEOUT,n)),t&&(Ue(ue.HDB_SETTINGS_NAMES.SERVER_KEEP_ALIVE_TIMEOUT_KEY,t),Ue(ue.CONFIG_PARAMS.HTTP_KEEPALIVETIMEOUT,t)),r&&(Ue(ue.HDB_SETTINGS_NAMES.SERVER_HEADERS_TIMEOUT_KEY,r),Ue(ue.CONFIG_PARAMS.HTTP_HEADERSTIMEOUT,r))}catch(t){let r=`Error reading in HDB environment variables from path ${ph}. Please check your boot props and settings files`;kl.fatal(r),kl.error(t)}}a(Yoe,"initTestEnvironment")});var $G=g((hTe,VG)=>{"use strict";var kG=require("joi"),{string:Vl,boolean:qG,array:Koe}=kG.types(),FG=L(),Woe=Xe();VG.exports=Qoe;function Qoe(e){let t=kG.object({operation:Vl.valid(FG.OPERATIONS_ENUM.ADD_NODE,FG.OPERATIONS_ENUM.UPDATE_NODE).required(),node_name:Vl.required(),subscriptions:Koe.items({schema:Vl.required(),table:Vl.optional(),hash_attribute:Vl.optional(),subscribe:qG.required(),publish:qG.required()}).min(1).required()});return Woe.validateBySchema(e,t)}a(Qoe,"updateRemoteSourceValidator")});var $l=g((pTe,YG)=>{"use strict";var XA=class{static{a(this,"UpdateRemoteResponseObject")}constructor(t,r,n=void 0){this.status=t,this.message=r,this.system_info=n}};YG.exports=XA});var JG=g((TTe,zG)=>{"use strict";var zoe=$G(),Ws=$(),jA=ke(),KG=L(),ZA=ln(),Bi=it(),WG=Su(),Joe=id(),{Node:Xoe,NodeSubscription:QG}=mi(),eO=$l(),tO=Q(),joe=ee(),{cloneDeep:Zoe}=require("lodash"),{broadcast:eae}=Ke();zG.exports=tae;async function tae(e){try{let t=zoe(e);if(t)return Ws.error(`Validation error in updateRemoteSource: ${t.message}`),new eO(jA.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,t.message);let{subscriptions:r,node_name:n,system_info:s}=e,i=[],o=Zoe(await ZA.getNodeRecord(n)),c=!tO.isEmptyOrZeroLength(o);o=c?o[0]:o,c&&Ws.trace(`Existing record found for ${n}, updating records subscriptions`);for(let _=0,l=r.length;_<l;_++){let d=r[_],f=d.schema,E=d.table;if(!tO.doesSchemaExist(f)){Ws.trace(`updateRemoteSource creating schema: ${f}`);try{await WG.createSchema({operation:"create_schema",schema:f})}catch(h){Ws.error(h)}}if(E&&!tO.doesTableExist(f,E)){let h=new Joe(f,E,d.hash_attribute);d.attributes&&(h.attributes=d.attributes),Ws.trace(`updateRemoteSource creating table: ${E} in schema: ${f} with attributes: ${JSON.stringify(d.attributes)}`);try{await WG.createTable(h)}catch(p){Ws.error(p)}Ws.trace(`Creating local stream for ${f}.${E}`),await Bi.createLocalTableStream(f,E)}if(f===KG.SYSTEM_SCHEMA_NAME&&await Bi.createLocalTableStream(f,E),c?(await Bi.updateConsumerIterator(f,E,n,"stop"),await Bi.updateRemoteConsumer(d,n),d.subscribe===!0&&await Bi.updateConsumerIterator(f,E,n,"start")):(await Bi.updateRemoteConsumer(d,n),d.subscribe===!0?await Bi.updateConsumerIterator(f,E,n,"start"):await Bi.updateConsumerIterator(f,E,n,"stop")),c){let h=!1;for(let p=0,S=o.subscriptions.length;p<S;p++){let T=o.subscriptions[p];if(T.schema===f&&T.table===E){T.publish=d.publish,T.subscribe=d.subscribe,h=!0;break}}h||o.subscriptions.push(new QG(f,E,d.publish,d.subscribe))}else i.push(new QG(f,E,d.publish,d.subscribe))}c||(o=new Xoe(n,i,void 0),Ws.trace(`No record found for ${n}, creating a new one`));let u=Object.create({});return Object.assign(u,o),u.system_info=s,await ZA.upsertNodeRecord(u),eae({type:"nats_update"}),new eO(jA.UPDATE_REMOTE_RESPONSE_STATUSES.SUCCESS,`Node ${joe.get(KG.CONFIG_PARAMS.CLUSTERING_NODENAME)} successfully updated remote source`,await ZA.getSystemInfo())}catch(t){Ws.error(t);let r=t.message?t.message:t;return new eO(jA.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,r)}}a(tae,"updateRemoteSource")});var eq=g((RTe,ZG)=>{"use strict";var jG=require("joi"),{string:XG}=jG.types(),rae=L(),nae=Xe();ZG.exports=sae;function sae(e){let t=jG.object({operation:XG.valid(rae.OPERATIONS_ENUM.REMOVE_NODE).required(),node_name:XG.required()});return nae.validateBySchema(e,t)}a(sae,"removeRemoteSourceValidator")});var nq=g((OTe,rq)=>{"use strict";var iae=eq(),Sh=$(),Th=ke(),rO=L(),oae=ln(),aae=Q(),tq=it(),cae=ee(),gh=$l(),{NodeSubscription:uae}=mi(),lae=ia(),_ae=ii(),{broadcast:dae}=Ke(),fae=cae.get(rO.CONFIG_PARAMS.CLUSTERING_NODENAME);rq.exports=Eae;async function Eae(e){try{let t=iae(e);if(t)return Sh.error(`Validation error in removeRemoteSource: ${t.message}`),new gh(Th.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,t.message);let r=e.node_name,n=await oae.getNodeRecord(r);if(aae.isEmptyOrZeroLength(n)){let i=`No record found for node '${r}'`;return Sh.error(i),new gh(Th.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,i)}n=n[0];for(let i=0,o=n.subscriptions.length;i<o;i++){let c=n.subscriptions[i];Sh.trace(`remove remote source removing subscription: ${c.schema}.${c.table} for node: ${r}`);let u=new uae(c.schema,c.table,!1,!1);await tq.updateConsumerIterator(c.schema,c.table,r,"stop"),await tq.updateRemoteConsumer(u,r)}let s=new lae(rO.SYSTEM_SCHEMA_NAME,rO.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[r]);return await _ae.deleteRecord(s),dae({type:"nats_update"}),new gh(Th.UPDATE_REMOTE_RESPONSE_STATUSES.SUCCESS,`Node ${fae} successfully removed node '${r}'.`)}catch(t){Sh.error(t);let r=t.message?t.message:t;return new gh(Th.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,r)}}a(Eae,"removeRemoteSource")});var aq=g((yTe,oq)=>{"use strict";var Rh=$(),Yl=L(),sq=ke(),nO=ee(),hae=Q(),iq=$l(),mae=ln(),pae=Bd(),Sae=vr();oq.exports=Tae;async function Tae(e){try{Rh.trace("getRemoteSourceConfig called");let t=process.uptime()*1e3,r=hae.ms_to_time(t),n=new gae(nO.get(Yl.CONFIG_PARAMS.CLUSTERING_HUBSERVER_CLUSTER_NETWORK_PORT),nO.get(Yl.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_PORT)??nO.get(Yl.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_SECUREPORT),r,await mae.getSystemInfo());try{let s={name:e.node_name,system_info:e.system_info},i=new pae(Yl.SYSTEM_SCHEMA_NAME,Yl.SYSTEM_TABLE_NAMES.NODE_TABLE_NAME,[s]);await Sae.update(i)}catch(s){Rh.error("Get remote config encountered an error updating system info for node:",e.node_name,s)}return Rh.trace("getRemoteSourceConfig response:",n),new iq(sq.UPDATE_REMOTE_RESPONSE_STATUSES.SUCCESS,n)}catch(t){Rh.error(t);let r=t.message?t.message:t;return new iq(sq.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,r)}}a(Tae,"getRemoteSourceConfig");function gae(e,t,r,n){this.uptime=r,this.ports={clustering:e,operations_api:t},this.system_info=n}a(gae,"ConfigResponseObject")});var _q=g((ITe,lq)=>{"use strict";var cq=ee();cq.initSync();var uq=it(),Kl=$(),sc=L(),sO=ke(),Rae=JG(),Aae=nq(),Oae=aq(),bae=$l(),{encode:yae,decode:Nae}=require("msgpackr"),Iae=Os(),wae=As(),Cae=require("util"),Dae=L(),{isMainThread:Lae,parentPort:Mae}=require("worker_threads");Ke();var Uae=Cae.promisify(Iae.setSchemaDataToGlobal),iO=cq.get(sc.CONFIG_PARAMS.CLUSTERING_NODENAME);lq.exports=Pae;async function Pae(){try{Kl.notify("Starting reply service."),await Uae();let e=await uq.getConnection(),t=`${iO}.__request__`,r=e.subscribe(t,{queue:iO});await vae(r)}catch(e){Kl.error(e)}}a(Pae,"initialize");async function vae(e){for await(let t of e){let r=Nae(t.data),n;switch(r.operation){case sc.OPERATIONS_ENUM.ADD_NODE:case sc.OPERATIONS_ENUM.UPDATE_NODE:n=await Rae(r);break;case sc.OPERATIONS_ENUM.REMOVE_NODE:n=await Aae(r);break;case sc.OPERATIONS_ENUM.CLUSTER_STATUS:n=await Oae(r);break;case sc.OPERATIONS_ENUM.DESCRIBE_ALL:n=await Bae();break;default:let s=`node '${iO}' reply service received unrecognized request operation`;Kl.error(s),n=new bae(sO.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,s)}Kl.trace(n),t.respond(yae(n))}}a(vae,"handleRequest");async function Bae(){try{return{status:sO.UPDATE_REMOTE_RESPONSE_STATUSES.SUCCESS,message:await wae.describeAll()}}catch(e){return Kl.error(e),{status:sO.UPDATE_REMOTE_RESPONSE_STATUSES.ERROR,message:e.message}}}a(Bae,"getRemoteDescribeAll");Lae||Mae.on("message",async e=>{let{type:t}=e;t===Dae.ITC_EVENT_TYPES.SHUTDOWN&&uq.closeConnection()})});var Hae=_q();(async()=>{try{await Hae()}catch(e){console.error("Error launching Nats reply service."),console.error(e)}})();
|